1 /*
   2  * Copyright (c) 2001, 2020, 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/g1BarrierSet.hpp"
  27 #include "gc/g1/g1BlockOffsetTable.inline.hpp"
  28 #include "gc/g1/g1CardTable.inline.hpp"
  29 #include "gc/g1/g1CardTableEntryClosure.hpp"
  30 #include "gc/g1/g1CollectedHeap.inline.hpp"
  31 #include "gc/g1/g1ConcurrentRefine.hpp"
  32 #include "gc/g1/g1DirtyCardQueue.hpp"
  33 #include "gc/g1/g1FromCardCache.hpp"
  34 #include "gc/g1/g1GCParPhaseTimesTracker.hpp"
  35 #include "gc/g1/g1GCPhaseTimes.hpp"
  36 #include "gc/g1/g1HotCardCache.hpp"
  37 #include "gc/g1/g1OopClosures.inline.hpp"
  38 #include "gc/g1/g1RootClosures.hpp"
  39 #include "gc/g1/g1RemSet.hpp"
  40 #include "gc/g1/g1SharedDirtyCardQueue.hpp"
  41 #include "gc/g1/heapRegion.inline.hpp"
  42 #include "gc/g1/heapRegionManager.inline.hpp"
  43 #include "gc/g1/heapRegionRemSet.inline.hpp"
  44 #include "gc/g1/sparsePRT.hpp"
  45 #include "gc/shared/gcTraceTime.inline.hpp"
  46 #include "gc/shared/ptrQueue.hpp"
  47 #include "gc/shared/suspendibleThreadSet.hpp"
  48 #include "jfr/jfrEvents.hpp"
  49 #include "memory/iterator.hpp"
  50 #include "memory/resourceArea.hpp"
  51 #include "oops/access.inline.hpp"
  52 #include "oops/oop.inline.hpp"
  53 #include "runtime/atomic.hpp"
  54 #include "runtime/os.hpp"
  55 #include "utilities/align.hpp"
  56 #include "utilities/globalDefinitions.hpp"
  57 #include "utilities/stack.inline.hpp"
  58 #include "utilities/ticks.hpp"
  59 
  60 // Collects information about the overall heap root scan progress during an evacuation.
  61 //
  62 // Scanning the remembered sets works by first merging all sources of cards to be
  63 // scanned (log buffers, hcc, remembered sets) into a single data structure to remove
  64 // duplicates and simplify work distribution.
  65 //
  66 // During the following card scanning we not only scan this combined set of cards, but
  67 // also remember that these were completely scanned. The following evacuation passes
  68 // do not scan these cards again, and so need to be preserved across increments.
  69 //
  70 // The representation for all the cards to scan is the card table: cards can have
  71 // one of three states during GC:
  72 // - clean: these cards will not be scanned in this pass
  73 // - dirty: these cards will be scanned in this pass
  74 // - scanned: these cards have already been scanned in a previous pass
  75 //
  76 // After all evacuation is done, we reset the card table to clean.
  77 //
  78 // Work distribution occurs on "chunk" basis, i.e. contiguous ranges of cards. As an
  79 // additional optimization, during card merging we remember which regions and which
  80 // chunks actually contain cards to be scanned. Threads iterate only across these
  81 // regions, and only compete for chunks containing any cards.
  82 //
  83 // Within these chunks, a worker scans the card table on "blocks" of cards, i.e.
  84 // contiguous ranges of dirty cards to be scanned. These blocks are converted to actual
  85 // memory ranges and then passed on to actual scanning.
  86 class G1RemSetScanState : public CHeapObj<mtGC> {
  87   class G1DirtyRegions;
  88 
  89   size_t _max_regions;
  90 
  91   // Has this region that is part of the regions in the collection set been processed yet.
  92   typedef bool G1RemsetIterState;
  93 
  94   G1RemsetIterState volatile* _collection_set_iter_state;
  95 
  96   // Card table iteration claim for each heap region, from 0 (completely unscanned)
  97   // to (>=) HeapRegion::CardsPerRegion (completely scanned).
  98   uint volatile* _card_table_scan_state;
  99 
 100   // Return "optimal" number of chunks per region we want to use for claiming areas
 101   // within a region to claim. Dependent on the region size as proxy for the heap
 102   // size, we limit the total number of chunks to limit memory usage and maintenance
 103   // effort of that table vs. granularity of distributing scanning work.
 104   // Testing showed that 8 for 1M/2M region, 16 for 4M/8M regions, 32 for 16/32M regions
 105   // seems to be such a good trade-off.
 106   static uint get_chunks_per_region(uint log_region_size) {
 107     // Limit the expected input values to current known possible values of the
 108     // (log) region size. Adjust as necessary after testing if changing the permissible
 109     // values for region size.
 110     assert(log_region_size >= 20 && log_region_size <= 25,
 111            "expected value in [20,25], but got %u", log_region_size);
 112     return 1u << (log_region_size / 2 - 7);
 113   }
 114 
 115   uint _scan_chunks_per_region;         // Number of chunks per region.
 116   uint8_t _log_scan_chunks_per_region;  // Log of number of chunks per region.
 117   bool* _region_scan_chunks;
 118   size_t _num_total_scan_chunks;        // Total number of elements in _region_scan_chunks.
 119   uint8_t _scan_chunks_shift;           // For conversion between card index and chunk index.
 120 public:
 121   uint scan_chunk_size() const { return (uint)1 << _scan_chunks_shift; }
 122 
 123   // Returns whether the chunk corresponding to the given region/card in region contain a
 124   // dirty card, i.e. actually needs scanning.
 125   bool chunk_needs_scan(uint const region_idx, uint const card_in_region) const {
 126     size_t const idx = ((size_t)region_idx << _log_scan_chunks_per_region) + (card_in_region >> _scan_chunks_shift);
 127     assert(idx < _num_total_scan_chunks, "Index " SIZE_FORMAT " out of bounds " SIZE_FORMAT,
 128            idx, _num_total_scan_chunks);
 129     return _region_scan_chunks[idx];
 130   }
 131 
 132 private:
 133   // The complete set of regions which card table needs to be cleared at the end of GC because
 134   // we scribbled all over them.
 135   G1DirtyRegions* _all_dirty_regions;
 136   // The set of regions which card table needs to be scanned for new dirty cards
 137   // in the current evacuation pass.
 138   G1DirtyRegions* _next_dirty_regions;
 139 
 140   // Set of (unique) regions that can be added to concurrently.
 141   class G1DirtyRegions : public CHeapObj<mtGC> {
 142     uint* _buffer;
 143     uint _cur_idx;
 144     size_t _max_regions;
 145 
 146     bool* _contains;
 147 
 148   public:
 149     G1DirtyRegions(size_t max_regions) :
 150       _buffer(NEW_C_HEAP_ARRAY(uint, max_regions, mtGC)),
 151       _cur_idx(0),
 152       _max_regions(max_regions),
 153       _contains(NEW_C_HEAP_ARRAY(bool, max_regions, mtGC)) {
 154 
 155       reset();
 156     }
 157 
 158     static size_t chunk_size() { return M; }
 159 
 160     ~G1DirtyRegions() {
 161       FREE_C_HEAP_ARRAY(uint, _buffer);
 162       FREE_C_HEAP_ARRAY(bool, _contains);
 163     }
 164 
 165     void reset() {
 166       _cur_idx = 0;
 167       ::memset(_contains, false, _max_regions * sizeof(bool));
 168     }
 169 
 170     uint size() const { return _cur_idx; }
 171 
 172     uint at(uint idx) const {
 173       assert(idx < _cur_idx, "Index %u beyond valid regions", idx);
 174       return _buffer[idx];
 175     }
 176 
 177     void add_dirty_region(uint region) {
 178       if (_contains[region]) {
 179         return;
 180       }
 181 
 182       bool marked_as_dirty = Atomic::cmpxchg(&_contains[region], false, true) == false;
 183       if (marked_as_dirty) {
 184         uint allocated = Atomic::fetch_and_add(&_cur_idx, 1u);
 185         _buffer[allocated] = region;
 186       }
 187     }
 188 
 189     // Creates the union of this and the other G1DirtyRegions.
 190     void merge(const G1DirtyRegions* other) {
 191       for (uint i = 0; i < other->size(); i++) {
 192         uint region = other->at(i);
 193         if (!_contains[region]) {
 194           _buffer[_cur_idx++] = region;
 195           _contains[region] = true;
 196         }
 197       }
 198     }
 199   };
 200 
 201   // For each region, contains the maximum top() value to be used during this garbage
 202   // collection. Subsumes common checks like filtering out everything but old and
 203   // humongous regions outside the collection set.
 204   // This is valid because we are not interested in scanning stray remembered set
 205   // entries from free or archive regions.
 206   HeapWord** _scan_top;
 207 
 208   class G1ClearCardTableTask : public AbstractGangTask {
 209     G1CollectedHeap* _g1h;
 210     G1DirtyRegions* _regions;
 211     uint _chunk_length;
 212 
 213     uint volatile _cur_dirty_regions;
 214 
 215     G1RemSetScanState* _scan_state;
 216 
 217   public:
 218     G1ClearCardTableTask(G1CollectedHeap* g1h,
 219                          G1DirtyRegions* regions,
 220                          uint chunk_length,
 221                          G1RemSetScanState* scan_state) :
 222       AbstractGangTask("G1 Clear Card Table Task"),
 223       _g1h(g1h),
 224       _regions(regions),
 225       _chunk_length(chunk_length),
 226       _cur_dirty_regions(0),
 227       _scan_state(scan_state) {
 228 
 229       assert(chunk_length > 0, "must be");
 230     }
 231 
 232     static uint chunk_size() { return M; }
 233 
 234     void work(uint worker_id) {
 235       while (_cur_dirty_regions < _regions->size()) {
 236         uint next = Atomic::fetch_and_add(&_cur_dirty_regions, _chunk_length);
 237         uint max = MIN2(next + _chunk_length, _regions->size());
 238 
 239         for (uint i = next; i < max; i++) {
 240           HeapRegion* r = _g1h->region_at(_regions->at(i));
 241           if (!r->is_survivor()) {
 242             r->clear_cardtable();
 243           }
 244         }
 245       }
 246     }
 247   };
 248 
 249   // Clear the card table of "dirty" regions.
 250   void clear_card_table(WorkGang* workers) {
 251     uint num_regions = _all_dirty_regions->size();
 252 
 253     if (num_regions == 0) {
 254       return;
 255     }
 256 
 257     uint const num_chunks = (uint)(align_up((size_t)num_regions << HeapRegion::LogCardsPerRegion, G1ClearCardTableTask::chunk_size()) / G1ClearCardTableTask::chunk_size());
 258     uint const num_workers = MIN2(num_chunks, workers->active_workers());
 259     uint const chunk_length = G1ClearCardTableTask::chunk_size() / (uint)HeapRegion::CardsPerRegion;
 260 
 261     // Iterate over the dirty cards region list.
 262     G1ClearCardTableTask cl(G1CollectedHeap::heap(), _all_dirty_regions, chunk_length, this);
 263 
 264     log_debug(gc, ergo)("Running %s using %u workers for %u "
 265                         "units of work for %u regions.",
 266                         cl.name(), num_workers, num_chunks, num_regions);
 267     workers->run_task(&cl, num_workers);
 268 
 269 #ifndef PRODUCT
 270     G1CollectedHeap::heap()->verifier()->verify_card_table_cleanup();
 271 #endif
 272   }
 273 
 274 public:
 275   G1RemSetScanState() :
 276     _max_regions(0),
 277     _collection_set_iter_state(NULL),
 278     _card_table_scan_state(NULL),
 279     _scan_chunks_per_region(get_chunks_per_region(HeapRegion::LogOfHRGrainBytes)),
 280     _log_scan_chunks_per_region(log2_uint(_scan_chunks_per_region)),
 281     _region_scan_chunks(NULL),
 282     _num_total_scan_chunks(0),
 283     _scan_chunks_shift(0),
 284     _all_dirty_regions(NULL),
 285     _next_dirty_regions(NULL),
 286     _scan_top(NULL) {
 287   }
 288 
 289   ~G1RemSetScanState() {
 290     FREE_C_HEAP_ARRAY(G1RemsetIterState, _collection_set_iter_state);
 291     FREE_C_HEAP_ARRAY(uint, _card_table_scan_state);
 292     FREE_C_HEAP_ARRAY(bool, _region_scan_chunks);
 293     FREE_C_HEAP_ARRAY(HeapWord*, _scan_top);
 294   }
 295 
 296   void initialize(size_t max_regions) {
 297     assert(_collection_set_iter_state == NULL, "Must not be initialized twice");
 298     _max_regions = max_regions;
 299     _collection_set_iter_state = NEW_C_HEAP_ARRAY(G1RemsetIterState, max_regions, mtGC);
 300     _card_table_scan_state = NEW_C_HEAP_ARRAY(uint, max_regions, mtGC);
 301     _num_total_scan_chunks = max_regions * _scan_chunks_per_region;
 302     _region_scan_chunks = NEW_C_HEAP_ARRAY(bool, _num_total_scan_chunks, mtGC);
 303 
 304     _scan_chunks_shift = (uint8_t)log2_intptr(HeapRegion::CardsPerRegion / _scan_chunks_per_region);
 305     _scan_top = NEW_C_HEAP_ARRAY(HeapWord*, max_regions, mtGC);
 306   }
 307 
 308   void prepare() {
 309     // Reset the claim and clear scan top for all regions, including
 310     // regions currently not available or free. Since regions might
 311     // become used during the collection these values must be valid
 312     // for those regions as well.
 313     for (size_t i = 0; i < _max_regions; i++) {
 314       reset_region_claim((uint)i);
 315       clear_scan_top((uint)i);
 316     }
 317 
 318     _all_dirty_regions = new G1DirtyRegions(_max_regions);
 319     _next_dirty_regions = new G1DirtyRegions(_max_regions);
 320   }
 321 
 322   void prepare_for_merge_heap_roots() {
 323     _all_dirty_regions->merge(_next_dirty_regions);
 324 
 325     _next_dirty_regions->reset();
 326     for (size_t i = 0; i < _max_regions; i++) {
 327       _card_table_scan_state[i] = 0;
 328     }
 329 
 330     ::memset(_region_scan_chunks, false, _num_total_scan_chunks * sizeof(*_region_scan_chunks));
 331   }
 332 
 333   // Returns whether the given region contains cards we need to scan. The remembered
 334   // set and other sources may contain cards that
 335   // - are in uncommitted regions
 336   // - are located in the collection set
 337   // - are located in free regions
 338   // as we do not clean up remembered sets before merging heap roots.
 339   bool contains_cards_to_process(uint const region_idx) const {
 340     HeapRegion* hr = G1CollectedHeap::heap()->region_at_or_null(region_idx);
 341     return (hr != NULL && !hr->in_collection_set() && hr->is_old_or_humongous_or_archive());
 342   }
 343 
 344   size_t num_visited_cards() const {
 345     size_t result = 0;
 346     for (uint i = 0; i < _num_total_scan_chunks; i++) {
 347       if (_region_scan_chunks[i]) {
 348         result++;
 349       }
 350     }
 351     return result * (HeapRegion::CardsPerRegion / _scan_chunks_per_region);
 352   }
 353 
 354   size_t num_cards_in_dirty_regions() const {
 355     return _next_dirty_regions->size() * HeapRegion::CardsPerRegion;
 356   }
 357 
 358   void set_chunk_region_dirty(size_t const region_card_idx) {
 359     size_t chunk_idx = region_card_idx >> _scan_chunks_shift;
 360     for (uint i = 0; i < _scan_chunks_per_region; i++) {
 361       _region_scan_chunks[chunk_idx++] = true;
 362     }
 363   }
 364 
 365   void set_chunk_dirty(size_t const card_idx) {
 366     assert((card_idx >> _scan_chunks_shift) < _num_total_scan_chunks,
 367            "Trying to access index " SIZE_FORMAT " out of bounds " SIZE_FORMAT,
 368            card_idx >> _scan_chunks_shift, _num_total_scan_chunks);
 369     size_t const chunk_idx = card_idx >> _scan_chunks_shift;
 370     if (!_region_scan_chunks[chunk_idx]) {
 371       _region_scan_chunks[chunk_idx] = true;
 372     }
 373   }
 374 
 375   void cleanup(WorkGang* workers) {
 376     _all_dirty_regions->merge(_next_dirty_regions);
 377 
 378     clear_card_table(workers);
 379 
 380     delete _all_dirty_regions;
 381     _all_dirty_regions = NULL;
 382 
 383     delete _next_dirty_regions;
 384     _next_dirty_regions = NULL;
 385   }
 386 
 387   void iterate_dirty_regions_from(HeapRegionClosure* cl, uint worker_id) {
 388     uint num_regions = _next_dirty_regions->size();
 389 
 390     if (num_regions == 0) {
 391       return;
 392     }
 393 
 394     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 395 
 396     WorkGang* workers = g1h->workers();
 397     uint const max_workers = workers->active_workers();
 398 
 399     uint const start_pos = num_regions * worker_id / max_workers;
 400     uint cur = start_pos;
 401 
 402     do {
 403       bool result = cl->do_heap_region(g1h->region_at(_next_dirty_regions->at(cur)));
 404       guarantee(!result, "Not allowed to ask for early termination.");
 405       cur++;
 406       if (cur == _next_dirty_regions->size()) {
 407         cur = 0;
 408       }
 409     } while (cur != start_pos);
 410   }
 411 
 412   void reset_region_claim(uint region_idx) {
 413     _collection_set_iter_state[region_idx] = false;
 414   }
 415 
 416   // Attempt to claim the given region in the collection set for iteration. Returns true
 417   // if this call caused the transition from Unclaimed to Claimed.
 418   inline bool claim_collection_set_region(uint region) {
 419     assert(region < _max_regions, "Tried to access invalid region %u", region);
 420     if (_collection_set_iter_state[region]) {
 421       return false;
 422     }
 423     return !Atomic::cmpxchg(&_collection_set_iter_state[region], false, true);
 424   }
 425 
 426   bool has_cards_to_scan(uint region) {
 427     assert(region < _max_regions, "Tried to access invalid region %u", region);
 428     return _card_table_scan_state[region] < HeapRegion::CardsPerRegion;
 429   }
 430 
 431   uint claim_cards_to_scan(uint region, uint increment) {
 432     assert(region < _max_regions, "Tried to access invalid region %u", region);
 433     return Atomic::fetch_and_add(&_card_table_scan_state[region], increment);
 434   }
 435 
 436   void add_dirty_region(uint const region) {
 437 #ifdef ASSERT
 438    HeapRegion* hr = G1CollectedHeap::heap()->region_at(region);
 439    assert(!hr->in_collection_set() && hr->is_old_or_humongous_or_archive(),
 440           "Region %u is not suitable for scanning, is %sin collection set or %s",
 441           hr->hrm_index(), hr->in_collection_set() ? "" : "not ", hr->get_short_type_str());
 442 #endif
 443     _next_dirty_regions->add_dirty_region(region);
 444   }
 445 
 446   void add_all_dirty_region(uint region) {
 447 #ifdef ASSERT
 448     HeapRegion* hr = G1CollectedHeap::heap()->region_at(region);
 449     assert(hr->in_collection_set(),
 450            "Only add young regions to all dirty regions directly but %u is %s",
 451            hr->hrm_index(), hr->get_short_type_str());
 452 #endif
 453     _all_dirty_regions->add_dirty_region(region);
 454   }
 455 
 456   void set_scan_top(uint region_idx, HeapWord* value) {
 457     _scan_top[region_idx] = value;
 458   }
 459 
 460   HeapWord* scan_top(uint region_idx) const {
 461     return _scan_top[region_idx];
 462   }
 463 
 464   void clear_scan_top(uint region_idx) {
 465     set_scan_top(region_idx, NULL);
 466   }
 467 };
 468 
 469 G1RemSet::G1RemSet(G1CollectedHeap* g1h,
 470                    G1CardTable* ct,
 471                    G1HotCardCache* hot_card_cache) :
 472   _scan_state(new G1RemSetScanState()),
 473   _prev_period_summary(false),
 474   _g1h(g1h),
 475   _ct(ct),
 476   _g1p(_g1h->policy()),
 477   _hot_card_cache(hot_card_cache) {
 478 }
 479 
 480 G1RemSet::~G1RemSet() {
 481   delete _scan_state;
 482 }
 483 
 484 uint G1RemSet::num_par_rem_sets() {
 485   return G1DirtyCardQueueSet::num_par_ids() + G1ConcurrentRefine::max_num_threads() + MAX2(ConcGCThreads, ParallelGCThreads);
 486 }
 487 
 488 void G1RemSet::initialize(size_t capacity, uint max_regions) {
 489   G1FromCardCache::initialize(num_par_rem_sets(), max_regions);
 490   _scan_state->initialize(max_regions);
 491 }
 492 
 493 // Helper class to scan and detect ranges of cards that need to be scanned on the
 494 // card table.
 495 class G1CardTableScanner : public StackObj {
 496 public:
 497   typedef CardTable::CardValue CardValue;
 498 
 499 private:
 500   CardValue* const _base_addr;
 501 
 502   CardValue* _cur_addr;
 503   CardValue* const _end_addr;
 504 
 505   static const size_t ToScanMask = G1CardTable::g1_card_already_scanned;
 506   static const size_t ExpandedToScanMask = G1CardTable::WordAlreadyScanned;
 507 
 508   bool cur_addr_aligned() const {
 509     return ((uintptr_t)_cur_addr) % sizeof(size_t) == 0;
 510   }
 511 
 512   bool cur_card_is_dirty() const {
 513     CardValue value = *_cur_addr;
 514     return (value & ToScanMask) == 0;
 515   }
 516 
 517   bool cur_word_of_cards_contains_any_dirty_card() const {
 518     assert(cur_addr_aligned(), "Current address should be aligned");
 519     size_t const value = *(size_t*)_cur_addr;
 520     return (~value & ExpandedToScanMask) != 0;
 521   }
 522 
 523   bool cur_word_of_cards_all_dirty_cards() const {
 524     size_t const value = *(size_t*)_cur_addr;
 525     return value == G1CardTable::WordAllDirty;
 526   }
 527 
 528   size_t get_and_advance_pos() {
 529     _cur_addr++;
 530     return pointer_delta(_cur_addr, _base_addr, sizeof(CardValue)) - 1;
 531   }
 532 
 533 public:
 534   G1CardTableScanner(CardValue* start_card, size_t size) :
 535     _base_addr(start_card),
 536     _cur_addr(start_card),
 537     _end_addr(start_card + size) {
 538 
 539     assert(is_aligned(start_card, sizeof(size_t)), "Unaligned start addr " PTR_FORMAT, p2i(start_card));
 540     assert(is_aligned(size, sizeof(size_t)), "Unaligned size " SIZE_FORMAT, size);
 541   }
 542 
 543   size_t find_next_dirty() {
 544     while (!cur_addr_aligned()) {
 545       if (cur_card_is_dirty()) {
 546         return get_and_advance_pos();
 547       }
 548       _cur_addr++;
 549     }
 550 
 551     assert(cur_addr_aligned(), "Current address should be aligned now.");
 552     while (_cur_addr != _end_addr) {
 553       if (cur_word_of_cards_contains_any_dirty_card()) {
 554         for (size_t i = 0; i < sizeof(size_t); i++) {
 555           if (cur_card_is_dirty()) {
 556             return get_and_advance_pos();
 557           }
 558           _cur_addr++;
 559         }
 560         assert(false, "Should not reach here given we detected a dirty card in the word.");
 561       }
 562       _cur_addr += sizeof(size_t);
 563     }
 564     return get_and_advance_pos();
 565   }
 566 
 567   size_t find_next_non_dirty() {
 568     assert(_cur_addr <= _end_addr, "Not allowed to search for marks after area.");
 569 
 570     while (!cur_addr_aligned()) {
 571       if (!cur_card_is_dirty()) {
 572         return get_and_advance_pos();
 573       }
 574       _cur_addr++;
 575     }
 576 
 577     assert(cur_addr_aligned(), "Current address should be aligned now.");
 578     while (_cur_addr != _end_addr) {
 579       if (!cur_word_of_cards_all_dirty_cards()) {
 580         for (size_t i = 0; i < sizeof(size_t); i++) {
 581           if (!cur_card_is_dirty()) {
 582             return get_and_advance_pos();
 583           }
 584           _cur_addr++;
 585         }
 586         assert(false, "Should not reach here given we detected a non-dirty card in the word.");
 587       }
 588       _cur_addr += sizeof(size_t);
 589     }
 590     return get_and_advance_pos();
 591   }
 592 };
 593 
 594 // Helper class to claim dirty chunks within the card table.
 595 class G1CardTableChunkClaimer {
 596   G1RemSetScanState* _scan_state;
 597   uint _region_idx;
 598   uint _cur_claim;
 599 
 600 public:
 601   G1CardTableChunkClaimer(G1RemSetScanState* scan_state, uint region_idx) :
 602     _scan_state(scan_state),
 603     _region_idx(region_idx),
 604     _cur_claim(0) {
 605     guarantee(size() <= HeapRegion::CardsPerRegion, "Should not claim more space than possible.");
 606   }
 607 
 608   bool has_next() {
 609     while (true) {
 610       _cur_claim = _scan_state->claim_cards_to_scan(_region_idx, size());
 611       if (_cur_claim >= HeapRegion::CardsPerRegion) {
 612         return false;
 613       }
 614       if (_scan_state->chunk_needs_scan(_region_idx, _cur_claim)) {
 615         return true;
 616       }
 617     }
 618   }
 619 
 620   uint value() const { return _cur_claim; }
 621   uint size() const { return _scan_state->scan_chunk_size(); }
 622 };
 623 
 624 // Scans a heap region for dirty cards.
 625 class G1ScanHRForRegionClosure : public HeapRegionClosure {
 626   G1CollectedHeap* _g1h;
 627   G1CardTable* _ct;
 628   G1BlockOffsetTable* _bot;
 629 
 630   G1ParScanThreadState* _pss;
 631 
 632   G1RemSetScanState* _scan_state;
 633 
 634   G1GCPhaseTimes::GCParPhases _phase;
 635 
 636   uint   _worker_id;
 637 
 638   size_t _cards_scanned;
 639   size_t _blocks_scanned;
 640   size_t _chunks_claimed;
 641 
 642   Tickspan _rem_set_root_scan_time;
 643   Tickspan _rem_set_trim_partially_time;
 644 
 645   // The address to which this thread already scanned (walked the heap) up to during
 646   // card scanning (exclusive).
 647   HeapWord* _scanned_to;
 648 
 649   HeapWord* scan_memregion(uint region_idx_for_card, MemRegion mr) {
 650     HeapRegion* const card_region = _g1h->region_at(region_idx_for_card);
 651     G1ScanCardClosure card_cl(_g1h, _pss);
 652 
 653     HeapWord* const scanned_to = card_region->oops_on_memregion_seq_iterate_careful<true>(mr, &card_cl);
 654     assert(scanned_to != NULL, "Should be able to scan range");
 655     assert(scanned_to >= mr.end(), "Scanned to " PTR_FORMAT " less than range " PTR_FORMAT, p2i(scanned_to), p2i(mr.end()));
 656 
 657     _pss->trim_queue_partially();
 658     return scanned_to;
 659   }
 660 
 661   void do_claimed_block(uint const region_idx_for_card, size_t const first_card, size_t const num_cards) {
 662     HeapWord* const card_start = _bot->address_for_index_raw(first_card);
 663 #ifdef ASSERT
 664     HeapRegion* hr = _g1h->region_at_or_null(region_idx_for_card);
 665     assert(hr == NULL || hr->is_in_reserved(card_start),
 666              "Card start " PTR_FORMAT " to scan outside of region %u", p2i(card_start), _g1h->region_at(region_idx_for_card)->hrm_index());
 667 #endif
 668     HeapWord* const top = _scan_state->scan_top(region_idx_for_card);
 669     if (card_start >= top) {
 670       return;
 671     }
 672 
 673     HeapWord* scan_end = MIN2(card_start + (num_cards << BOTConstants::LogN_words), top);
 674     if (_scanned_to >= scan_end) {
 675       return;
 676     }
 677     MemRegion mr(MAX2(card_start, _scanned_to), scan_end);
 678     _scanned_to = scan_memregion(region_idx_for_card, mr);
 679 
 680     _cards_scanned += num_cards;
 681   }
 682 
 683   ALWAYSINLINE void do_card_block(uint const region_idx, size_t const first_card, size_t const num_cards) {
 684     _ct->mark_as_scanned(first_card, num_cards);
 685     do_claimed_block(region_idx, first_card, num_cards);
 686     _blocks_scanned++;
 687   }
 688 
 689    void scan_heap_roots(HeapRegion* r) {
 690     EventGCPhaseParallel event;
 691     uint const region_idx = r->hrm_index();
 692 
 693     ResourceMark rm;
 694 
 695     G1CardTableChunkClaimer claim(_scan_state, region_idx);
 696 
 697     // Set the current scan "finger" to NULL for every heap region to scan. Since
 698     // the claim value is monotonically increasing, the check to not scan below this
 699     // will filter out objects spanning chunks within the region too then, as opposed
 700     // to resetting this value for every claim.
 701     _scanned_to = NULL;
 702 
 703     while (claim.has_next()) {
 704       size_t const region_card_base_idx = ((size_t)region_idx << HeapRegion::LogCardsPerRegion) + claim.value();
 705       CardTable::CardValue* const base_addr = _ct->byte_for_index(region_card_base_idx);
 706 
 707       G1CardTableScanner scan(base_addr, claim.size());
 708 
 709       size_t first_scan_idx = scan.find_next_dirty();
 710       while (first_scan_idx != claim.size()) {
 711         assert(*_ct->byte_for_index(region_card_base_idx + first_scan_idx) <= 0x1, "is %d at region %u idx " SIZE_FORMAT, *_ct->byte_for_index(region_card_base_idx + first_scan_idx), region_idx, first_scan_idx);
 712 
 713         size_t const last_scan_idx = scan.find_next_non_dirty();
 714         size_t const len = last_scan_idx - first_scan_idx;
 715 
 716         do_card_block(region_idx, region_card_base_idx + first_scan_idx, len);
 717 
 718         if (last_scan_idx == claim.size()) {
 719           break;
 720         }
 721 
 722         first_scan_idx = scan.find_next_dirty();
 723       }
 724       _chunks_claimed++;
 725     }
 726 
 727     event.commit(GCId::current(), _worker_id, G1GCPhaseTimes::phase_name(G1GCPhaseTimes::ScanHR));
 728   }
 729 
 730 public:
 731   G1ScanHRForRegionClosure(G1RemSetScanState* scan_state,
 732                            G1ParScanThreadState* pss,
 733                            uint worker_id,
 734                            G1GCPhaseTimes::GCParPhases phase) :
 735     _g1h(G1CollectedHeap::heap()),
 736     _ct(_g1h->card_table()),
 737     _bot(_g1h->bot()),
 738     _pss(pss),
 739     _scan_state(scan_state),
 740     _phase(phase),
 741     _worker_id(worker_id),
 742     _cards_scanned(0),
 743     _blocks_scanned(0),
 744     _chunks_claimed(0),
 745     _rem_set_root_scan_time(),
 746     _rem_set_trim_partially_time(),
 747     _scanned_to(NULL) {
 748   }
 749 
 750   bool do_heap_region(HeapRegion* r) {
 751     assert(!r->in_collection_set() && r->is_old_or_humongous_or_archive(),
 752            "Should only be called on old gen non-collection set regions but region %u is not.",
 753            r->hrm_index());
 754     uint const region_idx = r->hrm_index();
 755 
 756     if (_scan_state->has_cards_to_scan(region_idx)) {
 757       G1EvacPhaseWithTrimTimeTracker timer(_pss, _rem_set_root_scan_time, _rem_set_trim_partially_time);
 758       scan_heap_roots(r);
 759     }
 760     return false;
 761   }
 762 
 763   Tickspan rem_set_root_scan_time() const { return _rem_set_root_scan_time; }
 764   Tickspan rem_set_trim_partially_time() const { return _rem_set_trim_partially_time; }
 765 
 766   size_t cards_scanned() const { return _cards_scanned; }
 767   size_t blocks_scanned() const { return _blocks_scanned; }
 768   size_t chunks_claimed() const { return _chunks_claimed; }
 769 };
 770 
 771 void G1RemSet::scan_heap_roots(G1ParScanThreadState* pss,
 772                             uint worker_id,
 773                             G1GCPhaseTimes::GCParPhases scan_phase,
 774                             G1GCPhaseTimes::GCParPhases objcopy_phase) {
 775   G1ScanHRForRegionClosure cl(_scan_state, pss, worker_id, scan_phase);
 776   _scan_state->iterate_dirty_regions_from(&cl, worker_id);
 777 
 778   G1GCPhaseTimes* p = _g1p->phase_times();
 779 
 780   p->record_or_add_time_secs(objcopy_phase, worker_id, cl.rem_set_trim_partially_time().seconds());
 781 
 782   p->record_or_add_time_secs(scan_phase, worker_id, cl.rem_set_root_scan_time().seconds());
 783   p->record_or_add_thread_work_item(scan_phase, worker_id, cl.cards_scanned(), G1GCPhaseTimes::ScanHRScannedCards);
 784   p->record_or_add_thread_work_item(scan_phase, worker_id, cl.blocks_scanned(), G1GCPhaseTimes::ScanHRScannedBlocks);
 785   p->record_or_add_thread_work_item(scan_phase, worker_id, cl.chunks_claimed(), G1GCPhaseTimes::ScanHRClaimedChunks);
 786 }
 787 
 788 // Heap region closure to be applied to all regions in the current collection set
 789 // increment to fix up non-card related roots.
 790 class G1ScanCollectionSetRegionClosure : public HeapRegionClosure {
 791   G1ParScanThreadState* _pss;
 792   G1RemSetScanState* _scan_state;
 793 
 794   G1GCPhaseTimes::GCParPhases _scan_phase;
 795   G1GCPhaseTimes::GCParPhases _code_roots_phase;
 796 
 797   uint _worker_id;
 798 
 799   size_t _opt_refs_scanned;
 800   size_t _opt_refs_memory_used;
 801 
 802   Tickspan _strong_code_root_scan_time;
 803   Tickspan _strong_code_trim_partially_time;
 804 
 805   Tickspan _rem_set_opt_root_scan_time;
 806   Tickspan _rem_set_opt_trim_partially_time;
 807 
 808   void scan_opt_rem_set_roots(HeapRegion* r) {
 809     EventGCPhaseParallel event;
 810 
 811     G1OopStarChunkedList* opt_rem_set_list = _pss->oops_into_optional_region(r);
 812 
 813     G1ScanCardClosure scan_cl(G1CollectedHeap::heap(), _pss);
 814     G1ScanRSForOptionalClosure cl(G1CollectedHeap::heap(), &scan_cl);
 815     _opt_refs_scanned += opt_rem_set_list->oops_do(&cl, _pss->closures()->strong_oops());
 816     _opt_refs_memory_used += opt_rem_set_list->used_memory();
 817 
 818     event.commit(GCId::current(), _worker_id, G1GCPhaseTimes::phase_name(_scan_phase));
 819   }
 820 
 821 public:
 822   G1ScanCollectionSetRegionClosure(G1RemSetScanState* scan_state,
 823                                    G1ParScanThreadState* pss,
 824                                    uint worker_id,
 825                                    G1GCPhaseTimes::GCParPhases scan_phase,
 826                                    G1GCPhaseTimes::GCParPhases code_roots_phase) :
 827     _pss(pss),
 828     _scan_state(scan_state),
 829     _scan_phase(scan_phase),
 830     _code_roots_phase(code_roots_phase),
 831     _worker_id(worker_id),
 832     _opt_refs_scanned(0),
 833     _opt_refs_memory_used(0),
 834     _strong_code_root_scan_time(),
 835     _strong_code_trim_partially_time(),
 836     _rem_set_opt_root_scan_time(),
 837     _rem_set_opt_trim_partially_time() { }
 838 
 839   bool do_heap_region(HeapRegion* r) {
 840     uint const region_idx = r->hrm_index();
 841 
 842     // The individual references for the optional remembered set are per-worker, so we
 843     // always need to scan them.
 844     if (r->has_index_in_opt_cset()) {
 845       G1EvacPhaseWithTrimTimeTracker timer(_pss, _rem_set_opt_root_scan_time, _rem_set_opt_trim_partially_time);
 846       scan_opt_rem_set_roots(r);
 847     }
 848 
 849     if (_scan_state->claim_collection_set_region(region_idx)) {
 850       EventGCPhaseParallel event;
 851 
 852       G1EvacPhaseWithTrimTimeTracker timer(_pss, _strong_code_root_scan_time, _strong_code_trim_partially_time);
 853       // Scan the strong code root list attached to the current region
 854       r->strong_code_roots_do(_pss->closures()->weak_codeblobs());
 855 
 856       event.commit(GCId::current(), _worker_id, G1GCPhaseTimes::phase_name(_code_roots_phase));
 857     }
 858 
 859     return false;
 860   }
 861 
 862   Tickspan strong_code_root_scan_time() const { return _strong_code_root_scan_time;  }
 863   Tickspan strong_code_root_trim_partially_time() const { return _strong_code_trim_partially_time; }
 864 
 865   Tickspan rem_set_opt_root_scan_time() const { return _rem_set_opt_root_scan_time; }
 866   Tickspan rem_set_opt_trim_partially_time() const { return _rem_set_opt_trim_partially_time; }
 867 
 868   size_t opt_refs_scanned() const { return _opt_refs_scanned; }
 869   size_t opt_refs_memory_used() const { return _opt_refs_memory_used; }
 870 };
 871 
 872 void G1RemSet::scan_collection_set_regions(G1ParScanThreadState* pss,
 873                                            uint worker_id,
 874                                            G1GCPhaseTimes::GCParPhases scan_phase,
 875                                            G1GCPhaseTimes::GCParPhases coderoots_phase,
 876                                            G1GCPhaseTimes::GCParPhases objcopy_phase) {
 877   G1ScanCollectionSetRegionClosure cl(_scan_state, pss, worker_id, scan_phase, coderoots_phase);
 878   _g1h->collection_set_iterate_increment_from(&cl, worker_id);
 879 
 880   G1GCPhaseTimes* p = _g1h->phase_times();
 881 
 882   p->record_or_add_time_secs(scan_phase, worker_id, cl.rem_set_opt_root_scan_time().seconds());
 883   p->record_or_add_time_secs(scan_phase, worker_id, cl.rem_set_opt_trim_partially_time().seconds());
 884 
 885   p->record_or_add_time_secs(coderoots_phase, worker_id, cl.strong_code_root_scan_time().seconds());
 886   p->add_time_secs(objcopy_phase, worker_id, cl.strong_code_root_trim_partially_time().seconds());
 887 
 888   // At this time we record some metrics only for the evacuations after the initial one.
 889   if (scan_phase == G1GCPhaseTimes::OptScanHR) {
 890     p->record_or_add_thread_work_item(scan_phase, worker_id, cl.opt_refs_scanned(), G1GCPhaseTimes::ScanHRScannedOptRefs);
 891     p->record_or_add_thread_work_item(scan_phase, worker_id, cl.opt_refs_memory_used(), G1GCPhaseTimes::ScanHRUsedMemory);
 892   }
 893 }
 894 
 895 void G1RemSet::prepare_region_for_scan(HeapRegion* region) {
 896   uint hrm_index = region->hrm_index();
 897 
 898   if (region->in_collection_set()) {
 899     // Young regions had their card table marked as young at their allocation;
 900     // we need to make sure that these marks are cleared at the end of GC, *but*
 901     // they should not be scanned for cards.
 902     // So directly add them to the "all_dirty_regions".
 903     // Same for regions in the (initial) collection set: they may contain cards from
 904     // the log buffers, make sure they are cleaned.
 905     _scan_state->add_all_dirty_region(hrm_index);
 906   } else if (region->is_old_or_humongous_or_archive()) {
 907     _scan_state->set_scan_top(hrm_index, region->top());
 908   } else {
 909     assert(region->is_free(), "Should only be free region at this point %s", region->get_type_str());
 910   }
 911 }
 912 
 913 void G1RemSet::prepare_for_scan_heap_roots() {
 914   _scan_state->prepare();
 915 }
 916 
 917 class G1MergeHeapRootsTask : public AbstractGangTask {
 918 
 919   // Visitor for remembered sets, dropping entries onto the card table.
 920   class G1MergeCardSetClosure : public HeapRegionClosure {
 921     G1RemSetScanState* _scan_state;
 922     G1CardTable* _ct;
 923 
 924     uint _merged_sparse;
 925     uint _merged_fine;
 926     uint _merged_coarse;
 927 
 928     size_t _cards_dirty;
 929 
 930     // Returns if the region contains cards we need to scan. If so, remember that
 931     // region in the current set of dirty regions.
 932     bool remember_if_interesting(uint const region_idx) {
 933       if (!_scan_state->contains_cards_to_process(region_idx)) {
 934         return false;
 935       }
 936       _scan_state->add_dirty_region(region_idx);
 937       return true;
 938     }
 939   public:
 940     G1MergeCardSetClosure(G1RemSetScanState* scan_state) :
 941       _scan_state(scan_state),
 942       _ct(G1CollectedHeap::heap()->card_table()),
 943       _merged_sparse(0),
 944       _merged_fine(0),
 945       _merged_coarse(0),
 946       _cards_dirty(0) { }
 947 
 948     void next_coarse_prt(uint const region_idx) {
 949       if (!remember_if_interesting(region_idx)) {
 950         return;
 951       }
 952 
 953       _merged_coarse++;
 954 
 955       size_t region_base_idx = (size_t)region_idx << HeapRegion::LogCardsPerRegion;
 956       _cards_dirty += _ct->mark_region_dirty(region_base_idx, HeapRegion::CardsPerRegion);
 957       _scan_state->set_chunk_region_dirty(region_base_idx);
 958     }
 959 
 960     void next_fine_prt(uint const region_idx, BitMap* bm) {
 961       if (!remember_if_interesting(region_idx)) {
 962         return;
 963       }
 964 
 965       _merged_fine++;
 966 
 967       size_t const region_base_idx = (size_t)region_idx << HeapRegion::LogCardsPerRegion;
 968       BitMap::idx_t cur = bm->get_next_one_offset(0);
 969       while (cur != bm->size()) {
 970         _cards_dirty += _ct->mark_clean_as_dirty(region_base_idx + cur);
 971         _scan_state->set_chunk_dirty(region_base_idx + cur);
 972         cur = bm->get_next_one_offset(cur + 1);
 973       }
 974     }
 975 
 976     void next_sparse_prt(uint const region_idx, SparsePRTEntry::card_elem_t* cards, uint const num_cards) {
 977       if (!remember_if_interesting(region_idx)) {
 978         return;
 979       }
 980 
 981       _merged_sparse++;
 982 
 983       size_t const region_base_idx = (size_t)region_idx << HeapRegion::LogCardsPerRegion;
 984       for (uint i = 0; i < num_cards; i++) {
 985         size_t card_idx = region_base_idx + cards[i];
 986         _cards_dirty += _ct->mark_clean_as_dirty(card_idx);
 987         _scan_state->set_chunk_dirty(card_idx);
 988       }
 989     }
 990 
 991     virtual bool do_heap_region(HeapRegion* r) {
 992       assert(r->in_collection_set() || r->is_starts_humongous(), "must be");
 993 
 994       HeapRegionRemSet* rem_set = r->rem_set();
 995       if (!rem_set->is_empty()) {
 996         rem_set->iterate_prts(*this);
 997       }
 998 
 999       return false;
1000     }
1001 
1002     size_t merged_sparse() const { return _merged_sparse; }
1003     size_t merged_fine() const { return _merged_fine; }
1004     size_t merged_coarse() const { return _merged_coarse; }
1005 
1006     size_t cards_dirty() const { return _cards_dirty; }
1007   };
1008 
1009   // Visitor for the remembered sets of humongous candidate regions to merge their
1010   // remembered set into the card table.
1011   class G1FlushHumongousCandidateRemSets : public HeapRegionClosure {
1012     G1MergeCardSetClosure _cl;
1013 
1014   public:
1015     G1FlushHumongousCandidateRemSets(G1RemSetScanState* scan_state) : _cl(scan_state) { }
1016 
1017     virtual bool do_heap_region(HeapRegion* r) {
1018       G1CollectedHeap* g1h = G1CollectedHeap::heap();
1019 
1020       if (!r->is_starts_humongous() ||
1021           !g1h->region_attr(r->hrm_index()).is_humongous() ||
1022           r->rem_set()->is_empty()) {
1023         return false;
1024       }
1025 
1026       guarantee(r->rem_set()->occupancy_less_or_equal_than(G1RSetSparseRegionEntries),
1027                 "Found a not-small remembered set here. This is inconsistent with previous assumptions.");
1028 
1029       _cl.do_heap_region(r);
1030 
1031       // We should only clear the card based remembered set here as we will not
1032       // implicitly rebuild anything else during eager reclaim. Note that at the moment
1033       // (and probably never) we do not enter this path if there are other kind of
1034       // remembered sets for this region.
1035       r->rem_set()->clear_locked(true /* only_cardset */);
1036       // Clear_locked() above sets the state to Empty. However we want to continue
1037       // collecting remembered set entries for humongous regions that were not
1038       // reclaimed.
1039       r->rem_set()->set_state_complete();
1040 #ifdef ASSERT
1041       G1HeapRegionAttr region_attr = g1h->region_attr(r->hrm_index());
1042       assert(region_attr.needs_remset_update(), "must be");
1043 #endif
1044       assert(r->rem_set()->is_empty(), "At this point any humongous candidate remembered set must be empty.");
1045 
1046       return false;
1047     }
1048 
1049     size_t merged_sparse() const { return _cl.merged_sparse(); }
1050     size_t merged_fine() const { return _cl.merged_fine(); }
1051     size_t merged_coarse() const { return _cl.merged_coarse(); }
1052 
1053     size_t cards_dirty() const { return _cl.cards_dirty(); }
1054   };
1055 
1056   // Visitor for the log buffer entries to merge them into the card table.
1057   class G1MergeLogBufferCardsClosure : public G1CardTableEntryClosure {
1058     G1RemSetScanState* _scan_state;
1059     G1CardTable* _ct;
1060 
1061     size_t _cards_dirty;
1062     size_t _cards_skipped;
1063   public:
1064     G1MergeLogBufferCardsClosure(G1CollectedHeap* g1h, G1RemSetScanState* scan_state) :
1065       _scan_state(scan_state), _ct(g1h->card_table()), _cards_dirty(0), _cards_skipped(0)
1066     {}
1067 
1068     void do_card_ptr(CardValue* card_ptr, uint worker_id) {
1069       // The only time we care about recording cards that
1070       // contain references that point into the collection set
1071       // is during RSet updating within an evacuation pause.
1072       // In this case worker_id should be the id of a GC worker thread.
1073       assert(SafepointSynchronize::is_at_safepoint(), "not during an evacuation pause");
1074 
1075       uint const region_idx = _ct->region_idx_for(card_ptr);
1076 
1077       // The second clause must come after - the log buffers might contain cards to uncommited
1078       // regions.
1079       // This code may count duplicate entries in the log buffers (even if rare) multiple
1080       // times.
1081       if (_scan_state->contains_cards_to_process(region_idx) && (*card_ptr == G1CardTable::dirty_card_val())) {
1082         _scan_state->add_dirty_region(region_idx);
1083         _scan_state->set_chunk_dirty(_ct->index_for_cardvalue(card_ptr));
1084         _cards_dirty++;
1085       } else {
1086         // We may have had dirty cards in the (initial) collection set (or the
1087         // young regions which are always in the initial collection set). We do
1088         // not fix their cards here: we already added these regions to the set of
1089         // regions to clear the card table at the end during the prepare() phase.
1090         _cards_skipped++;
1091       }
1092     }
1093 
1094     size_t cards_dirty() const { return _cards_dirty; }
1095     size_t cards_skipped() const { return _cards_skipped; }
1096   };
1097 
1098   HeapRegionClaimer _hr_claimer;
1099   G1RemSetScanState* _scan_state;
1100   BufferNode::Stack _dirty_card_buffers;
1101   bool _initial_evacuation;
1102 
1103   volatile bool _fast_reclaim_handled;
1104 
1105   void apply_closure_to_dirty_card_buffers(G1MergeLogBufferCardsClosure* cl, uint worker_id) {
1106     G1DirtyCardQueueSet& dcqs = G1BarrierSet::dirty_card_queue_set();
1107     size_t buffer_size = dcqs.buffer_size();
1108     while (BufferNode* node = _dirty_card_buffers.pop()) {
1109       cl->apply_to_buffer(node, buffer_size, worker_id);
1110       dcqs.deallocate_buffer(node);
1111     }
1112   }
1113 
1114 public:
1115   G1MergeHeapRootsTask(G1RemSetScanState* scan_state, uint num_workers, bool initial_evacuation) :
1116     AbstractGangTask("G1 Merge Heap Roots"),
1117     _hr_claimer(num_workers),
1118     _scan_state(scan_state),
1119     _dirty_card_buffers(),
1120     _initial_evacuation(initial_evacuation),
1121     _fast_reclaim_handled(false)
1122   {
1123     if (initial_evacuation) {
1124       G1DirtyCardQueueSet& dcqs = G1BarrierSet::dirty_card_queue_set();
1125       G1BufferNodeList buffers = dcqs.take_all_completed_buffers();
1126       if (buffers._entry_count != 0) {
1127         _dirty_card_buffers.prepend(*buffers._head, *buffers._tail);
1128       }
1129     }
1130   }
1131 
1132   virtual void work(uint worker_id) {
1133     G1CollectedHeap* g1h = G1CollectedHeap::heap();
1134     G1GCPhaseTimes* p = g1h->phase_times();
1135 
1136     G1GCPhaseTimes::GCParPhases merge_remset_phase = _initial_evacuation ?
1137                                                      G1GCPhaseTimes::MergeRS :
1138                                                      G1GCPhaseTimes::OptMergeRS;
1139 
1140     // We schedule flushing the remembered sets of humongous fast reclaim candidates
1141     // onto the card table first to allow the remaining parallelized tasks hide it.
1142     if (_initial_evacuation &&
1143         p->fast_reclaim_humongous_candidates() > 0 &&
1144         !_fast_reclaim_handled &&
1145         !Atomic::cmpxchg(&_fast_reclaim_handled, false, true)) {
1146 
1147       G1GCParPhaseTimesTracker x(p, G1GCPhaseTimes::MergeER, worker_id);
1148 
1149       G1FlushHumongousCandidateRemSets cl(_scan_state);
1150       g1h->heap_region_iterate(&cl);
1151 
1152       p->record_or_add_thread_work_item(merge_remset_phase, worker_id, cl.merged_sparse(), G1GCPhaseTimes::MergeRSMergedSparse);
1153       p->record_or_add_thread_work_item(merge_remset_phase, worker_id, cl.merged_fine(), G1GCPhaseTimes::MergeRSMergedFine);
1154       p->record_or_add_thread_work_item(merge_remset_phase, worker_id, cl.merged_coarse(), G1GCPhaseTimes::MergeRSMergedCoarse);
1155       p->record_or_add_thread_work_item(merge_remset_phase, worker_id, cl.cards_dirty(), G1GCPhaseTimes::MergeRSDirtyCards);
1156     }
1157 
1158     // Merge remembered sets of current candidates.
1159     {
1160       G1GCParPhaseTimesTracker x(p, merge_remset_phase, worker_id, _initial_evacuation /* must_record */);
1161       G1MergeCardSetClosure cl(_scan_state);
1162       g1h->collection_set_iterate_increment_from(&cl, &_hr_claimer, worker_id);
1163 
1164       p->record_or_add_thread_work_item(merge_remset_phase, worker_id, cl.merged_sparse(), G1GCPhaseTimes::MergeRSMergedSparse);
1165       p->record_or_add_thread_work_item(merge_remset_phase, worker_id, cl.merged_fine(), G1GCPhaseTimes::MergeRSMergedFine);
1166       p->record_or_add_thread_work_item(merge_remset_phase, worker_id, cl.merged_coarse(), G1GCPhaseTimes::MergeRSMergedCoarse);
1167       p->record_or_add_thread_work_item(merge_remset_phase, worker_id, cl.cards_dirty(), G1GCPhaseTimes::MergeRSDirtyCards);
1168     }
1169 
1170     // Apply closure to log entries in the HCC.
1171     if (_initial_evacuation && G1HotCardCache::default_use_cache()) {
1172       assert(merge_remset_phase == G1GCPhaseTimes::MergeRS, "Wrong merge phase");
1173       G1GCParPhaseTimesTracker x(p, G1GCPhaseTimes::MergeHCC, worker_id);
1174       G1MergeLogBufferCardsClosure cl(g1h, _scan_state);
1175       g1h->iterate_hcc_closure(&cl, worker_id);
1176 
1177       p->record_thread_work_item(G1GCPhaseTimes::MergeHCC, worker_id, cl.cards_dirty(), G1GCPhaseTimes::MergeHCCDirtyCards);
1178       p->record_thread_work_item(G1GCPhaseTimes::MergeHCC, worker_id, cl.cards_skipped(), G1GCPhaseTimes::MergeHCCSkippedCards);
1179     }
1180 
1181     // Now apply the closure to all remaining log entries.
1182     if (_initial_evacuation) {
1183       assert(merge_remset_phase == G1GCPhaseTimes::MergeRS, "Wrong merge phase");
1184       G1GCParPhaseTimesTracker x(p, G1GCPhaseTimes::MergeLB, worker_id);
1185 
1186       G1MergeLogBufferCardsClosure cl(g1h, _scan_state);
1187       apply_closure_to_dirty_card_buffers(&cl, worker_id);
1188 
1189       p->record_thread_work_item(G1GCPhaseTimes::MergeLB, worker_id, cl.cards_dirty(), G1GCPhaseTimes::MergeLBDirtyCards);
1190       p->record_thread_work_item(G1GCPhaseTimes::MergeLB, worker_id, cl.cards_skipped(), G1GCPhaseTimes::MergeLBSkippedCards);
1191     }
1192   }
1193 };
1194 
1195 void G1RemSet::print_merge_heap_roots_stats() {
1196   size_t num_visited_cards = _scan_state->num_visited_cards();
1197 
1198   size_t total_dirty_region_cards = _scan_state->num_cards_in_dirty_regions();
1199 
1200   G1CollectedHeap* g1h = G1CollectedHeap::heap();
1201   size_t total_old_region_cards =
1202     (g1h->num_regions() - (g1h->num_free_regions() - g1h->collection_set()->cur_length())) * HeapRegion::CardsPerRegion;
1203 
1204   log_debug(gc,remset)("Visited cards " SIZE_FORMAT " Total dirty " SIZE_FORMAT " (%.2lf%%) Total old " SIZE_FORMAT " (%.2lf%%)",
1205                        num_visited_cards,
1206                        total_dirty_region_cards,
1207                        percent_of(num_visited_cards, total_dirty_region_cards),
1208                        total_old_region_cards,
1209                        percent_of(num_visited_cards, total_old_region_cards));
1210 }
1211 
1212 void G1RemSet::merge_heap_roots(bool initial_evacuation) {
1213   G1CollectedHeap* g1h = G1CollectedHeap::heap();
1214 
1215   {
1216     Ticks start = Ticks::now();
1217 
1218     _scan_state->prepare_for_merge_heap_roots();
1219 
1220     Tickspan total = Ticks::now() - start;
1221     if (initial_evacuation) {
1222       g1h->phase_times()->record_prepare_merge_heap_roots_time(total.seconds() * 1000.0);
1223     } else {
1224       g1h->phase_times()->record_or_add_optional_prepare_merge_heap_roots_time(total.seconds() * 1000.0);
1225     }
1226   }
1227 
1228   WorkGang* workers = g1h->workers();
1229   size_t const increment_length = g1h->collection_set()->increment_length();
1230 
1231   uint const num_workers = initial_evacuation ? workers->active_workers() :
1232                                                 MIN2(workers->active_workers(), (uint)increment_length);
1233 
1234   {
1235     G1MergeHeapRootsTask cl(_scan_state, num_workers, initial_evacuation);
1236     log_debug(gc, ergo)("Running %s using %u workers for " SIZE_FORMAT " regions",
1237                         cl.name(), num_workers, increment_length);
1238     workers->run_task(&cl, num_workers);
1239   }
1240 
1241   if (log_is_enabled(Debug, gc, remset)) {
1242     print_merge_heap_roots_stats();
1243   }
1244 }
1245 
1246 void G1RemSet::exclude_region_from_scan(uint region_idx) {
1247   _scan_state->clear_scan_top(region_idx);
1248 }
1249 
1250 void G1RemSet::cleanup_after_scan_heap_roots() {
1251   G1GCPhaseTimes* phase_times = _g1h->phase_times();
1252 
1253   // Set all cards back to clean.
1254   double start = os::elapsedTime();
1255   _scan_state->cleanup(_g1h->workers());
1256   phase_times->record_clear_ct_time((os::elapsedTime() - start) * 1000.0);
1257 }
1258 
1259 inline void check_card_ptr(CardTable::CardValue* card_ptr, G1CardTable* ct) {
1260 #ifdef ASSERT
1261   G1CollectedHeap* g1h = G1CollectedHeap::heap();
1262   assert(g1h->is_in_exact(ct->addr_for(card_ptr)),
1263          "Card at " PTR_FORMAT " index " SIZE_FORMAT " representing heap at " PTR_FORMAT " (%u) must be in committed heap",
1264          p2i(card_ptr),
1265          ct->index_for(ct->addr_for(card_ptr)),
1266          p2i(ct->addr_for(card_ptr)),
1267          g1h->addr_to_region(ct->addr_for(card_ptr)));
1268 #endif
1269 }
1270 
1271 bool G1RemSet::clean_card_before_refine(CardValue** const card_ptr_addr) {
1272   assert(!_g1h->is_gc_active(), "Only call concurrently");
1273 
1274   CardValue* card_ptr = *card_ptr_addr;
1275   // Find the start address represented by the card.
1276   HeapWord* start = _ct->addr_for(card_ptr);
1277   // And find the region containing it.
1278   HeapRegion* r = _g1h->heap_region_containing_or_null(start);
1279 
1280   // If this is a (stale) card into an uncommitted region, exit.
1281   if (r == NULL) {
1282     return false;
1283   }
1284 
1285   check_card_ptr(card_ptr, _ct);
1286 
1287   // If the card is no longer dirty, nothing to do.
1288   // We cannot load the card value before the "r == NULL" check, because G1
1289   // could uncommit parts of the card table covering uncommitted regions.
1290   if (*card_ptr != G1CardTable::dirty_card_val()) {
1291     return false;
1292   }
1293 
1294   // This check is needed for some uncommon cases where we should
1295   // ignore the card.
1296   //
1297   // The region could be young.  Cards for young regions are
1298   // distinctly marked (set to g1_young_gen), so the post-barrier will
1299   // filter them out.  However, that marking is performed
1300   // concurrently.  A write to a young object could occur before the
1301   // card has been marked young, slipping past the filter.
1302   //
1303   // The card could be stale, because the region has been freed since
1304   // the card was recorded. In this case the region type could be
1305   // anything.  If (still) free or (reallocated) young, just ignore
1306   // it.  If (reallocated) old or humongous, the later card trimming
1307   // and additional checks in iteration may detect staleness.  At
1308   // worst, we end up processing a stale card unnecessarily.
1309   //
1310   // In the normal (non-stale) case, the synchronization between the
1311   // enqueueing of the card and processing it here will have ensured
1312   // we see the up-to-date region type here.
1313   if (!r->is_old_or_humongous_or_archive()) {
1314     return false;
1315   }
1316 
1317   // The result from the hot card cache insert call is either:
1318   //   * pointer to the current card
1319   //     (implying that the current card is not 'hot'),
1320   //   * null
1321   //     (meaning we had inserted the card ptr into the "hot" card cache,
1322   //     which had some headroom),
1323   //   * a pointer to a "hot" card that was evicted from the "hot" cache.
1324   //
1325 
1326   if (_hot_card_cache->use_cache()) {
1327     assert(!SafepointSynchronize::is_at_safepoint(), "sanity");
1328 
1329     const CardValue* orig_card_ptr = card_ptr;
1330     card_ptr = _hot_card_cache->insert(card_ptr);
1331     if (card_ptr == NULL) {
1332       // There was no eviction. Nothing to do.
1333       return false;
1334     } else if (card_ptr != orig_card_ptr) {
1335       // Original card was inserted and an old card was evicted.
1336       start = _ct->addr_for(card_ptr);
1337       r = _g1h->heap_region_containing(start);
1338 
1339       // Check whether the region formerly in the cache should be
1340       // ignored, as discussed earlier for the original card.  The
1341       // region could have been freed while in the cache.
1342       if (!r->is_old_or_humongous_or_archive()) {
1343         return false;
1344       }
1345       *card_ptr_addr = card_ptr;
1346     } // Else we still have the original card.
1347   }
1348 
1349   // Trim the region designated by the card to what's been allocated
1350   // in the region.  The card could be stale, or the card could cover
1351   // (part of) an object at the end of the allocated space and extend
1352   // beyond the end of allocation.
1353 
1354   // Non-humongous objects are either allocated in the old regions during GC,
1355   // or mapped in archive regions during startup. So if region is old or
1356   // archive then top is stable.
1357   // Humongous object allocation sets top last; if top has not yet been set,
1358   // this is a stale card and we'll end up with an empty intersection.
1359   // If this is not a stale card, the synchronization between the
1360   // enqueuing of the card and processing it here will have ensured
1361   // we see the up-to-date top here.
1362   HeapWord* scan_limit = r->top();
1363 
1364   if (scan_limit <= start) {
1365     // If the trimmed region is empty, the card must be stale.
1366     return false;
1367   }
1368 
1369   // Okay to clean and process the card now.  There are still some
1370   // stale card cases that may be detected by iteration and dealt with
1371   // as iteration failure.
1372   *const_cast<volatile CardValue*>(card_ptr) = G1CardTable::clean_card_val();
1373 
1374   return true;
1375 }
1376 
1377 void G1RemSet::refine_card_concurrently(CardValue* const card_ptr,
1378                                         const uint worker_id) {
1379   assert(!_g1h->is_gc_active(), "Only call concurrently");
1380   check_card_ptr(card_ptr, _ct);
1381 
1382   // Construct the MemRegion representing the card.
1383   HeapWord* start = _ct->addr_for(card_ptr);
1384   // And find the region containing it.
1385   HeapRegion* r = _g1h->heap_region_containing(start);
1386   // This reload of the top is safe even though it happens after the full
1387   // fence, because top is stable for old, archive and unfiltered humongous
1388   // regions, so it must return the same value as the previous load when
1389   // cleaning the card. Also cleaning the card and refinement of the card
1390   // cannot span across safepoint, so we don't need to worry about top being
1391   // changed during safepoint.
1392   HeapWord* scan_limit = r->top();
1393   assert(scan_limit > start, "sanity");
1394 
1395   // Don't use addr_for(card_ptr + 1) which can ask for
1396   // a card beyond the heap.
1397   HeapWord* end = start + G1CardTable::card_size_in_words;
1398   MemRegion dirty_region(start, MIN2(scan_limit, end));
1399   assert(!dirty_region.is_empty(), "sanity");
1400 
1401   G1ConcurrentRefineOopClosure conc_refine_cl(_g1h, worker_id);
1402   if (r->oops_on_memregion_seq_iterate_careful<false>(dirty_region, &conc_refine_cl) != NULL) {
1403     return;
1404   }
1405 
1406   // If unable to process the card then we encountered an unparsable
1407   // part of the heap (e.g. a partially allocated object, so only
1408   // temporarily a problem) while processing a stale card.  Despite
1409   // the card being stale, we can't simply ignore it, because we've
1410   // already marked the card cleaned, so taken responsibility for
1411   // ensuring the card gets scanned.
1412   //
1413   // However, the card might have gotten re-dirtied and re-enqueued
1414   // while we worked.  (In fact, it's pretty likely.)
1415   if (*card_ptr == G1CardTable::dirty_card_val()) {
1416     return;
1417   }
1418 
1419   // Re-dirty the card and enqueue in the *shared* queue.  Can't use
1420   // the thread-local queue, because that might be the queue that is
1421   // being processed by us; we could be a Java thread conscripted to
1422   // perform refinement on our queue's current buffer.
1423   *card_ptr = G1CardTable::dirty_card_val();
1424   G1BarrierSet::shared_dirty_card_queue().enqueue(card_ptr);
1425 }
1426 
1427 void G1RemSet::print_periodic_summary_info(const char* header, uint period_count) {
1428   if ((G1SummarizeRSetStatsPeriod > 0) && log_is_enabled(Trace, gc, remset) &&
1429       (period_count % G1SummarizeRSetStatsPeriod == 0)) {
1430 
1431     G1RemSetSummary current;
1432     _prev_period_summary.subtract_from(&current);
1433 
1434     Log(gc, remset) log;
1435     log.trace("%s", header);
1436     ResourceMark rm;
1437     LogStream ls(log.trace());
1438     _prev_period_summary.print_on(&ls);
1439 
1440     _prev_period_summary.set(&current);
1441   }
1442 }
1443 
1444 void G1RemSet::print_summary_info() {
1445   Log(gc, remset, exit) log;
1446   if (log.is_trace()) {
1447     log.trace(" Cumulative RS summary");
1448     G1RemSetSummary current;
1449     ResourceMark rm;
1450     LogStream ls(log.trace());
1451     current.print_on(&ls);
1452   }
1453 }
1454 
1455 class G1RebuildRemSetTask: public AbstractGangTask {
1456   // Aggregate the counting data that was constructed concurrently
1457   // with marking.
1458   class G1RebuildRemSetHeapRegionClosure : public HeapRegionClosure {
1459     G1ConcurrentMark* _cm;
1460     G1RebuildRemSetClosure _update_cl;
1461 
1462     // Applies _update_cl to the references of the given object, limiting objArrays
1463     // to the given MemRegion. Returns the amount of words actually scanned.
1464     size_t scan_for_references(oop const obj, MemRegion mr) {
1465       size_t const obj_size = obj->size();
1466       // All non-objArrays and objArrays completely within the mr
1467       // can be scanned without passing the mr.
1468       if (!obj->is_objArray() || mr.contains(MemRegion(cast_from_oop<HeapWord*>(obj), obj_size))) {
1469         obj->oop_iterate(&_update_cl);
1470         return obj_size;
1471       }
1472       // This path is for objArrays crossing the given MemRegion. Only scan the
1473       // area within the MemRegion.
1474       obj->oop_iterate(&_update_cl, mr);
1475       return mr.intersection(MemRegion(cast_from_oop<HeapWord*>(obj), obj_size)).word_size();
1476     }
1477 
1478     // A humongous object is live (with respect to the scanning) either
1479     // a) it is marked on the bitmap as such
1480     // b) its TARS is larger than TAMS, i.e. has been allocated during marking.
1481     bool is_humongous_live(oop const humongous_obj, const G1CMBitMap* const bitmap, HeapWord* tams, HeapWord* tars) const {
1482       return bitmap->is_marked(humongous_obj) || (tars > tams);
1483     }
1484 
1485     // Iterator over the live objects within the given MemRegion.
1486     class LiveObjIterator : public StackObj {
1487       const G1CMBitMap* const _bitmap;
1488       const HeapWord* _tams;
1489       const MemRegion _mr;
1490       HeapWord* _current;
1491 
1492       bool is_below_tams() const {
1493         return _current < _tams;
1494       }
1495 
1496       bool is_live(HeapWord* obj) const {
1497         return !is_below_tams() || _bitmap->is_marked(obj);
1498       }
1499 
1500       HeapWord* bitmap_limit() const {
1501         return MIN2(const_cast<HeapWord*>(_tams), _mr.end());
1502       }
1503 
1504       void move_if_below_tams() {
1505         if (is_below_tams() && has_next()) {
1506           _current = _bitmap->get_next_marked_addr(_current, bitmap_limit());
1507         }
1508       }
1509     public:
1510       LiveObjIterator(const G1CMBitMap* const bitmap, const HeapWord* tams, const MemRegion mr, HeapWord* first_oop_into_mr) :
1511           _bitmap(bitmap),
1512           _tams(tams),
1513           _mr(mr),
1514           _current(first_oop_into_mr) {
1515 
1516         assert(_current <= _mr.start(),
1517                "First oop " PTR_FORMAT " should extend into mr [" PTR_FORMAT ", " PTR_FORMAT ")",
1518                p2i(first_oop_into_mr), p2i(mr.start()), p2i(mr.end()));
1519 
1520         // Step to the next live object within the MemRegion if needed.
1521         if (is_live(_current)) {
1522           // Non-objArrays were scanned by the previous part of that region.
1523           if (_current < mr.start() && !oop(_current)->is_objArray()) {
1524             _current += oop(_current)->size();
1525             // We might have positioned _current on a non-live object. Reposition to the next
1526             // live one if needed.
1527             move_if_below_tams();
1528           }
1529         } else {
1530           // The object at _current can only be dead if below TAMS, so we can use the bitmap.
1531           // immediately.
1532           _current = _bitmap->get_next_marked_addr(_current, bitmap_limit());
1533           assert(_current == _mr.end() || is_live(_current),
1534                  "Current " PTR_FORMAT " should be live (%s) or beyond the end of the MemRegion (" PTR_FORMAT ")",
1535                  p2i(_current), BOOL_TO_STR(is_live(_current)), p2i(_mr.end()));
1536         }
1537       }
1538 
1539       void move_to_next() {
1540         _current += next()->size();
1541         move_if_below_tams();
1542       }
1543 
1544       oop next() const {
1545         oop result = oop(_current);
1546         assert(is_live(_current),
1547                "Object " PTR_FORMAT " must be live TAMS " PTR_FORMAT " below %d mr " PTR_FORMAT " " PTR_FORMAT " outside %d",
1548                p2i(_current), p2i(_tams), _tams > _current, p2i(_mr.start()), p2i(_mr.end()), _mr.contains(result));
1549         return result;
1550       }
1551 
1552       bool has_next() const {
1553         return _current < _mr.end();
1554       }
1555     };
1556 
1557     // Rebuild remembered sets in the part of the region specified by mr and hr.
1558     // Objects between the bottom of the region and the TAMS are checked for liveness
1559     // using the given bitmap. Objects between TAMS and TARS are assumed to be live.
1560     // Returns the number of live words between bottom and TAMS.
1561     size_t rebuild_rem_set_in_region(const G1CMBitMap* const bitmap,
1562                                      HeapWord* const top_at_mark_start,
1563                                      HeapWord* const top_at_rebuild_start,
1564                                      HeapRegion* hr,
1565                                      MemRegion mr) {
1566       size_t marked_words = 0;
1567 
1568       if (hr->is_humongous()) {
1569         oop const humongous_obj = oop(hr->humongous_start_region()->bottom());
1570         if (is_humongous_live(humongous_obj, bitmap, top_at_mark_start, top_at_rebuild_start)) {
1571           // We need to scan both [bottom, TAMS) and [TAMS, top_at_rebuild_start);
1572           // however in case of humongous objects it is sufficient to scan the encompassing
1573           // area (top_at_rebuild_start is always larger or equal to TAMS) as one of the
1574           // two areas will be zero sized. I.e. TAMS is either
1575           // the same as bottom or top(_at_rebuild_start). There is no way TAMS has a different
1576           // value: this would mean that TAMS points somewhere into the object.
1577           assert(hr->top() == top_at_mark_start || hr->top() == top_at_rebuild_start,
1578                  "More than one object in the humongous region?");
1579           humongous_obj->oop_iterate(&_update_cl, mr);
1580           return top_at_mark_start != hr->bottom() ? mr.intersection(MemRegion(cast_from_oop<HeapWord*>(humongous_obj), humongous_obj->size())).byte_size() : 0;
1581         } else {
1582           return 0;
1583         }
1584       }
1585 
1586       for (LiveObjIterator it(bitmap, top_at_mark_start, mr, hr->block_start(mr.start())); it.has_next(); it.move_to_next()) {
1587         oop obj = it.next();
1588         size_t scanned_size = scan_for_references(obj, mr);
1589         if (cast_from_oop<HeapWord*>(obj) < top_at_mark_start) {
1590           marked_words += scanned_size;
1591         }
1592       }
1593 
1594       return marked_words * HeapWordSize;
1595     }
1596 public:
1597   G1RebuildRemSetHeapRegionClosure(G1CollectedHeap* g1h,
1598                                    G1ConcurrentMark* cm,
1599                                    uint worker_id) :
1600     HeapRegionClosure(),
1601     _cm(cm),
1602     _update_cl(g1h, worker_id) { }
1603 
1604     bool do_heap_region(HeapRegion* hr) {
1605       if (_cm->has_aborted()) {
1606         return true;
1607       }
1608 
1609       uint const region_idx = hr->hrm_index();
1610       DEBUG_ONLY(HeapWord* const top_at_rebuild_start_check = _cm->top_at_rebuild_start(region_idx);)
1611       assert(top_at_rebuild_start_check == NULL ||
1612              top_at_rebuild_start_check > hr->bottom(),
1613              "A TARS (" PTR_FORMAT ") == bottom() (" PTR_FORMAT ") indicates the old region %u is empty (%s)",
1614              p2i(top_at_rebuild_start_check), p2i(hr->bottom()),  region_idx, hr->get_type_str());
1615 
1616       size_t total_marked_bytes = 0;
1617       size_t const chunk_size_in_words = G1RebuildRemSetChunkSize / HeapWordSize;
1618 
1619       HeapWord* const top_at_mark_start = hr->prev_top_at_mark_start();
1620 
1621       HeapWord* cur = hr->bottom();
1622       while (cur < hr->end()) {
1623         // After every iteration (yield point) we need to check whether the region's
1624         // TARS changed due to e.g. eager reclaim.
1625         HeapWord* const top_at_rebuild_start = _cm->top_at_rebuild_start(region_idx);
1626         if (top_at_rebuild_start == NULL) {
1627           return false;
1628         }
1629 
1630         MemRegion next_chunk = MemRegion(hr->bottom(), top_at_rebuild_start).intersection(MemRegion(cur, chunk_size_in_words));
1631         if (next_chunk.is_empty()) {
1632           break;
1633         }
1634 
1635         const Ticks start = Ticks::now();
1636         size_t marked_bytes = rebuild_rem_set_in_region(_cm->prev_mark_bitmap(),
1637                                                         top_at_mark_start,
1638                                                         top_at_rebuild_start,
1639                                                         hr,
1640                                                         next_chunk);
1641         Tickspan time = Ticks::now() - start;
1642 
1643         log_trace(gc, remset, tracking)("Rebuilt region %u "
1644                                         "live " SIZE_FORMAT " "
1645                                         "time %.3fms "
1646                                         "marked bytes " SIZE_FORMAT " "
1647                                         "bot " PTR_FORMAT " "
1648                                         "TAMS " PTR_FORMAT " "
1649                                         "TARS " PTR_FORMAT,
1650                                         region_idx,
1651                                         _cm->liveness(region_idx) * HeapWordSize,
1652                                         time.seconds() * 1000.0,
1653                                         marked_bytes,
1654                                         p2i(hr->bottom()),
1655                                         p2i(top_at_mark_start),
1656                                         p2i(top_at_rebuild_start));
1657 
1658         if (marked_bytes > 0) {
1659           total_marked_bytes += marked_bytes;
1660         }
1661         cur += chunk_size_in_words;
1662 
1663         _cm->do_yield_check();
1664         if (_cm->has_aborted()) {
1665           return true;
1666         }
1667       }
1668       // In the final iteration of the loop the region might have been eagerly reclaimed.
1669       // Simply filter out those regions. We can not just use region type because there
1670       // might have already been new allocations into these regions.
1671       DEBUG_ONLY(HeapWord* const top_at_rebuild_start = _cm->top_at_rebuild_start(region_idx);)
1672       assert(top_at_rebuild_start == NULL ||
1673              total_marked_bytes == hr->marked_bytes(),
1674              "Marked bytes " SIZE_FORMAT " for region %u (%s) in [bottom, TAMS) do not match calculated marked bytes " SIZE_FORMAT " "
1675              "(" PTR_FORMAT " " PTR_FORMAT " " PTR_FORMAT ")",
1676              total_marked_bytes, hr->hrm_index(), hr->get_type_str(), hr->marked_bytes(),
1677              p2i(hr->bottom()), p2i(top_at_mark_start), p2i(top_at_rebuild_start));
1678        // Abort state may have changed after the yield check.
1679       return _cm->has_aborted();
1680     }
1681   };
1682 
1683   HeapRegionClaimer _hr_claimer;
1684   G1ConcurrentMark* _cm;
1685 
1686   uint _worker_id_offset;
1687 public:
1688   G1RebuildRemSetTask(G1ConcurrentMark* cm,
1689                       uint n_workers,
1690                       uint worker_id_offset) :
1691       AbstractGangTask("G1 Rebuild Remembered Set"),
1692       _hr_claimer(n_workers),
1693       _cm(cm),
1694       _worker_id_offset(worker_id_offset) {
1695   }
1696 
1697   void work(uint worker_id) {
1698     SuspendibleThreadSetJoiner sts_join;
1699 
1700     G1CollectedHeap* g1h = G1CollectedHeap::heap();
1701 
1702     G1RebuildRemSetHeapRegionClosure cl(g1h, _cm, _worker_id_offset + worker_id);
1703     g1h->heap_region_par_iterate_from_worker_offset(&cl, &_hr_claimer, worker_id);
1704   }
1705 };
1706 
1707 void G1RemSet::rebuild_rem_set(G1ConcurrentMark* cm,
1708                                WorkGang* workers,
1709                                uint worker_id_offset) {
1710   uint num_workers = workers->active_workers();
1711 
1712   G1RebuildRemSetTask cl(cm,
1713                          num_workers,
1714                          worker_id_offset);
1715   workers->run_task(&cl, num_workers);
1716 }