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