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