Tue, 16 Nov 2010 14:07:33 -0800
6978187: G1: assert(ParallelGCThreads> 1 || n_yielded() == _hrrs->occupied()) strikes again
Summary: An evacuation failure while copying the roots caused an object, A, to be forwarded to itself. During the subsequent RSet updating a reference to A was processed causing the reference to be added to the RSet of A's heap region. As a result of adding to the remembered set we ran into the issue described in 6930581 - the sparse table expanded and the RSet scanning code walked the cards in one instance of RHashTable (_cur) while the occupied() counts the cards in the expanded table (_next).
Reviewed-by: tonyp, iveresov
1 /*
2 * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 *
23 */
25 #include "incls/_precompiled.incl"
26 #include "incls/_g1RemSet.cpp.incl"
28 #define CARD_REPEAT_HISTO 0
30 #if CARD_REPEAT_HISTO
31 static size_t ct_freq_sz;
32 static jbyte* ct_freq = NULL;
34 void init_ct_freq_table(size_t heap_sz_bytes) {
35 if (ct_freq == NULL) {
36 ct_freq_sz = heap_sz_bytes/CardTableModRefBS::card_size;
37 ct_freq = new jbyte[ct_freq_sz];
38 for (size_t j = 0; j < ct_freq_sz; j++) ct_freq[j] = 0;
39 }
40 }
42 void ct_freq_note_card(size_t index) {
43 assert(0 <= index && index < ct_freq_sz, "Bounds error.");
44 if (ct_freq[index] < 100) { ct_freq[index]++; }
45 }
47 static IntHistogram card_repeat_count(10, 10);
49 void ct_freq_update_histo_and_reset() {
50 for (size_t j = 0; j < ct_freq_sz; j++) {
51 card_repeat_count.add_entry(ct_freq[j]);
52 ct_freq[j] = 0;
53 }
55 }
56 #endif
59 class IntoCSOopClosure: public OopsInHeapRegionClosure {
60 OopsInHeapRegionClosure* _blk;
61 G1CollectedHeap* _g1;
62 public:
63 IntoCSOopClosure(G1CollectedHeap* g1, OopsInHeapRegionClosure* blk) :
64 _g1(g1), _blk(blk) {}
65 void set_region(HeapRegion* from) {
66 _blk->set_region(from);
67 }
68 virtual void do_oop(narrowOop* p) { do_oop_work(p); }
69 virtual void do_oop( oop* p) { do_oop_work(p); }
70 template <class T> void do_oop_work(T* p) {
71 oop obj = oopDesc::load_decode_heap_oop(p);
72 if (_g1->obj_in_cs(obj)) _blk->do_oop(p);
73 }
74 bool apply_to_weak_ref_discovered_field() { return true; }
75 bool idempotent() { return true; }
76 };
78 class IntoCSRegionClosure: public HeapRegionClosure {
79 IntoCSOopClosure _blk;
80 G1CollectedHeap* _g1;
81 public:
82 IntoCSRegionClosure(G1CollectedHeap* g1, OopsInHeapRegionClosure* blk) :
83 _g1(g1), _blk(g1, blk) {}
84 bool doHeapRegion(HeapRegion* r) {
85 if (!r->in_collection_set()) {
86 _blk.set_region(r);
87 if (r->isHumongous()) {
88 if (r->startsHumongous()) {
89 oop obj = oop(r->bottom());
90 obj->oop_iterate(&_blk);
91 }
92 } else {
93 r->oop_before_save_marks_iterate(&_blk);
94 }
95 }
96 return false;
97 }
98 };
100 class VerifyRSCleanCardOopClosure: public OopClosure {
101 G1CollectedHeap* _g1;
102 public:
103 VerifyRSCleanCardOopClosure(G1CollectedHeap* g1) : _g1(g1) {}
105 virtual void do_oop(narrowOop* p) { do_oop_work(p); }
106 virtual void do_oop( oop* p) { do_oop_work(p); }
107 template <class T> void do_oop_work(T* p) {
108 oop obj = oopDesc::load_decode_heap_oop(p);
109 HeapRegion* to = _g1->heap_region_containing(obj);
110 guarantee(to == NULL || !to->in_collection_set(),
111 "Missed a rem set member.");
112 }
113 };
115 G1RemSet::G1RemSet(G1CollectedHeap* g1, CardTableModRefBS* ct_bs)
116 : _g1(g1), _conc_refine_cards(0),
117 _ct_bs(ct_bs), _g1p(_g1->g1_policy()),
118 _cg1r(g1->concurrent_g1_refine()),
119 _cset_rs_update_cl(NULL),
120 _cards_scanned(NULL), _total_cards_scanned(0)
121 {
122 _seq_task = new SubTasksDone(NumSeqTasks);
123 guarantee(n_workers() > 0, "There should be some workers");
124 _cset_rs_update_cl = NEW_C_HEAP_ARRAY(OopsInHeapRegionClosure*, n_workers());
125 for (uint i = 0; i < n_workers(); i++) {
126 _cset_rs_update_cl[i] = NULL;
127 }
128 }
130 G1RemSet::~G1RemSet() {
131 delete _seq_task;
132 for (uint i = 0; i < n_workers(); i++) {
133 assert(_cset_rs_update_cl[i] == NULL, "it should be");
134 }
135 FREE_C_HEAP_ARRAY(OopsInHeapRegionClosure*, _cset_rs_update_cl);
136 }
138 void CountNonCleanMemRegionClosure::do_MemRegion(MemRegion mr) {
139 if (_g1->is_in_g1_reserved(mr.start())) {
140 _n += (int) ((mr.byte_size() / CardTableModRefBS::card_size));
141 if (_start_first == NULL) _start_first = mr.start();
142 }
143 }
145 class ScanRSClosure : public HeapRegionClosure {
146 size_t _cards_done, _cards;
147 G1CollectedHeap* _g1h;
148 OopsInHeapRegionClosure* _oc;
149 G1BlockOffsetSharedArray* _bot_shared;
150 CardTableModRefBS *_ct_bs;
151 int _worker_i;
152 int _block_size;
153 bool _try_claimed;
154 public:
155 ScanRSClosure(OopsInHeapRegionClosure* oc, int worker_i) :
156 _oc(oc),
157 _cards(0),
158 _cards_done(0),
159 _worker_i(worker_i),
160 _try_claimed(false)
161 {
162 _g1h = G1CollectedHeap::heap();
163 _bot_shared = _g1h->bot_shared();
164 _ct_bs = (CardTableModRefBS*) (_g1h->barrier_set());
165 _block_size = MAX2<int>(G1RSetScanBlockSize, 1);
166 }
168 void set_try_claimed() { _try_claimed = true; }
170 void scanCard(size_t index, HeapRegion *r) {
171 _cards_done++;
172 DirtyCardToOopClosure* cl =
173 r->new_dcto_closure(_oc,
174 CardTableModRefBS::Precise,
175 HeapRegionDCTOC::IntoCSFilterKind);
177 // Set the "from" region in the closure.
178 _oc->set_region(r);
179 HeapWord* card_start = _bot_shared->address_for_index(index);
180 HeapWord* card_end = card_start + G1BlockOffsetSharedArray::N_words;
181 Space *sp = SharedHeap::heap()->space_containing(card_start);
182 MemRegion sm_region;
183 if (ParallelGCThreads > 0) {
184 // first find the used area
185 sm_region = sp->used_region_at_save_marks();
186 } else {
187 // The closure is not idempotent. We shouldn't look at objects
188 // allocated during the GC.
189 sm_region = sp->used_region_at_save_marks();
190 }
191 MemRegion mr = sm_region.intersection(MemRegion(card_start,card_end));
192 if (!mr.is_empty()) {
193 cl->do_MemRegion(mr);
194 }
195 }
197 void printCard(HeapRegion* card_region, size_t card_index,
198 HeapWord* card_start) {
199 gclog_or_tty->print_cr("T %d Region [" PTR_FORMAT ", " PTR_FORMAT ") "
200 "RS names card %p: "
201 "[" PTR_FORMAT ", " PTR_FORMAT ")",
202 _worker_i,
203 card_region->bottom(), card_region->end(),
204 card_index,
205 card_start, card_start + G1BlockOffsetSharedArray::N_words);
206 }
208 bool doHeapRegion(HeapRegion* r) {
209 assert(r->in_collection_set(), "should only be called on elements of CS.");
210 HeapRegionRemSet* hrrs = r->rem_set();
211 if (hrrs->iter_is_complete()) return false; // All done.
212 if (!_try_claimed && !hrrs->claim_iter()) return false;
213 _g1h->push_dirty_cards_region(r);
214 // If we didn't return above, then
215 // _try_claimed || r->claim_iter()
216 // is true: either we're supposed to work on claimed-but-not-complete
217 // regions, or we successfully claimed the region.
218 HeapRegionRemSetIterator* iter = _g1h->rem_set_iterator(_worker_i);
219 hrrs->init_iterator(iter);
220 size_t card_index;
222 // We claim cards in block so as to recude the contention. The block size is determined by
223 // the G1RSetScanBlockSize parameter.
224 size_t jump_to_card = hrrs->iter_claimed_next(_block_size);
225 for (size_t current_card = 0; iter->has_next(card_index); current_card++) {
226 if (current_card >= jump_to_card + _block_size) {
227 jump_to_card = hrrs->iter_claimed_next(_block_size);
228 }
229 if (current_card < jump_to_card) continue;
230 HeapWord* card_start = _g1h->bot_shared()->address_for_index(card_index);
231 #if 0
232 gclog_or_tty->print("Rem set iteration yielded card [" PTR_FORMAT ", " PTR_FORMAT ").\n",
233 card_start, card_start + CardTableModRefBS::card_size_in_words);
234 #endif
236 HeapRegion* card_region = _g1h->heap_region_containing(card_start);
237 assert(card_region != NULL, "Yielding cards not in the heap?");
238 _cards++;
240 if (!card_region->is_on_dirty_cards_region_list()) {
241 _g1h->push_dirty_cards_region(card_region);
242 }
244 // If the card is dirty, then we will scan it during updateRS.
245 if (!card_region->in_collection_set() && !_ct_bs->is_card_dirty(card_index)) {
246 // We make the card as "claimed" lazily (so races are possible but they're benign),
247 // which reduces the number of duplicate scans (the rsets of the regions in the cset
248 // can intersect).
249 if (!_ct_bs->is_card_claimed(card_index)) {
250 _ct_bs->set_card_claimed(card_index);
251 scanCard(card_index, card_region);
252 }
253 }
254 }
255 if (!_try_claimed) {
256 hrrs->set_iter_complete();
257 }
258 return false;
259 }
260 // Set all cards back to clean.
261 void cleanup() {_g1h->cleanUpCardTable();}
262 size_t cards_done() { return _cards_done;}
263 size_t cards_looked_up() { return _cards;}
264 };
266 // We want the parallel threads to start their scanning at
267 // different collection set regions to avoid contention.
268 // If we have:
269 // n collection set regions
270 // p threads
271 // Then thread t will start at region t * floor (n/p)
273 HeapRegion* G1RemSet::calculateStartRegion(int worker_i) {
274 HeapRegion* result = _g1p->collection_set();
275 if (ParallelGCThreads > 0) {
276 size_t cs_size = _g1p->collection_set_size();
277 int n_workers = _g1->workers()->total_workers();
278 size_t cs_spans = cs_size / n_workers;
279 size_t ind = cs_spans * worker_i;
280 for (size_t i = 0; i < ind; i++)
281 result = result->next_in_collection_set();
282 }
283 return result;
284 }
286 void G1RemSet::scanRS(OopsInHeapRegionClosure* oc, int worker_i) {
287 double rs_time_start = os::elapsedTime();
288 HeapRegion *startRegion = calculateStartRegion(worker_i);
290 ScanRSClosure scanRScl(oc, worker_i);
291 _g1->collection_set_iterate_from(startRegion, &scanRScl);
292 scanRScl.set_try_claimed();
293 _g1->collection_set_iterate_from(startRegion, &scanRScl);
295 double scan_rs_time_sec = os::elapsedTime() - rs_time_start;
297 assert( _cards_scanned != NULL, "invariant" );
298 _cards_scanned[worker_i] = scanRScl.cards_done();
300 _g1p->record_scan_rs_time(worker_i, scan_rs_time_sec * 1000.0);
301 }
303 // Closure used for updating RSets and recording references that
304 // point into the collection set. Only called during an
305 // evacuation pause.
307 class RefineRecordRefsIntoCSCardTableEntryClosure: public CardTableEntryClosure {
308 G1RemSet* _g1rs;
309 DirtyCardQueue* _into_cset_dcq;
310 public:
311 RefineRecordRefsIntoCSCardTableEntryClosure(G1CollectedHeap* g1h,
312 DirtyCardQueue* into_cset_dcq) :
313 _g1rs(g1h->g1_rem_set()), _into_cset_dcq(into_cset_dcq)
314 {}
315 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
316 // The only time we care about recording cards that
317 // contain references that point into the collection set
318 // is during RSet updating within an evacuation pause.
319 // In this case worker_i should be the id of a GC worker thread.
320 assert(SafepointSynchronize::is_at_safepoint(), "not during an evacuation pause");
321 assert(worker_i < (int) DirtyCardQueueSet::num_par_ids(), "should be a GC worker");
323 if (_g1rs->concurrentRefineOneCard(card_ptr, worker_i, true)) {
324 // 'card_ptr' contains references that point into the collection
325 // set. We need to record the card in the DCQS
326 // (G1CollectedHeap::into_cset_dirty_card_queue_set())
327 // that's used for that purpose.
328 //
329 // Enqueue the card
330 _into_cset_dcq->enqueue(card_ptr);
331 }
332 return true;
333 }
334 };
336 void G1RemSet::updateRS(DirtyCardQueue* into_cset_dcq, int worker_i) {
337 double start = os::elapsedTime();
338 // Apply the given closure to all remaining log entries.
339 RefineRecordRefsIntoCSCardTableEntryClosure into_cset_update_rs_cl(_g1, into_cset_dcq);
340 _g1->iterate_dirty_card_closure(&into_cset_update_rs_cl, into_cset_dcq, false, worker_i);
342 // Now there should be no dirty cards.
343 if (G1RSLogCheckCardTable) {
344 CountNonCleanMemRegionClosure cl(_g1);
345 _ct_bs->mod_card_iterate(&cl);
346 // XXX This isn't true any more: keeping cards of young regions
347 // marked dirty broke it. Need some reasonable fix.
348 guarantee(cl.n() == 0, "Card table should be clean.");
349 }
351 _g1p->record_update_rs_time(worker_i, (os::elapsedTime() - start) * 1000.0);
352 }
354 #ifndef PRODUCT
355 class PrintRSClosure : public HeapRegionClosure {
356 int _count;
357 public:
358 PrintRSClosure() : _count(0) {}
359 bool doHeapRegion(HeapRegion* r) {
360 HeapRegionRemSet* hrrs = r->rem_set();
361 _count += (int) hrrs->occupied();
362 if (hrrs->occupied() == 0) {
363 gclog_or_tty->print("Heap Region [" PTR_FORMAT ", " PTR_FORMAT ") "
364 "has no remset entries\n",
365 r->bottom(), r->end());
366 } else {
367 gclog_or_tty->print("Printing rem set for heap region [" PTR_FORMAT ", " PTR_FORMAT ")\n",
368 r->bottom(), r->end());
369 r->print();
370 hrrs->print();
371 gclog_or_tty->print("\nDone printing rem set\n");
372 }
373 return false;
374 }
375 int occupied() {return _count;}
376 };
377 #endif
379 class CountRSSizeClosure: public HeapRegionClosure {
380 size_t _n;
381 size_t _tot;
382 size_t _max;
383 HeapRegion* _max_r;
384 enum {
385 N = 20,
386 MIN = 6
387 };
388 int _histo[N];
389 public:
390 CountRSSizeClosure() : _n(0), _tot(0), _max(0), _max_r(NULL) {
391 for (int i = 0; i < N; i++) _histo[i] = 0;
392 }
393 bool doHeapRegion(HeapRegion* r) {
394 if (!r->continuesHumongous()) {
395 size_t occ = r->rem_set()->occupied();
396 _n++;
397 _tot += occ;
398 if (occ > _max) {
399 _max = occ;
400 _max_r = r;
401 }
402 // Fit it into a histo bin.
403 int s = 1 << MIN;
404 int i = 0;
405 while (occ > (size_t) s && i < (N-1)) {
406 s = s << 1;
407 i++;
408 }
409 _histo[i]++;
410 }
411 return false;
412 }
413 size_t n() { return _n; }
414 size_t tot() { return _tot; }
415 size_t mx() { return _max; }
416 HeapRegion* mxr() { return _max_r; }
417 void print_histo() {
418 int mx = N;
419 while (mx >= 0) {
420 if (_histo[mx-1] > 0) break;
421 mx--;
422 }
423 gclog_or_tty->print_cr("Number of regions with given RS sizes:");
424 gclog_or_tty->print_cr(" <= %8d %8d", 1 << MIN, _histo[0]);
425 for (int i = 1; i < mx-1; i++) {
426 gclog_or_tty->print_cr(" %8d - %8d %8d",
427 (1 << (MIN + i - 1)) + 1,
428 1 << (MIN + i),
429 _histo[i]);
430 }
431 gclog_or_tty->print_cr(" > %8d %8d", (1 << (MIN+mx-2))+1, _histo[mx-1]);
432 }
433 };
435 void G1RemSet::cleanupHRRS() {
436 HeapRegionRemSet::cleanup();
437 }
439 void G1RemSet::oops_into_collection_set_do(OopsInHeapRegionClosure* oc,
440 int worker_i) {
441 #if CARD_REPEAT_HISTO
442 ct_freq_update_histo_and_reset();
443 #endif
444 if (worker_i == 0) {
445 _cg1r->clear_and_record_card_counts();
446 }
448 // Make this into a command-line flag...
449 if (G1RSCountHisto && (ParallelGCThreads == 0 || worker_i == 0)) {
450 CountRSSizeClosure count_cl;
451 _g1->heap_region_iterate(&count_cl);
452 gclog_or_tty->print_cr("Avg of %d RS counts is %f, max is %d, "
453 "max region is " PTR_FORMAT,
454 count_cl.n(), (float)count_cl.tot()/(float)count_cl.n(),
455 count_cl.mx(), count_cl.mxr());
456 count_cl.print_histo();
457 }
459 // We cache the value of 'oc' closure into the appropriate slot in the
460 // _cset_rs_update_cl for this worker
461 assert(worker_i < (int)n_workers(), "sanity");
462 _cset_rs_update_cl[worker_i] = oc;
464 // A DirtyCardQueue that is used to hold cards containing references
465 // that point into the collection set. This DCQ is associated with a
466 // special DirtyCardQueueSet (see g1CollectedHeap.hpp). Under normal
467 // circumstances (i.e. the pause successfully completes), these cards
468 // are just discarded (there's no need to update the RSets of regions
469 // that were in the collection set - after the pause these regions
470 // are wholly 'free' of live objects. In the event of an evacuation
471 // failure the cards/buffers in this queue set are:
472 // * passed to the DirtyCardQueueSet that is used to manage deferred
473 // RSet updates, or
474 // * scanned for references that point into the collection set
475 // and the RSet of the corresponding region in the collection set
476 // is updated immediately.
477 DirtyCardQueue into_cset_dcq(&_g1->into_cset_dirty_card_queue_set());
479 assert((ParallelGCThreads > 0) || worker_i == 0, "invariant");
481 // The two flags below were introduced temporarily to serialize
482 // the updating and scanning of remembered sets. There are some
483 // race conditions when these two operations are done in parallel
484 // and they are causing failures. When we resolve said race
485 // conditions, we'll revert back to parallel remembered set
486 // updating and scanning. See CRs 6677707 and 6677708.
487 if (G1UseParallelRSetUpdating || (worker_i == 0)) {
488 updateRS(&into_cset_dcq, worker_i);
489 } else {
490 _g1p->record_update_rs_processed_buffers(worker_i, 0.0);
491 _g1p->record_update_rs_time(worker_i, 0.0);
492 }
493 if (G1UseParallelRSetScanning || (worker_i == 0)) {
494 scanRS(oc, worker_i);
495 } else {
496 _g1p->record_scan_rs_time(worker_i, 0.0);
497 }
499 // We now clear the cached values of _cset_rs_update_cl for this worker
500 _cset_rs_update_cl[worker_i] = NULL;
501 }
503 void G1RemSet::prepare_for_oops_into_collection_set_do() {
504 #if G1_REM_SET_LOGGING
505 PrintRSClosure cl;
506 _g1->collection_set_iterate(&cl);
507 #endif
508 cleanupHRRS();
509 ConcurrentG1Refine* cg1r = _g1->concurrent_g1_refine();
510 _g1->set_refine_cte_cl_concurrency(false);
511 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
512 dcqs.concatenate_logs();
514 if (ParallelGCThreads > 0) {
515 _seq_task->set_n_threads((int)n_workers());
516 }
517 guarantee( _cards_scanned == NULL, "invariant" );
518 _cards_scanned = NEW_C_HEAP_ARRAY(size_t, n_workers());
519 for (uint i = 0; i < n_workers(); ++i) {
520 _cards_scanned[i] = 0;
521 }
522 _total_cards_scanned = 0;
523 }
526 class cleanUpIteratorsClosure : public HeapRegionClosure {
527 bool doHeapRegion(HeapRegion *r) {
528 HeapRegionRemSet* hrrs = r->rem_set();
529 hrrs->init_for_par_iteration();
530 return false;
531 }
532 };
534 // This closure, applied to a DirtyCardQueueSet, is used to immediately
535 // update the RSets for the regions in the CSet. For each card it iterates
536 // through the oops which coincide with that card. It scans the reference
537 // fields in each oop; when it finds an oop that points into the collection
538 // set, the RSet for the region containing the referenced object is updated.
539 class UpdateRSetCardTableEntryIntoCSetClosure: public CardTableEntryClosure {
540 G1CollectedHeap* _g1;
541 CardTableModRefBS* _ct_bs;
542 public:
543 UpdateRSetCardTableEntryIntoCSetClosure(G1CollectedHeap* g1,
544 CardTableModRefBS* bs):
545 _g1(g1), _ct_bs(bs)
546 { }
548 bool do_card_ptr(jbyte* card_ptr, int worker_i) {
549 // Construct the region representing the card.
550 HeapWord* start = _ct_bs->addr_for(card_ptr);
551 // And find the region containing it.
552 HeapRegion* r = _g1->heap_region_containing(start);
553 assert(r != NULL, "unexpected null");
555 // Scan oops in the card looking for references into the collection set
556 HeapWord* end = _ct_bs->addr_for(card_ptr + 1);
557 MemRegion scanRegion(start, end);
559 UpdateRSetImmediate update_rs_cl(_g1->g1_rem_set());
560 FilterIntoCSClosure update_rs_cset_oop_cl(NULL, _g1, &update_rs_cl);
561 FilterOutOfRegionClosure filter_then_update_rs_cset_oop_cl(r, &update_rs_cset_oop_cl);
563 // We can pass false as the "filter_young" parameter here as:
564 // * we should be in a STW pause,
565 // * the DCQS to which this closure is applied is used to hold
566 // references that point into the collection set from the prior
567 // RSet updating,
568 // * the post-write barrier shouldn't be logging updates to young
569 // regions (but there is a situation where this can happen - see
570 // the comment in G1RemSet::concurrentRefineOneCard below -
571 // that should not be applicable here), and
572 // * during actual RSet updating, the filtering of cards in young
573 // regions in HeapRegion::oops_on_card_seq_iterate_careful is
574 // employed.
575 // As a result, when this closure is applied to "refs into cset"
576 // DCQS, we shouldn't see any cards in young regions.
577 update_rs_cl.set_region(r);
578 HeapWord* stop_point =
579 r->oops_on_card_seq_iterate_careful(scanRegion,
580 &filter_then_update_rs_cset_oop_cl,
581 false /* filter_young */);
583 // Since this is performed in the event of an evacuation failure, we
584 // we shouldn't see a non-null stop point
585 assert(stop_point == NULL, "saw an unallocated region");
586 return true;
587 }
588 };
590 void G1RemSet::cleanup_after_oops_into_collection_set_do() {
591 guarantee( _cards_scanned != NULL, "invariant" );
592 _total_cards_scanned = 0;
593 for (uint i = 0; i < n_workers(); ++i)
594 _total_cards_scanned += _cards_scanned[i];
595 FREE_C_HEAP_ARRAY(size_t, _cards_scanned);
596 _cards_scanned = NULL;
597 // Cleanup after copy
598 #if G1_REM_SET_LOGGING
599 PrintRSClosure cl;
600 _g1->heap_region_iterate(&cl);
601 #endif
602 _g1->set_refine_cte_cl_concurrency(true);
603 cleanUpIteratorsClosure iterClosure;
604 _g1->collection_set_iterate(&iterClosure);
605 // Set all cards back to clean.
606 _g1->cleanUpCardTable();
608 DirtyCardQueueSet& into_cset_dcqs = _g1->into_cset_dirty_card_queue_set();
609 int into_cset_n_buffers = into_cset_dcqs.completed_buffers_num();
611 if (_g1->evacuation_failed()) {
612 // Restore remembered sets for the regions pointing into the collection set.
614 if (G1DeferredRSUpdate) {
615 // If deferred RS updates are enabled then we just need to transfer
616 // the completed buffers from (a) the DirtyCardQueueSet used to hold
617 // cards that contain references that point into the collection set
618 // to (b) the DCQS used to hold the deferred RS updates
619 _g1->dirty_card_queue_set().merge_bufferlists(&into_cset_dcqs);
620 } else {
622 CardTableModRefBS* bs = (CardTableModRefBS*)_g1->barrier_set();
623 UpdateRSetCardTableEntryIntoCSetClosure update_rs_cset_immediate(_g1, bs);
625 int n_completed_buffers = 0;
626 while (into_cset_dcqs.apply_closure_to_completed_buffer(&update_rs_cset_immediate,
627 0, 0, true)) {
628 n_completed_buffers++;
629 }
630 assert(n_completed_buffers == into_cset_n_buffers, "missed some buffers");
631 }
632 }
634 // Free any completed buffers in the DirtyCardQueueSet used to hold cards
635 // which contain references that point into the collection.
636 _g1->into_cset_dirty_card_queue_set().clear();
637 assert(_g1->into_cset_dirty_card_queue_set().completed_buffers_num() == 0,
638 "all buffers should be freed");
639 _g1->into_cset_dirty_card_queue_set().clear_n_completed_buffers();
640 }
642 class ScrubRSClosure: public HeapRegionClosure {
643 G1CollectedHeap* _g1h;
644 BitMap* _region_bm;
645 BitMap* _card_bm;
646 CardTableModRefBS* _ctbs;
647 public:
648 ScrubRSClosure(BitMap* region_bm, BitMap* card_bm) :
649 _g1h(G1CollectedHeap::heap()),
650 _region_bm(region_bm), _card_bm(card_bm),
651 _ctbs(NULL)
652 {
653 ModRefBarrierSet* bs = _g1h->mr_bs();
654 guarantee(bs->is_a(BarrierSet::CardTableModRef), "Precondition");
655 _ctbs = (CardTableModRefBS*)bs;
656 }
658 bool doHeapRegion(HeapRegion* r) {
659 if (!r->continuesHumongous()) {
660 r->rem_set()->scrub(_ctbs, _region_bm, _card_bm);
661 }
662 return false;
663 }
664 };
666 void G1RemSet::scrub(BitMap* region_bm, BitMap* card_bm) {
667 ScrubRSClosure scrub_cl(region_bm, card_bm);
668 _g1->heap_region_iterate(&scrub_cl);
669 }
671 void G1RemSet::scrub_par(BitMap* region_bm, BitMap* card_bm,
672 int worker_num, int claim_val) {
673 ScrubRSClosure scrub_cl(region_bm, card_bm);
674 _g1->heap_region_par_iterate_chunked(&scrub_cl, worker_num, claim_val);
675 }
678 static IntHistogram out_of_histo(50, 50);
680 class TriggerClosure : public OopClosure {
681 bool _trigger;
682 public:
683 TriggerClosure() : _trigger(false) { }
684 bool value() const { return _trigger; }
685 template <class T> void do_oop_nv(T* p) { _trigger = true; }
686 virtual void do_oop(oop* p) { do_oop_nv(p); }
687 virtual void do_oop(narrowOop* p) { do_oop_nv(p); }
688 };
690 class InvokeIfNotTriggeredClosure: public OopClosure {
691 TriggerClosure* _t;
692 OopClosure* _oc;
693 public:
694 InvokeIfNotTriggeredClosure(TriggerClosure* t, OopClosure* oc):
695 _t(t), _oc(oc) { }
696 template <class T> void do_oop_nv(T* p) {
697 if (!_t->value()) _oc->do_oop(p);
698 }
699 virtual void do_oop(oop* p) { do_oop_nv(p); }
700 virtual void do_oop(narrowOop* p) { do_oop_nv(p); }
701 };
703 class Mux2Closure : public OopClosure {
704 OopClosure* _c1;
705 OopClosure* _c2;
706 public:
707 Mux2Closure(OopClosure *c1, OopClosure *c2) : _c1(c1), _c2(c2) { }
708 template <class T> void do_oop_nv(T* p) {
709 _c1->do_oop(p); _c2->do_oop(p);
710 }
711 virtual void do_oop(oop* p) { do_oop_nv(p); }
712 virtual void do_oop(narrowOop* p) { do_oop_nv(p); }
713 };
715 bool G1RemSet::concurrentRefineOneCard_impl(jbyte* card_ptr, int worker_i,
716 bool check_for_refs_into_cset) {
717 // Construct the region representing the card.
718 HeapWord* start = _ct_bs->addr_for(card_ptr);
719 // And find the region containing it.
720 HeapRegion* r = _g1->heap_region_containing(start);
721 assert(r != NULL, "unexpected null");
723 HeapWord* end = _ct_bs->addr_for(card_ptr + 1);
724 MemRegion dirtyRegion(start, end);
726 #if CARD_REPEAT_HISTO
727 init_ct_freq_table(_g1->g1_reserved_obj_bytes());
728 ct_freq_note_card(_ct_bs->index_for(start));
729 #endif
731 assert(!check_for_refs_into_cset || _cset_rs_update_cl[worker_i] != NULL, "sanity");
732 UpdateRSOrPushRefOopClosure update_rs_oop_cl(_g1,
733 _g1->g1_rem_set(),
734 _cset_rs_update_cl[worker_i],
735 check_for_refs_into_cset,
736 worker_i);
737 update_rs_oop_cl.set_from(r);
739 TriggerClosure trigger_cl;
740 FilterIntoCSClosure into_cs_cl(NULL, _g1, &trigger_cl);
741 InvokeIfNotTriggeredClosure invoke_cl(&trigger_cl, &into_cs_cl);
742 Mux2Closure mux(&invoke_cl, &update_rs_oop_cl);
744 FilterOutOfRegionClosure filter_then_update_rs_oop_cl(r,
745 (check_for_refs_into_cset ?
746 (OopClosure*)&mux :
747 (OopClosure*)&update_rs_oop_cl));
749 // Undirty the card.
750 *card_ptr = CardTableModRefBS::clean_card_val();
751 // We must complete this write before we do any of the reads below.
752 OrderAccess::storeload();
753 // And process it, being careful of unallocated portions of TLAB's.
755 // The region for the current card may be a young region. The
756 // current card may have been a card that was evicted from the
757 // card cache. When the card was inserted into the cache, we had
758 // determined that its region was non-young. While in the cache,
759 // the region may have been freed during a cleanup pause, reallocated
760 // and tagged as young.
761 //
762 // We wish to filter out cards for such a region but the current
763 // thread, if we're running conucrrently, may "see" the young type
764 // change at any time (so an earlier "is_young" check may pass or
765 // fail arbitrarily). We tell the iteration code to perform this
766 // filtering when it has been determined that there has been an actual
767 // allocation in this region and making it safe to check the young type.
768 bool filter_young = true;
770 HeapWord* stop_point =
771 r->oops_on_card_seq_iterate_careful(dirtyRegion,
772 &filter_then_update_rs_oop_cl,
773 filter_young);
775 // If stop_point is non-null, then we encountered an unallocated region
776 // (perhaps the unfilled portion of a TLAB.) For now, we'll dirty the
777 // card and re-enqueue: if we put off the card until a GC pause, then the
778 // unallocated portion will be filled in. Alternatively, we might try
779 // the full complexity of the technique used in "regular" precleaning.
780 if (stop_point != NULL) {
781 // The card might have gotten re-dirtied and re-enqueued while we
782 // worked. (In fact, it's pretty likely.)
783 if (*card_ptr != CardTableModRefBS::dirty_card_val()) {
784 *card_ptr = CardTableModRefBS::dirty_card_val();
785 MutexLockerEx x(Shared_DirtyCardQ_lock,
786 Mutex::_no_safepoint_check_flag);
787 DirtyCardQueue* sdcq =
788 JavaThread::dirty_card_queue_set().shared_dirty_card_queue();
789 sdcq->enqueue(card_ptr);
790 }
791 } else {
792 out_of_histo.add_entry(filter_then_update_rs_oop_cl.out_of_region());
793 _conc_refine_cards++;
794 }
796 return trigger_cl.value();
797 }
799 bool G1RemSet::concurrentRefineOneCard(jbyte* card_ptr, int worker_i,
800 bool check_for_refs_into_cset) {
801 // If the card is no longer dirty, nothing to do.
802 if (*card_ptr != CardTableModRefBS::dirty_card_val()) {
803 // No need to return that this card contains refs that point
804 // into the collection set.
805 return false;
806 }
808 // Construct the region representing the card.
809 HeapWord* start = _ct_bs->addr_for(card_ptr);
810 // And find the region containing it.
811 HeapRegion* r = _g1->heap_region_containing(start);
812 if (r == NULL) {
813 guarantee(_g1->is_in_permanent(start), "Or else where?");
814 // Again no need to return that this card contains refs that
815 // point into the collection set.
816 return false; // Not in the G1 heap (might be in perm, for example.)
817 }
818 // Why do we have to check here whether a card is on a young region,
819 // given that we dirty young regions and, as a result, the
820 // post-barrier is supposed to filter them out and never to enqueue
821 // them? When we allocate a new region as the "allocation region" we
822 // actually dirty its cards after we release the lock, since card
823 // dirtying while holding the lock was a performance bottleneck. So,
824 // as a result, it is possible for other threads to actually
825 // allocate objects in the region (after the acquire the lock)
826 // before all the cards on the region are dirtied. This is unlikely,
827 // and it doesn't happen often, but it can happen. So, the extra
828 // check below filters out those cards.
829 if (r->is_young()) {
830 return false;
831 }
832 // While we are processing RSet buffers during the collection, we
833 // actually don't want to scan any cards on the collection set,
834 // since we don't want to update remebered sets with entries that
835 // point into the collection set, given that live objects from the
836 // collection set are about to move and such entries will be stale
837 // very soon. This change also deals with a reliability issue which
838 // involves scanning a card in the collection set and coming across
839 // an array that was being chunked and looking malformed. Note,
840 // however, that if evacuation fails, we have to scan any objects
841 // that were not moved and create any missing entries.
842 if (r->in_collection_set()) {
843 return false;
844 }
846 // Should we defer processing the card?
847 //
848 // Previously the result from the insert_cache call would be
849 // either card_ptr (implying that card_ptr was currently "cold"),
850 // null (meaning we had inserted the card ptr into the "hot"
851 // cache, which had some headroom), or a "hot" card ptr
852 // extracted from the "hot" cache.
853 //
854 // Now that the _card_counts cache in the ConcurrentG1Refine
855 // instance is an evicting hash table, the result we get back
856 // could be from evicting the card ptr in an already occupied
857 // bucket (in which case we have replaced the card ptr in the
858 // bucket with card_ptr and "defer" is set to false). To avoid
859 // having a data structure (updates to which would need a lock)
860 // to hold these unprocessed dirty cards, we need to immediately
861 // process card_ptr. The actions needed to be taken on return
862 // from cache_insert are summarized in the following table:
863 //
864 // res defer action
865 // --------------------------------------------------------------
866 // null false card evicted from _card_counts & replaced with
867 // card_ptr; evicted ptr added to hot cache.
868 // No need to process res; immediately process card_ptr
869 //
870 // null true card not evicted from _card_counts; card_ptr added
871 // to hot cache.
872 // Nothing to do.
873 //
874 // non-null false card evicted from _card_counts & replaced with
875 // card_ptr; evicted ptr is currently "cold" or
876 // caused an eviction from the hot cache.
877 // Immediately process res; process card_ptr.
878 //
879 // non-null true card not evicted from _card_counts; card_ptr is
880 // currently cold, or caused an eviction from hot
881 // cache.
882 // Immediately process res; no need to process card_ptr.
885 jbyte* res = card_ptr;
886 bool defer = false;
888 // This gets set to true if the card being refined has references
889 // that point into the collection set.
890 bool oops_into_cset = false;
892 if (_cg1r->use_cache()) {
893 jbyte* res = _cg1r->cache_insert(card_ptr, &defer);
894 if (res != NULL && (res != card_ptr || defer)) {
895 start = _ct_bs->addr_for(res);
896 r = _g1->heap_region_containing(start);
897 if (r == NULL) {
898 assert(_g1->is_in_permanent(start), "Or else where?");
899 } else {
900 // Checking whether the region we got back from the cache
901 // is young here is inappropriate. The region could have been
902 // freed, reallocated and tagged as young while in the cache.
903 // Hence we could see its young type change at any time.
904 //
905 // Process card pointer we get back from the hot card cache. This
906 // will check whether the region containing the card is young
907 // _after_ checking that the region has been allocated from.
908 oops_into_cset = concurrentRefineOneCard_impl(res, worker_i,
909 false /* check_for_refs_into_cset */);
910 // The above call to concurrentRefineOneCard_impl is only
911 // performed if the hot card cache is enabled. This cache is
912 // disabled during an evacuation pause - which is the only
913 // time when we need know if the card contains references
914 // that point into the collection set. Also when the hot card
915 // cache is enabled, this code is executed by the concurrent
916 // refine threads - rather than the GC worker threads - and
917 // concurrentRefineOneCard_impl will return false.
918 assert(!oops_into_cset, "should not see true here");
919 }
920 }
921 }
923 if (!defer) {
924 oops_into_cset =
925 concurrentRefineOneCard_impl(card_ptr, worker_i, check_for_refs_into_cset);
926 // We should only be detecting that the card contains references
927 // that point into the collection set if the current thread is
928 // a GC worker thread.
929 assert(!oops_into_cset || SafepointSynchronize::is_at_safepoint(),
930 "invalid result at non safepoint");
931 }
932 return oops_into_cset;
933 }
935 class HRRSStatsIter: public HeapRegionClosure {
936 size_t _occupied;
937 size_t _total_mem_sz;
938 size_t _max_mem_sz;
939 HeapRegion* _max_mem_sz_region;
940 public:
941 HRRSStatsIter() :
942 _occupied(0),
943 _total_mem_sz(0),
944 _max_mem_sz(0),
945 _max_mem_sz_region(NULL)
946 {}
948 bool doHeapRegion(HeapRegion* r) {
949 if (r->continuesHumongous()) return false;
950 size_t mem_sz = r->rem_set()->mem_size();
951 if (mem_sz > _max_mem_sz) {
952 _max_mem_sz = mem_sz;
953 _max_mem_sz_region = r;
954 }
955 _total_mem_sz += mem_sz;
956 size_t occ = r->rem_set()->occupied();
957 _occupied += occ;
958 return false;
959 }
960 size_t total_mem_sz() { return _total_mem_sz; }
961 size_t max_mem_sz() { return _max_mem_sz; }
962 size_t occupied() { return _occupied; }
963 HeapRegion* max_mem_sz_region() { return _max_mem_sz_region; }
964 };
966 class PrintRSThreadVTimeClosure : public ThreadClosure {
967 public:
968 virtual void do_thread(Thread *t) {
969 ConcurrentG1RefineThread* crt = (ConcurrentG1RefineThread*) t;
970 gclog_or_tty->print(" %5.2f", crt->vtime_accum());
971 }
972 };
974 void G1RemSet::print_summary_info() {
975 G1CollectedHeap* g1 = G1CollectedHeap::heap();
977 #if CARD_REPEAT_HISTO
978 gclog_or_tty->print_cr("\nG1 card_repeat count histogram: ");
979 gclog_or_tty->print_cr(" # of repeats --> # of cards with that number.");
980 card_repeat_count.print_on(gclog_or_tty);
981 #endif
983 if (FILTEROUTOFREGIONCLOSURE_DOHISTOGRAMCOUNT) {
984 gclog_or_tty->print_cr("\nG1 rem-set out-of-region histogram: ");
985 gclog_or_tty->print_cr(" # of CS ptrs --> # of cards with that number.");
986 out_of_histo.print_on(gclog_or_tty);
987 }
988 gclog_or_tty->print_cr("\n Concurrent RS processed %d cards",
989 _conc_refine_cards);
990 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
991 jint tot_processed_buffers =
992 dcqs.processed_buffers_mut() + dcqs.processed_buffers_rs_thread();
993 gclog_or_tty->print_cr(" Of %d completed buffers:", tot_processed_buffers);
994 gclog_or_tty->print_cr(" %8d (%5.1f%%) by conc RS threads.",
995 dcqs.processed_buffers_rs_thread(),
996 100.0*(float)dcqs.processed_buffers_rs_thread()/
997 (float)tot_processed_buffers);
998 gclog_or_tty->print_cr(" %8d (%5.1f%%) by mutator threads.",
999 dcqs.processed_buffers_mut(),
1000 100.0*(float)dcqs.processed_buffers_mut()/
1001 (float)tot_processed_buffers);
1002 gclog_or_tty->print_cr(" Conc RS threads times(s)");
1003 PrintRSThreadVTimeClosure p;
1004 gclog_or_tty->print(" ");
1005 g1->concurrent_g1_refine()->threads_do(&p);
1006 gclog_or_tty->print_cr("");
1008 HRRSStatsIter blk;
1009 g1->heap_region_iterate(&blk);
1010 gclog_or_tty->print_cr(" Total heap region rem set sizes = " SIZE_FORMAT "K."
1011 " Max = " SIZE_FORMAT "K.",
1012 blk.total_mem_sz()/K, blk.max_mem_sz()/K);
1013 gclog_or_tty->print_cr(" Static structures = " SIZE_FORMAT "K,"
1014 " free_lists = " SIZE_FORMAT "K.",
1015 HeapRegionRemSet::static_mem_size()/K,
1016 HeapRegionRemSet::fl_mem_size()/K);
1017 gclog_or_tty->print_cr(" %d occupied cards represented.",
1018 blk.occupied());
1019 gclog_or_tty->print_cr(" Max sz region = [" PTR_FORMAT ", " PTR_FORMAT " )"
1020 ", cap = " SIZE_FORMAT "K, occ = " SIZE_FORMAT "K.",
1021 blk.max_mem_sz_region()->bottom(), blk.max_mem_sz_region()->end(),
1022 (blk.max_mem_sz_region()->rem_set()->mem_size() + K - 1)/K,
1023 (blk.max_mem_sz_region()->rem_set()->occupied() + K - 1)/K);
1024 gclog_or_tty->print_cr(" Did %d coarsenings.", HeapRegionRemSet::n_coarsenings());
1025 }
1027 void G1RemSet::prepare_for_verify() {
1028 if (G1HRRSFlushLogBuffersOnVerify &&
1029 (VerifyBeforeGC || VerifyAfterGC)
1030 && !_g1->full_collection()) {
1031 cleanupHRRS();
1032 _g1->set_refine_cte_cl_concurrency(false);
1033 if (SafepointSynchronize::is_at_safepoint()) {
1034 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
1035 dcqs.concatenate_logs();
1036 }
1037 bool cg1r_use_cache = _cg1r->use_cache();
1038 _cg1r->set_use_cache(false);
1039 DirtyCardQueue into_cset_dcq(&_g1->into_cset_dirty_card_queue_set());
1040 updateRS(&into_cset_dcq, 0);
1041 _g1->into_cset_dirty_card_queue_set().clear();
1042 _cg1r->set_use_cache(cg1r_use_cache);
1044 assert(JavaThread::dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed");
1045 }
1046 }