1 /*
   2  * Copyright (c) 2001, 2017, 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/concurrentG1Refine.hpp"
  27 #include "gc/g1/dirtyCardQueue.hpp"
  28 #include "gc/g1/g1BlockOffsetTable.inline.hpp"
  29 #include "gc/g1/g1CollectedHeap.inline.hpp"
  30 #include "gc/g1/g1FromCardCache.hpp"
  31 #include "gc/g1/g1GCPhaseTimes.hpp"
  32 #include "gc/g1/g1HotCardCache.hpp"
  33 #include "gc/g1/g1OopClosures.inline.hpp"
  34 #include "gc/g1/g1RemSet.inline.hpp"
  35 #include "gc/g1/g1SATBCardTableModRefBS.inline.hpp"
  36 #include "gc/g1/heapRegion.inline.hpp"
  37 #include "gc/g1/heapRegionManager.inline.hpp"
  38 #include "gc/g1/heapRegionRemSet.hpp"
  39 #include "gc/shared/gcTraceTime.inline.hpp"
  40 #include "memory/iterator.hpp"
  41 #include "memory/resourceArea.hpp"
  42 #include "oops/oop.inline.hpp"
  43 #include "utilities/globalDefinitions.hpp"
  44 #include "utilities/intHisto.hpp"
  45 #include "utilities/stack.inline.hpp"
  46 
  47 // Collects information about the overall remembered set scan progress during an evacuation.
  48 class G1RemSetScanState : public CHeapObj<mtGC> {
  49 private:
  50   class G1ClearCardTableTask : public AbstractGangTask {
  51     G1CollectedHeap* _g1h;
  52     uint* _dirty_region_list;
  53     size_t _num_dirty_regions;
  54     size_t _chunk_length;
  55 
  56     size_t volatile _cur_dirty_regions;
  57   public:
  58     G1ClearCardTableTask(G1CollectedHeap* g1h,
  59                          uint* dirty_region_list,
  60                          size_t num_dirty_regions,
  61                          size_t chunk_length) :
  62       AbstractGangTask("G1 Clear Card Table Task"),
  63       _g1h(g1h),
  64       _dirty_region_list(dirty_region_list),
  65       _num_dirty_regions(num_dirty_regions),
  66       _chunk_length(chunk_length),
  67       _cur_dirty_regions(0) {
  68 
  69       assert(chunk_length > 0, "must be");
  70     }
  71 
  72     static size_t chunk_size() { return M; }
  73 
  74     void work(uint worker_id) {
  75       G1SATBCardTableModRefBS* ct_bs = _g1h->g1_barrier_set();
  76 
  77       while (_cur_dirty_regions < _num_dirty_regions) {
  78         size_t next = Atomic::add(_chunk_length, &_cur_dirty_regions) - _chunk_length;
  79         size_t max = MIN2(next + _chunk_length, _num_dirty_regions);
  80 
  81         for (size_t i = next; i < max; i++) {
  82           HeapRegion* r = _g1h->region_at(_dirty_region_list[i]);
  83           if (!r->is_survivor()) {
  84             ct_bs->clear(MemRegion(r->bottom(), r->end()));
  85           }
  86         }
  87       }
  88     }
  89   };
  90 
  91   size_t _max_regions;
  92 
  93   // Scan progress for the remembered set of a single region. Transitions from
  94   // Unclaimed -> Claimed -> Complete.
  95   // At each of the transitions the thread that does the transition needs to perform
  96   // some special action once. This is the reason for the extra "Claimed" state.
  97   typedef jint G1RemsetIterState;
  98 
  99   static const G1RemsetIterState Unclaimed = 0; // The remembered set has not been scanned yet.
 100   static const G1RemsetIterState Claimed = 1;   // The remembered set is currently being scanned.
 101   static const G1RemsetIterState Complete = 2;  // The remembered set has been completely scanned.
 102 
 103   G1RemsetIterState volatile* _iter_states;
 104   // The current location where the next thread should continue scanning in a region's
 105   // remembered set.
 106   size_t volatile* _iter_claims;
 107 
 108   // Temporary buffer holding the regions we used to store remembered set scan duplicate
 109   // information. These are also called "dirty". Valid entries are from [0.._cur_dirty_region)
 110   uint* _dirty_region_buffer;
 111 
 112   typedef jbyte IsDirtyRegionState;
 113   static const IsDirtyRegionState Clean = 0;
 114   static const IsDirtyRegionState Dirty = 1;
 115   // Holds a flag for every region whether it is in the _dirty_region_buffer already
 116   // to avoid duplicates. Uses jbyte since there are no atomic instructions for bools.
 117   IsDirtyRegionState* _in_dirty_region_buffer;
 118   size_t _cur_dirty_region;
 119 
 120   // Creates a snapshot of the current _top values at the start of collection to
 121   // filter out card marks that we do not want to scan.
 122   class G1ResetScanTopClosure : public HeapRegionClosure {
 123   private:
 124     HeapWord** _scan_top;
 125   public:
 126     G1ResetScanTopClosure(HeapWord** scan_top) : _scan_top(scan_top) { }
 127 
 128     virtual bool doHeapRegion(HeapRegion* r) {
 129       uint hrm_index = r->hrm_index();
 130       if (!r->in_collection_set() && r->is_old_or_humongous()) {
 131         _scan_top[hrm_index] = r->top();
 132       } else {
 133         _scan_top[hrm_index] = r->bottom();
 134       }
 135       return false;
 136     }
 137   };
 138 
 139   // For each region, contains the maximum top() value to be used during this garbage
 140   // collection. Subsumes common checks like filtering out everything but old and
 141   // humongous regions outside the collection set.
 142   // This is valid because we are not interested in scanning stray remembered set
 143   // entries from free or archive regions.
 144   HeapWord** _scan_top;
 145 public:
 146   G1RemSetScanState() :
 147     _max_regions(0),
 148     _iter_states(NULL),
 149     _iter_claims(NULL),
 150     _dirty_region_buffer(NULL),
 151     _in_dirty_region_buffer(NULL),
 152     _cur_dirty_region(0),
 153     _scan_top(NULL) {
 154   }
 155 
 156   ~G1RemSetScanState() {
 157     if (_iter_states != NULL) {
 158       FREE_C_HEAP_ARRAY(G1RemsetIterState, _iter_states);
 159     }
 160     if (_iter_claims != NULL) {
 161       FREE_C_HEAP_ARRAY(size_t, _iter_claims);
 162     }
 163     if (_dirty_region_buffer != NULL) {
 164       FREE_C_HEAP_ARRAY(uint, _dirty_region_buffer);
 165     }
 166     if (_in_dirty_region_buffer != NULL) {
 167       FREE_C_HEAP_ARRAY(IsDirtyRegionState, _in_dirty_region_buffer);
 168     }
 169     if (_scan_top != NULL) {
 170       FREE_C_HEAP_ARRAY(HeapWord*, _scan_top);
 171     }
 172   }
 173 
 174   void initialize(uint max_regions) {
 175     assert(_iter_states == NULL, "Must not be initialized twice");
 176     assert(_iter_claims == NULL, "Must not be initialized twice");
 177     _max_regions = max_regions;
 178     _iter_states = NEW_C_HEAP_ARRAY(G1RemsetIterState, max_regions, mtGC);
 179     _iter_claims = NEW_C_HEAP_ARRAY(size_t, max_regions, mtGC);
 180     _dirty_region_buffer = NEW_C_HEAP_ARRAY(uint, max_regions, mtGC);
 181     _in_dirty_region_buffer = NEW_C_HEAP_ARRAY(IsDirtyRegionState, max_regions, mtGC);
 182     _scan_top = NEW_C_HEAP_ARRAY(HeapWord*, max_regions, mtGC);
 183   }
 184 
 185   void reset() {
 186     for (uint i = 0; i < _max_regions; i++) {
 187       _iter_states[i] = Unclaimed;
 188     }
 189 
 190     memset(_scan_top, 0, _max_regions * sizeof(HeapWord*));
 191     G1ResetScanTopClosure cl(_scan_top);
 192     G1CollectedHeap::heap()->heap_region_iterate(&cl);
 193 
 194     memset((void*)_iter_claims, 0, _max_regions * sizeof(size_t));
 195     memset(_in_dirty_region_buffer, Clean, _max_regions * sizeof(IsDirtyRegionState));
 196     _cur_dirty_region = 0;
 197   }
 198 
 199   // Attempt to claim the remembered set of the region for iteration. Returns true
 200   // if this call caused the transition from Unclaimed to Claimed.
 201   inline bool claim_iter(uint region) {
 202     assert(region < _max_regions, "Tried to access invalid region %u", region);
 203     if (_iter_states[region] != Unclaimed) {
 204       return false;
 205     }
 206     jint res = Atomic::cmpxchg(Claimed, (jint*)(&_iter_states[region]), Unclaimed);
 207     return (res == Unclaimed);
 208   }
 209 
 210   // Try to atomically sets the iteration state to "complete". Returns true for the
 211   // thread that caused the transition.
 212   inline bool set_iter_complete(uint region) {
 213     if (iter_is_complete(region)) {
 214       return false;
 215     }
 216     jint res = Atomic::cmpxchg(Complete, (jint*)(&_iter_states[region]), Claimed);
 217     return (res == Claimed);
 218   }
 219 
 220   // Returns true if the region's iteration is complete.
 221   inline bool iter_is_complete(uint region) const {
 222     assert(region < _max_regions, "Tried to access invalid region %u", region);
 223     return _iter_states[region] == Complete;
 224   }
 225 
 226   // The current position within the remembered set of the given region.
 227   inline size_t iter_claimed(uint region) const {
 228     assert(region < _max_regions, "Tried to access invalid region %u", region);
 229     return _iter_claims[region];
 230   }
 231 
 232   // Claim the next block of cards within the remembered set of the region with
 233   // step size.
 234   inline size_t iter_claimed_next(uint region, size_t step) {
 235     return Atomic::add(step, &_iter_claims[region]) - step;
 236   }
 237 
 238   void add_dirty_region(uint region) {
 239     if (_in_dirty_region_buffer[region] == Dirty) {
 240       return;
 241     }
 242 
 243     bool marked_as_dirty = Atomic::cmpxchg(Dirty, &_in_dirty_region_buffer[region], Clean) == Clean;
 244     if (marked_as_dirty) {
 245       size_t allocated = Atomic::add(1, &_cur_dirty_region) - 1;
 246       _dirty_region_buffer[allocated] = region;
 247     }
 248   }
 249 
 250   HeapWord* scan_top(uint region_idx) const {
 251     return _scan_top[region_idx];
 252   }
 253 
 254   // Clear the card table of "dirty" regions.
 255   void clear_card_table(WorkGang* workers) {
 256     if (_cur_dirty_region == 0) {
 257       return;
 258     }
 259 
 260     size_t const num_chunks = align_size_up(_cur_dirty_region * HeapRegion::CardsPerRegion, G1ClearCardTableTask::chunk_size()) / G1ClearCardTableTask::chunk_size();
 261     uint const num_workers = (uint)MIN2(num_chunks, (size_t)workers->active_workers());
 262     size_t const chunk_length = G1ClearCardTableTask::chunk_size() / HeapRegion::CardsPerRegion;
 263 
 264     // Iterate over the dirty cards region list.
 265     G1ClearCardTableTask cl(G1CollectedHeap::heap(), _dirty_region_buffer, _cur_dirty_region, chunk_length);
 266 
 267     log_debug(gc, ergo)("Running %s using %u workers for " SIZE_FORMAT " "
 268                         "units of work for " SIZE_FORMAT " regions.",
 269                         cl.name(), num_workers, num_chunks, _cur_dirty_region);
 270     workers->run_task(&cl, num_workers);
 271 
 272 #ifndef PRODUCT
 273     // Need to synchronize with concurrent cleanup since it needs to
 274     // finish its card table clearing before we can verify.
 275     G1CollectedHeap::heap()->wait_while_free_regions_coming();
 276     G1CollectedHeap::heap()->verifier()->verify_card_table_cleanup();
 277 #endif
 278   }
 279 };
 280 
 281 G1RemSet::G1RemSet(G1CollectedHeap* g1,
 282                    CardTableModRefBS* ct_bs,
 283                    G1HotCardCache* hot_card_cache) :
 284   _g1(g1),
 285   _scan_state(new G1RemSetScanState()),
 286   _conc_refine_cards(0),
 287   _ct_bs(ct_bs),
 288   _g1p(_g1->g1_policy()),
 289   _hot_card_cache(hot_card_cache),
 290   _prev_period_summary(),
 291   _into_cset_dirty_card_queue_set(false)
 292 {
 293   if (log_is_enabled(Trace, gc, remset)) {
 294     _prev_period_summary.initialize(this);
 295   }
 296   // Initialize the card queue set used to hold cards containing
 297   // references into the collection set.
 298   _into_cset_dirty_card_queue_set.initialize(NULL, // Should never be called by the Java code
 299                                              DirtyCardQ_CBL_mon,
 300                                              DirtyCardQ_FL_lock,
 301                                              -1, // never trigger processing
 302                                              -1, // no limit on length
 303                                              Shared_DirtyCardQ_lock,
 304                                              &JavaThread::dirty_card_queue_set());
 305 }
 306 
 307 G1RemSet::~G1RemSet() {
 308   if (_scan_state != NULL) {
 309     delete _scan_state;
 310   }
 311 }
 312 
 313 uint G1RemSet::num_par_rem_sets() {
 314   return MAX2(DirtyCardQueueSet::num_par_ids() + ConcurrentG1Refine::thread_num(), ParallelGCThreads);
 315 }
 316 
 317 void G1RemSet::initialize(size_t capacity, uint max_regions) {
 318   G1FromCardCache::initialize(num_par_rem_sets(), max_regions);
 319   _scan_state->initialize(max_regions);
 320   {
 321     GCTraceTime(Debug, gc, marking)("Initialize Card Live Data");
 322     _card_live_data.initialize(capacity, max_regions);
 323   }
 324   if (G1PretouchAuxiliaryMemory) {
 325     GCTraceTime(Debug, gc, marking)("Pre-Touch Card Live Data");
 326     _card_live_data.pretouch();
 327   }
 328 }
 329 
 330 G1ScanRSClosure::G1ScanRSClosure(G1RemSetScanState* scan_state,
 331                                  G1ParPushHeapRSClosure* push_heap_cl,
 332                                  CodeBlobClosure* code_root_cl,
 333                                  uint worker_i) :
 334   _scan_state(scan_state),
 335   _push_heap_cl(push_heap_cl),
 336   _code_root_cl(code_root_cl),
 337   _strong_code_root_scan_time_sec(0.0),
 338   _cards_claimed(0),
 339   _cards_scanned(0),
 340   _cards_skipped(0),
 341   _worker_i(worker_i) {
 342   _g1h = G1CollectedHeap::heap();
 343   _bot = _g1h->bot();
 344   _ct_bs = _g1h->g1_barrier_set();
 345   _block_size = MAX2<size_t>(G1RSetScanBlockSize, 1);
 346 }
 347 
 348 void G1ScanRSClosure::scan_card(size_t index, HeapWord* card_start, HeapRegion *r) {
 349   MemRegion card_region(card_start, BOTConstants::N_words);
 350   MemRegion pre_gc_allocated(r->bottom(), _scan_state->scan_top(r->hrm_index()));
 351   MemRegion mr = pre_gc_allocated.intersection(card_region);
 352   if (!mr.is_empty() && !_ct_bs->is_card_claimed(index)) {
 353     // We make the card as "claimed" lazily (so races are possible
 354     // but they're benign), which reduces the number of duplicate
 355     // scans (the rsets of the regions in the cset can intersect).
 356     _ct_bs->set_card_claimed(index);
 357     _push_heap_cl->set_region(r);
 358     r->oops_on_card_seq_iterate_careful<true>(mr, _push_heap_cl);
 359     _cards_scanned++;
 360   }
 361 }
 362 
 363 void G1ScanRSClosure::scan_strong_code_roots(HeapRegion* r) {
 364   double scan_start = os::elapsedTime();
 365   r->strong_code_roots_do(_code_root_cl);
 366   _strong_code_root_scan_time_sec += (os::elapsedTime() - scan_start);
 367 }
 368 
 369 bool G1ScanRSClosure::doHeapRegion(HeapRegion* r) {
 370   assert(r->in_collection_set(), "should only be called on elements of CS.");
 371   uint region_idx = r->hrm_index();
 372 
 373   if (_scan_state->iter_is_complete(region_idx)) {
 374     return false;
 375   }
 376   if (_scan_state->claim_iter(region_idx)) {
 377     // If we ever free the collection set concurrently, we should also
 378     // clear the card table concurrently therefore we won't need to
 379     // add regions of the collection set to the dirty cards region.
 380     _scan_state->add_dirty_region(region_idx);
 381   }
 382 
 383   HeapRegionRemSetIterator iter(r->rem_set());
 384   size_t card_index;
 385 
 386   // We claim cards in block so as to reduce the contention. The block size is determined by
 387   // the G1RSetScanBlockSize parameter.
 388   size_t claimed_card_block = _scan_state->iter_claimed_next(region_idx, _block_size);
 389   for (size_t current_card = 0; iter.has_next(card_index); current_card++) {
 390     if (current_card >= claimed_card_block + _block_size) {
 391       claimed_card_block = _scan_state->iter_claimed_next(region_idx, _block_size);
 392     }
 393     if (current_card < claimed_card_block) {
 394       _cards_skipped++;
 395       continue;
 396     }
 397     HeapWord* card_start = _g1h->bot()->address_for_index(card_index);
 398 
 399     HeapRegion* card_region = _g1h->heap_region_containing(card_start);
 400     _cards_claimed++;
 401 
 402     _scan_state->add_dirty_region(card_region->hrm_index());
 403 
 404     // If the card is dirty, then we will scan it during updateRS.
 405     if (!card_region->in_collection_set() &&
 406         !_ct_bs->is_card_dirty(card_index)) {
 407       scan_card(card_index, card_start, card_region);
 408     }
 409   }
 410   if (_scan_state->set_iter_complete(region_idx)) {
 411     // Scan the strong code root list attached to the current region
 412     scan_strong_code_roots(r);
 413   }
 414   return false;
 415 }
 416 
 417 void G1RemSet::scan_rem_set(G1ParPushHeapRSClosure* oops_in_heap_closure,
 418                             CodeBlobClosure* heap_region_codeblobs,
 419                             uint worker_i) {
 420   double rs_time_start = os::elapsedTime();
 421 
 422   G1ScanRSClosure cl(_scan_state, oops_in_heap_closure, heap_region_codeblobs, worker_i);
 423   _g1->collection_set_iterate_from(&cl, worker_i);
 424 
 425   double scan_rs_time_sec = (os::elapsedTime() - rs_time_start) -
 426                              cl.strong_code_root_scan_time_sec();
 427 
 428   G1GCPhaseTimes* p = _g1p->phase_times();
 429 
 430   p->record_time_secs(G1GCPhaseTimes::ScanRS, worker_i, scan_rs_time_sec);
 431   p->record_thread_work_item(G1GCPhaseTimes::ScanRS, worker_i, cl.cards_scanned(), G1GCPhaseTimes::ScannedCards);
 432   p->record_thread_work_item(G1GCPhaseTimes::ScanRS, worker_i, cl.cards_claimed(), G1GCPhaseTimes::ClaimedCards);
 433   p->record_thread_work_item(G1GCPhaseTimes::ScanRS, worker_i, cl.cards_skipped(), G1GCPhaseTimes::SkippedCards);
 434   
 435   p->record_time_secs(G1GCPhaseTimes::CodeRoots, worker_i, cl.strong_code_root_scan_time_sec());  
 436 }
 437 
 438 // Closure used for updating RSets and recording references that
 439 // point into the collection set. Only called during an
 440 // evacuation pause.
 441 
 442 class RefineRecordRefsIntoCSCardTableEntryClosure: public CardTableEntryClosure {
 443   G1RemSet* _g1rs;
 444   DirtyCardQueue* _into_cset_dcq;
 445   G1ParPushHeapRSClosure* _cl;
 446 public:
 447   RefineRecordRefsIntoCSCardTableEntryClosure(G1CollectedHeap* g1h,
 448                                               DirtyCardQueue* into_cset_dcq,
 449                                               G1ParPushHeapRSClosure* cl) :
 450     _g1rs(g1h->g1_rem_set()), _into_cset_dcq(into_cset_dcq), _cl(cl)
 451   {}
 452 
 453   bool do_card_ptr(jbyte* card_ptr, uint worker_i) {
 454     // The only time we care about recording cards that
 455     // contain references that point into the collection set
 456     // is during RSet updating within an evacuation pause.
 457     // In this case worker_i should be the id of a GC worker thread.
 458     assert(SafepointSynchronize::is_at_safepoint(), "not during an evacuation pause");
 459     assert(worker_i < ParallelGCThreads, "should be a GC worker");
 460 
 461     if (_g1rs->refine_card_during_gc(card_ptr, worker_i, _cl)) {
 462       // 'card_ptr' contains references that point into the collection
 463       // set. We need to record the card in the DCQS
 464       // (_into_cset_dirty_card_queue_set)
 465       // that's used for that purpose.
 466       //
 467       // Enqueue the card
 468       _into_cset_dcq->enqueue(card_ptr);
 469     }
 470     return true;
 471   }
 472 };
 473 
 474 void G1RemSet::update_rem_set(DirtyCardQueue* into_cset_dcq,
 475                               G1ParPushHeapRSClosure* oops_in_heap_closure,
 476                               uint worker_i) {
 477   RefineRecordRefsIntoCSCardTableEntryClosure into_cset_update_rs_cl(_g1, into_cset_dcq, oops_in_heap_closure);
 478 
 479   G1GCParPhaseTimesTracker x(_g1p->phase_times(), G1GCPhaseTimes::UpdateRS, worker_i);
 480   if (G1HotCardCache::default_use_cache()) {
 481     // Apply the closure to the entries of the hot card cache.
 482     G1GCParPhaseTimesTracker y(_g1p->phase_times(), G1GCPhaseTimes::ScanHCC, worker_i);
 483     _g1->iterate_hcc_closure(&into_cset_update_rs_cl, worker_i);
 484   }
 485   // Apply the closure to all remaining log entries.
 486   _g1->iterate_dirty_card_closure(&into_cset_update_rs_cl, worker_i);
 487 }
 488 
 489 void G1RemSet::cleanupHRRS() {
 490   HeapRegionRemSet::cleanup();
 491 }
 492 
 493 void G1RemSet::oops_into_collection_set_do(G1ParPushHeapRSClosure* cl,
 494                                            CodeBlobClosure* heap_region_codeblobs,
 495                                            uint worker_i) {
 496   // A DirtyCardQueue that is used to hold cards containing references
 497   // that point into the collection set. This DCQ is associated with a
 498   // special DirtyCardQueueSet (see g1CollectedHeap.hpp).  Under normal
 499   // circumstances (i.e. the pause successfully completes), these cards
 500   // are just discarded (there's no need to update the RSets of regions
 501   // that were in the collection set - after the pause these regions
 502   // are wholly 'free' of live objects. In the event of an evacuation
 503   // failure the cards/buffers in this queue set are passed to the
 504   // DirtyCardQueueSet that is used to manage RSet updates
 505   DirtyCardQueue into_cset_dcq(&_into_cset_dirty_card_queue_set);
 506 
 507   update_rem_set(&into_cset_dcq, cl, worker_i);
 508   scan_rem_set(cl, heap_region_codeblobs, worker_i);;
 509 }
 510 
 511 void G1RemSet::prepare_for_oops_into_collection_set_do() {
 512   _g1->set_refine_cte_cl_concurrency(false);
 513   DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
 514   dcqs.concatenate_logs();
 515 
 516   _scan_state->reset();
 517 }
 518 
 519 void G1RemSet::cleanup_after_oops_into_collection_set_do() {
 520   G1GCPhaseTimes* phase_times = _g1->g1_policy()->phase_times();
 521   // Cleanup after copy
 522   _g1->set_refine_cte_cl_concurrency(true);
 523 
 524   // Set all cards back to clean.
 525   double start = os::elapsedTime();
 526   _scan_state->clear_card_table(_g1->workers());
 527   phase_times->record_clear_ct_time((os::elapsedTime() - start) * 1000.0);
 528 
 529   DirtyCardQueueSet& into_cset_dcqs = _into_cset_dirty_card_queue_set;
 530 
 531   if (_g1->evacuation_failed()) {
 532     double restore_remembered_set_start = os::elapsedTime();
 533 
 534     // Restore remembered sets for the regions pointing into the collection set.
 535     // We just need to transfer the completed buffers from the DirtyCardQueueSet
 536     // used to hold cards that contain references that point into the collection set
 537     // to the DCQS used to hold the deferred RS updates.
 538     _g1->dirty_card_queue_set().merge_bufferlists(&into_cset_dcqs);
 539     phase_times->record_evac_fail_restore_remsets((os::elapsedTime() - restore_remembered_set_start) * 1000.0);
 540   }
 541 
 542   // Free any completed buffers in the DirtyCardQueueSet used to hold cards
 543   // which contain references that point into the collection.
 544   _into_cset_dirty_card_queue_set.clear();
 545   assert(_into_cset_dirty_card_queue_set.completed_buffers_num() == 0,
 546          "all buffers should be freed");
 547   _into_cset_dirty_card_queue_set.clear_n_completed_buffers();
 548 }
 549 
 550 class G1ScrubRSClosure: public HeapRegionClosure {
 551   G1CollectedHeap* _g1h;
 552   G1CardLiveData* _live_data;
 553 public:
 554   G1ScrubRSClosure(G1CardLiveData* live_data) :
 555     _g1h(G1CollectedHeap::heap()),
 556     _live_data(live_data) { }
 557 
 558   bool doHeapRegion(HeapRegion* r) {
 559     if (!r->is_continues_humongous()) {
 560       r->rem_set()->scrub(_live_data);
 561     }
 562     return false;
 563   }
 564 };
 565 
 566 void G1RemSet::scrub(uint worker_num, HeapRegionClaimer *hrclaimer) {
 567   G1ScrubRSClosure scrub_cl(&_card_live_data);
 568   _g1->heap_region_par_iterate(&scrub_cl, worker_num, hrclaimer);
 569 }
 570 
 571 inline void check_card_ptr(jbyte* card_ptr, CardTableModRefBS* ct_bs) {
 572 #ifdef ASSERT
 573   G1CollectedHeap* g1 = G1CollectedHeap::heap();
 574   assert(g1->is_in_exact(ct_bs->addr_for(card_ptr)),
 575          "Card at " PTR_FORMAT " index " SIZE_FORMAT " representing heap at " PTR_FORMAT " (%u) must be in committed heap",
 576          p2i(card_ptr),
 577          ct_bs->index_for(ct_bs->addr_for(card_ptr)),
 578          p2i(ct_bs->addr_for(card_ptr)),
 579          g1->addr_to_region(ct_bs->addr_for(card_ptr)));
 580 #endif
 581 }
 582 
 583 G1UpdateRSOrPushRefOopClosure::G1UpdateRSOrPushRefOopClosure(G1CollectedHeap* g1h,
 584                                                              G1ParPushHeapRSClosure* push_ref_cl,
 585                                                              bool record_refs_into_cset,
 586                                                              uint worker_i) :
 587   _g1(g1h),
 588   _from(NULL),
 589   _record_refs_into_cset(record_refs_into_cset),
 590   _has_refs_into_cset(false),
 591   _push_ref_cl(push_ref_cl),
 592   _worker_i(worker_i) { }
 593 
 594 void G1RemSet::refine_card_concurrently(jbyte* card_ptr,
 595                                         uint worker_i) {
 596   assert(!_g1->is_gc_active(), "Only call concurrently");
 597 
 598   check_card_ptr(card_ptr, _ct_bs);
 599 
 600   // If the card is no longer dirty, nothing to do.
 601   if (*card_ptr != CardTableModRefBS::dirty_card_val()) {
 602     return;
 603   }
 604 
 605   // Construct the region representing the card.
 606   HeapWord* start = _ct_bs->addr_for(card_ptr);
 607   // And find the region containing it.
 608   HeapRegion* r = _g1->heap_region_containing(start);
 609 
 610   // This check is needed for some uncommon cases where we should
 611   // ignore the card.
 612   //
 613   // The region could be young.  Cards for young regions are
 614   // distinctly marked (set to g1_young_gen), so the post-barrier will
 615   // filter them out.  However, that marking is performed
 616   // concurrently.  A write to a young object could occur before the
 617   // card has been marked young, slipping past the filter.
 618   //
 619   // The card could be stale, because the region has been freed since
 620   // the card was recorded. In this case the region type could be
 621   // anything.  If (still) free or (reallocated) young, just ignore
 622   // it.  If (reallocated) old or humongous, the later card trimming
 623   // and additional checks in iteration may detect staleness.  At
 624   // worst, we end up processing a stale card unnecessarily.
 625   //
 626   // In the normal (non-stale) case, the synchronization between the
 627   // enqueueing of the card and processing it here will have ensured
 628   // we see the up-to-date region type here.
 629   if (!r->is_old_or_humongous()) {
 630     return;
 631   }
 632 
 633   // While we are processing RSet buffers during the collection, we
 634   // actually don't want to scan any cards on the collection set,
 635   // since we don't want to update remembered sets with entries that
 636   // point into the collection set, given that live objects from the
 637   // collection set are about to move and such entries will be stale
 638   // very soon. This change also deals with a reliability issue which
 639   // involves scanning a card in the collection set and coming across
 640   // an array that was being chunked and looking malformed. Note,
 641   // however, that if evacuation fails, we have to scan any objects
 642   // that were not moved and create any missing entries.
 643   if (r->in_collection_set()) {
 644     return;
 645   }
 646 
 647   // The result from the hot card cache insert call is either:
 648   //   * pointer to the current card
 649   //     (implying that the current card is not 'hot'),
 650   //   * null
 651   //     (meaning we had inserted the card ptr into the "hot" card cache,
 652   //     which had some headroom),
 653   //   * a pointer to a "hot" card that was evicted from the "hot" cache.
 654   //
 655 
 656   if (_hot_card_cache->use_cache()) {
 657     assert(!SafepointSynchronize::is_at_safepoint(), "sanity");
 658 
 659     const jbyte* orig_card_ptr = card_ptr;
 660     card_ptr = _hot_card_cache->insert(card_ptr);
 661     if (card_ptr == NULL) {
 662       // There was no eviction. Nothing to do.
 663       return;
 664     } else if (card_ptr != orig_card_ptr) {
 665       // Original card was inserted and an old card was evicted.
 666       start = _ct_bs->addr_for(card_ptr);
 667       r = _g1->heap_region_containing(start);
 668 
 669       // Check whether the region formerly in the cache should be
 670       // ignored, as discussed earlier for the original card.  The
 671       // region could have been freed while in the cache.  The cset is
 672       // not relevant here, since we're in concurrent phase.
 673       if (!r->is_old_or_humongous()) {
 674         return;
 675       }
 676     } // Else we still have the original card.
 677   }
 678 
 679   // Trim the region designated by the card to what's been allocated
 680   // in the region.  The card could be stale, or the card could cover
 681   // (part of) an object at the end of the allocated space and extend
 682   // beyond the end of allocation.
 683 
 684   // Non-humongous objects are only allocated in the old-gen during
 685   // GC, so if region is old then top is stable.  Humongous object
 686   // allocation sets top last; if top has not yet been set, this is
 687   // a stale card and we'll end up with an empty intersection.  If
 688   // this is not a stale card, the synchronization between the
 689   // enqueuing of the card and processing it here will have ensured
 690   // we see the up-to-date top here.
 691   HeapWord* scan_limit = r->top();
 692 
 693   if (scan_limit <= start) {
 694     // If the trimmed region is empty, the card must be stale.
 695     return;
 696   }
 697 
 698   // Okay to clean and process the card now.  There are still some
 699   // stale card cases that may be detected by iteration and dealt with
 700   // as iteration failure.
 701   *const_cast<volatile jbyte*>(card_ptr) = CardTableModRefBS::clean_card_val();
 702 
 703   // This fence serves two purposes.  First, the card must be cleaned
 704   // before processing the contents.  Second, we can't proceed with
 705   // processing until after the read of top, for synchronization with
 706   // possibly concurrent humongous object allocation.  It's okay that
 707   // reading top and reading type were racy wrto each other.  We need
 708   // both set, in any order, to proceed.
 709   OrderAccess::fence();
 710 
 711   // Don't use addr_for(card_ptr + 1) which can ask for
 712   // a card beyond the heap.
 713   HeapWord* end = start + CardTableModRefBS::card_size_in_words;
 714   MemRegion dirty_region(start, MIN2(scan_limit, end));
 715   assert(!dirty_region.is_empty(), "sanity");
 716 
 717   G1ConcurrentRefineOopClosure conc_refine_cl(_g1, worker_i);
 718 
 719   bool card_processed =
 720     r->oops_on_card_seq_iterate_careful<false>(dirty_region, &conc_refine_cl);
 721 
 722   // If unable to process the card then we encountered an unparsable
 723   // part of the heap (e.g. a partially allocated object) while
 724   // processing a stale card.  Despite the card being stale, redirty
 725   // and re-enqueue, because we've already cleaned the card.  Without
 726   // this we could incorrectly discard a non-stale card.
 727   if (!card_processed) {
 728     // The card might have gotten re-dirtied and re-enqueued while we
 729     // worked.  (In fact, it's pretty likely.)
 730     if (*card_ptr != CardTableModRefBS::dirty_card_val()) {
 731       *card_ptr = CardTableModRefBS::dirty_card_val();
 732       MutexLockerEx x(Shared_DirtyCardQ_lock,
 733                       Mutex::_no_safepoint_check_flag);
 734       DirtyCardQueue* sdcq =
 735         JavaThread::dirty_card_queue_set().shared_dirty_card_queue();
 736       sdcq->enqueue(card_ptr);
 737     }
 738   } else {
 739     _conc_refine_cards++;
 740   }
 741 }
 742 
 743 bool G1RemSet::refine_card_during_gc(jbyte* card_ptr,
 744                                      uint worker_i,
 745                                      G1ParPushHeapRSClosure*  oops_in_heap_closure) {
 746   assert(_g1->is_gc_active(), "Only call during GC");
 747 
 748   check_card_ptr(card_ptr, _ct_bs);
 749 
 750   // If the card is no longer dirty, nothing to do. This covers cards that were already
 751   // scanned as parts of the remembered sets.
 752   if (*card_ptr != CardTableModRefBS::dirty_card_val()) {
 753     // No need to return that this card contains refs that point
 754     // into the collection set.
 755     return false;
 756   }
 757 
 758   // Construct the region representing the card.
 759   HeapWord* start = _ct_bs->addr_for(card_ptr);
 760   // And find the region containing it.
 761   HeapRegion* r = _g1->heap_region_containing(start);
 762 
 763   HeapWord* scan_limit = _scan_state->scan_top(r->hrm_index());
 764   if (scan_limit <= start) {
 765     // If the card starts above the area in the region containing objects to scan, skip it.
 766     return false;
 767   }
 768 
 769   // Okay to clean and process the card now.  There are still some
 770   // stale card cases that may be detected by iteration and dealt with
 771   // as iteration failure.
 772   *const_cast<volatile jbyte*>(card_ptr) = CardTableModRefBS::clean_card_val();
 773 
 774   // Don't use addr_for(card_ptr + 1) which can ask for
 775   // a card beyond the heap.
 776   HeapWord* end = start + CardTableModRefBS::card_size_in_words;
 777   MemRegion dirty_region(start, MIN2(scan_limit, end));
 778   assert(!dirty_region.is_empty(), "sanity");
 779 
 780   G1UpdateRSOrPushRefOopClosure update_rs_oop_cl(_g1,
 781                                                  oops_in_heap_closure,
 782                                                  true,
 783                                                  worker_i);
 784   update_rs_oop_cl.set_from(r);
 785 
 786   bool card_processed =
 787     r->oops_on_card_seq_iterate_careful<true>(dirty_region,
 788                                               &update_rs_oop_cl);
 789   assert(card_processed, "must be");
 790   _conc_refine_cards++;
 791  
 792   return update_rs_oop_cl.has_refs_into_cset();
 793 }
 794 
 795 void G1RemSet::print_periodic_summary_info(const char* header, uint period_count) {
 796   if ((G1SummarizeRSetStatsPeriod > 0) && log_is_enabled(Trace, gc, remset) &&
 797       (period_count % G1SummarizeRSetStatsPeriod == 0)) {
 798 
 799     if (!_prev_period_summary.initialized()) {
 800       _prev_period_summary.initialize(this);
 801     }
 802 
 803     G1RemSetSummary current;
 804     current.initialize(this);
 805     _prev_period_summary.subtract_from(&current);
 806 
 807     Log(gc, remset) log;
 808     log.trace("%s", header);
 809     ResourceMark rm;
 810     _prev_period_summary.print_on(log.trace_stream());
 811 
 812     _prev_period_summary.set(&current);
 813   }
 814 }
 815 
 816 void G1RemSet::print_summary_info() {
 817   Log(gc, remset, exit) log;
 818   if (log.is_trace()) {
 819     log.trace(" Cumulative RS summary");
 820     G1RemSetSummary current;
 821     current.initialize(this);
 822     ResourceMark rm;
 823     current.print_on(log.trace_stream());
 824   }
 825 }
 826 
 827 void G1RemSet::prepare_for_verify() {
 828   if (G1HRRSFlushLogBuffersOnVerify &&
 829       (VerifyBeforeGC || VerifyAfterGC)
 830       &&  (!_g1->collector_state()->full_collection() || G1VerifyRSetsDuringFullGC)) {
 831     cleanupHRRS();
 832     _g1->set_refine_cte_cl_concurrency(false);
 833     if (SafepointSynchronize::is_at_safepoint()) {
 834       DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
 835       dcqs.concatenate_logs();
 836     }
 837 
 838     bool use_hot_card_cache = _hot_card_cache->use_cache();
 839     _hot_card_cache->set_use_cache(false);
 840 
 841     DirtyCardQueue into_cset_dcq(&_into_cset_dirty_card_queue_set);
 842     update_rem_set(&into_cset_dcq, NULL, 0);
 843     _into_cset_dirty_card_queue_set.clear();
 844 
 845     _hot_card_cache->set_use_cache(use_hot_card_cache);
 846     assert(JavaThread::dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed");
 847   }
 848 }
 849 
 850 void G1RemSet::create_card_live_data(WorkGang* workers, G1CMBitMap* mark_bitmap) {
 851   _card_live_data.create(workers, mark_bitmap);
 852 }
 853 
 854 void G1RemSet::finalize_card_live_data(WorkGang* workers, G1CMBitMap* mark_bitmap) {
 855   _card_live_data.finalize(workers, mark_bitmap);
 856 }
 857 
 858 void G1RemSet::verify_card_live_data(WorkGang* workers, G1CMBitMap* bitmap) {
 859   _card_live_data.verify(workers, bitmap);
 860 }
 861 
 862 void G1RemSet::clear_card_live_data(WorkGang* workers) {
 863   _card_live_data.clear(workers);
 864 }
 865 
 866 #ifdef ASSERT
 867 void G1RemSet::verify_card_live_data_is_clear() {
 868   _card_live_data.verify_is_clear();
 869 }
 870 #endif