1 /*
   2  * Copyright (c) 2001, 2016, 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/metadataOnStackMark.hpp"
  27 #include "classfile/symbolTable.hpp"
  28 #include "code/codeCache.hpp"
  29 #include "gc/g1/concurrentMarkThread.inline.hpp"
  30 #include "gc/g1/g1CollectedHeap.inline.hpp"
  31 #include "gc/g1/g1CollectorState.hpp"
  32 #include "gc/g1/g1ConcurrentMark.inline.hpp"
  33 #include "gc/g1/g1HeapVerifier.hpp"
  34 #include "gc/g1/g1OopClosures.inline.hpp"
  35 #include "gc/g1/g1CardLiveData.inline.hpp"
  36 #include "gc/g1/g1Policy.hpp"
  37 #include "gc/g1/g1StringDedup.hpp"
  38 #include "gc/g1/heapRegion.inline.hpp"
  39 #include "gc/g1/heapRegionRemSet.hpp"
  40 #include "gc/g1/heapRegionSet.inline.hpp"
  41 #include "gc/g1/suspendibleThreadSet.hpp"
  42 #include "gc/shared/gcId.hpp"
  43 #include "gc/shared/gcTimer.hpp"
  44 #include "gc/shared/gcTrace.hpp"
  45 #include "gc/shared/gcTraceTime.inline.hpp"
  46 #include "gc/shared/genOopClosures.inline.hpp"
  47 #include "gc/shared/referencePolicy.hpp"
  48 #include "gc/shared/strongRootsScope.hpp"
  49 #include "gc/shared/taskqueue.inline.hpp"
  50 #include "gc/shared/vmGCOperations.hpp"
  51 #include "logging/log.hpp"
  52 #include "memory/allocation.hpp"
  53 #include "memory/resourceArea.hpp"
  54 #include "oops/oop.inline.hpp"
  55 #include "runtime/atomic.inline.hpp"
  56 #include "runtime/handles.inline.hpp"
  57 #include "runtime/java.hpp"
  58 #include "runtime/prefetch.inline.hpp"
  59 #include "services/memTracker.hpp"
  60 #include "utilities/growableArray.hpp"
  61 
  62 // Concurrent marking bit map wrapper
  63 
  64 G1CMBitMapRO::G1CMBitMapRO(int shifter) :
  65   _bm(),
  66   _shifter(shifter) {
  67   _bmStartWord = 0;
  68   _bmWordSize = 0;
  69 }
  70 
  71 HeapWord* G1CMBitMapRO::getNextMarkedWordAddress(const HeapWord* addr,
  72                                                  const HeapWord* limit) const {
  73   // First we must round addr *up* to a possible object boundary.
  74   addr = (HeapWord*)align_size_up((intptr_t)addr,
  75                                   HeapWordSize << _shifter);
  76   size_t addrOffset = heapWordToOffset(addr);
  77   assert(limit != NULL, "limit must not be NULL");
  78   size_t limitOffset = heapWordToOffset(limit);
  79   size_t nextOffset = _bm.get_next_one_offset(addrOffset, limitOffset);
  80   HeapWord* nextAddr = offsetToHeapWord(nextOffset);
  81   assert(nextAddr >= addr, "get_next_one postcondition");
  82   assert(nextAddr == limit || isMarked(nextAddr),
  83          "get_next_one postcondition");
  84   return nextAddr;
  85 }
  86 
  87 #ifndef PRODUCT
  88 bool G1CMBitMapRO::covers(MemRegion heap_rs) const {
  89   // assert(_bm.map() == _virtual_space.low(), "map inconsistency");
  90   assert(((size_t)_bm.size() * ((size_t)1 << _shifter)) == _bmWordSize,
  91          "size inconsistency");
  92   return _bmStartWord == (HeapWord*)(heap_rs.start()) &&
  93          _bmWordSize  == heap_rs.word_size();
  94 }
  95 #endif
  96 
  97 void G1CMBitMapRO::print_on_error(outputStream* st, const char* prefix) const {
  98   _bm.print_on_error(st, prefix);
  99 }
 100 
 101 size_t G1CMBitMap::compute_size(size_t heap_size) {
 102   return ReservedSpace::allocation_align_size_up(heap_size / mark_distance());
 103 }
 104 
 105 size_t G1CMBitMap::mark_distance() {
 106   return MinObjAlignmentInBytes * BitsPerByte;
 107 }
 108 
 109 void G1CMBitMap::initialize(MemRegion heap, G1RegionToSpaceMapper* storage) {
 110   _bmStartWord = heap.start();
 111   _bmWordSize = heap.word_size();
 112 
 113   _bm = BitMapView((BitMap::bm_word_t*) storage->reserved().start(), _bmWordSize >> _shifter);
 114 
 115   storage->set_mapping_changed_listener(&_listener);
 116 }
 117 
 118 void G1CMBitMapMappingChangedListener::on_commit(uint start_region, size_t num_regions, bool zero_filled) {
 119   if (zero_filled) {
 120     return;
 121   }
 122   // We need to clear the bitmap on commit, removing any existing information.
 123   MemRegion mr(G1CollectedHeap::heap()->bottom_addr_for_region(start_region), num_regions * HeapRegion::GrainWords);
 124   _bm->clear_range(mr);
 125 }
 126 
 127 void G1CMBitMap::clear_range(MemRegion mr) {
 128   mr.intersection(MemRegion(_bmStartWord, _bmWordSize));
 129   assert(!mr.is_empty(), "unexpected empty region");
 130   // convert address range into offset range
 131   _bm.at_put_range(heapWordToOffset(mr.start()),
 132                    heapWordToOffset(mr.end()), false);
 133 }
 134 
 135 G1CMMarkStack::G1CMMarkStack(G1ConcurrentMark* cm) :
 136   _base(NULL), _cm(cm)
 137 {}
 138 
 139 bool G1CMMarkStack::allocate(size_t capacity) {
 140   // allocate a stack of the requisite depth
 141   ReservedSpace rs(ReservedSpace::allocation_align_size_up(capacity * sizeof(oop)));
 142   if (!rs.is_reserved()) {
 143     log_warning(gc)("ConcurrentMark MarkStack allocation failure");
 144     return false;
 145   }
 146   MemTracker::record_virtual_memory_type((address)rs.base(), mtGC);
 147   if (!_virtual_space.initialize(rs, rs.size())) {
 148     log_warning(gc)("ConcurrentMark MarkStack backing store failure");
 149     // Release the virtual memory reserved for the marking stack
 150     rs.release();
 151     return false;
 152   }
 153   assert(_virtual_space.committed_size() == rs.size(),
 154          "Didn't reserve backing store for all of G1ConcurrentMark stack?");
 155   _base = (oop*) _virtual_space.low();
 156   setEmpty();
 157   _capacity = (jint) capacity;
 158   _saved_index = -1;
 159   _should_expand = false;
 160   return true;
 161 }
 162 
 163 void G1CMMarkStack::expand() {
 164   // Called, during remark, if we've overflown the marking stack during marking.
 165   assert(isEmpty(), "stack should been emptied while handling overflow");
 166   assert(_capacity <= (jint) MarkStackSizeMax, "stack bigger than permitted");
 167   // Clear expansion flag
 168   _should_expand = false;
 169   if (_capacity == (jint) MarkStackSizeMax) {
 170     log_trace(gc)("(benign) Can't expand marking stack capacity, at max size limit");
 171     return;
 172   }
 173   // Double capacity if possible
 174   jint new_capacity = MIN2(_capacity*2, (jint) MarkStackSizeMax);
 175   // Do not give up existing stack until we have managed to
 176   // get the double capacity that we desired.
 177   ReservedSpace rs(ReservedSpace::allocation_align_size_up(new_capacity *
 178                                                            sizeof(oop)));
 179   if (rs.is_reserved()) {
 180     // Release the backing store associated with old stack
 181     _virtual_space.release();
 182     // Reinitialize virtual space for new stack
 183     if (!_virtual_space.initialize(rs, rs.size())) {
 184       fatal("Not enough swap for expanded marking stack capacity");
 185     }
 186     _base = (oop*)(_virtual_space.low());
 187     _index = 0;
 188     _capacity = new_capacity;
 189   } else {
 190     // Failed to double capacity, continue;
 191     log_trace(gc)("(benign) Failed to expand marking stack capacity from " SIZE_FORMAT "K to " SIZE_FORMAT "K",
 192                   _capacity / K, new_capacity / K);
 193   }
 194 }
 195 
 196 void G1CMMarkStack::set_should_expand() {
 197   // If we're resetting the marking state because of an
 198   // marking stack overflow, record that we should, if
 199   // possible, expand the stack.
 200   _should_expand = _cm->has_overflown();
 201 }
 202 
 203 G1CMMarkStack::~G1CMMarkStack() {
 204   if (_base != NULL) {
 205     _base = NULL;
 206     _virtual_space.release();
 207   }
 208 }
 209 
 210 void G1CMMarkStack::par_push_arr(oop* ptr_arr, int n) {
 211   MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
 212   jint start = _index;
 213   jint next_index = start + n;
 214   if (next_index > _capacity) {
 215     _overflow = true;
 216     return;
 217   }
 218   // Otherwise.
 219   _index = next_index;
 220   for (int i = 0; i < n; i++) {
 221     int ind = start + i;
 222     assert(ind < _capacity, "By overflow test above.");
 223     _base[ind] = ptr_arr[i];
 224   }
 225 }
 226 
 227 bool G1CMMarkStack::par_pop_arr(oop* ptr_arr, int max, int* n) {
 228   MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
 229   jint index = _index;
 230   if (index == 0) {
 231     *n = 0;
 232     return false;
 233   } else {
 234     int k = MIN2(max, index);
 235     jint  new_ind = index - k;
 236     for (int j = 0; j < k; j++) {
 237       ptr_arr[j] = _base[new_ind + j];
 238     }
 239     _index = new_ind;
 240     *n = k;
 241     return true;
 242   }
 243 }
 244 
 245 void G1CMMarkStack::note_start_of_gc() {
 246   assert(_saved_index == -1,
 247          "note_start_of_gc()/end_of_gc() bracketed incorrectly");
 248   _saved_index = _index;
 249 }
 250 
 251 void G1CMMarkStack::note_end_of_gc() {
 252   // This is intentionally a guarantee, instead of an assert. If we
 253   // accidentally add something to the mark stack during GC, it
 254   // will be a correctness issue so it's better if we crash. we'll
 255   // only check this once per GC anyway, so it won't be a performance
 256   // issue in any way.
 257   guarantee(_saved_index == _index,
 258             "saved index: %d index: %d", _saved_index, _index);
 259   _saved_index = -1;
 260 }
 261 
 262 G1CMRootRegions::G1CMRootRegions() :
 263   _cm(NULL), _scan_in_progress(false),
 264   _should_abort(false), _claimed_survivor_index(0) { }
 265 
 266 void G1CMRootRegions::init(const G1SurvivorRegions* survivors, G1ConcurrentMark* cm) {
 267   _survivors = survivors;
 268   _cm = cm;
 269 }
 270 
 271 void G1CMRootRegions::prepare_for_scan() {
 272   assert(!scan_in_progress(), "pre-condition");
 273 
 274   // Currently, only survivors can be root regions.
 275   _claimed_survivor_index = 0;
 276   _scan_in_progress = true;
 277   _should_abort = false;
 278 }
 279 
 280 HeapRegion* G1CMRootRegions::claim_next() {
 281   if (_should_abort) {
 282     // If someone has set the should_abort flag, we return NULL to
 283     // force the caller to bail out of their loop.
 284     return NULL;
 285   }
 286 
 287   // Currently, only survivors can be root regions.
 288   const GrowableArray<HeapRegion*>* survivor_regions = _survivors->regions();
 289 
 290   int claimed_index = Atomic::add(1, &_claimed_survivor_index) - 1;
 291   if (claimed_index < survivor_regions->length()) {
 292     return survivor_regions->at(claimed_index);
 293   }
 294   return NULL;
 295 }
 296 
 297 void G1CMRootRegions::notify_scan_done() {
 298   MutexLockerEx x(RootRegionScan_lock, Mutex::_no_safepoint_check_flag);
 299   _scan_in_progress = false;
 300   RootRegionScan_lock->notify_all();
 301 }
 302 
 303 void G1CMRootRegions::cancel_scan() {
 304   notify_scan_done();
 305 }
 306 
 307 void G1CMRootRegions::scan_finished() {
 308   assert(scan_in_progress(), "pre-condition");
 309 
 310   // Currently, only survivors can be root regions.
 311   if (!_should_abort) {
 312     assert(_claimed_survivor_index >= 0, "otherwise comparison is invalid: %d", _claimed_survivor_index);
 313     assert((uint)_claimed_survivor_index >= _survivors->length(),
 314            "we should have claimed all survivors, claimed index = %u, length = %u",
 315            (uint)_claimed_survivor_index, _survivors->length());
 316   }
 317 
 318   notify_scan_done();
 319 }
 320 
 321 bool G1CMRootRegions::wait_until_scan_finished() {
 322   if (!scan_in_progress()) return false;
 323 
 324   {
 325     MutexLockerEx x(RootRegionScan_lock, Mutex::_no_safepoint_check_flag);
 326     while (scan_in_progress()) {
 327       RootRegionScan_lock->wait(Mutex::_no_safepoint_check_flag);
 328     }
 329   }
 330   return true;
 331 }
 332 
 333 uint G1ConcurrentMark::scale_parallel_threads(uint n_par_threads) {
 334   return MAX2((n_par_threads + 2) / 4, 1U);
 335 }
 336 
 337 G1ConcurrentMark::G1ConcurrentMark(G1CollectedHeap* g1h, G1RegionToSpaceMapper* prev_bitmap_storage, G1RegionToSpaceMapper* next_bitmap_storage) :
 338   _g1h(g1h),
 339   _markBitMap1(),
 340   _markBitMap2(),
 341   _parallel_marking_threads(0),
 342   _max_parallel_marking_threads(0),
 343   _sleep_factor(0.0),
 344   _marking_task_overhead(1.0),
 345   _cleanup_list("Cleanup List"),
 346 
 347   _prevMarkBitMap(&_markBitMap1),
 348   _nextMarkBitMap(&_markBitMap2),
 349 
 350   _markStack(this),
 351   // _finger set in set_non_marking_state
 352 
 353   _max_worker_id(ParallelGCThreads),
 354   // _active_tasks set in set_non_marking_state
 355   // _tasks set inside the constructor
 356   _task_queues(new G1CMTaskQueueSet((int) _max_worker_id)),
 357   _terminator(ParallelTaskTerminator((int) _max_worker_id, _task_queues)),
 358 
 359   _has_overflown(false),
 360   _concurrent(false),
 361   _has_aborted(false),
 362   _restart_for_overflow(false),
 363   _concurrent_marking_in_progress(false),
 364   _gc_timer_cm(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
 365   _gc_tracer_cm(new (ResourceObj::C_HEAP, mtGC) G1OldTracer()),
 366 
 367   // _verbose_level set below
 368 
 369   _init_times(),
 370   _remark_times(), _remark_mark_times(), _remark_weak_ref_times(),
 371   _cleanup_times(),
 372   _total_counting_time(0.0),
 373   _total_rs_scrub_time(0.0),
 374 
 375   _parallel_workers(NULL),
 376 
 377   _completed_initialization(false) {
 378 
 379   _markBitMap1.initialize(g1h->reserved_region(), prev_bitmap_storage);
 380   _markBitMap2.initialize(g1h->reserved_region(), next_bitmap_storage);
 381 
 382   // Create & start a ConcurrentMark thread.
 383   _cmThread = new ConcurrentMarkThread(this);
 384   assert(cmThread() != NULL, "CM Thread should have been created");
 385   assert(cmThread()->cm() != NULL, "CM Thread should refer to this cm");
 386   if (_cmThread->osthread() == NULL) {
 387       vm_shutdown_during_initialization("Could not create ConcurrentMarkThread");
 388   }
 389 
 390   assert(CGC_lock != NULL, "Where's the CGC_lock?");
 391   assert(_markBitMap1.covers(g1h->reserved_region()), "_markBitMap1 inconsistency");
 392   assert(_markBitMap2.covers(g1h->reserved_region()), "_markBitMap2 inconsistency");
 393 
 394   SATBMarkQueueSet& satb_qs = JavaThread::satb_mark_queue_set();
 395   satb_qs.set_buffer_size(G1SATBBufferSize);
 396 
 397   _root_regions.init(_g1h->survivor(), this);
 398 
 399   if (ConcGCThreads > ParallelGCThreads) {
 400     log_warning(gc)("Can't have more ConcGCThreads (%u) than ParallelGCThreads (%u).",
 401                     ConcGCThreads, ParallelGCThreads);
 402     return;
 403   }
 404   if (!FLAG_IS_DEFAULT(ConcGCThreads) && ConcGCThreads > 0) {
 405     // Note: ConcGCThreads has precedence over G1MarkingOverheadPercent
 406     // if both are set
 407     _sleep_factor             = 0.0;
 408     _marking_task_overhead    = 1.0;
 409   } else if (G1MarkingOverheadPercent > 0) {
 410     // We will calculate the number of parallel marking threads based
 411     // on a target overhead with respect to the soft real-time goal
 412     double marking_overhead = (double) G1MarkingOverheadPercent / 100.0;
 413     double overall_cm_overhead =
 414       (double) MaxGCPauseMillis * marking_overhead /
 415       (double) GCPauseIntervalMillis;
 416     double cpu_ratio = 1.0 / (double) os::processor_count();
 417     double marking_thread_num = ceil(overall_cm_overhead / cpu_ratio);
 418     double marking_task_overhead =
 419       overall_cm_overhead / marking_thread_num *
 420                                               (double) os::processor_count();
 421     double sleep_factor =
 422                        (1.0 - marking_task_overhead) / marking_task_overhead;
 423 
 424     FLAG_SET_ERGO(uint, ConcGCThreads, (uint) marking_thread_num);
 425     _sleep_factor             = sleep_factor;
 426     _marking_task_overhead    = marking_task_overhead;
 427   } else {
 428     // Calculate the number of parallel marking threads by scaling
 429     // the number of parallel GC threads.
 430     uint marking_thread_num = scale_parallel_threads(ParallelGCThreads);
 431     FLAG_SET_ERGO(uint, ConcGCThreads, marking_thread_num);
 432     _sleep_factor             = 0.0;
 433     _marking_task_overhead    = 1.0;
 434   }
 435 
 436   assert(ConcGCThreads > 0, "Should have been set");
 437   _parallel_marking_threads = ConcGCThreads;
 438   _max_parallel_marking_threads = _parallel_marking_threads;
 439 
 440   _parallel_workers = new WorkGang("G1 Marker",
 441        _max_parallel_marking_threads, false, true);
 442   if (_parallel_workers == NULL) {
 443     vm_exit_during_initialization("Failed necessary allocation.");
 444   } else {
 445     _parallel_workers->initialize_workers();
 446   }
 447 
 448   if (FLAG_IS_DEFAULT(MarkStackSize)) {
 449     size_t mark_stack_size =
 450       MIN2(MarkStackSizeMax,
 451           MAX2(MarkStackSize, (size_t) (parallel_marking_threads() * TASKQUEUE_SIZE)));
 452     // Verify that the calculated value for MarkStackSize is in range.
 453     // It would be nice to use the private utility routine from Arguments.
 454     if (!(mark_stack_size >= 1 && mark_stack_size <= MarkStackSizeMax)) {
 455       log_warning(gc)("Invalid value calculated for MarkStackSize (" SIZE_FORMAT "): "
 456                       "must be between 1 and " SIZE_FORMAT,
 457                       mark_stack_size, MarkStackSizeMax);
 458       return;
 459     }
 460     FLAG_SET_ERGO(size_t, MarkStackSize, mark_stack_size);
 461   } else {
 462     // Verify MarkStackSize is in range.
 463     if (FLAG_IS_CMDLINE(MarkStackSize)) {
 464       if (FLAG_IS_DEFAULT(MarkStackSizeMax)) {
 465         if (!(MarkStackSize >= 1 && MarkStackSize <= MarkStackSizeMax)) {
 466           log_warning(gc)("Invalid value specified for MarkStackSize (" SIZE_FORMAT "): "
 467                           "must be between 1 and " SIZE_FORMAT,
 468                           MarkStackSize, MarkStackSizeMax);
 469           return;
 470         }
 471       } else if (FLAG_IS_CMDLINE(MarkStackSizeMax)) {
 472         if (!(MarkStackSize >= 1 && MarkStackSize <= MarkStackSizeMax)) {
 473           log_warning(gc)("Invalid value specified for MarkStackSize (" SIZE_FORMAT ")"
 474                           " or for MarkStackSizeMax (" SIZE_FORMAT ")",
 475                           MarkStackSize, MarkStackSizeMax);
 476           return;
 477         }
 478       }
 479     }
 480   }
 481 
 482   if (!_markStack.allocate(MarkStackSize)) {
 483     log_warning(gc)("Failed to allocate CM marking stack");
 484     return;
 485   }
 486 
 487   _tasks = NEW_C_HEAP_ARRAY(G1CMTask*, _max_worker_id, mtGC);
 488   _accum_task_vtime = NEW_C_HEAP_ARRAY(double, _max_worker_id, mtGC);
 489 
 490   // so that the assertion in MarkingTaskQueue::task_queue doesn't fail
 491   _active_tasks = _max_worker_id;
 492 
 493   for (uint i = 0; i < _max_worker_id; ++i) {
 494     G1CMTaskQueue* task_queue = new G1CMTaskQueue();
 495     task_queue->initialize();
 496     _task_queues->register_queue(i, task_queue);
 497 
 498     _tasks[i] = new G1CMTask(i, this, task_queue, _task_queues);
 499 
 500     _accum_task_vtime[i] = 0.0;
 501   }
 502 
 503   // so that the call below can read a sensible value
 504   _heap_start = g1h->reserved_region().start();
 505   set_non_marking_state();
 506   _completed_initialization = true;
 507 }
 508 
 509 void G1ConcurrentMark::reset() {
 510   // Starting values for these two. This should be called in a STW
 511   // phase.
 512   MemRegion reserved = _g1h->g1_reserved();
 513   _heap_start = reserved.start();
 514   _heap_end   = reserved.end();
 515 
 516   // Separated the asserts so that we know which one fires.
 517   assert(_heap_start != NULL, "heap bounds should look ok");
 518   assert(_heap_end != NULL, "heap bounds should look ok");
 519   assert(_heap_start < _heap_end, "heap bounds should look ok");
 520 
 521   // Reset all the marking data structures and any necessary flags
 522   reset_marking_state();
 523 
 524   // We do reset all of them, since different phases will use
 525   // different number of active threads. So, it's easiest to have all
 526   // of them ready.
 527   for (uint i = 0; i < _max_worker_id; ++i) {
 528     _tasks[i]->reset(_nextMarkBitMap);
 529   }
 530 
 531   // we need this to make sure that the flag is on during the evac
 532   // pause with initial mark piggy-backed
 533   set_concurrent_marking_in_progress();
 534 }
 535 
 536 
 537 void G1ConcurrentMark::reset_marking_state(bool clear_overflow) {
 538   _markStack.set_should_expand();
 539   _markStack.setEmpty();        // Also clears the _markStack overflow flag
 540   if (clear_overflow) {
 541     clear_has_overflown();
 542   } else {
 543     assert(has_overflown(), "pre-condition");
 544   }
 545   _finger = _heap_start;
 546 
 547   for (uint i = 0; i < _max_worker_id; ++i) {
 548     G1CMTaskQueue* queue = _task_queues->queue(i);
 549     queue->set_empty();
 550   }
 551 }
 552 
 553 void G1ConcurrentMark::set_concurrency(uint active_tasks) {
 554   assert(active_tasks <= _max_worker_id, "we should not have more");
 555 
 556   _active_tasks = active_tasks;
 557   // Need to update the three data structures below according to the
 558   // number of active threads for this phase.
 559   _terminator   = ParallelTaskTerminator((int) active_tasks, _task_queues);
 560   _first_overflow_barrier_sync.set_n_workers((int) active_tasks);
 561   _second_overflow_barrier_sync.set_n_workers((int) active_tasks);
 562 }
 563 
 564 void G1ConcurrentMark::set_concurrency_and_phase(uint active_tasks, bool concurrent) {
 565   set_concurrency(active_tasks);
 566 
 567   _concurrent = concurrent;
 568   // We propagate this to all tasks, not just the active ones.
 569   for (uint i = 0; i < _max_worker_id; ++i)
 570     _tasks[i]->set_concurrent(concurrent);
 571 
 572   if (concurrent) {
 573     set_concurrent_marking_in_progress();
 574   } else {
 575     // We currently assume that the concurrent flag has been set to
 576     // false before we start remark. At this point we should also be
 577     // in a STW phase.
 578     assert(!concurrent_marking_in_progress(), "invariant");
 579     assert(out_of_regions(),
 580            "only way to get here: _finger: " PTR_FORMAT ", _heap_end: " PTR_FORMAT,
 581            p2i(_finger), p2i(_heap_end));
 582   }
 583 }
 584 
 585 void G1ConcurrentMark::set_non_marking_state() {
 586   // We set the global marking state to some default values when we're
 587   // not doing marking.
 588   reset_marking_state();
 589   _active_tasks = 0;
 590   clear_concurrent_marking_in_progress();
 591 }
 592 
 593 G1ConcurrentMark::~G1ConcurrentMark() {
 594   // The G1ConcurrentMark instance is never freed.
 595   ShouldNotReachHere();
 596 }
 597 
 598 class G1ClearBitMapTask : public AbstractGangTask {
 599 public:
 600   static size_t chunk_size() { return M; }
 601 
 602 private:
 603   // Heap region closure used for clearing the given mark bitmap.
 604   class G1ClearBitmapHRClosure : public HeapRegionClosure {
 605   private:
 606     G1CMBitMap* _bitmap;
 607     G1ConcurrentMark* _cm;
 608   public:
 609     G1ClearBitmapHRClosure(G1CMBitMap* bitmap, G1ConcurrentMark* cm) : HeapRegionClosure(), _cm(cm), _bitmap(bitmap) {
 610     }
 611 
 612     virtual bool doHeapRegion(HeapRegion* r) {
 613       size_t const chunk_size_in_words = G1ClearBitMapTask::chunk_size() / HeapWordSize;
 614 
 615       HeapWord* cur = r->bottom();
 616       HeapWord* const end = r->end();
 617 
 618       while (cur < end) {
 619         MemRegion mr(cur, MIN2(cur + chunk_size_in_words, end));
 620         _bitmap->clear_range(mr);
 621 
 622         cur += chunk_size_in_words;
 623 
 624         // Abort iteration if after yielding the marking has been aborted.
 625         if (_cm != NULL && _cm->do_yield_check() && _cm->has_aborted()) {
 626           return true;
 627         }
 628         // Repeat the asserts from before the start of the closure. We will do them
 629         // as asserts here to minimize their overhead on the product. However, we
 630         // will have them as guarantees at the beginning / end of the bitmap
 631         // clearing to get some checking in the product.
 632         assert(_cm == NULL || _cm->cmThread()->during_cycle(), "invariant");
 633         assert(_cm == NULL || !G1CollectedHeap::heap()->collector_state()->mark_in_progress(), "invariant");
 634       }
 635       assert(cur == end, "Must have completed iteration over the bitmap for region %u.", r->hrm_index());
 636 
 637       return false;
 638     }
 639   };
 640 
 641   G1ClearBitmapHRClosure _cl;
 642   HeapRegionClaimer _hr_claimer;
 643   bool _suspendible; // If the task is suspendible, workers must join the STS.
 644 
 645 public:
 646   G1ClearBitMapTask(G1CMBitMap* bitmap, G1ConcurrentMark* cm, uint n_workers, bool suspendible) :
 647     AbstractGangTask("G1 Clear Bitmap"),
 648     _cl(bitmap, suspendible ? cm : NULL),
 649     _hr_claimer(n_workers),
 650     _suspendible(suspendible)
 651   { }
 652 
 653   void work(uint worker_id) {
 654     SuspendibleThreadSetJoiner sts_join(_suspendible);
 655     G1CollectedHeap::heap()->heap_region_par_iterate(&_cl, worker_id, &_hr_claimer, true);
 656   }
 657 
 658   bool is_complete() {
 659     return _cl.complete();
 660   }
 661 };
 662 
 663 void G1ConcurrentMark::clear_bitmap(G1CMBitMap* bitmap, WorkGang* workers, bool may_yield) {
 664   assert(may_yield || SafepointSynchronize::is_at_safepoint(), "Non-yielding bitmap clear only allowed at safepoint.");
 665 
 666   size_t const num_bytes_to_clear = (HeapRegion::GrainBytes * _g1h->num_regions()) / G1CMBitMap::heap_map_factor();
 667   size_t const num_chunks = align_size_up(num_bytes_to_clear, G1ClearBitMapTask::chunk_size()) / G1ClearBitMapTask::chunk_size();
 668 
 669   uint const num_workers = (uint)MIN2(num_chunks, (size_t)workers->active_workers());
 670 
 671   G1ClearBitMapTask cl(bitmap, this, num_workers, may_yield);
 672 
 673   log_debug(gc, ergo)("Running %s with %u workers for " SIZE_FORMAT " work units.", cl.name(), num_workers, num_chunks);
 674   workers->run_task(&cl, num_workers);
 675   guarantee(!may_yield || cl.is_complete(), "Must have completed iteration when not yielding.");
 676 }
 677 
 678 void G1ConcurrentMark::cleanup_for_next_mark() {
 679   // Make sure that the concurrent mark thread looks to still be in
 680   // the current cycle.
 681   guarantee(cmThread()->during_cycle(), "invariant");
 682 
 683   // We are finishing up the current cycle by clearing the next
 684   // marking bitmap and getting it ready for the next cycle. During
 685   // this time no other cycle can start. So, let's make sure that this
 686   // is the case.
 687   guarantee(!_g1h->collector_state()->mark_in_progress(), "invariant");
 688 
 689   clear_bitmap(_nextMarkBitMap, _parallel_workers, true);
 690 
 691   // Clear the live count data. If the marking has been aborted, the abort()
 692   // call already did that.
 693   if (!has_aborted()) {
 694     clear_live_data(_parallel_workers);
 695     DEBUG_ONLY(verify_live_data_clear());
 696   }
 697 
 698   // Repeat the asserts from above.
 699   guarantee(cmThread()->during_cycle(), "invariant");
 700   guarantee(!_g1h->collector_state()->mark_in_progress(), "invariant");
 701 }
 702 
 703 void G1ConcurrentMark::clear_prev_bitmap(WorkGang* workers) {
 704   assert(SafepointSynchronize::is_at_safepoint(), "Should only clear the entire prev bitmap at a safepoint.");
 705   clear_bitmap((G1CMBitMap*)_prevMarkBitMap, workers, false);
 706 }
 707 
 708 class CheckBitmapClearHRClosure : public HeapRegionClosure {
 709   G1CMBitMap* _bitmap;
 710   bool _error;
 711  public:
 712   CheckBitmapClearHRClosure(G1CMBitMap* bitmap) : _bitmap(bitmap) {
 713   }
 714 
 715   virtual bool doHeapRegion(HeapRegion* r) {
 716     // This closure can be called concurrently to the mutator, so we must make sure
 717     // that the result of the getNextMarkedWordAddress() call is compared to the
 718     // value passed to it as limit to detect any found bits.
 719     // end never changes in G1.
 720     HeapWord* end = r->end();
 721     return _bitmap->getNextMarkedWordAddress(r->bottom(), end) != end;
 722   }
 723 };
 724 
 725 bool G1ConcurrentMark::nextMarkBitmapIsClear() {
 726   CheckBitmapClearHRClosure cl(_nextMarkBitMap);
 727   _g1h->heap_region_iterate(&cl);
 728   return cl.complete();
 729 }
 730 
 731 class NoteStartOfMarkHRClosure: public HeapRegionClosure {
 732 public:
 733   bool doHeapRegion(HeapRegion* r) {
 734     r->note_start_of_marking();
 735     return false;
 736   }
 737 };
 738 
 739 void G1ConcurrentMark::checkpointRootsInitialPre() {
 740   G1CollectedHeap* g1h = G1CollectedHeap::heap();
 741   G1Policy* g1p = g1h->g1_policy();
 742 
 743   _has_aborted = false;
 744 
 745   // Initialize marking structures. This has to be done in a STW phase.
 746   reset();
 747 
 748   // For each region note start of marking.
 749   NoteStartOfMarkHRClosure startcl;
 750   g1h->heap_region_iterate(&startcl);
 751 }
 752 
 753 
 754 void G1ConcurrentMark::checkpointRootsInitialPost() {
 755   G1CollectedHeap*   g1h = G1CollectedHeap::heap();
 756 
 757   // Start Concurrent Marking weak-reference discovery.
 758   ReferenceProcessor* rp = g1h->ref_processor_cm();
 759   // enable ("weak") refs discovery
 760   rp->enable_discovery();
 761   rp->setup_policy(false); // snapshot the soft ref policy to be used in this cycle
 762 
 763   SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
 764   // This is the start of  the marking cycle, we're expected all
 765   // threads to have SATB queues with active set to false.
 766   satb_mq_set.set_active_all_threads(true, /* new active value */
 767                                      false /* expected_active */);
 768 
 769   _root_regions.prepare_for_scan();
 770 
 771   // update_g1_committed() will be called at the end of an evac pause
 772   // when marking is on. So, it's also called at the end of the
 773   // initial-mark pause to update the heap end, if the heap expands
 774   // during it. No need to call it here.
 775 }
 776 
 777 /*
 778  * Notice that in the next two methods, we actually leave the STS
 779  * during the barrier sync and join it immediately afterwards. If we
 780  * do not do this, the following deadlock can occur: one thread could
 781  * be in the barrier sync code, waiting for the other thread to also
 782  * sync up, whereas another one could be trying to yield, while also
 783  * waiting for the other threads to sync up too.
 784  *
 785  * Note, however, that this code is also used during remark and in
 786  * this case we should not attempt to leave / enter the STS, otherwise
 787  * we'll either hit an assert (debug / fastdebug) or deadlock
 788  * (product). So we should only leave / enter the STS if we are
 789  * operating concurrently.
 790  *
 791  * Because the thread that does the sync barrier has left the STS, it
 792  * is possible to be suspended for a Full GC or an evacuation pause
 793  * could occur. This is actually safe, since the entering the sync
 794  * barrier is one of the last things do_marking_step() does, and it
 795  * doesn't manipulate any data structures afterwards.
 796  */
 797 
 798 void G1ConcurrentMark::enter_first_sync_barrier(uint worker_id) {
 799   bool barrier_aborted;
 800   {
 801     SuspendibleThreadSetLeaver sts_leave(concurrent());
 802     barrier_aborted = !_first_overflow_barrier_sync.enter();
 803   }
 804 
 805   // at this point everyone should have synced up and not be doing any
 806   // more work
 807 
 808   if (barrier_aborted) {
 809     // If the barrier aborted we ignore the overflow condition and
 810     // just abort the whole marking phase as quickly as possible.
 811     return;
 812   }
 813 
 814   // If we're executing the concurrent phase of marking, reset the marking
 815   // state; otherwise the marking state is reset after reference processing,
 816   // during the remark pause.
 817   // If we reset here as a result of an overflow during the remark we will
 818   // see assertion failures from any subsequent set_concurrency_and_phase()
 819   // calls.
 820   if (concurrent()) {
 821     // let the task associated with with worker 0 do this
 822     if (worker_id == 0) {
 823       // task 0 is responsible for clearing the global data structures
 824       // We should be here because of an overflow. During STW we should
 825       // not clear the overflow flag since we rely on it being true when
 826       // we exit this method to abort the pause and restart concurrent
 827       // marking.
 828       reset_marking_state(true /* clear_overflow */);
 829 
 830       log_info(gc, marking)("Concurrent Mark reset for overflow");
 831     }
 832   }
 833 
 834   // after this, each task should reset its own data structures then
 835   // then go into the second barrier
 836 }
 837 
 838 void G1ConcurrentMark::enter_second_sync_barrier(uint worker_id) {
 839   SuspendibleThreadSetLeaver sts_leave(concurrent());
 840   _second_overflow_barrier_sync.enter();
 841 
 842   // at this point everything should be re-initialized and ready to go
 843 }
 844 
 845 class G1CMConcurrentMarkingTask: public AbstractGangTask {
 846 private:
 847   G1ConcurrentMark*     _cm;
 848   ConcurrentMarkThread* _cmt;
 849 
 850 public:
 851   void work(uint worker_id) {
 852     assert(Thread::current()->is_ConcurrentGC_thread(),
 853            "this should only be done by a conc GC thread");
 854     ResourceMark rm;
 855 
 856     double start_vtime = os::elapsedVTime();
 857 
 858     {
 859       SuspendibleThreadSetJoiner sts_join;
 860 
 861       assert(worker_id < _cm->active_tasks(), "invariant");
 862       G1CMTask* the_task = _cm->task(worker_id);
 863       the_task->record_start_time();
 864       if (!_cm->has_aborted()) {
 865         do {
 866           double start_vtime_sec = os::elapsedVTime();
 867           double mark_step_duration_ms = G1ConcMarkStepDurationMillis;
 868 
 869           the_task->do_marking_step(mark_step_duration_ms,
 870                                     true  /* do_termination */,
 871                                     false /* is_serial*/);
 872 
 873           double end_vtime_sec = os::elapsedVTime();
 874           double elapsed_vtime_sec = end_vtime_sec - start_vtime_sec;
 875           _cm->clear_has_overflown();
 876 
 877           _cm->do_yield_check();
 878 
 879           jlong sleep_time_ms;
 880           if (!_cm->has_aborted() && the_task->has_aborted()) {
 881             sleep_time_ms =
 882               (jlong) (elapsed_vtime_sec * _cm->sleep_factor() * 1000.0);
 883             {
 884               SuspendibleThreadSetLeaver sts_leave;
 885               os::sleep(Thread::current(), sleep_time_ms, false);
 886             }
 887           }
 888         } while (!_cm->has_aborted() && the_task->has_aborted());
 889       }
 890       the_task->record_end_time();
 891       guarantee(!the_task->has_aborted() || _cm->has_aborted(), "invariant");
 892     }
 893 
 894     double end_vtime = os::elapsedVTime();
 895     _cm->update_accum_task_vtime(worker_id, end_vtime - start_vtime);
 896   }
 897 
 898   G1CMConcurrentMarkingTask(G1ConcurrentMark* cm,
 899                             ConcurrentMarkThread* cmt) :
 900       AbstractGangTask("Concurrent Mark"), _cm(cm), _cmt(cmt) { }
 901 
 902   ~G1CMConcurrentMarkingTask() { }
 903 };
 904 
 905 // Calculates the number of active workers for a concurrent
 906 // phase.
 907 uint G1ConcurrentMark::calc_parallel_marking_threads() {
 908   uint n_conc_workers = 0;
 909   if (!UseDynamicNumberOfGCThreads ||
 910       (!FLAG_IS_DEFAULT(ConcGCThreads) &&
 911        !ForceDynamicNumberOfGCThreads)) {
 912     n_conc_workers = max_parallel_marking_threads();
 913   } else {
 914     n_conc_workers =
 915       AdaptiveSizePolicy::calc_default_active_workers(
 916                                    max_parallel_marking_threads(),
 917                                    1, /* Minimum workers */
 918                                    parallel_marking_threads(),
 919                                    Threads::number_of_non_daemon_threads());
 920     // Don't scale down "n_conc_workers" by scale_parallel_threads() because
 921     // that scaling has already gone into "_max_parallel_marking_threads".
 922   }
 923   assert(n_conc_workers > 0, "Always need at least 1");
 924   return n_conc_workers;
 925 }
 926 
 927 void G1ConcurrentMark::scanRootRegion(HeapRegion* hr) {
 928   // Currently, only survivors can be root regions.
 929   assert(hr->next_top_at_mark_start() == hr->bottom(), "invariant");
 930   G1RootRegionScanClosure cl(_g1h, this);
 931 
 932   const uintx interval = PrefetchScanIntervalInBytes;
 933   HeapWord* curr = hr->bottom();
 934   const HeapWord* end = hr->top();
 935   while (curr < end) {
 936     Prefetch::read(curr, interval);
 937     oop obj = oop(curr);
 938     int size = obj->oop_iterate_size(&cl);
 939     assert(size == obj->size(), "sanity");
 940     curr += size;
 941   }
 942 }
 943 
 944 class G1CMRootRegionScanTask : public AbstractGangTask {
 945 private:
 946   G1ConcurrentMark* _cm;
 947 
 948 public:
 949   G1CMRootRegionScanTask(G1ConcurrentMark* cm) :
 950     AbstractGangTask("Root Region Scan"), _cm(cm) { }
 951 
 952   void work(uint worker_id) {
 953     assert(Thread::current()->is_ConcurrentGC_thread(),
 954            "this should only be done by a conc GC thread");
 955 
 956     G1CMRootRegions* root_regions = _cm->root_regions();
 957     HeapRegion* hr = root_regions->claim_next();
 958     while (hr != NULL) {
 959       _cm->scanRootRegion(hr);
 960       hr = root_regions->claim_next();
 961     }
 962   }
 963 };
 964 
 965 void G1ConcurrentMark::scan_root_regions() {
 966   // scan_in_progress() will have been set to true only if there was
 967   // at least one root region to scan. So, if it's false, we
 968   // should not attempt to do any further work.
 969   if (root_regions()->scan_in_progress()) {
 970     assert(!has_aborted(), "Aborting before root region scanning is finished not supported.");
 971 
 972     _parallel_marking_threads = calc_parallel_marking_threads();
 973     assert(parallel_marking_threads() <= max_parallel_marking_threads(),
 974            "Maximum number of marking threads exceeded");
 975     uint active_workers = MAX2(1U, parallel_marking_threads());
 976 
 977     G1CMRootRegionScanTask task(this);
 978     _parallel_workers->set_active_workers(active_workers);
 979     _parallel_workers->run_task(&task);
 980 
 981     // It's possible that has_aborted() is true here without actually
 982     // aborting the survivor scan earlier. This is OK as it's
 983     // mainly used for sanity checking.
 984     root_regions()->scan_finished();
 985   }
 986 }
 987 
 988 void G1ConcurrentMark::concurrent_cycle_start() {
 989   _gc_timer_cm->register_gc_start();
 990 
 991   _gc_tracer_cm->report_gc_start(GCCause::_no_gc /* first parameter is not used */, _gc_timer_cm->gc_start());
 992 
 993   _g1h->trace_heap_before_gc(_gc_tracer_cm);
 994 }
 995 
 996 void G1ConcurrentMark::concurrent_cycle_end() {
 997   _g1h->trace_heap_after_gc(_gc_tracer_cm);
 998 
 999   if (has_aborted()) {
1000     _gc_tracer_cm->report_concurrent_mode_failure();
1001   }
1002 
1003   _gc_timer_cm->register_gc_end();
1004 
1005   _gc_tracer_cm->report_gc_end(_gc_timer_cm->gc_end(), _gc_timer_cm->time_partitions());
1006 }
1007 
1008 void G1ConcurrentMark::mark_from_roots() {
1009   // we might be tempted to assert that:
1010   // assert(asynch == !SafepointSynchronize::is_at_safepoint(),
1011   //        "inconsistent argument?");
1012   // However that wouldn't be right, because it's possible that
1013   // a safepoint is indeed in progress as a younger generation
1014   // stop-the-world GC happens even as we mark in this generation.
1015 
1016   _restart_for_overflow = false;
1017 
1018   // _g1h has _n_par_threads
1019   _parallel_marking_threads = calc_parallel_marking_threads();
1020   assert(parallel_marking_threads() <= max_parallel_marking_threads(),
1021     "Maximum number of marking threads exceeded");
1022 
1023   uint active_workers = MAX2(1U, parallel_marking_threads());
1024   assert(active_workers > 0, "Should have been set");
1025 
1026   // Parallel task terminator is set in "set_concurrency_and_phase()"
1027   set_concurrency_and_phase(active_workers, true /* concurrent */);
1028 
1029   G1CMConcurrentMarkingTask markingTask(this, cmThread());
1030   _parallel_workers->set_active_workers(active_workers);
1031   _parallel_workers->run_task(&markingTask);
1032   print_stats();
1033 }
1034 
1035 void G1ConcurrentMark::checkpointRootsFinal(bool clear_all_soft_refs) {
1036   // world is stopped at this checkpoint
1037   assert(SafepointSynchronize::is_at_safepoint(),
1038          "world should be stopped");
1039 
1040   G1CollectedHeap* g1h = G1CollectedHeap::heap();
1041 
1042   // If a full collection has happened, we shouldn't do this.
1043   if (has_aborted()) {
1044     g1h->collector_state()->set_mark_in_progress(false); // So bitmap clearing isn't confused
1045     return;
1046   }
1047 
1048   SvcGCMarker sgcm(SvcGCMarker::OTHER);
1049 
1050   if (VerifyDuringGC) {
1051     HandleMark hm;  // handle scope
1052     g1h->prepare_for_verify();
1053     Universe::verify(VerifyOption_G1UsePrevMarking, "During GC (before)");
1054   }
1055   g1h->verifier()->check_bitmaps("Remark Start");
1056 
1057   G1Policy* g1p = g1h->g1_policy();
1058   g1p->record_concurrent_mark_remark_start();
1059 
1060   double start = os::elapsedTime();
1061 
1062   checkpointRootsFinalWork();
1063 
1064   double mark_work_end = os::elapsedTime();
1065 
1066   weakRefsWork(clear_all_soft_refs);
1067 
1068   if (has_overflown()) {
1069     // Oops.  We overflowed.  Restart concurrent marking.
1070     _restart_for_overflow = true;
1071 
1072     // Verify the heap w.r.t. the previous marking bitmap.
1073     if (VerifyDuringGC) {
1074       HandleMark hm;  // handle scope
1075       g1h->prepare_for_verify();
1076       Universe::verify(VerifyOption_G1UsePrevMarking, "During GC (overflow)");
1077     }
1078 
1079     // Clear the marking state because we will be restarting
1080     // marking due to overflowing the global mark stack.
1081     reset_marking_state();
1082   } else {
1083     SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
1084     // We're done with marking.
1085     // This is the end of  the marking cycle, we're expected all
1086     // threads to have SATB queues with active set to true.
1087     satb_mq_set.set_active_all_threads(false, /* new active value */
1088                                        true /* expected_active */);
1089 
1090     if (VerifyDuringGC) {
1091       HandleMark hm;  // handle scope
1092       g1h->prepare_for_verify();
1093       Universe::verify(VerifyOption_G1UseNextMarking, "During GC (after)");
1094     }
1095     g1h->verifier()->check_bitmaps("Remark End");
1096     assert(!restart_for_overflow(), "sanity");
1097     // Completely reset the marking state since marking completed
1098     set_non_marking_state();
1099   }
1100 
1101   // Expand the marking stack, if we have to and if we can.
1102   if (_markStack.should_expand()) {
1103     _markStack.expand();
1104   }
1105 
1106   // Statistics
1107   double now = os::elapsedTime();
1108   _remark_mark_times.add((mark_work_end - start) * 1000.0);
1109   _remark_weak_ref_times.add((now - mark_work_end) * 1000.0);
1110   _remark_times.add((now - start) * 1000.0);
1111 
1112   g1p->record_concurrent_mark_remark_end();
1113 
1114   G1CMIsAliveClosure is_alive(g1h);
1115   _gc_tracer_cm->report_object_count_after_gc(&is_alive);
1116 }
1117 
1118 class G1NoteEndOfConcMarkClosure : public HeapRegionClosure {
1119   G1CollectedHeap* _g1;
1120   size_t _freed_bytes;
1121   FreeRegionList* _local_cleanup_list;
1122   uint _old_regions_removed;
1123   uint _humongous_regions_removed;
1124   HRRSCleanupTask* _hrrs_cleanup_task;
1125 
1126 public:
1127   G1NoteEndOfConcMarkClosure(G1CollectedHeap* g1,
1128                              FreeRegionList* local_cleanup_list,
1129                              HRRSCleanupTask* hrrs_cleanup_task) :
1130     _g1(g1),
1131     _freed_bytes(0),
1132     _local_cleanup_list(local_cleanup_list),
1133     _old_regions_removed(0),
1134     _humongous_regions_removed(0),
1135     _hrrs_cleanup_task(hrrs_cleanup_task) { }
1136 
1137   size_t freed_bytes() { return _freed_bytes; }
1138   const uint old_regions_removed() { return _old_regions_removed; }
1139   const uint humongous_regions_removed() { return _humongous_regions_removed; }
1140 
1141   bool doHeapRegion(HeapRegion *hr) {
1142     if (hr->is_archive()) {
1143       return false;
1144     }
1145     _g1->reset_gc_time_stamps(hr);
1146     hr->note_end_of_marking();
1147 
1148     if (hr->used() > 0 && hr->max_live_bytes() == 0 && !hr->is_young()) {
1149       _freed_bytes += hr->used();
1150       hr->set_containing_set(NULL);
1151       if (hr->is_humongous()) {
1152         _humongous_regions_removed++;
1153         _g1->free_humongous_region(hr, _local_cleanup_list, true);
1154       } else {
1155         _old_regions_removed++;
1156         _g1->free_region(hr, _local_cleanup_list, true);
1157       }
1158     } else {
1159       hr->rem_set()->do_cleanup_work(_hrrs_cleanup_task);
1160     }
1161 
1162     return false;
1163   }
1164 };
1165 
1166 class G1ParNoteEndTask: public AbstractGangTask {
1167   friend class G1NoteEndOfConcMarkClosure;
1168 
1169 protected:
1170   G1CollectedHeap* _g1h;
1171   FreeRegionList* _cleanup_list;
1172   HeapRegionClaimer _hrclaimer;
1173 
1174 public:
1175   G1ParNoteEndTask(G1CollectedHeap* g1h, FreeRegionList* cleanup_list, uint n_workers) :
1176       AbstractGangTask("G1 note end"), _g1h(g1h), _cleanup_list(cleanup_list), _hrclaimer(n_workers) {
1177   }
1178 
1179   void work(uint worker_id) {
1180     FreeRegionList local_cleanup_list("Local Cleanup List");
1181     HRRSCleanupTask hrrs_cleanup_task;
1182     G1NoteEndOfConcMarkClosure g1_note_end(_g1h, &local_cleanup_list,
1183                                            &hrrs_cleanup_task);
1184     _g1h->heap_region_par_iterate(&g1_note_end, worker_id, &_hrclaimer);
1185     assert(g1_note_end.complete(), "Shouldn't have yielded!");
1186 
1187     // Now update the lists
1188     _g1h->remove_from_old_sets(g1_note_end.old_regions_removed(), g1_note_end.humongous_regions_removed());
1189     {
1190       MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
1191       _g1h->decrement_summary_bytes(g1_note_end.freed_bytes());
1192 
1193       // If we iterate over the global cleanup list at the end of
1194       // cleanup to do this printing we will not guarantee to only
1195       // generate output for the newly-reclaimed regions (the list
1196       // might not be empty at the beginning of cleanup; we might
1197       // still be working on its previous contents). So we do the
1198       // printing here, before we append the new regions to the global
1199       // cleanup list.
1200 
1201       G1HRPrinter* hr_printer = _g1h->hr_printer();
1202       if (hr_printer->is_active()) {
1203         FreeRegionListIterator iter(&local_cleanup_list);
1204         while (iter.more_available()) {
1205           HeapRegion* hr = iter.get_next();
1206           hr_printer->cleanup(hr);
1207         }
1208       }
1209 
1210       _cleanup_list->add_ordered(&local_cleanup_list);
1211       assert(local_cleanup_list.is_empty(), "post-condition");
1212 
1213       HeapRegionRemSet::finish_cleanup_task(&hrrs_cleanup_task);
1214     }
1215   }
1216 };
1217 
1218 void G1ConcurrentMark::cleanup() {
1219   // world is stopped at this checkpoint
1220   assert(SafepointSynchronize::is_at_safepoint(),
1221          "world should be stopped");
1222   G1CollectedHeap* g1h = G1CollectedHeap::heap();
1223 
1224   // If a full collection has happened, we shouldn't do this.
1225   if (has_aborted()) {
1226     g1h->collector_state()->set_mark_in_progress(false); // So bitmap clearing isn't confused
1227     return;
1228   }
1229 
1230   g1h->verifier()->verify_region_sets_optional();
1231 
1232   if (VerifyDuringGC) {
1233     HandleMark hm;  // handle scope
1234     g1h->prepare_for_verify();
1235     Universe::verify(VerifyOption_G1UsePrevMarking, "During GC (before)");
1236   }
1237   g1h->verifier()->check_bitmaps("Cleanup Start");
1238 
1239   G1Policy* g1p = g1h->g1_policy();
1240   g1p->record_concurrent_mark_cleanup_start();
1241 
1242   double start = os::elapsedTime();
1243 
1244   HeapRegionRemSet::reset_for_cleanup_tasks();
1245 
1246   {
1247     GCTraceTime(Debug, gc)("Finalize Live Data");
1248     finalize_live_data();
1249   }
1250 
1251   if (VerifyDuringGC) {
1252     GCTraceTime(Debug, gc)("Verify Live Data");
1253     verify_live_data();
1254   }
1255 
1256   g1h->collector_state()->set_mark_in_progress(false);
1257 
1258   double count_end = os::elapsedTime();
1259   double this_final_counting_time = (count_end - start);
1260   _total_counting_time += this_final_counting_time;
1261 
1262   if (log_is_enabled(Trace, gc, liveness)) {
1263     G1PrintRegionLivenessInfoClosure cl("Post-Marking");
1264     _g1h->heap_region_iterate(&cl);
1265   }
1266 
1267   // Install newly created mark bitMap as "prev".
1268   swapMarkBitMaps();
1269 
1270   g1h->reset_gc_time_stamp();
1271 
1272   uint n_workers = _g1h->workers()->active_workers();
1273 
1274   // Note end of marking in all heap regions.
1275   G1ParNoteEndTask g1_par_note_end_task(g1h, &_cleanup_list, n_workers);
1276   g1h->workers()->run_task(&g1_par_note_end_task);
1277   g1h->check_gc_time_stamps();
1278 
1279   if (!cleanup_list_is_empty()) {
1280     // The cleanup list is not empty, so we'll have to process it
1281     // concurrently. Notify anyone else that might be wanting free
1282     // regions that there will be more free regions coming soon.
1283     g1h->set_free_regions_coming();
1284   }
1285 
1286   // call below, since it affects the metric by which we sort the heap
1287   // regions.
1288   if (G1ScrubRemSets) {
1289     double rs_scrub_start = os::elapsedTime();
1290     g1h->scrub_rem_set();
1291     _total_rs_scrub_time += (os::elapsedTime() - rs_scrub_start);
1292   }
1293 
1294   // this will also free any regions totally full of garbage objects,
1295   // and sort the regions.
1296   g1h->g1_policy()->record_concurrent_mark_cleanup_end();
1297 
1298   // Statistics.
1299   double end = os::elapsedTime();
1300   _cleanup_times.add((end - start) * 1000.0);
1301 
1302   // Clean up will have freed any regions completely full of garbage.
1303   // Update the soft reference policy with the new heap occupancy.
1304   Universe::update_heap_info_at_gc();
1305 
1306   if (VerifyDuringGC) {
1307     HandleMark hm;  // handle scope
1308     g1h->prepare_for_verify();
1309     Universe::verify(VerifyOption_G1UsePrevMarking, "During GC (after)");
1310   }
1311 
1312   g1h->verifier()->check_bitmaps("Cleanup End");
1313 
1314   g1h->verifier()->verify_region_sets_optional();
1315 
1316   // We need to make this be a "collection" so any collection pause that
1317   // races with it goes around and waits for completeCleanup to finish.
1318   g1h->increment_total_collections();
1319 
1320   // Clean out dead classes and update Metaspace sizes.
1321   if (ClassUnloadingWithConcurrentMark) {
1322     ClassLoaderDataGraph::purge();
1323   }
1324   MetaspaceGC::compute_new_size();
1325 
1326   // We reclaimed old regions so we should calculate the sizes to make
1327   // sure we update the old gen/space data.
1328   g1h->g1mm()->update_sizes();
1329   g1h->allocation_context_stats().update_after_mark();
1330 }
1331 
1332 void G1ConcurrentMark::complete_cleanup() {
1333   if (has_aborted()) return;
1334 
1335   G1CollectedHeap* g1h = G1CollectedHeap::heap();
1336 
1337   _cleanup_list.verify_optional();
1338   FreeRegionList tmp_free_list("Tmp Free List");
1339 
1340   log_develop_trace(gc, freelist)("G1ConcRegionFreeing [complete cleanup] : "
1341                                   "cleanup list has %u entries",
1342                                   _cleanup_list.length());
1343 
1344   // No one else should be accessing the _cleanup_list at this point,
1345   // so it is not necessary to take any locks
1346   while (!_cleanup_list.is_empty()) {
1347     HeapRegion* hr = _cleanup_list.remove_region(true /* from_head */);
1348     assert(hr != NULL, "Got NULL from a non-empty list");
1349     hr->par_clear();
1350     tmp_free_list.add_ordered(hr);
1351 
1352     // Instead of adding one region at a time to the secondary_free_list,
1353     // we accumulate them in the local list and move them a few at a
1354     // time. This also cuts down on the number of notify_all() calls
1355     // we do during this process. We'll also append the local list when
1356     // _cleanup_list is empty (which means we just removed the last
1357     // region from the _cleanup_list).
1358     if ((tmp_free_list.length() % G1SecondaryFreeListAppendLength == 0) ||
1359         _cleanup_list.is_empty()) {
1360       log_develop_trace(gc, freelist)("G1ConcRegionFreeing [complete cleanup] : "
1361                                       "appending %u entries to the secondary_free_list, "
1362                                       "cleanup list still has %u entries",
1363                                       tmp_free_list.length(),
1364                                       _cleanup_list.length());
1365 
1366       {
1367         MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
1368         g1h->secondary_free_list_add(&tmp_free_list);
1369         SecondaryFreeList_lock->notify_all();
1370       }
1371 #ifndef PRODUCT
1372       if (G1StressConcRegionFreeing) {
1373         for (uintx i = 0; i < G1StressConcRegionFreeingDelayMillis; ++i) {
1374           os::sleep(Thread::current(), (jlong) 1, false);
1375         }
1376       }
1377 #endif
1378     }
1379   }
1380   assert(tmp_free_list.is_empty(), "post-condition");
1381 }
1382 
1383 // Supporting Object and Oop closures for reference discovery
1384 // and processing in during marking
1385 
1386 bool G1CMIsAliveClosure::do_object_b(oop obj) {
1387   HeapWord* addr = (HeapWord*)obj;
1388   return addr != NULL &&
1389          (!_g1->is_in_g1_reserved(addr) || !_g1->is_obj_ill(obj));
1390 }
1391 
1392 // 'Keep Alive' oop closure used by both serial parallel reference processing.
1393 // Uses the G1CMTask associated with a worker thread (for serial reference
1394 // processing the G1CMTask for worker 0 is used) to preserve (mark) and
1395 // trace referent objects.
1396 //
1397 // Using the G1CMTask and embedded local queues avoids having the worker
1398 // threads operating on the global mark stack. This reduces the risk
1399 // of overflowing the stack - which we would rather avoid at this late
1400 // state. Also using the tasks' local queues removes the potential
1401 // of the workers interfering with each other that could occur if
1402 // operating on the global stack.
1403 
1404 class G1CMKeepAliveAndDrainClosure: public OopClosure {
1405   G1ConcurrentMark* _cm;
1406   G1CMTask*         _task;
1407   int               _ref_counter_limit;
1408   int               _ref_counter;
1409   bool              _is_serial;
1410  public:
1411   G1CMKeepAliveAndDrainClosure(G1ConcurrentMark* cm, G1CMTask* task, bool is_serial) :
1412     _cm(cm), _task(task), _is_serial(is_serial),
1413     _ref_counter_limit(G1RefProcDrainInterval) {
1414     assert(_ref_counter_limit > 0, "sanity");
1415     assert(!_is_serial || _task->worker_id() == 0, "only task 0 for serial code");
1416     _ref_counter = _ref_counter_limit;
1417   }
1418 
1419   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
1420   virtual void do_oop(      oop* p) { do_oop_work(p); }
1421 
1422   template <class T> void do_oop_work(T* p) {
1423     if (!_cm->has_overflown()) {
1424       oop obj = oopDesc::load_decode_heap_oop(p);
1425       _task->deal_with_reference(obj);
1426       _ref_counter--;
1427 
1428       if (_ref_counter == 0) {
1429         // We have dealt with _ref_counter_limit references, pushing them
1430         // and objects reachable from them on to the local stack (and
1431         // possibly the global stack). Call G1CMTask::do_marking_step() to
1432         // process these entries.
1433         //
1434         // We call G1CMTask::do_marking_step() in a loop, which we'll exit if
1435         // there's nothing more to do (i.e. we're done with the entries that
1436         // were pushed as a result of the G1CMTask::deal_with_reference() calls
1437         // above) or we overflow.
1438         //
1439         // Note: G1CMTask::do_marking_step() can set the G1CMTask::has_aborted()
1440         // flag while there may still be some work to do. (See the comment at
1441         // the beginning of G1CMTask::do_marking_step() for those conditions -
1442         // one of which is reaching the specified time target.) It is only
1443         // when G1CMTask::do_marking_step() returns without setting the
1444         // has_aborted() flag that the marking step has completed.
1445         do {
1446           double mark_step_duration_ms = G1ConcMarkStepDurationMillis;
1447           _task->do_marking_step(mark_step_duration_ms,
1448                                  false      /* do_termination */,
1449                                  _is_serial);
1450         } while (_task->has_aborted() && !_cm->has_overflown());
1451         _ref_counter = _ref_counter_limit;
1452       }
1453     }
1454   }
1455 };
1456 
1457 // 'Drain' oop closure used by both serial and parallel reference processing.
1458 // Uses the G1CMTask associated with a given worker thread (for serial
1459 // reference processing the G1CMtask for worker 0 is used). Calls the
1460 // do_marking_step routine, with an unbelievably large timeout value,
1461 // to drain the marking data structures of the remaining entries
1462 // added by the 'keep alive' oop closure above.
1463 
1464 class G1CMDrainMarkingStackClosure: public VoidClosure {
1465   G1ConcurrentMark* _cm;
1466   G1CMTask*         _task;
1467   bool              _is_serial;
1468  public:
1469   G1CMDrainMarkingStackClosure(G1ConcurrentMark* cm, G1CMTask* task, bool is_serial) :
1470     _cm(cm), _task(task), _is_serial(is_serial) {
1471     assert(!_is_serial || _task->worker_id() == 0, "only task 0 for serial code");
1472   }
1473 
1474   void do_void() {
1475     do {
1476       // We call G1CMTask::do_marking_step() to completely drain the local
1477       // and global marking stacks of entries pushed by the 'keep alive'
1478       // oop closure (an instance of G1CMKeepAliveAndDrainClosure above).
1479       //
1480       // G1CMTask::do_marking_step() is called in a loop, which we'll exit
1481       // if there's nothing more to do (i.e. we've completely drained the
1482       // entries that were pushed as a a result of applying the 'keep alive'
1483       // closure to the entries on the discovered ref lists) or we overflow
1484       // the global marking stack.
1485       //
1486       // Note: G1CMTask::do_marking_step() can set the G1CMTask::has_aborted()
1487       // flag while there may still be some work to do. (See the comment at
1488       // the beginning of G1CMTask::do_marking_step() for those conditions -
1489       // one of which is reaching the specified time target.) It is only
1490       // when G1CMTask::do_marking_step() returns without setting the
1491       // has_aborted() flag that the marking step has completed.
1492 
1493       _task->do_marking_step(1000000000.0 /* something very large */,
1494                              true         /* do_termination */,
1495                              _is_serial);
1496     } while (_task->has_aborted() && !_cm->has_overflown());
1497   }
1498 };
1499 
1500 // Implementation of AbstractRefProcTaskExecutor for parallel
1501 // reference processing at the end of G1 concurrent marking
1502 
1503 class G1CMRefProcTaskExecutor: public AbstractRefProcTaskExecutor {
1504 private:
1505   G1CollectedHeap*  _g1h;
1506   G1ConcurrentMark* _cm;
1507   WorkGang*         _workers;
1508   uint              _active_workers;
1509 
1510 public:
1511   G1CMRefProcTaskExecutor(G1CollectedHeap* g1h,
1512                           G1ConcurrentMark* cm,
1513                           WorkGang* workers,
1514                           uint n_workers) :
1515     _g1h(g1h), _cm(cm),
1516     _workers(workers), _active_workers(n_workers) { }
1517 
1518   // Executes the given task using concurrent marking worker threads.
1519   virtual void execute(ProcessTask& task);
1520   virtual void execute(EnqueueTask& task);
1521 };
1522 
1523 class G1CMRefProcTaskProxy: public AbstractGangTask {
1524   typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
1525   ProcessTask&      _proc_task;
1526   G1CollectedHeap*  _g1h;
1527   G1ConcurrentMark* _cm;
1528 
1529 public:
1530   G1CMRefProcTaskProxy(ProcessTask& proc_task,
1531                        G1CollectedHeap* g1h,
1532                        G1ConcurrentMark* cm) :
1533     AbstractGangTask("Process reference objects in parallel"),
1534     _proc_task(proc_task), _g1h(g1h), _cm(cm) {
1535     ReferenceProcessor* rp = _g1h->ref_processor_cm();
1536     assert(rp->processing_is_mt(), "shouldn't be here otherwise");
1537   }
1538 
1539   virtual void work(uint worker_id) {
1540     ResourceMark rm;
1541     HandleMark hm;
1542     G1CMTask* task = _cm->task(worker_id);
1543     G1CMIsAliveClosure g1_is_alive(_g1h);
1544     G1CMKeepAliveAndDrainClosure g1_par_keep_alive(_cm, task, false /* is_serial */);
1545     G1CMDrainMarkingStackClosure g1_par_drain(_cm, task, false /* is_serial */);
1546 
1547     _proc_task.work(worker_id, g1_is_alive, g1_par_keep_alive, g1_par_drain);
1548   }
1549 };
1550 
1551 void G1CMRefProcTaskExecutor::execute(ProcessTask& proc_task) {
1552   assert(_workers != NULL, "Need parallel worker threads.");
1553   assert(_g1h->ref_processor_cm()->processing_is_mt(), "processing is not MT");
1554 
1555   G1CMRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _cm);
1556 
1557   // We need to reset the concurrency level before each
1558   // proxy task execution, so that the termination protocol
1559   // and overflow handling in G1CMTask::do_marking_step() knows
1560   // how many workers to wait for.
1561   _cm->set_concurrency(_active_workers);
1562   _workers->run_task(&proc_task_proxy);
1563 }
1564 
1565 class G1CMRefEnqueueTaskProxy: public AbstractGangTask {
1566   typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
1567   EnqueueTask& _enq_task;
1568 
1569 public:
1570   G1CMRefEnqueueTaskProxy(EnqueueTask& enq_task) :
1571     AbstractGangTask("Enqueue reference objects in parallel"),
1572     _enq_task(enq_task) { }
1573 
1574   virtual void work(uint worker_id) {
1575     _enq_task.work(worker_id);
1576   }
1577 };
1578 
1579 void G1CMRefProcTaskExecutor::execute(EnqueueTask& enq_task) {
1580   assert(_workers != NULL, "Need parallel worker threads.");
1581   assert(_g1h->ref_processor_cm()->processing_is_mt(), "processing is not MT");
1582 
1583   G1CMRefEnqueueTaskProxy enq_task_proxy(enq_task);
1584 
1585   // Not strictly necessary but...
1586   //
1587   // We need to reset the concurrency level before each
1588   // proxy task execution, so that the termination protocol
1589   // and overflow handling in G1CMTask::do_marking_step() knows
1590   // how many workers to wait for.
1591   _cm->set_concurrency(_active_workers);
1592   _workers->run_task(&enq_task_proxy);
1593 }
1594 
1595 void G1ConcurrentMark::weakRefsWorkParallelPart(BoolObjectClosure* is_alive, bool purged_classes) {
1596   G1CollectedHeap::heap()->parallel_cleaning(is_alive, true, true, purged_classes);
1597 }
1598 
1599 void G1ConcurrentMark::weakRefsWork(bool clear_all_soft_refs) {
1600   if (has_overflown()) {
1601     // Skip processing the discovered references if we have
1602     // overflown the global marking stack. Reference objects
1603     // only get discovered once so it is OK to not
1604     // de-populate the discovered reference lists. We could have,
1605     // but the only benefit would be that, when marking restarts,
1606     // less reference objects are discovered.
1607     return;
1608   }
1609 
1610   ResourceMark rm;
1611   HandleMark   hm;
1612 
1613   G1CollectedHeap* g1h = G1CollectedHeap::heap();
1614 
1615   // Is alive closure.
1616   G1CMIsAliveClosure g1_is_alive(g1h);
1617 
1618   // Inner scope to exclude the cleaning of the string and symbol
1619   // tables from the displayed time.
1620   {
1621     GCTraceTime(Debug, gc, phases) trace("Reference Processing", _gc_timer_cm);
1622 
1623     ReferenceProcessor* rp = g1h->ref_processor_cm();
1624 
1625     // See the comment in G1CollectedHeap::ref_processing_init()
1626     // about how reference processing currently works in G1.
1627 
1628     // Set the soft reference policy
1629     rp->setup_policy(clear_all_soft_refs);
1630     assert(_markStack.isEmpty(), "mark stack should be empty");
1631 
1632     // Instances of the 'Keep Alive' and 'Complete GC' closures used
1633     // in serial reference processing. Note these closures are also
1634     // used for serially processing (by the the current thread) the
1635     // JNI references during parallel reference processing.
1636     //
1637     // These closures do not need to synchronize with the worker
1638     // threads involved in parallel reference processing as these
1639     // instances are executed serially by the current thread (e.g.
1640     // reference processing is not multi-threaded and is thus
1641     // performed by the current thread instead of a gang worker).
1642     //
1643     // The gang tasks involved in parallel reference processing create
1644     // their own instances of these closures, which do their own
1645     // synchronization among themselves.
1646     G1CMKeepAliveAndDrainClosure g1_keep_alive(this, task(0), true /* is_serial */);
1647     G1CMDrainMarkingStackClosure g1_drain_mark_stack(this, task(0), true /* is_serial */);
1648 
1649     // We need at least one active thread. If reference processing
1650     // is not multi-threaded we use the current (VMThread) thread,
1651     // otherwise we use the work gang from the G1CollectedHeap and
1652     // we utilize all the worker threads we can.
1653     bool processing_is_mt = rp->processing_is_mt();
1654     uint active_workers = (processing_is_mt ? g1h->workers()->active_workers() : 1U);
1655     active_workers = MAX2(MIN2(active_workers, _max_worker_id), 1U);
1656 
1657     // Parallel processing task executor.
1658     G1CMRefProcTaskExecutor par_task_executor(g1h, this,
1659                                               g1h->workers(), active_workers);
1660     AbstractRefProcTaskExecutor* executor = (processing_is_mt ? &par_task_executor : NULL);
1661 
1662     // Set the concurrency level. The phase was already set prior to
1663     // executing the remark task.
1664     set_concurrency(active_workers);
1665 
1666     // Set the degree of MT processing here.  If the discovery was done MT,
1667     // the number of threads involved during discovery could differ from
1668     // the number of active workers.  This is OK as long as the discovered
1669     // Reference lists are balanced (see balance_all_queues() and balance_queues()).
1670     rp->set_active_mt_degree(active_workers);
1671 
1672     // Process the weak references.
1673     const ReferenceProcessorStats& stats =
1674         rp->process_discovered_references(&g1_is_alive,
1675                                           &g1_keep_alive,
1676                                           &g1_drain_mark_stack,
1677                                           executor,
1678                                           _gc_timer_cm);
1679     _gc_tracer_cm->report_gc_reference_stats(stats);
1680 
1681     // The do_oop work routines of the keep_alive and drain_marking_stack
1682     // oop closures will set the has_overflown flag if we overflow the
1683     // global marking stack.
1684 
1685     assert(_markStack.overflow() || _markStack.isEmpty(),
1686             "mark stack should be empty (unless it overflowed)");
1687 
1688     if (_markStack.overflow()) {
1689       // This should have been done already when we tried to push an
1690       // entry on to the global mark stack. But let's do it again.
1691       set_has_overflown();
1692     }
1693 
1694     assert(rp->num_q() == active_workers, "why not");
1695 
1696     rp->enqueue_discovered_references(executor);
1697 
1698     rp->verify_no_references_recorded();
1699     assert(!rp->discovery_enabled(), "Post condition");
1700   }
1701 
1702   if (has_overflown()) {
1703     // We can not trust g1_is_alive if the marking stack overflowed
1704     return;
1705   }
1706 
1707   assert(_markStack.isEmpty(), "Marking should have completed");
1708 
1709   // Unload Klasses, String, Symbols, Code Cache, etc.
1710   if (ClassUnloadingWithConcurrentMark) {
1711     bool purged_classes;
1712 
1713     {
1714       GCTraceTime(Debug, gc, phases) trace("System Dictionary Unloading", _gc_timer_cm);
1715       purged_classes = SystemDictionary::do_unloading(&g1_is_alive, false /* Defer klass cleaning */);
1716     }
1717 
1718     {
1719       GCTraceTime(Debug, gc, phases) trace("Parallel Unloading", _gc_timer_cm);
1720       weakRefsWorkParallelPart(&g1_is_alive, purged_classes);
1721     }
1722   }
1723 
1724   if (G1StringDedup::is_enabled()) {
1725     GCTraceTime(Debug, gc, phases) trace("String Deduplication Unlink", _gc_timer_cm);
1726     G1StringDedup::unlink(&g1_is_alive);
1727   }
1728 }
1729 
1730 void G1ConcurrentMark::swapMarkBitMaps() {
1731   G1CMBitMapRO* temp = _prevMarkBitMap;
1732   _prevMarkBitMap    = (G1CMBitMapRO*)_nextMarkBitMap;
1733   _nextMarkBitMap    = (G1CMBitMap*)  temp;
1734 }
1735 
1736 // Closure for marking entries in SATB buffers.
1737 class G1CMSATBBufferClosure : public SATBBufferClosure {
1738 private:
1739   G1CMTask* _task;
1740   G1CollectedHeap* _g1h;
1741 
1742   // This is very similar to G1CMTask::deal_with_reference, but with
1743   // more relaxed requirements for the argument, so this must be more
1744   // circumspect about treating the argument as an object.
1745   void do_entry(void* entry) const {
1746     _task->increment_refs_reached();
1747     HeapRegion* hr = _g1h->heap_region_containing(entry);
1748     if (entry < hr->next_top_at_mark_start()) {
1749       // Until we get here, we don't know whether entry refers to a valid
1750       // object; it could instead have been a stale reference.
1751       oop obj = static_cast<oop>(entry);
1752       assert(obj->is_oop(true /* ignore mark word */),
1753              "Invalid oop in SATB buffer: " PTR_FORMAT, p2i(obj));
1754       _task->make_reference_grey(obj);
1755     }
1756   }
1757 
1758 public:
1759   G1CMSATBBufferClosure(G1CMTask* task, G1CollectedHeap* g1h)
1760     : _task(task), _g1h(g1h) { }
1761 
1762   virtual void do_buffer(void** buffer, size_t size) {
1763     for (size_t i = 0; i < size; ++i) {
1764       do_entry(buffer[i]);
1765     }
1766   }
1767 };
1768 
1769 class G1RemarkThreadsClosure : public ThreadClosure {
1770   G1CMSATBBufferClosure _cm_satb_cl;
1771   G1CMOopClosure _cm_cl;
1772   MarkingCodeBlobClosure _code_cl;
1773   int _thread_parity;
1774 
1775  public:
1776   G1RemarkThreadsClosure(G1CollectedHeap* g1h, G1CMTask* task) :
1777     _cm_satb_cl(task, g1h),
1778     _cm_cl(g1h, g1h->concurrent_mark(), task),
1779     _code_cl(&_cm_cl, !CodeBlobToOopClosure::FixRelocations),
1780     _thread_parity(Threads::thread_claim_parity()) {}
1781 
1782   void do_thread(Thread* thread) {
1783     if (thread->is_Java_thread()) {
1784       if (thread->claim_oops_do(true, _thread_parity)) {
1785         JavaThread* jt = (JavaThread*)thread;
1786 
1787         // In theory it should not be neccessary to explicitly walk the nmethods to find roots for concurrent marking
1788         // however the liveness of oops reachable from nmethods have very complex lifecycles:
1789         // * Alive if on the stack of an executing method
1790         // * Weakly reachable otherwise
1791         // Some objects reachable from nmethods, such as the class loader (or klass_holder) of the receiver should be
1792         // live by the SATB invariant but other oops recorded in nmethods may behave differently.
1793         jt->nmethods_do(&_code_cl);
1794 
1795         jt->satb_mark_queue().apply_closure_and_empty(&_cm_satb_cl);
1796       }
1797     } else if (thread->is_VM_thread()) {
1798       if (thread->claim_oops_do(true, _thread_parity)) {
1799         JavaThread::satb_mark_queue_set().shared_satb_queue()->apply_closure_and_empty(&_cm_satb_cl);
1800       }
1801     }
1802   }
1803 };
1804 
1805 class G1CMRemarkTask: public AbstractGangTask {
1806 private:
1807   G1ConcurrentMark* _cm;
1808 public:
1809   void work(uint worker_id) {
1810     // Since all available tasks are actually started, we should
1811     // only proceed if we're supposed to be active.
1812     if (worker_id < _cm->active_tasks()) {
1813       G1CMTask* task = _cm->task(worker_id);
1814       task->record_start_time();
1815       {
1816         ResourceMark rm;
1817         HandleMark hm;
1818 
1819         G1RemarkThreadsClosure threads_f(G1CollectedHeap::heap(), task);
1820         Threads::threads_do(&threads_f);
1821       }
1822 
1823       do {
1824         task->do_marking_step(1000000000.0 /* something very large */,
1825                               true         /* do_termination       */,
1826                               false        /* is_serial            */);
1827       } while (task->has_aborted() && !_cm->has_overflown());
1828       // If we overflow, then we do not want to restart. We instead
1829       // want to abort remark and do concurrent marking again.
1830       task->record_end_time();
1831     }
1832   }
1833 
1834   G1CMRemarkTask(G1ConcurrentMark* cm, uint active_workers) :
1835     AbstractGangTask("Par Remark"), _cm(cm) {
1836     _cm->terminator()->reset_for_reuse(active_workers);
1837   }
1838 };
1839 
1840 void G1ConcurrentMark::checkpointRootsFinalWork() {
1841   ResourceMark rm;
1842   HandleMark   hm;
1843   G1CollectedHeap* g1h = G1CollectedHeap::heap();
1844 
1845   GCTraceTime(Debug, gc, phases) trace("Finalize Marking", _gc_timer_cm);
1846 
1847   g1h->ensure_parsability(false);
1848 
1849   // this is remark, so we'll use up all active threads
1850   uint active_workers = g1h->workers()->active_workers();
1851   set_concurrency_and_phase(active_workers, false /* concurrent */);
1852   // Leave _parallel_marking_threads at it's
1853   // value originally calculated in the G1ConcurrentMark
1854   // constructor and pass values of the active workers
1855   // through the gang in the task.
1856 
1857   {
1858     StrongRootsScope srs(active_workers);
1859 
1860     G1CMRemarkTask remarkTask(this, active_workers);
1861     // We will start all available threads, even if we decide that the
1862     // active_workers will be fewer. The extra ones will just bail out
1863     // immediately.
1864     g1h->workers()->run_task(&remarkTask);
1865   }
1866 
1867   SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
1868   guarantee(has_overflown() ||
1869             satb_mq_set.completed_buffers_num() == 0,
1870             "Invariant: has_overflown = %s, num buffers = " SIZE_FORMAT,
1871             BOOL_TO_STR(has_overflown()),
1872             satb_mq_set.completed_buffers_num());
1873 
1874   print_stats();
1875 }
1876 
1877 void G1ConcurrentMark::clearRangePrevBitmap(MemRegion mr) {
1878   // Note we are overriding the read-only view of the prev map here, via
1879   // the cast.
1880   ((G1CMBitMap*)_prevMarkBitMap)->clear_range(mr);
1881 }
1882 
1883 HeapRegion*
1884 G1ConcurrentMark::claim_region(uint worker_id) {
1885   // "checkpoint" the finger
1886   HeapWord* finger = _finger;
1887 
1888   // _heap_end will not change underneath our feet; it only changes at
1889   // yield points.
1890   while (finger < _heap_end) {
1891     assert(_g1h->is_in_g1_reserved(finger), "invariant");
1892 
1893     HeapRegion* curr_region = _g1h->heap_region_containing(finger);
1894 
1895     // Above heap_region_containing may return NULL as we always scan claim
1896     // until the end of the heap. In this case, just jump to the next region.
1897     HeapWord* end = curr_region != NULL ? curr_region->end() : finger + HeapRegion::GrainWords;
1898 
1899     // Is the gap between reading the finger and doing the CAS too long?
1900     HeapWord* res = (HeapWord*) Atomic::cmpxchg_ptr(end, &_finger, finger);
1901     if (res == finger && curr_region != NULL) {
1902       // we succeeded
1903       HeapWord*   bottom        = curr_region->bottom();
1904       HeapWord*   limit         = curr_region->next_top_at_mark_start();
1905 
1906       // notice that _finger == end cannot be guaranteed here since,
1907       // someone else might have moved the finger even further
1908       assert(_finger >= end, "the finger should have moved forward");
1909 
1910       if (limit > bottom) {
1911         return curr_region;
1912       } else {
1913         assert(limit == bottom,
1914                "the region limit should be at bottom");
1915         // we return NULL and the caller should try calling
1916         // claim_region() again.
1917         return NULL;
1918       }
1919     } else {
1920       assert(_finger > finger, "the finger should have moved forward");
1921       // read it again
1922       finger = _finger;
1923     }
1924   }
1925 
1926   return NULL;
1927 }
1928 
1929 #ifndef PRODUCT
1930 class VerifyNoCSetOops VALUE_OBJ_CLASS_SPEC {
1931 private:
1932   G1CollectedHeap* _g1h;
1933   const char* _phase;
1934   int _info;
1935 
1936 public:
1937   VerifyNoCSetOops(const char* phase, int info = -1) :
1938     _g1h(G1CollectedHeap::heap()),
1939     _phase(phase),
1940     _info(info)
1941   { }
1942 
1943   void operator()(oop obj) const {
1944     guarantee(obj->is_oop(),
1945               "Non-oop " PTR_FORMAT ", phase: %s, info: %d",
1946               p2i(obj), _phase, _info);
1947     guarantee(!_g1h->obj_in_cs(obj),
1948               "obj: " PTR_FORMAT " in CSet, phase: %s, info: %d",
1949               p2i(obj), _phase, _info);
1950   }
1951 };
1952 
1953 void G1ConcurrentMark::verify_no_cset_oops() {
1954   assert(SafepointSynchronize::is_at_safepoint(), "should be at a safepoint");
1955   if (!G1CollectedHeap::heap()->collector_state()->mark_in_progress()) {
1956     return;
1957   }
1958 
1959   // Verify entries on the global mark stack
1960   _markStack.iterate(VerifyNoCSetOops("Stack"));
1961 
1962   // Verify entries on the task queues
1963   for (uint i = 0; i < _max_worker_id; ++i) {
1964     G1CMTaskQueue* queue = _task_queues->queue(i);
1965     queue->iterate(VerifyNoCSetOops("Queue", i));
1966   }
1967 
1968   // Verify the global finger
1969   HeapWord* global_finger = finger();
1970   if (global_finger != NULL && global_finger < _heap_end) {
1971     // Since we always iterate over all regions, we might get a NULL HeapRegion
1972     // here.
1973     HeapRegion* global_hr = _g1h->heap_region_containing(global_finger);
1974     guarantee(global_hr == NULL || global_finger == global_hr->bottom(),
1975               "global finger: " PTR_FORMAT " region: " HR_FORMAT,
1976               p2i(global_finger), HR_FORMAT_PARAMS(global_hr));
1977   }
1978 
1979   // Verify the task fingers
1980   assert(parallel_marking_threads() <= _max_worker_id, "sanity");
1981   for (uint i = 0; i < parallel_marking_threads(); ++i) {
1982     G1CMTask* task = _tasks[i];
1983     HeapWord* task_finger = task->finger();
1984     if (task_finger != NULL && task_finger < _heap_end) {
1985       // See above note on the global finger verification.
1986       HeapRegion* task_hr = _g1h->heap_region_containing(task_finger);
1987       guarantee(task_hr == NULL || task_finger == task_hr->bottom() ||
1988                 !task_hr->in_collection_set(),
1989                 "task finger: " PTR_FORMAT " region: " HR_FORMAT,
1990                 p2i(task_finger), HR_FORMAT_PARAMS(task_hr));
1991     }
1992   }
1993 }
1994 #endif // PRODUCT
1995 void G1ConcurrentMark::create_live_data() {
1996   _g1h->g1_rem_set()->create_card_live_data(_parallel_workers, _nextMarkBitMap);
1997 }
1998 
1999 void G1ConcurrentMark::finalize_live_data() {
2000   _g1h->g1_rem_set()->finalize_card_live_data(_g1h->workers(), _nextMarkBitMap);
2001 }
2002 
2003 void G1ConcurrentMark::verify_live_data() {
2004   _g1h->g1_rem_set()->verify_card_live_data(_g1h->workers(), _nextMarkBitMap);
2005 }
2006 
2007 void G1ConcurrentMark::clear_live_data(WorkGang* workers) {
2008   _g1h->g1_rem_set()->clear_card_live_data(workers);
2009 }
2010 
2011 #ifdef ASSERT
2012 void G1ConcurrentMark::verify_live_data_clear() {
2013   _g1h->g1_rem_set()->verify_card_live_data_is_clear();
2014 }
2015 #endif
2016 
2017 void G1ConcurrentMark::print_stats() {
2018   if (!log_is_enabled(Debug, gc, stats)) {
2019     return;
2020   }
2021   log_debug(gc, stats)("---------------------------------------------------------------------");
2022   for (size_t i = 0; i < _active_tasks; ++i) {
2023     _tasks[i]->print_stats();
2024     log_debug(gc, stats)("---------------------------------------------------------------------");
2025   }
2026 }
2027 
2028 void G1ConcurrentMark::abort() {
2029   if (!cmThread()->during_cycle() || _has_aborted) {
2030     // We haven't started a concurrent cycle or we have already aborted it. No need to do anything.
2031     return;
2032   }
2033 
2034   // Clear all marks in the next bitmap for the next marking cycle. This will allow us to skip the next
2035   // concurrent bitmap clearing.
2036   {
2037     GCTraceTime(Debug, gc)("Clear Next Bitmap");
2038     clear_bitmap(_nextMarkBitMap, _g1h->workers(), false);
2039   }
2040   // Note we cannot clear the previous marking bitmap here
2041   // since VerifyDuringGC verifies the objects marked during
2042   // a full GC against the previous bitmap.
2043 
2044   {
2045     GCTraceTime(Debug, gc)("Clear Live Data");
2046     clear_live_data(_g1h->workers());
2047   }
2048   DEBUG_ONLY({
2049     GCTraceTime(Debug, gc)("Verify Live Data Clear");
2050     verify_live_data_clear();
2051   })
2052   // Empty mark stack
2053   reset_marking_state();
2054   for (uint i = 0; i < _max_worker_id; ++i) {
2055     _tasks[i]->clear_region_fields();
2056   }
2057   _first_overflow_barrier_sync.abort();
2058   _second_overflow_barrier_sync.abort();
2059   _has_aborted = true;
2060 
2061   SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
2062   satb_mq_set.abandon_partial_marking();
2063   // This can be called either during or outside marking, we'll read
2064   // the expected_active value from the SATB queue set.
2065   satb_mq_set.set_active_all_threads(
2066                                  false, /* new active value */
2067                                  satb_mq_set.is_active() /* expected_active */);
2068 }
2069 
2070 static void print_ms_time_info(const char* prefix, const char* name,
2071                                NumberSeq& ns) {
2072   log_trace(gc, marking)("%s%5d %12s: total time = %8.2f s (avg = %8.2f ms).",
2073                          prefix, ns.num(), name, ns.sum()/1000.0, ns.avg());
2074   if (ns.num() > 0) {
2075     log_trace(gc, marking)("%s         [std. dev = %8.2f ms, max = %8.2f ms]",
2076                            prefix, ns.sd(), ns.maximum());
2077   }
2078 }
2079 
2080 void G1ConcurrentMark::print_summary_info() {
2081   Log(gc, marking) log;
2082   if (!log.is_trace()) {
2083     return;
2084   }
2085 
2086   log.trace(" Concurrent marking:");
2087   print_ms_time_info("  ", "init marks", _init_times);
2088   print_ms_time_info("  ", "remarks", _remark_times);
2089   {
2090     print_ms_time_info("     ", "final marks", _remark_mark_times);
2091     print_ms_time_info("     ", "weak refs", _remark_weak_ref_times);
2092 
2093   }
2094   print_ms_time_info("  ", "cleanups", _cleanup_times);
2095   log.trace("    Finalize live data total time = %8.2f s (avg = %8.2f ms).",
2096             _total_counting_time, (_cleanup_times.num() > 0 ? _total_counting_time * 1000.0 / (double)_cleanup_times.num() : 0.0));
2097   if (G1ScrubRemSets) {
2098     log.trace("    RS scrub total time = %8.2f s (avg = %8.2f ms).",
2099               _total_rs_scrub_time, (_cleanup_times.num() > 0 ? _total_rs_scrub_time * 1000.0 / (double)_cleanup_times.num() : 0.0));
2100   }
2101   log.trace("  Total stop_world time = %8.2f s.",
2102             (_init_times.sum() + _remark_times.sum() + _cleanup_times.sum())/1000.0);
2103   log.trace("  Total concurrent time = %8.2f s (%8.2f s marking).",
2104             cmThread()->vtime_accum(), cmThread()->vtime_mark_accum());
2105 }
2106 
2107 void G1ConcurrentMark::print_worker_threads_on(outputStream* st) const {
2108   _parallel_workers->print_worker_threads_on(st);
2109 }
2110 
2111 void G1ConcurrentMark::threads_do(ThreadClosure* tc) const {
2112   _parallel_workers->threads_do(tc);
2113 }
2114 
2115 void G1ConcurrentMark::print_on_error(outputStream* st) const {
2116   st->print_cr("Marking Bits (Prev, Next): (CMBitMap*) " PTR_FORMAT ", (CMBitMap*) " PTR_FORMAT,
2117       p2i(_prevMarkBitMap), p2i(_nextMarkBitMap));
2118   _prevMarkBitMap->print_on_error(st, " Prev Bits: ");
2119   _nextMarkBitMap->print_on_error(st, " Next Bits: ");
2120 }
2121 
2122 // Closure for iteration over bitmaps
2123 class G1CMBitMapClosure : public BitMapClosure {
2124 private:
2125   // the bitmap that is being iterated over
2126   G1CMBitMap*                 _nextMarkBitMap;
2127   G1ConcurrentMark*           _cm;
2128   G1CMTask*                   _task;
2129 
2130 public:
2131   G1CMBitMapClosure(G1CMTask *task, G1ConcurrentMark* cm, G1CMBitMap* nextMarkBitMap) :
2132     _task(task), _cm(cm), _nextMarkBitMap(nextMarkBitMap) { }
2133 
2134   bool do_bit(size_t offset) {
2135     HeapWord* addr = _nextMarkBitMap->offsetToHeapWord(offset);
2136     assert(_nextMarkBitMap->isMarked(addr), "invariant");
2137     assert( addr < _cm->finger(), "invariant");
2138     assert(addr >= _task->finger(), "invariant");
2139 
2140     // We move that task's local finger along.
2141     _task->move_finger_to(addr);
2142 
2143     _task->scan_object(oop(addr));
2144     // we only partially drain the local queue and global stack
2145     _task->drain_local_queue(true);
2146     _task->drain_global_stack(true);
2147 
2148     // if the has_aborted flag has been raised, we need to bail out of
2149     // the iteration
2150     return !_task->has_aborted();
2151   }
2152 };
2153 
2154 static ReferenceProcessor* get_cm_oop_closure_ref_processor(G1CollectedHeap* g1h) {
2155   ReferenceProcessor* result = g1h->ref_processor_cm();
2156   assert(result != NULL, "CM reference processor should not be NULL");
2157   return result;
2158 }
2159 
2160 G1CMOopClosure::G1CMOopClosure(G1CollectedHeap* g1h,
2161                                G1ConcurrentMark* cm,
2162                                G1CMTask* task)
2163   : MetadataAwareOopClosure(get_cm_oop_closure_ref_processor(g1h)),
2164     _g1h(g1h), _cm(cm), _task(task)
2165 { }
2166 
2167 void G1CMTask::setup_for_region(HeapRegion* hr) {
2168   assert(hr != NULL,
2169         "claim_region() should have filtered out NULL regions");
2170   _curr_region  = hr;
2171   _finger       = hr->bottom();
2172   update_region_limit();
2173 }
2174 
2175 void G1CMTask::update_region_limit() {
2176   HeapRegion* hr            = _curr_region;
2177   HeapWord* bottom          = hr->bottom();
2178   HeapWord* limit           = hr->next_top_at_mark_start();
2179 
2180   if (limit == bottom) {
2181     // The region was collected underneath our feet.
2182     // We set the finger to bottom to ensure that the bitmap
2183     // iteration that will follow this will not do anything.
2184     // (this is not a condition that holds when we set the region up,
2185     // as the region is not supposed to be empty in the first place)
2186     _finger = bottom;
2187   } else if (limit >= _region_limit) {
2188     assert(limit >= _finger, "peace of mind");
2189   } else {
2190     assert(limit < _region_limit, "only way to get here");
2191     // This can happen under some pretty unusual circumstances.  An
2192     // evacuation pause empties the region underneath our feet (NTAMS
2193     // at bottom). We then do some allocation in the region (NTAMS
2194     // stays at bottom), followed by the region being used as a GC
2195     // alloc region (NTAMS will move to top() and the objects
2196     // originally below it will be grayed). All objects now marked in
2197     // the region are explicitly grayed, if below the global finger,
2198     // and we do not need in fact to scan anything else. So, we simply
2199     // set _finger to be limit to ensure that the bitmap iteration
2200     // doesn't do anything.
2201     _finger = limit;
2202   }
2203 
2204   _region_limit = limit;
2205 }
2206 
2207 void G1CMTask::giveup_current_region() {
2208   assert(_curr_region != NULL, "invariant");
2209   clear_region_fields();
2210 }
2211 
2212 void G1CMTask::clear_region_fields() {
2213   // Values for these three fields that indicate that we're not
2214   // holding on to a region.
2215   _curr_region   = NULL;
2216   _finger        = NULL;
2217   _region_limit  = NULL;
2218 }
2219 
2220 void G1CMTask::set_cm_oop_closure(G1CMOopClosure* cm_oop_closure) {
2221   if (cm_oop_closure == NULL) {
2222     assert(_cm_oop_closure != NULL, "invariant");
2223   } else {
2224     assert(_cm_oop_closure == NULL, "invariant");
2225   }
2226   _cm_oop_closure = cm_oop_closure;
2227 }
2228 
2229 void G1CMTask::reset(G1CMBitMap* nextMarkBitMap) {
2230   guarantee(nextMarkBitMap != NULL, "invariant");
2231   _nextMarkBitMap                = nextMarkBitMap;
2232   clear_region_fields();
2233 
2234   _calls                         = 0;
2235   _elapsed_time_ms               = 0.0;
2236   _termination_time_ms           = 0.0;
2237   _termination_start_time_ms     = 0.0;
2238 }
2239 
2240 bool G1CMTask::should_exit_termination() {
2241   regular_clock_call();
2242   // This is called when we are in the termination protocol. We should
2243   // quit if, for some reason, this task wants to abort or the global
2244   // stack is not empty (this means that we can get work from it).
2245   return !_cm->mark_stack_empty() || has_aborted();
2246 }
2247 
2248 void G1CMTask::reached_limit() {
2249   assert(_words_scanned >= _words_scanned_limit ||
2250          _refs_reached >= _refs_reached_limit ,
2251          "shouldn't have been called otherwise");
2252   regular_clock_call();
2253 }
2254 
2255 void G1CMTask::regular_clock_call() {
2256   if (has_aborted()) return;
2257 
2258   // First, we need to recalculate the words scanned and refs reached
2259   // limits for the next clock call.
2260   recalculate_limits();
2261 
2262   // During the regular clock call we do the following
2263 
2264   // (1) If an overflow has been flagged, then we abort.
2265   if (_cm->has_overflown()) {
2266     set_has_aborted();
2267     return;
2268   }
2269 
2270   // If we are not concurrent (i.e. we're doing remark) we don't need
2271   // to check anything else. The other steps are only needed during
2272   // the concurrent marking phase.
2273   if (!concurrent()) return;
2274 
2275   // (2) If marking has been aborted for Full GC, then we also abort.
2276   if (_cm->has_aborted()) {
2277     set_has_aborted();
2278     return;
2279   }
2280 
2281   double curr_time_ms = os::elapsedVTime() * 1000.0;
2282 
2283   // (4) We check whether we should yield. If we have to, then we abort.
2284   if (SuspendibleThreadSet::should_yield()) {
2285     // We should yield. To do this we abort the task. The caller is
2286     // responsible for yielding.
2287     set_has_aborted();
2288     return;
2289   }
2290 
2291   // (5) We check whether we've reached our time quota. If we have,
2292   // then we abort.
2293   double elapsed_time_ms = curr_time_ms - _start_time_ms;
2294   if (elapsed_time_ms > _time_target_ms) {
2295     set_has_aborted();
2296     _has_timed_out = true;
2297     return;
2298   }
2299 
2300   // (6) Finally, we check whether there are enough completed STAB
2301   // buffers available for processing. If there are, we abort.
2302   SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
2303   if (!_draining_satb_buffers && satb_mq_set.process_completed_buffers()) {
2304     // we do need to process SATB buffers, we'll abort and restart
2305     // the marking task to do so
2306     set_has_aborted();
2307     return;
2308   }
2309 }
2310 
2311 void G1CMTask::recalculate_limits() {
2312   _real_words_scanned_limit = _words_scanned + words_scanned_period;
2313   _words_scanned_limit      = _real_words_scanned_limit;
2314 
2315   _real_refs_reached_limit  = _refs_reached  + refs_reached_period;
2316   _refs_reached_limit       = _real_refs_reached_limit;
2317 }
2318 
2319 void G1CMTask::decrease_limits() {
2320   // This is called when we believe that we're going to do an infrequent
2321   // operation which will increase the per byte scanned cost (i.e. move
2322   // entries to/from the global stack). It basically tries to decrease the
2323   // scanning limit so that the clock is called earlier.
2324 
2325   _words_scanned_limit = _real_words_scanned_limit -
2326     3 * words_scanned_period / 4;
2327   _refs_reached_limit  = _real_refs_reached_limit -
2328     3 * refs_reached_period / 4;
2329 }
2330 
2331 void G1CMTask::move_entries_to_global_stack() {
2332   // local array where we'll store the entries that will be popped
2333   // from the local queue
2334   oop buffer[global_stack_transfer_size];
2335 
2336   int n = 0;
2337   oop obj;
2338   while (n < global_stack_transfer_size && _task_queue->pop_local(obj)) {
2339     buffer[n] = obj;
2340     ++n;
2341   }
2342 
2343   if (n > 0) {
2344     // we popped at least one entry from the local queue
2345 
2346     if (!_cm->mark_stack_push(buffer, n)) {
2347       set_has_aborted();
2348     }
2349   }
2350 
2351   // this operation was quite expensive, so decrease the limits
2352   decrease_limits();
2353 }
2354 
2355 void G1CMTask::get_entries_from_global_stack() {
2356   // local array where we'll store the entries that will be popped
2357   // from the global stack.
2358   oop buffer[global_stack_transfer_size];
2359   int n;
2360   _cm->mark_stack_pop(buffer, global_stack_transfer_size, &n);
2361   assert(n <= global_stack_transfer_size,
2362          "we should not pop more than the given limit");
2363   if (n > 0) {
2364     // yes, we did actually pop at least one entry
2365     for (int i = 0; i < n; ++i) {
2366       bool success = _task_queue->push(buffer[i]);
2367       // We only call this when the local queue is empty or under a
2368       // given target limit. So, we do not expect this push to fail.
2369       assert(success, "invariant");
2370     }
2371   }
2372 
2373   // this operation was quite expensive, so decrease the limits
2374   decrease_limits();
2375 }
2376 
2377 void G1CMTask::drain_local_queue(bool partially) {
2378   if (has_aborted()) return;
2379 
2380   // Decide what the target size is, depending whether we're going to
2381   // drain it partially (so that other tasks can steal if they run out
2382   // of things to do) or totally (at the very end).
2383   size_t target_size;
2384   if (partially) {
2385     target_size = MIN2((size_t)_task_queue->max_elems()/3, GCDrainStackTargetSize);
2386   } else {
2387     target_size = 0;
2388   }
2389 
2390   if (_task_queue->size() > target_size) {
2391     oop obj;
2392     bool ret = _task_queue->pop_local(obj);
2393     while (ret) {
2394       assert(_g1h->is_in_g1_reserved((HeapWord*) obj), "invariant" );
2395       assert(!_g1h->is_on_master_free_list(
2396                   _g1h->heap_region_containing((HeapWord*) obj)), "invariant");
2397 
2398       scan_object(obj);
2399 
2400       if (_task_queue->size() <= target_size || has_aborted()) {
2401         ret = false;
2402       } else {
2403         ret = _task_queue->pop_local(obj);
2404       }
2405     }
2406   }
2407 }
2408 
2409 void G1CMTask::drain_global_stack(bool partially) {
2410   if (has_aborted()) return;
2411 
2412   // We have a policy to drain the local queue before we attempt to
2413   // drain the global stack.
2414   assert(partially || _task_queue->size() == 0, "invariant");
2415 
2416   // Decide what the target size is, depending whether we're going to
2417   // drain it partially (so that other tasks can steal if they run out
2418   // of things to do) or totally (at the very end).  Notice that,
2419   // because we move entries from the global stack in chunks or
2420   // because another task might be doing the same, we might in fact
2421   // drop below the target. But, this is not a problem.
2422   size_t target_size;
2423   if (partially) {
2424     target_size = _cm->partial_mark_stack_size_target();
2425   } else {
2426     target_size = 0;
2427   }
2428 
2429   if (_cm->mark_stack_size() > target_size) {
2430     while (!has_aborted() && _cm->mark_stack_size() > target_size) {
2431       get_entries_from_global_stack();
2432       drain_local_queue(partially);
2433     }
2434   }
2435 }
2436 
2437 // SATB Queue has several assumptions on whether to call the par or
2438 // non-par versions of the methods. this is why some of the code is
2439 // replicated. We should really get rid of the single-threaded version
2440 // of the code to simplify things.
2441 void G1CMTask::drain_satb_buffers() {
2442   if (has_aborted()) return;
2443 
2444   // We set this so that the regular clock knows that we're in the
2445   // middle of draining buffers and doesn't set the abort flag when it
2446   // notices that SATB buffers are available for draining. It'd be
2447   // very counter productive if it did that. :-)
2448   _draining_satb_buffers = true;
2449 
2450   G1CMSATBBufferClosure satb_cl(this, _g1h);
2451   SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
2452 
2453   // This keeps claiming and applying the closure to completed buffers
2454   // until we run out of buffers or we need to abort.
2455   while (!has_aborted() &&
2456          satb_mq_set.apply_closure_to_completed_buffer(&satb_cl)) {
2457     regular_clock_call();
2458   }
2459 
2460   _draining_satb_buffers = false;
2461 
2462   assert(has_aborted() ||
2463          concurrent() ||
2464          satb_mq_set.completed_buffers_num() == 0, "invariant");
2465 
2466   // again, this was a potentially expensive operation, decrease the
2467   // limits to get the regular clock call early
2468   decrease_limits();
2469 }
2470 
2471 void G1CMTask::print_stats() {
2472   log_debug(gc, stats)("Marking Stats, task = %u, calls = %d",
2473                        _worker_id, _calls);
2474   log_debug(gc, stats)("  Elapsed time = %1.2lfms, Termination time = %1.2lfms",
2475                        _elapsed_time_ms, _termination_time_ms);
2476   log_debug(gc, stats)("  Step Times (cum): num = %d, avg = %1.2lfms, sd = %1.2lfms",
2477                        _step_times_ms.num(), _step_times_ms.avg(),
2478                        _step_times_ms.sd());
2479   log_debug(gc, stats)("                    max = %1.2lfms, total = %1.2lfms",
2480                        _step_times_ms.maximum(), _step_times_ms.sum());
2481 }
2482 
2483 bool G1ConcurrentMark::try_stealing(uint worker_id, int* hash_seed, oop& obj) {
2484   return _task_queues->steal(worker_id, hash_seed, obj);
2485 }
2486 
2487 /*****************************************************************************
2488 
2489     The do_marking_step(time_target_ms, ...) method is the building
2490     block of the parallel marking framework. It can be called in parallel
2491     with other invocations of do_marking_step() on different tasks
2492     (but only one per task, obviously) and concurrently with the
2493     mutator threads, or during remark, hence it eliminates the need
2494     for two versions of the code. When called during remark, it will
2495     pick up from where the task left off during the concurrent marking
2496     phase. Interestingly, tasks are also claimable during evacuation
2497     pauses too, since do_marking_step() ensures that it aborts before
2498     it needs to yield.
2499 
2500     The data structures that it uses to do marking work are the
2501     following:
2502 
2503       (1) Marking Bitmap. If there are gray objects that appear only
2504       on the bitmap (this happens either when dealing with an overflow
2505       or when the initial marking phase has simply marked the roots
2506       and didn't push them on the stack), then tasks claim heap
2507       regions whose bitmap they then scan to find gray objects. A
2508       global finger indicates where the end of the last claimed region
2509       is. A local finger indicates how far into the region a task has
2510       scanned. The two fingers are used to determine how to gray an
2511       object (i.e. whether simply marking it is OK, as it will be
2512       visited by a task in the future, or whether it needs to be also
2513       pushed on a stack).
2514 
2515       (2) Local Queue. The local queue of the task which is accessed
2516       reasonably efficiently by the task. Other tasks can steal from
2517       it when they run out of work. Throughout the marking phase, a
2518       task attempts to keep its local queue short but not totally
2519       empty, so that entries are available for stealing by other
2520       tasks. Only when there is no more work, a task will totally
2521       drain its local queue.
2522 
2523       (3) Global Mark Stack. This handles local queue overflow. During
2524       marking only sets of entries are moved between it and the local
2525       queues, as access to it requires a mutex and more fine-grain
2526       interaction with it which might cause contention. If it
2527       overflows, then the marking phase should restart and iterate
2528       over the bitmap to identify gray objects. Throughout the marking
2529       phase, tasks attempt to keep the global mark stack at a small
2530       length but not totally empty, so that entries are available for
2531       popping by other tasks. Only when there is no more work, tasks
2532       will totally drain the global mark stack.
2533 
2534       (4) SATB Buffer Queue. This is where completed SATB buffers are
2535       made available. Buffers are regularly removed from this queue
2536       and scanned for roots, so that the queue doesn't get too
2537       long. During remark, all completed buffers are processed, as
2538       well as the filled in parts of any uncompleted buffers.
2539 
2540     The do_marking_step() method tries to abort when the time target
2541     has been reached. There are a few other cases when the
2542     do_marking_step() method also aborts:
2543 
2544       (1) When the marking phase has been aborted (after a Full GC).
2545 
2546       (2) When a global overflow (on the global stack) has been
2547       triggered. Before the task aborts, it will actually sync up with
2548       the other tasks to ensure that all the marking data structures
2549       (local queues, stacks, fingers etc.)  are re-initialized so that
2550       when do_marking_step() completes, the marking phase can
2551       immediately restart.
2552 
2553       (3) When enough completed SATB buffers are available. The
2554       do_marking_step() method only tries to drain SATB buffers right
2555       at the beginning. So, if enough buffers are available, the
2556       marking step aborts and the SATB buffers are processed at
2557       the beginning of the next invocation.
2558 
2559       (4) To yield. when we have to yield then we abort and yield
2560       right at the end of do_marking_step(). This saves us from a lot
2561       of hassle as, by yielding we might allow a Full GC. If this
2562       happens then objects will be compacted underneath our feet, the
2563       heap might shrink, etc. We save checking for this by just
2564       aborting and doing the yield right at the end.
2565 
2566     From the above it follows that the do_marking_step() method should
2567     be called in a loop (or, otherwise, regularly) until it completes.
2568 
2569     If a marking step completes without its has_aborted() flag being
2570     true, it means it has completed the current marking phase (and
2571     also all other marking tasks have done so and have all synced up).
2572 
2573     A method called regular_clock_call() is invoked "regularly" (in
2574     sub ms intervals) throughout marking. It is this clock method that
2575     checks all the abort conditions which were mentioned above and
2576     decides when the task should abort. A work-based scheme is used to
2577     trigger this clock method: when the number of object words the
2578     marking phase has scanned or the number of references the marking
2579     phase has visited reach a given limit. Additional invocations to
2580     the method clock have been planted in a few other strategic places
2581     too. The initial reason for the clock method was to avoid calling
2582     vtime too regularly, as it is quite expensive. So, once it was in
2583     place, it was natural to piggy-back all the other conditions on it
2584     too and not constantly check them throughout the code.
2585 
2586     If do_termination is true then do_marking_step will enter its
2587     termination protocol.
2588 
2589     The value of is_serial must be true when do_marking_step is being
2590     called serially (i.e. by the VMThread) and do_marking_step should
2591     skip any synchronization in the termination and overflow code.
2592     Examples include the serial remark code and the serial reference
2593     processing closures.
2594 
2595     The value of is_serial must be false when do_marking_step is
2596     being called by any of the worker threads in a work gang.
2597     Examples include the concurrent marking code (CMMarkingTask),
2598     the MT remark code, and the MT reference processing closures.
2599 
2600  *****************************************************************************/
2601 
2602 void G1CMTask::do_marking_step(double time_target_ms,
2603                                bool do_termination,
2604                                bool is_serial) {
2605   assert(time_target_ms >= 1.0, "minimum granularity is 1ms");
2606   assert(concurrent() == _cm->concurrent(), "they should be the same");
2607 
2608   G1Policy* g1_policy = _g1h->g1_policy();
2609   assert(_task_queues != NULL, "invariant");
2610   assert(_task_queue != NULL, "invariant");
2611   assert(_task_queues->queue(_worker_id) == _task_queue, "invariant");
2612 
2613   assert(!_claimed,
2614          "only one thread should claim this task at any one time");
2615 
2616   // OK, this doesn't safeguard again all possible scenarios, as it is
2617   // possible for two threads to set the _claimed flag at the same
2618   // time. But it is only for debugging purposes anyway and it will
2619   // catch most problems.
2620   _claimed = true;
2621 
2622   _start_time_ms = os::elapsedVTime() * 1000.0;
2623 
2624   // If do_stealing is true then do_marking_step will attempt to
2625   // steal work from the other G1CMTasks. It only makes sense to
2626   // enable stealing when the termination protocol is enabled
2627   // and do_marking_step() is not being called serially.
2628   bool do_stealing = do_termination && !is_serial;
2629 
2630   double diff_prediction_ms = _g1h->g1_policy()->predictor().get_new_prediction(&_marking_step_diffs_ms);
2631   _time_target_ms = time_target_ms - diff_prediction_ms;
2632 
2633   // set up the variables that are used in the work-based scheme to
2634   // call the regular clock method
2635   _words_scanned = 0;
2636   _refs_reached  = 0;
2637   recalculate_limits();
2638 
2639   // clear all flags
2640   clear_has_aborted();
2641   _has_timed_out = false;
2642   _draining_satb_buffers = false;
2643 
2644   ++_calls;
2645 
2646   // Set up the bitmap and oop closures. Anything that uses them is
2647   // eventually called from this method, so it is OK to allocate these
2648   // statically.
2649   G1CMBitMapClosure bitmap_closure(this, _cm, _nextMarkBitMap);
2650   G1CMOopClosure    cm_oop_closure(_g1h, _cm, this);
2651   set_cm_oop_closure(&cm_oop_closure);
2652 
2653   if (_cm->has_overflown()) {
2654     // This can happen if the mark stack overflows during a GC pause
2655     // and this task, after a yield point, restarts. We have to abort
2656     // as we need to get into the overflow protocol which happens
2657     // right at the end of this task.
2658     set_has_aborted();
2659   }
2660 
2661   // First drain any available SATB buffers. After this, we will not
2662   // look at SATB buffers before the next invocation of this method.
2663   // If enough completed SATB buffers are queued up, the regular clock
2664   // will abort this task so that it restarts.
2665   drain_satb_buffers();
2666   // ...then partially drain the local queue and the global stack
2667   drain_local_queue(true);
2668   drain_global_stack(true);
2669 
2670   do {
2671     if (!has_aborted() && _curr_region != NULL) {
2672       // This means that we're already holding on to a region.
2673       assert(_finger != NULL, "if region is not NULL, then the finger "
2674              "should not be NULL either");
2675 
2676       // We might have restarted this task after an evacuation pause
2677       // which might have evacuated the region we're holding on to
2678       // underneath our feet. Let's read its limit again to make sure
2679       // that we do not iterate over a region of the heap that
2680       // contains garbage (update_region_limit() will also move
2681       // _finger to the start of the region if it is found empty).
2682       update_region_limit();
2683       // We will start from _finger not from the start of the region,
2684       // as we might be restarting this task after aborting half-way
2685       // through scanning this region. In this case, _finger points to
2686       // the address where we last found a marked object. If this is a
2687       // fresh region, _finger points to start().
2688       MemRegion mr = MemRegion(_finger, _region_limit);
2689 
2690       assert(!_curr_region->is_humongous() || mr.start() == _curr_region->bottom(),
2691              "humongous regions should go around loop once only");
2692 
2693       // Some special cases:
2694       // If the memory region is empty, we can just give up the region.
2695       // If the current region is humongous then we only need to check
2696       // the bitmap for the bit associated with the start of the object,
2697       // scan the object if it's live, and give up the region.
2698       // Otherwise, let's iterate over the bitmap of the part of the region
2699       // that is left.
2700       // If the iteration is successful, give up the region.
2701       if (mr.is_empty()) {
2702         giveup_current_region();
2703         regular_clock_call();
2704       } else if (_curr_region->is_humongous() && mr.start() == _curr_region->bottom()) {
2705         if (_nextMarkBitMap->isMarked(mr.start())) {
2706           // The object is marked - apply the closure
2707           BitMap::idx_t offset = _nextMarkBitMap->heapWordToOffset(mr.start());
2708           bitmap_closure.do_bit(offset);
2709         }
2710         // Even if this task aborted while scanning the humongous object
2711         // we can (and should) give up the current region.
2712         giveup_current_region();
2713         regular_clock_call();
2714       } else if (_nextMarkBitMap->iterate(&bitmap_closure, mr)) {
2715         giveup_current_region();
2716         regular_clock_call();
2717       } else {
2718         assert(has_aborted(), "currently the only way to do so");
2719         // The only way to abort the bitmap iteration is to return
2720         // false from the do_bit() method. However, inside the
2721         // do_bit() method we move the _finger to point to the
2722         // object currently being looked at. So, if we bail out, we
2723         // have definitely set _finger to something non-null.
2724         assert(_finger != NULL, "invariant");
2725 
2726         // Region iteration was actually aborted. So now _finger
2727         // points to the address of the object we last scanned. If we
2728         // leave it there, when we restart this task, we will rescan
2729         // the object. It is easy to avoid this. We move the finger by
2730         // enough to point to the next possible object header (the
2731         // bitmap knows by how much we need to move it as it knows its
2732         // granularity).
2733         assert(_finger < _region_limit, "invariant");
2734         HeapWord* new_finger = _nextMarkBitMap->nextObject(_finger);
2735         // Check if bitmap iteration was aborted while scanning the last object
2736         if (new_finger >= _region_limit) {
2737           giveup_current_region();
2738         } else {
2739           move_finger_to(new_finger);
2740         }
2741       }
2742     }
2743     // At this point we have either completed iterating over the
2744     // region we were holding on to, or we have aborted.
2745 
2746     // We then partially drain the local queue and the global stack.
2747     // (Do we really need this?)
2748     drain_local_queue(true);
2749     drain_global_stack(true);
2750 
2751     // Read the note on the claim_region() method on why it might
2752     // return NULL with potentially more regions available for
2753     // claiming and why we have to check out_of_regions() to determine
2754     // whether we're done or not.
2755     while (!has_aborted() && _curr_region == NULL && !_cm->out_of_regions()) {
2756       // We are going to try to claim a new region. We should have
2757       // given up on the previous one.
2758       // Separated the asserts so that we know which one fires.
2759       assert(_curr_region  == NULL, "invariant");
2760       assert(_finger       == NULL, "invariant");
2761       assert(_region_limit == NULL, "invariant");
2762       HeapRegion* claimed_region = _cm->claim_region(_worker_id);
2763       if (claimed_region != NULL) {
2764         // Yes, we managed to claim one
2765         setup_for_region(claimed_region);
2766         assert(_curr_region == claimed_region, "invariant");
2767       }
2768       // It is important to call the regular clock here. It might take
2769       // a while to claim a region if, for example, we hit a large
2770       // block of empty regions. So we need to call the regular clock
2771       // method once round the loop to make sure it's called
2772       // frequently enough.
2773       regular_clock_call();
2774     }
2775 
2776     if (!has_aborted() && _curr_region == NULL) {
2777       assert(_cm->out_of_regions(),
2778              "at this point we should be out of regions");
2779     }
2780   } while ( _curr_region != NULL && !has_aborted());
2781 
2782   if (!has_aborted()) {
2783     // We cannot check whether the global stack is empty, since other
2784     // tasks might be pushing objects to it concurrently.
2785     assert(_cm->out_of_regions(),
2786            "at this point we should be out of regions");
2787     // Try to reduce the number of available SATB buffers so that
2788     // remark has less work to do.
2789     drain_satb_buffers();
2790   }
2791 
2792   // Since we've done everything else, we can now totally drain the
2793   // local queue and global stack.
2794   drain_local_queue(false);
2795   drain_global_stack(false);
2796 
2797   // Attempt at work stealing from other task's queues.
2798   if (do_stealing && !has_aborted()) {
2799     // We have not aborted. This means that we have finished all that
2800     // we could. Let's try to do some stealing...
2801 
2802     // We cannot check whether the global stack is empty, since other
2803     // tasks might be pushing objects to it concurrently.
2804     assert(_cm->out_of_regions() && _task_queue->size() == 0,
2805            "only way to reach here");
2806     while (!has_aborted()) {
2807       oop obj;
2808       if (_cm->try_stealing(_worker_id, &_hash_seed, obj)) {
2809         assert(_nextMarkBitMap->isMarked((HeapWord*) obj),
2810                "any stolen object should be marked");
2811         scan_object(obj);
2812 
2813         // And since we're towards the end, let's totally drain the
2814         // local queue and global stack.
2815         drain_local_queue(false);
2816         drain_global_stack(false);
2817       } else {
2818         break;
2819       }
2820     }
2821   }
2822 
2823   // We still haven't aborted. Now, let's try to get into the
2824   // termination protocol.
2825   if (do_termination && !has_aborted()) {
2826     // We cannot check whether the global stack is empty, since other
2827     // tasks might be concurrently pushing objects on it.
2828     // Separated the asserts so that we know which one fires.
2829     assert(_cm->out_of_regions(), "only way to reach here");
2830     assert(_task_queue->size() == 0, "only way to reach here");
2831     _termination_start_time_ms = os::elapsedVTime() * 1000.0;
2832 
2833     // The G1CMTask class also extends the TerminatorTerminator class,
2834     // hence its should_exit_termination() method will also decide
2835     // whether to exit the termination protocol or not.
2836     bool finished = (is_serial ||
2837                      _cm->terminator()->offer_termination(this));
2838     double termination_end_time_ms = os::elapsedVTime() * 1000.0;
2839     _termination_time_ms +=
2840       termination_end_time_ms - _termination_start_time_ms;
2841 
2842     if (finished) {
2843       // We're all done.
2844 
2845       if (_worker_id == 0) {
2846         // let's allow task 0 to do this
2847         if (concurrent()) {
2848           assert(_cm->concurrent_marking_in_progress(), "invariant");
2849           // we need to set this to false before the next
2850           // safepoint. This way we ensure that the marking phase
2851           // doesn't observe any more heap expansions.
2852           _cm->clear_concurrent_marking_in_progress();
2853         }
2854       }
2855 
2856       // We can now guarantee that the global stack is empty, since
2857       // all other tasks have finished. We separated the guarantees so
2858       // that, if a condition is false, we can immediately find out
2859       // which one.
2860       guarantee(_cm->out_of_regions(), "only way to reach here");
2861       guarantee(_cm->mark_stack_empty(), "only way to reach here");
2862       guarantee(_task_queue->size() == 0, "only way to reach here");
2863       guarantee(!_cm->has_overflown(), "only way to reach here");
2864       guarantee(!_cm->mark_stack_overflow(), "only way to reach here");
2865     } else {
2866       // Apparently there's more work to do. Let's abort this task. It
2867       // will restart it and we can hopefully find more things to do.
2868       set_has_aborted();
2869     }
2870   }
2871 
2872   // Mainly for debugging purposes to make sure that a pointer to the
2873   // closure which was statically allocated in this frame doesn't
2874   // escape it by accident.
2875   set_cm_oop_closure(NULL);
2876   double end_time_ms = os::elapsedVTime() * 1000.0;
2877   double elapsed_time_ms = end_time_ms - _start_time_ms;
2878   // Update the step history.
2879   _step_times_ms.add(elapsed_time_ms);
2880 
2881   if (has_aborted()) {
2882     // The task was aborted for some reason.
2883     if (_has_timed_out) {
2884       double diff_ms = elapsed_time_ms - _time_target_ms;
2885       // Keep statistics of how well we did with respect to hitting
2886       // our target only if we actually timed out (if we aborted for
2887       // other reasons, then the results might get skewed).
2888       _marking_step_diffs_ms.add(diff_ms);
2889     }
2890 
2891     if (_cm->has_overflown()) {
2892       // This is the interesting one. We aborted because a global
2893       // overflow was raised. This means we have to restart the
2894       // marking phase and start iterating over regions. However, in
2895       // order to do this we have to make sure that all tasks stop
2896       // what they are doing and re-initialize in a safe manner. We
2897       // will achieve this with the use of two barrier sync points.
2898 
2899       if (!is_serial) {
2900         // We only need to enter the sync barrier if being called
2901         // from a parallel context
2902         _cm->enter_first_sync_barrier(_worker_id);
2903 
2904         // When we exit this sync barrier we know that all tasks have
2905         // stopped doing marking work. So, it's now safe to
2906         // re-initialize our data structures. At the end of this method,
2907         // task 0 will clear the global data structures.
2908       }
2909 
2910       // We clear the local state of this task...
2911       clear_region_fields();
2912 
2913       if (!is_serial) {
2914         // ...and enter the second barrier.
2915         _cm->enter_second_sync_barrier(_worker_id);
2916       }
2917       // At this point, if we're during the concurrent phase of
2918       // marking, everything has been re-initialized and we're
2919       // ready to restart.
2920     }
2921   }
2922 
2923   _claimed = false;
2924 }
2925 
2926 G1CMTask::G1CMTask(uint worker_id,
2927                    G1ConcurrentMark* cm,
2928                    G1CMTaskQueue* task_queue,
2929                    G1CMTaskQueueSet* task_queues)
2930   : _g1h(G1CollectedHeap::heap()),
2931     _worker_id(worker_id), _cm(cm),
2932     _claimed(false),
2933     _nextMarkBitMap(NULL), _hash_seed(17),
2934     _task_queue(task_queue),
2935     _task_queues(task_queues),
2936     _cm_oop_closure(NULL) {
2937   guarantee(task_queue != NULL, "invariant");
2938   guarantee(task_queues != NULL, "invariant");
2939 
2940   _marking_step_diffs_ms.add(0.5);
2941 }
2942 
2943 // These are formatting macros that are used below to ensure
2944 // consistent formatting. The *_H_* versions are used to format the
2945 // header for a particular value and they should be kept consistent
2946 // with the corresponding macro. Also note that most of the macros add
2947 // the necessary white space (as a prefix) which makes them a bit
2948 // easier to compose.
2949 
2950 // All the output lines are prefixed with this string to be able to
2951 // identify them easily in a large log file.
2952 #define G1PPRL_LINE_PREFIX            "###"
2953 
2954 #define G1PPRL_ADDR_BASE_FORMAT    " " PTR_FORMAT "-" PTR_FORMAT
2955 #ifdef _LP64
2956 #define G1PPRL_ADDR_BASE_H_FORMAT  " %37s"
2957 #else // _LP64
2958 #define G1PPRL_ADDR_BASE_H_FORMAT  " %21s"
2959 #endif // _LP64
2960 
2961 // For per-region info
2962 #define G1PPRL_TYPE_FORMAT            "   %-4s"
2963 #define G1PPRL_TYPE_H_FORMAT          "   %4s"
2964 #define G1PPRL_BYTE_FORMAT            "  " SIZE_FORMAT_W(9)
2965 #define G1PPRL_BYTE_H_FORMAT          "  %9s"
2966 #define G1PPRL_DOUBLE_FORMAT          "  %14.1f"
2967 #define G1PPRL_DOUBLE_H_FORMAT        "  %14s"
2968 
2969 // For summary info
2970 #define G1PPRL_SUM_ADDR_FORMAT(tag)    "  " tag ":" G1PPRL_ADDR_BASE_FORMAT
2971 #define G1PPRL_SUM_BYTE_FORMAT(tag)    "  " tag ": " SIZE_FORMAT
2972 #define G1PPRL_SUM_MB_FORMAT(tag)      "  " tag ": %1.2f MB"
2973 #define G1PPRL_SUM_MB_PERC_FORMAT(tag) G1PPRL_SUM_MB_FORMAT(tag) " / %1.2f %%"
2974 
2975 G1PrintRegionLivenessInfoClosure::
2976 G1PrintRegionLivenessInfoClosure(const char* phase_name)
2977   : _total_used_bytes(0), _total_capacity_bytes(0),
2978     _total_prev_live_bytes(0), _total_next_live_bytes(0),
2979     _total_remset_bytes(0), _total_strong_code_roots_bytes(0) {
2980   G1CollectedHeap* g1h = G1CollectedHeap::heap();
2981   MemRegion g1_reserved = g1h->g1_reserved();
2982   double now = os::elapsedTime();
2983 
2984   // Print the header of the output.
2985   log_trace(gc, liveness)(G1PPRL_LINE_PREFIX" PHASE %s @ %1.3f", phase_name, now);
2986   log_trace(gc, liveness)(G1PPRL_LINE_PREFIX" HEAP"
2987                           G1PPRL_SUM_ADDR_FORMAT("reserved")
2988                           G1PPRL_SUM_BYTE_FORMAT("region-size"),
2989                           p2i(g1_reserved.start()), p2i(g1_reserved.end()),
2990                           HeapRegion::GrainBytes);
2991   log_trace(gc, liveness)(G1PPRL_LINE_PREFIX);
2992   log_trace(gc, liveness)(G1PPRL_LINE_PREFIX
2993                           G1PPRL_TYPE_H_FORMAT
2994                           G1PPRL_ADDR_BASE_H_FORMAT
2995                           G1PPRL_BYTE_H_FORMAT
2996                           G1PPRL_BYTE_H_FORMAT
2997                           G1PPRL_BYTE_H_FORMAT
2998                           G1PPRL_DOUBLE_H_FORMAT
2999                           G1PPRL_BYTE_H_FORMAT
3000                           G1PPRL_BYTE_H_FORMAT,
3001                           "type", "address-range",
3002                           "used", "prev-live", "next-live", "gc-eff",
3003                           "remset", "code-roots");
3004   log_trace(gc, liveness)(G1PPRL_LINE_PREFIX
3005                           G1PPRL_TYPE_H_FORMAT
3006                           G1PPRL_ADDR_BASE_H_FORMAT
3007                           G1PPRL_BYTE_H_FORMAT
3008                           G1PPRL_BYTE_H_FORMAT
3009                           G1PPRL_BYTE_H_FORMAT
3010                           G1PPRL_DOUBLE_H_FORMAT
3011                           G1PPRL_BYTE_H_FORMAT
3012                           G1PPRL_BYTE_H_FORMAT,
3013                           "", "",
3014                           "(bytes)", "(bytes)", "(bytes)", "(bytes/ms)",
3015                           "(bytes)", "(bytes)");
3016 }
3017 
3018 bool G1PrintRegionLivenessInfoClosure::doHeapRegion(HeapRegion* r) {
3019   const char* type       = r->get_type_str();
3020   HeapWord* bottom       = r->bottom();
3021   HeapWord* end          = r->end();
3022   size_t capacity_bytes  = r->capacity();
3023   size_t used_bytes      = r->used();
3024   size_t prev_live_bytes = r->live_bytes();
3025   size_t next_live_bytes = r->next_live_bytes();
3026   double gc_eff          = r->gc_efficiency();
3027   size_t remset_bytes    = r->rem_set()->mem_size();
3028   size_t strong_code_roots_bytes = r->rem_set()->strong_code_roots_mem_size();
3029 
3030   _total_used_bytes      += used_bytes;
3031   _total_capacity_bytes  += capacity_bytes;
3032   _total_prev_live_bytes += prev_live_bytes;
3033   _total_next_live_bytes += next_live_bytes;
3034   _total_remset_bytes    += remset_bytes;
3035   _total_strong_code_roots_bytes += strong_code_roots_bytes;
3036 
3037   // Print a line for this particular region.
3038   log_trace(gc, liveness)(G1PPRL_LINE_PREFIX
3039                           G1PPRL_TYPE_FORMAT
3040                           G1PPRL_ADDR_BASE_FORMAT
3041                           G1PPRL_BYTE_FORMAT
3042                           G1PPRL_BYTE_FORMAT
3043                           G1PPRL_BYTE_FORMAT
3044                           G1PPRL_DOUBLE_FORMAT
3045                           G1PPRL_BYTE_FORMAT
3046                           G1PPRL_BYTE_FORMAT,
3047                           type, p2i(bottom), p2i(end),
3048                           used_bytes, prev_live_bytes, next_live_bytes, gc_eff,
3049                           remset_bytes, strong_code_roots_bytes);
3050 
3051   return false;
3052 }
3053 
3054 G1PrintRegionLivenessInfoClosure::~G1PrintRegionLivenessInfoClosure() {
3055   // add static memory usages to remembered set sizes
3056   _total_remset_bytes += HeapRegionRemSet::fl_mem_size() + HeapRegionRemSet::static_mem_size();
3057   // Print the footer of the output.
3058   log_trace(gc, liveness)(G1PPRL_LINE_PREFIX);
3059   log_trace(gc, liveness)(G1PPRL_LINE_PREFIX
3060                          " SUMMARY"
3061                          G1PPRL_SUM_MB_FORMAT("capacity")
3062                          G1PPRL_SUM_MB_PERC_FORMAT("used")
3063                          G1PPRL_SUM_MB_PERC_FORMAT("prev-live")
3064                          G1PPRL_SUM_MB_PERC_FORMAT("next-live")
3065                          G1PPRL_SUM_MB_FORMAT("remset")
3066                          G1PPRL_SUM_MB_FORMAT("code-roots"),
3067                          bytes_to_mb(_total_capacity_bytes),
3068                          bytes_to_mb(_total_used_bytes),
3069                          perc(_total_used_bytes, _total_capacity_bytes),
3070                          bytes_to_mb(_total_prev_live_bytes),
3071                          perc(_total_prev_live_bytes, _total_capacity_bytes),
3072                          bytes_to_mb(_total_next_live_bytes),
3073                          perc(_total_next_live_bytes, _total_capacity_bytes),
3074                          bytes_to_mb(_total_remset_bytes),
3075                          bytes_to_mb(_total_strong_code_roots_bytes));
3076 }