1 /* 2 * Copyright (c) 2001, 2018, 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 */ 24 25 #include "precompiled.hpp" 26 #include "gc/g1/dirtyCardQueue.hpp" 27 #include "gc/g1/g1BarrierSet.hpp" 28 #include "gc/g1/g1BlockOffsetTable.inline.hpp" 29 #include "gc/g1/g1CardTable.inline.hpp" 30 #include "gc/g1/g1CollectedHeap.inline.hpp" 31 #include "gc/g1/g1ConcurrentRefine.hpp" 32 #include "gc/g1/g1FromCardCache.hpp" 33 #include "gc/g1/g1GCPhaseTimes.hpp" 34 #include "gc/g1/g1HotCardCache.hpp" 35 #include "gc/g1/g1OopClosures.inline.hpp" 36 #include "gc/g1/g1RootClosures.hpp" 37 #include "gc/g1/g1RemSet.hpp" 38 #include "gc/g1/heapRegion.inline.hpp" 39 #include "gc/g1/heapRegionManager.inline.hpp" 40 #include "gc/g1/heapRegionRemSet.hpp" 41 #include "gc/shared/gcTraceTime.inline.hpp" 42 #include "gc/shared/suspendibleThreadSet.hpp" 43 #include "memory/iterator.hpp" 44 #include "memory/resourceArea.hpp" 45 #include "oops/access.inline.hpp" 46 #include "oops/oop.inline.hpp" 47 #include "runtime/os.hpp" 48 #include "utilities/align.hpp" 49 #include "utilities/globalDefinitions.hpp" 50 #include "utilities/intHisto.hpp" 51 #include "utilities/stack.inline.hpp" 52 #include "utilities/ticks.hpp" 53 54 // Collects information about the overall remembered set scan progress during an evacuation. 55 class G1RemSetScanState : public CHeapObj<mtGC> { 56 private: 57 class G1ClearCardTableTask : public AbstractGangTask { 58 G1CollectedHeap* _g1h; 59 uint* _dirty_region_list; 60 size_t _num_dirty_regions; 61 size_t _chunk_length; 62 63 size_t volatile _cur_dirty_regions; 64 public: 65 G1ClearCardTableTask(G1CollectedHeap* g1h, 66 uint* dirty_region_list, 67 size_t num_dirty_regions, 68 size_t chunk_length) : 69 AbstractGangTask("G1 Clear Card Table Task"), 70 _g1h(g1h), 71 _dirty_region_list(dirty_region_list), 72 _num_dirty_regions(num_dirty_regions), 73 _chunk_length(chunk_length), 74 _cur_dirty_regions(0) { 75 76 assert(chunk_length > 0, "must be"); 77 } 78 79 static size_t chunk_size() { return M; } 80 81 void work(uint worker_id) { 82 while (_cur_dirty_regions < _num_dirty_regions) { 83 size_t next = Atomic::add(_chunk_length, &_cur_dirty_regions) - _chunk_length; 84 size_t max = MIN2(next + _chunk_length, _num_dirty_regions); 85 86 for (size_t i = next; i < max; i++) { 87 HeapRegion* r = _g1h->region_at(_dirty_region_list[i]); 88 if (!r->is_survivor()) { 89 r->clear_cardtable(); 90 } 91 } 92 } 93 } 94 }; 95 96 size_t _max_regions; 97 98 // Scan progress for the remembered set of a single region. Transitions from 99 // Unclaimed -> Claimed -> Complete. 100 // At each of the transitions the thread that does the transition needs to perform 101 // some special action once. This is the reason for the extra "Claimed" state. 102 typedef jint G1RemsetIterState; 103 104 static const G1RemsetIterState Unclaimed = 0; // The remembered set has not been scanned yet. 105 static const G1RemsetIterState Claimed = 1; // The remembered set is currently being scanned. 106 static const G1RemsetIterState Complete = 2; // The remembered set has been completely scanned. 107 108 G1RemsetIterState volatile* _iter_states; 109 // The current location where the next thread should continue scanning in a region's 110 // remembered set. 111 size_t volatile* _iter_claims; 112 113 // Temporary buffer holding the regions we used to store remembered set scan duplicate 114 // information. These are also called "dirty". Valid entries are from [0.._cur_dirty_region) 115 uint* _dirty_region_buffer; 116 117 typedef jbyte IsDirtyRegionState; 118 static const IsDirtyRegionState Clean = 0; 119 static const IsDirtyRegionState Dirty = 1; 120 // Holds a flag for every region whether it is in the _dirty_region_buffer already 121 // to avoid duplicates. Uses jbyte since there are no atomic instructions for bools. 122 IsDirtyRegionState* _in_dirty_region_buffer; 123 size_t _cur_dirty_region; 124 125 // Creates a snapshot of the current _top values at the start of collection to 126 // filter out card marks that we do not want to scan. 127 class G1ResetScanTopClosure : public HeapRegionClosure { 128 private: 129 HeapWord** _scan_top; 130 public: 131 G1ResetScanTopClosure(HeapWord** scan_top) : _scan_top(scan_top) { } 132 133 virtual bool do_heap_region(HeapRegion* r) { 134 uint hrm_index = r->hrm_index(); 135 if (!r->in_collection_set() && r->is_old_or_humongous_or_archive()) { 136 _scan_top[hrm_index] = r->top(); 137 } else { 138 _scan_top[hrm_index] = r->bottom(); 139 } 140 return false; 141 } 142 }; 143 144 // For each region, contains the maximum top() value to be used during this garbage 145 // collection. Subsumes common checks like filtering out everything but old and 146 // humongous regions outside the collection set. 147 // This is valid because we are not interested in scanning stray remembered set 148 // entries from free or archive regions. 149 HeapWord** _scan_top; 150 public: 151 G1RemSetScanState() : 152 _max_regions(0), 153 _iter_states(NULL), 154 _iter_claims(NULL), 155 _dirty_region_buffer(NULL), 156 _in_dirty_region_buffer(NULL), 157 _cur_dirty_region(0), 158 _scan_top(NULL) { 159 } 160 161 ~G1RemSetScanState() { 162 if (_iter_states != NULL) { 163 FREE_C_HEAP_ARRAY(G1RemsetIterState, _iter_states); 164 } 165 if (_iter_claims != NULL) { 166 FREE_C_HEAP_ARRAY(size_t, _iter_claims); 167 } 168 if (_dirty_region_buffer != NULL) { 169 FREE_C_HEAP_ARRAY(uint, _dirty_region_buffer); 170 } 171 if (_in_dirty_region_buffer != NULL) { 172 FREE_C_HEAP_ARRAY(IsDirtyRegionState, _in_dirty_region_buffer); 173 } 174 if (_scan_top != NULL) { 175 FREE_C_HEAP_ARRAY(HeapWord*, _scan_top); 176 } 177 } 178 179 void initialize(uint max_regions) { 180 assert(_iter_states == NULL, "Must not be initialized twice"); 181 assert(_iter_claims == NULL, "Must not be initialized twice"); 182 _max_regions = max_regions; 183 _iter_states = NEW_C_HEAP_ARRAY(G1RemsetIterState, max_regions, mtGC); 184 _iter_claims = NEW_C_HEAP_ARRAY(size_t, max_regions, mtGC); 185 _dirty_region_buffer = NEW_C_HEAP_ARRAY(uint, max_regions, mtGC); 186 _in_dirty_region_buffer = NEW_C_HEAP_ARRAY(IsDirtyRegionState, max_regions, mtGC); 187 _scan_top = NEW_C_HEAP_ARRAY(HeapWord*, max_regions, mtGC); 188 } 189 190 void reset() { 191 for (uint i = 0; i < _max_regions; i++) { 192 _iter_states[i] = Unclaimed; 193 } 194 195 G1ResetScanTopClosure cl(_scan_top); 196 G1CollectedHeap::heap()->heap_region_iterate(&cl); 197 198 memset((void*)_iter_claims, 0, _max_regions * sizeof(size_t)); 199 memset(_in_dirty_region_buffer, Clean, _max_regions * sizeof(IsDirtyRegionState)); 200 _cur_dirty_region = 0; 201 } 202 203 // Attempt to claim the remembered set of the region for iteration. Returns true 204 // if this call caused the transition from Unclaimed to Claimed. 205 inline bool claim_iter(uint region) { 206 assert(region < _max_regions, "Tried to access invalid region %u", region); 207 if (_iter_states[region] != Unclaimed) { 208 return false; 209 } 210 G1RemsetIterState res = Atomic::cmpxchg(Claimed, &_iter_states[region], Unclaimed); 211 return (res == Unclaimed); 212 } 213 214 // Try to atomically sets the iteration state to "complete". Returns true for the 215 // thread that caused the transition. 216 inline bool set_iter_complete(uint region) { 217 if (iter_is_complete(region)) { 218 return false; 219 } 220 G1RemsetIterState res = Atomic::cmpxchg(Complete, &_iter_states[region], Claimed); 221 return (res == Claimed); 222 } 223 224 // Returns true if the region's iteration is complete. 225 inline bool iter_is_complete(uint region) const { 226 assert(region < _max_regions, "Tried to access invalid region %u", region); 227 return _iter_states[region] == Complete; 228 } 229 230 // The current position within the remembered set of the given region. 231 inline size_t iter_claimed(uint region) const { 232 assert(region < _max_regions, "Tried to access invalid region %u", region); 233 return _iter_claims[region]; 234 } 235 236 // Claim the next block of cards within the remembered set of the region with 237 // step size. 238 inline size_t iter_claimed_next(uint region, size_t step) { 239 return Atomic::add(step, &_iter_claims[region]) - step; 240 } 241 242 void add_dirty_region(uint region) { 243 if (_in_dirty_region_buffer[region] == Dirty) { 244 return; 245 } 246 247 bool marked_as_dirty = Atomic::cmpxchg(Dirty, &_in_dirty_region_buffer[region], Clean) == Clean; 248 if (marked_as_dirty) { 249 size_t allocated = Atomic::add(1u, &_cur_dirty_region) - 1; 250 _dirty_region_buffer[allocated] = region; 251 } 252 } 253 254 HeapWord* scan_top(uint region_idx) const { 255 return _scan_top[region_idx]; 256 } 257 258 // Clear the card table of "dirty" regions. 259 void clear_card_table(WorkGang* workers) { 260 if (_cur_dirty_region == 0) { 261 return; 262 } 263 264 size_t const num_chunks = align_up(_cur_dirty_region * HeapRegion::CardsPerRegion, G1ClearCardTableTask::chunk_size()) / G1ClearCardTableTask::chunk_size(); 265 uint const num_workers = (uint)MIN2(num_chunks, (size_t)workers->active_workers()); 266 size_t const chunk_length = G1ClearCardTableTask::chunk_size() / HeapRegion::CardsPerRegion; 267 268 // Iterate over the dirty cards region list. 269 G1ClearCardTableTask cl(G1CollectedHeap::heap(), _dirty_region_buffer, _cur_dirty_region, chunk_length); 270 271 log_debug(gc, ergo)("Running %s using %u workers for " SIZE_FORMAT " " 272 "units of work for " SIZE_FORMAT " regions.", 273 cl.name(), num_workers, num_chunks, _cur_dirty_region); 274 workers->run_task(&cl, num_workers); 275 276 #ifndef PRODUCT 277 G1CollectedHeap::heap()->verifier()->verify_card_table_cleanup(); 278 #endif 279 } 280 }; 281 282 G1RemSet::G1RemSet(G1CollectedHeap* g1h, 283 G1CardTable* ct, 284 G1HotCardCache* hot_card_cache) : 285 _scan_state(new G1RemSetScanState()), 286 _prev_period_summary(), 287 _g1h(g1h), 288 _num_conc_refined_cards(0), 289 _ct(ct), 290 _g1p(_g1h->g1_policy()), 291 _hot_card_cache(hot_card_cache) { 292 } 293 294 G1RemSet::~G1RemSet() { 295 if (_scan_state != NULL) { 296 delete _scan_state; 297 } 298 } 299 300 uint G1RemSet::num_par_rem_sets() { 301 return DirtyCardQueueSet::num_par_ids() + G1ConcurrentRefine::max_num_threads() + MAX2(ConcGCThreads, ParallelGCThreads); 302 } 303 304 void G1RemSet::initialize(size_t capacity, uint max_regions) { 305 G1FromCardCache::initialize(num_par_rem_sets(), max_regions); 306 _scan_state->initialize(max_regions); 307 } 308 309 G1ScanRSForRegionClosure::G1ScanRSForRegionClosure(G1RemSetScanState* scan_state, 310 G1ScanObjsDuringScanRSClosure* scan_obj_on_card, 311 G1ParScanThreadState* pss, 312 uint worker_i) : 313 _g1h(G1CollectedHeap::heap()), 314 _ct(_g1h->card_table()), 315 _pss(pss), 316 _scan_objs_on_card_cl(scan_obj_on_card), 317 _scan_state(scan_state), 318 _worker_i(worker_i), 319 _cards_scanned(0), 320 _cards_claimed(0), 321 _cards_skipped(0), 322 _rem_set_root_scan_time(), 323 _rem_set_trim_partially_time(), 324 _strong_code_root_scan_time(), 325 _strong_code_trim_partially_time() { 326 } 327 328 void G1ScanRSForRegionClosure::claim_card(size_t card_index, const uint region_idx_for_card){ 329 _ct->set_card_claimed(card_index); 330 _scan_state->add_dirty_region(region_idx_for_card); 331 } 332 333 void G1ScanRSForRegionClosure::scan_card(MemRegion mr, uint region_idx_for_card) { 334 HeapRegion* const card_region = _g1h->region_at(region_idx_for_card); 335 _scan_objs_on_card_cl->set_region(card_region); 336 card_region->oops_on_card_seq_iterate_careful<true>(mr, _scan_objs_on_card_cl); 337 _scan_objs_on_card_cl->trim_queue_partially(); 338 _cards_scanned++; 339 } 340 341 void G1ScanRSForRegionClosure::scan_rem_set_roots(HeapRegion* r) { 342 uint const region_idx = r->hrm_index(); 343 344 if (_scan_state->claim_iter(region_idx)) { 345 // If we ever free the collection set concurrently, we should also 346 // clear the card table concurrently therefore we won't need to 347 // add regions of the collection set to the dirty cards region. 348 _scan_state->add_dirty_region(region_idx); 349 } 350 351 // We claim cards in blocks so as to reduce the contention. 352 size_t const block_size = G1RSetScanBlockSize; 353 354 HeapRegionRemSetIterator iter(r->rem_set()); 355 size_t card_index; 356 357 size_t claimed_card_block = _scan_state->iter_claimed_next(region_idx, block_size); 358 for (size_t current_card = 0; iter.has_next(card_index); current_card++) { 359 if (current_card >= claimed_card_block + block_size) { 360 claimed_card_block = _scan_state->iter_claimed_next(region_idx, block_size); 361 } 362 if (current_card < claimed_card_block) { 363 _cards_skipped++; 364 continue; 365 } 366 _cards_claimed++; 367 368 // If the card is dirty, then G1 will scan it during Update RS. 369 if (_ct->is_card_claimed(card_index) || _ct->is_card_dirty(card_index)) { 370 continue; 371 } 372 373 HeapWord* const card_start = _g1h->bot()->address_for_index(card_index); 374 uint const region_idx_for_card = _g1h->addr_to_region(card_start); 375 376 assert(_g1h->region_at(region_idx_for_card)->is_in_reserved(card_start), 377 "Card start " PTR_FORMAT " to scan outside of region %u", p2i(card_start), _g1h->region_at(region_idx_for_card)->hrm_index()); 378 HeapWord* const top = _scan_state->scan_top(region_idx_for_card); 379 if (card_start >= top) { 380 continue; 381 } 382 383 // We claim lazily (so races are possible but they're benign), which reduces the 384 // number of duplicate scans (the rsets of the regions in the cset can intersect). 385 // Claim the card after checking bounds above: the remembered set may contain 386 // random cards into current survivor, and we would then have an incorrectly 387 // claimed card in survivor space. Card table clear does not reset the card table 388 // of survivor space regions. 389 claim_card(card_index, region_idx_for_card); 390 391 MemRegion const mr(card_start, MIN2(card_start + BOTConstants::N_words, top)); 392 393 scan_card(mr, region_idx_for_card); 394 } 395 } 396 397 void G1ScanRSForRegionClosure::scan_strong_code_roots(HeapRegion* r) { 398 r->strong_code_roots_do(_pss->closures()->weak_codeblobs()); 399 } 400 401 bool G1ScanRSForRegionClosure::do_heap_region(HeapRegion* r) { 402 assert(r->in_collection_set(), 403 "Should only be called on elements of the collection set but region %u is not.", 404 r->hrm_index()); 405 uint const region_idx = r->hrm_index(); 406 407 // Do an early out if we know we are complete. 408 if (_scan_state->iter_is_complete(region_idx)) { 409 return false; 410 } 411 412 { 413 G1EvacPhaseWithTrimTimeTracker timer(_pss, _rem_set_root_scan_time, _rem_set_trim_partially_time); 414 scan_rem_set_roots(r); 415 } 416 417 if (_scan_state->set_iter_complete(region_idx)) { 418 G1EvacPhaseWithTrimTimeTracker timer(_pss, _strong_code_root_scan_time, _strong_code_trim_partially_time); 419 // Scan the strong code root list attached to the current region 420 scan_strong_code_roots(r); 421 } 422 return false; 423 } 424 425 void G1RemSet::scan_rem_set(G1ParScanThreadState* pss, uint worker_i) { 426 G1ScanObjsDuringScanRSClosure scan_cl(_g1h, pss); 427 G1ScanRSForRegionClosure cl(_scan_state, &scan_cl, pss, worker_i); 428 _g1h->collection_set_iterate_from(&cl, worker_i); 429 430 G1GCPhaseTimes* p = _g1p->phase_times(); 431 432 p->record_time_secs(G1GCPhaseTimes::ScanRS, worker_i, cl.rem_set_root_scan_time().seconds()); 433 p->add_time_secs(G1GCPhaseTimes::ObjCopy, worker_i, cl.rem_set_trim_partially_time().seconds()); 434 435 p->record_thread_work_item(G1GCPhaseTimes::ScanRS, worker_i, cl.cards_scanned(), G1GCPhaseTimes::ScanRSScannedCards); 436 p->record_thread_work_item(G1GCPhaseTimes::ScanRS, worker_i, cl.cards_claimed(), G1GCPhaseTimes::ScanRSClaimedCards); 437 p->record_thread_work_item(G1GCPhaseTimes::ScanRS, worker_i, cl.cards_skipped(), G1GCPhaseTimes::ScanRSSkippedCards); 438 439 p->record_time_secs(G1GCPhaseTimes::CodeRoots, worker_i, cl.strong_code_root_scan_time().seconds()); 440 p->add_time_secs(G1GCPhaseTimes::ObjCopy, worker_i, cl.strong_code_root_trim_partially_time().seconds()); 441 } 442 443 // Closure used for updating rem sets. Only called during an evacuation pause. 444 class G1RefineCardClosure: public CardTableEntryClosure { 445 G1RemSet* _g1rs; 446 G1ScanObjsDuringUpdateRSClosure* _update_rs_cl; 447 448 size_t _cards_scanned; 449 size_t _cards_skipped; 450 public: 451 G1RefineCardClosure(G1CollectedHeap* g1h, G1ScanObjsDuringUpdateRSClosure* update_rs_cl) : 452 _g1rs(g1h->g1_rem_set()), _update_rs_cl(update_rs_cl), _cards_scanned(0), _cards_skipped(0) 453 {} 454 455 bool do_card_ptr(jbyte* card_ptr, uint worker_i) { 456 // The only time we care about recording cards that 457 // contain references that point into the collection set 458 // is during RSet updating within an evacuation pause. 459 // In this case worker_i should be the id of a GC worker thread. 460 assert(SafepointSynchronize::is_at_safepoint(), "not during an evacuation pause"); 461 462 bool card_scanned = _g1rs->refine_card_during_gc(card_ptr, _update_rs_cl); 463 464 if (card_scanned) { 465 _update_rs_cl->trim_queue_partially(); 466 _cards_scanned++; 467 } else { 468 _cards_skipped++; 469 } 470 return true; 471 } 472 473 size_t cards_scanned() const { return _cards_scanned; } 474 size_t cards_skipped() const { return _cards_skipped; } 475 }; 476 477 void G1RemSet::update_rem_set(G1ParScanThreadState* pss, uint worker_i) { 478 G1GCPhaseTimes* p = _g1p->phase_times(); 479 480 // Apply closure to log entries in the HCC. 481 if (G1HotCardCache::default_use_cache()) { 482 G1EvacPhaseTimesTracker x(p, pss, G1GCPhaseTimes::ScanHCC, worker_i); 483 484 G1ScanObjsDuringUpdateRSClosure scan_hcc_cl(_g1h, pss, worker_i); 485 G1RefineCardClosure refine_card_cl(_g1h, &scan_hcc_cl); 486 _g1h->iterate_hcc_closure(&refine_card_cl, worker_i); 487 } 488 489 // Now apply the closure to all remaining log entries. 490 { 491 G1EvacPhaseTimesTracker x(p, pss, G1GCPhaseTimes::UpdateRS, worker_i); 492 493 G1ScanObjsDuringUpdateRSClosure update_rs_cl(_g1h, pss, worker_i); 494 G1RefineCardClosure refine_card_cl(_g1h, &update_rs_cl); 495 _g1h->iterate_dirty_card_closure(&refine_card_cl, worker_i); 496 497 p->record_thread_work_item(G1GCPhaseTimes::UpdateRS, worker_i, refine_card_cl.cards_scanned(), G1GCPhaseTimes::UpdateRSScannedCards); 498 p->record_thread_work_item(G1GCPhaseTimes::UpdateRS, worker_i, refine_card_cl.cards_skipped(), G1GCPhaseTimes::UpdateRSSkippedCards); 499 } 500 } 501 502 void G1RemSet::cleanupHRRS() { 503 HeapRegionRemSet::cleanup(); 504 } 505 506 void G1RemSet::oops_into_collection_set_do(G1ParScanThreadState* pss, uint worker_i) { 507 update_rem_set(pss, worker_i); 508 scan_rem_set(pss, worker_i);; 509 } 510 511 void G1RemSet::prepare_for_oops_into_collection_set_do() { 512 DirtyCardQueueSet& dcqs = G1BarrierSet::dirty_card_queue_set(); 513 dcqs.concatenate_logs(); 514 515 _scan_state->reset(); 516 } 517 518 void G1RemSet::cleanup_after_oops_into_collection_set_do() { 519 G1GCPhaseTimes* phase_times = _g1h->g1_policy()->phase_times(); 520 521 // Set all cards back to clean. 522 double start = os::elapsedTime(); 523 _scan_state->clear_card_table(_g1h->workers()); 524 phase_times->record_clear_ct_time((os::elapsedTime() - start) * 1000.0); 525 } 526 527 inline void check_card_ptr(jbyte* card_ptr, G1CardTable* ct) { 528 #ifdef ASSERT 529 G1CollectedHeap* g1h = G1CollectedHeap::heap(); 530 assert(g1h->is_in_exact(ct->addr_for(card_ptr)), 531 "Card at " PTR_FORMAT " index " SIZE_FORMAT " representing heap at " PTR_FORMAT " (%u) must be in committed heap", 532 p2i(card_ptr), 533 ct->index_for(ct->addr_for(card_ptr)), 534 p2i(ct->addr_for(card_ptr)), 535 g1h->addr_to_region(ct->addr_for(card_ptr))); 536 #endif 537 } 538 539 void G1RemSet::refine_card_concurrently(jbyte* card_ptr, 540 uint worker_i) { 541 assert(!_g1h->is_gc_active(), "Only call concurrently"); 542 543 check_card_ptr(card_ptr, _ct); 544 545 // If the card is no longer dirty, nothing to do. 546 if (*card_ptr != G1CardTable::dirty_card_val()) { 547 return; 548 } 549 550 // Construct the region representing the card. 551 HeapWord* start = _ct->addr_for(card_ptr); 552 // And find the region containing it. 553 HeapRegion* r = _g1h->heap_region_containing(start); 554 555 // This check is needed for some uncommon cases where we should 556 // ignore the card. 557 // 558 // The region could be young. Cards for young regions are 559 // distinctly marked (set to g1_young_gen), so the post-barrier will 560 // filter them out. However, that marking is performed 561 // concurrently. A write to a young object could occur before the 562 // card has been marked young, slipping past the filter. 563 // 564 // The card could be stale, because the region has been freed since 565 // the card was recorded. In this case the region type could be 566 // anything. If (still) free or (reallocated) young, just ignore 567 // it. If (reallocated) old or humongous, the later card trimming 568 // and additional checks in iteration may detect staleness. At 569 // worst, we end up processing a stale card unnecessarily. 570 // 571 // In the normal (non-stale) case, the synchronization between the 572 // enqueueing of the card and processing it here will have ensured 573 // we see the up-to-date region type here. 574 if (!r->is_old_or_humongous_or_archive()) { 575 return; 576 } 577 578 // The result from the hot card cache insert call is either: 579 // * pointer to the current card 580 // (implying that the current card is not 'hot'), 581 // * null 582 // (meaning we had inserted the card ptr into the "hot" card cache, 583 // which had some headroom), 584 // * a pointer to a "hot" card that was evicted from the "hot" cache. 585 // 586 587 if (_hot_card_cache->use_cache()) { 588 assert(!SafepointSynchronize::is_at_safepoint(), "sanity"); 589 590 const jbyte* orig_card_ptr = card_ptr; 591 card_ptr = _hot_card_cache->insert(card_ptr); 592 if (card_ptr == NULL) { 593 // There was no eviction. Nothing to do. 594 return; 595 } else if (card_ptr != orig_card_ptr) { 596 // Original card was inserted and an old card was evicted. 597 start = _ct->addr_for(card_ptr); 598 r = _g1h->heap_region_containing(start); 599 600 // Check whether the region formerly in the cache should be 601 // ignored, as discussed earlier for the original card. The 602 // region could have been freed while in the cache. 603 if (!r->is_old_or_humongous_or_archive()) { 604 return; 605 } 606 } // Else we still have the original card. 607 } 608 609 // Trim the region designated by the card to what's been allocated 610 // in the region. The card could be stale, or the card could cover 611 // (part of) an object at the end of the allocated space and extend 612 // beyond the end of allocation. 613 614 // Non-humongous objects are only allocated in the old-gen during 615 // GC, so if region is old then top is stable. Humongous object 616 // allocation sets top last; if top has not yet been set, this is 617 // a stale card and we'll end up with an empty intersection. If 618 // this is not a stale card, the synchronization between the 619 // enqueuing of the card and processing it here will have ensured 620 // we see the up-to-date top here. 621 HeapWord* scan_limit = r->top(); 622 623 if (scan_limit <= start) { 624 // If the trimmed region is empty, the card must be stale. 625 return; 626 } 627 628 // Okay to clean and process the card now. There are still some 629 // stale card cases that may be detected by iteration and dealt with 630 // as iteration failure. 631 *const_cast<volatile jbyte*>(card_ptr) = G1CardTable::clean_card_val(); 632 633 // This fence serves two purposes. First, the card must be cleaned 634 // before processing the contents. Second, we can't proceed with 635 // processing until after the read of top, for synchronization with 636 // possibly concurrent humongous object allocation. It's okay that 637 // reading top and reading type were racy wrto each other. We need 638 // both set, in any order, to proceed. 639 OrderAccess::fence(); 640 641 // Don't use addr_for(card_ptr + 1) which can ask for 642 // a card beyond the heap. 643 HeapWord* end = start + G1CardTable::card_size_in_words; 644 MemRegion dirty_region(start, MIN2(scan_limit, end)); 645 assert(!dirty_region.is_empty(), "sanity"); 646 647 G1ConcurrentRefineOopClosure conc_refine_cl(_g1h, worker_i); 648 649 bool card_processed = 650 r->oops_on_card_seq_iterate_careful<false>(dirty_region, &conc_refine_cl); 651 652 // If unable to process the card then we encountered an unparsable 653 // part of the heap (e.g. a partially allocated object) while 654 // processing a stale card. Despite the card being stale, redirty 655 // and re-enqueue, because we've already cleaned the card. Without 656 // this we could incorrectly discard a non-stale card. 657 if (!card_processed) { 658 // The card might have gotten re-dirtied and re-enqueued while we 659 // worked. (In fact, it's pretty likely.) 660 if (*card_ptr != G1CardTable::dirty_card_val()) { 661 *card_ptr = G1CardTable::dirty_card_val(); 662 MutexLockerEx x(Shared_DirtyCardQ_lock, 663 Mutex::_no_safepoint_check_flag); 664 DirtyCardQueue* sdcq = 665 G1BarrierSet::dirty_card_queue_set().shared_dirty_card_queue(); 666 sdcq->enqueue(card_ptr); 667 } 668 } else { 669 _num_conc_refined_cards++; // Unsynchronized update, only used for logging. 670 } 671 } 672 673 bool G1RemSet::refine_card_during_gc(jbyte* card_ptr, 674 G1ScanObjsDuringUpdateRSClosure* update_rs_cl) { 675 assert(_g1h->is_gc_active(), "Only call during GC"); 676 677 check_card_ptr(card_ptr, _ct); 678 679 // If the card is no longer dirty, nothing to do. This covers cards that were already 680 // scanned as parts of the remembered sets. 681 if (*card_ptr != G1CardTable::dirty_card_val()) { 682 return false; 683 } 684 685 // We claim lazily (so races are possible but they're benign), which reduces the 686 // number of potential duplicate scans (multiple threads may enqueue the same card twice). 687 *card_ptr = G1CardTable::clean_card_val() | G1CardTable::claimed_card_val(); 688 689 // Construct the region representing the card. 690 HeapWord* card_start = _ct->addr_for(card_ptr); 691 // And find the region containing it. 692 uint const card_region_idx = _g1h->addr_to_region(card_start); 693 694 _scan_state->add_dirty_region(card_region_idx); 695 HeapWord* scan_limit = _scan_state->scan_top(card_region_idx); 696 if (scan_limit <= card_start) { 697 // If the card starts above the area in the region containing objects to scan, skip it. 698 return false; 699 } 700 701 // Don't use addr_for(card_ptr + 1) which can ask for 702 // a card beyond the heap. 703 HeapWord* card_end = card_start + G1CardTable::card_size_in_words; 704 MemRegion dirty_region(card_start, MIN2(scan_limit, card_end)); 705 assert(!dirty_region.is_empty(), "sanity"); 706 707 HeapRegion* const card_region = _g1h->region_at(card_region_idx); 708 update_rs_cl->set_region(card_region); 709 bool card_processed = card_region->oops_on_card_seq_iterate_careful<true>(dirty_region, update_rs_cl); 710 assert(card_processed, "must be"); 711 return true; 712 } 713 714 void G1RemSet::print_periodic_summary_info(const char* header, uint period_count) { 715 if ((G1SummarizeRSetStatsPeriod > 0) && log_is_enabled(Trace, gc, remset) && 716 (period_count % G1SummarizeRSetStatsPeriod == 0)) { 717 718 G1RemSetSummary current(this); 719 _prev_period_summary.subtract_from(¤t); 720 721 Log(gc, remset) log; 722 log.trace("%s", header); 723 ResourceMark rm; 724 LogStream ls(log.trace()); 725 _prev_period_summary.print_on(&ls); 726 727 _prev_period_summary.set(¤t); 728 } 729 } 730 731 void G1RemSet::print_summary_info() { 732 Log(gc, remset, exit) log; 733 if (log.is_trace()) { 734 log.trace(" Cumulative RS summary"); 735 G1RemSetSummary current(this); 736 ResourceMark rm; 737 LogStream ls(log.trace()); 738 current.print_on(&ls); 739 } 740 } 741 742 class G1RebuildRemSetTask: public AbstractGangTask { 743 // Aggregate the counting data that was constructed concurrently 744 // with marking. 745 class G1RebuildRemSetHeapRegionClosure : public HeapRegionClosure { 746 G1ConcurrentMark* _cm; 747 G1RebuildRemSetClosure _update_cl; 748 749 // Applies _update_cl to the references of the given object, limiting objArrays 750 // to the given MemRegion. Returns the amount of words actually scanned. 751 size_t scan_for_references(oop const obj, MemRegion mr) { 752 size_t const obj_size = obj->size(); 753 // All non-objArrays and objArrays completely within the mr 754 // can be scanned without passing the mr. 755 if (!obj->is_objArray() || mr.contains(MemRegion((HeapWord*)obj, obj_size))) { 756 obj->oop_iterate(&_update_cl); 757 return obj_size; 758 } 759 // This path is for objArrays crossing the given MemRegion. Only scan the 760 // area within the MemRegion. 761 obj->oop_iterate(&_update_cl, mr); 762 return mr.intersection(MemRegion((HeapWord*)obj, obj_size)).word_size(); 763 } 764 765 // A humongous object is live (with respect to the scanning) either 766 // a) it is marked on the bitmap as such 767 // b) its TARS is larger than TAMS, i.e. has been allocated during marking. 768 bool is_humongous_live(oop const humongous_obj, const G1CMBitMap* const bitmap, HeapWord* tams, HeapWord* tars) const { 769 return bitmap->is_marked(humongous_obj) || (tars > tams); 770 } 771 772 // Iterator over the live objects within the given MemRegion. 773 class LiveObjIterator : public StackObj { 774 const G1CMBitMap* const _bitmap; 775 const HeapWord* _tams; 776 const MemRegion _mr; 777 HeapWord* _current; 778 779 bool is_below_tams() const { 780 return _current < _tams; 781 } 782 783 bool is_live(HeapWord* obj) const { 784 return !is_below_tams() || _bitmap->is_marked(obj); 785 } 786 787 HeapWord* bitmap_limit() const { 788 return MIN2(const_cast<HeapWord*>(_tams), _mr.end()); 789 } 790 791 void move_if_below_tams() { 792 if (is_below_tams() && has_next()) { 793 _current = _bitmap->get_next_marked_addr(_current, bitmap_limit()); 794 } 795 } 796 public: 797 LiveObjIterator(const G1CMBitMap* const bitmap, const HeapWord* tams, const MemRegion mr, HeapWord* first_oop_into_mr) : 798 _bitmap(bitmap), 799 _tams(tams), 800 _mr(mr), 801 _current(first_oop_into_mr) { 802 803 assert(_current <= _mr.start(), 804 "First oop " PTR_FORMAT " should extend into mr [" PTR_FORMAT ", " PTR_FORMAT ")", 805 p2i(first_oop_into_mr), p2i(mr.start()), p2i(mr.end())); 806 807 // Step to the next live object within the MemRegion if needed. 808 if (is_live(_current)) { 809 // Non-objArrays were scanned by the previous part of that region. 810 if (_current < mr.start() && !oop(_current)->is_objArray()) { 811 _current += oop(_current)->size(); 812 // We might have positioned _current on a non-live object. Reposition to the next 813 // live one if needed. 814 move_if_below_tams(); 815 } 816 } else { 817 // The object at _current can only be dead if below TAMS, so we can use the bitmap. 818 // immediately. 819 _current = _bitmap->get_next_marked_addr(_current, bitmap_limit()); 820 assert(_current == _mr.end() || is_live(_current), 821 "Current " PTR_FORMAT " should be live (%s) or beyond the end of the MemRegion (" PTR_FORMAT ")", 822 p2i(_current), BOOL_TO_STR(is_live(_current)), p2i(_mr.end())); 823 } 824 } 825 826 void move_to_next() { 827 _current += next()->size(); 828 move_if_below_tams(); 829 } 830 831 oop next() const { 832 oop result = oop(_current); 833 assert(is_live(_current), 834 "Object " PTR_FORMAT " must be live TAMS " PTR_FORMAT " below %d mr " PTR_FORMAT " " PTR_FORMAT " outside %d", 835 p2i(_current), p2i(_tams), _tams > _current, p2i(_mr.start()), p2i(_mr.end()), _mr.contains(result)); 836 return result; 837 } 838 839 bool has_next() const { 840 return _current < _mr.end(); 841 } 842 }; 843 844 // Rebuild remembered sets in the part of the region specified by mr and hr. 845 // Objects between the bottom of the region and the TAMS are checked for liveness 846 // using the given bitmap. Objects between TAMS and TARS are assumed to be live. 847 // Returns the number of live words between bottom and TAMS. 848 size_t rebuild_rem_set_in_region(const G1CMBitMap* const bitmap, 849 HeapWord* const top_at_mark_start, 850 HeapWord* const top_at_rebuild_start, 851 HeapRegion* hr, 852 MemRegion mr) { 853 size_t marked_words = 0; 854 855 if (hr->is_humongous()) { 856 oop const humongous_obj = oop(hr->humongous_start_region()->bottom()); 857 if (is_humongous_live(humongous_obj, bitmap, top_at_mark_start, top_at_rebuild_start)) { 858 // We need to scan both [bottom, TAMS) and [TAMS, top_at_rebuild_start); 859 // however in case of humongous objects it is sufficient to scan the encompassing 860 // area (top_at_rebuild_start is always larger or equal to TAMS) as one of the 861 // two areas will be zero sized. I.e. TAMS is either 862 // the same as bottom or top(_at_rebuild_start). There is no way TAMS has a different 863 // value: this would mean that TAMS points somewhere into the object. 864 assert(hr->top() == top_at_mark_start || hr->top() == top_at_rebuild_start, 865 "More than one object in the humongous region?"); 866 humongous_obj->oop_iterate(&_update_cl, mr); 867 return top_at_mark_start != hr->bottom() ? mr.intersection(MemRegion((HeapWord*)humongous_obj, humongous_obj->size())).byte_size() : 0; 868 } else { 869 return 0; 870 } 871 } 872 873 for (LiveObjIterator it(bitmap, top_at_mark_start, mr, hr->block_start(mr.start())); it.has_next(); it.move_to_next()) { 874 oop obj = it.next(); 875 size_t scanned_size = scan_for_references(obj, mr); 876 if ((HeapWord*)obj < top_at_mark_start) { 877 marked_words += scanned_size; 878 } 879 } 880 881 return marked_words * HeapWordSize; 882 } 883 public: 884 G1RebuildRemSetHeapRegionClosure(G1CollectedHeap* g1h, 885 G1ConcurrentMark* cm, 886 uint worker_id) : 887 HeapRegionClosure(), 888 _cm(cm), 889 _update_cl(g1h, worker_id) { } 890 891 bool do_heap_region(HeapRegion* hr) { 892 if (_cm->has_aborted()) { 893 return true; 894 } 895 896 uint const region_idx = hr->hrm_index(); 897 DEBUG_ONLY(HeapWord* const top_at_rebuild_start_check = _cm->top_at_rebuild_start(region_idx);) 898 assert(top_at_rebuild_start_check == NULL || 899 top_at_rebuild_start_check > hr->bottom(), 900 "A TARS (" PTR_FORMAT ") == bottom() (" PTR_FORMAT ") indicates the old region %u is empty (%s)", 901 p2i(top_at_rebuild_start_check), p2i(hr->bottom()), region_idx, hr->get_type_str()); 902 903 size_t total_marked_bytes = 0; 904 size_t const chunk_size_in_words = G1RebuildRemSetChunkSize / HeapWordSize; 905 906 HeapWord* const top_at_mark_start = hr->prev_top_at_mark_start(); 907 908 HeapWord* cur = hr->bottom(); 909 while (cur < hr->end()) { 910 // After every iteration (yield point) we need to check whether the region's 911 // TARS changed due to e.g. eager reclaim. 912 HeapWord* const top_at_rebuild_start = _cm->top_at_rebuild_start(region_idx); 913 if (top_at_rebuild_start == NULL) { 914 return false; 915 } 916 917 MemRegion next_chunk = MemRegion(hr->bottom(), top_at_rebuild_start).intersection(MemRegion(cur, chunk_size_in_words)); 918 if (next_chunk.is_empty()) { 919 break; 920 } 921 922 const Ticks start = Ticks::now(); 923 size_t marked_bytes = rebuild_rem_set_in_region(_cm->prev_mark_bitmap(), 924 top_at_mark_start, 925 top_at_rebuild_start, 926 hr, 927 next_chunk); 928 Tickspan time = Ticks::now() - start; 929 930 log_trace(gc, remset, tracking)("Rebuilt region %u " 931 "live " SIZE_FORMAT " " 932 "time %.3fms " 933 "marked bytes " SIZE_FORMAT " " 934 "bot " PTR_FORMAT " " 935 "TAMS " PTR_FORMAT " " 936 "TARS " PTR_FORMAT, 937 region_idx, 938 _cm->liveness(region_idx) * HeapWordSize, 939 time.seconds() * 1000.0, 940 marked_bytes, 941 p2i(hr->bottom()), 942 p2i(top_at_mark_start), 943 p2i(top_at_rebuild_start)); 944 945 if (marked_bytes > 0) { 946 total_marked_bytes += marked_bytes; 947 } 948 cur += chunk_size_in_words; 949 950 _cm->do_yield_check(); 951 if (_cm->has_aborted()) { 952 return true; 953 } 954 } 955 // In the final iteration of the loop the region might have been eagerly reclaimed. 956 // Simply filter out those regions. We can not just use region type because there 957 // might have already been new allocations into these regions. 958 DEBUG_ONLY(HeapWord* const top_at_rebuild_start = _cm->top_at_rebuild_start(region_idx);) 959 assert(top_at_rebuild_start == NULL || 960 total_marked_bytes == hr->marked_bytes(), 961 "Marked bytes " SIZE_FORMAT " for region %u (%s) in [bottom, TAMS) do not match calculated marked bytes " SIZE_FORMAT " " 962 "(" PTR_FORMAT " " PTR_FORMAT " " PTR_FORMAT ")", 963 total_marked_bytes, hr->hrm_index(), hr->get_type_str(), hr->marked_bytes(), 964 p2i(hr->bottom()), p2i(top_at_mark_start), p2i(top_at_rebuild_start)); 965 // Abort state may have changed after the yield check. 966 return _cm->has_aborted(); 967 } 968 }; 969 970 HeapRegionClaimer _hr_claimer; 971 G1ConcurrentMark* _cm; 972 973 uint _worker_id_offset; 974 public: 975 G1RebuildRemSetTask(G1ConcurrentMark* cm, 976 uint n_workers, 977 uint worker_id_offset) : 978 AbstractGangTask("G1 Rebuild Remembered Set"), 979 _hr_claimer(n_workers), 980 _cm(cm), 981 _worker_id_offset(worker_id_offset) { 982 } 983 984 void work(uint worker_id) { 985 SuspendibleThreadSetJoiner sts_join; 986 987 G1CollectedHeap* g1h = G1CollectedHeap::heap(); 988 989 G1RebuildRemSetHeapRegionClosure cl(g1h, _cm, _worker_id_offset + worker_id); 990 g1h->heap_region_par_iterate_from_worker_offset(&cl, &_hr_claimer, worker_id); 991 } 992 }; 993 994 void G1RemSet::rebuild_rem_set(G1ConcurrentMark* cm, 995 WorkGang* workers, 996 uint worker_id_offset) { 997 uint num_workers = workers->active_workers(); 998 999 G1RebuildRemSetTask cl(cm, 1000 num_workers, 1001 worker_id_offset); 1002 workers->run_task(&cl, num_workers); 1003 }