1 /*
   2  * Copyright (c) 2001, 2021, 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/classLoaderDataGraph.hpp"
  27 #include "classfile/metadataOnStackMark.hpp"
  28 #include "classfile/stringTable.hpp"
  29 #include "code/codeCache.hpp"
  30 #include "code/icBuffer.hpp"
  31 #include "compiler/oopMap.hpp"
  32 #include "gc/g1/g1Allocator.inline.hpp"
  33 #include "gc/g1/g1Arguments.hpp"
  34 #include "gc/g1/g1BarrierSet.hpp"
  35 #include "gc/g1/g1CollectedHeap.inline.hpp"
  36 #include "gc/g1/g1CollectionSet.hpp"
  37 #include "gc/g1/g1CollectorState.hpp"
  38 #include "gc/g1/g1ConcurrentRefine.hpp"
  39 #include "gc/g1/g1ConcurrentRefineThread.hpp"
  40 #include "gc/g1/g1ConcurrentMarkThread.inline.hpp"
  41 #include "gc/g1/g1DirtyCardQueue.hpp"
  42 #include "gc/g1/g1EvacStats.inline.hpp"
  43 #include "gc/g1/g1FullCollector.hpp"
  44 #include "gc/g1/g1GCParPhaseTimesTracker.hpp"
  45 #include "gc/g1/g1GCPhaseTimes.hpp"
  46 #include "gc/g1/g1GCPauseType.hpp"
  47 #include "gc/g1/g1HeapSizingPolicy.hpp"
  48 #include "gc/g1/g1HeapTransition.hpp"
  49 #include "gc/g1/g1HeapVerifier.hpp"
  50 #include "gc/g1/g1HotCardCache.hpp"
  51 #include "gc/g1/g1InitLogger.hpp"
  52 #include "gc/g1/g1MemoryPool.hpp"
  53 #include "gc/g1/g1OopClosures.inline.hpp"
  54 #include "gc/g1/g1ParallelCleaning.hpp"
  55 #include "gc/g1/g1ParScanThreadState.inline.hpp"
  56 #include "gc/g1/g1PeriodicGCTask.hpp"
  57 #include "gc/g1/g1Policy.hpp"
  58 #include "gc/g1/g1RedirtyCardsQueue.hpp"
  59 #include "gc/g1/g1RegionToSpaceMapper.hpp"
  60 #include "gc/g1/g1RemSet.hpp"
  61 #include "gc/g1/g1RootClosures.hpp"
  62 #include "gc/g1/g1RootProcessor.hpp"
  63 #include "gc/g1/g1SATBMarkQueueSet.hpp"
  64 #include "gc/g1/g1ThreadLocalData.hpp"
  65 #include "gc/g1/g1Trace.hpp"
  66 #include "gc/g1/g1ServiceThread.hpp"
  67 #include "gc/g1/g1UncommitRegionTask.hpp"
  68 #include "gc/g1/g1VMOperations.hpp"
  69 #include "gc/g1/g1YoungGCPostEvacuateTasks.hpp"
  70 #include "gc/g1/heapRegion.inline.hpp"
  71 #include "gc/g1/heapRegionRemSet.hpp"
  72 #include "gc/g1/heapRegionSet.inline.hpp"
  73 #include "gc/shared/concurrentGCBreakpoints.hpp"
  74 #include "gc/shared/gcBehaviours.hpp"
  75 #include "gc/shared/gcHeapSummary.hpp"
  76 #include "gc/shared/gcId.hpp"
  77 #include "gc/shared/gcLocker.hpp"
  78 #include "gc/shared/gcTimer.hpp"
  79 #include "gc/shared/gcTraceTime.inline.hpp"
  80 #include "gc/shared/generationSpec.hpp"
  81 #include "gc/shared/isGCActiveMark.hpp"
  82 #include "gc/shared/locationPrinter.inline.hpp"
  83 #include "gc/shared/oopStorageParState.hpp"
  84 #include "gc/shared/preservedMarks.inline.hpp"
  85 #include "gc/shared/suspendibleThreadSet.hpp"
  86 #include "gc/shared/referenceProcessor.inline.hpp"
  87 #include "gc/shared/taskTerminator.hpp"
  88 #include "gc/shared/taskqueue.inline.hpp"
  89 #include "gc/shared/tlab_globals.hpp"
  90 #include "gc/shared/weakProcessor.inline.hpp"
  91 #include "gc/shared/workerPolicy.hpp"
  92 #include "logging/log.hpp"
  93 #include "memory/allocation.hpp"
  94 #include "memory/iterator.hpp"
  95 #include "memory/heapInspection.hpp"
  96 #include "memory/metaspaceUtils.hpp"
  97 #include "memory/resourceArea.hpp"
  98 #include "memory/universe.hpp"
  99 #include "oops/access.inline.hpp"
 100 #include "oops/compressedOops.inline.hpp"
 101 #include "oops/oop.inline.hpp"
 102 #include "runtime/atomic.hpp"
 103 #include "runtime/handles.inline.hpp"
 104 #include "runtime/init.hpp"
 105 #include "runtime/java.hpp"
 106 #include "runtime/orderAccess.hpp"
 107 #include "runtime/threadSMR.hpp"
 108 #include "runtime/vmThread.hpp"
 109 #include "utilities/align.hpp"
 110 #include "utilities/autoRestore.hpp"
 111 #include "utilities/bitMap.inline.hpp"
 112 #include "utilities/globalDefinitions.hpp"
 113 #include "utilities/stack.inline.hpp"
 114 
 115 size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
 116 
 117 // INVARIANTS/NOTES
 118 //
 119 // All allocation activity covered by the G1CollectedHeap interface is
 120 // serialized by acquiring the HeapLock.  This happens in mem_allocate
 121 // and allocate_new_tlab, which are the "entry" points to the
 122 // allocation code from the rest of the JVM.  (Note that this does not
 123 // apply to TLAB allocation, which is not part of this interface: it
 124 // is done by clients of this interface.)
 125 
 126 void G1RegionMappingChangedListener::reset_from_card_cache(uint start_idx, size_t num_regions) {
 127   HeapRegionRemSet::invalidate_from_card_cache(start_idx, num_regions);
 128 }
 129 
 130 void G1RegionMappingChangedListener::on_commit(uint start_idx, size_t num_regions, bool zero_filled) {
 131   // The from card cache is not the memory that is actually committed. So we cannot
 132   // take advantage of the zero_filled parameter.
 133   reset_from_card_cache(start_idx, num_regions);
 134 }
 135 
 136 Tickspan G1CollectedHeap::run_task_timed(AbstractGangTask* task) {
 137   Ticks start = Ticks::now();
 138   workers()->run_task(task);
 139   return Ticks::now() - start;
 140 }
 141 
 142 void G1CollectedHeap::run_batch_task(G1BatchedGangTask* cl) {
 143   uint num_workers = MAX2(1u, MIN2(cl->num_workers_estimate(), workers()->active_workers()));
 144   cl->set_max_workers(num_workers);
 145   workers()->run_task(cl, num_workers);
 146 }
 147 
 148 HeapRegion* G1CollectedHeap::new_heap_region(uint hrs_index,
 149                                              MemRegion mr) {
 150   return new HeapRegion(hrs_index, bot(), mr);
 151 }
 152 
 153 // Private methods.
 154 
 155 HeapRegion* G1CollectedHeap::new_region(size_t word_size,
 156                                         HeapRegionType type,
 157                                         bool do_expand,
 158                                         uint node_index) {
 159   assert(!is_humongous(word_size) || word_size <= HeapRegion::GrainWords,
 160          "the only time we use this to allocate a humongous region is "
 161          "when we are allocating a single humongous region");
 162 
 163   HeapRegion* res = _hrm.allocate_free_region(type, node_index);
 164 
 165   if (res == NULL && do_expand && _expand_heap_after_alloc_failure) {
 166     // Currently, only attempts to allocate GC alloc regions set
 167     // do_expand to true. So, we should only reach here during a
 168     // safepoint. If this assumption changes we might have to
 169     // reconsider the use of _expand_heap_after_alloc_failure.
 170     assert(SafepointSynchronize::is_at_safepoint(), "invariant");
 171 
 172     log_debug(gc, ergo, heap)("Attempt heap expansion (region allocation request failed). Allocation request: " SIZE_FORMAT "B",
 173                               word_size * HeapWordSize);
 174 
 175     assert(word_size * HeapWordSize < HeapRegion::GrainBytes,
 176            "This kind of expansion should never be more than one region. Size: " SIZE_FORMAT,
 177            word_size * HeapWordSize);
 178     if (expand_single_region(node_index)) {
 179       // Given that expand_single_region() succeeded in expanding the heap, and we
 180       // always expand the heap by an amount aligned to the heap
 181       // region size, the free list should in theory not be empty.
 182       // In either case allocate_free_region() will check for NULL.
 183       res = _hrm.allocate_free_region(type, node_index);
 184     } else {
 185       _expand_heap_after_alloc_failure = false;
 186     }
 187   }
 188   return res;
 189 }
 190 
 191 HeapWord*
 192 G1CollectedHeap::humongous_obj_allocate_initialize_regions(HeapRegion* first_hr,
 193                                                            uint num_regions,
 194                                                            size_t word_size) {
 195   assert(first_hr != NULL, "pre-condition");
 196   assert(is_humongous(word_size), "word_size should be humongous");
 197   assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");
 198 
 199   // Index of last region in the series.
 200   uint first = first_hr->hrm_index();
 201   uint last = first + num_regions - 1;
 202 
 203   // We need to initialize the region(s) we just discovered. This is
 204   // a bit tricky given that it can happen concurrently with
 205   // refinement threads refining cards on these regions and
 206   // potentially wanting to refine the BOT as they are scanning
 207   // those cards (this can happen shortly after a cleanup; see CR
 208   // 6991377). So we have to set up the region(s) carefully and in
 209   // a specific order.
 210 
 211   // The word size sum of all the regions we will allocate.
 212   size_t word_size_sum = (size_t) num_regions * HeapRegion::GrainWords;
 213   assert(word_size <= word_size_sum, "sanity");
 214 
 215   // The passed in hr will be the "starts humongous" region. The header
 216   // of the new object will be placed at the bottom of this region.
 217   HeapWord* new_obj = first_hr->bottom();
 218   // This will be the new top of the new object.
 219   HeapWord* obj_top = new_obj + word_size;
 220 
 221   // First, we need to zero the header of the space that we will be
 222   // allocating. When we update top further down, some refinement
 223   // threads might try to scan the region. By zeroing the header we
 224   // ensure that any thread that will try to scan the region will
 225   // come across the zero klass word and bail out.
 226   //
 227   // NOTE: It would not have been correct to have used
 228   // CollectedHeap::fill_with_object() and make the space look like
 229   // an int array. The thread that is doing the allocation will
 230   // later update the object header to a potentially different array
 231   // type and, for a very short period of time, the klass and length
 232   // fields will be inconsistent. This could cause a refinement
 233   // thread to calculate the object size incorrectly.
 234   Copy::fill_to_words(new_obj, oopDesc::header_size(), 0);
 235 
 236   // Next, pad out the unused tail of the last region with filler
 237   // objects, for improved usage accounting.
 238   // How many words we use for filler objects.
 239   size_t word_fill_size = word_size_sum - word_size;
 240 
 241   // How many words memory we "waste" which cannot hold a filler object.
 242   size_t words_not_fillable = 0;
 243 
 244   if (word_fill_size >= min_fill_size()) {
 245     fill_with_objects(obj_top, word_fill_size);
 246   } else if (word_fill_size > 0) {
 247     // We have space to fill, but we cannot fit an object there.
 248     words_not_fillable = word_fill_size;
 249     word_fill_size = 0;
 250   }
 251 
 252   // We will set up the first region as "starts humongous". This
 253   // will also update the BOT covering all the regions to reflect
 254   // that there is a single object that starts at the bottom of the
 255   // first region.
 256   first_hr->set_starts_humongous(obj_top, word_fill_size);
 257   _policy->remset_tracker()->update_at_allocate(first_hr);
 258   // Then, if there are any, we will set up the "continues
 259   // humongous" regions.
 260   HeapRegion* hr = NULL;
 261   for (uint i = first + 1; i <= last; ++i) {
 262     hr = region_at(i);
 263     hr->set_continues_humongous(first_hr);
 264     _policy->remset_tracker()->update_at_allocate(hr);
 265   }
 266 
 267   // Up to this point no concurrent thread would have been able to
 268   // do any scanning on any region in this series. All the top
 269   // fields still point to bottom, so the intersection between
 270   // [bottom,top] and [card_start,card_end] will be empty. Before we
 271   // update the top fields, we'll do a storestore to make sure that
 272   // no thread sees the update to top before the zeroing of the
 273   // object header and the BOT initialization.
 274   OrderAccess::storestore();
 275 
 276   // Now, we will update the top fields of the "continues humongous"
 277   // regions except the last one.
 278   for (uint i = first; i < last; ++i) {
 279     hr = region_at(i);
 280     hr->set_top(hr->end());
 281   }
 282 
 283   hr = region_at(last);
 284   // If we cannot fit a filler object, we must set top to the end
 285   // of the humongous object, otherwise we cannot iterate the heap
 286   // and the BOT will not be complete.
 287   hr->set_top(hr->end() - words_not_fillable);
 288 
 289   assert(hr->bottom() < obj_top && obj_top <= hr->end(),
 290          "obj_top should be in last region");
 291 
 292   _verifier->check_bitmaps("Humongous Region Allocation", first_hr);
 293 
 294   assert(words_not_fillable == 0 ||
 295          first_hr->bottom() + word_size_sum - words_not_fillable == hr->top(),
 296          "Miscalculation in humongous allocation");
 297 
 298   increase_used((word_size_sum - words_not_fillable) * HeapWordSize);
 299 
 300   for (uint i = first; i <= last; ++i) {
 301     hr = region_at(i);
 302     _humongous_set.add(hr);
 303     _hr_printer.alloc(hr);
 304   }
 305 
 306   return new_obj;
 307 }
 308 
 309 size_t G1CollectedHeap::humongous_obj_size_in_regions(size_t word_size) {
 310   assert(is_humongous(word_size), "Object of size " SIZE_FORMAT " must be humongous here", word_size);
 311   return align_up(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords;
 312 }
 313 
 314 // If could fit into free regions w/o expansion, try.
 315 // Otherwise, if can expand, do so.
 316 // Otherwise, if using ex regions might help, try with ex given back.
 317 HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size) {
 318   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
 319 
 320   _verifier->verify_region_sets_optional();
 321 
 322   uint obj_regions = (uint) humongous_obj_size_in_regions(word_size);
 323 
 324   // Policy: First try to allocate a humongous object in the free list.
 325   HeapRegion* humongous_start = _hrm.allocate_humongous(obj_regions);
 326   if (humongous_start == NULL) {
 327     // Policy: We could not find enough regions for the humongous object in the
 328     // free list. Look through the heap to find a mix of free and uncommitted regions.
 329     // If so, expand the heap and allocate the humongous object.
 330     humongous_start = _hrm.expand_and_allocate_humongous(obj_regions);
 331     if (humongous_start != NULL) {
 332       // We managed to find a region by expanding the heap.
 333       log_debug(gc, ergo, heap)("Heap expansion (humongous allocation request). Allocation request: " SIZE_FORMAT "B",
 334                                 word_size * HeapWordSize);
 335       policy()->record_new_heap_size(num_regions());
 336     } else {
 337       // Policy: Potentially trigger a defragmentation GC.
 338     }
 339   }
 340 
 341   HeapWord* result = NULL;
 342   if (humongous_start != NULL) {
 343     result = humongous_obj_allocate_initialize_regions(humongous_start, obj_regions, word_size);
 344     assert(result != NULL, "it should always return a valid result");
 345 
 346     // A successful humongous object allocation changes the used space
 347     // information of the old generation so we need to recalculate the
 348     // sizes and update the jstat counters here.
 349     g1mm()->update_sizes();
 350   }
 351 
 352   _verifier->verify_region_sets_optional();
 353 
 354   return result;
 355 }
 356 
 357 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t min_size,
 358                                              size_t requested_size,
 359                                              size_t* actual_size) {
 360   assert_heap_not_locked_and_not_at_safepoint();
 361   assert(!is_humongous(requested_size), "we do not allow humongous TLABs");
 362 
 363   return attempt_allocation(min_size, requested_size, actual_size);
 364 }
 365 
 366 HeapWord*
 367 G1CollectedHeap::mem_allocate(size_t word_size,
 368                               bool*  gc_overhead_limit_was_exceeded) {
 369   assert_heap_not_locked_and_not_at_safepoint();
 370 
 371   if (is_humongous(word_size)) {
 372     return attempt_allocation_humongous(word_size);
 373   }
 374   size_t dummy = 0;
 375   return attempt_allocation(word_size, word_size, &dummy);
 376 }
 377 
 378 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size) {
 379   ResourceMark rm; // For retrieving the thread names in log messages.
 380 
 381   // Make sure you read the note in attempt_allocation_humongous().
 382 
 383   assert_heap_not_locked_and_not_at_safepoint();
 384   assert(!is_humongous(word_size), "attempt_allocation_slow() should not "
 385          "be called for humongous allocation requests");
 386 
 387   // We should only get here after the first-level allocation attempt
 388   // (attempt_allocation()) failed to allocate.
 389 
 390   // We will loop until a) we manage to successfully perform the
 391   // allocation or b) we successfully schedule a collection which
 392   // fails to perform the allocation. b) is the only case when we'll
 393   // return NULL.
 394   HeapWord* result = NULL;
 395   for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
 396     bool should_try_gc;
 397     bool preventive_collection_required = false;
 398     uint gc_count_before;
 399 
 400     {
 401       MutexLocker x(Heap_lock);
 402 
 403       // Now that we have the lock, we first retry the allocation in case another
 404       // thread changed the region while we were waiting to acquire the lock.
 405       size_t actual_size;
 406       result = _allocator->attempt_allocation(word_size, word_size, &actual_size);
 407       if (result != NULL) {
 408         return result;
 409       }
 410 
 411       preventive_collection_required = policy()->preventive_collection_required(1);
 412       if (!preventive_collection_required) {
 413         // We've already attempted a lock-free allocation above, so we don't want to
 414         // do it again. Let's jump straight to replacing the active region.
 415         result = _allocator->attempt_allocation_using_new_region(word_size);
 416         if (result != NULL) {
 417           return result;
 418         }
 419 
 420         // If the GCLocker is active and we are bound for a GC, try expanding young gen.
 421         // This is different to when only GCLocker::needs_gc() is set: try to avoid
 422         // waiting because the GCLocker is active to not wait too long.
 423         if (GCLocker::is_active_and_needs_gc() && policy()->can_expand_young_list()) {
 424           // No need for an ergo message here, can_expand_young_list() does this when
 425           // it returns true.
 426           result = _allocator->attempt_allocation_force(word_size);
 427           if (result != NULL) {
 428             return result;
 429           }
 430         }
 431       }
 432 
 433       // Only try a GC if the GCLocker does not signal the need for a GC. Wait until
 434       // the GCLocker initiated GC has been performed and then retry. This includes
 435       // the case when the GC Locker is not active but has not been performed.
 436       should_try_gc = !GCLocker::needs_gc();
 437       // Read the GC count while still holding the Heap_lock.
 438       gc_count_before = total_collections();
 439     }
 440 
 441     if (should_try_gc) {
 442       GCCause::Cause gc_cause = preventive_collection_required ? GCCause::_g1_preventive_collection
 443                                                               : GCCause::_g1_inc_collection_pause;
 444       bool succeeded;
 445       result = do_collection_pause(word_size, gc_count_before, &succeeded, gc_cause);
 446       if (result != NULL) {
 447         assert(succeeded, "only way to get back a non-NULL result");
 448         log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,
 449                              Thread::current()->name(), p2i(result));
 450         return result;
 451       }
 452 
 453       if (succeeded) {
 454         // We successfully scheduled a collection which failed to allocate. No
 455         // point in trying to allocate further. We'll just return NULL.
 456         log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "
 457                              SIZE_FORMAT " words", Thread::current()->name(), word_size);
 458         return NULL;
 459       }
 460       log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT " words",
 461                            Thread::current()->name(), word_size);
 462     } else {
 463       // Failed to schedule a collection.
 464       if (gclocker_retry_count > GCLockerRetryAllocationCount) {
 465         log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "
 466                                SIZE_FORMAT " words", Thread::current()->name(), word_size);
 467         return NULL;
 468       }
 469       log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());
 470       // The GCLocker is either active or the GCLocker initiated
 471       // GC has not yet been performed. Stall until it is and
 472       // then retry the allocation.
 473       GCLocker::stall_until_clear();
 474       gclocker_retry_count += 1;
 475     }
 476 
 477     // We can reach here if we were unsuccessful in scheduling a
 478     // collection (because another thread beat us to it) or if we were
 479     // stalled due to the GC locker. In either can we should retry the
 480     // allocation attempt in case another thread successfully
 481     // performed a collection and reclaimed enough space. We do the
 482     // first attempt (without holding the Heap_lock) here and the
 483     // follow-on attempt will be at the start of the next loop
 484     // iteration (after taking the Heap_lock).
 485     size_t dummy = 0;
 486     result = _allocator->attempt_allocation(word_size, word_size, &dummy);
 487     if (result != NULL) {
 488       return result;
 489     }
 490 
 491     // Give a warning if we seem to be looping forever.
 492     if ((QueuedAllocationWarningCount > 0) &&
 493         (try_count % QueuedAllocationWarningCount == 0)) {
 494       log_warning(gc, alloc)("%s:  Retried allocation %u times for " SIZE_FORMAT " words",
 495                              Thread::current()->name(), try_count, word_size);
 496     }
 497   }
 498 
 499   ShouldNotReachHere();
 500   return NULL;
 501 }
 502 
 503 void G1CollectedHeap::begin_archive_alloc_range(bool open) {
 504   assert_at_safepoint_on_vm_thread();
 505   if (_archive_allocator == NULL) {
 506     _archive_allocator = G1ArchiveAllocator::create_allocator(this, open);
 507   }
 508 }
 509 
 510 bool G1CollectedHeap::is_archive_alloc_too_large(size_t word_size) {
 511   // Allocations in archive regions cannot be of a size that would be considered
 512   // humongous even for a minimum-sized region, because G1 region sizes/boundaries
 513   // may be different at archive-restore time.
 514   return word_size >= humongous_threshold_for(HeapRegion::min_region_size_in_words());
 515 }
 516 
 517 HeapWord* G1CollectedHeap::archive_mem_allocate(size_t word_size) {
 518   assert_at_safepoint_on_vm_thread();
 519   assert(_archive_allocator != NULL, "_archive_allocator not initialized");
 520   if (is_archive_alloc_too_large(word_size)) {
 521     return NULL;
 522   }
 523   return _archive_allocator->archive_mem_allocate(word_size);
 524 }
 525 
 526 void G1CollectedHeap::end_archive_alloc_range(GrowableArray<MemRegion>* ranges,
 527                                               size_t end_alignment_in_bytes) {
 528   assert_at_safepoint_on_vm_thread();
 529   assert(_archive_allocator != NULL, "_archive_allocator not initialized");
 530 
 531   // Call complete_archive to do the real work, filling in the MemRegion
 532   // array with the archive regions.
 533   _archive_allocator->complete_archive(ranges, end_alignment_in_bytes);
 534   delete _archive_allocator;
 535   _archive_allocator = NULL;
 536 }
 537 
 538 bool G1CollectedHeap::check_archive_addresses(MemRegion* ranges, size_t count) {
 539   assert(ranges != NULL, "MemRegion array NULL");
 540   assert(count != 0, "No MemRegions provided");
 541   MemRegion reserved = _hrm.reserved();
 542   for (size_t i = 0; i < count; i++) {
 543     if (!reserved.contains(ranges[i].start()) || !reserved.contains(ranges[i].last())) {
 544       return false;
 545     }
 546   }
 547   return true;
 548 }
 549 
 550 bool G1CollectedHeap::alloc_archive_regions(MemRegion* ranges,
 551                                             size_t count,
 552                                             bool open) {
 553   assert(!is_init_completed(), "Expect to be called at JVM init time");
 554   assert(ranges != NULL, "MemRegion array NULL");
 555   assert(count != 0, "No MemRegions provided");
 556   MutexLocker x(Heap_lock);
 557 
 558   MemRegion reserved = _hrm.reserved();
 559   HeapWord* prev_last_addr = NULL;
 560   HeapRegion* prev_last_region = NULL;
 561 
 562   // Temporarily disable pretouching of heap pages. This interface is used
 563   // when mmap'ing archived heap data in, so pre-touching is wasted.
 564   FlagSetting fs(AlwaysPreTouch, false);
 565 
 566   // For each specified MemRegion range, allocate the corresponding G1
 567   // regions and mark them as archive regions. We expect the ranges
 568   // in ascending starting address order, without overlap.
 569   for (size_t i = 0; i < count; i++) {
 570     MemRegion curr_range = ranges[i];
 571     HeapWord* start_address = curr_range.start();
 572     size_t word_size = curr_range.word_size();
 573     HeapWord* last_address = curr_range.last();
 574     size_t commits = 0;
 575 
 576     guarantee(reserved.contains(start_address) && reserved.contains(last_address),
 577               "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
 578               p2i(start_address), p2i(last_address));
 579     guarantee(start_address > prev_last_addr,
 580               "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
 581               p2i(start_address), p2i(prev_last_addr));
 582     prev_last_addr = last_address;
 583 
 584     // Check for ranges that start in the same G1 region in which the previous
 585     // range ended, and adjust the start address so we don't try to allocate
 586     // the same region again. If the current range is entirely within that
 587     // region, skip it, just adjusting the recorded top.
 588     HeapRegion* start_region = _hrm.addr_to_region(start_address);
 589     if ((prev_last_region != NULL) && (start_region == prev_last_region)) {
 590       start_address = start_region->end();
 591       if (start_address > last_address) {
 592         increase_used(word_size * HeapWordSize);
 593         start_region->set_top(last_address + 1);
 594         continue;
 595       }
 596       start_region->set_top(start_address);
 597       curr_range = MemRegion(start_address, last_address + 1);
 598       start_region = _hrm.addr_to_region(start_address);
 599     }
 600 
 601     // Perform the actual region allocation, exiting if it fails.
 602     // Then note how much new space we have allocated.
 603     if (!_hrm.allocate_containing_regions(curr_range, &commits, workers())) {
 604       return false;
 605     }
 606     increase_used(word_size * HeapWordSize);
 607     if (commits != 0) {
 608       log_debug(gc, ergo, heap)("Attempt heap expansion (allocate archive regions). Total size: " SIZE_FORMAT "B",
 609                                 HeapRegion::GrainWords * HeapWordSize * commits);
 610 
 611     }
 612 
 613     // Mark each G1 region touched by the range as archive, add it to
 614     // the old set, and set top.
 615     HeapRegion* curr_region = _hrm.addr_to_region(start_address);
 616     HeapRegion* last_region = _hrm.addr_to_region(last_address);
 617     prev_last_region = last_region;
 618 
 619     while (curr_region != NULL) {
 620       assert(curr_region->is_empty() && !curr_region->is_pinned(),
 621              "Region already in use (index %u)", curr_region->hrm_index());
 622       if (open) {
 623         curr_region->set_open_archive();
 624       } else {
 625         curr_region->set_closed_archive();
 626       }
 627       _hr_printer.alloc(curr_region);
 628       _archive_set.add(curr_region);
 629       HeapWord* top;
 630       HeapRegion* next_region;
 631       if (curr_region != last_region) {
 632         top = curr_region->end();
 633         next_region = _hrm.next_region_in_heap(curr_region);
 634       } else {
 635         top = last_address + 1;
 636         next_region = NULL;
 637       }
 638       curr_region->set_top(top);
 639       curr_region = next_region;
 640     }
 641   }
 642   return true;
 643 }
 644 
 645 void G1CollectedHeap::fill_archive_regions(MemRegion* ranges, size_t count) {
 646   assert(!is_init_completed(), "Expect to be called at JVM init time");
 647   assert(ranges != NULL, "MemRegion array NULL");
 648   assert(count != 0, "No MemRegions provided");
 649   MemRegion reserved = _hrm.reserved();
 650   HeapWord *prev_last_addr = NULL;
 651   HeapRegion* prev_last_region = NULL;
 652 
 653   // For each MemRegion, create filler objects, if needed, in the G1 regions
 654   // that contain the address range. The address range actually within the
 655   // MemRegion will not be modified. That is assumed to have been initialized
 656   // elsewhere, probably via an mmap of archived heap data.
 657   MutexLocker x(Heap_lock);
 658   for (size_t i = 0; i < count; i++) {
 659     HeapWord* start_address = ranges[i].start();
 660     HeapWord* last_address = ranges[i].last();
 661 
 662     assert(reserved.contains(start_address) && reserved.contains(last_address),
 663            "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
 664            p2i(start_address), p2i(last_address));
 665     assert(start_address > prev_last_addr,
 666            "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
 667            p2i(start_address), p2i(prev_last_addr));
 668 
 669     HeapRegion* start_region = _hrm.addr_to_region(start_address);
 670     HeapRegion* last_region = _hrm.addr_to_region(last_address);
 671     HeapWord* bottom_address = start_region->bottom();
 672 
 673     // Check for a range beginning in the same region in which the
 674     // previous one ended.
 675     if (start_region == prev_last_region) {
 676       bottom_address = prev_last_addr + 1;
 677     }
 678 
 679     // Verify that the regions were all marked as archive regions by
 680     // alloc_archive_regions.
 681     HeapRegion* curr_region = start_region;
 682     while (curr_region != NULL) {
 683       guarantee(curr_region->is_archive(),
 684                 "Expected archive region at index %u", curr_region->hrm_index());
 685       if (curr_region != last_region) {
 686         curr_region = _hrm.next_region_in_heap(curr_region);
 687       } else {
 688         curr_region = NULL;
 689       }
 690     }
 691 
 692     prev_last_addr = last_address;
 693     prev_last_region = last_region;
 694 
 695     // Fill the memory below the allocated range with dummy object(s),
 696     // if the region bottom does not match the range start, or if the previous
 697     // range ended within the same G1 region, and there is a gap.
 698     assert(start_address >= bottom_address, "bottom address should not be greater than start address");
 699     if (start_address > bottom_address) {
 700       size_t fill_size = pointer_delta(start_address, bottom_address);
 701       G1CollectedHeap::fill_with_objects(bottom_address, fill_size);
 702       increase_used(fill_size * HeapWordSize);
 703     }
 704   }
 705 }
 706 
 707 inline HeapWord* G1CollectedHeap::attempt_allocation(size_t min_word_size,
 708                                                      size_t desired_word_size,
 709                                                      size_t* actual_word_size) {
 710   assert_heap_not_locked_and_not_at_safepoint();
 711   assert(!is_humongous(desired_word_size), "attempt_allocation() should not "
 712          "be called for humongous allocation requests");
 713 
 714   HeapWord* result = _allocator->attempt_allocation(min_word_size, desired_word_size, actual_word_size);
 715 
 716   if (result == NULL) {
 717     *actual_word_size = desired_word_size;
 718     result = attempt_allocation_slow(desired_word_size);
 719   }
 720 
 721   assert_heap_not_locked();
 722   if (result != NULL) {
 723     assert(*actual_word_size != 0, "Actual size must have been set here");
 724     dirty_young_block(result, *actual_word_size);
 725   } else {
 726     *actual_word_size = 0;
 727   }
 728 
 729   return result;
 730 }
 731 
 732 void G1CollectedHeap::populate_archive_regions_bot_part(MemRegion* ranges, size_t count) {
 733   assert(!is_init_completed(), "Expect to be called at JVM init time");
 734   assert(ranges != NULL, "MemRegion array NULL");
 735   assert(count != 0, "No MemRegions provided");
 736 
 737   HeapWord* st = ranges[0].start();
 738   HeapWord* last = ranges[count-1].last();
 739   HeapRegion* hr_st = _hrm.addr_to_region(st);
 740   HeapRegion* hr_last = _hrm.addr_to_region(last);
 741 
 742   HeapRegion* hr_curr = hr_st;
 743   while (hr_curr != NULL) {
 744     hr_curr->update_bot();
 745     if (hr_curr != hr_last) {
 746       hr_curr = _hrm.next_region_in_heap(hr_curr);
 747     } else {
 748       hr_curr = NULL;
 749     }
 750   }
 751 }
 752 
 753 void G1CollectedHeap::dealloc_archive_regions(MemRegion* ranges, size_t count) {
 754   assert(!is_init_completed(), "Expect to be called at JVM init time");
 755   assert(ranges != NULL, "MemRegion array NULL");
 756   assert(count != 0, "No MemRegions provided");
 757   MemRegion reserved = _hrm.reserved();
 758   HeapWord* prev_last_addr = NULL;
 759   HeapRegion* prev_last_region = NULL;
 760   size_t size_used = 0;
 761   uint shrink_count = 0;
 762 
 763   // For each Memregion, free the G1 regions that constitute it, and
 764   // notify mark-sweep that the range is no longer to be considered 'archive.'
 765   MutexLocker x(Heap_lock);
 766   for (size_t i = 0; i < count; i++) {
 767     HeapWord* start_address = ranges[i].start();
 768     HeapWord* last_address = ranges[i].last();
 769 
 770     assert(reserved.contains(start_address) && reserved.contains(last_address),
 771            "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
 772            p2i(start_address), p2i(last_address));
 773     assert(start_address > prev_last_addr,
 774            "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
 775            p2i(start_address), p2i(prev_last_addr));
 776     size_used += ranges[i].byte_size();
 777     prev_last_addr = last_address;
 778 
 779     HeapRegion* start_region = _hrm.addr_to_region(start_address);
 780     HeapRegion* last_region = _hrm.addr_to_region(last_address);
 781 
 782     // Check for ranges that start in the same G1 region in which the previous
 783     // range ended, and adjust the start address so we don't try to free
 784     // the same region again. If the current range is entirely within that
 785     // region, skip it.
 786     if (start_region == prev_last_region) {
 787       start_address = start_region->end();
 788       if (start_address > last_address) {
 789         continue;
 790       }
 791       start_region = _hrm.addr_to_region(start_address);
 792     }
 793     prev_last_region = last_region;
 794 
 795     // After verifying that each region was marked as an archive region by
 796     // alloc_archive_regions, set it free and empty and uncommit it.
 797     HeapRegion* curr_region = start_region;
 798     while (curr_region != NULL) {
 799       guarantee(curr_region->is_archive(),
 800                 "Expected archive region at index %u", curr_region->hrm_index());
 801       uint curr_index = curr_region->hrm_index();
 802       _archive_set.remove(curr_region);
 803       curr_region->set_free();
 804       curr_region->set_top(curr_region->bottom());
 805       if (curr_region != last_region) {
 806         curr_region = _hrm.next_region_in_heap(curr_region);
 807       } else {
 808         curr_region = NULL;
 809       }
 810 
 811       _hrm.shrink_at(curr_index, 1);
 812       shrink_count++;
 813     }
 814   }
 815 
 816   if (shrink_count != 0) {
 817     log_debug(gc, ergo, heap)("Attempt heap shrinking (archive regions). Total size: " SIZE_FORMAT "B",
 818                               HeapRegion::GrainWords * HeapWordSize * shrink_count);
 819     // Explicit uncommit.
 820     uncommit_regions(shrink_count);
 821   }
 822   decrease_used(size_used);
 823 }
 824 
 825 HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size) {
 826   ResourceMark rm; // For retrieving the thread names in log messages.
 827 
 828   // The structure of this method has a lot of similarities to
 829   // attempt_allocation_slow(). The reason these two were not merged
 830   // into a single one is that such a method would require several "if
 831   // allocation is not humongous do this, otherwise do that"
 832   // conditional paths which would obscure its flow. In fact, an early
 833   // version of this code did use a unified method which was harder to
 834   // follow and, as a result, it had subtle bugs that were hard to
 835   // track down. So keeping these two methods separate allows each to
 836   // be more readable. It will be good to keep these two in sync as
 837   // much as possible.
 838 
 839   assert_heap_not_locked_and_not_at_safepoint();
 840   assert(is_humongous(word_size), "attempt_allocation_humongous() "
 841          "should only be called for humongous allocations");
 842 
 843   // Humongous objects can exhaust the heap quickly, so we should check if we
 844   // need to start a marking cycle at each humongous object allocation. We do
 845   // the check before we do the actual allocation. The reason for doing it
 846   // before the allocation is that we avoid having to keep track of the newly
 847   // allocated memory while we do a GC.
 848   if (policy()->need_to_start_conc_mark("concurrent humongous allocation",
 849                                         word_size)) {
 850     collect(GCCause::_g1_humongous_allocation);
 851   }
 852 
 853   // We will loop until a) we manage to successfully perform the
 854   // allocation or b) we successfully schedule a collection which
 855   // fails to perform the allocation. b) is the only case when we'll
 856   // return NULL.
 857   HeapWord* result = NULL;
 858   for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
 859     bool should_try_gc;
 860     bool preventive_collection_required = false;
 861     uint gc_count_before;
 862 
 863 
 864     {
 865       MutexLocker x(Heap_lock);
 866 
 867       size_t size_in_regions = humongous_obj_size_in_regions(word_size);
 868       preventive_collection_required = policy()->preventive_collection_required((uint)size_in_regions);
 869       if (!preventive_collection_required) {
 870         // Given that humongous objects are not allocated in young
 871         // regions, we'll first try to do the allocation without doing a
 872         // collection hoping that there's enough space in the heap.
 873         result = humongous_obj_allocate(word_size);
 874         if (result != NULL) {
 875           policy()->old_gen_alloc_tracker()->
 876             add_allocated_humongous_bytes_since_last_gc(size_in_regions * HeapRegion::GrainBytes);
 877           return result;
 878         }
 879       }
 880 
 881       // Only try a GC if the GCLocker does not signal the need for a GC. Wait until
 882       // the GCLocker initiated GC has been performed and then retry. This includes
 883       // the case when the GC Locker is not active but has not been performed.
 884       should_try_gc = !GCLocker::needs_gc();
 885       // Read the GC count while still holding the Heap_lock.
 886       gc_count_before = total_collections();
 887     }
 888 
 889     if (should_try_gc) {
 890       GCCause::Cause gc_cause = preventive_collection_required ? GCCause::_g1_preventive_collection
 891                                                               : GCCause::_g1_humongous_allocation;
 892       bool succeeded;
 893       result = do_collection_pause(word_size, gc_count_before, &succeeded, gc_cause);
 894       if (result != NULL) {
 895         assert(succeeded, "only way to get back a non-NULL result");
 896         log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,
 897                              Thread::current()->name(), p2i(result));
 898         size_t size_in_regions = humongous_obj_size_in_regions(word_size);
 899         policy()->old_gen_alloc_tracker()->
 900           record_collection_pause_humongous_allocation(size_in_regions * HeapRegion::GrainBytes);
 901         return result;
 902       }
 903 
 904       if (succeeded) {
 905         // We successfully scheduled a collection which failed to allocate. No
 906         // point in trying to allocate further. We'll just return NULL.
 907         log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "
 908                              SIZE_FORMAT " words", Thread::current()->name(), word_size);
 909         return NULL;
 910       }
 911       log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT "",
 912                            Thread::current()->name(), word_size);
 913     } else {
 914       // Failed to schedule a collection.
 915       if (gclocker_retry_count > GCLockerRetryAllocationCount) {
 916         log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "
 917                                SIZE_FORMAT " words", Thread::current()->name(), word_size);
 918         return NULL;
 919       }
 920       log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());
 921       // The GCLocker is either active or the GCLocker initiated
 922       // GC has not yet been performed. Stall until it is and
 923       // then retry the allocation.
 924       GCLocker::stall_until_clear();
 925       gclocker_retry_count += 1;
 926     }
 927 
 928 
 929     // We can reach here if we were unsuccessful in scheduling a
 930     // collection (because another thread beat us to it) or if we were
 931     // stalled due to the GC locker. In either can we should retry the
 932     // allocation attempt in case another thread successfully
 933     // performed a collection and reclaimed enough space.
 934     // Humongous object allocation always needs a lock, so we wait for the retry
 935     // in the next iteration of the loop, unlike for the regular iteration case.
 936     // Give a warning if we seem to be looping forever.
 937 
 938     if ((QueuedAllocationWarningCount > 0) &&
 939         (try_count % QueuedAllocationWarningCount == 0)) {
 940       log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words",
 941                              Thread::current()->name(), try_count, word_size);
 942     }
 943   }
 944 
 945   ShouldNotReachHere();
 946   return NULL;
 947 }
 948 
 949 HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size,
 950                                                            bool expect_null_mutator_alloc_region) {
 951   assert_at_safepoint_on_vm_thread();
 952   assert(!_allocator->has_mutator_alloc_region() || !expect_null_mutator_alloc_region,
 953          "the current alloc region was unexpectedly found to be non-NULL");
 954 
 955   if (!is_humongous(word_size)) {
 956     return _allocator->attempt_allocation_locked(word_size);
 957   } else {
 958     HeapWord* result = humongous_obj_allocate(word_size);
 959     if (result != NULL && policy()->need_to_start_conc_mark("STW humongous allocation")) {
 960       collector_state()->set_initiate_conc_mark_if_possible(true);
 961     }
 962     return result;
 963   }
 964 
 965   ShouldNotReachHere();
 966 }
 967 
 968 class PostCompactionPrinterClosure: public HeapRegionClosure {
 969 private:
 970   G1HRPrinter* _hr_printer;
 971 public:
 972   bool do_heap_region(HeapRegion* hr) {
 973     assert(!hr->is_young(), "not expecting to find young regions");
 974     _hr_printer->post_compaction(hr);
 975     return false;
 976   }
 977 
 978   PostCompactionPrinterClosure(G1HRPrinter* hr_printer)
 979     : _hr_printer(hr_printer) { }
 980 };
 981 
 982 void G1CollectedHeap::print_hrm_post_compaction() {
 983   if (_hr_printer.is_active()) {
 984     PostCompactionPrinterClosure cl(hr_printer());
 985     heap_region_iterate(&cl);
 986   }
 987 }
 988 
 989 void G1CollectedHeap::abort_concurrent_cycle() {
 990   // If we start the compaction before the CM threads finish
 991   // scanning the root regions we might trip them over as we'll
 992   // be moving objects / updating references. So let's wait until
 993   // they are done. By telling them to abort, they should complete
 994   // early.
 995   _cm->root_regions()->abort();
 996   _cm->root_regions()->wait_until_scan_finished();
 997 
 998   // Disable discovery and empty the discovered lists
 999   // for the CM ref processor.
1000   _ref_processor_cm->disable_discovery();
1001   _ref_processor_cm->abandon_partial_discovery();
1002   _ref_processor_cm->verify_no_references_recorded();
1003 
1004   // Abandon current iterations of concurrent marking and concurrent
1005   // refinement, if any are in progress.
1006   concurrent_mark()->concurrent_cycle_abort();
1007 }
1008 
1009 void G1CollectedHeap::prepare_heap_for_full_collection() {
1010   // Make sure we'll choose a new allocation region afterwards.
1011   _allocator->release_mutator_alloc_regions();
1012   _allocator->abandon_gc_alloc_regions();
1013 
1014   // We may have added regions to the current incremental collection
1015   // set between the last GC or pause and now. We need to clear the
1016   // incremental collection set and then start rebuilding it afresh
1017   // after this full GC.
1018   abandon_collection_set(collection_set());
1019 
1020   _hrm.remove_all_free_regions();
1021 }
1022 
1023 void G1CollectedHeap::verify_before_full_collection(bool explicit_gc) {
1024   assert(!GCCause::is_user_requested_gc(gc_cause()) || explicit_gc, "invariant");
1025   assert_used_and_recalculate_used_equal(this);
1026   _verifier->verify_region_sets_optional();
1027   _verifier->verify_before_gc(G1HeapVerifier::G1VerifyFull);
1028   _verifier->check_bitmaps("Full GC Start");
1029 }
1030 
1031 void G1CollectedHeap::prepare_heap_for_mutators() {
1032   // Delete metaspaces for unloaded class loaders and clean up loader_data graph
1033   ClassLoaderDataGraph::purge(/*at_safepoint*/true);
1034   DEBUG_ONLY(MetaspaceUtils::verify();)
1035 
1036   // Prepare heap for normal collections.
1037   assert(num_free_regions() == 0, "we should not have added any free regions");
1038   rebuild_region_sets(false /* free_list_only */);
1039   abort_refinement();
1040   resize_heap_if_necessary();
1041   uncommit_regions_if_necessary();
1042 
1043   // Rebuild the strong code root lists for each region
1044   rebuild_strong_code_roots();
1045 
1046   // Purge code root memory
1047   purge_code_root_memory();
1048 
1049   // Start a new incremental collection set for the next pause
1050   start_new_collection_set();
1051 
1052   _allocator->init_mutator_alloc_regions();
1053 
1054   // Post collection state updates.
1055   MetaspaceGC::compute_new_size();
1056 }
1057 
1058 void G1CollectedHeap::abort_refinement() {
1059   if (_hot_card_cache->use_cache()) {
1060     _hot_card_cache->reset_hot_cache();
1061   }
1062 
1063   // Discard all remembered set updates and reset refinement statistics.
1064   G1BarrierSet::dirty_card_queue_set().abandon_logs();
1065   assert(G1BarrierSet::dirty_card_queue_set().num_cards() == 0,
1066          "DCQS should be empty");
1067   concurrent_refine()->get_and_reset_refinement_stats();
1068 }
1069 
1070 void G1CollectedHeap::verify_after_full_collection() {
1071   _hrm.verify_optional();
1072   _verifier->verify_region_sets_optional();
1073   _verifier->verify_after_gc(G1HeapVerifier::G1VerifyFull);
1074 
1075   // This call implicitly verifies that the next bitmap is clear after Full GC.
1076   _verifier->check_bitmaps("Full GC End");
1077 
1078   // At this point there should be no regions in the
1079   // entire heap tagged as young.
1080   assert(check_young_list_empty(), "young list should be empty at this point");
1081 
1082   // Note: since we've just done a full GC, concurrent
1083   // marking is no longer active. Therefore we need not
1084   // re-enable reference discovery for the CM ref processor.
1085   // That will be done at the start of the next marking cycle.
1086   // We also know that the STW processor should no longer
1087   // discover any new references.
1088   assert(!_ref_processor_stw->discovery_enabled(), "Postcondition");
1089   assert(!_ref_processor_cm->discovery_enabled(), "Postcondition");
1090   _ref_processor_stw->verify_no_references_recorded();
1091   _ref_processor_cm->verify_no_references_recorded();
1092 }
1093 
1094 void G1CollectedHeap::print_heap_after_full_collection(G1HeapTransition* heap_transition) {
1095   // Post collection logging.
1096   // We should do this after we potentially resize the heap so
1097   // that all the COMMIT / UNCOMMIT events are generated before
1098   // the compaction events.
1099   print_hrm_post_compaction();
1100   heap_transition->print();
1101   print_heap_after_gc();
1102   print_heap_regions();
1103 }
1104 
1105 bool G1CollectedHeap::do_full_collection(bool explicit_gc,
1106                                          bool clear_all_soft_refs,
1107                                          bool do_maximum_compaction) {
1108   assert_at_safepoint_on_vm_thread();
1109 
1110   if (GCLocker::check_active_before_gc()) {
1111     // Full GC was not completed.
1112     return false;
1113   }
1114 
1115   const bool do_clear_all_soft_refs = clear_all_soft_refs ||
1116       soft_ref_policy()->should_clear_all_soft_refs();
1117 
1118   G1FullCollector collector(this, explicit_gc, do_clear_all_soft_refs, do_maximum_compaction);
1119   GCTraceTime(Info, gc) tm("Pause Full", NULL, gc_cause(), true);
1120 
1121   collector.prepare_collection();
1122   collector.collect();
1123   collector.complete_collection();
1124 
1125   // Full collection was successfully completed.
1126   return true;
1127 }
1128 
1129 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {
1130   // Currently, there is no facility in the do_full_collection(bool) API to notify
1131   // the caller that the collection did not succeed (e.g., because it was locked
1132   // out by the GC locker). So, right now, we'll ignore the return value.
1133   // When clear_all_soft_refs is set we want to do a maximum compaction
1134   // not leaving any dead wood.
1135   bool do_maximum_compaction = clear_all_soft_refs;
1136   bool dummy = do_full_collection(true,                /* explicit_gc */
1137                                   clear_all_soft_refs,
1138                                   do_maximum_compaction);
1139 }
1140 
1141 bool G1CollectedHeap::upgrade_to_full_collection() {
1142   GCCauseSetter compaction(this, GCCause::_g1_compaction_pause);
1143   log_info(gc, ergo)("Attempting full compaction clearing soft references");
1144   bool success = do_full_collection(false /* explicit gc */,
1145                                     true  /* clear_all_soft_refs */,
1146                                     false /* do_maximum_compaction */);
1147   // do_full_collection only fails if blocked by GC locker and that can't
1148   // be the case here since we only call this when already completed one gc.
1149   assert(success, "invariant");
1150   return success;
1151 }
1152 
1153 void G1CollectedHeap::resize_heap_if_necessary() {
1154   assert_at_safepoint_on_vm_thread();
1155 
1156   bool should_expand;
1157   size_t resize_amount = _heap_sizing_policy->full_collection_resize_amount(should_expand);
1158 
1159   if (resize_amount == 0) {
1160     return;
1161   } else if (should_expand) {
1162     expand(resize_amount, _workers);
1163   } else {
1164     shrink(resize_amount);
1165   }
1166 }
1167 
1168 HeapWord* G1CollectedHeap::satisfy_failed_allocation_helper(size_t word_size,
1169                                                             bool do_gc,
1170                                                             bool maximum_compaction,
1171                                                             bool expect_null_mutator_alloc_region,
1172                                                             bool* gc_succeeded) {
1173   *gc_succeeded = true;
1174   // Let's attempt the allocation first.
1175   HeapWord* result =
1176     attempt_allocation_at_safepoint(word_size,
1177                                     expect_null_mutator_alloc_region);
1178   if (result != NULL) {
1179     return result;
1180   }
1181 
1182   // In a G1 heap, we're supposed to keep allocation from failing by
1183   // incremental pauses.  Therefore, at least for now, we'll favor
1184   // expansion over collection.  (This might change in the future if we can
1185   // do something smarter than full collection to satisfy a failed alloc.)
1186   result = expand_and_allocate(word_size);
1187   if (result != NULL) {
1188     return result;
1189   }
1190 
1191   if (do_gc) {
1192     GCCauseSetter compaction(this, GCCause::_g1_compaction_pause);
1193     // Expansion didn't work, we'll try to do a Full GC.
1194     // If maximum_compaction is set we clear all soft references and don't
1195     // allow any dead wood to be left on the heap.
1196     if (maximum_compaction) {
1197       log_info(gc, ergo)("Attempting maximum full compaction clearing soft references");
1198     } else {
1199       log_info(gc, ergo)("Attempting full compaction");
1200     }
1201     *gc_succeeded = do_full_collection(false, /* explicit_gc */
1202                                        maximum_compaction /* clear_all_soft_refs */ ,
1203                                        maximum_compaction /* do_maximum_compaction */);
1204   }
1205 
1206   return NULL;
1207 }
1208 
1209 HeapWord* G1CollectedHeap::satisfy_failed_allocation(size_t word_size,
1210                                                      bool* succeeded) {
1211   assert_at_safepoint_on_vm_thread();
1212 
1213   // Attempts to allocate followed by Full GC.
1214   HeapWord* result =
1215     satisfy_failed_allocation_helper(word_size,
1216                                      true,  /* do_gc */
1217                                      false, /* maximum_collection */
1218                                      false, /* expect_null_mutator_alloc_region */
1219                                      succeeded);
1220 
1221   if (result != NULL || !*succeeded) {
1222     return result;
1223   }
1224 
1225   // Attempts to allocate followed by Full GC that will collect all soft references.
1226   result = satisfy_failed_allocation_helper(word_size,
1227                                             true, /* do_gc */
1228                                             true, /* maximum_collection */
1229                                             true, /* expect_null_mutator_alloc_region */
1230                                             succeeded);
1231 
1232   if (result != NULL || !*succeeded) {
1233     return result;
1234   }
1235 
1236   // Attempts to allocate, no GC
1237   result = satisfy_failed_allocation_helper(word_size,
1238                                             false, /* do_gc */
1239                                             false, /* maximum_collection */
1240                                             true,  /* expect_null_mutator_alloc_region */
1241                                             succeeded);
1242 
1243   if (result != NULL) {
1244     return result;
1245   }
1246 
1247   assert(!soft_ref_policy()->should_clear_all_soft_refs(),
1248          "Flag should have been handled and cleared prior to this point");
1249 
1250   // What else?  We might try synchronous finalization later.  If the total
1251   // space available is large enough for the allocation, then a more
1252   // complete compaction phase than we've tried so far might be
1253   // appropriate.
1254   return NULL;
1255 }
1256 
1257 // Attempting to expand the heap sufficiently
1258 // to support an allocation of the given "word_size".  If
1259 // successful, perform the allocation and return the address of the
1260 // allocated block, or else "NULL".
1261 
1262 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {
1263   assert_at_safepoint_on_vm_thread();
1264 
1265   _verifier->verify_region_sets_optional();
1266 
1267   size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes);
1268   log_debug(gc, ergo, heap)("Attempt heap expansion (allocation request failed). Allocation request: " SIZE_FORMAT "B",
1269                             word_size * HeapWordSize);
1270 
1271 
1272   if (expand(expand_bytes, _workers)) {
1273     _hrm.verify_optional();
1274     _verifier->verify_region_sets_optional();
1275     return attempt_allocation_at_safepoint(word_size,
1276                                            false /* expect_null_mutator_alloc_region */);
1277   }
1278   return NULL;
1279 }
1280 
1281 bool G1CollectedHeap::expand(size_t expand_bytes, WorkGang* pretouch_workers, double* expand_time_ms) {
1282   size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes);
1283   aligned_expand_bytes = align_up(aligned_expand_bytes,
1284                                        HeapRegion::GrainBytes);
1285 
1286   log_debug(gc, ergo, heap)("Expand the heap. requested expansion amount: " SIZE_FORMAT "B expansion amount: " SIZE_FORMAT "B",
1287                             expand_bytes, aligned_expand_bytes);
1288 
1289   if (is_maximal_no_gc()) {
1290     log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)");
1291     return false;
1292   }
1293 
1294   double expand_heap_start_time_sec = os::elapsedTime();
1295   uint regions_to_expand = (uint)(aligned_expand_bytes / HeapRegion::GrainBytes);
1296   assert(regions_to_expand > 0, "Must expand by at least one region");
1297 
1298   uint expanded_by = _hrm.expand_by(regions_to_expand, pretouch_workers);
1299   if (expand_time_ms != NULL) {
1300     *expand_time_ms = (os::elapsedTime() - expand_heap_start_time_sec) * MILLIUNITS;
1301   }
1302 
1303   if (expanded_by > 0) {
1304     size_t actual_expand_bytes = expanded_by * HeapRegion::GrainBytes;
1305     assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition");
1306     policy()->record_new_heap_size(num_regions());
1307   } else {
1308     log_debug(gc, ergo, heap)("Did not expand the heap (heap expansion operation failed)");
1309 
1310     // The expansion of the virtual storage space was unsuccessful.
1311     // Let's see if it was because we ran out of swap.
1312     if (G1ExitOnExpansionFailure &&
1313         _hrm.available() >= regions_to_expand) {
1314       // We had head room...
1315       vm_exit_out_of_memory(aligned_expand_bytes, OOM_MMAP_ERROR, "G1 heap expansion");
1316     }
1317   }
1318   return regions_to_expand > 0;
1319 }
1320 
1321 bool G1CollectedHeap::expand_single_region(uint node_index) {
1322   uint expanded_by = _hrm.expand_on_preferred_node(node_index);
1323 
1324   if (expanded_by == 0) {
1325     assert(is_maximal_no_gc(), "Should be no regions left, available: %u", _hrm.available());
1326     log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)");
1327     return false;
1328   }
1329 
1330   policy()->record_new_heap_size(num_regions());
1331   return true;
1332 }
1333 
1334 void G1CollectedHeap::shrink_helper(size_t shrink_bytes) {
1335   size_t aligned_shrink_bytes =
1336     ReservedSpace::page_align_size_down(shrink_bytes);
1337   aligned_shrink_bytes = align_down(aligned_shrink_bytes,
1338                                          HeapRegion::GrainBytes);
1339   uint num_regions_to_remove = (uint)(shrink_bytes / HeapRegion::GrainBytes);
1340 
1341   uint num_regions_removed = _hrm.shrink_by(num_regions_to_remove);
1342   size_t shrunk_bytes = num_regions_removed * HeapRegion::GrainBytes;
1343 
1344   log_debug(gc, ergo, heap)("Shrink the heap. requested shrinking amount: " SIZE_FORMAT "B aligned shrinking amount: " SIZE_FORMAT "B attempted shrinking amount: " SIZE_FORMAT "B",
1345                             shrink_bytes, aligned_shrink_bytes, shrunk_bytes);
1346   if (num_regions_removed > 0) {
1347     log_debug(gc, heap)("Uncommittable regions after shrink: %u", num_regions_removed);
1348     policy()->record_new_heap_size(num_regions());
1349   } else {
1350     log_debug(gc, ergo, heap)("Did not expand the heap (heap shrinking operation failed)");
1351   }
1352 }
1353 
1354 void G1CollectedHeap::shrink(size_t shrink_bytes) {
1355   _verifier->verify_region_sets_optional();
1356 
1357   // We should only reach here at the end of a Full GC or during Remark which
1358   // means we should not not be holding to any GC alloc regions. The method
1359   // below will make sure of that and do any remaining clean up.
1360   _allocator->abandon_gc_alloc_regions();
1361 
1362   // Instead of tearing down / rebuilding the free lists here, we
1363   // could instead use the remove_all_pending() method on free_list to
1364   // remove only the ones that we need to remove.
1365   _hrm.remove_all_free_regions();
1366   shrink_helper(shrink_bytes);
1367   rebuild_region_sets(true /* free_list_only */);
1368 
1369   _hrm.verify_optional();
1370   _verifier->verify_region_sets_optional();
1371 }
1372 
1373 class OldRegionSetChecker : public HeapRegionSetChecker {
1374 public:
1375   void check_mt_safety() {
1376     // Master Old Set MT safety protocol:
1377     // (a) If we're at a safepoint, operations on the master old set
1378     // should be invoked:
1379     // - by the VM thread (which will serialize them), or
1380     // - by the GC workers while holding the FreeList_lock, if we're
1381     //   at a safepoint for an evacuation pause (this lock is taken
1382     //   anyway when an GC alloc region is retired so that a new one
1383     //   is allocated from the free list), or
1384     // - by the GC workers while holding the OldSets_lock, if we're at a
1385     //   safepoint for a cleanup pause.
1386     // (b) If we're not at a safepoint, operations on the master old set
1387     // should be invoked while holding the Heap_lock.
1388 
1389     if (SafepointSynchronize::is_at_safepoint()) {
1390       guarantee(Thread::current()->is_VM_thread() ||
1391                 FreeList_lock->owned_by_self() || OldSets_lock->owned_by_self(),
1392                 "master old set MT safety protocol at a safepoint");
1393     } else {
1394       guarantee(Heap_lock->owned_by_self(), "master old set MT safety protocol outside a safepoint");
1395     }
1396   }
1397   bool is_correct_type(HeapRegion* hr) { return hr->is_old(); }
1398   const char* get_description() { return "Old Regions"; }
1399 };
1400 
1401 class ArchiveRegionSetChecker : public HeapRegionSetChecker {
1402 public:
1403   void check_mt_safety() {
1404     guarantee(!Universe::is_fully_initialized() || SafepointSynchronize::is_at_safepoint(),
1405               "May only change archive regions during initialization or safepoint.");
1406   }
1407   bool is_correct_type(HeapRegion* hr) { return hr->is_archive(); }
1408   const char* get_description() { return "Archive Regions"; }
1409 };
1410 
1411 class HumongousRegionSetChecker : public HeapRegionSetChecker {
1412 public:
1413   void check_mt_safety() {
1414     // Humongous Set MT safety protocol:
1415     // (a) If we're at a safepoint, operations on the master humongous
1416     // set should be invoked by either the VM thread (which will
1417     // serialize them) or by the GC workers while holding the
1418     // OldSets_lock.
1419     // (b) If we're not at a safepoint, operations on the master
1420     // humongous set should be invoked while holding the Heap_lock.
1421 
1422     if (SafepointSynchronize::is_at_safepoint()) {
1423       guarantee(Thread::current()->is_VM_thread() ||
1424                 OldSets_lock->owned_by_self(),
1425                 "master humongous set MT safety protocol at a safepoint");
1426     } else {
1427       guarantee(Heap_lock->owned_by_self(),
1428                 "master humongous set MT safety protocol outside a safepoint");
1429     }
1430   }
1431   bool is_correct_type(HeapRegion* hr) { return hr->is_humongous(); }
1432   const char* get_description() { return "Humongous Regions"; }
1433 };
1434 
1435 G1CollectedHeap::G1CollectedHeap() :
1436   CollectedHeap(),
1437   _service_thread(NULL),
1438   _periodic_gc_task(NULL),
1439   _workers(NULL),
1440   _card_table(NULL),
1441   _collection_pause_end(Ticks::now()),
1442   _soft_ref_policy(),
1443   _old_set("Old Region Set", new OldRegionSetChecker()),
1444   _archive_set("Archive Region Set", new ArchiveRegionSetChecker()),
1445   _humongous_set("Humongous Region Set", new HumongousRegionSetChecker()),
1446   _bot(NULL),
1447   _listener(),
1448   _numa(G1NUMA::create()),
1449   _hrm(),
1450   _allocator(NULL),
1451   _verifier(NULL),
1452   _summary_bytes_used(0),
1453   _bytes_used_during_gc(0),
1454   _archive_allocator(NULL),
1455   _survivor_evac_stats("Young", YoungPLABSize, PLABWeight),
1456   _old_evac_stats("Old", OldPLABSize, PLABWeight),
1457   _expand_heap_after_alloc_failure(true),
1458   _g1mm(NULL),
1459   _humongous_reclaim_candidates(),
1460   _num_humongous_objects(0),
1461   _num_humongous_reclaim_candidates(0),
1462   _hr_printer(),
1463   _collector_state(),
1464   _old_marking_cycles_started(0),
1465   _old_marking_cycles_completed(0),
1466   _eden(),
1467   _survivor(),
1468   _gc_timer_stw(new (ResourceObj::C_HEAP, mtGC) STWGCTimer()),
1469   _gc_tracer_stw(new (ResourceObj::C_HEAP, mtGC) G1NewTracer()),
1470   _policy(new G1Policy(_gc_timer_stw)),
1471   _heap_sizing_policy(NULL),
1472   _collection_set(this, _policy),
1473   _hot_card_cache(NULL),
1474   _rem_set(NULL),
1475   _cm(NULL),
1476   _cm_thread(NULL),
1477   _cr(NULL),
1478   _task_queues(NULL),
1479   _num_regions_failed_evacuation(0),
1480   _regions_failed_evacuation(NULL),
1481   _evacuation_failed_info_array(NULL),
1482   _preserved_marks_set(true /* in_c_heap */),
1483 #ifndef PRODUCT
1484   _evacuation_failure_alot_for_current_gc(false),
1485   _evacuation_failure_alot_gc_number(0),
1486   _evacuation_failure_alot_count(0),
1487 #endif
1488   _ref_processor_stw(NULL),
1489   _is_alive_closure_stw(this),
1490   _is_subject_to_discovery_stw(this),
1491   _ref_processor_cm(NULL),
1492   _is_alive_closure_cm(this),
1493   _is_subject_to_discovery_cm(this),
1494   _region_attr() {
1495 
1496   _verifier = new G1HeapVerifier(this);
1497 
1498   _allocator = new G1Allocator(this);
1499 
1500   _heap_sizing_policy = G1HeapSizingPolicy::create(this, _policy->analytics());
1501 
1502   _humongous_object_threshold_in_words = humongous_threshold_for(HeapRegion::GrainWords);
1503 
1504   // Override the default _filler_array_max_size so that no humongous filler
1505   // objects are created.
1506   _filler_array_max_size = _humongous_object_threshold_in_words;
1507 
1508   uint n_queues = ParallelGCThreads;
1509   _task_queues = new G1ScannerTasksQueueSet(n_queues);
1510 
1511   _evacuation_failed_info_array = NEW_C_HEAP_ARRAY(EvacuationFailedInfo, n_queues, mtGC);
1512 
1513   for (uint i = 0; i < n_queues; i++) {
1514     G1ScannerTasksQueue* q = new G1ScannerTasksQueue();
1515     q->initialize();
1516     _task_queues->register_queue(i, q);
1517     ::new (&_evacuation_failed_info_array[i]) EvacuationFailedInfo();
1518   }
1519 
1520   // Initialize the G1EvacuationFailureALot counters and flags.
1521   NOT_PRODUCT(reset_evacuation_should_fail();)
1522   _gc_tracer_stw->initialize();
1523 
1524   guarantee(_task_queues != NULL, "task_queues allocation failure.");
1525 }
1526 
1527 G1RegionToSpaceMapper* G1CollectedHeap::create_aux_memory_mapper(const char* description,
1528                                                                  size_t size,
1529                                                                  size_t translation_factor) {
1530   size_t preferred_page_size = os::page_size_for_region_unaligned(size, 1);
1531   // Allocate a new reserved space, preferring to use large pages.
1532   ReservedSpace rs(size, preferred_page_size);
1533   size_t page_size = rs.page_size();
1534   G1RegionToSpaceMapper* result  =
1535     G1RegionToSpaceMapper::create_mapper(rs,
1536                                          size,
1537                                          page_size,
1538                                          HeapRegion::GrainBytes,
1539                                          translation_factor,
1540                                          mtGC);
1541 
1542   os::trace_page_sizes_for_requested_size(description,
1543                                           size,
1544                                           page_size,
1545                                           preferred_page_size,
1546                                           rs.base(),
1547                                           rs.size());
1548 
1549   return result;
1550 }
1551 
1552 jint G1CollectedHeap::initialize_concurrent_refinement() {
1553   jint ecode = JNI_OK;
1554   _cr = G1ConcurrentRefine::create(&ecode);
1555   return ecode;
1556 }
1557 
1558 jint G1CollectedHeap::initialize_service_thread() {
1559   _service_thread = new G1ServiceThread();
1560   if (_service_thread->osthread() == NULL) {
1561     vm_shutdown_during_initialization("Could not create G1ServiceThread");
1562     return JNI_ENOMEM;
1563   }
1564   return JNI_OK;
1565 }
1566 
1567 jint G1CollectedHeap::initialize() {
1568 
1569   // Necessary to satisfy locking discipline assertions.
1570 
1571   MutexLocker x(Heap_lock);
1572 
1573   // While there are no constraints in the GC code that HeapWordSize
1574   // be any particular value, there are multiple other areas in the
1575   // system which believe this to be true (e.g. oop->object_size in some
1576   // cases incorrectly returns the size in wordSize units rather than
1577   // HeapWordSize).
1578   guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
1579 
1580   size_t init_byte_size = InitialHeapSize;
1581   size_t reserved_byte_size = G1Arguments::heap_reserved_size_bytes();
1582 
1583   // Ensure that the sizes are properly aligned.
1584   Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");
1585   Universe::check_alignment(reserved_byte_size, HeapRegion::GrainBytes, "g1 heap");
1586   Universe::check_alignment(reserved_byte_size, HeapAlignment, "g1 heap");
1587 
1588   // Reserve the maximum.
1589 
1590   // When compressed oops are enabled, the preferred heap base
1591   // is calculated by subtracting the requested size from the
1592   // 32Gb boundary and using the result as the base address for
1593   // heap reservation. If the requested size is not aligned to
1594   // HeapRegion::GrainBytes (i.e. the alignment that is passed
1595   // into the ReservedHeapSpace constructor) then the actual
1596   // base of the reserved heap may end up differing from the
1597   // address that was requested (i.e. the preferred heap base).
1598   // If this happens then we could end up using a non-optimal
1599   // compressed oops mode.
1600 
1601   ReservedHeapSpace heap_rs = Universe::reserve_heap(reserved_byte_size,
1602                                                      HeapAlignment);
1603 
1604   initialize_reserved_region(heap_rs);
1605 
1606   // Create the barrier set for the entire reserved region.
1607   G1CardTable* ct = new G1CardTable(heap_rs.region());
1608   ct->initialize();
1609   G1BarrierSet* bs = new G1BarrierSet(ct);
1610   bs->initialize();
1611   assert(bs->is_a(BarrierSet::G1BarrierSet), "sanity");
1612   BarrierSet::set_barrier_set(bs);
1613   _card_table = ct;
1614 
1615   {
1616     G1SATBMarkQueueSet& satbqs = bs->satb_mark_queue_set();
1617     satbqs.set_process_completed_buffers_threshold(G1SATBProcessCompletedThreshold);
1618     satbqs.set_buffer_enqueue_threshold_percentage(G1SATBBufferEnqueueingThresholdPercent);
1619   }
1620 
1621   // Create the hot card cache.
1622   _hot_card_cache = new G1HotCardCache(this);
1623 
1624   // Create space mappers.
1625   size_t page_size = heap_rs.page_size();
1626   G1RegionToSpaceMapper* heap_storage =
1627     G1RegionToSpaceMapper::create_mapper(heap_rs,
1628                                          heap_rs.size(),
1629                                          page_size,
1630                                          HeapRegion::GrainBytes,
1631                                          1,
1632                                          mtJavaHeap);
1633   if(heap_storage == NULL) {
1634     vm_shutdown_during_initialization("Could not initialize G1 heap");
1635     return JNI_ERR;
1636   }
1637 
1638   os::trace_page_sizes("Heap",
1639                        MinHeapSize,
1640                        reserved_byte_size,
1641                        page_size,
1642                        heap_rs.base(),
1643                        heap_rs.size());
1644   heap_storage->set_mapping_changed_listener(&_listener);
1645 
1646   // Create storage for the BOT, card table, card counts table (hot card cache) and the bitmaps.
1647   G1RegionToSpaceMapper* bot_storage =
1648     create_aux_memory_mapper("Block Offset Table",
1649                              G1BlockOffsetTable::compute_size(heap_rs.size() / HeapWordSize),
1650                              G1BlockOffsetTable::heap_map_factor());
1651 
1652   G1RegionToSpaceMapper* cardtable_storage =
1653     create_aux_memory_mapper("Card Table",
1654                              G1CardTable::compute_size(heap_rs.size() / HeapWordSize),
1655                              G1CardTable::heap_map_factor());
1656 
1657   G1RegionToSpaceMapper* card_counts_storage =
1658     create_aux_memory_mapper("Card Counts Table",
1659                              G1CardCounts::compute_size(heap_rs.size() / HeapWordSize),
1660                              G1CardCounts::heap_map_factor());
1661 
1662   size_t bitmap_size = G1CMBitMap::compute_size(heap_rs.size());
1663   G1RegionToSpaceMapper* prev_bitmap_storage =
1664     create_aux_memory_mapper("Prev Bitmap", bitmap_size, G1CMBitMap::heap_map_factor());
1665   G1RegionToSpaceMapper* next_bitmap_storage =
1666     create_aux_memory_mapper("Next Bitmap", bitmap_size, G1CMBitMap::heap_map_factor());
1667 
1668   _hrm.initialize(heap_storage, prev_bitmap_storage, next_bitmap_storage, bot_storage, cardtable_storage, card_counts_storage);
1669   _card_table->initialize(cardtable_storage);
1670 
1671   // Do later initialization work for concurrent refinement.
1672   _hot_card_cache->initialize(card_counts_storage);
1673 
1674   // 6843694 - ensure that the maximum region index can fit
1675   // in the remembered set structures.
1676   const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;
1677   guarantee((max_reserved_regions() - 1) <= max_region_idx, "too many regions");
1678 
1679   // The G1FromCardCache reserves card with value 0 as "invalid", so the heap must not
1680   // start within the first card.
1681   guarantee(heap_rs.base() >= (char*)G1CardTable::card_size, "Java heap must not start within the first card.");
1682   G1FromCardCache::initialize(max_reserved_regions());
1683   // Also create a G1 rem set.
1684   _rem_set = new G1RemSet(this, _card_table, _hot_card_cache);
1685   _rem_set->initialize(max_reserved_regions());
1686 
1687   size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1;
1688   guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized");
1689   guarantee(HeapRegion::CardsPerRegion < max_cards_per_region,
1690             "too many cards per region");
1691 
1692   FreeRegionList::set_unrealistically_long_length(max_regions() + 1);
1693 
1694   _bot = new G1BlockOffsetTable(reserved(), bot_storage);
1695 
1696   {
1697     size_t granularity = HeapRegion::GrainBytes;
1698 
1699     _region_attr.initialize(reserved(), granularity);
1700     _humongous_reclaim_candidates.initialize(reserved(), granularity);
1701   }
1702 
1703   _workers = new WorkGang("GC Thread", ParallelGCThreads,
1704                           true /* are_GC_task_threads */,
1705                           false /* are_ConcurrentGC_threads */);
1706   if (_workers == NULL) {
1707     return JNI_ENOMEM;
1708   }
1709   _workers->initialize_workers();
1710 
1711   _numa->set_region_info(HeapRegion::GrainBytes, page_size);
1712 
1713   // Create the G1ConcurrentMark data structure and thread.
1714   // (Must do this late, so that "max_[reserved_]regions" is defined.)
1715   _cm = new G1ConcurrentMark(this, prev_bitmap_storage, next_bitmap_storage);
1716   _cm_thread = _cm->cm_thread();
1717 
1718   // Now expand into the initial heap size.
1719   if (!expand(init_byte_size, _workers)) {
1720     vm_shutdown_during_initialization("Failed to allocate initial heap.");
1721     return JNI_ENOMEM;
1722   }
1723 
1724   // Perform any initialization actions delegated to the policy.
1725   policy()->init(this, &_collection_set);
1726 
1727   jint ecode = initialize_concurrent_refinement();
1728   if (ecode != JNI_OK) {
1729     return ecode;
1730   }
1731 
1732   ecode = initialize_service_thread();
1733   if (ecode != JNI_OK) {
1734     return ecode;
1735   }
1736 
1737   // Initialize and schedule sampling task on service thread.
1738   _rem_set->initialize_sampling_task(service_thread());
1739 
1740   // Create and schedule the periodic gc task on the service thread.
1741   _periodic_gc_task = new G1PeriodicGCTask("Periodic GC Task");
1742   _service_thread->register_task(_periodic_gc_task);
1743 
1744   {
1745     G1DirtyCardQueueSet& dcqs = G1BarrierSet::dirty_card_queue_set();
1746     dcqs.set_process_cards_threshold(concurrent_refine()->yellow_zone());
1747     dcqs.set_max_cards(concurrent_refine()->red_zone());
1748   }
1749 
1750   // Here we allocate the dummy HeapRegion that is required by the
1751   // G1AllocRegion class.
1752   HeapRegion* dummy_region = _hrm.get_dummy_region();
1753 
1754   // We'll re-use the same region whether the alloc region will
1755   // require BOT updates or not and, if it doesn't, then a non-young
1756   // region will complain that it cannot support allocations without
1757   // BOT updates. So we'll tag the dummy region as eden to avoid that.
1758   dummy_region->set_eden();
1759   // Make sure it's full.
1760   dummy_region->set_top(dummy_region->end());
1761   G1AllocRegion::setup(this, dummy_region);
1762 
1763   _allocator->init_mutator_alloc_regions();
1764 
1765   // Do create of the monitoring and management support so that
1766   // values in the heap have been properly initialized.
1767   _g1mm = new G1MonitoringSupport(this);
1768 
1769   _preserved_marks_set.init(ParallelGCThreads);
1770 
1771   _collection_set.initialize(max_reserved_regions());
1772 
1773   _regions_failed_evacuation = NEW_C_HEAP_ARRAY(volatile bool, max_regions(), mtGC);
1774 
1775   G1InitLogger::print();
1776 
1777   return JNI_OK;
1778 }
1779 
1780 void G1CollectedHeap::stop() {
1781   // Stop all concurrent threads. We do this to make sure these threads
1782   // do not continue to execute and access resources (e.g. logging)
1783   // that are destroyed during shutdown.
1784   _cr->stop();
1785   _service_thread->stop();
1786   _cm_thread->stop();
1787 }
1788 
1789 void G1CollectedHeap::safepoint_synchronize_begin() {
1790   SuspendibleThreadSet::synchronize();
1791 }
1792 
1793 void G1CollectedHeap::safepoint_synchronize_end() {
1794   SuspendibleThreadSet::desynchronize();
1795 }
1796 
1797 void G1CollectedHeap::post_initialize() {
1798   CollectedHeap::post_initialize();
1799   ref_processing_init();
1800 }
1801 
1802 void G1CollectedHeap::ref_processing_init() {
1803   // Reference processing in G1 currently works as follows:
1804   //
1805   // * There are two reference processor instances. One is
1806   //   used to record and process discovered references
1807   //   during concurrent marking; the other is used to
1808   //   record and process references during STW pauses
1809   //   (both full and incremental).
1810   // * Both ref processors need to 'span' the entire heap as
1811   //   the regions in the collection set may be dotted around.
1812   //
1813   // * For the concurrent marking ref processor:
1814   //   * Reference discovery is enabled at concurrent start.
1815   //   * Reference discovery is disabled and the discovered
1816   //     references processed etc during remarking.
1817   //   * Reference discovery is MT (see below).
1818   //   * Reference discovery requires a barrier (see below).
1819   //   * Reference processing may or may not be MT
1820   //     (depending on the value of ParallelRefProcEnabled
1821   //     and ParallelGCThreads).
1822   //   * A full GC disables reference discovery by the CM
1823   //     ref processor and abandons any entries on it's
1824   //     discovered lists.
1825   //
1826   // * For the STW processor:
1827   //   * Non MT discovery is enabled at the start of a full GC.
1828   //   * Processing and enqueueing during a full GC is non-MT.
1829   //   * During a full GC, references are processed after marking.
1830   //
1831   //   * Discovery (may or may not be MT) is enabled at the start
1832   //     of an incremental evacuation pause.
1833   //   * References are processed near the end of a STW evacuation pause.
1834   //   * For both types of GC:
1835   //     * Discovery is atomic - i.e. not concurrent.
1836   //     * Reference discovery will not need a barrier.
1837 
1838   // Concurrent Mark ref processor
1839   _ref_processor_cm =
1840     new ReferenceProcessor(&_is_subject_to_discovery_cm,
1841                            ParallelGCThreads,                              // degree of mt processing
1842                            (ParallelGCThreads > 1) || (ConcGCThreads > 1), // mt discovery
1843                            MAX2(ParallelGCThreads, ConcGCThreads),         // degree of mt discovery
1844                            false,                                          // Reference discovery is not atomic
1845                            &_is_alive_closure_cm);                         // is alive closure
1846 
1847   // STW ref processor
1848   _ref_processor_stw =
1849     new ReferenceProcessor(&_is_subject_to_discovery_stw,
1850                            ParallelGCThreads,                    // degree of mt processing
1851                            (ParallelGCThreads > 1),              // mt discovery
1852                            ParallelGCThreads,                    // degree of mt discovery
1853                            true,                                 // Reference discovery is atomic
1854                            &_is_alive_closure_stw);              // is alive closure
1855 }
1856 
1857 SoftRefPolicy* G1CollectedHeap::soft_ref_policy() {
1858   return &_soft_ref_policy;
1859 }
1860 
1861 size_t G1CollectedHeap::capacity() const {
1862   return _hrm.length() * HeapRegion::GrainBytes;
1863 }
1864 
1865 size_t G1CollectedHeap::unused_committed_regions_in_bytes() const {
1866   return _hrm.total_free_bytes();
1867 }
1868 
1869 void G1CollectedHeap::iterate_hcc_closure(G1CardTableEntryClosure* cl, uint worker_id) {
1870   _hot_card_cache->drain(cl, worker_id);
1871 }
1872 
1873 // Computes the sum of the storage used by the various regions.
1874 size_t G1CollectedHeap::used() const {
1875   size_t result = _summary_bytes_used + _allocator->used_in_alloc_regions();
1876   if (_archive_allocator != NULL) {
1877     result += _archive_allocator->used();
1878   }
1879   return result;
1880 }
1881 
1882 size_t G1CollectedHeap::used_unlocked() const {
1883   return _summary_bytes_used;
1884 }
1885 
1886 class SumUsedClosure: public HeapRegionClosure {
1887   size_t _used;
1888 public:
1889   SumUsedClosure() : _used(0) {}
1890   bool do_heap_region(HeapRegion* r) {
1891     _used += r->used();
1892     return false;
1893   }
1894   size_t result() { return _used; }
1895 };
1896 
1897 size_t G1CollectedHeap::recalculate_used() const {
1898   SumUsedClosure blk;
1899   heap_region_iterate(&blk);
1900   return blk.result();
1901 }
1902 
1903 bool  G1CollectedHeap::is_user_requested_concurrent_full_gc(GCCause::Cause cause) {
1904   switch (cause) {
1905     case GCCause::_java_lang_system_gc:                 return ExplicitGCInvokesConcurrent;
1906     case GCCause::_dcmd_gc_run:                         return ExplicitGCInvokesConcurrent;
1907     case GCCause::_wb_conc_mark:                        return true;
1908     default :                                           return false;
1909   }
1910 }
1911 
1912 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
1913   switch (cause) {
1914     case GCCause::_g1_humongous_allocation: return true;
1915     case GCCause::_g1_periodic_collection:  return G1PeriodicGCInvokesConcurrent;
1916     case GCCause::_wb_breakpoint:           return true;
1917     default:                                return is_user_requested_concurrent_full_gc(cause);
1918   }
1919 }
1920 
1921 #ifndef PRODUCT
1922 void G1CollectedHeap::allocate_dummy_regions() {
1923   // Let's fill up most of the region
1924   size_t word_size = HeapRegion::GrainWords - 1024;
1925   // And as a result the region we'll allocate will be humongous.
1926   guarantee(is_humongous(word_size), "sanity");
1927 
1928   // _filler_array_max_size is set to humongous object threshold
1929   // but temporarily change it to use CollectedHeap::fill_with_object().
1930   AutoModifyRestore<size_t> temporarily(_filler_array_max_size, word_size);
1931 
1932   for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) {
1933     // Let's use the existing mechanism for the allocation
1934     HeapWord* dummy_obj = humongous_obj_allocate(word_size);
1935     if (dummy_obj != NULL) {
1936       MemRegion mr(dummy_obj, word_size);
1937       CollectedHeap::fill_with_object(mr);
1938     } else {
1939       // If we can't allocate once, we probably cannot allocate
1940       // again. Let's get out of the loop.
1941       break;
1942     }
1943   }
1944 }
1945 #endif // !PRODUCT
1946 
1947 void G1CollectedHeap::increment_old_marking_cycles_started() {
1948   assert(_old_marking_cycles_started == _old_marking_cycles_completed ||
1949          _old_marking_cycles_started == _old_marking_cycles_completed + 1,
1950          "Wrong marking cycle count (started: %d, completed: %d)",
1951          _old_marking_cycles_started, _old_marking_cycles_completed);
1952 
1953   _old_marking_cycles_started++;
1954 }
1955 
1956 void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent,
1957                                                              bool whole_heap_examined) {
1958   MonitorLocker ml(G1OldGCCount_lock, Mutex::_no_safepoint_check_flag);
1959 
1960   // We assume that if concurrent == true, then the caller is a
1961   // concurrent thread that was joined the Suspendible Thread
1962   // Set. If there's ever a cheap way to check this, we should add an
1963   // assert here.
1964 
1965   // Given that this method is called at the end of a Full GC or of a
1966   // concurrent cycle, and those can be nested (i.e., a Full GC can
1967   // interrupt a concurrent cycle), the number of full collections
1968   // completed should be either one (in the case where there was no
1969   // nesting) or two (when a Full GC interrupted a concurrent cycle)
1970   // behind the number of full collections started.
1971 
1972   // This is the case for the inner caller, i.e. a Full GC.
1973   assert(concurrent ||
1974          (_old_marking_cycles_started == _old_marking_cycles_completed + 1) ||
1975          (_old_marking_cycles_started == _old_marking_cycles_completed + 2),
1976          "for inner caller (Full GC): _old_marking_cycles_started = %u "
1977          "is inconsistent with _old_marking_cycles_completed = %u",
1978          _old_marking_cycles_started, _old_marking_cycles_completed);
1979 
1980   // This is the case for the outer caller, i.e. the concurrent cycle.
1981   assert(!concurrent ||
1982          (_old_marking_cycles_started == _old_marking_cycles_completed + 1),
1983          "for outer caller (concurrent cycle): "
1984          "_old_marking_cycles_started = %u "
1985          "is inconsistent with _old_marking_cycles_completed = %u",
1986          _old_marking_cycles_started, _old_marking_cycles_completed);
1987 
1988   _old_marking_cycles_completed += 1;
1989   if (whole_heap_examined) {
1990     // Signal that we have completed a visit to all live objects.
1991     record_whole_heap_examined_timestamp();
1992   }
1993 
1994   // We need to clear the "in_progress" flag in the CM thread before
1995   // we wake up any waiters (especially when ExplicitInvokesConcurrent
1996   // is set) so that if a waiter requests another System.gc() it doesn't
1997   // incorrectly see that a marking cycle is still in progress.
1998   if (concurrent) {
1999     _cm_thread->set_idle();
2000   }
2001 
2002   // Notify threads waiting in System.gc() (with ExplicitGCInvokesConcurrent)
2003   // for a full GC to finish that their wait is over.
2004   ml.notify_all();
2005 }
2006 
2007 void G1CollectedHeap::collect(GCCause::Cause cause) {
2008   try_collect(cause);
2009 }
2010 
2011 // Return true if (x < y) with allowance for wraparound.
2012 static bool gc_counter_less_than(uint x, uint y) {
2013   return (x - y) > (UINT_MAX/2);
2014 }
2015 
2016 // LOG_COLLECT_CONCURRENTLY(cause, msg, args...)
2017 // Macro so msg printing is format-checked.
2018 #define LOG_COLLECT_CONCURRENTLY(cause, ...)                            \
2019   do {                                                                  \
2020     LogTarget(Trace, gc) LOG_COLLECT_CONCURRENTLY_lt;                   \
2021     if (LOG_COLLECT_CONCURRENTLY_lt.is_enabled()) {                     \
2022       ResourceMark rm; /* For thread name. */                           \
2023       LogStream LOG_COLLECT_CONCURRENTLY_s(&LOG_COLLECT_CONCURRENTLY_lt); \
2024       LOG_COLLECT_CONCURRENTLY_s.print("%s: Try Collect Concurrently (%s): ", \
2025                                        Thread::current()->name(),       \
2026                                        GCCause::to_string(cause));      \
2027       LOG_COLLECT_CONCURRENTLY_s.print(__VA_ARGS__);                    \
2028     }                                                                   \
2029   } while (0)
2030 
2031 #define LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, result) \
2032   LOG_COLLECT_CONCURRENTLY(cause, "complete %s", BOOL_TO_STR(result))
2033 
2034 bool G1CollectedHeap::try_collect_concurrently(GCCause::Cause cause,
2035                                                uint gc_counter,
2036                                                uint old_marking_started_before) {
2037   assert_heap_not_locked();
2038   assert(should_do_concurrent_full_gc(cause),
2039          "Non-concurrent cause %s", GCCause::to_string(cause));
2040 
2041   for (uint i = 1; true; ++i) {
2042     // Try to schedule concurrent start evacuation pause that will
2043     // start a concurrent cycle.
2044     LOG_COLLECT_CONCURRENTLY(cause, "attempt %u", i);
2045     VM_G1TryInitiateConcMark op(gc_counter,
2046                                 cause,
2047                                 policy()->max_pause_time_ms());
2048     VMThread::execute(&op);
2049 
2050     // Request is trivially finished.
2051     if (cause == GCCause::_g1_periodic_collection) {
2052       LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, op.gc_succeeded());
2053       return op.gc_succeeded();
2054     }
2055 
2056     // If VMOp skipped initiating concurrent marking cycle because
2057     // we're terminating, then we're done.
2058     if (op.terminating()) {
2059       LOG_COLLECT_CONCURRENTLY(cause, "skipped: terminating");
2060       return false;
2061     }
2062 
2063     // Lock to get consistent set of values.
2064     uint old_marking_started_after;
2065     uint old_marking_completed_after;
2066     {
2067       MutexLocker ml(Heap_lock);
2068       // Update gc_counter for retrying VMOp if needed. Captured here to be
2069       // consistent with the values we use below for termination tests.  If
2070       // a retry is needed after a possible wait, and another collection
2071       // occurs in the meantime, it will cause our retry to be skipped and
2072       // we'll recheck for termination with updated conditions from that
2073       // more recent collection.  That's what we want, rather than having
2074       // our retry possibly perform an unnecessary collection.
2075       gc_counter = total_collections();
2076       old_marking_started_after = _old_marking_cycles_started;
2077       old_marking_completed_after = _old_marking_cycles_completed;
2078     }
2079 
2080     if (cause == GCCause::_wb_breakpoint) {
2081       if (op.gc_succeeded()) {
2082         LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
2083         return true;
2084       }
2085       // When _wb_breakpoint there can't be another cycle or deferred.
2086       assert(!op.cycle_already_in_progress(), "invariant");
2087       assert(!op.whitebox_attached(), "invariant");
2088       // Concurrent cycle attempt might have been cancelled by some other
2089       // collection, so retry.  Unlike other cases below, we want to retry
2090       // even if cancelled by a STW full collection, because we really want
2091       // to start a concurrent cycle.
2092       if (old_marking_started_before != old_marking_started_after) {
2093         LOG_COLLECT_CONCURRENTLY(cause, "ignoring STW full GC");
2094         old_marking_started_before = old_marking_started_after;
2095       }
2096     } else if (!GCCause::is_user_requested_gc(cause)) {
2097       // For an "automatic" (not user-requested) collection, we just need to
2098       // ensure that progress is made.
2099       //
2100       // Request is finished if any of
2101       // (1) the VMOp successfully performed a GC,
2102       // (2) a concurrent cycle was already in progress,
2103       // (3) whitebox is controlling concurrent cycles,
2104       // (4) a new cycle was started (by this thread or some other), or
2105       // (5) a Full GC was performed.
2106       // Cases (4) and (5) are detected together by a change to
2107       // _old_marking_cycles_started.
2108       //
2109       // Note that (1) does not imply (4).  If we're still in the mixed
2110       // phase of an earlier concurrent collection, the request to make the
2111       // collection a concurrent start won't be honored.  If we don't check for
2112       // both conditions we'll spin doing back-to-back collections.
2113       if (op.gc_succeeded() ||
2114           op.cycle_already_in_progress() ||
2115           op.whitebox_attached() ||
2116           (old_marking_started_before != old_marking_started_after)) {
2117         LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
2118         return true;
2119       }
2120     } else {                    // User-requested GC.
2121       // For a user-requested collection, we want to ensure that a complete
2122       // full collection has been performed before returning, but without
2123       // waiting for more than needed.
2124 
2125       // For user-requested GCs (unlike non-UR), a successful VMOp implies a
2126       // new cycle was started.  That's good, because it's not clear what we
2127       // should do otherwise.  Trying again just does back to back GCs.
2128       // Can't wait for someone else to start a cycle.  And returning fails
2129       // to meet the goal of ensuring a full collection was performed.
2130       assert(!op.gc_succeeded() ||
2131              (old_marking_started_before != old_marking_started_after),
2132              "invariant: succeeded %s, started before %u, started after %u",
2133              BOOL_TO_STR(op.gc_succeeded()),
2134              old_marking_started_before, old_marking_started_after);
2135 
2136       // Request is finished if a full collection (concurrent or stw)
2137       // was started after this request and has completed, e.g.
2138       // started_before < completed_after.
2139       if (gc_counter_less_than(old_marking_started_before,
2140                                old_marking_completed_after)) {
2141         LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
2142         return true;
2143       }
2144 
2145       if (old_marking_started_after != old_marking_completed_after) {
2146         // If there is an in-progress cycle (possibly started by us), then
2147         // wait for that cycle to complete, e.g.
2148         // while completed_now < started_after.
2149         LOG_COLLECT_CONCURRENTLY(cause, "wait");
2150         MonitorLocker ml(G1OldGCCount_lock);
2151         while (gc_counter_less_than(_old_marking_cycles_completed,
2152                                     old_marking_started_after)) {
2153           ml.wait();
2154         }
2155         // Request is finished if the collection we just waited for was
2156         // started after this request.
2157         if (old_marking_started_before != old_marking_started_after) {
2158           LOG_COLLECT_CONCURRENTLY(cause, "complete after wait");
2159           return true;
2160         }
2161       }
2162 
2163       // If VMOp was successful then it started a new cycle that the above
2164       // wait &etc should have recognized as finishing this request.  This
2165       // differs from a non-user-request, where gc_succeeded does not imply
2166       // a new cycle was started.
2167       assert(!op.gc_succeeded(), "invariant");
2168 
2169       if (op.cycle_already_in_progress()) {
2170         // If VMOp failed because a cycle was already in progress, it
2171         // is now complete.  But it didn't finish this user-requested
2172         // GC, so try again.
2173         LOG_COLLECT_CONCURRENTLY(cause, "retry after in-progress");
2174         continue;
2175       } else if (op.whitebox_attached()) {
2176         // If WhiteBox wants control, wait for notification of a state
2177         // change in the controller, then try again.  Don't wait for
2178         // release of control, since collections may complete while in
2179         // control.  Note: This won't recognize a STW full collection
2180         // while waiting; we can't wait on multiple monitors.
2181         LOG_COLLECT_CONCURRENTLY(cause, "whitebox control stall");
2182         MonitorLocker ml(ConcurrentGCBreakpoints::monitor());
2183         if (ConcurrentGCBreakpoints::is_controlled()) {
2184           ml.wait();
2185         }
2186         continue;
2187       }
2188     }
2189 
2190     // Collection failed and should be retried.
2191     assert(op.transient_failure(), "invariant");
2192 
2193     if (GCLocker::is_active_and_needs_gc()) {
2194       // If GCLocker is active, wait until clear before retrying.
2195       LOG_COLLECT_CONCURRENTLY(cause, "gc-locker stall");
2196       GCLocker::stall_until_clear();
2197     }
2198 
2199     LOG_COLLECT_CONCURRENTLY(cause, "retry");
2200   }
2201 }
2202 
2203 bool G1CollectedHeap::try_collect(GCCause::Cause cause) {
2204   assert_heap_not_locked();
2205 
2206   // Lock to get consistent set of values.
2207   uint gc_count_before;
2208   uint full_gc_count_before;
2209   uint old_marking_started_before;
2210   {
2211     MutexLocker ml(Heap_lock);
2212     gc_count_before = total_collections();
2213     full_gc_count_before = total_full_collections();
2214     old_marking_started_before = _old_marking_cycles_started;
2215   }
2216 
2217   if (should_do_concurrent_full_gc(cause)) {
2218     return try_collect_concurrently(cause,
2219                                     gc_count_before,
2220                                     old_marking_started_before);
2221   } else if (GCLocker::should_discard(cause, gc_count_before)) {
2222     // Indicate failure to be consistent with VMOp failure due to
2223     // another collection slipping in after our gc_count but before
2224     // our request is processed.
2225     return false;
2226   } else if (cause == GCCause::_gc_locker || cause == GCCause::_wb_young_gc
2227              DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) {
2228 
2229     // Schedule a standard evacuation pause. We're setting word_size
2230     // to 0 which means that we are not requesting a post-GC allocation.
2231     VM_G1CollectForAllocation op(0,     /* word_size */
2232                                  gc_count_before,
2233                                  cause,
2234                                  policy()->max_pause_time_ms());
2235     VMThread::execute(&op);
2236     return op.gc_succeeded();
2237   } else {
2238     // Schedule a Full GC.
2239     VM_G1CollectFull op(gc_count_before, full_gc_count_before, cause);
2240     VMThread::execute(&op);
2241     return op.gc_succeeded();
2242   }
2243 }
2244 
2245 bool G1CollectedHeap::is_in(const void* p) const {
2246   return is_in_reserved(p) && _hrm.is_available(addr_to_region((HeapWord*)p));
2247 }
2248 
2249 // Iteration functions.
2250 
2251 // Iterates an ObjectClosure over all objects within a HeapRegion.
2252 
2253 class IterateObjectClosureRegionClosure: public HeapRegionClosure {
2254   ObjectClosure* _cl;
2255 public:
2256   IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
2257   bool do_heap_region(HeapRegion* r) {
2258     if (!r->is_continues_humongous()) {
2259       r->object_iterate(_cl);
2260     }
2261     return false;
2262   }
2263 };
2264 
2265 void G1CollectedHeap::object_iterate(ObjectClosure* cl) {
2266   IterateObjectClosureRegionClosure blk(cl);
2267   heap_region_iterate(&blk);
2268 }
2269 
2270 class G1ParallelObjectIterator : public ParallelObjectIteratorImpl {
2271 private:
2272   G1CollectedHeap*  _heap;
2273   HeapRegionClaimer _claimer;
2274 
2275 public:
2276   G1ParallelObjectIterator(uint thread_num) :
2277       _heap(G1CollectedHeap::heap()),
2278       _claimer(thread_num == 0 ? G1CollectedHeap::heap()->workers()->active_workers() : thread_num) {}
2279 
2280   virtual void object_iterate(ObjectClosure* cl, uint worker_id) {
2281     _heap->object_iterate_parallel(cl, worker_id, &_claimer);
2282   }
2283 };
2284 
2285 ParallelObjectIteratorImpl* G1CollectedHeap::parallel_object_iterator(uint thread_num) {
2286   return new G1ParallelObjectIterator(thread_num);
2287 }
2288 
2289 void G1CollectedHeap::object_iterate_parallel(ObjectClosure* cl, uint worker_id, HeapRegionClaimer* claimer) {
2290   IterateObjectClosureRegionClosure blk(cl);
2291   heap_region_par_iterate_from_worker_offset(&blk, claimer, worker_id);
2292 }
2293 
2294 void G1CollectedHeap::keep_alive(oop obj) {
2295   G1BarrierSet::enqueue_preloaded(obj);
2296 }
2297 
2298 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const {
2299   _hrm.iterate(cl);
2300 }
2301 
2302 void G1CollectedHeap::heap_region_par_iterate_from_worker_offset(HeapRegionClosure* cl,
2303                                                                  HeapRegionClaimer *hrclaimer,
2304                                                                  uint worker_id) const {
2305   _hrm.par_iterate(cl, hrclaimer, hrclaimer->offset_for_worker(worker_id));
2306 }
2307 
2308 void G1CollectedHeap::heap_region_par_iterate_from_start(HeapRegionClosure* cl,
2309                                                          HeapRegionClaimer *hrclaimer) const {
2310   _hrm.par_iterate(cl, hrclaimer, 0);
2311 }
2312 
2313 void G1CollectedHeap::collection_set_iterate_all(HeapRegionClosure* cl) {
2314   _collection_set.iterate(cl);
2315 }
2316 
2317 void G1CollectedHeap::collection_set_par_iterate_all(HeapRegionClosure* cl, HeapRegionClaimer* hr_claimer, uint worker_id) {
2318   _collection_set.par_iterate(cl, hr_claimer, worker_id, workers()->active_workers());
2319 }
2320 
2321 void G1CollectedHeap::collection_set_iterate_increment_from(HeapRegionClosure *cl, HeapRegionClaimer* hr_claimer, uint worker_id) {
2322   _collection_set.iterate_incremental_part_from(cl, hr_claimer, worker_id, workers()->active_workers());
2323 }
2324 
2325 HeapWord* G1CollectedHeap::block_start(const void* addr) const {
2326   HeapRegion* hr = heap_region_containing(addr);
2327   return hr->block_start(addr);
2328 }
2329 
2330 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
2331   HeapRegion* hr = heap_region_containing(addr);
2332   return hr->block_is_obj(addr);
2333 }
2334 
2335 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {
2336   return (_policy->young_list_target_length() - _survivor.length()) * HeapRegion::GrainBytes;
2337 }
2338 
2339 size_t G1CollectedHeap::tlab_used(Thread* ignored) const {
2340   return _eden.length() * HeapRegion::GrainBytes;
2341 }
2342 
2343 // For G1 TLABs should not contain humongous objects, so the maximum TLAB size
2344 // must be equal to the humongous object limit.
2345 size_t G1CollectedHeap::max_tlab_size() const {
2346   return align_down(_humongous_object_threshold_in_words, MinObjAlignment);
2347 }
2348 
2349 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {
2350   return _allocator->unsafe_max_tlab_alloc();
2351 }
2352 
2353 size_t G1CollectedHeap::max_capacity() const {
2354   return max_regions() * HeapRegion::GrainBytes;
2355 }
2356 
2357 void G1CollectedHeap::prepare_for_verify() {
2358   _verifier->prepare_for_verify();
2359 }
2360 
2361 void G1CollectedHeap::verify(VerifyOption vo) {
2362   _verifier->verify(vo);
2363 }
2364 
2365 bool G1CollectedHeap::supports_concurrent_gc_breakpoints() const {
2366   return true;
2367 }
2368 
2369 bool G1CollectedHeap::is_archived_object(oop object) const {
2370   return object != NULL && heap_region_containing(object)->is_archive();
2371 }
2372 
2373 class PrintRegionClosure: public HeapRegionClosure {
2374   outputStream* _st;
2375 public:
2376   PrintRegionClosure(outputStream* st) : _st(st) {}
2377   bool do_heap_region(HeapRegion* r) {
2378     r->print_on(_st);
2379     return false;
2380   }
2381 };
2382 
2383 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
2384                                        const HeapRegion* hr,
2385                                        const VerifyOption vo) const {
2386   switch (vo) {
2387   case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj, hr);
2388   case VerifyOption_G1UseNextMarking: return is_obj_ill(obj, hr);
2389   case VerifyOption_G1UseFullMarking: return is_obj_dead_full(obj, hr);
2390   default:                            ShouldNotReachHere();
2391   }
2392   return false; // keep some compilers happy
2393 }
2394 
2395 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
2396                                        const VerifyOption vo) const {
2397   switch (vo) {
2398   case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj);
2399   case VerifyOption_G1UseNextMarking: return is_obj_ill(obj);
2400   case VerifyOption_G1UseFullMarking: return is_obj_dead_full(obj);
2401   default:                            ShouldNotReachHere();
2402   }
2403   return false; // keep some compilers happy
2404 }
2405 
2406 void G1CollectedHeap::print_heap_regions() const {
2407   LogTarget(Trace, gc, heap, region) lt;
2408   if (lt.is_enabled()) {
2409     LogStream ls(lt);
2410     print_regions_on(&ls);
2411   }
2412 }
2413 
2414 void G1CollectedHeap::print_on(outputStream* st) const {
2415   size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked();
2416   st->print(" %-20s", "garbage-first heap");
2417   st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",
2418             capacity()/K, heap_used/K);
2419   st->print(" [" PTR_FORMAT ", " PTR_FORMAT ")",
2420             p2i(_hrm.reserved().start()),
2421             p2i(_hrm.reserved().end()));
2422   st->cr();
2423   st->print("  region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K);
2424   uint young_regions = young_regions_count();
2425   st->print("%u young (" SIZE_FORMAT "K), ", young_regions,
2426             (size_t) young_regions * HeapRegion::GrainBytes / K);
2427   uint survivor_regions = survivor_regions_count();
2428   st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions,
2429             (size_t) survivor_regions * HeapRegion::GrainBytes / K);
2430   st->cr();
2431   if (_numa->is_enabled()) {
2432     uint num_nodes = _numa->num_active_nodes();
2433     st->print("  remaining free region(s) on each NUMA node: ");
2434     const int* node_ids = _numa->node_ids();
2435     for (uint node_index = 0; node_index < num_nodes; node_index++) {
2436       uint num_free_regions = _hrm.num_free_regions(node_index);
2437       st->print("%d=%u ", node_ids[node_index], num_free_regions);
2438     }
2439     st->cr();
2440   }
2441   MetaspaceUtils::print_on(st);
2442 }
2443 
2444 void G1CollectedHeap::print_regions_on(outputStream* st) const {
2445   st->print_cr("Heap Regions: E=young(eden), S=young(survivor), O=old, "
2446                "HS=humongous(starts), HC=humongous(continues), "
2447                "CS=collection set, F=free, "
2448                "OA=open archive, CA=closed archive, "
2449                "TAMS=top-at-mark-start (previous, next)");
2450   PrintRegionClosure blk(st);
2451   heap_region_iterate(&blk);
2452 }
2453 
2454 void G1CollectedHeap::print_extended_on(outputStream* st) const {
2455   print_on(st);
2456 
2457   // Print the per-region information.
2458   st->cr();
2459   print_regions_on(st);
2460 }
2461 
2462 void G1CollectedHeap::print_on_error(outputStream* st) const {
2463   this->CollectedHeap::print_on_error(st);
2464 
2465   if (_cm != NULL) {
2466     st->cr();
2467     _cm->print_on_error(st);
2468   }
2469 }
2470 
2471 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
2472   workers()->threads_do(tc);
2473   tc->do_thread(_cm_thread);
2474   _cm->threads_do(tc);
2475   _cr->threads_do(tc);
2476   tc->do_thread(_service_thread);
2477 }
2478 
2479 void G1CollectedHeap::print_tracing_info() const {
2480   rem_set()->print_summary_info();
2481   concurrent_mark()->print_summary_info();
2482 }
2483 
2484 #ifndef PRODUCT
2485 // Helpful for debugging RSet issues.
2486 
2487 class PrintRSetsClosure : public HeapRegionClosure {
2488 private:
2489   const char* _msg;
2490   size_t _occupied_sum;
2491 
2492 public:
2493   bool do_heap_region(HeapRegion* r) {
2494     HeapRegionRemSet* hrrs = r->rem_set();
2495     size_t occupied = hrrs->occupied();
2496     _occupied_sum += occupied;
2497 
2498     tty->print_cr("Printing RSet for region " HR_FORMAT, HR_FORMAT_PARAMS(r));
2499     if (occupied == 0) {
2500       tty->print_cr("  RSet is empty");
2501     } else {
2502       hrrs->print();
2503     }
2504     tty->print_cr("----------");
2505     return false;
2506   }
2507 
2508   PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) {
2509     tty->cr();
2510     tty->print_cr("========================================");
2511     tty->print_cr("%s", msg);
2512     tty->cr();
2513   }
2514 
2515   ~PrintRSetsClosure() {
2516     tty->print_cr("Occupied Sum: " SIZE_FORMAT, _occupied_sum);
2517     tty->print_cr("========================================");
2518     tty->cr();
2519   }
2520 };
2521 
2522 void G1CollectedHeap::print_cset_rsets() {
2523   PrintRSetsClosure cl("Printing CSet RSets");
2524   collection_set_iterate_all(&cl);
2525 }
2526 
2527 void G1CollectedHeap::print_all_rsets() {
2528   PrintRSetsClosure cl("Printing All RSets");;
2529   heap_region_iterate(&cl);
2530 }
2531 #endif // PRODUCT
2532 
2533 bool G1CollectedHeap::print_location(outputStream* st, void* addr) const {
2534   return BlockLocationPrinter<G1CollectedHeap>::print_location(st, addr);
2535 }
2536 
2537 G1HeapSummary G1CollectedHeap::create_g1_heap_summary() {
2538 
2539   size_t eden_used_bytes = _eden.used_bytes();
2540   size_t survivor_used_bytes = _survivor.used_bytes();
2541   size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked();
2542 
2543   size_t eden_capacity_bytes =
2544     (policy()->young_list_target_length() * HeapRegion::GrainBytes) - survivor_used_bytes;
2545 
2546   VirtualSpaceSummary heap_summary = create_heap_space_summary();
2547   return G1HeapSummary(heap_summary, heap_used, eden_used_bytes,
2548                        eden_capacity_bytes, survivor_used_bytes, num_regions());
2549 }
2550 
2551 G1EvacSummary G1CollectedHeap::create_g1_evac_summary(G1EvacStats* stats) {
2552   return G1EvacSummary(stats->allocated(), stats->wasted(), stats->undo_wasted(),
2553                        stats->unused(), stats->used(), stats->region_end_waste(),
2554                        stats->regions_filled(), stats->direct_allocated(),
2555                        stats->failure_used(), stats->failure_waste());
2556 }
2557 
2558 void G1CollectedHeap::trace_heap(GCWhen::Type when, const GCTracer* gc_tracer) {
2559   const G1HeapSummary& heap_summary = create_g1_heap_summary();
2560   gc_tracer->report_gc_heap_summary(when, heap_summary);
2561 
2562   const MetaspaceSummary& metaspace_summary = create_metaspace_summary();
2563   gc_tracer->report_metaspace_summary(when, metaspace_summary);
2564 }
2565 
2566 void G1CollectedHeap::gc_prologue(bool full) {
2567   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
2568 
2569   // This summary needs to be printed before incrementing total collections.
2570   rem_set()->print_periodic_summary_info("Before GC RS summary", total_collections());
2571 
2572   // Update common counters.
2573   increment_total_collections(full /* full gc */);
2574   if (full || collector_state()->in_concurrent_start_gc()) {
2575     increment_old_marking_cycles_started();
2576   }
2577 
2578   // Fill TLAB's and such
2579   {
2580     Ticks start = Ticks::now();
2581     ensure_parsability(true);
2582     Tickspan dt = Ticks::now() - start;
2583     phase_times()->record_prepare_tlab_time_ms(dt.seconds() * MILLIUNITS);
2584   }
2585 
2586   if (!full) {
2587     // Flush dirty card queues to qset, so later phases don't need to account
2588     // for partially filled per-thread queues and such.  Not needed for full
2589     // collections, which ignore those logs.
2590     Ticks start = Ticks::now();
2591     G1BarrierSet::dirty_card_queue_set().concatenate_logs();
2592     Tickspan dt = Ticks::now() - start;
2593     phase_times()->record_concatenate_dirty_card_logs_time_ms(dt.seconds() * MILLIUNITS);
2594   }
2595 }
2596 
2597 void G1CollectedHeap::gc_epilogue(bool full) {
2598   // Update common counters.
2599   if (full) {
2600     // Update the number of full collections that have been completed.
2601     increment_old_marking_cycles_completed(false /* concurrent */, true /* liveness_completed */);
2602   }
2603 
2604   // We are at the end of the GC. Total collections has already been increased.
2605   rem_set()->print_periodic_summary_info("After GC RS summary", total_collections() - 1);
2606 
2607 #if COMPILER2_OR_JVMCI
2608   assert(DerivedPointerTable::is_empty(), "derived pointer present");
2609 #endif
2610 
2611   double start = os::elapsedTime();
2612   resize_all_tlabs();
2613   phase_times()->record_resize_tlab_time_ms((os::elapsedTime() - start) * 1000.0);
2614 
2615   MemoryService::track_memory_usage();
2616   // We have just completed a GC. Update the soft reference
2617   // policy with the new heap occupancy
2618   Universe::heap()->update_capacity_and_used_at_gc();
2619 
2620   // Print NUMA statistics.
2621   _numa->print_statistics();
2622 
2623   _collection_pause_end = Ticks::now();
2624 }
2625 
2626 uint G1CollectedHeap::uncommit_regions(uint region_limit) {
2627   return _hrm.uncommit_inactive_regions(region_limit);
2628 }
2629 
2630 bool G1CollectedHeap::has_uncommittable_regions() {
2631   return _hrm.has_inactive_regions();
2632 }
2633 
2634 void G1CollectedHeap::uncommit_regions_if_necessary() {
2635   if (has_uncommittable_regions()) {
2636     G1UncommitRegionTask::enqueue();
2637   }
2638 }
2639 
2640 void G1CollectedHeap::verify_numa_regions(const char* desc) {
2641   LogTarget(Trace, gc, heap, verify) lt;
2642 
2643   if (lt.is_enabled()) {
2644     LogStream ls(lt);
2645     // Iterate all heap regions to print matching between preferred numa id and actual numa id.
2646     G1NodeIndexCheckClosure cl(desc, _numa, &ls);
2647     heap_region_iterate(&cl);
2648   }
2649 }
2650 
2651 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
2652                                                uint gc_count_before,
2653                                                bool* succeeded,
2654                                                GCCause::Cause gc_cause) {
2655   assert_heap_not_locked_and_not_at_safepoint();
2656   VM_G1CollectForAllocation op(word_size,
2657                                gc_count_before,
2658                                gc_cause,
2659                                policy()->max_pause_time_ms());
2660   VMThread::execute(&op);
2661 
2662   HeapWord* result = op.result();
2663   bool ret_succeeded = op.prologue_succeeded() && op.gc_succeeded();
2664   assert(result == NULL || ret_succeeded,
2665          "the result should be NULL if the VM did not succeed");
2666   *succeeded = ret_succeeded;
2667 
2668   assert_heap_not_locked();
2669   return result;
2670 }
2671 
2672 void G1CollectedHeap::start_concurrent_cycle(bool concurrent_operation_is_full_mark) {
2673   assert(!_cm_thread->in_progress(), "Can not start concurrent operation while in progress");
2674 
2675   MutexLocker x(CGC_lock, Mutex::_no_safepoint_check_flag);
2676   if (concurrent_operation_is_full_mark) {
2677     _cm->post_concurrent_mark_start();
2678     _cm_thread->start_full_mark();
2679   } else {
2680     _cm->post_concurrent_undo_start();
2681     _cm_thread->start_undo_mark();
2682   }
2683   CGC_lock->notify();
2684 }
2685 
2686 bool G1CollectedHeap::is_potential_eager_reclaim_candidate(HeapRegion* r) const {
2687   // We don't nominate objects with many remembered set entries, on
2688   // the assumption that such objects are likely still live.
2689   HeapRegionRemSet* rem_set = r->rem_set();
2690 
2691   return G1EagerReclaimHumongousObjectsWithStaleRefs ?
2692          rem_set->occupancy_less_or_equal_than(G1EagerReclaimRemSetThreshold) :
2693          G1EagerReclaimHumongousObjects && rem_set->is_empty();
2694 }
2695 
2696 #ifndef PRODUCT
2697 void G1CollectedHeap::verify_region_attr_remset_update() {
2698   class VerifyRegionAttrRemSet : public HeapRegionClosure {
2699   public:
2700     virtual bool do_heap_region(HeapRegion* r) {
2701       G1CollectedHeap* g1h = G1CollectedHeap::heap();
2702       bool const needs_remset_update = g1h->region_attr(r->bottom()).needs_remset_update();
2703       assert(r->rem_set()->is_tracked() == needs_remset_update,
2704              "Region %u remset tracking status (%s) different to region attribute (%s)",
2705              r->hrm_index(), BOOL_TO_STR(r->rem_set()->is_tracked()), BOOL_TO_STR(needs_remset_update));
2706       return false;
2707     }
2708   } cl;
2709   heap_region_iterate(&cl);
2710 }
2711 #endif
2712 
2713 class VerifyRegionRemSetClosure : public HeapRegionClosure {
2714   public:
2715     bool do_heap_region(HeapRegion* hr) {
2716       if (!hr->is_archive() && !hr->is_continues_humongous()) {
2717         hr->verify_rem_set();
2718       }
2719       return false;
2720     }
2721 };
2722 
2723 uint G1CollectedHeap::num_task_queues() const {
2724   return _task_queues->size();
2725 }
2726 
2727 #if TASKQUEUE_STATS
2728 void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) {
2729   st->print_raw_cr("GC Task Stats");
2730   st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();
2731   st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();
2732 }
2733 
2734 void G1CollectedHeap::print_taskqueue_stats() const {
2735   if (!log_is_enabled(Trace, gc, task, stats)) {
2736     return;
2737   }
2738   Log(gc, task, stats) log;
2739   ResourceMark rm;
2740   LogStream ls(log.trace());
2741   outputStream* st = &ls;
2742 
2743   print_taskqueue_stats_hdr(st);
2744 
2745   TaskQueueStats totals;
2746   const uint n = num_task_queues();
2747   for (uint i = 0; i < n; ++i) {
2748     st->print("%3u ", i); task_queue(i)->stats.print(st); st->cr();
2749     totals += task_queue(i)->stats;
2750   }
2751   st->print_raw("tot "); totals.print(st); st->cr();
2752 
2753   DEBUG_ONLY(totals.verify());
2754 }
2755 
2756 void G1CollectedHeap::reset_taskqueue_stats() {
2757   const uint n = num_task_queues();
2758   for (uint i = 0; i < n; ++i) {
2759     task_queue(i)->stats.reset();
2760   }
2761 }
2762 #endif // TASKQUEUE_STATS
2763 
2764 void G1CollectedHeap::wait_for_root_region_scanning() {
2765   double scan_wait_start = os::elapsedTime();
2766   // We have to wait until the CM threads finish scanning the
2767   // root regions as it's the only way to ensure that all the
2768   // objects on them have been correctly scanned before we start
2769   // moving them during the GC.
2770   bool waited = _cm->root_regions()->wait_until_scan_finished();
2771   double wait_time_ms = 0.0;
2772   if (waited) {
2773     double scan_wait_end = os::elapsedTime();
2774     wait_time_ms = (scan_wait_end - scan_wait_start) * 1000.0;
2775   }
2776   phase_times()->record_root_region_scan_wait_time(wait_time_ms);
2777 }
2778 
2779 class G1PrintCollectionSetClosure : public HeapRegionClosure {
2780 private:
2781   G1HRPrinter* _hr_printer;
2782 public:
2783   G1PrintCollectionSetClosure(G1HRPrinter* hr_printer) : HeapRegionClosure(), _hr_printer(hr_printer) { }
2784 
2785   virtual bool do_heap_region(HeapRegion* r) {
2786     _hr_printer->cset(r);
2787     return false;
2788   }
2789 };
2790 
2791 void G1CollectedHeap::start_new_collection_set() {
2792   double start = os::elapsedTime();
2793 
2794   collection_set()->start_incremental_building();
2795 
2796   clear_region_attr();
2797 
2798   guarantee(_eden.length() == 0, "eden should have been cleared");
2799   policy()->transfer_survivors_to_cset(survivor());
2800 
2801   // We redo the verification but now wrt to the new CSet which
2802   // has just got initialized after the previous CSet was freed.
2803   _cm->verify_no_collection_set_oops();
2804 
2805   phase_times()->record_start_new_cset_time_ms((os::elapsedTime() - start) * 1000.0);
2806 }
2807 
2808 void G1CollectedHeap::calculate_collection_set(G1EvacuationInfo& evacuation_info, double target_pause_time_ms) {
2809 
2810   _collection_set.finalize_initial_collection_set(target_pause_time_ms, &_survivor);
2811   evacuation_info.set_collectionset_regions(collection_set()->region_length() +
2812                                             collection_set()->optional_region_length());
2813 
2814   _cm->verify_no_collection_set_oops();
2815 
2816   if (_hr_printer.is_active()) {
2817     G1PrintCollectionSetClosure cl(&_hr_printer);
2818     _collection_set.iterate(&cl);
2819     _collection_set.iterate_optional(&cl);
2820   }
2821 }
2822 
2823 G1HeapVerifier::G1VerifyType G1CollectedHeap::young_collection_verify_type() const {
2824   if (collector_state()->in_concurrent_start_gc()) {
2825     return G1HeapVerifier::G1VerifyConcurrentStart;
2826   } else if (collector_state()->in_young_only_phase()) {
2827     return G1HeapVerifier::G1VerifyYoungNormal;
2828   } else {
2829     return G1HeapVerifier::G1VerifyMixed;
2830   }
2831 }
2832 
2833 void G1CollectedHeap::verify_before_young_collection(G1HeapVerifier::G1VerifyType type) {
2834   if (VerifyRememberedSets) {
2835     log_info(gc, verify)("[Verifying RemSets before GC]");
2836     VerifyRegionRemSetClosure v_cl;
2837     heap_region_iterate(&v_cl);
2838   }
2839   _verifier->verify_before_gc(type);
2840   _verifier->check_bitmaps("GC Start");
2841   verify_numa_regions("GC Start");
2842 }
2843 
2844 void G1CollectedHeap::verify_after_young_collection(G1HeapVerifier::G1VerifyType type) {
2845   if (VerifyRememberedSets) {
2846     log_info(gc, verify)("[Verifying RemSets after GC]");
2847     VerifyRegionRemSetClosure v_cl;
2848     heap_region_iterate(&v_cl);
2849   }
2850   _verifier->verify_after_gc(type);
2851   _verifier->check_bitmaps("GC End");
2852   verify_numa_regions("GC End");
2853 }
2854 
2855 void G1CollectedHeap::expand_heap_after_young_collection(){
2856   size_t expand_bytes = _heap_sizing_policy->young_collection_expansion_amount();
2857   if (expand_bytes > 0) {
2858     // No need for an ergo logging here,
2859     // expansion_amount() does this when it returns a value > 0.
2860     double expand_ms = 0.0;
2861     if (!expand(expand_bytes, _workers, &expand_ms)) {
2862       // We failed to expand the heap. Cannot do anything about it.
2863     }
2864     phase_times()->record_expand_heap_time(expand_ms);
2865   }
2866 }
2867 
2868 void G1CollectedHeap::set_young_gc_name(char* young_gc_name) {
2869   G1GCPauseType pause_type =
2870     // The strings for all Concurrent Start pauses are the same, so the parameter
2871     // does not matter here.
2872     collector_state()->young_gc_pause_type(false /* concurrent_operation_is_full_mark */);
2873   snprintf(young_gc_name,
2874            MaxYoungGCNameLength,
2875            "Pause Young (%s)",
2876            G1GCPauseTypeHelper::to_string(pause_type));
2877 }
2878 
2879 bool G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
2880   assert_at_safepoint_on_vm_thread();
2881   guarantee(!is_gc_active(), "collection is not reentrant");
2882 
2883   if (GCLocker::check_active_before_gc()) {
2884     return false;
2885   }
2886 
2887   do_collection_pause_at_safepoint_helper(target_pause_time_ms);
2888   return true;
2889 }
2890 
2891 void G1CollectedHeap::gc_tracer_report_gc_start() {
2892   _gc_timer_stw->register_gc_start();
2893   _gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());
2894 }
2895 
2896 void G1CollectedHeap::gc_tracer_report_gc_end(bool concurrent_operation_is_full_mark,
2897                                               G1EvacuationInfo& evacuation_info) {
2898   _gc_tracer_stw->report_evacuation_info(&evacuation_info);
2899   _gc_tracer_stw->report_tenuring_threshold(_policy->tenuring_threshold());
2900 
2901   _gc_timer_stw->register_gc_end();
2902   _gc_tracer_stw->report_gc_end(_gc_timer_stw->gc_end(),
2903   _gc_timer_stw->time_partitions());
2904 }
2905 
2906 void G1CollectedHeap::do_collection_pause_at_safepoint_helper(double target_pause_time_ms) {
2907   GCIdMark gc_id_mark;
2908 
2909   SvcGCMarker sgcm(SvcGCMarker::MINOR);
2910   ResourceMark rm;
2911 
2912   policy()->note_gc_start();
2913 
2914   gc_tracer_report_gc_start();
2915 
2916   wait_for_root_region_scanning();
2917 
2918   print_heap_before_gc();
2919   print_heap_regions();
2920   trace_heap_before_gc(_gc_tracer_stw);
2921 
2922   _verifier->verify_region_sets_optional();
2923   _verifier->verify_dirty_young_regions();
2924 
2925   // We should not be doing concurrent start unless the concurrent mark thread is running
2926   if (!_cm_thread->should_terminate()) {
2927     // This call will decide whether this pause is a concurrent start
2928     // pause. If it is, in_concurrent_start_gc() will return true
2929     // for the duration of this pause.
2930     policy()->decide_on_conc_mark_initiation();
2931   }
2932 
2933   // We do not allow concurrent start to be piggy-backed on a mixed GC.
2934   assert(!collector_state()->in_concurrent_start_gc() ||
2935          collector_state()->in_young_only_phase(), "sanity");
2936   // We also do not allow mixed GCs during marking.
2937   assert(!collector_state()->mark_or_rebuild_in_progress() || collector_state()->in_young_only_phase(), "sanity");
2938 
2939   // Record whether this pause may need to trigger a concurrent operation. Later,
2940   // when we signal the G1ConcurrentMarkThread, the collector state has already
2941   // been reset for the next pause.
2942   bool should_start_concurrent_mark_operation = collector_state()->in_concurrent_start_gc();
2943   bool concurrent_operation_is_full_mark = false;
2944 
2945   // Inner scope for scope based logging, timers, and stats collection
2946   {
2947     G1EvacuationInfo evacuation_info;
2948 
2949     GCTraceCPUTime tcpu;
2950 
2951     char young_gc_name[MaxYoungGCNameLength];
2952     set_young_gc_name(young_gc_name);
2953 
2954     GCTraceTime(Info, gc) tm(young_gc_name, NULL, gc_cause(), true);
2955 
2956     uint active_workers = WorkerPolicy::calc_active_workers(workers()->total_workers(),
2957                                                             workers()->active_workers(),
2958                                                             Threads::number_of_non_daemon_threads());
2959     active_workers = workers()->update_active_workers(active_workers);
2960     log_info(gc,task)("Using %u workers of %u for evacuation", active_workers, workers()->total_workers());
2961 
2962     G1MonitoringScope ms(g1mm(),
2963                          false /* full_gc */,
2964                          collector_state()->in_mixed_phase() /* all_memory_pools_affected */);
2965 
2966     G1HeapTransition heap_transition(this);
2967 
2968     {
2969       IsGCActiveMark x;
2970 
2971       gc_prologue(false);
2972 
2973       G1HeapVerifier::G1VerifyType verify_type = young_collection_verify_type();
2974       verify_before_young_collection(verify_type);
2975 
2976       {
2977         // The elapsed time induced by the start time below deliberately elides
2978         // the possible verification above.
2979         double sample_start_time_sec = os::elapsedTime();
2980 
2981         // Please see comment in g1CollectedHeap.hpp and
2982         // G1CollectedHeap::ref_processing_init() to see how
2983         // reference processing currently works in G1.
2984         _ref_processor_stw->enable_discovery();
2985 
2986         // We want to temporarily turn off discovery by the
2987         // CM ref processor, if necessary, and turn it back on
2988         // on again later if we do. Using a scoped
2989         // NoRefDiscovery object will do this.
2990         NoRefDiscovery no_cm_discovery(_ref_processor_cm);
2991 
2992         policy()->record_collection_pause_start(sample_start_time_sec);
2993 
2994         // Forget the current allocation region (we might even choose it to be part
2995         // of the collection set!).
2996         _allocator->release_mutator_alloc_regions();
2997 
2998         calculate_collection_set(evacuation_info, target_pause_time_ms);
2999 
3000         G1RedirtyCardsQueueSet rdcqs(G1BarrierSet::dirty_card_queue_set().allocator());
3001         G1ParScanThreadStateSet per_thread_states(this,
3002                                                   &rdcqs,
3003                                                   workers()->active_workers(),
3004                                                   collection_set()->young_region_length(),
3005                                                   collection_set()->optional_region_length());
3006         pre_evacuate_collection_set(evacuation_info, &per_thread_states);
3007 
3008         bool may_do_optional_evacuation = _collection_set.optional_region_length() != 0;
3009         // Actually do the work...
3010         evacuate_initial_collection_set(&per_thread_states, may_do_optional_evacuation);
3011 
3012         if (may_do_optional_evacuation) {
3013           evacuate_optional_collection_set(&per_thread_states);
3014         }
3015         post_evacuate_collection_set(evacuation_info, &rdcqs, &per_thread_states);
3016 
3017         start_new_collection_set();
3018 
3019         _survivor_evac_stats.adjust_desired_plab_sz();
3020         _old_evac_stats.adjust_desired_plab_sz();
3021 
3022         allocate_dummy_regions();
3023 
3024         _allocator->init_mutator_alloc_regions();
3025 
3026         expand_heap_after_young_collection();
3027 
3028         // Refine the type of a concurrent mark operation now that we did the
3029         // evacuation, eventually aborting it.
3030         concurrent_operation_is_full_mark = policy()->concurrent_operation_is_full_mark("Revise IHOP");
3031 
3032         // Need to report the collection pause now since record_collection_pause_end()
3033         // modifies it to the next state.
3034         _gc_tracer_stw->report_young_gc_pause(collector_state()->young_gc_pause_type(concurrent_operation_is_full_mark));
3035 
3036         double sample_end_time_sec = os::elapsedTime();
3037         double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS;
3038         policy()->record_collection_pause_end(pause_time_ms, concurrent_operation_is_full_mark);
3039       }
3040 
3041       verify_after_young_collection(verify_type);
3042 
3043       gc_epilogue(false);
3044     }
3045 
3046     // Print the remainder of the GC log output.
3047     if (evacuation_failed()) {
3048       log_info(gc)("To-space exhausted");
3049     }
3050 
3051     policy()->print_phases();
3052     heap_transition.print();
3053 
3054     _hrm.verify_optional();
3055     _verifier->verify_region_sets_optional();
3056 
3057     TASKQUEUE_STATS_ONLY(print_taskqueue_stats());
3058     TASKQUEUE_STATS_ONLY(reset_taskqueue_stats());
3059 
3060     print_heap_after_gc();
3061     print_heap_regions();
3062     trace_heap_after_gc(_gc_tracer_stw);
3063 
3064     // We must call G1MonitoringSupport::update_sizes() in the same scoping level
3065     // as an active TraceMemoryManagerStats object (i.e. before the destructor for the
3066     // TraceMemoryManagerStats is called) so that the G1 memory pools are updated
3067     // before any GC notifications are raised.
3068     g1mm()->update_sizes();
3069 
3070     gc_tracer_report_gc_end(concurrent_operation_is_full_mark, evacuation_info);
3071   }
3072   // It should now be safe to tell the concurrent mark thread to start
3073   // without its logging output interfering with the logging output
3074   // that came from the pause.
3075 
3076   if (should_start_concurrent_mark_operation) {
3077     // CAUTION: after the start_concurrent_cycle() call below, the concurrent marking
3078     // thread(s) could be running concurrently with us. Make sure that anything
3079     // after this point does not assume that we are the only GC thread running.
3080     // Note: of course, the actual marking work will not start until the safepoint
3081     // itself is released in SuspendibleThreadSet::desynchronize().
3082     start_concurrent_cycle(concurrent_operation_is_full_mark);
3083     ConcurrentGCBreakpoints::notify_idle_to_active();
3084   }
3085 }
3086 
3087 void G1CollectedHeap::preserve_mark_during_evac_failure(uint worker_id, oop obj, markWord m) {
3088   _evacuation_failed_info_array[worker_id].register_copy_failure(obj->size());
3089   _preserved_marks_set.get(worker_id)->push_if_necessary(obj, m);
3090 }
3091 
3092 bool G1ParEvacuateFollowersClosure::offer_termination() {
3093   EventGCPhaseParallel event;
3094   G1ParScanThreadState* const pss = par_scan_state();
3095   start_term_time();
3096   const bool res = (terminator() == nullptr) ? true : terminator()->offer_termination();
3097   end_term_time();
3098   event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(G1GCPhaseTimes::Termination));
3099   return res;
3100 }
3101 
3102 void G1ParEvacuateFollowersClosure::do_void() {
3103   EventGCPhaseParallel event;
3104   G1ParScanThreadState* const pss = par_scan_state();
3105   pss->trim_queue();
3106   event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase));
3107   do {
3108     EventGCPhaseParallel event;
3109     pss->steal_and_trim_queue(queues());
3110     event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase));
3111   } while (!offer_termination());
3112 }
3113 
3114 void G1CollectedHeap::complete_cleaning(BoolObjectClosure* is_alive,
3115                                         bool class_unloading_occurred) {
3116   uint num_workers = workers()->active_workers();
3117   G1ParallelCleaningTask unlink_task(is_alive, num_workers, class_unloading_occurred);
3118   workers()->run_task(&unlink_task);
3119 }
3120 
3121 // Weak Reference Processing support
3122 
3123 bool G1STWIsAliveClosure::do_object_b(oop p) {
3124   // An object is reachable if it is outside the collection set,
3125   // or is inside and copied.
3126   return !_g1h->is_in_cset(p) || p->is_forwarded();
3127 }
3128 
3129 bool G1STWSubjectToDiscoveryClosure::do_object_b(oop obj) {
3130   assert(obj != NULL, "must not be NULL");
3131   assert(_g1h->is_in_reserved(obj), "Trying to discover obj " PTR_FORMAT " not in heap", p2i(obj));
3132   // The areas the CM and STW ref processor manage must be disjoint. The is_in_cset() below
3133   // may falsely indicate that this is not the case here: however the collection set only
3134   // contains old regions when concurrent mark is not running.
3135   return _g1h->is_in_cset(obj) || _g1h->heap_region_containing(obj)->is_survivor();
3136 }
3137 
3138 // Non Copying Keep Alive closure
3139 class G1KeepAliveClosure: public OopClosure {
3140   G1CollectedHeap*_g1h;
3141 public:
3142   G1KeepAliveClosure(G1CollectedHeap* g1h) :_g1h(g1h) {}
3143   void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }
3144   void do_oop(oop* p) {
3145     oop obj = *p;
3146     assert(obj != NULL, "the caller should have filtered out NULL values");
3147 
3148     const G1HeapRegionAttr region_attr =_g1h->region_attr(obj);
3149     if (!region_attr.is_in_cset_or_humongous()) {
3150       return;
3151     }
3152     if (region_attr.is_in_cset()) {
3153       assert( obj->is_forwarded(), "invariant" );
3154       *p = obj->forwardee();
3155     } else {
3156       assert(!obj->is_forwarded(), "invariant" );
3157       assert(region_attr.is_humongous(),
3158              "Only allowed G1HeapRegionAttr state is IsHumongous, but is %d", region_attr.type());
3159      _g1h->set_humongous_is_live(obj);
3160     }
3161   }
3162 };
3163 
3164 // Copying Keep Alive closure - can be called from both
3165 // serial and parallel code as long as different worker
3166 // threads utilize different G1ParScanThreadState instances
3167 // and different queues.
3168 
3169 class G1CopyingKeepAliveClosure: public OopClosure {
3170   G1CollectedHeap*         _g1h;
3171   G1ParScanThreadState*    _par_scan_state;
3172 
3173 public:
3174   G1CopyingKeepAliveClosure(G1CollectedHeap* g1h,
3175                             G1ParScanThreadState* pss):
3176     _g1h(g1h),
3177     _par_scan_state(pss)
3178   {}
3179 
3180   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
3181   virtual void do_oop(      oop* p) { do_oop_work(p); }
3182 
3183   template <class T> void do_oop_work(T* p) {
3184     oop obj = RawAccess<>::oop_load(p);
3185 
3186     if (_g1h->is_in_cset_or_humongous(obj)) {
3187       // If the referent object has been forwarded (either copied
3188       // to a new location or to itself in the event of an
3189       // evacuation failure) then we need to update the reference
3190       // field and, if both reference and referent are in the G1
3191       // heap, update the RSet for the referent.
3192       //
3193       // If the referent has not been forwarded then we have to keep
3194       // it alive by policy. Therefore we have copy the referent.
3195       //
3196       // When the queue is drained (after each phase of reference processing)
3197       // the object and it's followers will be copied, the reference field set
3198       // to point to the new location, and the RSet updated.
3199       _par_scan_state->push_on_queue(ScannerTask(p));
3200     }
3201   }
3202 };
3203 
3204 // Special closure for enqueuing discovered fields: during enqueue the card table
3205 // may not be in shape to properly handle normal barrier calls (e.g. card marks
3206 // in regions that failed evacuation, scribbling of various values by card table
3207 // scan code). Additionally the regular barrier enqueues into the "global"
3208 // DCQS, but during GC we need these to-be-refined entries in the GC local queue
3209 // so that after clearing the card table, the redirty cards phase will properly
3210 // mark all dirty cards to be picked up by refinement.
3211 class G1EnqueueDiscoveredFieldClosure : public EnqueueDiscoveredFieldClosure {
3212   G1CollectedHeap* _g1h;
3213   G1ParScanThreadState* _pss;
3214 
3215 public:
3216   G1EnqueueDiscoveredFieldClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) : _g1h(g1h), _pss(pss) { }
3217 
3218   virtual void enqueue(HeapWord* discovered_field_addr, oop value) {
3219     assert(_g1h->is_in(discovered_field_addr), PTR_FORMAT " is not in heap ", p2i(discovered_field_addr));
3220     // Store the value first, whatever it is.
3221     RawAccess<>::oop_store(discovered_field_addr, value);
3222     if (value == NULL) {
3223       return;
3224     }
3225     _pss->write_ref_field_post(discovered_field_addr, value);
3226   }
3227 };
3228 
3229 // Serial drain queue closure. Called as the 'complete_gc'
3230 // closure for each discovered list in some of the
3231 // reference processing phases.
3232 
3233 class G1STWDrainQueueClosure: public VoidClosure {
3234 protected:
3235   G1CollectedHeap* _g1h;
3236   G1ParScanThreadState* _par_scan_state;
3237 
3238   G1ParScanThreadState*   par_scan_state() { return _par_scan_state; }
3239 
3240 public:
3241   G1STWDrainQueueClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) :
3242     _g1h(g1h),
3243     _par_scan_state(pss)
3244   { }
3245 
3246   void do_void() {
3247     G1ParScanThreadState* const pss = par_scan_state();
3248     pss->trim_queue();
3249   }
3250 };
3251 
3252 class G1STWRefProcProxyTask : public RefProcProxyTask {
3253   G1CollectedHeap& _g1h;
3254   G1ParScanThreadStateSet& _pss;
3255   TaskTerminator _terminator;
3256   G1ScannerTasksQueueSet& _task_queues;
3257 
3258 public:
3259   G1STWRefProcProxyTask(uint max_workers, G1CollectedHeap& g1h, G1ParScanThreadStateSet& pss, G1ScannerTasksQueueSet& task_queues)
3260     : RefProcProxyTask("G1STWRefProcProxyTask", max_workers),
3261       _g1h(g1h),
3262       _pss(pss),
3263       _terminator(max_workers, &task_queues),
3264       _task_queues(task_queues) {}
3265 
3266   void work(uint worker_id) override {
3267     assert(worker_id < _max_workers, "sanity");
3268     uint index = (_tm == RefProcThreadModel::Single) ? 0 : worker_id;
3269     _pss.state_for_worker(index)->set_ref_discoverer(nullptr);
3270     G1STWIsAliveClosure is_alive(&_g1h);
3271     G1CopyingKeepAliveClosure keep_alive(&_g1h, _pss.state_for_worker(index));
3272     G1ParEvacuateFollowersClosure complete_gc(&_g1h, _pss.state_for_worker(index), &_task_queues, _tm == RefProcThreadModel::Single ? nullptr : &_terminator, G1GCPhaseTimes::ObjCopy);
3273     G1EnqueueDiscoveredFieldClosure enqueue(&_g1h, _pss.state_for_worker(index));
3274     _rp_task->rp_work(worker_id, &is_alive, &keep_alive, &enqueue, &complete_gc);
3275   }
3276 
3277   void prepare_run_task_hook() override {
3278     _terminator.reset_for_reuse(_queue_count);
3279   }
3280 };
3281 
3282 // End of weak reference support closures
3283 
3284 void G1CollectedHeap::process_discovered_references(G1ParScanThreadStateSet* per_thread_states) {
3285   double ref_proc_start = os::elapsedTime();
3286 
3287   ReferenceProcessor* rp = _ref_processor_stw;
3288   assert(rp->discovery_enabled(), "should have been enabled");
3289 
3290   // Use only a single queue for this PSS.
3291   G1ParScanThreadState*          pss = per_thread_states->state_for_worker(0);
3292   pss->set_ref_discoverer(NULL);
3293   assert(pss->queue_is_empty(), "pre-condition");
3294 
3295   // Setup the soft refs policy...
3296   rp->setup_policy(false);
3297 
3298   ReferenceProcessorPhaseTimes& pt = *phase_times()->ref_phase_times();
3299 
3300   ReferenceProcessorStats stats;
3301   uint no_of_gc_workers = workers()->active_workers();
3302 
3303   // Parallel reference processing
3304   assert(no_of_gc_workers <= rp->max_num_queues(),
3305          "Mismatch between the number of GC workers %u and the maximum number of Reference process queues %u",
3306          no_of_gc_workers,  rp->max_num_queues());
3307 
3308   rp->set_active_mt_degree(no_of_gc_workers);
3309   G1STWRefProcProxyTask task(rp->max_num_queues(), *this, *per_thread_states, *_task_queues);
3310   stats = rp->process_discovered_references(task, pt);
3311 
3312   _gc_tracer_stw->report_gc_reference_stats(stats);
3313 
3314   // We have completed copying any necessary live referent objects.
3315   assert(pss->queue_is_empty(), "both queue and overflow should be empty");
3316 
3317   make_pending_list_reachable();
3318 
3319   assert(!rp->discovery_enabled(), "Postcondition");
3320   rp->verify_no_references_recorded();
3321 
3322   double ref_proc_time = os::elapsedTime() - ref_proc_start;
3323   phase_times()->record_ref_proc_time(ref_proc_time * 1000.0);
3324 }
3325 
3326 void G1CollectedHeap::make_pending_list_reachable() {
3327   if (collector_state()->in_concurrent_start_gc()) {
3328     oop pll_head = Universe::reference_pending_list();
3329     if (pll_head != NULL) {
3330       // Any valid worker id is fine here as we are in the VM thread and single-threaded.
3331       _cm->mark_in_next_bitmap(0 /* worker_id */, pll_head);
3332     }
3333   }
3334 }
3335 
3336 static bool do_humongous_object_logging() {
3337   return log_is_enabled(Debug, gc, humongous);
3338 }
3339 
3340 bool G1CollectedHeap::should_do_eager_reclaim() const {
3341   // As eager reclaim logging also gives information about humongous objects in
3342   // the heap in general, always do the eager reclaim pass even without known
3343   // candidates.
3344   return (G1EagerReclaimHumongousObjects &&
3345           (has_humongous_reclaim_candidates() || do_humongous_object_logging()));
3346 }
3347 
3348 class G1PrepareEvacuationTask : public AbstractGangTask {
3349   class G1PrepareRegionsClosure : public HeapRegionClosure {
3350     G1CollectedHeap* _g1h;
3351     G1PrepareEvacuationTask* _parent_task;
3352     uint _worker_humongous_total;
3353     uint _worker_humongous_candidates;
3354 
3355     bool humongous_region_is_candidate(HeapRegion* region) const {
3356       assert(region->is_starts_humongous(), "Must start a humongous object");
3357 
3358       oop obj = cast_to_oop(region->bottom());
3359 
3360       // Dead objects cannot be eager reclaim candidates. Due to class
3361       // unloading it is unsafe to query their classes so we return early.
3362       if (_g1h->is_obj_dead(obj, region)) {
3363         return false;
3364       }
3365 
3366       // If we do not have a complete remembered set for the region, then we can
3367       // not be sure that we have all references to it.
3368       if (!region->rem_set()->is_complete()) {
3369         return false;
3370       }
3371       // Candidate selection must satisfy the following constraints
3372       // while concurrent marking is in progress:
3373       //
3374       // * In order to maintain SATB invariants, an object must not be
3375       // reclaimed if it was allocated before the start of marking and
3376       // has not had its references scanned.  Such an object must have
3377       // its references (including type metadata) scanned to ensure no
3378       // live objects are missed by the marking process.  Objects
3379       // allocated after the start of concurrent marking don't need to
3380       // be scanned.
3381       //
3382       // * An object must not be reclaimed if it is on the concurrent
3383       // mark stack.  Objects allocated after the start of concurrent
3384       // marking are never pushed on the mark stack.
3385       //
3386       // Nominating only objects allocated after the start of concurrent
3387       // marking is sufficient to meet both constraints.  This may miss
3388       // some objects that satisfy the constraints, but the marking data
3389       // structures don't support efficiently performing the needed
3390       // additional tests or scrubbing of the mark stack.
3391       //
3392       // However, we presently only nominate is_typeArray() objects.
3393       // A humongous object containing references induces remembered
3394       // set entries on other regions.  In order to reclaim such an
3395       // object, those remembered sets would need to be cleaned up.
3396       //
3397       // We also treat is_typeArray() objects specially, allowing them
3398       // to be reclaimed even if allocated before the start of
3399       // concurrent mark.  For this we rely on mark stack insertion to
3400       // exclude is_typeArray() objects, preventing reclaiming an object
3401       // that is in the mark stack.  We also rely on the metadata for
3402       // such objects to be built-in and so ensured to be kept live.
3403       // Frequent allocation and drop of large binary blobs is an
3404       // important use case for eager reclaim, and this special handling
3405       // may reduce needed headroom.
3406 
3407       return obj->is_typeArray() &&
3408              _g1h->is_potential_eager_reclaim_candidate(region);
3409     }
3410 
3411   public:
3412     G1PrepareRegionsClosure(G1CollectedHeap* g1h, G1PrepareEvacuationTask* parent_task) :
3413       _g1h(g1h),
3414       _parent_task(parent_task),
3415       _worker_humongous_total(0),
3416       _worker_humongous_candidates(0) { }
3417 
3418     ~G1PrepareRegionsClosure() {
3419       _parent_task->add_humongous_candidates(_worker_humongous_candidates);
3420       _parent_task->add_humongous_total(_worker_humongous_total);
3421     }
3422 
3423     virtual bool do_heap_region(HeapRegion* hr) {
3424       // First prepare the region for scanning
3425       _g1h->rem_set()->prepare_region_for_scan(hr);
3426 
3427       // Now check if region is a humongous candidate
3428       if (!hr->is_starts_humongous()) {
3429         _g1h->register_region_with_region_attr(hr);
3430         return false;
3431       }
3432 
3433       uint index = hr->hrm_index();
3434       if (humongous_region_is_candidate(hr)) {
3435         _g1h->set_humongous_reclaim_candidate(index, true);
3436         _g1h->register_humongous_region_with_region_attr(index);
3437         _worker_humongous_candidates++;
3438         // We will later handle the remembered sets of these regions.
3439       } else {
3440         _g1h->set_humongous_reclaim_candidate(index, false);
3441         _g1h->register_region_with_region_attr(hr);
3442       }
3443       log_debug(gc, humongous)("Humongous region %u (object size " SIZE_FORMAT " @ " PTR_FORMAT ") remset " SIZE_FORMAT " code roots " SIZE_FORMAT " marked %d reclaim candidate %d type array %d",
3444                                index,
3445                                (size_t)cast_to_oop(hr->bottom())->size() * HeapWordSize,
3446                                p2i(hr->bottom()),
3447                                hr->rem_set()->occupied(),
3448                                hr->rem_set()->strong_code_roots_list_length(),
3449                                _g1h->concurrent_mark()->next_mark_bitmap()->is_marked(hr->bottom()),
3450                                _g1h->is_humongous_reclaim_candidate(index),
3451                                cast_to_oop(hr->bottom())->is_typeArray()
3452                               );
3453       _worker_humongous_total++;
3454 
3455       return false;
3456     }
3457   };
3458 
3459   G1CollectedHeap* _g1h;
3460   HeapRegionClaimer _claimer;
3461   volatile uint _humongous_total;
3462   volatile uint _humongous_candidates;
3463 public:
3464   G1PrepareEvacuationTask(G1CollectedHeap* g1h) :
3465     AbstractGangTask("Prepare Evacuation"),
3466     _g1h(g1h),
3467     _claimer(_g1h->workers()->active_workers()),
3468     _humongous_total(0),
3469     _humongous_candidates(0) { }
3470 
3471   void work(uint worker_id) {
3472     G1PrepareRegionsClosure cl(_g1h, this);
3473     _g1h->heap_region_par_iterate_from_worker_offset(&cl, &_claimer, worker_id);
3474   }
3475 
3476   void add_humongous_candidates(uint candidates) {
3477     Atomic::add(&_humongous_candidates, candidates);
3478   }
3479 
3480   void add_humongous_total(uint total) {
3481     Atomic::add(&_humongous_total, total);
3482   }
3483 
3484   uint humongous_candidates() {
3485     return _humongous_candidates;
3486   }
3487 
3488   uint humongous_total() {
3489     return _humongous_total;
3490   }
3491 };
3492 
3493 void G1CollectedHeap::pre_evacuate_collection_set(G1EvacuationInfo& evacuation_info, G1ParScanThreadStateSet* per_thread_states) {
3494   _bytes_used_during_gc = 0;
3495 
3496   _expand_heap_after_alloc_failure = true;
3497   Atomic::store(&_num_regions_failed_evacuation, 0u);
3498 
3499   memset((void*)_regions_failed_evacuation, false, sizeof(bool) * max_regions());
3500 
3501   // Disable the hot card cache.
3502   _hot_card_cache->reset_hot_cache_claimed_index();
3503   _hot_card_cache->set_use_cache(false);
3504 
3505   // Initialize the GC alloc regions.
3506   _allocator->init_gc_alloc_regions(evacuation_info);
3507 
3508   {
3509     Ticks start = Ticks::now();
3510     rem_set()->prepare_for_scan_heap_roots();
3511     phase_times()->record_prepare_heap_roots_time_ms((Ticks::now() - start).seconds() * 1000.0);
3512   }
3513 
3514   {
3515     G1PrepareEvacuationTask g1_prep_task(this);
3516     Tickspan task_time = run_task_timed(&g1_prep_task);
3517 
3518     phase_times()->record_register_regions(task_time.seconds() * 1000.0);
3519     _num_humongous_objects = g1_prep_task.humongous_total();
3520     _num_humongous_reclaim_candidates = g1_prep_task.humongous_candidates();
3521   }
3522 
3523   assert(_verifier->check_region_attr_table(), "Inconsistency in the region attributes table.");
3524   _preserved_marks_set.assert_empty();
3525 
3526 #if COMPILER2_OR_JVMCI
3527   DerivedPointerTable::clear();
3528 #endif
3529 
3530   // Concurrent start needs claim bits to keep track of the marked-through CLDs.
3531   if (collector_state()->in_concurrent_start_gc()) {
3532     concurrent_mark()->pre_concurrent_start(gc_cause());
3533 
3534     double start_clear_claimed_marks = os::elapsedTime();
3535 
3536     ClassLoaderDataGraph::clear_claimed_marks();
3537 
3538     double recorded_clear_claimed_marks_time_ms = (os::elapsedTime() - start_clear_claimed_marks) * 1000.0;
3539     phase_times()->record_clear_claimed_marks_time_ms(recorded_clear_claimed_marks_time_ms);
3540   }
3541 
3542   // Should G1EvacuationFailureALot be in effect for this GC?
3543   NOT_PRODUCT(set_evacuation_failure_alot_for_current_gc();)
3544 }
3545 
3546 class G1EvacuateRegionsBaseTask : public AbstractGangTask {
3547 protected:
3548   G1CollectedHeap* _g1h;
3549   G1ParScanThreadStateSet* _per_thread_states;
3550   G1ScannerTasksQueueSet* _task_queues;
3551   TaskTerminator _terminator;
3552   uint _num_workers;
3553 
3554   void evacuate_live_objects(G1ParScanThreadState* pss,
3555                              uint worker_id,
3556                              G1GCPhaseTimes::GCParPhases objcopy_phase,
3557                              G1GCPhaseTimes::GCParPhases termination_phase) {
3558     G1GCPhaseTimes* p = _g1h->phase_times();
3559 
3560     Ticks start = Ticks::now();
3561     G1ParEvacuateFollowersClosure cl(_g1h, pss, _task_queues, &_terminator, objcopy_phase);
3562     cl.do_void();
3563 
3564     assert(pss->queue_is_empty(), "should be empty");
3565 
3566     Tickspan evac_time = (Ticks::now() - start);
3567     p->record_or_add_time_secs(objcopy_phase, worker_id, evac_time.seconds() - cl.term_time());
3568 
3569     if (termination_phase == G1GCPhaseTimes::Termination) {
3570       p->record_time_secs(termination_phase, worker_id, cl.term_time());
3571       p->record_thread_work_item(termination_phase, worker_id, cl.term_attempts());
3572     } else {
3573       p->record_or_add_time_secs(termination_phase, worker_id, cl.term_time());
3574       p->record_or_add_thread_work_item(termination_phase, worker_id, cl.term_attempts());
3575     }
3576     assert(pss->trim_ticks().value() == 0,
3577            "Unexpected partial trimming during evacuation value " JLONG_FORMAT,
3578            pss->trim_ticks().value());
3579   }
3580 
3581   virtual void start_work(uint worker_id) { }
3582 
3583   virtual void end_work(uint worker_id) { }
3584 
3585   virtual void scan_roots(G1ParScanThreadState* pss, uint worker_id) = 0;
3586 
3587   virtual void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) = 0;
3588 
3589 public:
3590   G1EvacuateRegionsBaseTask(const char* name,
3591                             G1ParScanThreadStateSet* per_thread_states,
3592                             G1ScannerTasksQueueSet* task_queues,
3593                             uint num_workers) :
3594     AbstractGangTask(name),
3595     _g1h(G1CollectedHeap::heap()),
3596     _per_thread_states(per_thread_states),
3597     _task_queues(task_queues),
3598     _terminator(num_workers, _task_queues),
3599     _num_workers(num_workers)
3600   { }
3601 
3602   void work(uint worker_id) {
3603     start_work(worker_id);
3604 
3605     {
3606       ResourceMark rm;
3607 
3608       G1ParScanThreadState* pss = _per_thread_states->state_for_worker(worker_id);
3609       pss->set_ref_discoverer(_g1h->ref_processor_stw());
3610 
3611       scan_roots(pss, worker_id);
3612       evacuate_live_objects(pss, worker_id);
3613     }
3614 
3615     end_work(worker_id);
3616   }
3617 };
3618 
3619 class G1EvacuateRegionsTask : public G1EvacuateRegionsBaseTask {
3620   G1RootProcessor* _root_processor;
3621   bool _has_optional_evacuation_work;
3622 
3623   void scan_roots(G1ParScanThreadState* pss, uint worker_id) {
3624     _root_processor->evacuate_roots(pss, worker_id);
3625     _g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::ScanHR, G1GCPhaseTimes::ObjCopy, _has_optional_evacuation_work);
3626     _g1h->rem_set()->scan_collection_set_regions(pss, worker_id, G1GCPhaseTimes::ScanHR, G1GCPhaseTimes::CodeRoots, G1GCPhaseTimes::ObjCopy);
3627   }
3628 
3629   void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) {
3630     G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::ObjCopy, G1GCPhaseTimes::Termination);
3631   }
3632 
3633   void start_work(uint worker_id) {
3634     _g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerStart, worker_id, Ticks::now().seconds());
3635   }
3636 
3637   void end_work(uint worker_id) {
3638     _g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerEnd, worker_id, Ticks::now().seconds());
3639   }
3640 
3641 public:
3642   G1EvacuateRegionsTask(G1CollectedHeap* g1h,
3643                         G1ParScanThreadStateSet* per_thread_states,
3644                         G1ScannerTasksQueueSet* task_queues,
3645                         G1RootProcessor* root_processor,
3646                         uint num_workers,
3647                         bool has_optional_evacuation_work) :
3648     G1EvacuateRegionsBaseTask("G1 Evacuate Regions", per_thread_states, task_queues, num_workers),
3649     _root_processor(root_processor),
3650     _has_optional_evacuation_work(has_optional_evacuation_work)
3651   { }
3652 };
3653 
3654 void G1CollectedHeap::evacuate_initial_collection_set(G1ParScanThreadStateSet* per_thread_states,
3655                                                       bool has_optional_evacuation_work) {
3656   G1GCPhaseTimes* p = phase_times();
3657 
3658   {
3659     Ticks start = Ticks::now();
3660     rem_set()->merge_heap_roots(true /* initial_evacuation */);
3661     p->record_merge_heap_roots_time((Ticks::now() - start).seconds() * 1000.0);
3662   }
3663 
3664   Tickspan task_time;
3665   const uint num_workers = workers()->active_workers();
3666 
3667   Ticks start_processing = Ticks::now();
3668   {
3669     G1RootProcessor root_processor(this, num_workers);
3670     G1EvacuateRegionsTask g1_par_task(this,
3671                                       per_thread_states,
3672                                       _task_queues,
3673                                       &root_processor,
3674                                       num_workers,
3675                                       has_optional_evacuation_work);
3676     task_time = run_task_timed(&g1_par_task);
3677     // Closing the inner scope will execute the destructor for the G1RootProcessor object.
3678     // To extract its code root fixup time we measure total time of this scope and
3679     // subtract from the time the WorkGang task took.
3680   }
3681   Tickspan total_processing = Ticks::now() - start_processing;
3682 
3683   p->record_initial_evac_time(task_time.seconds() * 1000.0);
3684   p->record_or_add_code_root_fixup_time((total_processing - task_time).seconds() * 1000.0);
3685 
3686   rem_set()->complete_evac_phase(has_optional_evacuation_work);
3687 }
3688 
3689 class G1EvacuateOptionalRegionsTask : public G1EvacuateRegionsBaseTask {
3690 
3691   void scan_roots(G1ParScanThreadState* pss, uint worker_id) {
3692     _g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::OptObjCopy, true /* remember_already_scanned_cards */);
3693     _g1h->rem_set()->scan_collection_set_regions(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::OptCodeRoots, G1GCPhaseTimes::OptObjCopy);
3694   }
3695 
3696   void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) {
3697     G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::OptObjCopy, G1GCPhaseTimes::OptTermination);
3698   }
3699 
3700 public:
3701   G1EvacuateOptionalRegionsTask(G1ParScanThreadStateSet* per_thread_states,
3702                                 G1ScannerTasksQueueSet* queues,
3703                                 uint num_workers) :
3704     G1EvacuateRegionsBaseTask("G1 Evacuate Optional Regions", per_thread_states, queues, num_workers) {
3705   }
3706 };
3707 
3708 void G1CollectedHeap::evacuate_next_optional_regions(G1ParScanThreadStateSet* per_thread_states) {
3709   class G1MarkScope : public MarkScope { };
3710 
3711   Tickspan task_time;
3712 
3713   Ticks start_processing = Ticks::now();
3714   {
3715     G1MarkScope code_mark_scope;
3716     G1EvacuateOptionalRegionsTask task(per_thread_states, _task_queues, workers()->active_workers());
3717     task_time = run_task_timed(&task);
3718     // See comment in evacuate_collection_set() for the reason of the scope.
3719   }
3720   Tickspan total_processing = Ticks::now() - start_processing;
3721 
3722   G1GCPhaseTimes* p = phase_times();
3723   p->record_or_add_code_root_fixup_time((total_processing - task_time).seconds() * 1000.0);
3724 }
3725 
3726 void G1CollectedHeap::evacuate_optional_collection_set(G1ParScanThreadStateSet* per_thread_states) {
3727   const double gc_start_time_ms = phase_times()->cur_collection_start_sec() * 1000.0;
3728 
3729   while (!evacuation_failed() && _collection_set.optional_region_length() > 0) {
3730 
3731     double time_used_ms = os::elapsedTime() * 1000.0 - gc_start_time_ms;
3732     double time_left_ms = MaxGCPauseMillis - time_used_ms;
3733 
3734     if (time_left_ms < 0 ||
3735         !_collection_set.finalize_optional_for_evacuation(time_left_ms * policy()->optional_evacuation_fraction())) {
3736       log_trace(gc, ergo, cset)("Skipping evacuation of %u optional regions, no more regions can be evacuated in %.3fms",
3737                                 _collection_set.optional_region_length(), time_left_ms);
3738       break;
3739     }
3740 
3741     {
3742       Ticks start = Ticks::now();
3743       rem_set()->merge_heap_roots(false /* initial_evacuation */);
3744       phase_times()->record_or_add_optional_merge_heap_roots_time((Ticks::now() - start).seconds() * 1000.0);
3745     }
3746 
3747     {
3748       Ticks start = Ticks::now();
3749       evacuate_next_optional_regions(per_thread_states);
3750       phase_times()->record_or_add_optional_evac_time((Ticks::now() - start).seconds() * 1000.0);
3751     }
3752 
3753     rem_set()->complete_evac_phase(true /* has_more_than_one_evacuation_phase */);
3754   }
3755 
3756   _collection_set.abandon_optional_collection_set(per_thread_states);
3757 }
3758 
3759 void G1CollectedHeap::post_evacuate_collection_set(G1EvacuationInfo& evacuation_info,
3760                                                    G1RedirtyCardsQueueSet* rdcqs,
3761                                                    G1ParScanThreadStateSet* per_thread_states) {
3762   G1GCPhaseTimes* p = phase_times();
3763 
3764   // Process any discovered reference objects - we have
3765   // to do this _before_ we retire the GC alloc regions
3766   // as we may have to copy some 'reachable' referent
3767   // objects (and their reachable sub-graphs) that were
3768   // not copied during the pause.
3769   process_discovered_references(per_thread_states);
3770 
3771   G1STWIsAliveClosure is_alive(this);
3772   G1KeepAliveClosure keep_alive(this);
3773 
3774   WeakProcessor::weak_oops_do(workers(), &is_alive, &keep_alive, p->weak_phase_times());
3775 
3776   _allocator->release_gc_alloc_regions(evacuation_info);
3777 
3778   post_evacuate_cleanup_1(per_thread_states, rdcqs);
3779 
3780   post_evacuate_cleanup_2(&_preserved_marks_set, rdcqs, &evacuation_info, per_thread_states->surviving_young_words());
3781 
3782   assert_used_and_recalculate_used_equal(this);
3783 
3784   rebuild_free_region_list();
3785 
3786   record_obj_copy_mem_stats();
3787 
3788   evacuation_info.set_collectionset_used_before(collection_set()->bytes_used_before());
3789   evacuation_info.set_bytes_used(_bytes_used_during_gc);
3790 
3791   policy()->print_age_table();
3792 }
3793 
3794 void G1CollectedHeap::record_obj_copy_mem_stats() {
3795   policy()->old_gen_alloc_tracker()->
3796     add_allocated_bytes_since_last_gc(_old_evac_stats.allocated() * HeapWordSize);
3797 
3798   _gc_tracer_stw->report_evacuation_statistics(create_g1_evac_summary(&_survivor_evac_stats),
3799                                                create_g1_evac_summary(&_old_evac_stats));
3800 }
3801 
3802 void G1CollectedHeap::free_region(HeapRegion* hr, FreeRegionList* free_list) {
3803   assert(!hr->is_free(), "the region should not be free");
3804   assert(!hr->is_empty(), "the region should not be empty");
3805   assert(_hrm.is_available(hr->hrm_index()), "region should be committed");
3806 
3807   if (G1VerifyBitmaps) {
3808     MemRegion mr(hr->bottom(), hr->end());
3809     concurrent_mark()->clear_range_in_prev_bitmap(mr);
3810   }
3811 
3812   // Clear the card counts for this region.
3813   // Note: we only need to do this if the region is not young
3814   // (since we don't refine cards in young regions).
3815   if (!hr->is_young()) {
3816     _hot_card_cache->reset_card_counts(hr);
3817   }
3818 
3819   // Reset region metadata to allow reuse.
3820   hr->hr_clear(true /* clear_space */);
3821   _policy->remset_tracker()->update_at_free(hr);
3822 
3823   if (free_list != NULL) {
3824     free_list->add_ordered(hr);
3825   }
3826 }
3827 
3828 void G1CollectedHeap::free_humongous_region(HeapRegion* hr,
3829                                             FreeRegionList* free_list) {
3830   assert(hr->is_humongous(), "this is only for humongous regions");
3831   hr->clear_humongous();
3832   free_region(hr, free_list);
3833 }
3834 
3835 void G1CollectedHeap::remove_from_old_gen_sets(const uint old_regions_removed,
3836                                                const uint archive_regions_removed,
3837                                                const uint humongous_regions_removed) {
3838   if (old_regions_removed > 0 || archive_regions_removed > 0 || humongous_regions_removed > 0) {
3839     MutexLocker x(OldSets_lock, Mutex::_no_safepoint_check_flag);
3840     _old_set.bulk_remove(old_regions_removed);
3841     _archive_set.bulk_remove(archive_regions_removed);
3842     _humongous_set.bulk_remove(humongous_regions_removed);
3843   }
3844 
3845 }
3846 
3847 void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) {
3848   assert(list != NULL, "list can't be null");
3849   if (!list->is_empty()) {
3850     MutexLocker x(FreeList_lock, Mutex::_no_safepoint_check_flag);
3851     _hrm.insert_list_into_free_list(list);
3852   }
3853 }
3854 
3855 void G1CollectedHeap::decrement_summary_bytes(size_t bytes) {
3856   decrease_used(bytes);
3857 }
3858 
3859 void G1CollectedHeap::post_evacuate_cleanup_1(G1ParScanThreadStateSet* per_thread_states,
3860                                               G1RedirtyCardsQueueSet* rdcqs) {
3861   Ticks start = Ticks::now();
3862   {
3863     G1PostEvacuateCollectionSetCleanupTask1 cl(per_thread_states, rdcqs);
3864     run_batch_task(&cl);
3865   }
3866   phase_times()->record_post_evacuate_cleanup_task_1_time((Ticks::now() - start).seconds() * 1000.0);
3867 }
3868 
3869 void G1CollectedHeap::post_evacuate_cleanup_2(PreservedMarksSet* preserved_marks,
3870                                               G1RedirtyCardsQueueSet* rdcqs,
3871                                               G1EvacuationInfo* evacuation_info,
3872                                               const size_t* surviving_young_words) {
3873   Ticks start = Ticks::now();
3874   {
3875     G1PostEvacuateCollectionSetCleanupTask2 cl(preserved_marks, rdcqs, evacuation_info, surviving_young_words);
3876     run_batch_task(&cl);
3877   }
3878   phase_times()->record_post_evacuate_cleanup_task_2_time((Ticks::now() - start).seconds() * 1000.0);
3879 }
3880 
3881 void G1CollectedHeap::clear_eden() {
3882   _eden.clear();
3883 }
3884 
3885 void G1CollectedHeap::clear_collection_set() {
3886   collection_set()->clear();
3887 }
3888 
3889 void G1CollectedHeap::rebuild_free_region_list() {
3890   Ticks start = Ticks::now();
3891   _hrm.rebuild_free_list(workers());
3892   phase_times()->record_total_rebuild_freelist_time_ms((Ticks::now() - start).seconds() * 1000.0);
3893 }
3894 
3895 class G1AbandonCollectionSetClosure : public HeapRegionClosure {
3896 public:
3897   virtual bool do_heap_region(HeapRegion* r) {
3898     assert(r->in_collection_set(), "Region %u must have been in collection set", r->hrm_index());
3899     G1CollectedHeap::heap()->clear_region_attr(r);
3900     r->clear_young_index_in_cset();
3901     return false;
3902   }
3903 };
3904 
3905 void G1CollectedHeap::abandon_collection_set(G1CollectionSet* collection_set) {
3906   G1AbandonCollectionSetClosure cl;
3907   collection_set_iterate_all(&cl);
3908 
3909   collection_set->clear();
3910   collection_set->stop_incremental_building();
3911 }
3912 
3913 bool G1CollectedHeap::is_old_gc_alloc_region(HeapRegion* hr) {
3914   return _allocator->is_retained_old_region(hr);
3915 }
3916 
3917 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {
3918   _eden.add(hr);
3919   _policy->set_region_eden(hr);
3920 }
3921 
3922 #ifdef ASSERT
3923 
3924 class NoYoungRegionsClosure: public HeapRegionClosure {
3925 private:
3926   bool _success;
3927 public:
3928   NoYoungRegionsClosure() : _success(true) { }
3929   bool do_heap_region(HeapRegion* r) {
3930     if (r->is_young()) {
3931       log_error(gc, verify)("Region [" PTR_FORMAT ", " PTR_FORMAT ") tagged as young",
3932                             p2i(r->bottom()), p2i(r->end()));
3933       _success = false;
3934     }
3935     return false;
3936   }
3937   bool success() { return _success; }
3938 };
3939 
3940 bool G1CollectedHeap::check_young_list_empty() {
3941   bool ret = (young_regions_count() == 0);
3942 
3943   NoYoungRegionsClosure closure;
3944   heap_region_iterate(&closure);
3945   ret = ret && closure.success();
3946 
3947   return ret;
3948 }
3949 
3950 #endif // ASSERT
3951 
3952 // Remove the given HeapRegion from the appropriate region set.
3953 void G1CollectedHeap::prepare_region_for_full_compaction(HeapRegion* hr) {
3954    if (hr->is_archive()) {
3955     _archive_set.remove(hr);
3956   } else if (hr->is_humongous()) {
3957     _humongous_set.remove(hr);
3958   } else if (hr->is_old()) {
3959     _old_set.remove(hr);
3960   } else if (hr->is_young()) {
3961     // Note that emptying the eden and survivor lists is postponed and instead
3962     // done as the first step when rebuilding the regions sets again. The reason
3963     // for this is that during a full GC string deduplication needs to know if
3964     // a collected region was young or old when the full GC was initiated.
3965     hr->uninstall_surv_rate_group();
3966   } else {
3967     // We ignore free regions, we'll empty the free list afterwards.
3968     assert(hr->is_free(), "it cannot be another type");
3969   }
3970 }
3971 
3972 void G1CollectedHeap::increase_used(size_t bytes) {
3973   _summary_bytes_used += bytes;
3974 }
3975 
3976 void G1CollectedHeap::decrease_used(size_t bytes) {
3977   assert(_summary_bytes_used >= bytes,
3978          "invariant: _summary_bytes_used: " SIZE_FORMAT " should be >= bytes: " SIZE_FORMAT,
3979          _summary_bytes_used, bytes);
3980   _summary_bytes_used -= bytes;
3981 }
3982 
3983 void G1CollectedHeap::set_used(size_t bytes) {
3984   _summary_bytes_used = bytes;
3985 }
3986 
3987 class RebuildRegionSetsClosure : public HeapRegionClosure {
3988 private:
3989   bool _free_list_only;
3990 
3991   HeapRegionSet* _old_set;
3992   HeapRegionSet* _archive_set;
3993   HeapRegionSet* _humongous_set;
3994 
3995   HeapRegionManager* _hrm;
3996 
3997   size_t _total_used;
3998 
3999 public:
4000   RebuildRegionSetsClosure(bool free_list_only,
4001                            HeapRegionSet* old_set,
4002                            HeapRegionSet* archive_set,
4003                            HeapRegionSet* humongous_set,
4004                            HeapRegionManager* hrm) :
4005     _free_list_only(free_list_only), _old_set(old_set), _archive_set(archive_set),
4006     _humongous_set(humongous_set), _hrm(hrm), _total_used(0) {
4007     assert(_hrm->num_free_regions() == 0, "pre-condition");
4008     if (!free_list_only) {
4009       assert(_old_set->is_empty(), "pre-condition");
4010       assert(_archive_set->is_empty(), "pre-condition");
4011       assert(_humongous_set->is_empty(), "pre-condition");
4012     }
4013   }
4014 
4015   bool do_heap_region(HeapRegion* r) {
4016     if (r->is_empty()) {
4017       assert(r->rem_set()->is_empty(), "Empty regions should have empty remembered sets.");
4018       // Add free regions to the free list
4019       r->set_free();
4020       _hrm->insert_into_free_list(r);
4021     } else if (!_free_list_only) {
4022       assert(r->rem_set()->is_empty(), "At this point remembered sets must have been cleared.");
4023 
4024       if (r->is_humongous()) {
4025         _humongous_set->add(r);
4026       } else if (r->is_archive()) {
4027         _archive_set->add(r);
4028       } else {
4029         assert(r->is_young() || r->is_free() || r->is_old(), "invariant");
4030         // We now move all (non-humongous, non-old, non-archive) regions to old gen,
4031         // and register them as such.
4032         r->move_to_old();
4033         _old_set->add(r);
4034       }
4035       _total_used += r->used();
4036     }
4037 
4038     return false;
4039   }
4040 
4041   size_t total_used() {
4042     return _total_used;
4043   }
4044 };
4045 
4046 void G1CollectedHeap::rebuild_region_sets(bool free_list_only) {
4047   assert_at_safepoint_on_vm_thread();
4048 
4049   if (!free_list_only) {
4050     _eden.clear();
4051     _survivor.clear();
4052   }
4053 
4054   RebuildRegionSetsClosure cl(free_list_only,
4055                               &_old_set, &_archive_set, &_humongous_set,
4056                               &_hrm);
4057   heap_region_iterate(&cl);
4058 
4059   if (!free_list_only) {
4060     set_used(cl.total_used());
4061     if (_archive_allocator != NULL) {
4062       _archive_allocator->clear_used();
4063     }
4064   }
4065   assert_used_and_recalculate_used_equal(this);
4066 }
4067 
4068 // Methods for the mutator alloc region
4069 
4070 HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size,
4071                                                       bool force,
4072                                                       uint node_index) {
4073   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
4074   bool should_allocate = policy()->should_allocate_mutator_region();
4075   if (force || should_allocate) {
4076     HeapRegion* new_alloc_region = new_region(word_size,
4077                                               HeapRegionType::Eden,
4078                                               false /* do_expand */,
4079                                               node_index);
4080     if (new_alloc_region != NULL) {
4081       set_region_short_lived_locked(new_alloc_region);
4082       _hr_printer.alloc(new_alloc_region, !should_allocate);
4083       _verifier->check_bitmaps("Mutator Region Allocation", new_alloc_region);
4084       _policy->remset_tracker()->update_at_allocate(new_alloc_region);
4085       return new_alloc_region;
4086     }
4087   }
4088   return NULL;
4089 }
4090 
4091 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region,
4092                                                   size_t allocated_bytes) {
4093   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
4094   assert(alloc_region->is_eden(), "all mutator alloc regions should be eden");
4095 
4096   collection_set()->add_eden_region(alloc_region);
4097   increase_used(allocated_bytes);
4098   _eden.add_used_bytes(allocated_bytes);
4099   _hr_printer.retire(alloc_region);
4100 
4101   // We update the eden sizes here, when the region is retired,
4102   // instead of when it's allocated, since this is the point that its
4103   // used space has been recorded in _summary_bytes_used.
4104   g1mm()->update_eden_size();
4105 }
4106 
4107 // Methods for the GC alloc regions
4108 
4109 bool G1CollectedHeap::has_more_regions(G1HeapRegionAttr dest) {
4110   if (dest.is_old()) {
4111     return true;
4112   } else {
4113     return survivor_regions_count() < policy()->max_survivor_regions();
4114   }
4115 }
4116 
4117 HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size, G1HeapRegionAttr dest, uint node_index) {
4118   assert(FreeList_lock->owned_by_self(), "pre-condition");
4119 
4120   if (!has_more_regions(dest)) {
4121     return NULL;
4122   }
4123 
4124   HeapRegionType type;
4125   if (dest.is_young()) {
4126     type = HeapRegionType::Survivor;
4127   } else {
4128     type = HeapRegionType::Old;
4129   }
4130 
4131   HeapRegion* new_alloc_region = new_region(word_size,
4132                                             type,
4133                                             true /* do_expand */,
4134                                             node_index);
4135 
4136   if (new_alloc_region != NULL) {
4137     if (type.is_survivor()) {
4138       new_alloc_region->set_survivor();
4139       _survivor.add(new_alloc_region);
4140       _verifier->check_bitmaps("Survivor Region Allocation", new_alloc_region);
4141     } else {
4142       new_alloc_region->set_old();
4143       _verifier->check_bitmaps("Old Region Allocation", new_alloc_region);
4144     }
4145     _policy->remset_tracker()->update_at_allocate(new_alloc_region);
4146     register_region_with_region_attr(new_alloc_region);
4147     _hr_printer.alloc(new_alloc_region);
4148     return new_alloc_region;
4149   }
4150   return NULL;
4151 }
4152 
4153 void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region,
4154                                              size_t allocated_bytes,
4155                                              G1HeapRegionAttr dest) {
4156   _bytes_used_during_gc += allocated_bytes;
4157   if (dest.is_old()) {
4158     old_set_add(alloc_region);
4159   } else {
4160     assert(dest.is_young(), "Retiring alloc region should be young (%d)", dest.type());
4161     _survivor.add_used_bytes(allocated_bytes);
4162   }
4163 
4164   bool const during_im = collector_state()->in_concurrent_start_gc();
4165   if (during_im && allocated_bytes > 0) {
4166     _cm->root_regions()->add(alloc_region->next_top_at_mark_start(), alloc_region->top());
4167   }
4168   _hr_printer.retire(alloc_region);
4169 }
4170 
4171 HeapRegion* G1CollectedHeap::alloc_highest_free_region() {
4172   bool expanded = false;
4173   uint index = _hrm.find_highest_free(&expanded);
4174 
4175   if (index != G1_NO_HRM_INDEX) {
4176     if (expanded) {
4177       log_debug(gc, ergo, heap)("Attempt heap expansion (requested address range outside heap bounds). region size: " SIZE_FORMAT "B",
4178                                 HeapRegion::GrainWords * HeapWordSize);
4179     }
4180     return _hrm.allocate_free_regions_starting_at(index, 1);
4181   }
4182   return NULL;
4183 }
4184 
4185 // Optimized nmethod scanning
4186 
4187 class RegisterNMethodOopClosure: public OopClosure {
4188   G1CollectedHeap* _g1h;
4189   nmethod* _nm;
4190 
4191   template <class T> void do_oop_work(T* p) {
4192     T heap_oop = RawAccess<>::oop_load(p);
4193     if (!CompressedOops::is_null(heap_oop)) {
4194       oop obj = CompressedOops::decode_not_null(heap_oop);
4195       HeapRegion* hr = _g1h->heap_region_containing(obj);
4196       assert(!hr->is_continues_humongous(),
4197              "trying to add code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT
4198              " starting at " HR_FORMAT,
4199              p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()));
4200 
4201       // HeapRegion::add_strong_code_root_locked() avoids adding duplicate entries.
4202       hr->add_strong_code_root_locked(_nm);
4203     }
4204   }
4205 
4206 public:
4207   RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
4208     _g1h(g1h), _nm(nm) {}
4209 
4210   void do_oop(oop* p)       { do_oop_work(p); }
4211   void do_oop(narrowOop* p) { do_oop_work(p); }
4212 };
4213 
4214 class UnregisterNMethodOopClosure: public OopClosure {
4215   G1CollectedHeap* _g1h;
4216   nmethod* _nm;
4217 
4218   template <class T> void do_oop_work(T* p) {
4219     T heap_oop = RawAccess<>::oop_load(p);
4220     if (!CompressedOops::is_null(heap_oop)) {
4221       oop obj = CompressedOops::decode_not_null(heap_oop);
4222       HeapRegion* hr = _g1h->heap_region_containing(obj);
4223       assert(!hr->is_continues_humongous(),
4224              "trying to remove code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT
4225              " starting at " HR_FORMAT,
4226              p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()));
4227 
4228       hr->remove_strong_code_root(_nm);
4229     }
4230   }
4231 
4232 public:
4233   UnregisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
4234     _g1h(g1h), _nm(nm) {}
4235 
4236   void do_oop(oop* p)       { do_oop_work(p); }
4237   void do_oop(narrowOop* p) { do_oop_work(p); }
4238 };
4239 
4240 void G1CollectedHeap::register_nmethod(nmethod* nm) {
4241   guarantee(nm != NULL, "sanity");
4242   RegisterNMethodOopClosure reg_cl(this, nm);
4243   nm->oops_do(&reg_cl);
4244 }
4245 
4246 void G1CollectedHeap::unregister_nmethod(nmethod* nm) {
4247   guarantee(nm != NULL, "sanity");
4248   UnregisterNMethodOopClosure reg_cl(this, nm);
4249   nm->oops_do(&reg_cl, true);
4250 }
4251 
4252 void G1CollectedHeap::update_used_after_gc() {
4253   if (evacuation_failed()) {
4254     // Reset the G1EvacuationFailureALot counters and flags
4255     NOT_PRODUCT(reset_evacuation_should_fail();)
4256 
4257     set_used(recalculate_used());
4258 
4259     if (_archive_allocator != NULL) {
4260       _archive_allocator->clear_used();
4261     }
4262     for (uint i = 0; i < ParallelGCThreads; i++) {
4263       if (_evacuation_failed_info_array[i].has_failed()) {
4264         _gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]);
4265       }
4266     }
4267   } else {
4268     // The "used" of the the collection set have already been subtracted
4269     // when they were freed.  Add in the bytes used.
4270     increase_used(_bytes_used_during_gc);
4271   }
4272 }
4273 
4274 void G1CollectedHeap::reset_hot_card_cache() {
4275   _hot_card_cache->reset_hot_cache();
4276   _hot_card_cache->set_use_cache(true);
4277 }
4278 
4279 void G1CollectedHeap::purge_code_root_memory() {
4280   G1CodeRootSet::purge();
4281 }
4282 
4283 class RebuildStrongCodeRootClosure: public CodeBlobClosure {
4284   G1CollectedHeap* _g1h;
4285 
4286 public:
4287   RebuildStrongCodeRootClosure(G1CollectedHeap* g1h) :
4288     _g1h(g1h) {}
4289 
4290   void do_code_blob(CodeBlob* cb) {
4291     nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL;
4292     if (nm == NULL) {
4293       return;
4294     }
4295 
4296     _g1h->register_nmethod(nm);
4297   }
4298 };
4299 
4300 void G1CollectedHeap::rebuild_strong_code_roots() {
4301   RebuildStrongCodeRootClosure blob_cl(this);
4302   CodeCache::blobs_do(&blob_cl);
4303 }
4304 
4305 void G1CollectedHeap::initialize_serviceability() {
4306   _g1mm->initialize_serviceability();
4307 }
4308 
4309 MemoryUsage G1CollectedHeap::memory_usage() {
4310   return _g1mm->memory_usage();
4311 }
4312 
4313 GrowableArray<GCMemoryManager*> G1CollectedHeap::memory_managers() {
4314   return _g1mm->memory_managers();
4315 }
4316 
4317 GrowableArray<MemoryPool*> G1CollectedHeap::memory_pools() {
4318   return _g1mm->memory_pools();
4319 }