1 /*
   2  * Copyright (c) 2001, 2014, 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 "classfile/symbolTable.hpp"
  27 #include "gc_implementation/g1/concurrentMark.inline.hpp"
  28 #include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
  29 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
  30 #include "gc_implementation/g1/g1CollectorPolicy.hpp"
  31 #include "gc_implementation/g1/g1ErgoVerbose.hpp"
  32 #include "gc_implementation/g1/g1Log.hpp"
  33 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
  34 #include "gc_implementation/g1/g1RemSet.hpp"
  35 #include "gc_implementation/g1/heapRegion.inline.hpp"
  36 #include "gc_implementation/g1/heapRegionRemSet.hpp"
  37 #include "gc_implementation/g1/heapRegionSeq.inline.hpp"
  38 #include "gc_implementation/shared/vmGCOperations.hpp"
  39 #include "gc_implementation/shared/gcTimer.hpp"
  40 #include "gc_implementation/shared/gcTrace.hpp"
  41 #include "gc_implementation/shared/gcTraceTime.hpp"
  42 #include "memory/genOopClosures.inline.hpp"
  43 #include "memory/referencePolicy.hpp"
  44 #include "memory/resourceArea.hpp"
  45 #include "oops/oop.inline.hpp"
  46 #include "runtime/handles.inline.hpp"
  47 #include "runtime/java.hpp"
  48 #include "runtime/atomic.inline.hpp"
  49 #include "runtime/prefetch.inline.hpp"
  50 #include "services/memTracker.hpp"
  51 
  52 // Concurrent marking bit map wrapper
  53 
  54 CMBitMapRO::CMBitMapRO(int shifter) :
  55   _bm(),
  56   _shifter(shifter) {
  57   _bmStartWord = 0;
  58   _bmWordSize = 0;
  59 }
  60 
  61 HeapWord* CMBitMapRO::getNextMarkedWordAddress(HeapWord* addr,
  62                                                HeapWord* limit) const {
  63   // First we must round addr *up* to a possible object boundary.
  64   addr = (HeapWord*)align_size_up((intptr_t)addr,
  65                                   HeapWordSize << _shifter);
  66   size_t addrOffset = heapWordToOffset(addr);
  67   if (limit == NULL) {
  68     limit = _bmStartWord + _bmWordSize;
  69   }
  70   size_t limitOffset = heapWordToOffset(limit);
  71   size_t nextOffset = _bm.get_next_one_offset(addrOffset, limitOffset);
  72   HeapWord* nextAddr = offsetToHeapWord(nextOffset);
  73   assert(nextAddr >= addr, "get_next_one postcondition");
  74   assert(nextAddr == limit || isMarked(nextAddr),
  75          "get_next_one postcondition");
  76   return nextAddr;
  77 }
  78 
  79 HeapWord* CMBitMapRO::getNextUnmarkedWordAddress(HeapWord* addr,
  80                                                  HeapWord* limit) const {
  81   size_t addrOffset = heapWordToOffset(addr);
  82   if (limit == NULL) {
  83     limit = _bmStartWord + _bmWordSize;
  84   }
  85   size_t limitOffset = heapWordToOffset(limit);
  86   size_t nextOffset = _bm.get_next_zero_offset(addrOffset, limitOffset);
  87   HeapWord* nextAddr = offsetToHeapWord(nextOffset);
  88   assert(nextAddr >= addr, "get_next_one postcondition");
  89   assert(nextAddr == limit || !isMarked(nextAddr),
  90          "get_next_one postcondition");
  91   return nextAddr;
  92 }
  93 
  94 int CMBitMapRO::heapWordDiffToOffsetDiff(size_t diff) const {
  95   assert((diff & ((1 << _shifter) - 1)) == 0, "argument check");
  96   return (int) (diff >> _shifter);
  97 }
  98 
  99 #ifndef PRODUCT
 100 bool CMBitMapRO::covers(ReservedSpace heap_rs) const {
 101   // assert(_bm.map() == _virtual_space.low(), "map inconsistency");
 102   assert(((size_t)_bm.size() * ((size_t)1 << _shifter)) == _bmWordSize,
 103          "size inconsistency");
 104   return _bmStartWord == (HeapWord*)(heap_rs.base()) &&
 105          _bmWordSize  == heap_rs.size()>>LogHeapWordSize;
 106 }
 107 #endif
 108 
 109 void CMBitMapRO::print_on_error(outputStream* st, const char* prefix) const {
 110   _bm.print_on_error(st, prefix);
 111 }
 112 
 113 bool CMBitMap::allocate(ReservedSpace heap_rs) {
 114   _bmStartWord = (HeapWord*)(heap_rs.base());
 115   _bmWordSize  = heap_rs.size()/HeapWordSize;    // heap_rs.size() is in bytes
 116   ReservedSpace brs(ReservedSpace::allocation_align_size_up(
 117                      (_bmWordSize >> (_shifter + LogBitsPerByte)) + 1));
 118   if (!brs.is_reserved()) {
 119     warning("ConcurrentMark marking bit map allocation failure");
 120     return false;
 121   }
 122   MemTracker::record_virtual_memory_type((address)brs.base(), mtGC);
 123   // For now we'll just commit all of the bit map up front.
 124   // Later on we'll try to be more parsimonious with swap.
 125   if (!_virtual_space.initialize(brs, brs.size())) {
 126     warning("ConcurrentMark marking bit map backing store failure");
 127     return false;
 128   }
 129   assert(_virtual_space.committed_size() == brs.size(),
 130          "didn't reserve backing store for all of concurrent marking bit map?");
 131   _bm.set_map((uintptr_t*)_virtual_space.low());
 132   assert(_virtual_space.committed_size() << (_shifter + LogBitsPerByte) >=
 133          _bmWordSize, "inconsistency in bit map sizing");
 134   _bm.set_size(_bmWordSize >> _shifter);
 135   return true;
 136 }
 137 
 138 void CMBitMap::clearAll() {
 139   _bm.clear();
 140   return;
 141 }
 142 
 143 void CMBitMap::markRange(MemRegion mr) {
 144   mr.intersection(MemRegion(_bmStartWord, _bmWordSize));
 145   assert(!mr.is_empty(), "unexpected empty region");
 146   assert((offsetToHeapWord(heapWordToOffset(mr.end())) ==
 147           ((HeapWord *) mr.end())),
 148          "markRange memory region end is not card aligned");
 149   // convert address range into offset range
 150   _bm.at_put_range(heapWordToOffset(mr.start()),
 151                    heapWordToOffset(mr.end()), true);
 152 }
 153 
 154 void CMBitMap::clearRange(MemRegion mr) {
 155   mr.intersection(MemRegion(_bmStartWord, _bmWordSize));
 156   assert(!mr.is_empty(), "unexpected empty region");
 157   // convert address range into offset range
 158   _bm.at_put_range(heapWordToOffset(mr.start()),
 159                    heapWordToOffset(mr.end()), false);
 160 }
 161 
 162 MemRegion CMBitMap::getAndClearMarkedRegion(HeapWord* addr,
 163                                             HeapWord* end_addr) {
 164   HeapWord* start = getNextMarkedWordAddress(addr);
 165   start = MIN2(start, end_addr);
 166   HeapWord* end   = getNextUnmarkedWordAddress(start);
 167   end = MIN2(end, end_addr);
 168   assert(start <= end, "Consistency check");
 169   MemRegion mr(start, end);
 170   if (!mr.is_empty()) {
 171     clearRange(mr);
 172   }
 173   return mr;
 174 }
 175 
 176 CMMarkStack::CMMarkStack(ConcurrentMark* cm) :
 177   _base(NULL), _cm(cm)
 178 #ifdef ASSERT
 179   , _drain_in_progress(false)
 180   , _drain_in_progress_yields(false)
 181 #endif
 182 {}
 183 
 184 bool CMMarkStack::allocate(size_t capacity) {
 185   // allocate a stack of the requisite depth
 186   ReservedSpace rs(ReservedSpace::allocation_align_size_up(capacity * sizeof(oop)));
 187   if (!rs.is_reserved()) {
 188     warning("ConcurrentMark MarkStack allocation failure");
 189     return false;
 190   }
 191   MemTracker::record_virtual_memory_type((address)rs.base(), mtGC);
 192   if (!_virtual_space.initialize(rs, rs.size())) {
 193     warning("ConcurrentMark MarkStack backing store failure");
 194     // Release the virtual memory reserved for the marking stack
 195     rs.release();
 196     return false;
 197   }
 198   assert(_virtual_space.committed_size() == rs.size(),
 199          "Didn't reserve backing store for all of ConcurrentMark stack?");
 200   _base = (oop*) _virtual_space.low();
 201   setEmpty();
 202   _capacity = (jint) capacity;
 203   _saved_index = -1;
 204   _should_expand = false;
 205   NOT_PRODUCT(_max_depth = 0);
 206   return true;
 207 }
 208 
 209 void CMMarkStack::expand() {
 210   // Called, during remark, if we've overflown the marking stack during marking.
 211   assert(isEmpty(), "stack should been emptied while handling overflow");
 212   assert(_capacity <= (jint) MarkStackSizeMax, "stack bigger than permitted");
 213   // Clear expansion flag
 214   _should_expand = false;
 215   if (_capacity == (jint) MarkStackSizeMax) {
 216     if (PrintGCDetails && Verbose) {
 217       gclog_or_tty->print_cr(" (benign) Can't expand marking stack capacity, at max size limit");
 218     }
 219     return;
 220   }
 221   // Double capacity if possible
 222   jint new_capacity = MIN2(_capacity*2, (jint) MarkStackSizeMax);
 223   // Do not give up existing stack until we have managed to
 224   // get the double capacity that we desired.
 225   ReservedSpace rs(ReservedSpace::allocation_align_size_up(new_capacity *
 226                                                            sizeof(oop)));
 227   if (rs.is_reserved()) {
 228     // Release the backing store associated with old stack
 229     _virtual_space.release();
 230     // Reinitialize virtual space for new stack
 231     if (!_virtual_space.initialize(rs, rs.size())) {
 232       fatal("Not enough swap for expanded marking stack capacity");
 233     }
 234     _base = (oop*)(_virtual_space.low());
 235     _index = 0;
 236     _capacity = new_capacity;
 237   } else {
 238     if (PrintGCDetails && Verbose) {
 239       // Failed to double capacity, continue;
 240       gclog_or_tty->print(" (benign) Failed to expand marking stack capacity from "
 241                           SIZE_FORMAT"K to " SIZE_FORMAT"K",
 242                           _capacity / K, new_capacity / K);
 243     }
 244   }
 245 }
 246 
 247 void CMMarkStack::set_should_expand() {
 248   // If we're resetting the marking state because of an
 249   // marking stack overflow, record that we should, if
 250   // possible, expand the stack.
 251   _should_expand = _cm->has_overflown();
 252 }
 253 
 254 CMMarkStack::~CMMarkStack() {
 255   if (_base != NULL) {
 256     _base = NULL;
 257     _virtual_space.release();
 258   }
 259 }
 260 
 261 void CMMarkStack::par_push(oop ptr) {
 262   while (true) {
 263     if (isFull()) {
 264       _overflow = true;
 265       return;
 266     }
 267     // Otherwise...
 268     jint index = _index;
 269     jint next_index = index+1;
 270     jint res = Atomic::cmpxchg(next_index, &_index, index);
 271     if (res == index) {
 272       _base[index] = ptr;
 273       // Note that we don't maintain this atomically.  We could, but it
 274       // doesn't seem necessary.
 275       NOT_PRODUCT(_max_depth = MAX2(_max_depth, next_index));
 276       return;
 277     }
 278     // Otherwise, we need to try again.
 279   }
 280 }
 281 
 282 void CMMarkStack::par_adjoin_arr(oop* ptr_arr, int n) {
 283   while (true) {
 284     if (isFull()) {
 285       _overflow = true;
 286       return;
 287     }
 288     // Otherwise...
 289     jint index = _index;
 290     jint next_index = index + n;
 291     if (next_index > _capacity) {
 292       _overflow = true;
 293       return;
 294     }
 295     jint res = Atomic::cmpxchg(next_index, &_index, index);
 296     if (res == index) {
 297       for (int i = 0; i < n; i++) {
 298         int  ind = index + i;
 299         assert(ind < _capacity, "By overflow test above.");
 300         _base[ind] = ptr_arr[i];
 301       }
 302       NOT_PRODUCT(_max_depth = MAX2(_max_depth, next_index));
 303       return;
 304     }
 305     // Otherwise, we need to try again.
 306   }
 307 }
 308 
 309 void CMMarkStack::par_push_arr(oop* ptr_arr, int n) {
 310   MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
 311   jint start = _index;
 312   jint next_index = start + n;
 313   if (next_index > _capacity) {
 314     _overflow = true;
 315     return;
 316   }
 317   // Otherwise.
 318   _index = next_index;
 319   for (int i = 0; i < n; i++) {
 320     int ind = start + i;
 321     assert(ind < _capacity, "By overflow test above.");
 322     _base[ind] = ptr_arr[i];
 323   }
 324   NOT_PRODUCT(_max_depth = MAX2(_max_depth, next_index));
 325 }
 326 
 327 bool CMMarkStack::par_pop_arr(oop* ptr_arr, int max, int* n) {
 328   MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
 329   jint index = _index;
 330   if (index == 0) {
 331     *n = 0;
 332     return false;
 333   } else {
 334     int k = MIN2(max, index);
 335     jint  new_ind = index - k;
 336     for (int j = 0; j < k; j++) {
 337       ptr_arr[j] = _base[new_ind + j];
 338     }
 339     _index = new_ind;
 340     *n = k;
 341     return true;
 342   }
 343 }
 344 
 345 template<class OopClosureClass>
 346 bool CMMarkStack::drain(OopClosureClass* cl, CMBitMap* bm, bool yield_after) {
 347   assert(!_drain_in_progress || !_drain_in_progress_yields || yield_after
 348          || SafepointSynchronize::is_at_safepoint(),
 349          "Drain recursion must be yield-safe.");
 350   bool res = true;
 351   debug_only(_drain_in_progress = true);
 352   debug_only(_drain_in_progress_yields = yield_after);
 353   while (!isEmpty()) {
 354     oop newOop = pop();
 355     assert(G1CollectedHeap::heap()->is_in_reserved(newOop), "Bad pop");
 356     assert(newOop->is_oop(), "Expected an oop");
 357     assert(bm == NULL || bm->isMarked((HeapWord*)newOop),
 358            "only grey objects on this stack");
 359     newOop->oop_iterate(cl);
 360     if (yield_after && _cm->do_yield_check()) {
 361       res = false;
 362       break;
 363     }
 364   }
 365   debug_only(_drain_in_progress = false);
 366   return res;
 367 }
 368 
 369 void CMMarkStack::note_start_of_gc() {
 370   assert(_saved_index == -1,
 371          "note_start_of_gc()/end_of_gc() bracketed incorrectly");
 372   _saved_index = _index;
 373 }
 374 
 375 void CMMarkStack::note_end_of_gc() {
 376   // This is intentionally a guarantee, instead of an assert. If we
 377   // accidentally add something to the mark stack during GC, it
 378   // will be a correctness issue so it's better if we crash. we'll
 379   // only check this once per GC anyway, so it won't be a performance
 380   // issue in any way.
 381   guarantee(_saved_index == _index,
 382             err_msg("saved index: %d index: %d", _saved_index, _index));
 383   _saved_index = -1;
 384 }
 385 
 386 void CMMarkStack::oops_do(OopClosure* f) {
 387   assert(_saved_index == _index,
 388          err_msg("saved index: %d index: %d", _saved_index, _index));
 389   for (int i = 0; i < _index; i += 1) {
 390     f->do_oop(&_base[i]);
 391   }
 392 }
 393 
 394 bool ConcurrentMark::not_yet_marked(oop obj) const {
 395   return _g1h->is_obj_ill(obj);
 396 }
 397 
 398 CMRootRegions::CMRootRegions() :
 399   _young_list(NULL), _cm(NULL), _scan_in_progress(false),
 400   _should_abort(false),  _next_survivor(NULL) { }
 401 
 402 void CMRootRegions::init(G1CollectedHeap* g1h, ConcurrentMark* cm) {
 403   _young_list = g1h->young_list();
 404   _cm = cm;
 405 }
 406 
 407 void CMRootRegions::prepare_for_scan() {
 408   assert(!scan_in_progress(), "pre-condition");
 409 
 410   // Currently, only survivors can be root regions.
 411   assert(_next_survivor == NULL, "pre-condition");
 412   _next_survivor = _young_list->first_survivor_region();
 413   _scan_in_progress = (_next_survivor != NULL);
 414   _should_abort = false;
 415 }
 416 
 417 HeapRegion* CMRootRegions::claim_next() {
 418   if (_should_abort) {
 419     // If someone has set the should_abort flag, we return NULL to
 420     // force the caller to bail out of their loop.
 421     return NULL;
 422   }
 423 
 424   // Currently, only survivors can be root regions.
 425   HeapRegion* res = _next_survivor;
 426   if (res != NULL) {
 427     MutexLockerEx x(RootRegionScan_lock, Mutex::_no_safepoint_check_flag);
 428     // Read it again in case it changed while we were waiting for the lock.
 429     res = _next_survivor;
 430     if (res != NULL) {
 431       if (res == _young_list->last_survivor_region()) {
 432         // We just claimed the last survivor so store NULL to indicate
 433         // that we're done.
 434         _next_survivor = NULL;
 435       } else {
 436         _next_survivor = res->get_next_young_region();
 437       }
 438     } else {
 439       // Someone else claimed the last survivor while we were trying
 440       // to take the lock so nothing else to do.
 441     }
 442   }
 443   assert(res == NULL || res->is_survivor(), "post-condition");
 444 
 445   return res;
 446 }
 447 
 448 void CMRootRegions::scan_finished() {
 449   assert(scan_in_progress(), "pre-condition");
 450 
 451   // Currently, only survivors can be root regions.
 452   if (!_should_abort) {
 453     assert(_next_survivor == NULL, "we should have claimed all survivors");
 454   }
 455   _next_survivor = NULL;
 456 
 457   {
 458     MutexLockerEx x(RootRegionScan_lock, Mutex::_no_safepoint_check_flag);
 459     _scan_in_progress = false;
 460     RootRegionScan_lock->notify_all();
 461   }
 462 }
 463 
 464 bool CMRootRegions::wait_until_scan_finished() {
 465   if (!scan_in_progress()) return false;
 466 
 467   {
 468     MutexLockerEx x(RootRegionScan_lock, Mutex::_no_safepoint_check_flag);
 469     while (scan_in_progress()) {
 470       RootRegionScan_lock->wait(Mutex::_no_safepoint_check_flag);
 471     }
 472   }
 473   return true;
 474 }
 475 
 476 #ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away
 477 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
 478 #endif // _MSC_VER
 479 
 480 uint ConcurrentMark::scale_parallel_threads(uint n_par_threads) {
 481   return MAX2((n_par_threads + 2) / 4, 1U);
 482 }
 483 
 484 ConcurrentMark::ConcurrentMark(G1CollectedHeap* g1h, ReservedSpace heap_rs) :
 485   _g1h(g1h),
 486   _markBitMap1(log2_intptr(MinObjAlignment)),
 487   _markBitMap2(log2_intptr(MinObjAlignment)),
 488   _parallel_marking_threads(0),
 489   _max_parallel_marking_threads(0),
 490   _sleep_factor(0.0),
 491   _marking_task_overhead(1.0),
 492   _cleanup_sleep_factor(0.0),
 493   _cleanup_task_overhead(1.0),
 494   _cleanup_list("Cleanup List"),
 495   _region_bm((BitMap::idx_t)(g1h->max_regions()), false /* in_resource_area*/),
 496   _card_bm((heap_rs.size() + CardTableModRefBS::card_size - 1) >>
 497             CardTableModRefBS::card_shift,
 498             false /* in_resource_area*/),
 499 
 500   _prevMarkBitMap(&_markBitMap1),
 501   _nextMarkBitMap(&_markBitMap2),
 502 
 503   _markStack(this),
 504   // _finger set in set_non_marking_state
 505 
 506   _max_worker_id(MAX2((uint)ParallelGCThreads, 1U)),
 507   // _active_tasks set in set_non_marking_state
 508   // _tasks set inside the constructor
 509   _task_queues(new CMTaskQueueSet((int) _max_worker_id)),
 510   _terminator(ParallelTaskTerminator((int) _max_worker_id, _task_queues)),
 511 
 512   _has_overflown(false),
 513   _concurrent(false),
 514   _has_aborted(false),
 515   _restart_for_overflow(false),
 516   _concurrent_marking_in_progress(false),
 517 
 518   // _verbose_level set below
 519 
 520   _init_times(),
 521   _remark_times(), _remark_mark_times(), _remark_weak_ref_times(),
 522   _cleanup_times(),
 523   _total_counting_time(0.0),
 524   _total_rs_scrub_time(0.0),
 525 
 526   _parallel_workers(NULL),
 527 
 528   _count_card_bitmaps(NULL),
 529   _count_marked_bytes(NULL),
 530   _completed_initialization(false) {
 531   CMVerboseLevel verbose_level = (CMVerboseLevel) G1MarkingVerboseLevel;
 532   if (verbose_level < no_verbose) {
 533     verbose_level = no_verbose;
 534   }
 535   if (verbose_level > high_verbose) {
 536     verbose_level = high_verbose;
 537   }
 538   _verbose_level = verbose_level;
 539 
 540   if (verbose_low()) {
 541     gclog_or_tty->print_cr("[global] init, heap start = "PTR_FORMAT", "
 542                            "heap end = " PTR_FORMAT, p2i(_heap_start), p2i(_heap_end));
 543   }
 544 
 545   if (!_markBitMap1.allocate(heap_rs)) {
 546     warning("Failed to allocate first CM bit map");
 547     return;
 548   }
 549   if (!_markBitMap2.allocate(heap_rs)) {
 550     warning("Failed to allocate second CM bit map");
 551     return;
 552   }
 553 
 554   // Create & start a ConcurrentMark thread.
 555   _cmThread = new ConcurrentMarkThread(this);
 556   assert(cmThread() != NULL, "CM Thread should have been created");
 557   assert(cmThread()->cm() != NULL, "CM Thread should refer to this cm");
 558   if (_cmThread->osthread() == NULL) {
 559       vm_shutdown_during_initialization("Could not create ConcurrentMarkThread");
 560   }
 561 
 562   assert(CGC_lock != NULL, "Where's the CGC_lock?");
 563   assert(_markBitMap1.covers(heap_rs), "_markBitMap1 inconsistency");
 564   assert(_markBitMap2.covers(heap_rs), "_markBitMap2 inconsistency");
 565 
 566   SATBMarkQueueSet& satb_qs = JavaThread::satb_mark_queue_set();
 567   satb_qs.set_buffer_size(G1SATBBufferSize);
 568 
 569   _root_regions.init(_g1h, this);
 570 
 571   if (ConcGCThreads > ParallelGCThreads) {
 572     warning("Can't have more ConcGCThreads (" UINTX_FORMAT ") "
 573             "than ParallelGCThreads (" UINTX_FORMAT ").",
 574             ConcGCThreads, ParallelGCThreads);
 575     return;
 576   }
 577   if (ParallelGCThreads == 0) {
 578     // if we are not running with any parallel GC threads we will not
 579     // spawn any marking threads either
 580     _parallel_marking_threads =       0;
 581     _max_parallel_marking_threads =   0;
 582     _sleep_factor             =     0.0;
 583     _marking_task_overhead    =     1.0;
 584   } else {
 585     if (!FLAG_IS_DEFAULT(ConcGCThreads) && ConcGCThreads > 0) {
 586       // Note: ConcGCThreads has precedence over G1MarkingOverheadPercent
 587       // if both are set
 588       _sleep_factor             = 0.0;
 589       _marking_task_overhead    = 1.0;
 590     } else if (G1MarkingOverheadPercent > 0) {
 591       // We will calculate the number of parallel marking threads based
 592       // on a target overhead with respect to the soft real-time goal
 593       double marking_overhead = (double) G1MarkingOverheadPercent / 100.0;
 594       double overall_cm_overhead =
 595         (double) MaxGCPauseMillis * marking_overhead /
 596         (double) GCPauseIntervalMillis;
 597       double cpu_ratio = 1.0 / (double) os::processor_count();
 598       double marking_thread_num = ceil(overall_cm_overhead / cpu_ratio);
 599       double marking_task_overhead =
 600         overall_cm_overhead / marking_thread_num *
 601                                                 (double) os::processor_count();
 602       double sleep_factor =
 603                          (1.0 - marking_task_overhead) / marking_task_overhead;
 604 
 605       FLAG_SET_ERGO(uintx, ConcGCThreads, (uint) marking_thread_num);
 606       _sleep_factor             = sleep_factor;
 607       _marking_task_overhead    = marking_task_overhead;
 608     } else {
 609       // Calculate the number of parallel marking threads by scaling
 610       // the number of parallel GC threads.
 611       uint marking_thread_num = scale_parallel_threads((uint) ParallelGCThreads);
 612       FLAG_SET_ERGO(uintx, ConcGCThreads, marking_thread_num);
 613       _sleep_factor             = 0.0;
 614       _marking_task_overhead    = 1.0;
 615     }
 616 
 617     assert(ConcGCThreads > 0, "Should have been set");
 618     _parallel_marking_threads = (uint) ConcGCThreads;
 619     _max_parallel_marking_threads = _parallel_marking_threads;
 620 
 621     if (parallel_marking_threads() > 1) {
 622       _cleanup_task_overhead = 1.0;
 623     } else {
 624       _cleanup_task_overhead = marking_task_overhead();
 625     }
 626     _cleanup_sleep_factor =
 627                      (1.0 - cleanup_task_overhead()) / cleanup_task_overhead();
 628 
 629 #if 0
 630     gclog_or_tty->print_cr("Marking Threads          %d", parallel_marking_threads());
 631     gclog_or_tty->print_cr("CM Marking Task Overhead %1.4lf", marking_task_overhead());
 632     gclog_or_tty->print_cr("CM Sleep Factor          %1.4lf", sleep_factor());
 633     gclog_or_tty->print_cr("CL Marking Task Overhead %1.4lf", cleanup_task_overhead());
 634     gclog_or_tty->print_cr("CL Sleep Factor          %1.4lf", cleanup_sleep_factor());
 635 #endif
 636 
 637     guarantee(parallel_marking_threads() > 0, "peace of mind");
 638     _parallel_workers = new FlexibleWorkGang("G1 Parallel Marking Threads",
 639          _max_parallel_marking_threads, false, true);
 640     if (_parallel_workers == NULL) {
 641       vm_exit_during_initialization("Failed necessary allocation.");
 642     } else {
 643       _parallel_workers->initialize_workers();
 644     }
 645   }
 646 
 647   if (FLAG_IS_DEFAULT(MarkStackSize)) {
 648     uintx mark_stack_size =
 649       MIN2(MarkStackSizeMax,
 650           MAX2(MarkStackSize, (uintx) (parallel_marking_threads() * TASKQUEUE_SIZE)));
 651     // Verify that the calculated value for MarkStackSize is in range.
 652     // It would be nice to use the private utility routine from Arguments.
 653     if (!(mark_stack_size >= 1 && mark_stack_size <= MarkStackSizeMax)) {
 654       warning("Invalid value calculated for MarkStackSize (" UINTX_FORMAT "): "
 655               "must be between " UINTX_FORMAT " and " UINTX_FORMAT,
 656               mark_stack_size, (uintx) 1, MarkStackSizeMax);
 657       return;
 658     }
 659     FLAG_SET_ERGO(uintx, MarkStackSize, mark_stack_size);
 660   } else {
 661     // Verify MarkStackSize is in range.
 662     if (FLAG_IS_CMDLINE(MarkStackSize)) {
 663       if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
 664         if (!(MarkStackSize >= 1 && MarkStackSize <= MarkStackSizeMax)) {
 665           warning("Invalid value specified for MarkStackSize (" UINTX_FORMAT "): "
 666                   "must be between " UINTX_FORMAT " and " UINTX_FORMAT,
 667                   MarkStackSize, (uintx) 1, MarkStackSizeMax);
 668           return;
 669         }
 670       } else if (FLAG_IS_CMDLINE(MarkStackSizeMax)) {
 671         if (!(MarkStackSize >= 1 && MarkStackSize <= MarkStackSizeMax)) {
 672           warning("Invalid value specified for MarkStackSize (" UINTX_FORMAT ")"
 673                   " or for MarkStackSizeMax (" UINTX_FORMAT ")",
 674                   MarkStackSize, MarkStackSizeMax);
 675           return;
 676         }
 677       }
 678     }
 679   }
 680 
 681   if (!_markStack.allocate(MarkStackSize)) {
 682     warning("Failed to allocate CM marking stack");
 683     return;
 684   }
 685 
 686   _tasks = NEW_C_HEAP_ARRAY(CMTask*, _max_worker_id, mtGC);
 687   _accum_task_vtime = NEW_C_HEAP_ARRAY(double, _max_worker_id, mtGC);
 688 
 689   _count_card_bitmaps = NEW_C_HEAP_ARRAY(BitMap,  _max_worker_id, mtGC);
 690   _count_marked_bytes = NEW_C_HEAP_ARRAY(size_t*, _max_worker_id, mtGC);
 691 
 692   BitMap::idx_t card_bm_size = _card_bm.size();
 693 
 694   // so that the assertion in MarkingTaskQueue::task_queue doesn't fail
 695   _active_tasks = _max_worker_id;
 696 
 697   size_t max_regions = (size_t) _g1h->max_regions();
 698   for (uint i = 0; i < _max_worker_id; ++i) {
 699     CMTaskQueue* task_queue = new CMTaskQueue();
 700     task_queue->initialize();
 701     _task_queues->register_queue(i, task_queue);
 702 
 703     _count_card_bitmaps[i] = BitMap(card_bm_size, false);
 704     _count_marked_bytes[i] = NEW_C_HEAP_ARRAY(size_t, max_regions, mtGC);
 705 
 706     _tasks[i] = new CMTask(i, this,
 707                            _count_marked_bytes[i],
 708                            &_count_card_bitmaps[i],
 709                            task_queue, _task_queues);
 710 
 711     _accum_task_vtime[i] = 0.0;
 712   }
 713 
 714   // Calculate the card number for the bottom of the heap. Used
 715   // in biasing indexes into the accounting card bitmaps.
 716   _heap_bottom_card_num =
 717     intptr_t(uintptr_t(_g1h->reserved_region().start()) >>
 718                                 CardTableModRefBS::card_shift);
 719 
 720   // Clear all the liveness counting data
 721   clear_all_count_data();
 722 
 723   // so that the call below can read a sensible value
 724   _heap_start = (HeapWord*) heap_rs.base();
 725   set_non_marking_state();
 726   _completed_initialization = true;
 727 }
 728 
 729 void ConcurrentMark::update_g1_committed(bool force) {
 730   // If concurrent marking is not in progress, then we do not need to
 731   // update _heap_end.
 732   if (!concurrent_marking_in_progress() && !force) return;
 733 
 734   MemRegion committed = _g1h->g1_committed();
 735   assert(committed.start() == _heap_start, "start shouldn't change");
 736   HeapWord* new_end = committed.end();
 737   if (new_end > _heap_end) {
 738     // The heap has been expanded.
 739 
 740     _heap_end = new_end;
 741   }
 742   // Notice that the heap can also shrink. However, this only happens
 743   // during a Full GC (at least currently) and the entire marking
 744   // phase will bail out and the task will not be restarted. So, let's
 745   // do nothing.
 746 }
 747 
 748 void ConcurrentMark::reset() {
 749   // Starting values for these two. This should be called in a STW
 750   // phase. CM will be notified of any future g1_committed expansions
 751   // will be at the end of evacuation pauses, when tasks are
 752   // inactive.
 753   MemRegion committed = _g1h->g1_committed();
 754   _heap_start = committed.start();
 755   _heap_end   = committed.end();
 756 
 757   // Separated the asserts so that we know which one fires.
 758   assert(_heap_start != NULL, "heap bounds should look ok");
 759   assert(_heap_end != NULL, "heap bounds should look ok");
 760   assert(_heap_start < _heap_end, "heap bounds should look ok");
 761 
 762   // Reset all the marking data structures and any necessary flags
 763   reset_marking_state();
 764 
 765   if (verbose_low()) {
 766     gclog_or_tty->print_cr("[global] resetting");
 767   }
 768 
 769   // We do reset all of them, since different phases will use
 770   // different number of active threads. So, it's easiest to have all
 771   // of them ready.
 772   for (uint i = 0; i < _max_worker_id; ++i) {
 773     _tasks[i]->reset(_nextMarkBitMap);
 774   }
 775 
 776   // we need this to make sure that the flag is on during the evac
 777   // pause with initial mark piggy-backed
 778   set_concurrent_marking_in_progress();
 779 }
 780 
 781 
 782 void ConcurrentMark::reset_marking_state(bool clear_overflow) {
 783   _markStack.set_should_expand();
 784   _markStack.setEmpty();        // Also clears the _markStack overflow flag
 785   if (clear_overflow) {
 786     clear_has_overflown();
 787   } else {
 788     assert(has_overflown(), "pre-condition");
 789   }
 790   _finger = _heap_start;
 791 
 792   for (uint i = 0; i < _max_worker_id; ++i) {
 793     CMTaskQueue* queue = _task_queues->queue(i);
 794     queue->set_empty();
 795   }
 796 }
 797 
 798 void ConcurrentMark::set_concurrency(uint active_tasks) {
 799   assert(active_tasks <= _max_worker_id, "we should not have more");
 800 
 801   _active_tasks = active_tasks;
 802   // Need to update the three data structures below according to the
 803   // number of active threads for this phase.
 804   _terminator   = ParallelTaskTerminator((int) active_tasks, _task_queues);
 805   _first_overflow_barrier_sync.set_n_workers((int) active_tasks);
 806   _second_overflow_barrier_sync.set_n_workers((int) active_tasks);
 807 }
 808 
 809 void ConcurrentMark::set_concurrency_and_phase(uint active_tasks, bool concurrent) {
 810   set_concurrency(active_tasks);
 811 
 812   _concurrent = concurrent;
 813   // We propagate this to all tasks, not just the active ones.
 814   for (uint i = 0; i < _max_worker_id; ++i)
 815     _tasks[i]->set_concurrent(concurrent);
 816 
 817   if (concurrent) {
 818     set_concurrent_marking_in_progress();
 819   } else {
 820     // We currently assume that the concurrent flag has been set to
 821     // false before we start remark. At this point we should also be
 822     // in a STW phase.
 823     assert(!concurrent_marking_in_progress(), "invariant");
 824     assert(out_of_regions(),
 825            err_msg("only way to get here: _finger: "PTR_FORMAT", _heap_end: "PTR_FORMAT,
 826                    p2i(_finger), p2i(_heap_end)));
 827     update_g1_committed(true);
 828   }
 829 }
 830 
 831 void ConcurrentMark::set_non_marking_state() {
 832   // We set the global marking state to some default values when we're
 833   // not doing marking.
 834   reset_marking_state();
 835   _active_tasks = 0;
 836   clear_concurrent_marking_in_progress();
 837 }
 838 
 839 ConcurrentMark::~ConcurrentMark() {
 840   // The ConcurrentMark instance is never freed.
 841   ShouldNotReachHere();
 842 }
 843 
 844 void ConcurrentMark::clearNextBitmap() {
 845   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 846   G1CollectorPolicy* g1p = g1h->g1_policy();
 847 
 848   // Make sure that the concurrent mark thread looks to still be in
 849   // the current cycle.
 850   guarantee(cmThread()->during_cycle(), "invariant");
 851 
 852   // We are finishing up the current cycle by clearing the next
 853   // marking bitmap and getting it ready for the next cycle. During
 854   // this time no other cycle can start. So, let's make sure that this
 855   // is the case.
 856   guarantee(!g1h->mark_in_progress(), "invariant");
 857 
 858   // clear the mark bitmap (no grey objects to start with).
 859   // We need to do this in chunks and offer to yield in between
 860   // each chunk.
 861   HeapWord* start  = _nextMarkBitMap->startWord();
 862   HeapWord* end    = _nextMarkBitMap->endWord();
 863   HeapWord* cur    = start;
 864   size_t chunkSize = M;
 865   while (cur < end) {
 866     HeapWord* next = cur + chunkSize;
 867     if (next > end) {
 868       next = end;
 869     }
 870     MemRegion mr(cur,next);
 871     _nextMarkBitMap->clearRange(mr);
 872     cur = next;
 873     do_yield_check();
 874 
 875     // Repeat the asserts from above. We'll do them as asserts here to
 876     // minimize their overhead on the product. However, we'll have
 877     // them as guarantees at the beginning / end of the bitmap
 878     // clearing to get some checking in the product.
 879     assert(cmThread()->during_cycle(), "invariant");
 880     assert(!g1h->mark_in_progress(), "invariant");
 881   }
 882 
 883   // Clear the liveness counting data
 884   clear_all_count_data();
 885 
 886   // Repeat the asserts from above.
 887   guarantee(cmThread()->during_cycle(), "invariant");
 888   guarantee(!g1h->mark_in_progress(), "invariant");
 889 }
 890 
 891 class NoteStartOfMarkHRClosure: public HeapRegionClosure {
 892 public:
 893   bool doHeapRegion(HeapRegion* r) {
 894     if (!r->continuesHumongous()) {
 895       r->note_start_of_marking();
 896     }
 897     return false;
 898   }
 899 };
 900 
 901 void ConcurrentMark::checkpointRootsInitialPre() {
 902   G1CollectedHeap*   g1h = G1CollectedHeap::heap();
 903   G1CollectorPolicy* g1p = g1h->g1_policy();
 904 
 905   _has_aborted = false;
 906 
 907 #ifndef PRODUCT
 908   if (G1PrintReachableAtInitialMark) {
 909     print_reachable("at-cycle-start",
 910                     VerifyOption_G1UsePrevMarking, true /* all */);
 911   }
 912 #endif
 913 
 914   // Initialize marking structures. This has to be done in a STW phase.
 915   reset();
 916 
 917   // For each region note start of marking.
 918   NoteStartOfMarkHRClosure startcl;
 919   g1h->heap_region_iterate(&startcl);
 920 }
 921 
 922 
 923 void ConcurrentMark::checkpointRootsInitialPost() {
 924   G1CollectedHeap*   g1h = G1CollectedHeap::heap();
 925 
 926   // If we force an overflow during remark, the remark operation will
 927   // actually abort and we'll restart concurrent marking. If we always
 928   // force an overflow during remark we'll never actually complete the
 929   // marking phase. So, we initialize this here, at the start of the
 930   // cycle, so that at the remaining overflow number will decrease at
 931   // every remark and we'll eventually not need to cause one.
 932   force_overflow_stw()->init();
 933 
 934   // Start Concurrent Marking weak-reference discovery.
 935   ReferenceProcessor* rp = g1h->ref_processor_cm();
 936   // enable ("weak") refs discovery
 937   rp->enable_discovery(true /*verify_disabled*/, true /*verify_no_refs*/);
 938   rp->setup_policy(false); // snapshot the soft ref policy to be used in this cycle
 939 
 940   SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
 941   // This is the start of  the marking cycle, we're expected all
 942   // threads to have SATB queues with active set to false.
 943   satb_mq_set.set_active_all_threads(true, /* new active value */
 944                                      false /* expected_active */);
 945 
 946   _root_regions.prepare_for_scan();
 947 
 948   // update_g1_committed() will be called at the end of an evac pause
 949   // when marking is on. So, it's also called at the end of the
 950   // initial-mark pause to update the heap end, if the heap expands
 951   // during it. No need to call it here.
 952 }
 953 
 954 /*
 955  * Notice that in the next two methods, we actually leave the STS
 956  * during the barrier sync and join it immediately afterwards. If we
 957  * do not do this, the following deadlock can occur: one thread could
 958  * be in the barrier sync code, waiting for the other thread to also
 959  * sync up, whereas another one could be trying to yield, while also
 960  * waiting for the other threads to sync up too.
 961  *
 962  * Note, however, that this code is also used during remark and in
 963  * this case we should not attempt to leave / enter the STS, otherwise
 964  * we'll either hit an assert (debug / fastdebug) or deadlock
 965  * (product). So we should only leave / enter the STS if we are
 966  * operating concurrently.
 967  *
 968  * Because the thread that does the sync barrier has left the STS, it
 969  * is possible to be suspended for a Full GC or an evacuation pause
 970  * could occur. This is actually safe, since the entering the sync
 971  * barrier is one of the last things do_marking_step() does, and it
 972  * doesn't manipulate any data structures afterwards.
 973  */
 974 
 975 void ConcurrentMark::enter_first_sync_barrier(uint worker_id) {
 976   if (verbose_low()) {
 977     gclog_or_tty->print_cr("[%u] entering first barrier", worker_id);
 978   }
 979 
 980   if (concurrent()) {
 981     SuspendibleThreadSet::leave();
 982   }
 983 
 984   bool barrier_aborted = !_first_overflow_barrier_sync.enter();
 985 
 986   if (concurrent()) {
 987     SuspendibleThreadSet::join();
 988   }
 989   // at this point everyone should have synced up and not be doing any
 990   // more work
 991 
 992   if (verbose_low()) {
 993     if (barrier_aborted) {
 994       gclog_or_tty->print_cr("[%u] aborted first barrier", worker_id);
 995     } else {
 996       gclog_or_tty->print_cr("[%u] leaving first barrier", worker_id);
 997     }
 998   }
 999 
1000   if (barrier_aborted) {
1001     // If the barrier aborted we ignore the overflow condition and
1002     // just abort the whole marking phase as quickly as possible.
1003     return;
1004   }
1005 
1006   // If we're executing the concurrent phase of marking, reset the marking
1007   // state; otherwise the marking state is reset after reference processing,
1008   // during the remark pause.
1009   // If we reset here as a result of an overflow during the remark we will
1010   // see assertion failures from any subsequent set_concurrency_and_phase()
1011   // calls.
1012   if (concurrent()) {
1013     // let the task associated with with worker 0 do this
1014     if (worker_id == 0) {
1015       // task 0 is responsible for clearing the global data structures
1016       // We should be here because of an overflow. During STW we should
1017       // not clear the overflow flag since we rely on it being true when
1018       // we exit this method to abort the pause and restart concurrent
1019       // marking.
1020       reset_marking_state(true /* clear_overflow */);
1021       force_overflow()->update();
1022 
1023       if (G1Log::fine()) {
1024         gclog_or_tty->date_stamp(PrintGCDateStamps);
1025         gclog_or_tty->stamp(PrintGCTimeStamps);
1026         gclog_or_tty->print_cr("[GC concurrent-mark-reset-for-overflow]");
1027       }
1028     }
1029   }
1030 
1031   // after this, each task should reset its own data structures then
1032   // then go into the second barrier
1033 }
1034 
1035 void ConcurrentMark::enter_second_sync_barrier(uint worker_id) {
1036   if (verbose_low()) {
1037     gclog_or_tty->print_cr("[%u] entering second barrier", worker_id);
1038   }
1039 
1040   if (concurrent()) {
1041     SuspendibleThreadSet::leave();
1042   }
1043 
1044   bool barrier_aborted = !_second_overflow_barrier_sync.enter();
1045 
1046   if (concurrent()) {
1047     SuspendibleThreadSet::join();
1048   }
1049   // at this point everything should be re-initialized and ready to go
1050 
1051   if (verbose_low()) {
1052     if (barrier_aborted) {
1053       gclog_or_tty->print_cr("[%u] aborted second barrier", worker_id);
1054     } else {
1055       gclog_or_tty->print_cr("[%u] leaving second barrier", worker_id);
1056     }
1057   }
1058 }
1059 
1060 #ifndef PRODUCT
1061 void ForceOverflowSettings::init() {
1062   _num_remaining = G1ConcMarkForceOverflow;
1063   _force = false;
1064   update();
1065 }
1066 
1067 void ForceOverflowSettings::update() {
1068   if (_num_remaining > 0) {
1069     _num_remaining -= 1;
1070     _force = true;
1071   } else {
1072     _force = false;
1073   }
1074 }
1075 
1076 bool ForceOverflowSettings::should_force() {
1077   if (_force) {
1078     _force = false;
1079     return true;
1080   } else {
1081     return false;
1082   }
1083 }
1084 #endif // !PRODUCT
1085 
1086 class CMConcurrentMarkingTask: public AbstractGangTask {
1087 private:
1088   ConcurrentMark*       _cm;
1089   ConcurrentMarkThread* _cmt;
1090 
1091 public:
1092   void work(uint worker_id) {
1093     assert(Thread::current()->is_ConcurrentGC_thread(),
1094            "this should only be done by a conc GC thread");
1095     ResourceMark rm;
1096 
1097     double start_vtime = os::elapsedVTime();
1098 
1099     SuspendibleThreadSet::join();
1100 
1101     assert(worker_id < _cm->active_tasks(), "invariant");
1102     CMTask* the_task = _cm->task(worker_id);
1103     the_task->record_start_time();
1104     if (!_cm->has_aborted()) {
1105       do {
1106         double start_vtime_sec = os::elapsedVTime();
1107         double start_time_sec = os::elapsedTime();
1108         double mark_step_duration_ms = G1ConcMarkStepDurationMillis;
1109 
1110         the_task->do_marking_step(mark_step_duration_ms,
1111                                   true  /* do_termination */,
1112                                   false /* is_serial*/);
1113 
1114         double end_time_sec = os::elapsedTime();
1115         double end_vtime_sec = os::elapsedVTime();
1116         double elapsed_vtime_sec = end_vtime_sec - start_vtime_sec;
1117         double elapsed_time_sec = end_time_sec - start_time_sec;
1118         _cm->clear_has_overflown();
1119 
1120         bool ret = _cm->do_yield_check(worker_id);
1121 
1122         jlong sleep_time_ms;
1123         if (!_cm->has_aborted() && the_task->has_aborted()) {
1124           sleep_time_ms =
1125             (jlong) (elapsed_vtime_sec * _cm->sleep_factor() * 1000.0);
1126           SuspendibleThreadSet::leave();
1127           os::sleep(Thread::current(), sleep_time_ms, false);
1128           SuspendibleThreadSet::join();
1129         }
1130         double end_time2_sec = os::elapsedTime();
1131         double elapsed_time2_sec = end_time2_sec - start_time_sec;
1132 
1133 #if 0
1134           gclog_or_tty->print_cr("CM: elapsed %1.4lf ms, sleep %1.4lf ms, "
1135                                  "overhead %1.4lf",
1136                                  elapsed_vtime_sec * 1000.0, (double) sleep_time_ms,
1137                                  the_task->conc_overhead(os::elapsedTime()) * 8.0);
1138           gclog_or_tty->print_cr("elapsed time %1.4lf ms, time 2: %1.4lf ms",
1139                                  elapsed_time_sec * 1000.0, elapsed_time2_sec * 1000.0);
1140 #endif
1141       } while (!_cm->has_aborted() && the_task->has_aborted());
1142     }
1143     the_task->record_end_time();
1144     guarantee(!the_task->has_aborted() || _cm->has_aborted(), "invariant");
1145 
1146     SuspendibleThreadSet::leave();
1147 
1148     double end_vtime = os::elapsedVTime();
1149     _cm->update_accum_task_vtime(worker_id, end_vtime - start_vtime);
1150   }
1151 
1152   CMConcurrentMarkingTask(ConcurrentMark* cm,
1153                           ConcurrentMarkThread* cmt) :
1154       AbstractGangTask("Concurrent Mark"), _cm(cm), _cmt(cmt) { }
1155 
1156   ~CMConcurrentMarkingTask() { }
1157 };
1158 
1159 // Calculates the number of active workers for a concurrent
1160 // phase.
1161 uint ConcurrentMark::calc_parallel_marking_threads() {
1162   if (G1CollectedHeap::use_parallel_gc_threads()) {
1163     uint n_conc_workers = 0;
1164     if (!UseDynamicNumberOfGCThreads ||
1165         (!FLAG_IS_DEFAULT(ConcGCThreads) &&
1166          !ForceDynamicNumberOfGCThreads)) {
1167       n_conc_workers = max_parallel_marking_threads();
1168     } else {
1169       n_conc_workers =
1170         AdaptiveSizePolicy::calc_default_active_workers(
1171                                      max_parallel_marking_threads(),
1172                                      1, /* Minimum workers */
1173                                      parallel_marking_threads(),
1174                                      Threads::number_of_non_daemon_threads());
1175       // Don't scale down "n_conc_workers" by scale_parallel_threads() because
1176       // that scaling has already gone into "_max_parallel_marking_threads".
1177     }
1178     assert(n_conc_workers > 0, "Always need at least 1");
1179     return n_conc_workers;
1180   }
1181   // If we are not running with any parallel GC threads we will not
1182   // have spawned any marking threads either. Hence the number of
1183   // concurrent workers should be 0.
1184   return 0;
1185 }
1186 
1187 void ConcurrentMark::scanRootRegion(HeapRegion* hr, uint worker_id) {
1188   // Currently, only survivors can be root regions.
1189   assert(hr->next_top_at_mark_start() == hr->bottom(), "invariant");
1190   G1RootRegionScanClosure cl(_g1h, this, worker_id);
1191 
1192   const uintx interval = PrefetchScanIntervalInBytes;
1193   HeapWord* curr = hr->bottom();
1194   const HeapWord* end = hr->top();
1195   while (curr < end) {
1196     Prefetch::read(curr, interval);
1197     oop obj = oop(curr);
1198     int size = obj->oop_iterate(&cl);
1199     assert(size == obj->size(), "sanity");
1200     curr += size;
1201   }
1202 }
1203 
1204 class CMRootRegionScanTask : public AbstractGangTask {
1205 private:
1206   ConcurrentMark* _cm;
1207 
1208 public:
1209   CMRootRegionScanTask(ConcurrentMark* cm) :
1210     AbstractGangTask("Root Region Scan"), _cm(cm) { }
1211 
1212   void work(uint worker_id) {
1213     assert(Thread::current()->is_ConcurrentGC_thread(),
1214            "this should only be done by a conc GC thread");
1215 
1216     CMRootRegions* root_regions = _cm->root_regions();
1217     HeapRegion* hr = root_regions->claim_next();
1218     while (hr != NULL) {
1219       _cm->scanRootRegion(hr, worker_id);
1220       hr = root_regions->claim_next();
1221     }
1222   }
1223 };
1224 
1225 void ConcurrentMark::scanRootRegions() {
1226   // scan_in_progress() will have been set to true only if there was
1227   // at least one root region to scan. So, if it's false, we
1228   // should not attempt to do any further work.
1229   if (root_regions()->scan_in_progress()) {
1230     _parallel_marking_threads = calc_parallel_marking_threads();
1231     assert(parallel_marking_threads() <= max_parallel_marking_threads(),
1232            "Maximum number of marking threads exceeded");
1233     uint active_workers = MAX2(1U, parallel_marking_threads());
1234 
1235     CMRootRegionScanTask task(this);
1236     if (use_parallel_marking_threads()) {
1237       _parallel_workers->set_active_workers((int) active_workers);
1238       _parallel_workers->run_task(&task);
1239     } else {
1240       task.work(0);
1241     }
1242 
1243     // It's possible that has_aborted() is true here without actually
1244     // aborting the survivor scan earlier. This is OK as it's
1245     // mainly used for sanity checking.
1246     root_regions()->scan_finished();
1247   }
1248 }
1249 
1250 void ConcurrentMark::markFromRoots() {
1251   // we might be tempted to assert that:
1252   // assert(asynch == !SafepointSynchronize::is_at_safepoint(),
1253   //        "inconsistent argument?");
1254   // However that wouldn't be right, because it's possible that
1255   // a safepoint is indeed in progress as a younger generation
1256   // stop-the-world GC happens even as we mark in this generation.
1257 
1258   _restart_for_overflow = false;
1259   force_overflow_conc()->init();
1260 
1261   // _g1h has _n_par_threads
1262   _parallel_marking_threads = calc_parallel_marking_threads();
1263   assert(parallel_marking_threads() <= max_parallel_marking_threads(),
1264     "Maximum number of marking threads exceeded");
1265 
1266   uint active_workers = MAX2(1U, parallel_marking_threads());
1267 
1268   // Parallel task terminator is set in "set_concurrency_and_phase()"
1269   set_concurrency_and_phase(active_workers, true /* concurrent */);
1270 
1271   CMConcurrentMarkingTask markingTask(this, cmThread());
1272   if (use_parallel_marking_threads()) {
1273     _parallel_workers->set_active_workers((int)active_workers);
1274     // Don't set _n_par_threads because it affects MT in process_strong_roots()
1275     // and the decisions on that MT processing is made elsewhere.
1276     assert(_parallel_workers->active_workers() > 0, "Should have been set");
1277     _parallel_workers->run_task(&markingTask);
1278   } else {
1279     markingTask.work(0);
1280   }
1281   print_stats();
1282 }
1283 
1284 void ConcurrentMark::checkpointRootsFinal(bool clear_all_soft_refs) {
1285   // world is stopped at this checkpoint
1286   assert(SafepointSynchronize::is_at_safepoint(),
1287          "world should be stopped");
1288 
1289   G1CollectedHeap* g1h = G1CollectedHeap::heap();
1290 
1291   // If a full collection has happened, we shouldn't do this.
1292   if (has_aborted()) {
1293     g1h->set_marking_complete(); // So bitmap clearing isn't confused
1294     return;
1295   }
1296 
1297   SvcGCMarker sgcm(SvcGCMarker::OTHER);
1298 
1299   if (VerifyDuringGC) {
1300     HandleMark hm;  // handle scope
1301     Universe::heap()->prepare_for_verify();
1302     Universe::verify(VerifyOption_G1UsePrevMarking,
1303                      " VerifyDuringGC:(before)");
1304   }
1305   g1h->check_bitmaps("Remark Start");
1306 
1307   G1CollectorPolicy* g1p = g1h->g1_policy();
1308   g1p->record_concurrent_mark_remark_start();
1309 
1310   double start = os::elapsedTime();
1311 
1312   checkpointRootsFinalWork();
1313 
1314   double mark_work_end = os::elapsedTime();
1315 
1316   weakRefsWork(clear_all_soft_refs);
1317 
1318   if (has_overflown()) {
1319     // Oops.  We overflowed.  Restart concurrent marking.
1320     _restart_for_overflow = true;
1321     if (G1TraceMarkStackOverflow) {
1322       gclog_or_tty->print_cr("\nRemark led to restart for overflow.");
1323     }
1324 
1325     // Verify the heap w.r.t. the previous marking bitmap.
1326     if (VerifyDuringGC) {
1327       HandleMark hm;  // handle scope
1328       Universe::heap()->prepare_for_verify();
1329       Universe::verify(VerifyOption_G1UsePrevMarking,
1330                        " VerifyDuringGC:(overflow)");
1331     }
1332 
1333     // Clear the marking state because we will be restarting
1334     // marking due to overflowing the global mark stack.
1335     reset_marking_state();
1336   } else {
1337     // Aggregate the per-task counting data that we have accumulated
1338     // while marking.
1339     aggregate_count_data();
1340 
1341     SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
1342     // We're done with marking.
1343     // This is the end of  the marking cycle, we're expected all
1344     // threads to have SATB queues with active set to true.
1345     satb_mq_set.set_active_all_threads(false, /* new active value */
1346                                        true /* expected_active */);
1347 
1348     if (VerifyDuringGC) {
1349       HandleMark hm;  // handle scope
1350       Universe::heap()->prepare_for_verify();
1351       Universe::verify(VerifyOption_G1UseNextMarking,
1352                        " VerifyDuringGC:(after)");
1353     }
1354     g1h->check_bitmaps("Remark End");
1355     assert(!restart_for_overflow(), "sanity");
1356     // Completely reset the marking state since marking completed
1357     set_non_marking_state();
1358   }
1359 
1360   // Expand the marking stack, if we have to and if we can.
1361   if (_markStack.should_expand()) {
1362     _markStack.expand();
1363   }
1364 
1365   // Statistics
1366   double now = os::elapsedTime();
1367   _remark_mark_times.add((mark_work_end - start) * 1000.0);
1368   _remark_weak_ref_times.add((now - mark_work_end) * 1000.0);
1369   _remark_times.add((now - start) * 1000.0);
1370 
1371   g1p->record_concurrent_mark_remark_end();
1372 
1373   G1CMIsAliveClosure is_alive(g1h);
1374   g1h->gc_tracer_cm()->report_object_count_after_gc(&is_alive);
1375 }
1376 
1377 // Base class of the closures that finalize and verify the
1378 // liveness counting data.
1379 class CMCountDataClosureBase: public HeapRegionClosure {
1380 protected:
1381   G1CollectedHeap* _g1h;
1382   ConcurrentMark* _cm;
1383   CardTableModRefBS* _ct_bs;
1384 
1385   BitMap* _region_bm;
1386   BitMap* _card_bm;
1387 
1388   // Takes a region that's not empty (i.e., it has at least one
1389   // live object in it and sets its corresponding bit on the region
1390   // bitmap to 1. If the region is "starts humongous" it will also set
1391   // to 1 the bits on the region bitmap that correspond to its
1392   // associated "continues humongous" regions.
1393   void set_bit_for_region(HeapRegion* hr) {
1394     assert(!hr->continuesHumongous(), "should have filtered those out");
1395 
1396     BitMap::idx_t index = (BitMap::idx_t) hr->hrs_index();
1397     if (!hr->startsHumongous()) {
1398       // Normal (non-humongous) case: just set the bit.
1399       _region_bm->par_at_put(index, true);
1400     } else {
1401       // Starts humongous case: calculate how many regions are part of
1402       // this humongous region and then set the bit range.
1403       BitMap::idx_t end_index = (BitMap::idx_t) hr->last_hc_index();
1404       _region_bm->par_at_put_range(index, end_index, true);
1405     }
1406   }
1407 
1408 public:
1409   CMCountDataClosureBase(G1CollectedHeap* g1h,
1410                          BitMap* region_bm, BitMap* card_bm):
1411     _g1h(g1h), _cm(g1h->concurrent_mark()),
1412     _ct_bs((CardTableModRefBS*) (g1h->barrier_set())),
1413     _region_bm(region_bm), _card_bm(card_bm) { }
1414 };
1415 
1416 // Closure that calculates the # live objects per region. Used
1417 // for verification purposes during the cleanup pause.
1418 class CalcLiveObjectsClosure: public CMCountDataClosureBase {
1419   CMBitMapRO* _bm;
1420   size_t _region_marked_bytes;
1421 
1422 public:
1423   CalcLiveObjectsClosure(CMBitMapRO *bm, G1CollectedHeap* g1h,
1424                          BitMap* region_bm, BitMap* card_bm) :
1425     CMCountDataClosureBase(g1h, region_bm, card_bm),
1426     _bm(bm), _region_marked_bytes(0) { }
1427 
1428   bool doHeapRegion(HeapRegion* hr) {
1429 
1430     if (hr->continuesHumongous()) {
1431       // We will ignore these here and process them when their
1432       // associated "starts humongous" region is processed (see
1433       // set_bit_for_heap_region()). Note that we cannot rely on their
1434       // associated "starts humongous" region to have their bit set to
1435       // 1 since, due to the region chunking in the parallel region
1436       // iteration, a "continues humongous" region might be visited
1437       // before its associated "starts humongous".
1438       return false;
1439     }
1440 
1441     HeapWord* ntams = hr->next_top_at_mark_start();
1442     HeapWord* start = hr->bottom();
1443 
1444     assert(start <= hr->end() && start <= ntams && ntams <= hr->end(),
1445            err_msg("Preconditions not met - "
1446                    "start: "PTR_FORMAT", ntams: "PTR_FORMAT", end: "PTR_FORMAT,
1447                    p2i(start), p2i(ntams), p2i(hr->end())));
1448 
1449     // Find the first marked object at or after "start".
1450     start = _bm->getNextMarkedWordAddress(start, ntams);
1451 
1452     size_t marked_bytes = 0;
1453 
1454     while (start < ntams) {
1455       oop obj = oop(start);
1456       int obj_sz = obj->size();
1457       HeapWord* obj_end = start + obj_sz;
1458 
1459       BitMap::idx_t start_idx = _cm->card_bitmap_index_for(start);
1460       BitMap::idx_t end_idx = _cm->card_bitmap_index_for(obj_end);
1461 
1462       // Note: if we're looking at the last region in heap - obj_end
1463       // could be actually just beyond the end of the heap; end_idx
1464       // will then correspond to a (non-existent) card that is also
1465       // just beyond the heap.
1466       if (_g1h->is_in_g1_reserved(obj_end) && !_ct_bs->is_card_aligned(obj_end)) {
1467         // end of object is not card aligned - increment to cover
1468         // all the cards spanned by the object
1469         end_idx += 1;
1470       }
1471 
1472       // Set the bits in the card BM for the cards spanned by this object.
1473       _cm->set_card_bitmap_range(_card_bm, start_idx, end_idx, true /* is_par */);
1474 
1475       // Add the size of this object to the number of marked bytes.
1476       marked_bytes += (size_t)obj_sz * HeapWordSize;
1477 
1478       // Find the next marked object after this one.
1479       start = _bm->getNextMarkedWordAddress(obj_end, ntams);
1480     }
1481 
1482     // Mark the allocated-since-marking portion...
1483     HeapWord* top = hr->top();
1484     if (ntams < top) {
1485       BitMap::idx_t start_idx = _cm->card_bitmap_index_for(ntams);
1486       BitMap::idx_t end_idx = _cm->card_bitmap_index_for(top);
1487 
1488       // Note: if we're looking at the last region in heap - top
1489       // could be actually just beyond the end of the heap; end_idx
1490       // will then correspond to a (non-existent) card that is also
1491       // just beyond the heap.
1492       if (_g1h->is_in_g1_reserved(top) && !_ct_bs->is_card_aligned(top)) {
1493         // end of object is not card aligned - increment to cover
1494         // all the cards spanned by the object
1495         end_idx += 1;
1496       }
1497       _cm->set_card_bitmap_range(_card_bm, start_idx, end_idx, true /* is_par */);
1498 
1499       // This definitely means the region has live objects.
1500       set_bit_for_region(hr);
1501     }
1502 
1503     // Update the live region bitmap.
1504     if (marked_bytes > 0) {
1505       set_bit_for_region(hr);
1506     }
1507 
1508     // Set the marked bytes for the current region so that
1509     // it can be queried by a calling verification routine
1510     _region_marked_bytes = marked_bytes;
1511 
1512     return false;
1513   }
1514 
1515   size_t region_marked_bytes() const { return _region_marked_bytes; }
1516 };
1517 
1518 // Heap region closure used for verifying the counting data
1519 // that was accumulated concurrently and aggregated during
1520 // the remark pause. This closure is applied to the heap
1521 // regions during the STW cleanup pause.
1522 
1523 class VerifyLiveObjectDataHRClosure: public HeapRegionClosure {
1524   G1CollectedHeap* _g1h;
1525   ConcurrentMark* _cm;
1526   CalcLiveObjectsClosure _calc_cl;
1527   BitMap* _region_bm;   // Region BM to be verified
1528   BitMap* _card_bm;     // Card BM to be verified
1529   bool _verbose;        // verbose output?
1530 
1531   BitMap* _exp_region_bm; // Expected Region BM values
1532   BitMap* _exp_card_bm;   // Expected card BM values
1533 
1534   int _failures;
1535 
1536 public:
1537   VerifyLiveObjectDataHRClosure(G1CollectedHeap* g1h,
1538                                 BitMap* region_bm,
1539                                 BitMap* card_bm,
1540                                 BitMap* exp_region_bm,
1541                                 BitMap* exp_card_bm,
1542                                 bool verbose) :
1543     _g1h(g1h), _cm(g1h->concurrent_mark()),
1544     _calc_cl(_cm->nextMarkBitMap(), g1h, exp_region_bm, exp_card_bm),
1545     _region_bm(region_bm), _card_bm(card_bm), _verbose(verbose),
1546     _exp_region_bm(exp_region_bm), _exp_card_bm(exp_card_bm),
1547     _failures(0) { }
1548 
1549   int failures() const { return _failures; }
1550 
1551   bool doHeapRegion(HeapRegion* hr) {
1552     if (hr->continuesHumongous()) {
1553       // We will ignore these here and process them when their
1554       // associated "starts humongous" region is processed (see
1555       // set_bit_for_heap_region()). Note that we cannot rely on their
1556       // associated "starts humongous" region to have their bit set to
1557       // 1 since, due to the region chunking in the parallel region
1558       // iteration, a "continues humongous" region might be visited
1559       // before its associated "starts humongous".
1560       return false;
1561     }
1562 
1563     int failures = 0;
1564 
1565     // Call the CalcLiveObjectsClosure to walk the marking bitmap for
1566     // this region and set the corresponding bits in the expected region
1567     // and card bitmaps.
1568     bool res = _calc_cl.doHeapRegion(hr);
1569     assert(res == false, "should be continuing");
1570 
1571     MutexLockerEx x((_verbose ? ParGCRareEvent_lock : NULL),
1572                     Mutex::_no_safepoint_check_flag);
1573 
1574     // Verify the marked bytes for this region.
1575     size_t exp_marked_bytes = _calc_cl.region_marked_bytes();
1576     size_t act_marked_bytes = hr->next_marked_bytes();
1577 
1578     // We're not OK if expected marked bytes > actual marked bytes. It means
1579     // we have missed accounting some objects during the actual marking.
1580     if (exp_marked_bytes > act_marked_bytes) {
1581       if (_verbose) {
1582         gclog_or_tty->print_cr("Region %u: marked bytes mismatch: "
1583                                "expected: " SIZE_FORMAT ", actual: " SIZE_FORMAT,
1584                                hr->hrs_index(), exp_marked_bytes, act_marked_bytes);
1585       }
1586       failures += 1;
1587     }
1588 
1589     // Verify the bit, for this region, in the actual and expected
1590     // (which was just calculated) region bit maps.
1591     // We're not OK if the bit in the calculated expected region
1592     // bitmap is set and the bit in the actual region bitmap is not.
1593     BitMap::idx_t index = (BitMap::idx_t) hr->hrs_index();
1594 
1595     bool expected = _exp_region_bm->at(index);
1596     bool actual = _region_bm->at(index);
1597     if (expected && !actual) {
1598       if (_verbose) {
1599         gclog_or_tty->print_cr("Region %u: region bitmap mismatch: "
1600                                "expected: %s, actual: %s",
1601                                hr->hrs_index(),
1602                                BOOL_TO_STR(expected), BOOL_TO_STR(actual));
1603       }
1604       failures += 1;
1605     }
1606 
1607     // Verify that the card bit maps for the cards spanned by the current
1608     // region match. We have an error if we have a set bit in the expected
1609     // bit map and the corresponding bit in the actual bitmap is not set.
1610 
1611     BitMap::idx_t start_idx = _cm->card_bitmap_index_for(hr->bottom());
1612     BitMap::idx_t end_idx = _cm->card_bitmap_index_for(hr->top());
1613 
1614     for (BitMap::idx_t i = start_idx; i < end_idx; i+=1) {
1615       expected = _exp_card_bm->at(i);
1616       actual = _card_bm->at(i);
1617 
1618       if (expected && !actual) {
1619         if (_verbose) {
1620           gclog_or_tty->print_cr("Region %u: card bitmap mismatch at " SIZE_FORMAT ": "
1621                                  "expected: %s, actual: %s",
1622                                  hr->hrs_index(), i,
1623                                  BOOL_TO_STR(expected), BOOL_TO_STR(actual));
1624         }
1625         failures += 1;
1626       }
1627     }
1628 
1629     if (failures > 0 && _verbose)  {
1630       gclog_or_tty->print_cr("Region " HR_FORMAT ", ntams: " PTR_FORMAT ", "
1631                              "marked_bytes: calc/actual " SIZE_FORMAT "/" SIZE_FORMAT,
1632                              HR_FORMAT_PARAMS(hr), p2i(hr->next_top_at_mark_start()),
1633                              _calc_cl.region_marked_bytes(), hr->next_marked_bytes());
1634     }
1635 
1636     _failures += failures;
1637 
1638     // We could stop iteration over the heap when we
1639     // find the first violating region by returning true.
1640     return false;
1641   }
1642 };
1643 
1644 class G1ParVerifyFinalCountTask: public AbstractGangTask {
1645 protected:
1646   G1CollectedHeap* _g1h;
1647   ConcurrentMark* _cm;
1648   BitMap* _actual_region_bm;
1649   BitMap* _actual_card_bm;
1650 
1651   uint    _n_workers;
1652 
1653   BitMap* _expected_region_bm;
1654   BitMap* _expected_card_bm;
1655 
1656   int  _failures;
1657   bool _verbose;
1658 
1659 public:
1660   G1ParVerifyFinalCountTask(G1CollectedHeap* g1h,
1661                             BitMap* region_bm, BitMap* card_bm,
1662                             BitMap* expected_region_bm, BitMap* expected_card_bm)
1663     : AbstractGangTask("G1 verify final counting"),
1664       _g1h(g1h), _cm(_g1h->concurrent_mark()),
1665       _actual_region_bm(region_bm), _actual_card_bm(card_bm),
1666       _expected_region_bm(expected_region_bm), _expected_card_bm(expected_card_bm),
1667       _failures(0), _verbose(false),
1668       _n_workers(0) {
1669     assert(VerifyDuringGC, "don't call this otherwise");
1670 
1671     // Use the value already set as the number of active threads
1672     // in the call to run_task().
1673     if (G1CollectedHeap::use_parallel_gc_threads()) {
1674       assert( _g1h->workers()->active_workers() > 0,
1675         "Should have been previously set");
1676       _n_workers = _g1h->workers()->active_workers();
1677     } else {
1678       _n_workers = 1;
1679     }
1680 
1681     assert(_expected_card_bm->size() == _actual_card_bm->size(), "sanity");
1682     assert(_expected_region_bm->size() == _actual_region_bm->size(), "sanity");
1683 
1684     _verbose = _cm->verbose_medium();
1685   }
1686 
1687   void work(uint worker_id) {
1688     assert(worker_id < _n_workers, "invariant");
1689 
1690     VerifyLiveObjectDataHRClosure verify_cl(_g1h,
1691                                             _actual_region_bm, _actual_card_bm,
1692                                             _expected_region_bm,
1693                                             _expected_card_bm,
1694                                             _verbose);
1695 
1696     if (G1CollectedHeap::use_parallel_gc_threads()) {
1697       _g1h->heap_region_par_iterate_chunked(&verify_cl,
1698                                             worker_id,
1699                                             _n_workers,
1700                                             HeapRegion::VerifyCountClaimValue);
1701     } else {
1702       _g1h->heap_region_iterate(&verify_cl);
1703     }
1704 
1705     Atomic::add(verify_cl.failures(), &_failures);
1706   }
1707 
1708   int failures() const { return _failures; }
1709 };
1710 
1711 // Closure that finalizes the liveness counting data.
1712 // Used during the cleanup pause.
1713 // Sets the bits corresponding to the interval [NTAMS, top]
1714 // (which contains the implicitly live objects) in the
1715 // card liveness bitmap. Also sets the bit for each region,
1716 // containing live data, in the region liveness bitmap.
1717 
1718 class FinalCountDataUpdateClosure: public CMCountDataClosureBase {
1719  public:
1720   FinalCountDataUpdateClosure(G1CollectedHeap* g1h,
1721                               BitMap* region_bm,
1722                               BitMap* card_bm) :
1723     CMCountDataClosureBase(g1h, region_bm, card_bm) { }
1724 
1725   bool doHeapRegion(HeapRegion* hr) {
1726 
1727     if (hr->continuesHumongous()) {
1728       // We will ignore these here and process them when their
1729       // associated "starts humongous" region is processed (see
1730       // set_bit_for_heap_region()). Note that we cannot rely on their
1731       // associated "starts humongous" region to have their bit set to
1732       // 1 since, due to the region chunking in the parallel region
1733       // iteration, a "continues humongous" region might be visited
1734       // before its associated "starts humongous".
1735       return false;
1736     }
1737 
1738     HeapWord* ntams = hr->next_top_at_mark_start();
1739     HeapWord* top   = hr->top();
1740 
1741     assert(hr->bottom() <= ntams && ntams <= hr->end(), "Preconditions.");
1742 
1743     // Mark the allocated-since-marking portion...
1744     if (ntams < top) {
1745       // This definitely means the region has live objects.
1746       set_bit_for_region(hr);
1747 
1748       // Now set the bits in the card bitmap for [ntams, top)
1749       BitMap::idx_t start_idx = _cm->card_bitmap_index_for(ntams);
1750       BitMap::idx_t end_idx = _cm->card_bitmap_index_for(top);
1751 
1752       // Note: if we're looking at the last region in heap - top
1753       // could be actually just beyond the end of the heap; end_idx
1754       // will then correspond to a (non-existent) card that is also
1755       // just beyond the heap.
1756       if (_g1h->is_in_g1_reserved(top) && !_ct_bs->is_card_aligned(top)) {
1757         // end of object is not card aligned - increment to cover
1758         // all the cards spanned by the object
1759         end_idx += 1;
1760       }
1761 
1762       assert(end_idx <= _card_bm->size(),
1763              err_msg("oob: end_idx=  "SIZE_FORMAT", bitmap size= "SIZE_FORMAT,
1764                      end_idx, _card_bm->size()));
1765       assert(start_idx < _card_bm->size(),
1766              err_msg("oob: start_idx=  "SIZE_FORMAT", bitmap size= "SIZE_FORMAT,
1767                      start_idx, _card_bm->size()));
1768 
1769       _cm->set_card_bitmap_range(_card_bm, start_idx, end_idx, true /* is_par */);
1770     }
1771 
1772     // Set the bit for the region if it contains live data
1773     if (hr->next_marked_bytes() > 0) {
1774       set_bit_for_region(hr);
1775     }
1776 
1777     return false;
1778   }
1779 };
1780 
1781 class G1ParFinalCountTask: public AbstractGangTask {
1782 protected:
1783   G1CollectedHeap* _g1h;
1784   ConcurrentMark* _cm;
1785   BitMap* _actual_region_bm;
1786   BitMap* _actual_card_bm;
1787 
1788   uint    _n_workers;
1789 
1790 public:
1791   G1ParFinalCountTask(G1CollectedHeap* g1h, BitMap* region_bm, BitMap* card_bm)
1792     : AbstractGangTask("G1 final counting"),
1793       _g1h(g1h), _cm(_g1h->concurrent_mark()),
1794       _actual_region_bm(region_bm), _actual_card_bm(card_bm),
1795       _n_workers(0) {
1796     // Use the value already set as the number of active threads
1797     // in the call to run_task().
1798     if (G1CollectedHeap::use_parallel_gc_threads()) {
1799       assert( _g1h->workers()->active_workers() > 0,
1800         "Should have been previously set");
1801       _n_workers = _g1h->workers()->active_workers();
1802     } else {
1803       _n_workers = 1;
1804     }
1805   }
1806 
1807   void work(uint worker_id) {
1808     assert(worker_id < _n_workers, "invariant");
1809 
1810     FinalCountDataUpdateClosure final_update_cl(_g1h,
1811                                                 _actual_region_bm,
1812                                                 _actual_card_bm);
1813 
1814     if (G1CollectedHeap::use_parallel_gc_threads()) {
1815       _g1h->heap_region_par_iterate_chunked(&final_update_cl,
1816                                             worker_id,
1817                                             _n_workers,
1818                                             HeapRegion::FinalCountClaimValue);
1819     } else {
1820       _g1h->heap_region_iterate(&final_update_cl);
1821     }
1822   }
1823 };
1824 
1825 class G1ParNoteEndTask;
1826 
1827 class G1NoteEndOfConcMarkClosure : public HeapRegionClosure {
1828   G1CollectedHeap* _g1;
1829   size_t _max_live_bytes;
1830   uint _regions_claimed;
1831   size_t _freed_bytes;
1832   FreeRegionList* _local_cleanup_list;
1833   HeapRegionSetCount _old_regions_removed;
1834   HeapRegionSetCount _humongous_regions_removed;
1835   HRRSCleanupTask* _hrrs_cleanup_task;
1836   double _claimed_region_time;
1837   double _max_region_time;
1838 
1839 public:
1840   G1NoteEndOfConcMarkClosure(G1CollectedHeap* g1,
1841                              FreeRegionList* local_cleanup_list,
1842                              HRRSCleanupTask* hrrs_cleanup_task) :
1843     _g1(g1),
1844     _max_live_bytes(0), _regions_claimed(0),
1845     _freed_bytes(0),
1846     _claimed_region_time(0.0), _max_region_time(0.0),
1847     _local_cleanup_list(local_cleanup_list),
1848     _old_regions_removed(),
1849     _humongous_regions_removed(),
1850     _hrrs_cleanup_task(hrrs_cleanup_task) { }
1851 
1852   size_t freed_bytes() { return _freed_bytes; }
1853   const HeapRegionSetCount& old_regions_removed() { return _old_regions_removed; }
1854   const HeapRegionSetCount& humongous_regions_removed() { return _humongous_regions_removed; }
1855 
1856   bool doHeapRegion(HeapRegion *hr) {
1857     if (hr->continuesHumongous()) {
1858       return false;
1859     }
1860     // We use a claim value of zero here because all regions
1861     // were claimed with value 1 in the FinalCount task.
1862     _g1->reset_gc_time_stamps(hr);
1863     double start = os::elapsedTime();
1864     _regions_claimed++;
1865     hr->note_end_of_marking();
1866     _max_live_bytes += hr->max_live_bytes();
1867 
1868     if (hr->used() > 0 && hr->max_live_bytes() == 0 && !hr->is_young()) {
1869       _freed_bytes += hr->used();
1870       hr->set_containing_set(NULL);
1871       if (hr->isHumongous()) {
1872         assert(hr->startsHumongous(), "we should only see starts humongous");
1873         _humongous_regions_removed.increment(1u, hr->capacity());
1874         _g1->free_humongous_region(hr, _local_cleanup_list, true);
1875       } else {
1876         _old_regions_removed.increment(1u, hr->capacity());
1877         _g1->free_region(hr, _local_cleanup_list, true);
1878       }
1879     } else {
1880       hr->rem_set()->do_cleanup_work(_hrrs_cleanup_task);
1881     }
1882 
1883     double region_time = (os::elapsedTime() - start);
1884     _claimed_region_time += region_time;
1885     if (region_time > _max_region_time) {
1886       _max_region_time = region_time;
1887     }
1888     return false;
1889   }
1890 
1891   size_t max_live_bytes() { return _max_live_bytes; }
1892   uint regions_claimed() { return _regions_claimed; }
1893   double claimed_region_time_sec() { return _claimed_region_time; }
1894   double max_region_time_sec() { return _max_region_time; }
1895 };
1896 
1897 class G1ParNoteEndTask: public AbstractGangTask {
1898   friend class G1NoteEndOfConcMarkClosure;
1899 
1900 protected:
1901   G1CollectedHeap* _g1h;
1902   size_t _max_live_bytes;
1903   size_t _freed_bytes;
1904   FreeRegionList* _cleanup_list;
1905 
1906 public:
1907   G1ParNoteEndTask(G1CollectedHeap* g1h,
1908                    FreeRegionList* cleanup_list) :
1909     AbstractGangTask("G1 note end"), _g1h(g1h),
1910     _max_live_bytes(0), _freed_bytes(0), _cleanup_list(cleanup_list) { }
1911 
1912   void work(uint worker_id) {
1913     double start = os::elapsedTime();
1914     FreeRegionList local_cleanup_list("Local Cleanup List");
1915     HRRSCleanupTask hrrs_cleanup_task;
1916     G1NoteEndOfConcMarkClosure g1_note_end(_g1h, &local_cleanup_list,
1917                                            &hrrs_cleanup_task);
1918     if (G1CollectedHeap::use_parallel_gc_threads()) {
1919       _g1h->heap_region_par_iterate_chunked(&g1_note_end, worker_id,
1920                                             _g1h->workers()->active_workers(),
1921                                             HeapRegion::NoteEndClaimValue);
1922     } else {
1923       _g1h->heap_region_iterate(&g1_note_end);
1924     }
1925     assert(g1_note_end.complete(), "Shouldn't have yielded!");
1926 
1927     // Now update the lists
1928     _g1h->remove_from_old_sets(g1_note_end.old_regions_removed(), g1_note_end.humongous_regions_removed());
1929     {
1930       MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
1931       _g1h->decrement_summary_bytes(g1_note_end.freed_bytes());
1932       _max_live_bytes += g1_note_end.max_live_bytes();
1933       _freed_bytes += g1_note_end.freed_bytes();
1934 
1935       // If we iterate over the global cleanup list at the end of
1936       // cleanup to do this printing we will not guarantee to only
1937       // generate output for the newly-reclaimed regions (the list
1938       // might not be empty at the beginning of cleanup; we might
1939       // still be working on its previous contents). So we do the
1940       // printing here, before we append the new regions to the global
1941       // cleanup list.
1942 
1943       G1HRPrinter* hr_printer = _g1h->hr_printer();
1944       if (hr_printer->is_active()) {
1945         FreeRegionListIterator iter(&local_cleanup_list);
1946         while (iter.more_available()) {
1947           HeapRegion* hr = iter.get_next();
1948           hr_printer->cleanup(hr);
1949         }
1950       }
1951 
1952       _cleanup_list->add_ordered(&local_cleanup_list);
1953       assert(local_cleanup_list.is_empty(), "post-condition");
1954 
1955       HeapRegionRemSet::finish_cleanup_task(&hrrs_cleanup_task);
1956     }
1957   }
1958   size_t max_live_bytes() { return _max_live_bytes; }
1959   size_t freed_bytes() { return _freed_bytes; }
1960 };
1961 
1962 class G1ParScrubRemSetTask: public AbstractGangTask {
1963 protected:
1964   G1RemSet* _g1rs;
1965   BitMap* _region_bm;
1966   BitMap* _card_bm;
1967 public:
1968   G1ParScrubRemSetTask(G1CollectedHeap* g1h,
1969                        BitMap* region_bm, BitMap* card_bm) :
1970     AbstractGangTask("G1 ScrubRS"), _g1rs(g1h->g1_rem_set()),
1971     _region_bm(region_bm), _card_bm(card_bm) { }
1972 
1973   void work(uint worker_id) {
1974     if (G1CollectedHeap::use_parallel_gc_threads()) {
1975       _g1rs->scrub_par(_region_bm, _card_bm, worker_id,
1976                        HeapRegion::ScrubRemSetClaimValue);
1977     } else {
1978       _g1rs->scrub(_region_bm, _card_bm);
1979     }
1980   }
1981 
1982 };
1983 
1984 void ConcurrentMark::cleanup() {
1985   // world is stopped at this checkpoint
1986   assert(SafepointSynchronize::is_at_safepoint(),
1987          "world should be stopped");
1988   G1CollectedHeap* g1h = G1CollectedHeap::heap();
1989 
1990   // If a full collection has happened, we shouldn't do this.
1991   if (has_aborted()) {
1992     g1h->set_marking_complete(); // So bitmap clearing isn't confused
1993     return;
1994   }
1995 
1996   g1h->verify_region_sets_optional();
1997 
1998   if (VerifyDuringGC) {
1999     HandleMark hm;  // handle scope
2000     Universe::heap()->prepare_for_verify();
2001     Universe::verify(VerifyOption_G1UsePrevMarking,
2002                      " VerifyDuringGC:(before)");
2003   }
2004   g1h->check_bitmaps("Cleanup Start");
2005 
2006   G1CollectorPolicy* g1p = G1CollectedHeap::heap()->g1_policy();
2007   g1p->record_concurrent_mark_cleanup_start();
2008 
2009   double start = os::elapsedTime();
2010 
2011   HeapRegionRemSet::reset_for_cleanup_tasks();
2012 
2013   uint n_workers;
2014 
2015   // Do counting once more with the world stopped for good measure.
2016   G1ParFinalCountTask g1_par_count_task(g1h, &_region_bm, &_card_bm);
2017 
2018   if (G1CollectedHeap::use_parallel_gc_threads()) {
2019    assert(g1h->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
2020            "sanity check");
2021 
2022     g1h->set_par_threads();
2023     n_workers = g1h->n_par_threads();
2024     assert(g1h->n_par_threads() == n_workers,
2025            "Should not have been reset");
2026     g1h->workers()->run_task(&g1_par_count_task);
2027     // Done with the parallel phase so reset to 0.
2028     g1h->set_par_threads(0);
2029 
2030     assert(g1h->check_heap_region_claim_values(HeapRegion::FinalCountClaimValue),
2031            "sanity check");
2032   } else {
2033     n_workers = 1;
2034     g1_par_count_task.work(0);
2035   }
2036 
2037   if (VerifyDuringGC) {
2038     // Verify that the counting data accumulated during marking matches
2039     // that calculated by walking the marking bitmap.
2040 
2041     // Bitmaps to hold expected values
2042     BitMap expected_region_bm(_region_bm.size(), true);
2043     BitMap expected_card_bm(_card_bm.size(), true);
2044 
2045     G1ParVerifyFinalCountTask g1_par_verify_task(g1h,
2046                                                  &_region_bm,
2047                                                  &_card_bm,
2048                                                  &expected_region_bm,
2049                                                  &expected_card_bm);
2050 
2051     if (G1CollectedHeap::use_parallel_gc_threads()) {
2052       g1h->set_par_threads((int)n_workers);
2053       g1h->workers()->run_task(&g1_par_verify_task);
2054       // Done with the parallel phase so reset to 0.
2055       g1h->set_par_threads(0);
2056 
2057       assert(g1h->check_heap_region_claim_values(HeapRegion::VerifyCountClaimValue),
2058              "sanity check");
2059     } else {
2060       g1_par_verify_task.work(0);
2061     }
2062 
2063     guarantee(g1_par_verify_task.failures() == 0, "Unexpected accounting failures");
2064   }
2065 
2066   size_t start_used_bytes = g1h->used();
2067   g1h->set_marking_complete();
2068 
2069   double count_end = os::elapsedTime();
2070   double this_final_counting_time = (count_end - start);
2071   _total_counting_time += this_final_counting_time;
2072 
2073   if (G1PrintRegionLivenessInfo) {
2074     G1PrintRegionLivenessInfoClosure cl(gclog_or_tty, "Post-Marking");
2075     _g1h->heap_region_iterate(&cl);
2076   }
2077 
2078   // Install newly created mark bitMap as "prev".
2079   swapMarkBitMaps();
2080 
2081   g1h->reset_gc_time_stamp();
2082 
2083   // Note end of marking in all heap regions.
2084   G1ParNoteEndTask g1_par_note_end_task(g1h, &_cleanup_list);
2085   if (G1CollectedHeap::use_parallel_gc_threads()) {
2086     g1h->set_par_threads((int)n_workers);
2087     g1h->workers()->run_task(&g1_par_note_end_task);
2088     g1h->set_par_threads(0);
2089 
2090     assert(g1h->check_heap_region_claim_values(HeapRegion::NoteEndClaimValue),
2091            "sanity check");
2092   } else {
2093     g1_par_note_end_task.work(0);
2094   }
2095   g1h->check_gc_time_stamps();
2096 
2097   if (!cleanup_list_is_empty()) {
2098     // The cleanup list is not empty, so we'll have to process it
2099     // concurrently. Notify anyone else that might be wanting free
2100     // regions that there will be more free regions coming soon.
2101     g1h->set_free_regions_coming();
2102   }
2103 
2104   // call below, since it affects the metric by which we sort the heap
2105   // regions.
2106   if (G1ScrubRemSets) {
2107     double rs_scrub_start = os::elapsedTime();
2108     G1ParScrubRemSetTask g1_par_scrub_rs_task(g1h, &_region_bm, &_card_bm);
2109     if (G1CollectedHeap::use_parallel_gc_threads()) {
2110       g1h->set_par_threads((int)n_workers);
2111       g1h->workers()->run_task(&g1_par_scrub_rs_task);
2112       g1h->set_par_threads(0);
2113 
2114       assert(g1h->check_heap_region_claim_values(
2115                                             HeapRegion::ScrubRemSetClaimValue),
2116              "sanity check");
2117     } else {
2118       g1_par_scrub_rs_task.work(0);
2119     }
2120 
2121     double rs_scrub_end = os::elapsedTime();
2122     double this_rs_scrub_time = (rs_scrub_end - rs_scrub_start);
2123     _total_rs_scrub_time += this_rs_scrub_time;
2124   }
2125 
2126   // this will also free any regions totally full of garbage objects,
2127   // and sort the regions.
2128   g1h->g1_policy()->record_concurrent_mark_cleanup_end((int)n_workers);
2129 
2130   // Statistics.
2131   double end = os::elapsedTime();
2132   _cleanup_times.add((end - start) * 1000.0);
2133 
2134   if (G1Log::fine()) {
2135     g1h->print_size_transition(gclog_or_tty,
2136                                start_used_bytes,
2137                                g1h->used(),
2138                                g1h->capacity());
2139   }
2140 
2141   // Clean up will have freed any regions completely full of garbage.
2142   // Update the soft reference policy with the new heap occupancy.
2143   Universe::update_heap_info_at_gc();
2144 
2145   // We need to make this be a "collection" so any collection pause that
2146   // races with it goes around and waits for completeCleanup to finish.
2147   g1h->increment_total_collections();
2148 
2149   // We reclaimed old regions so we should calculate the sizes to make
2150   // sure we update the old gen/space data.
2151   g1h->g1mm()->update_sizes();
2152 
2153   if (VerifyDuringGC) {
2154     HandleMark hm;  // handle scope
2155     Universe::heap()->prepare_for_verify();
2156     Universe::verify(VerifyOption_G1UsePrevMarking,
2157                      " VerifyDuringGC:(after)");
2158   }
2159   g1h->check_bitmaps("Cleanup End");
2160 
2161   g1h->verify_region_sets_optional();
2162   g1h->trace_heap_after_concurrent_cycle();
2163 }
2164 
2165 void ConcurrentMark::completeCleanup() {
2166   if (has_aborted()) return;
2167 
2168   G1CollectedHeap* g1h = G1CollectedHeap::heap();
2169 
2170   _cleanup_list.verify_optional();
2171   FreeRegionList tmp_free_list("Tmp Free List");
2172 
2173   if (G1ConcRegionFreeingVerbose) {
2174     gclog_or_tty->print_cr("G1ConcRegionFreeing [complete cleanup] : "
2175                            "cleanup list has %u entries",
2176                            _cleanup_list.length());
2177   }
2178 
2179   // Noone else should be accessing the _cleanup_list at this point,
2180   // so it's not necessary to take any locks
2181   while (!_cleanup_list.is_empty()) {
2182     HeapRegion* hr = _cleanup_list.remove_head();
2183     assert(hr != NULL, "Got NULL from a non-empty list");
2184     hr->par_clear();
2185     tmp_free_list.add_ordered(hr);
2186 
2187     // Instead of adding one region at a time to the secondary_free_list,
2188     // we accumulate them in the local list and move them a few at a
2189     // time. This also cuts down on the number of notify_all() calls
2190     // we do during this process. We'll also append the local list when
2191     // _cleanup_list is empty (which means we just removed the last
2192     // region from the _cleanup_list).
2193     if ((tmp_free_list.length() % G1SecondaryFreeListAppendLength == 0) ||
2194         _cleanup_list.is_empty()) {
2195       if (G1ConcRegionFreeingVerbose) {
2196         gclog_or_tty->print_cr("G1ConcRegionFreeing [complete cleanup] : "
2197                                "appending %u entries to the secondary_free_list, "
2198                                "cleanup list still has %u entries",
2199                                tmp_free_list.length(),
2200                                _cleanup_list.length());
2201       }
2202 
2203       {
2204         MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
2205         g1h->secondary_free_list_add(&tmp_free_list);
2206         SecondaryFreeList_lock->notify_all();
2207       }
2208 
2209       if (G1StressConcRegionFreeing) {
2210         for (uintx i = 0; i < G1StressConcRegionFreeingDelayMillis; ++i) {
2211           os::sleep(Thread::current(), (jlong) 1, false);
2212         }
2213       }
2214     }
2215   }
2216   assert(tmp_free_list.is_empty(), "post-condition");
2217 }
2218 
2219 // Supporting Object and Oop closures for reference discovery
2220 // and processing in during marking
2221 
2222 bool G1CMIsAliveClosure::do_object_b(oop obj) {
2223   HeapWord* addr = (HeapWord*)obj;
2224   return addr != NULL &&
2225          (!_g1->is_in_g1_reserved(addr) || !_g1->is_obj_ill(obj));
2226 }
2227 
2228 // 'Keep Alive' oop closure used by both serial parallel reference processing.
2229 // Uses the CMTask associated with a worker thread (for serial reference
2230 // processing the CMTask for worker 0 is used) to preserve (mark) and
2231 // trace referent objects.
2232 //
2233 // Using the CMTask and embedded local queues avoids having the worker
2234 // threads operating on the global mark stack. This reduces the risk
2235 // of overflowing the stack - which we would rather avoid at this late
2236 // state. Also using the tasks' local queues removes the potential
2237 // of the workers interfering with each other that could occur if
2238 // operating on the global stack.
2239 
2240 class G1CMKeepAliveAndDrainClosure: public OopClosure {
2241   ConcurrentMark* _cm;
2242   CMTask*         _task;
2243   int             _ref_counter_limit;
2244   int             _ref_counter;
2245   bool            _is_serial;
2246  public:
2247   G1CMKeepAliveAndDrainClosure(ConcurrentMark* cm, CMTask* task, bool is_serial) :
2248     _cm(cm), _task(task), _is_serial(is_serial),
2249     _ref_counter_limit(G1RefProcDrainInterval) {
2250     assert(_ref_counter_limit > 0, "sanity");
2251     assert(!_is_serial || _task->worker_id() == 0, "only task 0 for serial code");
2252     _ref_counter = _ref_counter_limit;
2253   }
2254 
2255   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
2256   virtual void do_oop(      oop* p) { do_oop_work(p); }
2257 
2258   template <class T> void do_oop_work(T* p) {
2259     if (!_cm->has_overflown()) {
2260       oop obj = oopDesc::load_decode_heap_oop(p);
2261       if (_cm->verbose_high()) {
2262         gclog_or_tty->print_cr("\t[%u] we're looking at location "
2263                                "*"PTR_FORMAT" = "PTR_FORMAT,
2264                                _task->worker_id(), p2i(p), p2i((void*) obj));
2265       }
2266 
2267       _task->deal_with_reference(obj);
2268       _ref_counter--;
2269 
2270       if (_ref_counter == 0) {
2271         // We have dealt with _ref_counter_limit references, pushing them
2272         // and objects reachable from them on to the local stack (and
2273         // possibly the global stack). Call CMTask::do_marking_step() to
2274         // process these entries.
2275         //
2276         // We call CMTask::do_marking_step() in a loop, which we'll exit if
2277         // there's nothing more to do (i.e. we're done with the entries that
2278         // were pushed as a result of the CMTask::deal_with_reference() calls
2279         // above) or we overflow.
2280         //
2281         // Note: CMTask::do_marking_step() can set the CMTask::has_aborted()
2282         // flag while there may still be some work to do. (See the comment at
2283         // the beginning of CMTask::do_marking_step() for those conditions -
2284         // one of which is reaching the specified time target.) It is only
2285         // when CMTask::do_marking_step() returns without setting the
2286         // has_aborted() flag that the marking step has completed.
2287         do {
2288           double mark_step_duration_ms = G1ConcMarkStepDurationMillis;
2289           _task->do_marking_step(mark_step_duration_ms,
2290                                  false      /* do_termination */,
2291                                  _is_serial);
2292         } while (_task->has_aborted() && !_cm->has_overflown());
2293         _ref_counter = _ref_counter_limit;
2294       }
2295     } else {
2296       if (_cm->verbose_high()) {
2297          gclog_or_tty->print_cr("\t[%u] CM Overflow", _task->worker_id());
2298       }
2299     }
2300   }
2301 };
2302 
2303 // 'Drain' oop closure used by both serial and parallel reference processing.
2304 // Uses the CMTask associated with a given worker thread (for serial
2305 // reference processing the CMtask for worker 0 is used). Calls the
2306 // do_marking_step routine, with an unbelievably large timeout value,
2307 // to drain the marking data structures of the remaining entries
2308 // added by the 'keep alive' oop closure above.
2309 
2310 class G1CMDrainMarkingStackClosure: public VoidClosure {
2311   ConcurrentMark* _cm;
2312   CMTask*         _task;
2313   bool            _is_serial;
2314  public:
2315   G1CMDrainMarkingStackClosure(ConcurrentMark* cm, CMTask* task, bool is_serial) :
2316     _cm(cm), _task(task), _is_serial(is_serial) {
2317     assert(!_is_serial || _task->worker_id() == 0, "only task 0 for serial code");
2318   }
2319 
2320   void do_void() {
2321     do {
2322       if (_cm->verbose_high()) {
2323         gclog_or_tty->print_cr("\t[%u] Drain: Calling do_marking_step - serial: %s",
2324                                _task->worker_id(), BOOL_TO_STR(_is_serial));
2325       }
2326 
2327       // We call CMTask::do_marking_step() to completely drain the local
2328       // and global marking stacks of entries pushed by the 'keep alive'
2329       // oop closure (an instance of G1CMKeepAliveAndDrainClosure above).
2330       //
2331       // CMTask::do_marking_step() is called in a loop, which we'll exit
2332       // if there's nothing more to do (i.e. we've completely drained the
2333       // entries that were pushed as a a result of applying the 'keep alive'
2334       // closure to the entries on the discovered ref lists) or we overflow
2335       // the global marking stack.
2336       //
2337       // Note: CMTask::do_marking_step() can set the CMTask::has_aborted()
2338       // flag while there may still be some work to do. (See the comment at
2339       // the beginning of CMTask::do_marking_step() for those conditions -
2340       // one of which is reaching the specified time target.) It is only
2341       // when CMTask::do_marking_step() returns without setting the
2342       // has_aborted() flag that the marking step has completed.
2343 
2344       _task->do_marking_step(1000000000.0 /* something very large */,
2345                              true         /* do_termination */,
2346                              _is_serial);
2347     } while (_task->has_aborted() && !_cm->has_overflown());
2348   }
2349 };
2350 
2351 // Implementation of AbstractRefProcTaskExecutor for parallel
2352 // reference processing at the end of G1 concurrent marking
2353 
2354 class G1CMRefProcTaskExecutor: public AbstractRefProcTaskExecutor {
2355 private:
2356   G1CollectedHeap* _g1h;
2357   ConcurrentMark*  _cm;
2358   WorkGang*        _workers;
2359   int              _active_workers;
2360 
2361 public:
2362   G1CMRefProcTaskExecutor(G1CollectedHeap* g1h,
2363                         ConcurrentMark* cm,
2364                         WorkGang* workers,
2365                         int n_workers) :
2366     _g1h(g1h), _cm(cm),
2367     _workers(workers), _active_workers(n_workers) { }
2368 
2369   // Executes the given task using concurrent marking worker threads.
2370   virtual void execute(ProcessTask& task);
2371   virtual void execute(EnqueueTask& task);
2372 };
2373 
2374 class G1CMRefProcTaskProxy: public AbstractGangTask {
2375   typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
2376   ProcessTask&     _proc_task;
2377   G1CollectedHeap* _g1h;
2378   ConcurrentMark*  _cm;
2379 
2380 public:
2381   G1CMRefProcTaskProxy(ProcessTask& proc_task,
2382                      G1CollectedHeap* g1h,
2383                      ConcurrentMark* cm) :
2384     AbstractGangTask("Process reference objects in parallel"),
2385     _proc_task(proc_task), _g1h(g1h), _cm(cm) {
2386     ReferenceProcessor* rp = _g1h->ref_processor_cm();
2387     assert(rp->processing_is_mt(), "shouldn't be here otherwise");
2388   }
2389 
2390   virtual void work(uint worker_id) {
2391     CMTask* task = _cm->task(worker_id);
2392     G1CMIsAliveClosure g1_is_alive(_g1h);
2393     G1CMKeepAliveAndDrainClosure g1_par_keep_alive(_cm, task, false /* is_serial */);
2394     G1CMDrainMarkingStackClosure g1_par_drain(_cm, task, false /* is_serial */);
2395 
2396     _proc_task.work(worker_id, g1_is_alive, g1_par_keep_alive, g1_par_drain);
2397   }
2398 };
2399 
2400 void G1CMRefProcTaskExecutor::execute(ProcessTask& proc_task) {
2401   assert(_workers != NULL, "Need parallel worker threads.");
2402   assert(_g1h->ref_processor_cm()->processing_is_mt(), "processing is not MT");
2403 
2404   G1CMRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _cm);
2405 
2406   // We need to reset the concurrency level before each
2407   // proxy task execution, so that the termination protocol
2408   // and overflow handling in CMTask::do_marking_step() knows
2409   // how many workers to wait for.
2410   _cm->set_concurrency(_active_workers);
2411   _g1h->set_par_threads(_active_workers);
2412   _workers->run_task(&proc_task_proxy);
2413   _g1h->set_par_threads(0);
2414 }
2415 
2416 class G1CMRefEnqueueTaskProxy: public AbstractGangTask {
2417   typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
2418   EnqueueTask& _enq_task;
2419 
2420 public:
2421   G1CMRefEnqueueTaskProxy(EnqueueTask& enq_task) :
2422     AbstractGangTask("Enqueue reference objects in parallel"),
2423     _enq_task(enq_task) { }
2424 
2425   virtual void work(uint worker_id) {
2426     _enq_task.work(worker_id);
2427   }
2428 };
2429 
2430 void G1CMRefProcTaskExecutor::execute(EnqueueTask& enq_task) {
2431   assert(_workers != NULL, "Need parallel worker threads.");
2432   assert(_g1h->ref_processor_cm()->processing_is_mt(), "processing is not MT");
2433 
2434   G1CMRefEnqueueTaskProxy enq_task_proxy(enq_task);
2435 
2436   // Not strictly necessary but...
2437   //
2438   // We need to reset the concurrency level before each
2439   // proxy task execution, so that the termination protocol
2440   // and overflow handling in CMTask::do_marking_step() knows
2441   // how many workers to wait for.
2442   _cm->set_concurrency(_active_workers);
2443   _g1h->set_par_threads(_active_workers);
2444   _workers->run_task(&enq_task_proxy);
2445   _g1h->set_par_threads(0);
2446 }
2447 
2448 void ConcurrentMark::weakRefsWork(bool clear_all_soft_refs) {
2449   if (has_overflown()) {
2450     // Skip processing the discovered references if we have
2451     // overflown the global marking stack. Reference objects
2452     // only get discovered once so it is OK to not
2453     // de-populate the discovered reference lists. We could have,
2454     // but the only benefit would be that, when marking restarts,
2455     // less reference objects are discovered.
2456     return;
2457   }
2458 
2459   ResourceMark rm;
2460   HandleMark   hm;
2461 
2462   G1CollectedHeap* g1h = G1CollectedHeap::heap();
2463 
2464   // Is alive closure.
2465   G1CMIsAliveClosure g1_is_alive(g1h);
2466 
2467   // Inner scope to exclude the cleaning of the string and symbol
2468   // tables from the displayed time.
2469   {
2470     if (G1Log::finer()) {
2471       gclog_or_tty->put(' ');
2472     }
2473     GCTraceTime t("GC ref-proc", G1Log::finer(), false, g1h->gc_timer_cm());
2474 
2475     ReferenceProcessor* rp = g1h->ref_processor_cm();
2476 
2477     // See the comment in G1CollectedHeap::ref_processing_init()
2478     // about how reference processing currently works in G1.
2479 
2480     // Set the soft reference policy
2481     rp->setup_policy(clear_all_soft_refs);
2482     assert(_markStack.isEmpty(), "mark stack should be empty");
2483 
2484     // Instances of the 'Keep Alive' and 'Complete GC' closures used
2485     // in serial reference processing. Note these closures are also
2486     // used for serially processing (by the the current thread) the
2487     // JNI references during parallel reference processing.
2488     //
2489     // These closures do not need to synchronize with the worker
2490     // threads involved in parallel reference processing as these
2491     // instances are executed serially by the current thread (e.g.
2492     // reference processing is not multi-threaded and is thus
2493     // performed by the current thread instead of a gang worker).
2494     //
2495     // The gang tasks involved in parallel reference processing create
2496     // their own instances of these closures, which do their own
2497     // synchronization among themselves.
2498     G1CMKeepAliveAndDrainClosure g1_keep_alive(this, task(0), true /* is_serial */);
2499     G1CMDrainMarkingStackClosure g1_drain_mark_stack(this, task(0), true /* is_serial */);
2500 
2501     // We need at least one active thread. If reference processing
2502     // is not multi-threaded we use the current (VMThread) thread,
2503     // otherwise we use the work gang from the G1CollectedHeap and
2504     // we utilize all the worker threads we can.
2505     bool processing_is_mt = rp->processing_is_mt() && g1h->workers() != NULL;
2506     uint active_workers = (processing_is_mt ? g1h->workers()->active_workers() : 1U);
2507     active_workers = MAX2(MIN2(active_workers, _max_worker_id), 1U);
2508 
2509     // Parallel processing task executor.
2510     G1CMRefProcTaskExecutor par_task_executor(g1h, this,
2511                                               g1h->workers(), active_workers);
2512     AbstractRefProcTaskExecutor* executor = (processing_is_mt ? &par_task_executor : NULL);
2513 
2514     // Set the concurrency level. The phase was already set prior to
2515     // executing the remark task.
2516     set_concurrency(active_workers);
2517 
2518     // Set the degree of MT processing here.  If the discovery was done MT,
2519     // the number of threads involved during discovery could differ from
2520     // the number of active workers.  This is OK as long as the discovered
2521     // Reference lists are balanced (see balance_all_queues() and balance_queues()).
2522     rp->set_active_mt_degree(active_workers);
2523 
2524     // Process the weak references.
2525     const ReferenceProcessorStats& stats =
2526         rp->process_discovered_references(&g1_is_alive,
2527                                           &g1_keep_alive,
2528                                           &g1_drain_mark_stack,
2529                                           executor,
2530                                           g1h->gc_timer_cm());
2531     g1h->gc_tracer_cm()->report_gc_reference_stats(stats);
2532 
2533     // The do_oop work routines of the keep_alive and drain_marking_stack
2534     // oop closures will set the has_overflown flag if we overflow the
2535     // global marking stack.
2536 
2537     assert(_markStack.overflow() || _markStack.isEmpty(),
2538             "mark stack should be empty (unless it overflowed)");
2539 
2540     if (_markStack.overflow()) {
2541       // This should have been done already when we tried to push an
2542       // entry on to the global mark stack. But let's do it again.
2543       set_has_overflown();
2544     }
2545 
2546     assert(rp->num_q() == active_workers, "why not");
2547 
2548     rp->enqueue_discovered_references(executor);
2549 
2550     rp->verify_no_references_recorded();
2551     assert(!rp->discovery_enabled(), "Post condition");
2552   }
2553 
2554   if (has_overflown()) {
2555     // We can not trust g1_is_alive if the marking stack overflowed
2556     return;
2557   }
2558 
2559   g1h->unlink_string_and_symbol_table(&g1_is_alive,
2560                                       /* process_strings */ false, // currently strings are always roots
2561                                       /* process_symbols */ true);
2562 }
2563 
2564 void ConcurrentMark::swapMarkBitMaps() {
2565   CMBitMapRO* temp = _prevMarkBitMap;
2566   _prevMarkBitMap  = (CMBitMapRO*)_nextMarkBitMap;
2567   _nextMarkBitMap  = (CMBitMap*)  temp;
2568 }
2569 
2570 class CMRemarkTask: public AbstractGangTask {
2571 private:
2572   ConcurrentMark* _cm;
2573   bool            _is_serial;
2574 public:
2575   void work(uint worker_id) {
2576     // Since all available tasks are actually started, we should
2577     // only proceed if we're supposed to be active.
2578     if (worker_id < _cm->active_tasks()) {
2579       CMTask* task = _cm->task(worker_id);
2580       task->record_start_time();
2581       do {
2582         task->do_marking_step(1000000000.0 /* something very large */,
2583                               true         /* do_termination       */,
2584                               _is_serial);
2585       } while (task->has_aborted() && !_cm->has_overflown());
2586       // If we overflow, then we do not want to restart. We instead
2587       // want to abort remark and do concurrent marking again.
2588       task->record_end_time();
2589     }
2590   }
2591 
2592   CMRemarkTask(ConcurrentMark* cm, int active_workers, bool is_serial) :
2593     AbstractGangTask("Par Remark"), _cm(cm), _is_serial(is_serial) {
2594     _cm->terminator()->reset_for_reuse(active_workers);
2595   }
2596 };
2597 
2598 void ConcurrentMark::checkpointRootsFinalWork() {
2599   ResourceMark rm;
2600   HandleMark   hm;
2601   G1CollectedHeap* g1h = G1CollectedHeap::heap();
2602 
2603   g1h->ensure_parsability(false);
2604 
2605   if (G1CollectedHeap::use_parallel_gc_threads()) {
2606     G1CollectedHeap::StrongRootsScope srs(g1h);
2607     // this is remark, so we'll use up all active threads
2608     uint active_workers = g1h->workers()->active_workers();
2609     if (active_workers == 0) {
2610       assert(active_workers > 0, "Should have been set earlier");
2611       active_workers = (uint) ParallelGCThreads;
2612       g1h->workers()->set_active_workers(active_workers);
2613     }
2614     set_concurrency_and_phase(active_workers, false /* concurrent */);
2615     // Leave _parallel_marking_threads at it's
2616     // value originally calculated in the ConcurrentMark
2617     // constructor and pass values of the active workers
2618     // through the gang in the task.
2619 
2620     CMRemarkTask remarkTask(this, active_workers, false /* is_serial */);
2621     // We will start all available threads, even if we decide that the
2622     // active_workers will be fewer. The extra ones will just bail out
2623     // immediately.
2624     g1h->set_par_threads(active_workers);
2625     g1h->workers()->run_task(&remarkTask);
2626     g1h->set_par_threads(0);
2627   } else {
2628     G1CollectedHeap::StrongRootsScope srs(g1h);
2629     uint active_workers = 1;
2630     set_concurrency_and_phase(active_workers, false /* concurrent */);
2631 
2632     // Note - if there's no work gang then the VMThread will be
2633     // the thread to execute the remark - serially. We have
2634     // to pass true for the is_serial parameter so that
2635     // CMTask::do_marking_step() doesn't enter the sync
2636     // barriers in the event of an overflow. Doing so will
2637     // cause an assert that the current thread is not a
2638     // concurrent GC thread.
2639     CMRemarkTask remarkTask(this, active_workers, true /* is_serial*/);
2640     remarkTask.work(0);
2641   }
2642   SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
2643   guarantee(has_overflown() ||
2644             satb_mq_set.completed_buffers_num() == 0,
2645             err_msg("Invariant: has_overflown = %s, num buffers = %d",
2646                     BOOL_TO_STR(has_overflown()),
2647                     satb_mq_set.completed_buffers_num()));
2648 
2649   print_stats();
2650 }
2651 
2652 #ifndef PRODUCT
2653 
2654 class PrintReachableOopClosure: public OopClosure {
2655 private:
2656   G1CollectedHeap* _g1h;
2657   outputStream*    _out;
2658   VerifyOption     _vo;
2659   bool             _all;
2660 
2661 public:
2662   PrintReachableOopClosure(outputStream* out,
2663                            VerifyOption  vo,
2664                            bool          all) :
2665     _g1h(G1CollectedHeap::heap()),
2666     _out(out), _vo(vo), _all(all) { }
2667 
2668   void do_oop(narrowOop* p) { do_oop_work(p); }
2669   void do_oop(      oop* p) { do_oop_work(p); }
2670 
2671   template <class T> void do_oop_work(T* p) {
2672     oop         obj = oopDesc::load_decode_heap_oop(p);
2673     const char* str = NULL;
2674     const char* str2 = "";
2675 
2676     if (obj == NULL) {
2677       str = "";
2678     } else if (!_g1h->is_in_g1_reserved(obj)) {
2679       str = " O";
2680     } else {
2681       HeapRegion* hr  = _g1h->heap_region_containing(obj);
2682       bool over_tams = _g1h->allocated_since_marking(obj, hr, _vo);
2683       bool marked = _g1h->is_marked(obj, _vo);
2684 
2685       if (over_tams) {
2686         str = " >";
2687         if (marked) {
2688           str2 = " AND MARKED";
2689         }
2690       } else if (marked) {
2691         str = " M";
2692       } else {
2693         str = " NOT";
2694       }
2695     }
2696 
2697     _out->print_cr("  "PTR_FORMAT": "PTR_FORMAT"%s%s",
2698                    p2i(p), p2i((void*) obj), str, str2);
2699   }
2700 };
2701 
2702 class PrintReachableObjectClosure : public ObjectClosure {
2703 private:
2704   G1CollectedHeap* _g1h;
2705   outputStream*    _out;
2706   VerifyOption     _vo;
2707   bool             _all;
2708   HeapRegion*      _hr;
2709 
2710 public:
2711   PrintReachableObjectClosure(outputStream* out,
2712                               VerifyOption  vo,
2713                               bool          all,
2714                               HeapRegion*   hr) :
2715     _g1h(G1CollectedHeap::heap()),
2716     _out(out), _vo(vo), _all(all), _hr(hr) { }
2717 
2718   void do_object(oop o) {
2719     bool over_tams = _g1h->allocated_since_marking(o, _hr, _vo);
2720     bool marked = _g1h->is_marked(o, _vo);
2721     bool print_it = _all || over_tams || marked;
2722 
2723     if (print_it) {
2724       _out->print_cr(" "PTR_FORMAT"%s",
2725                      p2i((void *)o), (over_tams) ? " >" : (marked) ? " M" : "");
2726       PrintReachableOopClosure oopCl(_out, _vo, _all);
2727       o->oop_iterate_no_header(&oopCl);
2728     }
2729   }
2730 };
2731 
2732 class PrintReachableRegionClosure : public HeapRegionClosure {
2733 private:
2734   G1CollectedHeap* _g1h;
2735   outputStream*    _out;
2736   VerifyOption     _vo;
2737   bool             _all;
2738 
2739 public:
2740   bool doHeapRegion(HeapRegion* hr) {
2741     HeapWord* b = hr->bottom();
2742     HeapWord* e = hr->end();
2743     HeapWord* t = hr->top();
2744     HeapWord* p = _g1h->top_at_mark_start(hr, _vo);
2745     _out->print_cr("** ["PTR_FORMAT", "PTR_FORMAT"] top: "PTR_FORMAT" "
2746                    "TAMS: " PTR_FORMAT, p2i(b), p2i(e), p2i(t), p2i(p));
2747     _out->cr();
2748 
2749     HeapWord* from = b;
2750     HeapWord* to   = t;
2751 
2752     if (to > from) {
2753       _out->print_cr("Objects in [" PTR_FORMAT ", " PTR_FORMAT "]", p2i(from), p2i(to));
2754       _out->cr();
2755       PrintReachableObjectClosure ocl(_out, _vo, _all, hr);
2756       hr->object_iterate_mem_careful(MemRegion(from, to), &ocl);
2757       _out->cr();
2758     }
2759 
2760     return false;
2761   }
2762 
2763   PrintReachableRegionClosure(outputStream* out,
2764                               VerifyOption  vo,
2765                               bool          all) :
2766     _g1h(G1CollectedHeap::heap()), _out(out), _vo(vo), _all(all) { }
2767 };
2768 
2769 void ConcurrentMark::print_reachable(const char* str,
2770                                      VerifyOption vo,
2771                                      bool all) {
2772   gclog_or_tty->cr();
2773   gclog_or_tty->print_cr("== Doing heap dump... ");
2774 
2775   if (G1PrintReachableBaseFile == NULL) {
2776     gclog_or_tty->print_cr("  #### error: no base file defined");
2777     return;
2778   }
2779 
2780   if (strlen(G1PrintReachableBaseFile) + 1 + strlen(str) >
2781       (JVM_MAXPATHLEN - 1)) {
2782     gclog_or_tty->print_cr("  #### error: file name too long");
2783     return;
2784   }
2785 
2786   char file_name[JVM_MAXPATHLEN];
2787   sprintf(file_name, "%s.%s", G1PrintReachableBaseFile, str);
2788   gclog_or_tty->print_cr("  dumping to file %s", file_name);
2789 
2790   fileStream fout(file_name);
2791   if (!fout.is_open()) {
2792     gclog_or_tty->print_cr("  #### error: could not open file");
2793     return;
2794   }
2795 
2796   outputStream* out = &fout;
2797   out->print_cr("-- USING %s", _g1h->top_at_mark_start_str(vo));
2798   out->cr();
2799 
2800   out->print_cr("--- ITERATING OVER REGIONS");
2801   out->cr();
2802   PrintReachableRegionClosure rcl(out, vo, all);
2803   _g1h->heap_region_iterate(&rcl);
2804   out->cr();
2805 
2806   gclog_or_tty->print_cr("  done");
2807   gclog_or_tty->flush();
2808 }
2809 
2810 #endif // PRODUCT
2811 
2812 void ConcurrentMark::clearRangePrevBitmap(MemRegion mr) {
2813   // Note we are overriding the read-only view of the prev map here, via
2814   // the cast.
2815   ((CMBitMap*)_prevMarkBitMap)->clearRange(mr);
2816 }
2817 
2818 void ConcurrentMark::clearRangeNextBitmap(MemRegion mr) {
2819   _nextMarkBitMap->clearRange(mr);
2820 }
2821 
2822 void ConcurrentMark::clearRangeBothBitmaps(MemRegion mr) {
2823   clearRangePrevBitmap(mr);
2824   clearRangeNextBitmap(mr);
2825 }
2826 
2827 HeapRegion*
2828 ConcurrentMark::claim_region(uint worker_id) {
2829   // "checkpoint" the finger
2830   HeapWord* finger = _finger;
2831 
2832   // _heap_end will not change underneath our feet; it only changes at
2833   // yield points.
2834   while (finger < _heap_end) {
2835     assert(_g1h->is_in_g1_reserved(finger), "invariant");
2836 
2837     // Note on how this code handles humongous regions. In the
2838     // normal case the finger will reach the start of a "starts
2839     // humongous" (SH) region. Its end will either be the end of the
2840     // last "continues humongous" (CH) region in the sequence, or the
2841     // standard end of the SH region (if the SH is the only region in
2842     // the sequence). That way claim_region() will skip over the CH
2843     // regions. However, there is a subtle race between a CM thread
2844     // executing this method and a mutator thread doing a humongous
2845     // object allocation. The two are not mutually exclusive as the CM
2846     // thread does not need to hold the Heap_lock when it gets
2847     // here. So there is a chance that claim_region() will come across
2848     // a free region that's in the progress of becoming a SH or a CH
2849     // region. In the former case, it will either
2850     //   a) Miss the update to the region's end, in which case it will
2851     //      visit every subsequent CH region, will find their bitmaps
2852     //      empty, and do nothing, or
2853     //   b) Will observe the update of the region's end (in which case
2854     //      it will skip the subsequent CH regions).
2855     // If it comes across a region that suddenly becomes CH, the
2856     // scenario will be similar to b). So, the race between
2857     // claim_region() and a humongous object allocation might force us
2858     // to do a bit of unnecessary work (due to some unnecessary bitmap
2859     // iterations) but it should not introduce and correctness issues.
2860     HeapRegion* curr_region   = _g1h->heap_region_containing_raw(finger);
2861     HeapWord*   bottom        = curr_region->bottom();
2862     HeapWord*   end           = curr_region->end();
2863     HeapWord*   limit         = curr_region->next_top_at_mark_start();
2864 
2865     if (verbose_low()) {
2866       gclog_or_tty->print_cr("[%u] curr_region = "PTR_FORMAT" "
2867                              "["PTR_FORMAT", "PTR_FORMAT"), "
2868                              "limit = "PTR_FORMAT,
2869                              worker_id, p2i(curr_region), p2i(bottom), p2i(end), p2i(limit));
2870     }
2871 
2872     // Is the gap between reading the finger and doing the CAS too long?
2873     HeapWord* res = (HeapWord*) Atomic::cmpxchg_ptr(end, &_finger, finger);
2874     if (res == finger) {
2875       // we succeeded
2876 
2877       // notice that _finger == end cannot be guaranteed here since,
2878       // someone else might have moved the finger even further
2879       assert(_finger >= end, "the finger should have moved forward");
2880 
2881       if (verbose_low()) {
2882         gclog_or_tty->print_cr("[%u] we were successful with region = "
2883                                PTR_FORMAT, worker_id, p2i(curr_region));
2884       }
2885 
2886       if (limit > bottom) {
2887         if (verbose_low()) {
2888           gclog_or_tty->print_cr("[%u] region "PTR_FORMAT" is not empty, "
2889                                  "returning it ", worker_id, p2i(curr_region));
2890         }
2891         return curr_region;
2892       } else {
2893         assert(limit == bottom,
2894                "the region limit should be at bottom");
2895         if (verbose_low()) {
2896           gclog_or_tty->print_cr("[%u] region "PTR_FORMAT" is empty, "
2897                                  "returning NULL", worker_id, p2i(curr_region));
2898         }
2899         // we return NULL and the caller should try calling
2900         // claim_region() again.
2901         return NULL;
2902       }
2903     } else {
2904       assert(_finger > finger, "the finger should have moved forward");
2905       if (verbose_low()) {
2906         gclog_or_tty->print_cr("[%u] somebody else moved the finger, "
2907                                "global finger = "PTR_FORMAT", "
2908                                "our finger = "PTR_FORMAT,
2909                                worker_id, p2i(_finger), p2i(finger));
2910       }
2911 
2912       // read it again
2913       finger = _finger;
2914     }
2915   }
2916 
2917   return NULL;
2918 }
2919 
2920 #ifndef PRODUCT
2921 enum VerifyNoCSetOopsPhase {
2922   VerifyNoCSetOopsStack,
2923   VerifyNoCSetOopsQueues,
2924   VerifyNoCSetOopsSATBCompleted,
2925   VerifyNoCSetOopsSATBThread
2926 };
2927 
2928 class VerifyNoCSetOopsClosure : public OopClosure, public ObjectClosure  {
2929 private:
2930   G1CollectedHeap* _g1h;
2931   VerifyNoCSetOopsPhase _phase;
2932   int _info;
2933 
2934   const char* phase_str() {
2935     switch (_phase) {
2936     case VerifyNoCSetOopsStack:         return "Stack";
2937     case VerifyNoCSetOopsQueues:        return "Queue";
2938     case VerifyNoCSetOopsSATBCompleted: return "Completed SATB Buffers";
2939     case VerifyNoCSetOopsSATBThread:    return "Thread SATB Buffers";
2940     default:                            ShouldNotReachHere();
2941     }
2942     return NULL;
2943   }
2944 
2945   void do_object_work(oop obj) {
2946     guarantee(!_g1h->obj_in_cs(obj),
2947               err_msg("obj: "PTR_FORMAT" in CSet, phase: %s, info: %d",
2948                       p2i((void*) obj), phase_str(), _info));
2949   }
2950 
2951 public:
2952   VerifyNoCSetOopsClosure() : _g1h(G1CollectedHeap::heap()) { }
2953 
2954   void set_phase(VerifyNoCSetOopsPhase phase, int info = -1) {
2955     _phase = phase;
2956     _info = info;
2957   }
2958 
2959   virtual void do_oop(oop* p) {
2960     oop obj = oopDesc::load_decode_heap_oop(p);
2961     do_object_work(obj);
2962   }
2963 
2964   virtual void do_oop(narrowOop* p) {
2965     // We should not come across narrow oops while scanning marking
2966     // stacks and SATB buffers.
2967     ShouldNotReachHere();
2968   }
2969 
2970   virtual void do_object(oop obj) {
2971     do_object_work(obj);
2972   }
2973 };
2974 
2975 void ConcurrentMark::verify_no_cset_oops(bool verify_stacks,
2976                                          bool verify_enqueued_buffers,
2977                                          bool verify_thread_buffers,
2978                                          bool verify_fingers) {
2979   assert(SafepointSynchronize::is_at_safepoint(), "should be at a safepoint");
2980   if (!G1CollectedHeap::heap()->mark_in_progress()) {
2981     return;
2982   }
2983 
2984   VerifyNoCSetOopsClosure cl;
2985 
2986   if (verify_stacks) {
2987     // Verify entries on the global mark stack
2988     cl.set_phase(VerifyNoCSetOopsStack);
2989     _markStack.oops_do(&cl);
2990 
2991     // Verify entries on the task queues
2992     for (uint i = 0; i < _max_worker_id; i += 1) {
2993       cl.set_phase(VerifyNoCSetOopsQueues, i);
2994       CMTaskQueue* queue = _task_queues->queue(i);
2995       queue->oops_do(&cl);
2996     }
2997   }
2998 
2999   SATBMarkQueueSet& satb_qs = JavaThread::satb_mark_queue_set();
3000 
3001   // Verify entries on the enqueued SATB buffers
3002   if (verify_enqueued_buffers) {
3003     cl.set_phase(VerifyNoCSetOopsSATBCompleted);
3004     satb_qs.iterate_completed_buffers_read_only(&cl);
3005   }
3006 
3007   // Verify entries on the per-thread SATB buffers
3008   if (verify_thread_buffers) {
3009     cl.set_phase(VerifyNoCSetOopsSATBThread);
3010     satb_qs.iterate_thread_buffers_read_only(&cl);
3011   }
3012 
3013   if (verify_fingers) {
3014     // Verify the global finger
3015     HeapWord* global_finger = finger();
3016     if (global_finger != NULL && global_finger < _heap_end) {
3017       // The global finger always points to a heap region boundary. We
3018       // use heap_region_containing_raw() to get the containing region
3019       // given that the global finger could be pointing to a free region
3020       // which subsequently becomes continues humongous. If that
3021       // happens, heap_region_containing() will return the bottom of the
3022       // corresponding starts humongous region and the check below will
3023       // not hold any more.
3024       HeapRegion* global_hr = _g1h->heap_region_containing_raw(global_finger);
3025       guarantee(global_finger == global_hr->bottom(),
3026                 err_msg("global finger: "PTR_FORMAT" region: "HR_FORMAT,
3027                         p2i(global_finger), HR_FORMAT_PARAMS(global_hr)));
3028     }
3029 
3030     // Verify the task fingers
3031     assert(parallel_marking_threads() <= _max_worker_id, "sanity");
3032     for (int i = 0; i < (int) parallel_marking_threads(); i += 1) {
3033       CMTask* task = _tasks[i];
3034       HeapWord* task_finger = task->finger();
3035       if (task_finger != NULL && task_finger < _heap_end) {
3036         // See above note on the global finger verification.
3037         HeapRegion* task_hr = _g1h->heap_region_containing_raw(task_finger);
3038         guarantee(task_finger == task_hr->bottom() ||
3039                   !task_hr->in_collection_set(),
3040                   err_msg("task finger: "PTR_FORMAT" region: "HR_FORMAT,
3041                           p2i(task_finger), HR_FORMAT_PARAMS(task_hr)));
3042       }
3043     }
3044   }
3045 }
3046 #endif // PRODUCT
3047 
3048 // Aggregate the counting data that was constructed concurrently
3049 // with marking.
3050 class AggregateCountDataHRClosure: public HeapRegionClosure {
3051   G1CollectedHeap* _g1h;
3052   ConcurrentMark* _cm;
3053   CardTableModRefBS* _ct_bs;
3054   BitMap* _cm_card_bm;
3055   uint _max_worker_id;
3056 
3057  public:
3058   AggregateCountDataHRClosure(G1CollectedHeap* g1h,
3059                               BitMap* cm_card_bm,
3060                               uint max_worker_id) :
3061     _g1h(g1h), _cm(g1h->concurrent_mark()),
3062     _ct_bs((CardTableModRefBS*) (g1h->barrier_set())),
3063     _cm_card_bm(cm_card_bm), _max_worker_id(max_worker_id) { }
3064 
3065   bool doHeapRegion(HeapRegion* hr) {
3066     if (hr->continuesHumongous()) {
3067       // We will ignore these here and process them when their
3068       // associated "starts humongous" region is processed.
3069       // Note that we cannot rely on their associated
3070       // "starts humongous" region to have their bit set to 1
3071       // since, due to the region chunking in the parallel region
3072       // iteration, a "continues humongous" region might be visited
3073       // before its associated "starts humongous".
3074       return false;
3075     }
3076 
3077     HeapWord* start = hr->bottom();
3078     HeapWord* limit = hr->next_top_at_mark_start();
3079     HeapWord* end = hr->end();
3080 
3081     assert(start <= limit && limit <= hr->top() && hr->top() <= hr->end(),
3082            err_msg("Preconditions not met - "
3083                    "start: "PTR_FORMAT", limit: "PTR_FORMAT", "
3084                    "top: "PTR_FORMAT", end: "PTR_FORMAT,
3085                    p2i(start), p2i(limit), p2i(hr->top()), p2i(hr->end())));
3086 
3087     assert(hr->next_marked_bytes() == 0, "Precondition");
3088 
3089     if (start == limit) {
3090       // NTAMS of this region has not been set so nothing to do.
3091       return false;
3092     }
3093 
3094     // 'start' should be in the heap.
3095     assert(_g1h->is_in_g1_reserved(start) && _ct_bs->is_card_aligned(start), "sanity");
3096     // 'end' *may* be just beyond the end of the heap (if hr is the last region)
3097     assert(!_g1h->is_in_g1_reserved(end) || _ct_bs->is_card_aligned(end), "sanity");
3098 
3099     BitMap::idx_t start_idx = _cm->card_bitmap_index_for(start);
3100     BitMap::idx_t limit_idx = _cm->card_bitmap_index_for(limit);
3101     BitMap::idx_t end_idx = _cm->card_bitmap_index_for(end);
3102 
3103     // If ntams is not card aligned then we bump card bitmap index
3104     // for limit so that we get the all the cards spanned by
3105     // the object ending at ntams.
3106     // Note: if this is the last region in the heap then ntams
3107     // could be actually just beyond the end of the the heap;
3108     // limit_idx will then  correspond to a (non-existent) card
3109     // that is also outside the heap.
3110     if (_g1h->is_in_g1_reserved(limit) && !_ct_bs->is_card_aligned(limit)) {
3111       limit_idx += 1;
3112     }
3113 
3114     assert(limit_idx <= end_idx, "or else use atomics");
3115 
3116     // Aggregate the "stripe" in the count data associated with hr.
3117     uint hrs_index = hr->hrs_index();
3118     size_t marked_bytes = 0;
3119 
3120     for (uint i = 0; i < _max_worker_id; i += 1) {
3121       size_t* marked_bytes_array = _cm->count_marked_bytes_array_for(i);
3122       BitMap* task_card_bm = _cm->count_card_bitmap_for(i);
3123 
3124       // Fetch the marked_bytes in this region for task i and
3125       // add it to the running total for this region.
3126       marked_bytes += marked_bytes_array[hrs_index];
3127 
3128       // Now union the bitmaps[0,max_worker_id)[start_idx..limit_idx)
3129       // into the global card bitmap.
3130       BitMap::idx_t scan_idx = task_card_bm->get_next_one_offset(start_idx, limit_idx);
3131 
3132       while (scan_idx < limit_idx) {
3133         assert(task_card_bm->at(scan_idx) == true, "should be");
3134         _cm_card_bm->set_bit(scan_idx);
3135         assert(_cm_card_bm->at(scan_idx) == true, "should be");
3136 
3137         // BitMap::get_next_one_offset() can handle the case when
3138         // its left_offset parameter is greater than its right_offset
3139         // parameter. It does, however, have an early exit if
3140         // left_offset == right_offset. So let's limit the value
3141         // passed in for left offset here.
3142         BitMap::idx_t next_idx = MIN2(scan_idx + 1, limit_idx);
3143         scan_idx = task_card_bm->get_next_one_offset(next_idx, limit_idx);
3144       }
3145     }
3146 
3147     // Update the marked bytes for this region.
3148     hr->add_to_marked_bytes(marked_bytes);
3149 
3150     // Next heap region
3151     return false;
3152   }
3153 };
3154 
3155 class G1AggregateCountDataTask: public AbstractGangTask {
3156 protected:
3157   G1CollectedHeap* _g1h;
3158   ConcurrentMark* _cm;
3159   BitMap* _cm_card_bm;
3160   uint _max_worker_id;
3161   int _active_workers;
3162 
3163 public:
3164   G1AggregateCountDataTask(G1CollectedHeap* g1h,
3165                            ConcurrentMark* cm,
3166                            BitMap* cm_card_bm,
3167                            uint max_worker_id,
3168                            int n_workers) :
3169     AbstractGangTask("Count Aggregation"),
3170     _g1h(g1h), _cm(cm), _cm_card_bm(cm_card_bm),
3171     _max_worker_id(max_worker_id),
3172     _active_workers(n_workers) { }
3173 
3174   void work(uint worker_id) {
3175     AggregateCountDataHRClosure cl(_g1h, _cm_card_bm, _max_worker_id);
3176 
3177     if (G1CollectedHeap::use_parallel_gc_threads()) {
3178       _g1h->heap_region_par_iterate_chunked(&cl, worker_id,
3179                                             _active_workers,
3180                                             HeapRegion::AggregateCountClaimValue);
3181     } else {
3182       _g1h->heap_region_iterate(&cl);
3183     }
3184   }
3185 };
3186 
3187 
3188 void ConcurrentMark::aggregate_count_data() {
3189   int n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
3190                         _g1h->workers()->active_workers() :
3191                         1);
3192 
3193   G1AggregateCountDataTask g1_par_agg_task(_g1h, this, &_card_bm,
3194                                            _max_worker_id, n_workers);
3195 
3196   if (G1CollectedHeap::use_parallel_gc_threads()) {
3197     assert(_g1h->check_heap_region_claim_values(HeapRegion::InitialClaimValue),
3198            "sanity check");
3199     _g1h->set_par_threads(n_workers);
3200     _g1h->workers()->run_task(&g1_par_agg_task);
3201     _g1h->set_par_threads(0);
3202 
3203     assert(_g1h->check_heap_region_claim_values(HeapRegion::AggregateCountClaimValue),
3204            "sanity check");
3205     _g1h->reset_heap_region_claim_values();
3206   } else {
3207     g1_par_agg_task.work(0);
3208   }
3209 }
3210 
3211 // Clear the per-worker arrays used to store the per-region counting data
3212 void ConcurrentMark::clear_all_count_data() {
3213   // Clear the global card bitmap - it will be filled during
3214   // liveness count aggregation (during remark) and the
3215   // final counting task.
3216   _card_bm.clear();
3217 
3218   // Clear the global region bitmap - it will be filled as part
3219   // of the final counting task.
3220   _region_bm.clear();
3221 
3222   uint max_regions = _g1h->max_regions();
3223   assert(_max_worker_id > 0, "uninitialized");
3224 
3225   for (uint i = 0; i < _max_worker_id; i += 1) {
3226     BitMap* task_card_bm = count_card_bitmap_for(i);
3227     size_t* marked_bytes_array = count_marked_bytes_array_for(i);
3228 
3229     assert(task_card_bm->size() == _card_bm.size(), "size mismatch");
3230     assert(marked_bytes_array != NULL, "uninitialized");
3231 
3232     memset(marked_bytes_array, 0, (size_t) max_regions * sizeof(size_t));
3233     task_card_bm->clear();
3234   }
3235 }
3236 
3237 void ConcurrentMark::print_stats() {
3238   if (verbose_stats()) {
3239     gclog_or_tty->print_cr("---------------------------------------------------------------------");
3240     for (size_t i = 0; i < _active_tasks; ++i) {
3241       _tasks[i]->print_stats();
3242       gclog_or_tty->print_cr("---------------------------------------------------------------------");
3243     }
3244   }
3245 }
3246 
3247 // abandon current marking iteration due to a Full GC
3248 void ConcurrentMark::abort() {
3249   // Clear all marks to force marking thread to do nothing
3250   _nextMarkBitMap->clearAll();
3251 
3252   // Note we cannot clear the previous marking bitmap here
3253   // since VerifyDuringGC verifies the objects marked during
3254   // a full GC against the previous bitmap.
3255 
3256   // Clear the liveness counting data
3257   clear_all_count_data();
3258   // Empty mark stack
3259   reset_marking_state();
3260   for (uint i = 0; i < _max_worker_id; ++i) {
3261     _tasks[i]->clear_region_fields();
3262   }
3263   _first_overflow_barrier_sync.abort();
3264   _second_overflow_barrier_sync.abort();
3265   _has_aborted = true;
3266 
3267   SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
3268   satb_mq_set.abandon_partial_marking();
3269   // This can be called either during or outside marking, we'll read
3270   // the expected_active value from the SATB queue set.
3271   satb_mq_set.set_active_all_threads(
3272                                  false, /* new active value */
3273                                  satb_mq_set.is_active() /* expected_active */);
3274 
3275   _g1h->trace_heap_after_concurrent_cycle();
3276   _g1h->register_concurrent_cycle_end();
3277 }
3278 
3279 static void print_ms_time_info(const char* prefix, const char* name,
3280                                NumberSeq& ns) {
3281   gclog_or_tty->print_cr("%s%5d %12s: total time = %8.2f s (avg = %8.2f ms).",
3282                          prefix, ns.num(), name, ns.sum()/1000.0, ns.avg());
3283   if (ns.num() > 0) {
3284     gclog_or_tty->print_cr("%s         [std. dev = %8.2f ms, max = %8.2f ms]",
3285                            prefix, ns.sd(), ns.maximum());
3286   }
3287 }
3288 
3289 void ConcurrentMark::print_summary_info() {
3290   gclog_or_tty->print_cr(" Concurrent marking:");
3291   print_ms_time_info("  ", "init marks", _init_times);
3292   print_ms_time_info("  ", "remarks", _remark_times);
3293   {
3294     print_ms_time_info("     ", "final marks", _remark_mark_times);
3295     print_ms_time_info("     ", "weak refs", _remark_weak_ref_times);
3296 
3297   }
3298   print_ms_time_info("  ", "cleanups", _cleanup_times);
3299   gclog_or_tty->print_cr("    Final counting total time = %8.2f s (avg = %8.2f ms).",
3300                          _total_counting_time,
3301                          (_cleanup_times.num() > 0 ? _total_counting_time * 1000.0 /
3302                           (double)_cleanup_times.num()
3303                          : 0.0));
3304   if (G1ScrubRemSets) {
3305     gclog_or_tty->print_cr("    RS scrub total time = %8.2f s (avg = %8.2f ms).",
3306                            _total_rs_scrub_time,
3307                            (_cleanup_times.num() > 0 ? _total_rs_scrub_time * 1000.0 /
3308                             (double)_cleanup_times.num()
3309                            : 0.0));
3310   }
3311   gclog_or_tty->print_cr("  Total stop_world time = %8.2f s.",
3312                          (_init_times.sum() + _remark_times.sum() +
3313                           _cleanup_times.sum())/1000.0);
3314   gclog_or_tty->print_cr("  Total concurrent time = %8.2f s "
3315                 "(%8.2f s marking).",
3316                 cmThread()->vtime_accum(),
3317                 cmThread()->vtime_mark_accum());
3318 }
3319 
3320 void ConcurrentMark::print_worker_threads_on(outputStream* st) const {
3321   if (use_parallel_marking_threads()) {
3322     _parallel_workers->print_worker_threads_on(st);
3323   }
3324 }
3325 
3326 void ConcurrentMark::print_on_error(outputStream* st) const {
3327   st->print_cr("Marking Bits (Prev, Next): (CMBitMap*) " PTR_FORMAT ", (CMBitMap*) " PTR_FORMAT,
3328       p2i(_prevMarkBitMap), p2i(_nextMarkBitMap));
3329   _prevMarkBitMap->print_on_error(st, " Prev Bits: ");
3330   _nextMarkBitMap->print_on_error(st, " Next Bits: ");
3331 }
3332 
3333 // We take a break if someone is trying to stop the world.
3334 bool ConcurrentMark::do_yield_check(uint worker_id) {
3335   if (SuspendibleThreadSet::should_yield()) {
3336     if (worker_id == 0) {
3337       _g1h->g1_policy()->record_concurrent_pause();
3338     }
3339     SuspendibleThreadSet::yield();
3340     return true;
3341   } else {
3342     return false;
3343   }
3344 }
3345 
3346 bool ConcurrentMark::containing_card_is_marked(void* p) {
3347   size_t offset = pointer_delta(p, _g1h->reserved_region().start(), 1);
3348   return _card_bm.at(offset >> CardTableModRefBS::card_shift);
3349 }
3350 
3351 bool ConcurrentMark::containing_cards_are_marked(void* start,
3352                                                  void* last) {
3353   return containing_card_is_marked(start) &&
3354          containing_card_is_marked(last);
3355 }
3356 
3357 #ifndef PRODUCT
3358 // for debugging purposes
3359 void ConcurrentMark::print_finger() {
3360   gclog_or_tty->print_cr("heap ["PTR_FORMAT", "PTR_FORMAT"), global finger = "PTR_FORMAT,
3361                          p2i(_heap_start), p2i(_heap_end), p2i(_finger));
3362   for (uint i = 0; i < _max_worker_id; ++i) {
3363     gclog_or_tty->print("   %u: " PTR_FORMAT, i, p2i(_tasks[i]->finger()));
3364   }
3365   gclog_or_tty->cr();
3366 }
3367 #endif
3368 
3369 void CMTask::scan_object(oop obj) {
3370   assert(_nextMarkBitMap->isMarked((HeapWord*) obj), "invariant");
3371 
3372   if (_cm->verbose_high()) {
3373     gclog_or_tty->print_cr("[%u] we're scanning object "PTR_FORMAT,
3374                            _worker_id, p2i((void*) obj));
3375   }
3376 
3377   size_t obj_size = obj->size();
3378   _words_scanned += obj_size;
3379 
3380   obj->oop_iterate(_cm_oop_closure);
3381   statsOnly( ++_objs_scanned );
3382   check_limits();
3383 }
3384 
3385 // Closure for iteration over bitmaps
3386 class CMBitMapClosure : public BitMapClosure {
3387 private:
3388   // the bitmap that is being iterated over
3389   CMBitMap*                   _nextMarkBitMap;
3390   ConcurrentMark*             _cm;
3391   CMTask*                     _task;
3392 
3393 public:
3394   CMBitMapClosure(CMTask *task, ConcurrentMark* cm, CMBitMap* nextMarkBitMap) :
3395     _task(task), _cm(cm), _nextMarkBitMap(nextMarkBitMap) { }
3396 
3397   bool do_bit(size_t offset) {
3398     HeapWord* addr = _nextMarkBitMap->offsetToHeapWord(offset);
3399     assert(_nextMarkBitMap->isMarked(addr), "invariant");
3400     assert( addr < _cm->finger(), "invariant");
3401 
3402     statsOnly( _task->increase_objs_found_on_bitmap() );
3403     assert(addr >= _task->finger(), "invariant");
3404 
3405     // We move that task's local finger along.
3406     _task->move_finger_to(addr);
3407 
3408     _task->scan_object(oop(addr));
3409     // we only partially drain the local queue and global stack
3410     _task->drain_local_queue(true);
3411     _task->drain_global_stack(true);
3412 
3413     // if the has_aborted flag has been raised, we need to bail out of
3414     // the iteration
3415     return !_task->has_aborted();
3416   }
3417 };
3418 
3419 // Closure for iterating over objects, currently only used for
3420 // processing SATB buffers.
3421 class CMObjectClosure : public ObjectClosure {
3422 private:
3423   CMTask* _task;
3424 
3425 public:
3426   void do_object(oop obj) {
3427     _task->deal_with_reference(obj);
3428   }
3429 
3430   CMObjectClosure(CMTask* task) : _task(task) { }
3431 };
3432 
3433 G1CMOopClosure::G1CMOopClosure(G1CollectedHeap* g1h,
3434                                ConcurrentMark* cm,
3435                                CMTask* task)
3436   : _g1h(g1h), _cm(cm), _task(task) {
3437   assert(_ref_processor == NULL, "should be initialized to NULL");
3438 
3439   if (G1UseConcMarkReferenceProcessing) {
3440     _ref_processor = g1h->ref_processor_cm();
3441     assert(_ref_processor != NULL, "should not be NULL");
3442   }
3443 }
3444 
3445 void CMTask::setup_for_region(HeapRegion* hr) {
3446   assert(hr != NULL,
3447         "claim_region() should have filtered out NULL regions");
3448   assert(!hr->continuesHumongous(),
3449         "claim_region() should have filtered out continues humongous regions");
3450 
3451   if (_cm->verbose_low()) {
3452     gclog_or_tty->print_cr("[%u] setting up for region "PTR_FORMAT,
3453                            _worker_id, p2i(hr));
3454   }
3455 
3456   _curr_region  = hr;
3457   _finger       = hr->bottom();
3458   update_region_limit();
3459 }
3460 
3461 void CMTask::update_region_limit() {
3462   HeapRegion* hr            = _curr_region;
3463   HeapWord* bottom          = hr->bottom();
3464   HeapWord* limit           = hr->next_top_at_mark_start();
3465 
3466   if (limit == bottom) {
3467     if (_cm->verbose_low()) {
3468       gclog_or_tty->print_cr("[%u] found an empty region "
3469                              "["PTR_FORMAT", "PTR_FORMAT")",
3470                              _worker_id, p2i(bottom), p2i(limit));
3471     }
3472     // The region was collected underneath our feet.
3473     // We set the finger to bottom to ensure that the bitmap
3474     // iteration that will follow this will not do anything.
3475     // (this is not a condition that holds when we set the region up,
3476     // as the region is not supposed to be empty in the first place)
3477     _finger = bottom;
3478   } else if (limit >= _region_limit) {
3479     assert(limit >= _finger, "peace of mind");
3480   } else {
3481     assert(limit < _region_limit, "only way to get here");
3482     // This can happen under some pretty unusual circumstances.  An
3483     // evacuation pause empties the region underneath our feet (NTAMS
3484     // at bottom). We then do some allocation in the region (NTAMS
3485     // stays at bottom), followed by the region being used as a GC
3486     // alloc region (NTAMS will move to top() and the objects
3487     // originally below it will be grayed). All objects now marked in
3488     // the region are explicitly grayed, if below the global finger,
3489     // and we do not need in fact to scan anything else. So, we simply
3490     // set _finger to be limit to ensure that the bitmap iteration
3491     // doesn't do anything.
3492     _finger = limit;
3493   }
3494 
3495   _region_limit = limit;
3496 }
3497 
3498 void CMTask::giveup_current_region() {
3499   assert(_curr_region != NULL, "invariant");
3500   if (_cm->verbose_low()) {
3501     gclog_or_tty->print_cr("[%u] giving up region "PTR_FORMAT,
3502                            _worker_id, p2i(_curr_region));
3503   }
3504   clear_region_fields();
3505 }
3506 
3507 void CMTask::clear_region_fields() {
3508   // Values for these three fields that indicate that we're not
3509   // holding on to a region.
3510   _curr_region   = NULL;
3511   _finger        = NULL;
3512   _region_limit  = NULL;
3513 }
3514 
3515 void CMTask::set_cm_oop_closure(G1CMOopClosure* cm_oop_closure) {
3516   if (cm_oop_closure == NULL) {
3517     assert(_cm_oop_closure != NULL, "invariant");
3518   } else {
3519     assert(_cm_oop_closure == NULL, "invariant");
3520   }
3521   _cm_oop_closure = cm_oop_closure;
3522 }
3523 
3524 void CMTask::reset(CMBitMap* nextMarkBitMap) {
3525   guarantee(nextMarkBitMap != NULL, "invariant");
3526 
3527   if (_cm->verbose_low()) {
3528     gclog_or_tty->print_cr("[%u] resetting", _worker_id);
3529   }
3530 
3531   _nextMarkBitMap                = nextMarkBitMap;
3532   clear_region_fields();
3533 
3534   _calls                         = 0;
3535   _elapsed_time_ms               = 0.0;
3536   _termination_time_ms           = 0.0;
3537   _termination_start_time_ms     = 0.0;
3538 
3539 #if _MARKING_STATS_
3540   _local_pushes                  = 0;
3541   _local_pops                    = 0;
3542   _local_max_size                = 0;
3543   _objs_scanned                  = 0;
3544   _global_pushes                 = 0;
3545   _global_pops                   = 0;
3546   _global_max_size               = 0;
3547   _global_transfers_to           = 0;
3548   _global_transfers_from         = 0;
3549   _regions_claimed               = 0;
3550   _objs_found_on_bitmap          = 0;
3551   _satb_buffers_processed        = 0;
3552   _steal_attempts                = 0;
3553   _steals                        = 0;
3554   _aborted                       = 0;
3555   _aborted_overflow              = 0;
3556   _aborted_cm_aborted            = 0;
3557   _aborted_yield                 = 0;
3558   _aborted_timed_out             = 0;
3559   _aborted_satb                  = 0;
3560   _aborted_termination           = 0;
3561 #endif // _MARKING_STATS_
3562 }
3563 
3564 bool CMTask::should_exit_termination() {
3565   regular_clock_call();
3566   // This is called when we are in the termination protocol. We should
3567   // quit if, for some reason, this task wants to abort or the global
3568   // stack is not empty (this means that we can get work from it).
3569   return !_cm->mark_stack_empty() || has_aborted();
3570 }
3571 
3572 void CMTask::reached_limit() {
3573   assert(_words_scanned >= _words_scanned_limit ||
3574          _refs_reached >= _refs_reached_limit ,
3575          "shouldn't have been called otherwise");
3576   regular_clock_call();
3577 }
3578 
3579 void CMTask::regular_clock_call() {
3580   if (has_aborted()) return;
3581 
3582   // First, we need to recalculate the words scanned and refs reached
3583   // limits for the next clock call.
3584   recalculate_limits();
3585 
3586   // During the regular clock call we do the following
3587 
3588   // (1) If an overflow has been flagged, then we abort.
3589   if (_cm->has_overflown()) {
3590     set_has_aborted();
3591     return;
3592   }
3593 
3594   // If we are not concurrent (i.e. we're doing remark) we don't need
3595   // to check anything else. The other steps are only needed during
3596   // the concurrent marking phase.
3597   if (!concurrent()) return;
3598 
3599   // (2) If marking has been aborted for Full GC, then we also abort.
3600   if (_cm->has_aborted()) {
3601     set_has_aborted();
3602     statsOnly( ++_aborted_cm_aborted );
3603     return;
3604   }
3605 
3606   double curr_time_ms = os::elapsedVTime() * 1000.0;
3607 
3608   // (3) If marking stats are enabled, then we update the step history.
3609 #if _MARKING_STATS_
3610   if (_words_scanned >= _words_scanned_limit) {
3611     ++_clock_due_to_scanning;
3612   }
3613   if (_refs_reached >= _refs_reached_limit) {
3614     ++_clock_due_to_marking;
3615   }
3616 
3617   double last_interval_ms = curr_time_ms - _interval_start_time_ms;
3618   _interval_start_time_ms = curr_time_ms;
3619   _all_clock_intervals_ms.add(last_interval_ms);
3620 
3621   if (_cm->verbose_medium()) {
3622       gclog_or_tty->print_cr("[%u] regular clock, interval = %1.2lfms, "
3623                         "scanned = %d%s, refs reached = %d%s",
3624                         _worker_id, last_interval_ms,
3625                         _words_scanned,
3626                         (_words_scanned >= _words_scanned_limit) ? " (*)" : "",
3627                         _refs_reached,
3628                         (_refs_reached >= _refs_reached_limit) ? " (*)" : "");
3629   }
3630 #endif // _MARKING_STATS_
3631 
3632   // (4) We check whether we should yield. If we have to, then we abort.
3633   if (SuspendibleThreadSet::should_yield()) {
3634     // We should yield. To do this we abort the task. The caller is
3635     // responsible for yielding.
3636     set_has_aborted();
3637     statsOnly( ++_aborted_yield );
3638     return;
3639   }
3640 
3641   // (5) We check whether we've reached our time quota. If we have,
3642   // then we abort.
3643   double elapsed_time_ms = curr_time_ms - _start_time_ms;
3644   if (elapsed_time_ms > _time_target_ms) {
3645     set_has_aborted();
3646     _has_timed_out = true;
3647     statsOnly( ++_aborted_timed_out );
3648     return;
3649   }
3650 
3651   // (6) Finally, we check whether there are enough completed STAB
3652   // buffers available for processing. If there are, we abort.
3653   SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
3654   if (!_draining_satb_buffers && satb_mq_set.process_completed_buffers()) {
3655     if (_cm->verbose_low()) {
3656       gclog_or_tty->print_cr("[%u] aborting to deal with pending SATB buffers",
3657                              _worker_id);
3658     }
3659     // we do need to process SATB buffers, we'll abort and restart
3660     // the marking task to do so
3661     set_has_aborted();
3662     statsOnly( ++_aborted_satb );
3663     return;
3664   }
3665 }
3666 
3667 void CMTask::recalculate_limits() {
3668   _real_words_scanned_limit = _words_scanned + words_scanned_period;
3669   _words_scanned_limit      = _real_words_scanned_limit;
3670 
3671   _real_refs_reached_limit  = _refs_reached  + refs_reached_period;
3672   _refs_reached_limit       = _real_refs_reached_limit;
3673 }
3674 
3675 void CMTask::decrease_limits() {
3676   // This is called when we believe that we're going to do an infrequent
3677   // operation which will increase the per byte scanned cost (i.e. move
3678   // entries to/from the global stack). It basically tries to decrease the
3679   // scanning limit so that the clock is called earlier.
3680 
3681   if (_cm->verbose_medium()) {
3682     gclog_or_tty->print_cr("[%u] decreasing limits", _worker_id);
3683   }
3684 
3685   _words_scanned_limit = _real_words_scanned_limit -
3686     3 * words_scanned_period / 4;
3687   _refs_reached_limit  = _real_refs_reached_limit -
3688     3 * refs_reached_period / 4;
3689 }
3690 
3691 void CMTask::move_entries_to_global_stack() {
3692   // local array where we'll store the entries that will be popped
3693   // from the local queue
3694   oop buffer[global_stack_transfer_size];
3695 
3696   int n = 0;
3697   oop obj;
3698   while (n < global_stack_transfer_size && _task_queue->pop_local(obj)) {
3699     buffer[n] = obj;
3700     ++n;
3701   }
3702 
3703   if (n > 0) {
3704     // we popped at least one entry from the local queue
3705 
3706     statsOnly( ++_global_transfers_to; _local_pops += n );
3707 
3708     if (!_cm->mark_stack_push(buffer, n)) {
3709       if (_cm->verbose_low()) {
3710         gclog_or_tty->print_cr("[%u] aborting due to global stack overflow",
3711                                _worker_id);
3712       }
3713       set_has_aborted();
3714     } else {
3715       // the transfer was successful
3716 
3717       if (_cm->verbose_medium()) {
3718         gclog_or_tty->print_cr("[%u] pushed %d entries to the global stack",
3719                                _worker_id, n);
3720       }
3721       statsOnly( int tmp_size = _cm->mark_stack_size();
3722                  if (tmp_size > _global_max_size) {
3723                    _global_max_size = tmp_size;
3724                  }
3725                  _global_pushes += n );
3726     }
3727   }
3728 
3729   // this operation was quite expensive, so decrease the limits
3730   decrease_limits();
3731 }
3732 
3733 void CMTask::get_entries_from_global_stack() {
3734   // local array where we'll store the entries that will be popped
3735   // from the global stack.
3736   oop buffer[global_stack_transfer_size];
3737   int n;
3738   _cm->mark_stack_pop(buffer, global_stack_transfer_size, &n);
3739   assert(n <= global_stack_transfer_size,
3740          "we should not pop more than the given limit");
3741   if (n > 0) {
3742     // yes, we did actually pop at least one entry
3743 
3744     statsOnly( ++_global_transfers_from; _global_pops += n );
3745     if (_cm->verbose_medium()) {
3746       gclog_or_tty->print_cr("[%u] popped %d entries from the global stack",
3747                              _worker_id, n);
3748     }
3749     for (int i = 0; i < n; ++i) {
3750       bool success = _task_queue->push(buffer[i]);
3751       // We only call this when the local queue is empty or under a
3752       // given target limit. So, we do not expect this push to fail.
3753       assert(success, "invariant");
3754     }
3755 
3756     statsOnly( int tmp_size = _task_queue->size();
3757                if (tmp_size > _local_max_size) {
3758                  _local_max_size = tmp_size;
3759                }
3760                _local_pushes += n );
3761   }
3762 
3763   // this operation was quite expensive, so decrease the limits
3764   decrease_limits();
3765 }
3766 
3767 void CMTask::drain_local_queue(bool partially) {
3768   if (has_aborted()) return;
3769 
3770   // Decide what the target size is, depending whether we're going to
3771   // drain it partially (so that other tasks can steal if they run out
3772   // of things to do) or totally (at the very end).
3773   size_t target_size;
3774   if (partially) {
3775     target_size = MIN2((size_t)_task_queue->max_elems()/3, GCDrainStackTargetSize);
3776   } else {
3777     target_size = 0;
3778   }
3779 
3780   if (_task_queue->size() > target_size) {
3781     if (_cm->verbose_high()) {
3782       gclog_or_tty->print_cr("[%u] draining local queue, target size = " SIZE_FORMAT,
3783                              _worker_id, target_size);
3784     }
3785 
3786     oop obj;
3787     bool ret = _task_queue->pop_local(obj);
3788     while (ret) {
3789       statsOnly( ++_local_pops );
3790 
3791       if (_cm->verbose_high()) {
3792         gclog_or_tty->print_cr("[%u] popped "PTR_FORMAT, _worker_id,
3793                                p2i((void*) obj));
3794       }
3795 
3796       assert(_g1h->is_in_g1_reserved((HeapWord*) obj), "invariant" );
3797       assert(!_g1h->is_on_master_free_list(
3798                   _g1h->heap_region_containing((HeapWord*) obj)), "invariant");
3799 
3800       scan_object(obj);
3801 
3802       if (_task_queue->size() <= target_size || has_aborted()) {
3803         ret = false;
3804       } else {
3805         ret = _task_queue->pop_local(obj);
3806       }
3807     }
3808 
3809     if (_cm->verbose_high()) {
3810       gclog_or_tty->print_cr("[%u] drained local queue, size = %u",
3811                              _worker_id, _task_queue->size());
3812     }
3813   }
3814 }
3815 
3816 void CMTask::drain_global_stack(bool partially) {
3817   if (has_aborted()) return;
3818 
3819   // We have a policy to drain the local queue before we attempt to
3820   // drain the global stack.
3821   assert(partially || _task_queue->size() == 0, "invariant");
3822 
3823   // Decide what the target size is, depending whether we're going to
3824   // drain it partially (so that other tasks can steal if they run out
3825   // of things to do) or totally (at the very end).  Notice that,
3826   // because we move entries from the global stack in chunks or
3827   // because another task might be doing the same, we might in fact
3828   // drop below the target. But, this is not a problem.
3829   size_t target_size;
3830   if (partially) {
3831     target_size = _cm->partial_mark_stack_size_target();
3832   } else {
3833     target_size = 0;
3834   }
3835 
3836   if (_cm->mark_stack_size() > target_size) {
3837     if (_cm->verbose_low()) {
3838       gclog_or_tty->print_cr("[%u] draining global_stack, target size " SIZE_FORMAT,
3839                              _worker_id, target_size);
3840     }
3841 
3842     while (!has_aborted() && _cm->mark_stack_size() > target_size) {
3843       get_entries_from_global_stack();
3844       drain_local_queue(partially);
3845     }
3846 
3847     if (_cm->verbose_low()) {
3848       gclog_or_tty->print_cr("[%u] drained global stack, size = " SIZE_FORMAT,
3849                              _worker_id, _cm->mark_stack_size());
3850     }
3851   }
3852 }
3853 
3854 // SATB Queue has several assumptions on whether to call the par or
3855 // non-par versions of the methods. this is why some of the code is
3856 // replicated. We should really get rid of the single-threaded version
3857 // of the code to simplify things.
3858 void CMTask::drain_satb_buffers() {
3859   if (has_aborted()) return;
3860 
3861   // We set this so that the regular clock knows that we're in the
3862   // middle of draining buffers and doesn't set the abort flag when it
3863   // notices that SATB buffers are available for draining. It'd be
3864   // very counter productive if it did that. :-)
3865   _draining_satb_buffers = true;
3866 
3867   CMObjectClosure oc(this);
3868   SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
3869   if (G1CollectedHeap::use_parallel_gc_threads()) {
3870     satb_mq_set.set_par_closure(_worker_id, &oc);
3871   } else {
3872     satb_mq_set.set_closure(&oc);
3873   }
3874 
3875   // This keeps claiming and applying the closure to completed buffers
3876   // until we run out of buffers or we need to abort.
3877   if (G1CollectedHeap::use_parallel_gc_threads()) {
3878     while (!has_aborted() &&
3879            satb_mq_set.par_apply_closure_to_completed_buffer(_worker_id)) {
3880       if (_cm->verbose_medium()) {
3881         gclog_or_tty->print_cr("[%u] processed an SATB buffer", _worker_id);
3882       }
3883       statsOnly( ++_satb_buffers_processed );
3884       regular_clock_call();
3885     }
3886   } else {
3887     while (!has_aborted() &&
3888            satb_mq_set.apply_closure_to_completed_buffer()) {
3889       if (_cm->verbose_medium()) {
3890         gclog_or_tty->print_cr("[%u] processed an SATB buffer", _worker_id);
3891       }
3892       statsOnly( ++_satb_buffers_processed );
3893       regular_clock_call();
3894     }
3895   }
3896 
3897   if (!concurrent() && !has_aborted()) {
3898     // We should only do this during remark.
3899     if (G1CollectedHeap::use_parallel_gc_threads()) {
3900       satb_mq_set.par_iterate_closure_all_threads(_worker_id);
3901     } else {
3902       satb_mq_set.iterate_closure_all_threads();
3903     }
3904   }
3905 
3906   _draining_satb_buffers = false;
3907 
3908   assert(has_aborted() ||
3909          concurrent() ||
3910          satb_mq_set.completed_buffers_num() == 0, "invariant");
3911 
3912   if (G1CollectedHeap::use_parallel_gc_threads()) {
3913     satb_mq_set.set_par_closure(_worker_id, NULL);
3914   } else {
3915     satb_mq_set.set_closure(NULL);
3916   }
3917 
3918   // again, this was a potentially expensive operation, decrease the
3919   // limits to get the regular clock call early
3920   decrease_limits();
3921 }
3922 
3923 void CMTask::print_stats() {
3924   gclog_or_tty->print_cr("Marking Stats, task = %u, calls = %d",
3925                          _worker_id, _calls);
3926   gclog_or_tty->print_cr("  Elapsed time = %1.2lfms, Termination time = %1.2lfms",
3927                          _elapsed_time_ms, _termination_time_ms);
3928   gclog_or_tty->print_cr("  Step Times (cum): num = %d, avg = %1.2lfms, sd = %1.2lfms",
3929                          _step_times_ms.num(), _step_times_ms.avg(),
3930                          _step_times_ms.sd());
3931   gclog_or_tty->print_cr("                    max = %1.2lfms, total = %1.2lfms",
3932                          _step_times_ms.maximum(), _step_times_ms.sum());
3933 
3934 #if _MARKING_STATS_
3935   gclog_or_tty->print_cr("  Clock Intervals (cum): num = %d, avg = %1.2lfms, sd = %1.2lfms",
3936                          _all_clock_intervals_ms.num(), _all_clock_intervals_ms.avg(),
3937                          _all_clock_intervals_ms.sd());
3938   gclog_or_tty->print_cr("                         max = %1.2lfms, total = %1.2lfms",
3939                          _all_clock_intervals_ms.maximum(),
3940                          _all_clock_intervals_ms.sum());
3941   gclog_or_tty->print_cr("  Clock Causes (cum): scanning = %d, marking = %d",
3942                          _clock_due_to_scanning, _clock_due_to_marking);
3943   gclog_or_tty->print_cr("  Objects: scanned = %d, found on the bitmap = %d",
3944                          _objs_scanned, _objs_found_on_bitmap);
3945   gclog_or_tty->print_cr("  Local Queue:  pushes = %d, pops = %d, max size = %d",
3946                          _local_pushes, _local_pops, _local_max_size);
3947   gclog_or_tty->print_cr("  Global Stack: pushes = %d, pops = %d, max size = %d",
3948                          _global_pushes, _global_pops, _global_max_size);
3949   gclog_or_tty->print_cr("                transfers to = %d, transfers from = %d",
3950                          _global_transfers_to,_global_transfers_from);
3951   gclog_or_tty->print_cr("  Regions: claimed = %d", _regions_claimed);
3952   gclog_or_tty->print_cr("  SATB buffers: processed = %d", _satb_buffers_processed);
3953   gclog_or_tty->print_cr("  Steals: attempts = %d, successes = %d",
3954                          _steal_attempts, _steals);
3955   gclog_or_tty->print_cr("  Aborted: %d, due to", _aborted);
3956   gclog_or_tty->print_cr("    overflow: %d, global abort: %d, yield: %d",
3957                          _aborted_overflow, _aborted_cm_aborted, _aborted_yield);
3958   gclog_or_tty->print_cr("    time out: %d, SATB: %d, termination: %d",
3959                          _aborted_timed_out, _aborted_satb, _aborted_termination);
3960 #endif // _MARKING_STATS_
3961 }
3962 
3963 /*****************************************************************************
3964 
3965     The do_marking_step(time_target_ms, ...) method is the building
3966     block of the parallel marking framework. It can be called in parallel
3967     with other invocations of do_marking_step() on different tasks
3968     (but only one per task, obviously) and concurrently with the
3969     mutator threads, or during remark, hence it eliminates the need
3970     for two versions of the code. When called during remark, it will
3971     pick up from where the task left off during the concurrent marking
3972     phase. Interestingly, tasks are also claimable during evacuation
3973     pauses too, since do_marking_step() ensures that it aborts before
3974     it needs to yield.
3975 
3976     The data structures that it uses to do marking work are the
3977     following:
3978 
3979       (1) Marking Bitmap. If there are gray objects that appear only
3980       on the bitmap (this happens either when dealing with an overflow
3981       or when the initial marking phase has simply marked the roots
3982       and didn't push them on the stack), then tasks claim heap
3983       regions whose bitmap they then scan to find gray objects. A
3984       global finger indicates where the end of the last claimed region
3985       is. A local finger indicates how far into the region a task has
3986       scanned. The two fingers are used to determine how to gray an
3987       object (i.e. whether simply marking it is OK, as it will be
3988       visited by a task in the future, or whether it needs to be also
3989       pushed on a stack).
3990 
3991       (2) Local Queue. The local queue of the task which is accessed
3992       reasonably efficiently by the task. Other tasks can steal from
3993       it when they run out of work. Throughout the marking phase, a
3994       task attempts to keep its local queue short but not totally
3995       empty, so that entries are available for stealing by other
3996       tasks. Only when there is no more work, a task will totally
3997       drain its local queue.
3998 
3999       (3) Global Mark Stack. This handles local queue overflow. During
4000       marking only sets of entries are moved between it and the local
4001       queues, as access to it requires a mutex and more fine-grain
4002       interaction with it which might cause contention. If it
4003       overflows, then the marking phase should restart and iterate
4004       over the bitmap to identify gray objects. Throughout the marking
4005       phase, tasks attempt to keep the global mark stack at a small
4006       length but not totally empty, so that entries are available for
4007       popping by other tasks. Only when there is no more work, tasks
4008       will totally drain the global mark stack.
4009 
4010       (4) SATB Buffer Queue. This is where completed SATB buffers are
4011       made available. Buffers are regularly removed from this queue
4012       and scanned for roots, so that the queue doesn't get too
4013       long. During remark, all completed buffers are processed, as
4014       well as the filled in parts of any uncompleted buffers.
4015 
4016     The do_marking_step() method tries to abort when the time target
4017     has been reached. There are a few other cases when the
4018     do_marking_step() method also aborts:
4019 
4020       (1) When the marking phase has been aborted (after a Full GC).
4021 
4022       (2) When a global overflow (on the global stack) has been
4023       triggered. Before the task aborts, it will actually sync up with
4024       the other tasks to ensure that all the marking data structures
4025       (local queues, stacks, fingers etc.)  are re-initialized so that
4026       when do_marking_step() completes, the marking phase can
4027       immediately restart.
4028 
4029       (3) When enough completed SATB buffers are available. The
4030       do_marking_step() method only tries to drain SATB buffers right
4031       at the beginning. So, if enough buffers are available, the
4032       marking step aborts and the SATB buffers are processed at
4033       the beginning of the next invocation.
4034 
4035       (4) To yield. when we have to yield then we abort and yield
4036       right at the end of do_marking_step(). This saves us from a lot
4037       of hassle as, by yielding we might allow a Full GC. If this
4038       happens then objects will be compacted underneath our feet, the
4039       heap might shrink, etc. We save checking for this by just
4040       aborting and doing the yield right at the end.
4041 
4042     From the above it follows that the do_marking_step() method should
4043     be called in a loop (or, otherwise, regularly) until it completes.
4044 
4045     If a marking step completes without its has_aborted() flag being
4046     true, it means it has completed the current marking phase (and
4047     also all other marking tasks have done so and have all synced up).
4048 
4049     A method called regular_clock_call() is invoked "regularly" (in
4050     sub ms intervals) throughout marking. It is this clock method that
4051     checks all the abort conditions which were mentioned above and
4052     decides when the task should abort. A work-based scheme is used to
4053     trigger this clock method: when the number of object words the
4054     marking phase has scanned or the number of references the marking
4055     phase has visited reach a given limit. Additional invocations to
4056     the method clock have been planted in a few other strategic places
4057     too. The initial reason for the clock method was to avoid calling
4058     vtime too regularly, as it is quite expensive. So, once it was in
4059     place, it was natural to piggy-back all the other conditions on it
4060     too and not constantly check them throughout the code.
4061 
4062     If do_termination is true then do_marking_step will enter its
4063     termination protocol.
4064 
4065     The value of is_serial must be true when do_marking_step is being
4066     called serially (i.e. by the VMThread) and do_marking_step should
4067     skip any synchronization in the termination and overflow code.
4068     Examples include the serial remark code and the serial reference
4069     processing closures.
4070 
4071     The value of is_serial must be false when do_marking_step is
4072     being called by any of the worker threads in a work gang.
4073     Examples include the concurrent marking code (CMMarkingTask),
4074     the MT remark code, and the MT reference processing closures.
4075 
4076  *****************************************************************************/
4077 
4078 void CMTask::do_marking_step(double time_target_ms,
4079                              bool do_termination,
4080                              bool is_serial) {
4081   assert(time_target_ms >= 1.0, "minimum granularity is 1ms");
4082   assert(concurrent() == _cm->concurrent(), "they should be the same");
4083 
4084   G1CollectorPolicy* g1_policy = _g1h->g1_policy();
4085   assert(_task_queues != NULL, "invariant");
4086   assert(_task_queue != NULL, "invariant");
4087   assert(_task_queues->queue(_worker_id) == _task_queue, "invariant");
4088 
4089   assert(!_claimed,
4090          "only one thread should claim this task at any one time");
4091 
4092   // OK, this doesn't safeguard again all possible scenarios, as it is
4093   // possible for two threads to set the _claimed flag at the same
4094   // time. But it is only for debugging purposes anyway and it will
4095   // catch most problems.
4096   _claimed = true;
4097 
4098   _start_time_ms = os::elapsedVTime() * 1000.0;
4099   statsOnly( _interval_start_time_ms = _start_time_ms );
4100 
4101   // If do_stealing is true then do_marking_step will attempt to
4102   // steal work from the other CMTasks. It only makes sense to
4103   // enable stealing when the termination protocol is enabled
4104   // and do_marking_step() is not being called serially.
4105   bool do_stealing = do_termination && !is_serial;
4106 
4107   double diff_prediction_ms =
4108     g1_policy->get_new_prediction(&_marking_step_diffs_ms);
4109   _time_target_ms = time_target_ms - diff_prediction_ms;
4110 
4111   // set up the variables that are used in the work-based scheme to
4112   // call the regular clock method
4113   _words_scanned = 0;
4114   _refs_reached  = 0;
4115   recalculate_limits();
4116 
4117   // clear all flags
4118   clear_has_aborted();
4119   _has_timed_out = false;
4120   _draining_satb_buffers = false;
4121 
4122   ++_calls;
4123 
4124   if (_cm->verbose_low()) {
4125     gclog_or_tty->print_cr("[%u] >>>>>>>>>> START, call = %d, "
4126                            "target = %1.2lfms >>>>>>>>>>",
4127                            _worker_id, _calls, _time_target_ms);
4128   }
4129 
4130   // Set up the bitmap and oop closures. Anything that uses them is
4131   // eventually called from this method, so it is OK to allocate these
4132   // statically.
4133   CMBitMapClosure bitmap_closure(this, _cm, _nextMarkBitMap);
4134   G1CMOopClosure  cm_oop_closure(_g1h, _cm, this);
4135   set_cm_oop_closure(&cm_oop_closure);
4136 
4137   if (_cm->has_overflown()) {
4138     // This can happen if the mark stack overflows during a GC pause
4139     // and this task, after a yield point, restarts. We have to abort
4140     // as we need to get into the overflow protocol which happens
4141     // right at the end of this task.
4142     set_has_aborted();
4143   }
4144 
4145   // First drain any available SATB buffers. After this, we will not
4146   // look at SATB buffers before the next invocation of this method.
4147   // If enough completed SATB buffers are queued up, the regular clock
4148   // will abort this task so that it restarts.
4149   drain_satb_buffers();
4150   // ...then partially drain the local queue and the global stack
4151   drain_local_queue(true);
4152   drain_global_stack(true);
4153 
4154   do {
4155     if (!has_aborted() && _curr_region != NULL) {
4156       // This means that we're already holding on to a region.
4157       assert(_finger != NULL, "if region is not NULL, then the finger "
4158              "should not be NULL either");
4159 
4160       // We might have restarted this task after an evacuation pause
4161       // which might have evacuated the region we're holding on to
4162       // underneath our feet. Let's read its limit again to make sure
4163       // that we do not iterate over a region of the heap that
4164       // contains garbage (update_region_limit() will also move
4165       // _finger to the start of the region if it is found empty).
4166       update_region_limit();
4167       // We will start from _finger not from the start of the region,
4168       // as we might be restarting this task after aborting half-way
4169       // through scanning this region. In this case, _finger points to
4170       // the address where we last found a marked object. If this is a
4171       // fresh region, _finger points to start().
4172       MemRegion mr = MemRegion(_finger, _region_limit);
4173 
4174       if (_cm->verbose_low()) {
4175         gclog_or_tty->print_cr("[%u] we're scanning part "
4176                                "["PTR_FORMAT", "PTR_FORMAT") "
4177                                "of region "HR_FORMAT,
4178                                _worker_id, p2i(_finger), p2i(_region_limit),
4179                                HR_FORMAT_PARAMS(_curr_region));
4180       }
4181 
4182       assert(!_curr_region->isHumongous() || mr.start() == _curr_region->bottom(),
4183              "humongous regions should go around loop once only");
4184 
4185       // Some special cases:
4186       // If the memory region is empty, we can just give up the region.
4187       // If the current region is humongous then we only need to check
4188       // the bitmap for the bit associated with the start of the object,
4189       // scan the object if it's live, and give up the region.
4190       // Otherwise, let's iterate over the bitmap of the part of the region
4191       // that is left.
4192       // If the iteration is successful, give up the region.
4193       if (mr.is_empty()) {
4194         giveup_current_region();
4195         regular_clock_call();
4196       } else if (_curr_region->isHumongous() && mr.start() == _curr_region->bottom()) {
4197         if (_nextMarkBitMap->isMarked(mr.start())) {
4198           // The object is marked - apply the closure
4199           BitMap::idx_t offset = _nextMarkBitMap->heapWordToOffset(mr.start());
4200           bitmap_closure.do_bit(offset);
4201         }
4202         // Even if this task aborted while scanning the humongous object
4203         // we can (and should) give up the current region.
4204         giveup_current_region();
4205         regular_clock_call();
4206       } else if (_nextMarkBitMap->iterate(&bitmap_closure, mr)) {
4207         giveup_current_region();
4208         regular_clock_call();
4209       } else {
4210         assert(has_aborted(), "currently the only way to do so");
4211         // The only way to abort the bitmap iteration is to return
4212         // false from the do_bit() method. However, inside the
4213         // do_bit() method we move the _finger to point to the
4214         // object currently being looked at. So, if we bail out, we
4215         // have definitely set _finger to something non-null.
4216         assert(_finger != NULL, "invariant");
4217 
4218         // Region iteration was actually aborted. So now _finger
4219         // points to the address of the object we last scanned. If we
4220         // leave it there, when we restart this task, we will rescan
4221         // the object. It is easy to avoid this. We move the finger by
4222         // enough to point to the next possible object header (the
4223         // bitmap knows by how much we need to move it as it knows its
4224         // granularity).
4225         assert(_finger < _region_limit, "invariant");
4226         HeapWord* new_finger = _nextMarkBitMap->nextObject(_finger);
4227         // Check if bitmap iteration was aborted while scanning the last object
4228         if (new_finger >= _region_limit) {
4229           giveup_current_region();
4230         } else {
4231           move_finger_to(new_finger);
4232         }
4233       }
4234     }
4235     // At this point we have either completed iterating over the
4236     // region we were holding on to, or we have aborted.
4237 
4238     // We then partially drain the local queue and the global stack.
4239     // (Do we really need this?)
4240     drain_local_queue(true);
4241     drain_global_stack(true);
4242 
4243     // Read the note on the claim_region() method on why it might
4244     // return NULL with potentially more regions available for
4245     // claiming and why we have to check out_of_regions() to determine
4246     // whether we're done or not.
4247     while (!has_aborted() && _curr_region == NULL && !_cm->out_of_regions()) {
4248       // We are going to try to claim a new region. We should have
4249       // given up on the previous one.
4250       // Separated the asserts so that we know which one fires.
4251       assert(_curr_region  == NULL, "invariant");
4252       assert(_finger       == NULL, "invariant");
4253       assert(_region_limit == NULL, "invariant");
4254       if (_cm->verbose_low()) {
4255         gclog_or_tty->print_cr("[%u] trying to claim a new region", _worker_id);
4256       }
4257       HeapRegion* claimed_region = _cm->claim_region(_worker_id);
4258       if (claimed_region != NULL) {
4259         // Yes, we managed to claim one
4260         statsOnly( ++_regions_claimed );
4261 
4262         if (_cm->verbose_low()) {
4263           gclog_or_tty->print_cr("[%u] we successfully claimed "
4264                                  "region "PTR_FORMAT,
4265                                  _worker_id, p2i(claimed_region));
4266         }
4267 
4268         setup_for_region(claimed_region);
4269         assert(_curr_region == claimed_region, "invariant");
4270       }
4271       // It is important to call the regular clock here. It might take
4272       // a while to claim a region if, for example, we hit a large
4273       // block of empty regions. So we need to call the regular clock
4274       // method once round the loop to make sure it's called
4275       // frequently enough.
4276       regular_clock_call();
4277     }
4278 
4279     if (!has_aborted() && _curr_region == NULL) {
4280       assert(_cm->out_of_regions(),
4281              "at this point we should be out of regions");
4282     }
4283   } while ( _curr_region != NULL && !has_aborted());
4284 
4285   if (!has_aborted()) {
4286     // We cannot check whether the global stack is empty, since other
4287     // tasks might be pushing objects to it concurrently.
4288     assert(_cm->out_of_regions(),
4289            "at this point we should be out of regions");
4290 
4291     if (_cm->verbose_low()) {
4292       gclog_or_tty->print_cr("[%u] all regions claimed", _worker_id);
4293     }
4294 
4295     // Try to reduce the number of available SATB buffers so that
4296     // remark has less work to do.
4297     drain_satb_buffers();
4298   }
4299 
4300   // Since we've done everything else, we can now totally drain the
4301   // local queue and global stack.
4302   drain_local_queue(false);
4303   drain_global_stack(false);
4304 
4305   // Attempt at work stealing from other task's queues.
4306   if (do_stealing && !has_aborted()) {
4307     // We have not aborted. This means that we have finished all that
4308     // we could. Let's try to do some stealing...
4309 
4310     // We cannot check whether the global stack is empty, since other
4311     // tasks might be pushing objects to it concurrently.
4312     assert(_cm->out_of_regions() && _task_queue->size() == 0,
4313            "only way to reach here");
4314 
4315     if (_cm->verbose_low()) {
4316       gclog_or_tty->print_cr("[%u] starting to steal", _worker_id);
4317     }
4318 
4319     while (!has_aborted()) {
4320       oop obj;
4321       statsOnly( ++_steal_attempts );
4322 
4323       if (_cm->try_stealing(_worker_id, &_hash_seed, obj)) {
4324         if (_cm->verbose_medium()) {
4325           gclog_or_tty->print_cr("[%u] stolen "PTR_FORMAT" successfully",
4326                                  _worker_id, p2i((void*) obj));
4327         }
4328 
4329         statsOnly( ++_steals );
4330 
4331         assert(_nextMarkBitMap->isMarked((HeapWord*) obj),
4332                "any stolen object should be marked");
4333         scan_object(obj);
4334 
4335         // And since we're towards the end, let's totally drain the
4336         // local queue and global stack.
4337         drain_local_queue(false);
4338         drain_global_stack(false);
4339       } else {
4340         break;
4341       }
4342     }
4343   }
4344 
4345   // If we are about to wrap up and go into termination, check if we
4346   // should raise the overflow flag.
4347   if (do_termination && !has_aborted()) {
4348     if (_cm->force_overflow()->should_force()) {
4349       _cm->set_has_overflown();
4350       regular_clock_call();
4351     }
4352   }
4353 
4354   // We still haven't aborted. Now, let's try to get into the
4355   // termination protocol.
4356   if (do_termination && !has_aborted()) {
4357     // We cannot check whether the global stack is empty, since other
4358     // tasks might be concurrently pushing objects on it.
4359     // Separated the asserts so that we know which one fires.
4360     assert(_cm->out_of_regions(), "only way to reach here");
4361     assert(_task_queue->size() == 0, "only way to reach here");
4362 
4363     if (_cm->verbose_low()) {
4364       gclog_or_tty->print_cr("[%u] starting termination protocol", _worker_id);
4365     }
4366 
4367     _termination_start_time_ms = os::elapsedVTime() * 1000.0;
4368 
4369     // The CMTask class also extends the TerminatorTerminator class,
4370     // hence its should_exit_termination() method will also decide
4371     // whether to exit the termination protocol or not.
4372     bool finished = (is_serial ||
4373                      _cm->terminator()->offer_termination(this));
4374     double termination_end_time_ms = os::elapsedVTime() * 1000.0;
4375     _termination_time_ms +=
4376       termination_end_time_ms - _termination_start_time_ms;
4377 
4378     if (finished) {
4379       // We're all done.
4380 
4381       if (_worker_id == 0) {
4382         // let's allow task 0 to do this
4383         if (concurrent()) {
4384           assert(_cm->concurrent_marking_in_progress(), "invariant");
4385           // we need to set this to false before the next
4386           // safepoint. This way we ensure that the marking phase
4387           // doesn't observe any more heap expansions.
4388           _cm->clear_concurrent_marking_in_progress();
4389         }
4390       }
4391 
4392       // We can now guarantee that the global stack is empty, since
4393       // all other tasks have finished. We separated the guarantees so
4394       // that, if a condition is false, we can immediately find out
4395       // which one.
4396       guarantee(_cm->out_of_regions(), "only way to reach here");
4397       guarantee(_cm->mark_stack_empty(), "only way to reach here");
4398       guarantee(_task_queue->size() == 0, "only way to reach here");
4399       guarantee(!_cm->has_overflown(), "only way to reach here");
4400       guarantee(!_cm->mark_stack_overflow(), "only way to reach here");
4401 
4402       if (_cm->verbose_low()) {
4403         gclog_or_tty->print_cr("[%u] all tasks terminated", _worker_id);
4404       }
4405     } else {
4406       // Apparently there's more work to do. Let's abort this task. It
4407       // will restart it and we can hopefully find more things to do.
4408 
4409       if (_cm->verbose_low()) {
4410         gclog_or_tty->print_cr("[%u] apparently there is more work to do",
4411                                _worker_id);
4412       }
4413 
4414       set_has_aborted();
4415       statsOnly( ++_aborted_termination );
4416     }
4417   }
4418 
4419   // Mainly for debugging purposes to make sure that a pointer to the
4420   // closure which was statically allocated in this frame doesn't
4421   // escape it by accident.
4422   set_cm_oop_closure(NULL);
4423   double end_time_ms = os::elapsedVTime() * 1000.0;
4424   double elapsed_time_ms = end_time_ms - _start_time_ms;
4425   // Update the step history.
4426   _step_times_ms.add(elapsed_time_ms);
4427 
4428   if (has_aborted()) {
4429     // The task was aborted for some reason.
4430 
4431     statsOnly( ++_aborted );
4432 
4433     if (_has_timed_out) {
4434       double diff_ms = elapsed_time_ms - _time_target_ms;
4435       // Keep statistics of how well we did with respect to hitting
4436       // our target only if we actually timed out (if we aborted for
4437       // other reasons, then the results might get skewed).
4438       _marking_step_diffs_ms.add(diff_ms);
4439     }
4440 
4441     if (_cm->has_overflown()) {
4442       // This is the interesting one. We aborted because a global
4443       // overflow was raised. This means we have to restart the
4444       // marking phase and start iterating over regions. However, in
4445       // order to do this we have to make sure that all tasks stop
4446       // what they are doing and re-initialize in a safe manner. We
4447       // will achieve this with the use of two barrier sync points.
4448 
4449       if (_cm->verbose_low()) {
4450         gclog_or_tty->print_cr("[%u] detected overflow", _worker_id);
4451       }
4452 
4453       if (!is_serial) {
4454         // We only need to enter the sync barrier if being called
4455         // from a parallel context
4456         _cm->enter_first_sync_barrier(_worker_id);
4457 
4458         // When we exit this sync barrier we know that all tasks have
4459         // stopped doing marking work. So, it's now safe to
4460         // re-initialize our data structures. At the end of this method,
4461         // task 0 will clear the global data structures.
4462       }
4463 
4464       statsOnly( ++_aborted_overflow );
4465 
4466       // We clear the local state of this task...
4467       clear_region_fields();
4468 
4469       if (!is_serial) {
4470         // ...and enter the second barrier.
4471         _cm->enter_second_sync_barrier(_worker_id);
4472       }
4473       // At this point, if we're during the concurrent phase of
4474       // marking, everything has been re-initialized and we're
4475       // ready to restart.
4476     }
4477 
4478     if (_cm->verbose_low()) {
4479       gclog_or_tty->print_cr("[%u] <<<<<<<<<< ABORTING, target = %1.2lfms, "
4480                              "elapsed = %1.2lfms <<<<<<<<<<",
4481                              _worker_id, _time_target_ms, elapsed_time_ms);
4482       if (_cm->has_aborted()) {
4483         gclog_or_tty->print_cr("[%u] ========== MARKING ABORTED ==========",
4484                                _worker_id);
4485       }
4486     }
4487   } else {
4488     if (_cm->verbose_low()) {
4489       gclog_or_tty->print_cr("[%u] <<<<<<<<<< FINISHED, target = %1.2lfms, "
4490                              "elapsed = %1.2lfms <<<<<<<<<<",
4491                              _worker_id, _time_target_ms, elapsed_time_ms);
4492     }
4493   }
4494 
4495   _claimed = false;
4496 }
4497 
4498 CMTask::CMTask(uint worker_id,
4499                ConcurrentMark* cm,
4500                size_t* marked_bytes,
4501                BitMap* card_bm,
4502                CMTaskQueue* task_queue,
4503                CMTaskQueueSet* task_queues)
4504   : _g1h(G1CollectedHeap::heap()),
4505     _worker_id(worker_id), _cm(cm),
4506     _claimed(false),
4507     _nextMarkBitMap(NULL), _hash_seed(17),
4508     _task_queue(task_queue),
4509     _task_queues(task_queues),
4510     _cm_oop_closure(NULL),
4511     _marked_bytes_array(marked_bytes),
4512     _card_bm(card_bm) {
4513   guarantee(task_queue != NULL, "invariant");
4514   guarantee(task_queues != NULL, "invariant");
4515 
4516   statsOnly( _clock_due_to_scanning = 0;
4517              _clock_due_to_marking  = 0 );
4518 
4519   _marking_step_diffs_ms.add(0.5);
4520 }
4521 
4522 // These are formatting macros that are used below to ensure
4523 // consistent formatting. The *_H_* versions are used to format the
4524 // header for a particular value and they should be kept consistent
4525 // with the corresponding macro. Also note that most of the macros add
4526 // the necessary white space (as a prefix) which makes them a bit
4527 // easier to compose.
4528 
4529 // All the output lines are prefixed with this string to be able to
4530 // identify them easily in a large log file.
4531 #define G1PPRL_LINE_PREFIX            "###"
4532 
4533 #define G1PPRL_ADDR_BASE_FORMAT    " "PTR_FORMAT"-"PTR_FORMAT
4534 #ifdef _LP64
4535 #define G1PPRL_ADDR_BASE_H_FORMAT  " %37s"
4536 #else // _LP64
4537 #define G1PPRL_ADDR_BASE_H_FORMAT  " %21s"
4538 #endif // _LP64
4539 
4540 // For per-region info
4541 #define G1PPRL_TYPE_FORMAT            "   %-4s"
4542 #define G1PPRL_TYPE_H_FORMAT          "   %4s"
4543 #define G1PPRL_BYTE_FORMAT            "  "SIZE_FORMAT_W(9)
4544 #define G1PPRL_BYTE_H_FORMAT          "  %9s"
4545 #define G1PPRL_DOUBLE_FORMAT          "  %14.1f"
4546 #define G1PPRL_DOUBLE_H_FORMAT        "  %14s"
4547 
4548 // For summary info
4549 #define G1PPRL_SUM_ADDR_FORMAT(tag)    "  "tag":"G1PPRL_ADDR_BASE_FORMAT
4550 #define G1PPRL_SUM_BYTE_FORMAT(tag)    "  "tag": "SIZE_FORMAT
4551 #define G1PPRL_SUM_MB_FORMAT(tag)      "  "tag": %1.2f MB"
4552 #define G1PPRL_SUM_MB_PERC_FORMAT(tag) G1PPRL_SUM_MB_FORMAT(tag)" / %1.2f %%"
4553 
4554 G1PrintRegionLivenessInfoClosure::
4555 G1PrintRegionLivenessInfoClosure(outputStream* out, const char* phase_name)
4556   : _out(out),
4557     _total_used_bytes(0), _total_capacity_bytes(0),
4558     _total_prev_live_bytes(0), _total_next_live_bytes(0),
4559     _hum_used_bytes(0), _hum_capacity_bytes(0),
4560     _hum_prev_live_bytes(0), _hum_next_live_bytes(0),
4561     _total_remset_bytes(0), _total_strong_code_roots_bytes(0) {
4562   G1CollectedHeap* g1h = G1CollectedHeap::heap();
4563   MemRegion g1_committed = g1h->g1_committed();
4564   MemRegion g1_reserved = g1h->g1_reserved();
4565   double now = os::elapsedTime();
4566 
4567   // Print the header of the output.
4568   _out->cr();
4569   _out->print_cr(G1PPRL_LINE_PREFIX" PHASE %s @ %1.3f", phase_name, now);
4570   _out->print_cr(G1PPRL_LINE_PREFIX" HEAP"
4571                  G1PPRL_SUM_ADDR_FORMAT("committed")
4572                  G1PPRL_SUM_ADDR_FORMAT("reserved")
4573                  G1PPRL_SUM_BYTE_FORMAT("region-size"),
4574                  p2i(g1_committed.start()), p2i(g1_committed.end()),
4575                  p2i(g1_reserved.start()), p2i(g1_reserved.end()),
4576                  HeapRegion::GrainBytes);
4577   _out->print_cr(G1PPRL_LINE_PREFIX);
4578   _out->print_cr(G1PPRL_LINE_PREFIX
4579                 G1PPRL_TYPE_H_FORMAT
4580                 G1PPRL_ADDR_BASE_H_FORMAT
4581                 G1PPRL_BYTE_H_FORMAT
4582                 G1PPRL_BYTE_H_FORMAT
4583                 G1PPRL_BYTE_H_FORMAT
4584                 G1PPRL_DOUBLE_H_FORMAT
4585                 G1PPRL_BYTE_H_FORMAT
4586                 G1PPRL_BYTE_H_FORMAT,
4587                 "type", "address-range",
4588                 "used", "prev-live", "next-live", "gc-eff",
4589                 "remset", "code-roots");
4590   _out->print_cr(G1PPRL_LINE_PREFIX
4591                 G1PPRL_TYPE_H_FORMAT
4592                 G1PPRL_ADDR_BASE_H_FORMAT
4593                 G1PPRL_BYTE_H_FORMAT
4594                 G1PPRL_BYTE_H_FORMAT
4595                 G1PPRL_BYTE_H_FORMAT
4596                 G1PPRL_DOUBLE_H_FORMAT
4597                 G1PPRL_BYTE_H_FORMAT
4598                 G1PPRL_BYTE_H_FORMAT,
4599                 "", "",
4600                 "(bytes)", "(bytes)", "(bytes)", "(bytes/ms)",
4601                 "(bytes)", "(bytes)");
4602 }
4603 
4604 // It takes as a parameter a reference to one of the _hum_* fields, it
4605 // deduces the corresponding value for a region in a humongous region
4606 // series (either the region size, or what's left if the _hum_* field
4607 // is < the region size), and updates the _hum_* field accordingly.
4608 size_t G1PrintRegionLivenessInfoClosure::get_hum_bytes(size_t* hum_bytes) {
4609   size_t bytes = 0;
4610   // The > 0 check is to deal with the prev and next live bytes which
4611   // could be 0.
4612   if (*hum_bytes > 0) {
4613     bytes = MIN2(HeapRegion::GrainBytes, *hum_bytes);
4614     *hum_bytes -= bytes;
4615   }
4616   return bytes;
4617 }
4618 
4619 // It deduces the values for a region in a humongous region series
4620 // from the _hum_* fields and updates those accordingly. It assumes
4621 // that that _hum_* fields have already been set up from the "starts
4622 // humongous" region and we visit the regions in address order.
4623 void G1PrintRegionLivenessInfoClosure::get_hum_bytes(size_t* used_bytes,
4624                                                      size_t* capacity_bytes,
4625                                                      size_t* prev_live_bytes,
4626                                                      size_t* next_live_bytes) {
4627   assert(_hum_used_bytes > 0 && _hum_capacity_bytes > 0, "pre-condition");
4628   *used_bytes      = get_hum_bytes(&_hum_used_bytes);
4629   *capacity_bytes  = get_hum_bytes(&_hum_capacity_bytes);
4630   *prev_live_bytes = get_hum_bytes(&_hum_prev_live_bytes);
4631   *next_live_bytes = get_hum_bytes(&_hum_next_live_bytes);
4632 }
4633 
4634 bool G1PrintRegionLivenessInfoClosure::doHeapRegion(HeapRegion* r) {
4635   const char* type = "";
4636   HeapWord* bottom       = r->bottom();
4637   HeapWord* end          = r->end();
4638   size_t capacity_bytes  = r->capacity();
4639   size_t used_bytes      = r->used();
4640   size_t prev_live_bytes = r->live_bytes();
4641   size_t next_live_bytes = r->next_live_bytes();
4642   double gc_eff          = r->gc_efficiency();
4643   size_t remset_bytes    = r->rem_set()->mem_size();
4644   size_t strong_code_roots_bytes = r->rem_set()->strong_code_roots_mem_size();
4645 
4646   if (r->used() == 0) {
4647     type = "FREE";
4648   } else if (r->is_survivor()) {
4649     type = "SURV";
4650   } else if (r->is_young()) {
4651     type = "EDEN";
4652   } else if (r->startsHumongous()) {
4653     type = "HUMS";
4654 
4655     assert(_hum_used_bytes == 0 && _hum_capacity_bytes == 0 &&
4656            _hum_prev_live_bytes == 0 && _hum_next_live_bytes == 0,
4657            "they should have been zeroed after the last time we used them");
4658     // Set up the _hum_* fields.
4659     _hum_capacity_bytes  = capacity_bytes;
4660     _hum_used_bytes      = used_bytes;
4661     _hum_prev_live_bytes = prev_live_bytes;
4662     _hum_next_live_bytes = next_live_bytes;
4663     get_hum_bytes(&used_bytes, &capacity_bytes,
4664                   &prev_live_bytes, &next_live_bytes);
4665     end = bottom + HeapRegion::GrainWords;
4666   } else if (r->continuesHumongous()) {
4667     type = "HUMC";
4668     get_hum_bytes(&used_bytes, &capacity_bytes,
4669                   &prev_live_bytes, &next_live_bytes);
4670     assert(end == bottom + HeapRegion::GrainWords, "invariant");
4671   } else {
4672     type = "OLD";
4673   }
4674 
4675   _total_used_bytes      += used_bytes;
4676   _total_capacity_bytes  += capacity_bytes;
4677   _total_prev_live_bytes += prev_live_bytes;
4678   _total_next_live_bytes += next_live_bytes;
4679   _total_remset_bytes    += remset_bytes;
4680   _total_strong_code_roots_bytes += strong_code_roots_bytes;
4681 
4682   // Print a line for this particular region.
4683   _out->print_cr(G1PPRL_LINE_PREFIX
4684                  G1PPRL_TYPE_FORMAT
4685                  G1PPRL_ADDR_BASE_FORMAT
4686                  G1PPRL_BYTE_FORMAT
4687                  G1PPRL_BYTE_FORMAT
4688                  G1PPRL_BYTE_FORMAT
4689                  G1PPRL_DOUBLE_FORMAT
4690                  G1PPRL_BYTE_FORMAT
4691                  G1PPRL_BYTE_FORMAT,
4692                  type, p2i(bottom), p2i(end),
4693                  used_bytes, prev_live_bytes, next_live_bytes, gc_eff,
4694                  remset_bytes, strong_code_roots_bytes);
4695 
4696   return false;
4697 }
4698 
4699 G1PrintRegionLivenessInfoClosure::~G1PrintRegionLivenessInfoClosure() {
4700   // add static memory usages to remembered set sizes
4701   _total_remset_bytes += HeapRegionRemSet::fl_mem_size() + HeapRegionRemSet::static_mem_size();
4702   // Print the footer of the output.
4703   _out->print_cr(G1PPRL_LINE_PREFIX);
4704   _out->print_cr(G1PPRL_LINE_PREFIX
4705                  " SUMMARY"
4706                  G1PPRL_SUM_MB_FORMAT("capacity")
4707                  G1PPRL_SUM_MB_PERC_FORMAT("used")
4708                  G1PPRL_SUM_MB_PERC_FORMAT("prev-live")
4709                  G1PPRL_SUM_MB_PERC_FORMAT("next-live")
4710                  G1PPRL_SUM_MB_FORMAT("remset")
4711                  G1PPRL_SUM_MB_FORMAT("code-roots"),
4712                  bytes_to_mb(_total_capacity_bytes),
4713                  bytes_to_mb(_total_used_bytes),
4714                  perc(_total_used_bytes, _total_capacity_bytes),
4715                  bytes_to_mb(_total_prev_live_bytes),
4716                  perc(_total_prev_live_bytes, _total_capacity_bytes),
4717                  bytes_to_mb(_total_next_live_bytes),
4718                  perc(_total_next_live_bytes, _total_capacity_bytes),
4719                  bytes_to_mb(_total_remset_bytes),
4720                  bytes_to_mb(_total_strong_code_roots_bytes));
4721   _out->cr();
4722 }