1 /*
   2  * Copyright (c) 2001, 2022, 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/g1BatchedTask.hpp"
  36 #include "gc/g1/g1CollectedHeap.inline.hpp"
  37 #include "gc/g1/g1CollectionSet.hpp"
  38 #include "gc/g1/g1CollectionSetCandidates.hpp"
  39 #include "gc/g1/g1CollectorState.hpp"
  40 #include "gc/g1/g1ConcurrentRefine.hpp"
  41 #include "gc/g1/g1ConcurrentRefineThread.hpp"
  42 #include "gc/g1/g1ConcurrentMarkThread.inline.hpp"
  43 #include "gc/g1/g1DirtyCardQueue.hpp"
  44 #include "gc/g1/g1EvacStats.inline.hpp"
  45 #include "gc/g1/g1FullCollector.hpp"
  46 #include "gc/g1/g1GCCounters.hpp"
  47 #include "gc/g1/g1GCParPhaseTimesTracker.hpp"
  48 #include "gc/g1/g1GCPhaseTimes.hpp"
  49 #include "gc/g1/g1GCPauseType.hpp"
  50 #include "gc/g1/g1HeapSizingPolicy.hpp"
  51 #include "gc/g1/g1HeapTransition.hpp"
  52 #include "gc/g1/g1HeapVerifier.hpp"
  53 #include "gc/g1/g1HotCardCache.hpp"
  54 #include "gc/g1/g1InitLogger.hpp"
  55 #include "gc/g1/g1MemoryPool.hpp"
  56 #include "gc/g1/g1OopClosures.inline.hpp"
  57 #include "gc/g1/g1ParallelCleaning.hpp"
  58 #include "gc/g1/g1ParScanThreadState.inline.hpp"
  59 #include "gc/g1/g1PeriodicGCTask.hpp"
  60 #include "gc/g1/g1Policy.hpp"
  61 #include "gc/g1/g1RedirtyCardsQueue.hpp"
  62 #include "gc/g1/g1RegionToSpaceMapper.hpp"
  63 #include "gc/g1/g1RemSet.hpp"
  64 #include "gc/g1/g1RootClosures.hpp"
  65 #include "gc/g1/g1RootProcessor.hpp"
  66 #include "gc/g1/g1SATBMarkQueueSet.hpp"
  67 #include "gc/g1/g1SegmentedArrayFreeMemoryTask.hpp"
  68 #include "gc/g1/g1ServiceThread.hpp"
  69 #include "gc/g1/g1ThreadLocalData.hpp"
  70 #include "gc/g1/g1Trace.hpp"
  71 #include "gc/g1/g1UncommitRegionTask.hpp"
  72 #include "gc/g1/g1VMOperations.hpp"
  73 #include "gc/g1/g1YoungCollector.hpp"
  74 #include "gc/g1/g1YoungGCEvacFailureInjector.hpp"
  75 #include "gc/g1/heapRegion.inline.hpp"
  76 #include "gc/g1/heapRegionRemSet.inline.hpp"
  77 #include "gc/g1/heapRegionSet.inline.hpp"
  78 #include "gc/shared/concurrentGCBreakpoints.hpp"
  79 #include "gc/shared/gcBehaviours.hpp"
  80 #include "gc/shared/gcHeapSummary.hpp"
  81 #include "gc/shared/gcId.hpp"
  82 #include "gc/shared/gcLocker.hpp"
  83 #include "gc/shared/gcTimer.hpp"
  84 #include "gc/shared/gcTraceTime.inline.hpp"
  85 #include "gc/shared/generationSpec.hpp"
  86 #include "gc/shared/isGCActiveMark.hpp"
  87 #include "gc/shared/locationPrinter.inline.hpp"
  88 #include "gc/shared/oopStorageParState.hpp"
  89 #include "gc/shared/preservedMarks.inline.hpp"
  90 #include "gc/shared/slidingForwarding.inline.hpp"
  91 #include "gc/shared/suspendibleThreadSet.hpp"
  92 #include "gc/shared/referenceProcessor.inline.hpp"
  93 #include "gc/shared/suspendibleThreadSet.hpp"
  94 #include "gc/shared/taskqueue.inline.hpp"
  95 #include "gc/shared/taskTerminator.hpp"
  96 #include "gc/shared/tlab_globals.hpp"
  97 #include "gc/shared/workerPolicy.hpp"
  98 #include "gc/shared/weakProcessor.inline.hpp"
  99 #include "logging/log.hpp"
 100 #include "memory/allocation.hpp"
 101 #include "memory/heapInspection.hpp"
 102 #include "memory/iterator.hpp"
 103 #include "memory/metaspaceUtils.hpp"
 104 #include "memory/resourceArea.hpp"
 105 #include "memory/universe.hpp"
 106 #include "oops/access.inline.hpp"
 107 #include "oops/compressedOops.inline.hpp"
 108 #include "oops/oop.inline.hpp"
 109 #include "runtime/atomic.hpp"
 110 #include "runtime/handles.inline.hpp"
 111 #include "runtime/init.hpp"
 112 #include "runtime/java.hpp"
 113 #include "runtime/orderAccess.hpp"
 114 #include "runtime/threadSMR.hpp"
 115 #include "runtime/vmThread.hpp"
 116 #include "utilities/align.hpp"
 117 #include "utilities/autoRestore.hpp"
 118 #include "utilities/bitMap.inline.hpp"
 119 #include "utilities/globalDefinitions.hpp"
 120 #include "utilities/stack.inline.hpp"
 121 
 122 size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
 123 
 124 // INVARIANTS/NOTES
 125 //
 126 // All allocation activity covered by the G1CollectedHeap interface is
 127 // serialized by acquiring the HeapLock.  This happens in mem_allocate
 128 // and allocate_new_tlab, which are the "entry" points to the
 129 // allocation code from the rest of the JVM.  (Note that this does not
 130 // apply to TLAB allocation, which is not part of this interface: it
 131 // is done by clients of this interface.)
 132 
 133 void G1RegionMappingChangedListener::reset_from_card_cache(uint start_idx, size_t num_regions) {
 134   HeapRegionRemSet::invalidate_from_card_cache(start_idx, num_regions);
 135 }
 136 
 137 void G1RegionMappingChangedListener::on_commit(uint start_idx, size_t num_regions, bool zero_filled) {
 138   // The from card cache is not the memory that is actually committed. So we cannot
 139   // take advantage of the zero_filled parameter.
 140   reset_from_card_cache(start_idx, num_regions);
 141 }
 142 
 143 void G1CollectedHeap::run_batch_task(G1BatchedTask* cl) {
 144   uint num_workers = MAX2(1u, MIN2(cl->num_workers_estimate(), workers()->active_workers()));
 145   cl->set_max_workers(num_workers);
 146   workers()->run_task(cl, num_workers);
 147 }
 148 
 149 HeapRegion* G1CollectedHeap::new_heap_region(uint hrs_index,
 150                                              MemRegion mr) {
 151   return new HeapRegion(hrs_index, bot(), mr, &_card_set_config);
 152 }
 153 
 154 // Private methods.
 155 
 156 HeapRegion* G1CollectedHeap::new_region(size_t word_size,
 157                                         HeapRegionType type,
 158                                         bool do_expand,
 159                                         uint node_index) {
 160   assert(!is_humongous(word_size) || word_size <= HeapRegion::GrainWords,
 161          "the only time we use this to allocate a humongous region is "
 162          "when we are allocating a single humongous region");
 163 
 164   HeapRegion* res = _hrm.allocate_free_region(type, node_index);
 165 
 166   if (res == NULL && do_expand) {
 167     // Currently, only attempts to allocate GC alloc regions set
 168     // do_expand to true. So, we should only reach here during a
 169     // safepoint.
 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     }
 185   }
 186   return res;
 187 }
 188 
 189 HeapWord*
 190 G1CollectedHeap::humongous_obj_allocate_initialize_regions(HeapRegion* first_hr,
 191                                                            uint num_regions,
 192                                                            size_t word_size) {
 193   assert(first_hr != NULL, "pre-condition");
 194   assert(is_humongous(word_size), "word_size should be humongous");
 195   assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");
 196 
 197   // Index of last region in the series.
 198   uint first = first_hr->hrm_index();
 199   uint last = first + num_regions - 1;
 200 
 201   // We need to initialize the region(s) we just discovered. This is
 202   // a bit tricky given that it can happen concurrently with
 203   // refinement threads refining cards on these regions and
 204   // potentially wanting to refine the BOT as they are scanning
 205   // those cards (this can happen shortly after a cleanup; see CR
 206   // 6991377). So we have to set up the region(s) carefully and in
 207   // a specific order.
 208 
 209   // The word size sum of all the regions we will allocate.
 210   size_t word_size_sum = (size_t) num_regions * HeapRegion::GrainWords;
 211   assert(word_size <= word_size_sum, "sanity");
 212 
 213   // The passed in hr will be the "starts humongous" region. The header
 214   // of the new object will be placed at the bottom of this region.
 215   HeapWord* new_obj = first_hr->bottom();
 216   // This will be the new top of the new object.
 217   HeapWord* obj_top = new_obj + word_size;
 218 
 219   // First, we need to zero the header of the space that we will be
 220   // allocating. When we update top further down, some refinement
 221   // threads might try to scan the region. By zeroing the header we
 222   // ensure that any thread that will try to scan the region will
 223   // come across the zero klass word and bail out.
 224   //
 225   // NOTE: It would not have been correct to have used
 226   // CollectedHeap::fill_with_object() and make the space look like
 227   // an int array. The thread that is doing the allocation will
 228   // later update the object header to a potentially different array
 229   // type and, for a very short period of time, the klass and length
 230   // fields will be inconsistent. This could cause a refinement
 231   // thread to calculate the object size incorrectly.
 232   Copy::fill_to_words(new_obj, oopDesc::header_size(), 0);
 233 
 234   // Next, pad out the unused tail of the last region with filler
 235   // objects, for improved usage accounting.
 236   // How many words we use for filler objects.
 237   size_t word_fill_size = word_size_sum - word_size;
 238 
 239   // How many words memory we "waste" which cannot hold a filler object.
 240   size_t words_not_fillable = 0;
 241 
 242   if (word_fill_size >= min_fill_size()) {
 243     fill_with_objects(obj_top, word_fill_size);
 244   } else if (word_fill_size > 0) {
 245     // We have space to fill, but we cannot fit an object there.
 246     words_not_fillable = word_fill_size;
 247     word_fill_size = 0;
 248   }
 249 
 250   // We will set up the first region as "starts humongous". This
 251   // will also update the BOT covering all the regions to reflect
 252   // that there is a single object that starts at the bottom of the
 253   // first region.
 254   first_hr->set_starts_humongous(obj_top, word_fill_size);
 255   _policy->remset_tracker()->update_at_allocate(first_hr);
 256   // Then, if there are any, we will set up the "continues
 257   // humongous" regions.
 258   HeapRegion* hr = NULL;
 259   for (uint i = first + 1; i <= last; ++i) {
 260     hr = region_at(i);
 261     hr->set_continues_humongous(first_hr);
 262     _policy->remset_tracker()->update_at_allocate(hr);
 263   }
 264 
 265   // Up to this point no concurrent thread would have been able to
 266   // do any scanning on any region in this series. All the top
 267   // fields still point to bottom, so the intersection between
 268   // [bottom,top] and [card_start,card_end] will be empty. Before we
 269   // update the top fields, we'll do a storestore to make sure that
 270   // no thread sees the update to top before the zeroing of the
 271   // object header and the BOT initialization.
 272   OrderAccess::storestore();
 273 
 274   // Now, we will update the top fields of the "continues humongous"
 275   // regions except the last one.
 276   for (uint i = first; i < last; ++i) {
 277     hr = region_at(i);
 278     hr->set_top(hr->end());
 279   }
 280 
 281   hr = region_at(last);
 282   // If we cannot fit a filler object, we must set top to the end
 283   // of the humongous object, otherwise we cannot iterate the heap
 284   // and the BOT will not be complete.
 285   hr->set_top(hr->end() - words_not_fillable);
 286 
 287   assert(hr->bottom() < obj_top && obj_top <= hr->end(),
 288          "obj_top should be in last region");
 289 
 290   _verifier->check_bitmaps("Humongous Region Allocation", first_hr);
 291 
 292   assert(words_not_fillable == 0 ||
 293          first_hr->bottom() + word_size_sum - words_not_fillable == hr->top(),
 294          "Miscalculation in humongous allocation");
 295 
 296   increase_used((word_size_sum - words_not_fillable) * HeapWordSize);
 297 
 298   for (uint i = first; i <= last; ++i) {
 299     hr = region_at(i);
 300     _humongous_set.add(hr);
 301     _hr_printer.alloc(hr);
 302   }
 303 
 304   return new_obj;
 305 }
 306 
 307 size_t G1CollectedHeap::humongous_obj_size_in_regions(size_t word_size) {
 308   assert(is_humongous(word_size), "Object of size " SIZE_FORMAT " must be humongous here", word_size);
 309   return align_up(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords;
 310 }
 311 
 312 // If could fit into free regions w/o expansion, try.
 313 // Otherwise, if can expand, do so.
 314 // Otherwise, if using ex regions might help, try with ex given back.
 315 HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size) {
 316   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
 317 
 318   _verifier->verify_region_sets_optional();
 319 
 320   uint obj_regions = (uint) humongous_obj_size_in_regions(word_size);
 321 
 322   // Policy: First try to allocate a humongous object in the free list.
 323   HeapRegion* humongous_start = _hrm.allocate_humongous(obj_regions);
 324   if (humongous_start == NULL) {
 325     // Policy: We could not find enough regions for the humongous object in the
 326     // free list. Look through the heap to find a mix of free and uncommitted regions.
 327     // If so, expand the heap and allocate the humongous object.
 328     humongous_start = _hrm.expand_and_allocate_humongous(obj_regions);
 329     if (humongous_start != NULL) {
 330       // We managed to find a region by expanding the heap.
 331       log_debug(gc, ergo, heap)("Heap expansion (humongous allocation request). Allocation request: " SIZE_FORMAT "B",
 332                                 word_size * HeapWordSize);
 333       policy()->record_new_heap_size(num_regions());
 334     } else {
 335       // Policy: Potentially trigger a defragmentation GC.
 336     }
 337   }
 338 
 339   HeapWord* result = NULL;
 340   if (humongous_start != NULL) {
 341     result = humongous_obj_allocate_initialize_regions(humongous_start, obj_regions, word_size);
 342     assert(result != NULL, "it should always return a valid result");
 343 
 344     // A successful humongous object allocation changes the used space
 345     // information of the old generation so we need to recalculate the
 346     // sizes and update the jstat counters here.
 347     monitoring_support()->update_sizes();
 348   }
 349 
 350   _verifier->verify_region_sets_optional();
 351 
 352   return result;
 353 }
 354 
 355 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t min_size,
 356                                              size_t requested_size,
 357                                              size_t* actual_size) {
 358   assert_heap_not_locked_and_not_at_safepoint();
 359   assert(!is_humongous(requested_size), "we do not allow humongous TLABs");
 360 
 361   return attempt_allocation(min_size, requested_size, actual_size);
 362 }
 363 
 364 HeapWord*
 365 G1CollectedHeap::mem_allocate(size_t word_size,
 366                               bool*  gc_overhead_limit_was_exceeded) {
 367   assert_heap_not_locked_and_not_at_safepoint();
 368 
 369   if (is_humongous(word_size)) {
 370     return attempt_allocation_humongous(word_size);
 371   }
 372   size_t dummy = 0;
 373   return attempt_allocation(word_size, word_size, &dummy);
 374 }
 375 
 376 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size) {
 377   ResourceMark rm; // For retrieving the thread names in log messages.
 378 
 379   // Make sure you read the note in attempt_allocation_humongous().
 380 
 381   assert_heap_not_locked_and_not_at_safepoint();
 382   assert(!is_humongous(word_size), "attempt_allocation_slow() should not "
 383          "be called for humongous allocation requests");
 384 
 385   // We should only get here after the first-level allocation attempt
 386   // (attempt_allocation()) failed to allocate.
 387 
 388   // We will loop until a) we manage to successfully perform the
 389   // allocation or b) we successfully schedule a collection which
 390   // fails to perform the allocation. b) is the only case when we'll
 391   // return NULL.
 392   HeapWord* result = NULL;
 393   for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
 394     bool should_try_gc;
 395     bool preventive_collection_required = false;
 396     uint gc_count_before;
 397 
 398     {
 399       MutexLocker x(Heap_lock);
 400 
 401       // Now that we have the lock, we first retry the allocation in case another
 402       // thread changed the region while we were waiting to acquire the lock.
 403       size_t actual_size;
 404       result = _allocator->attempt_allocation(word_size, word_size, &actual_size);
 405       if (result != NULL) {
 406         return result;
 407       }
 408 
 409       preventive_collection_required = policy()->preventive_collection_required(1);
 410       if (!preventive_collection_required) {
 411         // We've already attempted a lock-free allocation above, so we don't want to
 412         // do it again. Let's jump straight to replacing the active region.
 413         result = _allocator->attempt_allocation_using_new_region(word_size);
 414         if (result != NULL) {
 415           return result;
 416         }
 417 
 418         // If the GCLocker is active and we are bound for a GC, try expanding young gen.
 419         // This is different to when only GCLocker::needs_gc() is set: try to avoid
 420         // waiting because the GCLocker is active to not wait too long.
 421         if (GCLocker::is_active_and_needs_gc() && policy()->can_expand_young_list()) {
 422           // No need for an ergo message here, can_expand_young_list() does this when
 423           // it returns true.
 424           result = _allocator->attempt_allocation_force(word_size);
 425           if (result != NULL) {
 426             return result;
 427           }
 428         }
 429       }
 430 
 431       // Only try a GC if the GCLocker does not signal the need for a GC. Wait until
 432       // the GCLocker initiated GC has been performed and then retry. This includes
 433       // the case when the GC Locker is not active but has not been performed.
 434       should_try_gc = !GCLocker::needs_gc();
 435       // Read the GC count while still holding the Heap_lock.
 436       gc_count_before = total_collections();
 437     }
 438 
 439     if (should_try_gc) {
 440       GCCause::Cause gc_cause = preventive_collection_required ? GCCause::_g1_preventive_collection
 441                                                               : GCCause::_g1_inc_collection_pause;
 442       bool succeeded;
 443       result = do_collection_pause(word_size, gc_count_before, &succeeded, gc_cause);
 444       if (result != NULL) {
 445         assert(succeeded, "only way to get back a non-NULL result");
 446         log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,
 447                              Thread::current()->name(), p2i(result));
 448         return result;
 449       }
 450 
 451       if (succeeded) {
 452         // We successfully scheduled a collection which failed to allocate. No
 453         // point in trying to allocate further. We'll just return NULL.
 454         log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "
 455                              SIZE_FORMAT " words", Thread::current()->name(), word_size);
 456         return NULL;
 457       }
 458       log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT " words",
 459                            Thread::current()->name(), word_size);
 460     } else {
 461       // Failed to schedule a collection.
 462       if (gclocker_retry_count > GCLockerRetryAllocationCount) {
 463         log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "
 464                                SIZE_FORMAT " words", Thread::current()->name(), word_size);
 465         return NULL;
 466       }
 467       log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());
 468       // The GCLocker is either active or the GCLocker initiated
 469       // GC has not yet been performed. Stall until it is and
 470       // then retry the allocation.
 471       GCLocker::stall_until_clear();
 472       gclocker_retry_count += 1;
 473     }
 474 
 475     // We can reach here if we were unsuccessful in scheduling a
 476     // collection (because another thread beat us to it) or if we were
 477     // stalled due to the GC locker. In either can we should retry the
 478     // allocation attempt in case another thread successfully
 479     // performed a collection and reclaimed enough space. We do the
 480     // first attempt (without holding the Heap_lock) here and the
 481     // follow-on attempt will be at the start of the next loop
 482     // iteration (after taking the Heap_lock).
 483     size_t dummy = 0;
 484     result = _allocator->attempt_allocation(word_size, word_size, &dummy);
 485     if (result != NULL) {
 486       return result;
 487     }
 488 
 489     // Give a warning if we seem to be looping forever.
 490     if ((QueuedAllocationWarningCount > 0) &&
 491         (try_count % QueuedAllocationWarningCount == 0)) {
 492       log_warning(gc, alloc)("%s:  Retried allocation %u times for " SIZE_FORMAT " words",
 493                              Thread::current()->name(), try_count, word_size);
 494     }
 495   }
 496 
 497   ShouldNotReachHere();
 498   return NULL;
 499 }
 500 
 501 void G1CollectedHeap::begin_archive_alloc_range(bool open) {
 502   assert_at_safepoint_on_vm_thread();
 503   assert(_archive_allocator == nullptr, "should not be initialized");
 504   _archive_allocator = G1ArchiveAllocator::create_allocator(this, open);
 505 }
 506 
 507 bool G1CollectedHeap::is_archive_alloc_too_large(size_t word_size) {
 508   // Allocations in archive regions cannot be of a size that would be considered
 509   // humongous even for a minimum-sized region, because G1 region sizes/boundaries
 510   // may be different at archive-restore time.
 511   return word_size >= humongous_threshold_for(HeapRegion::min_region_size_in_words());
 512 }
 513 
 514 HeapWord* G1CollectedHeap::archive_mem_allocate(size_t word_size) {
 515   assert_at_safepoint_on_vm_thread();
 516   assert(_archive_allocator != nullptr, "_archive_allocator not initialized");
 517   if (is_archive_alloc_too_large(word_size)) {
 518     return nullptr;
 519   }
 520   return _archive_allocator->archive_mem_allocate(word_size);
 521 }
 522 
 523 void G1CollectedHeap::end_archive_alloc_range(GrowableArray<MemRegion>* ranges,
 524                                               size_t end_alignment_in_bytes) {
 525   assert_at_safepoint_on_vm_thread();
 526   assert(_archive_allocator != nullptr, "_archive_allocator not initialized");
 527 
 528   // Call complete_archive to do the real work, filling in the MemRegion
 529   // array with the archive regions.
 530   _archive_allocator->complete_archive(ranges, end_alignment_in_bytes);
 531   delete _archive_allocator;
 532   _archive_allocator = nullptr;
 533 }
 534 
 535 bool G1CollectedHeap::check_archive_addresses(MemRegion* ranges, size_t count) {
 536   assert(ranges != NULL, "MemRegion array NULL");
 537   assert(count != 0, "No MemRegions provided");
 538   MemRegion reserved = _hrm.reserved();
 539   for (size_t i = 0; i < count; i++) {
 540     if (!reserved.contains(ranges[i].start()) || !reserved.contains(ranges[i].last())) {
 541       return false;
 542     }
 543   }
 544   return true;
 545 }
 546 
 547 bool G1CollectedHeap::alloc_archive_regions(MemRegion* ranges,
 548                                             size_t count,
 549                                             bool open) {
 550   assert(!is_init_completed(), "Expect to be called at JVM init time");
 551   assert(ranges != NULL, "MemRegion array NULL");
 552   assert(count != 0, "No MemRegions provided");
 553   MutexLocker x(Heap_lock);
 554 
 555   MemRegion reserved = _hrm.reserved();
 556   HeapWord* prev_last_addr = NULL;
 557   HeapRegion* prev_last_region = NULL;
 558 
 559   // Temporarily disable pretouching of heap pages. This interface is used
 560   // when mmap'ing archived heap data in, so pre-touching is wasted.
 561   FlagSetting fs(AlwaysPreTouch, false);
 562 
 563   // For each specified MemRegion range, allocate the corresponding G1
 564   // regions and mark them as archive regions. We expect the ranges
 565   // in ascending starting address order, without overlap.
 566   for (size_t i = 0; i < count; i++) {
 567     MemRegion curr_range = ranges[i];
 568     HeapWord* start_address = curr_range.start();
 569     size_t word_size = curr_range.word_size();
 570     HeapWord* last_address = curr_range.last();
 571     size_t commits = 0;
 572 
 573     guarantee(reserved.contains(start_address) && reserved.contains(last_address),
 574               "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
 575               p2i(start_address), p2i(last_address));
 576     guarantee(start_address > prev_last_addr,
 577               "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
 578               p2i(start_address), p2i(prev_last_addr));
 579     prev_last_addr = last_address;
 580 
 581     // Check for ranges that start in the same G1 region in which the previous
 582     // range ended, and adjust the start address so we don't try to allocate
 583     // the same region again. If the current range is entirely within that
 584     // region, skip it, just adjusting the recorded top.
 585     HeapRegion* start_region = _hrm.addr_to_region(start_address);
 586     if ((prev_last_region != NULL) && (start_region == prev_last_region)) {
 587       start_address = start_region->end();
 588       if (start_address > last_address) {
 589         increase_used(word_size * HeapWordSize);
 590         start_region->set_top(last_address + 1);
 591         continue;
 592       }
 593       start_region->set_top(start_address);
 594       curr_range = MemRegion(start_address, last_address + 1);
 595       start_region = _hrm.addr_to_region(start_address);
 596     }
 597 
 598     // Perform the actual region allocation, exiting if it fails.
 599     // Then note how much new space we have allocated.
 600     if (!_hrm.allocate_containing_regions(curr_range, &commits, workers())) {
 601       return false;
 602     }
 603     increase_used(word_size * HeapWordSize);
 604     if (commits != 0) {
 605       log_debug(gc, ergo, heap)("Attempt heap expansion (allocate archive regions). Total size: " SIZE_FORMAT "B",
 606                                 HeapRegion::GrainWords * HeapWordSize * commits);
 607 
 608     }
 609 
 610     // Mark each G1 region touched by the range as archive, add it to
 611     // the old set, and set top.
 612     HeapRegion* curr_region = _hrm.addr_to_region(start_address);
 613     HeapRegion* last_region = _hrm.addr_to_region(last_address);
 614     prev_last_region = last_region;
 615 
 616     while (curr_region != NULL) {
 617       assert(curr_region->is_empty() && !curr_region->is_pinned(),
 618              "Region already in use (index %u)", curr_region->hrm_index());
 619       if (open) {
 620         curr_region->set_open_archive();
 621       } else {
 622         curr_region->set_closed_archive();
 623       }
 624       _hr_printer.alloc(curr_region);
 625       _archive_set.add(curr_region);
 626       HeapWord* top;
 627       HeapRegion* next_region;
 628       if (curr_region != last_region) {
 629         top = curr_region->end();
 630         next_region = _hrm.next_region_in_heap(curr_region);
 631       } else {
 632         top = last_address + 1;
 633         next_region = NULL;
 634       }
 635       curr_region->set_top(top);
 636       curr_region = next_region;
 637     }
 638   }
 639   return true;
 640 }
 641 
 642 void G1CollectedHeap::fill_archive_regions(MemRegion* ranges, size_t count) {
 643   assert(!is_init_completed(), "Expect to be called at JVM init time");
 644   assert(ranges != NULL, "MemRegion array NULL");
 645   assert(count != 0, "No MemRegions provided");
 646   MemRegion reserved = _hrm.reserved();
 647   HeapWord *prev_last_addr = NULL;
 648   HeapRegion* prev_last_region = NULL;
 649 
 650   // For each MemRegion, create filler objects, if needed, in the G1 regions
 651   // that contain the address range. The address range actually within the
 652   // MemRegion will not be modified. That is assumed to have been initialized
 653   // elsewhere, probably via an mmap of archived heap data.
 654   MutexLocker x(Heap_lock);
 655   for (size_t i = 0; i < count; i++) {
 656     HeapWord* start_address = ranges[i].start();
 657     HeapWord* last_address = ranges[i].last();
 658 
 659     assert(reserved.contains(start_address) && reserved.contains(last_address),
 660            "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
 661            p2i(start_address), p2i(last_address));
 662     assert(start_address > prev_last_addr,
 663            "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
 664            p2i(start_address), p2i(prev_last_addr));
 665 
 666     HeapRegion* start_region = _hrm.addr_to_region(start_address);
 667     HeapRegion* last_region = _hrm.addr_to_region(last_address);
 668     HeapWord* bottom_address = start_region->bottom();
 669 
 670     // Check for a range beginning in the same region in which the
 671     // previous one ended.
 672     if (start_region == prev_last_region) {
 673       bottom_address = prev_last_addr + 1;
 674     }
 675 
 676     // Verify that the regions were all marked as archive regions by
 677     // alloc_archive_regions.
 678     HeapRegion* curr_region = start_region;
 679     while (curr_region != NULL) {
 680       guarantee(curr_region->is_archive(),
 681                 "Expected archive region at index %u", curr_region->hrm_index());
 682       if (curr_region != last_region) {
 683         curr_region = _hrm.next_region_in_heap(curr_region);
 684       } else {
 685         curr_region = NULL;
 686       }
 687     }
 688 
 689     prev_last_addr = last_address;
 690     prev_last_region = last_region;
 691 
 692     // Fill the memory below the allocated range with dummy object(s),
 693     // if the region bottom does not match the range start, or if the previous
 694     // range ended within the same G1 region, and there is a gap.
 695     assert(start_address >= bottom_address, "bottom address should not be greater than start address");
 696     if (start_address > bottom_address) {
 697       size_t fill_size = pointer_delta(start_address, bottom_address);
 698       G1CollectedHeap::fill_with_objects(bottom_address, fill_size);
 699       increase_used(fill_size * HeapWordSize);
 700     }
 701   }
 702 }
 703 
 704 inline HeapWord* G1CollectedHeap::attempt_allocation(size_t min_word_size,
 705                                                      size_t desired_word_size,
 706                                                      size_t* actual_word_size) {
 707   assert_heap_not_locked_and_not_at_safepoint();
 708   assert(!is_humongous(desired_word_size), "attempt_allocation() should not "
 709          "be called for humongous allocation requests");
 710 
 711   HeapWord* result = _allocator->attempt_allocation(min_word_size, desired_word_size, actual_word_size);
 712 
 713   if (result == NULL) {
 714     *actual_word_size = desired_word_size;
 715     result = attempt_allocation_slow(desired_word_size);
 716   }
 717 
 718   assert_heap_not_locked();
 719   if (result != NULL) {
 720     assert(*actual_word_size != 0, "Actual size must have been set here");
 721     dirty_young_block(result, *actual_word_size);
 722   } else {
 723     *actual_word_size = 0;
 724   }
 725 
 726   return result;
 727 }
 728 
 729 void G1CollectedHeap::populate_archive_regions_bot_part(MemRegion* ranges, size_t count) {
 730   assert(!is_init_completed(), "Expect to be called at JVM init time");
 731   assert(ranges != NULL, "MemRegion array NULL");
 732   assert(count != 0, "No MemRegions provided");
 733 
 734   HeapWord* st = ranges[0].start();
 735   HeapWord* last = ranges[count-1].last();
 736   HeapRegion* hr_st = _hrm.addr_to_region(st);
 737   HeapRegion* hr_last = _hrm.addr_to_region(last);
 738 
 739   HeapRegion* hr_curr = hr_st;
 740   while (hr_curr != NULL) {
 741     hr_curr->update_bot();
 742     if (hr_curr != hr_last) {
 743       hr_curr = _hrm.next_region_in_heap(hr_curr);
 744     } else {
 745       hr_curr = NULL;
 746     }
 747   }
 748 }
 749 
 750 void G1CollectedHeap::dealloc_archive_regions(MemRegion* ranges, size_t count) {
 751   assert(!is_init_completed(), "Expect to be called at JVM init time");
 752   assert(ranges != NULL, "MemRegion array NULL");
 753   assert(count != 0, "No MemRegions provided");
 754   MemRegion reserved = _hrm.reserved();
 755   HeapWord* prev_last_addr = NULL;
 756   HeapRegion* prev_last_region = NULL;
 757   size_t size_used = 0;
 758   uint shrink_count = 0;
 759 
 760   // For each Memregion, free the G1 regions that constitute it, and
 761   // notify mark-sweep that the range is no longer to be considered 'archive.'
 762   MutexLocker x(Heap_lock);
 763   for (size_t i = 0; i < count; i++) {
 764     HeapWord* start_address = ranges[i].start();
 765     HeapWord* last_address = ranges[i].last();
 766 
 767     assert(reserved.contains(start_address) && reserved.contains(last_address),
 768            "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
 769            p2i(start_address), p2i(last_address));
 770     assert(start_address > prev_last_addr,
 771            "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
 772            p2i(start_address), p2i(prev_last_addr));
 773     size_used += ranges[i].byte_size();
 774     prev_last_addr = last_address;
 775 
 776     HeapRegion* start_region = _hrm.addr_to_region(start_address);
 777     HeapRegion* last_region = _hrm.addr_to_region(last_address);
 778 
 779     // Check for ranges that start in the same G1 region in which the previous
 780     // range ended, and adjust the start address so we don't try to free
 781     // the same region again. If the current range is entirely within that
 782     // region, skip it.
 783     if (start_region == prev_last_region) {
 784       start_address = start_region->end();
 785       if (start_address > last_address) {
 786         continue;
 787       }
 788       start_region = _hrm.addr_to_region(start_address);
 789     }
 790     prev_last_region = last_region;
 791 
 792     // After verifying that each region was marked as an archive region by
 793     // alloc_archive_regions, set it free and empty and uncommit it.
 794     HeapRegion* curr_region = start_region;
 795     while (curr_region != NULL) {
 796       guarantee(curr_region->is_archive(),
 797                 "Expected archive region at index %u", curr_region->hrm_index());
 798       uint curr_index = curr_region->hrm_index();
 799       _archive_set.remove(curr_region);
 800       curr_region->set_free();
 801       curr_region->set_top(curr_region->bottom());
 802       if (curr_region != last_region) {
 803         curr_region = _hrm.next_region_in_heap(curr_region);
 804       } else {
 805         curr_region = NULL;
 806       }
 807 
 808       _hrm.shrink_at(curr_index, 1);
 809       shrink_count++;
 810     }
 811   }
 812 
 813   if (shrink_count != 0) {
 814     log_debug(gc, ergo, heap)("Attempt heap shrinking (archive regions). Total size: " SIZE_FORMAT "B",
 815                               HeapRegion::GrainWords * HeapWordSize * shrink_count);
 816     // Explicit uncommit.
 817     uncommit_regions(shrink_count);
 818   }
 819   decrease_used(size_used);
 820 }
 821 
 822 HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size) {
 823   ResourceMark rm; // For retrieving the thread names in log messages.
 824 
 825   // The structure of this method has a lot of similarities to
 826   // attempt_allocation_slow(). The reason these two were not merged
 827   // into a single one is that such a method would require several "if
 828   // allocation is not humongous do this, otherwise do that"
 829   // conditional paths which would obscure its flow. In fact, an early
 830   // version of this code did use a unified method which was harder to
 831   // follow and, as a result, it had subtle bugs that were hard to
 832   // track down. So keeping these two methods separate allows each to
 833   // be more readable. It will be good to keep these two in sync as
 834   // much as possible.
 835 
 836   assert_heap_not_locked_and_not_at_safepoint();
 837   assert(is_humongous(word_size), "attempt_allocation_humongous() "
 838          "should only be called for humongous allocations");
 839 
 840   // Humongous objects can exhaust the heap quickly, so we should check if we
 841   // need to start a marking cycle at each humongous object allocation. We do
 842   // the check before we do the actual allocation. The reason for doing it
 843   // before the allocation is that we avoid having to keep track of the newly
 844   // allocated memory while we do a GC.
 845   if (policy()->need_to_start_conc_mark("concurrent humongous allocation",
 846                                         word_size)) {
 847     collect(GCCause::_g1_humongous_allocation);
 848   }
 849 
 850   // We will loop until a) we manage to successfully perform the
 851   // allocation or b) we successfully schedule a collection which
 852   // fails to perform the allocation. b) is the only case when we'll
 853   // return NULL.
 854   HeapWord* result = NULL;
 855   for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
 856     bool should_try_gc;
 857     bool preventive_collection_required = false;
 858     uint gc_count_before;
 859 
 860 
 861     {
 862       MutexLocker x(Heap_lock);
 863 
 864       size_t size_in_regions = humongous_obj_size_in_regions(word_size);
 865       preventive_collection_required = policy()->preventive_collection_required((uint)size_in_regions);
 866       if (!preventive_collection_required) {
 867         // Given that humongous objects are not allocated in young
 868         // regions, we'll first try to do the allocation without doing a
 869         // collection hoping that there's enough space in the heap.
 870         result = humongous_obj_allocate(word_size);
 871         if (result != NULL) {
 872           policy()->old_gen_alloc_tracker()->
 873             add_allocated_humongous_bytes_since_last_gc(size_in_regions * HeapRegion::GrainBytes);
 874           return result;
 875         }
 876       }
 877 
 878       // Only try a GC if the GCLocker does not signal the need for a GC. Wait until
 879       // the GCLocker initiated GC has been performed and then retry. This includes
 880       // the case when the GC Locker is not active but has not been performed.
 881       should_try_gc = !GCLocker::needs_gc();
 882       // Read the GC count while still holding the Heap_lock.
 883       gc_count_before = total_collections();
 884     }
 885 
 886     if (should_try_gc) {
 887       GCCause::Cause gc_cause = preventive_collection_required ? GCCause::_g1_preventive_collection
 888                                                               : GCCause::_g1_humongous_allocation;
 889       bool succeeded;
 890       result = do_collection_pause(word_size, gc_count_before, &succeeded, gc_cause);
 891       if (result != NULL) {
 892         assert(succeeded, "only way to get back a non-NULL result");
 893         log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,
 894                              Thread::current()->name(), p2i(result));
 895         size_t size_in_regions = humongous_obj_size_in_regions(word_size);
 896         policy()->old_gen_alloc_tracker()->
 897           record_collection_pause_humongous_allocation(size_in_regions * HeapRegion::GrainBytes);
 898         return result;
 899       }
 900 
 901       if (succeeded) {
 902         // We successfully scheduled a collection which failed to allocate. No
 903         // point in trying to allocate further. We'll just return NULL.
 904         log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "
 905                              SIZE_FORMAT " words", Thread::current()->name(), word_size);
 906         return NULL;
 907       }
 908       log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT "",
 909                            Thread::current()->name(), word_size);
 910     } else {
 911       // Failed to schedule a collection.
 912       if (gclocker_retry_count > GCLockerRetryAllocationCount) {
 913         log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "
 914                                SIZE_FORMAT " words", Thread::current()->name(), word_size);
 915         return NULL;
 916       }
 917       log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());
 918       // The GCLocker is either active or the GCLocker initiated
 919       // GC has not yet been performed. Stall until it is and
 920       // then retry the allocation.
 921       GCLocker::stall_until_clear();
 922       gclocker_retry_count += 1;
 923     }
 924 
 925 
 926     // We can reach here if we were unsuccessful in scheduling a
 927     // collection (because another thread beat us to it) or if we were
 928     // stalled due to the GC locker. In either can we should retry the
 929     // allocation attempt in case another thread successfully
 930     // performed a collection and reclaimed enough space.
 931     // Humongous object allocation always needs a lock, so we wait for the retry
 932     // in the next iteration of the loop, unlike for the regular iteration case.
 933     // Give a warning if we seem to be looping forever.
 934 
 935     if ((QueuedAllocationWarningCount > 0) &&
 936         (try_count % QueuedAllocationWarningCount == 0)) {
 937       log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words",
 938                              Thread::current()->name(), try_count, word_size);
 939     }
 940   }
 941 
 942   ShouldNotReachHere();
 943   return NULL;
 944 }
 945 
 946 HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size,
 947                                                            bool expect_null_mutator_alloc_region) {
 948   assert_at_safepoint_on_vm_thread();
 949   assert(!_allocator->has_mutator_alloc_region() || !expect_null_mutator_alloc_region,
 950          "the current alloc region was unexpectedly found to be non-NULL");
 951 
 952   if (!is_humongous(word_size)) {
 953     return _allocator->attempt_allocation_locked(word_size);
 954   } else {
 955     HeapWord* result = humongous_obj_allocate(word_size);
 956     if (result != NULL && policy()->need_to_start_conc_mark("STW humongous allocation")) {
 957       collector_state()->set_initiate_conc_mark_if_possible(true);
 958     }
 959     return result;
 960   }
 961 
 962   ShouldNotReachHere();
 963 }
 964 
 965 class PostCompactionPrinterClosure: public HeapRegionClosure {
 966 private:
 967   G1HRPrinter* _hr_printer;
 968 public:
 969   bool do_heap_region(HeapRegion* hr) {
 970     assert(!hr->is_young(), "not expecting to find young regions");
 971     _hr_printer->post_compaction(hr);
 972     return false;
 973   }
 974 
 975   PostCompactionPrinterClosure(G1HRPrinter* hr_printer)
 976     : _hr_printer(hr_printer) { }
 977 };
 978 
 979 void G1CollectedHeap::print_heap_after_full_collection() {
 980   // Post collection region logging.
 981   // We should do this after we potentially resize the heap so
 982   // that all the COMMIT / UNCOMMIT events are generated before
 983   // the compaction events.
 984   if (_hr_printer.is_active()) {
 985     PostCompactionPrinterClosure cl(hr_printer());
 986     heap_region_iterate(&cl);
 987   }
 988 }
 989 
 990 void G1CollectedHeap::abort_concurrent_cycle() {
 991   // If we start the compaction before the CM threads finish
 992   // scanning the root regions we might trip them over as we'll
 993   // be moving objects / updating references. So let's wait until
 994   // they are done. By telling them to abort, they should complete
 995   // early.
 996   _cm->root_regions()->abort();
 997   _cm->root_regions()->wait_until_scan_finished();
 998 
 999   // Disable discovery and empty the discovered lists
1000   // for the CM ref processor.
1001   _ref_processor_cm->disable_discovery();
1002   _ref_processor_cm->abandon_partial_discovery();
1003   _ref_processor_cm->verify_no_references_recorded();
1004 
1005   // Abandon current iterations of concurrent marking and concurrent
1006   // refinement, if any are in progress.
1007   concurrent_mark()->concurrent_cycle_abort();
1008 }
1009 
1010 void G1CollectedHeap::prepare_heap_for_full_collection() {
1011   // Make sure we'll choose a new allocation region afterwards.
1012   _allocator->release_mutator_alloc_regions();
1013   _allocator->abandon_gc_alloc_regions();
1014 
1015   // We may have added regions to the current incremental collection
1016   // set between the last GC or pause and now. We need to clear the
1017   // incremental collection set and then start rebuilding it afresh
1018   // after this full GC.
1019   abandon_collection_set(collection_set());
1020 
1021   _hrm.remove_all_free_regions();
1022 }
1023 
1024 void G1CollectedHeap::verify_before_full_collection(bool explicit_gc) {
1025   assert(!GCCause::is_user_requested_gc(gc_cause()) || explicit_gc, "invariant");
1026   assert_used_and_recalculate_used_equal(this);
1027   if (!VerifyBeforeGC) {
1028     return;
1029   }
1030   _verifier->verify_region_sets_optional();
1031   _verifier->verify_before_gc(G1HeapVerifier::G1VerifyFull);
1032   _verifier->check_bitmaps("Full GC Start");
1033 }
1034 
1035 void G1CollectedHeap::prepare_heap_for_mutators() {
1036   // Delete metaspaces for unloaded class loaders and clean up loader_data graph
1037   ClassLoaderDataGraph::purge(/*at_safepoint*/true);
1038   DEBUG_ONLY(MetaspaceUtils::verify();)
1039 
1040   // Prepare heap for normal collections.
1041   assert(num_free_regions() == 0, "we should not have added any free regions");
1042   rebuild_region_sets(false /* free_list_only */);
1043   abort_refinement();
1044   resize_heap_if_necessary();
1045   uncommit_regions_if_necessary();
1046 
1047   // Rebuild the code root lists for each region
1048   rebuild_code_roots();
1049 
1050   // Purge code root memory
1051   purge_code_root_memory();
1052 
1053   // Start a new incremental collection set for the next pause
1054   start_new_collection_set();
1055 
1056   _allocator->init_mutator_alloc_regions();
1057 
1058   // Post collection state updates.
1059   MetaspaceGC::compute_new_size();
1060 }
1061 
1062 void G1CollectedHeap::abort_refinement() {
1063   if (_hot_card_cache->use_cache()) {
1064     _hot_card_cache->reset_hot_cache();
1065   }
1066 
1067   // Discard all remembered set updates and reset refinement statistics.
1068   G1BarrierSet::dirty_card_queue_set().abandon_logs();
1069   assert(G1BarrierSet::dirty_card_queue_set().num_cards() == 0,
1070          "DCQS should be empty");
1071   concurrent_refine()->get_and_reset_refinement_stats();
1072 }
1073 
1074 void G1CollectedHeap::verify_after_full_collection() {
1075   if (!VerifyAfterGC) {
1076     return;
1077   }
1078   _hrm.verify_optional();
1079   _verifier->verify_region_sets_optional();
1080   _verifier->verify_after_gc(G1HeapVerifier::G1VerifyFull);
1081 
1082   // This call implicitly verifies that the next bitmap is clear after Full GC.
1083   _verifier->check_bitmaps("Full GC End");
1084 
1085   // At this point there should be no regions in the
1086   // entire heap tagged as young.
1087   assert(check_young_list_empty(), "young list should be empty at this point");
1088 
1089   // Note: since we've just done a full GC, concurrent
1090   // marking is no longer active. Therefore we need not
1091   // re-enable reference discovery for the CM ref processor.
1092   // That will be done at the start of the next marking cycle.
1093   // We also know that the STW processor should no longer
1094   // discover any new references.
1095   assert(!_ref_processor_stw->discovery_enabled(), "Postcondition");
1096   assert(!_ref_processor_cm->discovery_enabled(), "Postcondition");
1097   _ref_processor_stw->verify_no_references_recorded();
1098   _ref_processor_cm->verify_no_references_recorded();
1099 }
1100 
1101 bool G1CollectedHeap::do_full_collection(bool explicit_gc,
1102                                          bool clear_all_soft_refs,
1103                                          bool do_maximal_compaction) {
1104   assert_at_safepoint_on_vm_thread();
1105 
1106   if (GCLocker::check_active_before_gc()) {
1107     // Full GC was not completed.
1108     return false;
1109   }
1110 
1111   const bool do_clear_all_soft_refs = clear_all_soft_refs ||
1112       soft_ref_policy()->should_clear_all_soft_refs();
1113 
1114   G1FullGCMark gc_mark;
1115   GCTraceTime(Info, gc) tm("Pause Full", NULL, gc_cause(), true);
1116   G1FullCollector collector(this, explicit_gc, do_clear_all_soft_refs, do_maximal_compaction);
1117 
1118   collector.prepare_collection();
1119   collector.collect();
1120   collector.complete_collection();
1121 
1122   // Full collection was successfully completed.
1123   return true;
1124 }
1125 
1126 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {
1127   // Currently, there is no facility in the do_full_collection(bool) API to notify
1128   // the caller that the collection did not succeed (e.g., because it was locked
1129   // out by the GC locker). So, right now, we'll ignore the return value.
1130   // When clear_all_soft_refs is set we want to do a maximal compaction
1131   // not leaving any dead wood.
1132   bool do_maximal_compaction = clear_all_soft_refs;
1133   bool dummy = do_full_collection(true,                /* explicit_gc */
1134                                   clear_all_soft_refs,
1135                                   do_maximal_compaction);
1136 }
1137 
1138 bool G1CollectedHeap::upgrade_to_full_collection() {
1139   GCCauseSetter compaction(this, GCCause::_g1_compaction_pause);
1140   log_info(gc, ergo)("Attempting full compaction clearing soft references");
1141   bool success = do_full_collection(false /* explicit gc */,
1142                                     true  /* clear_all_soft_refs */,
1143                                     false /* do_maximal_compaction */);
1144   // do_full_collection only fails if blocked by GC locker and that can't
1145   // be the case here since we only call this when already completed one gc.
1146   assert(success, "invariant");
1147   return success;
1148 }
1149 
1150 void G1CollectedHeap::resize_heap_if_necessary() {
1151   assert_at_safepoint_on_vm_thread();
1152 
1153   bool should_expand;
1154   size_t resize_amount = _heap_sizing_policy->full_collection_resize_amount(should_expand);
1155 
1156   if (resize_amount == 0) {
1157     return;
1158   } else if (should_expand) {
1159     expand(resize_amount, _workers);
1160   } else {
1161     shrink(resize_amount);
1162   }
1163 }
1164 
1165 HeapWord* G1CollectedHeap::satisfy_failed_allocation_helper(size_t word_size,
1166                                                             bool do_gc,
1167                                                             bool maximal_compaction,
1168                                                             bool expect_null_mutator_alloc_region,
1169                                                             bool* gc_succeeded) {
1170   *gc_succeeded = true;
1171   // Let's attempt the allocation first.
1172   HeapWord* result =
1173     attempt_allocation_at_safepoint(word_size,
1174                                     expect_null_mutator_alloc_region);
1175   if (result != NULL) {
1176     return result;
1177   }
1178 
1179   // In a G1 heap, we're supposed to keep allocation from failing by
1180   // incremental pauses.  Therefore, at least for now, we'll favor
1181   // expansion over collection.  (This might change in the future if we can
1182   // do something smarter than full collection to satisfy a failed alloc.)
1183   result = expand_and_allocate(word_size);
1184   if (result != NULL) {
1185     return result;
1186   }
1187 
1188   if (do_gc) {
1189     GCCauseSetter compaction(this, GCCause::_g1_compaction_pause);
1190     // Expansion didn't work, we'll try to do a Full GC.
1191     // If maximal_compaction is set we clear all soft references and don't
1192     // allow any dead wood to be left on the heap.
1193     if (maximal_compaction) {
1194       log_info(gc, ergo)("Attempting maximal full compaction clearing soft references");
1195     } else {
1196       log_info(gc, ergo)("Attempting full compaction");
1197     }
1198     *gc_succeeded = do_full_collection(false, /* explicit_gc */
1199                                        maximal_compaction /* clear_all_soft_refs */ ,
1200                                        maximal_compaction /* do_maximal_compaction */);
1201   }
1202 
1203   return NULL;
1204 }
1205 
1206 HeapWord* G1CollectedHeap::satisfy_failed_allocation(size_t word_size,
1207                                                      bool* succeeded) {
1208   assert_at_safepoint_on_vm_thread();
1209 
1210   // Attempts to allocate followed by Full GC.
1211   HeapWord* result =
1212     satisfy_failed_allocation_helper(word_size,
1213                                      true,  /* do_gc */
1214                                      false, /* maximum_collection */
1215                                      false, /* expect_null_mutator_alloc_region */
1216                                      succeeded);
1217 
1218   if (result != NULL || !*succeeded) {
1219     return result;
1220   }
1221 
1222   // Attempts to allocate followed by Full GC that will collect all soft references.
1223   result = satisfy_failed_allocation_helper(word_size,
1224                                             true, /* do_gc */
1225                                             true, /* maximum_collection */
1226                                             true, /* expect_null_mutator_alloc_region */
1227                                             succeeded);
1228 
1229   if (result != NULL || !*succeeded) {
1230     return result;
1231   }
1232 
1233   // Attempts to allocate, no GC
1234   result = satisfy_failed_allocation_helper(word_size,
1235                                             false, /* do_gc */
1236                                             false, /* maximum_collection */
1237                                             true,  /* expect_null_mutator_alloc_region */
1238                                             succeeded);
1239 
1240   if (result != NULL) {
1241     return result;
1242   }
1243 
1244   assert(!soft_ref_policy()->should_clear_all_soft_refs(),
1245          "Flag should have been handled and cleared prior to this point");
1246 
1247   // What else?  We might try synchronous finalization later.  If the total
1248   // space available is large enough for the allocation, then a more
1249   // complete compaction phase than we've tried so far might be
1250   // appropriate.
1251   return NULL;
1252 }
1253 
1254 // Attempting to expand the heap sufficiently
1255 // to support an allocation of the given "word_size".  If
1256 // successful, perform the allocation and return the address of the
1257 // allocated block, or else "NULL".
1258 
1259 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {
1260   assert_at_safepoint_on_vm_thread();
1261 
1262   _verifier->verify_region_sets_optional();
1263 
1264   size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes);
1265   log_debug(gc, ergo, heap)("Attempt heap expansion (allocation request failed). Allocation request: " SIZE_FORMAT "B",
1266                             word_size * HeapWordSize);
1267 
1268 
1269   if (expand(expand_bytes, _workers)) {
1270     _hrm.verify_optional();
1271     _verifier->verify_region_sets_optional();
1272     return attempt_allocation_at_safepoint(word_size,
1273                                            false /* expect_null_mutator_alloc_region */);
1274   }
1275   return NULL;
1276 }
1277 
1278 bool G1CollectedHeap::expand(size_t expand_bytes, WorkerThreads* pretouch_workers, double* expand_time_ms) {
1279   size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes);
1280   aligned_expand_bytes = align_up(aligned_expand_bytes,
1281                                        HeapRegion::GrainBytes);
1282 
1283   log_debug(gc, ergo, heap)("Expand the heap. requested expansion amount: " SIZE_FORMAT "B expansion amount: " SIZE_FORMAT "B",
1284                             expand_bytes, aligned_expand_bytes);
1285 
1286   if (is_maximal_no_gc()) {
1287     log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)");
1288     return false;
1289   }
1290 
1291   double expand_heap_start_time_sec = os::elapsedTime();
1292   uint regions_to_expand = (uint)(aligned_expand_bytes / HeapRegion::GrainBytes);
1293   assert(regions_to_expand > 0, "Must expand by at least one region");
1294 
1295   uint expanded_by = _hrm.expand_by(regions_to_expand, pretouch_workers);
1296   if (expand_time_ms != NULL) {
1297     *expand_time_ms = (os::elapsedTime() - expand_heap_start_time_sec) * MILLIUNITS;
1298   }
1299 
1300   if (expanded_by > 0) {
1301     size_t actual_expand_bytes = expanded_by * HeapRegion::GrainBytes;
1302     assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition");
1303     policy()->record_new_heap_size(num_regions());
1304   } else {
1305     log_debug(gc, ergo, heap)("Did not expand the heap (heap expansion operation failed)");
1306 
1307     // The expansion of the virtual storage space was unsuccessful.
1308     // Let's see if it was because we ran out of swap.
1309     if (G1ExitOnExpansionFailure &&
1310         _hrm.available() >= regions_to_expand) {
1311       // We had head room...
1312       vm_exit_out_of_memory(aligned_expand_bytes, OOM_MMAP_ERROR, "G1 heap expansion");
1313     }
1314   }
1315   return expanded_by > 0;
1316 }
1317 
1318 bool G1CollectedHeap::expand_single_region(uint node_index) {
1319   uint expanded_by = _hrm.expand_on_preferred_node(node_index);
1320 
1321   if (expanded_by == 0) {
1322     assert(is_maximal_no_gc(), "Should be no regions left, available: %u", _hrm.available());
1323     log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)");
1324     return false;
1325   }
1326 
1327   policy()->record_new_heap_size(num_regions());
1328   return true;
1329 }
1330 
1331 void G1CollectedHeap::shrink_helper(size_t shrink_bytes) {
1332   size_t aligned_shrink_bytes =
1333     ReservedSpace::page_align_size_down(shrink_bytes);
1334   aligned_shrink_bytes = align_down(aligned_shrink_bytes,
1335                                          HeapRegion::GrainBytes);
1336   uint num_regions_to_remove = (uint)(shrink_bytes / HeapRegion::GrainBytes);
1337 
1338   uint num_regions_removed = _hrm.shrink_by(num_regions_to_remove);
1339   size_t shrunk_bytes = num_regions_removed * HeapRegion::GrainBytes;
1340 
1341   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",
1342                             shrink_bytes, aligned_shrink_bytes, shrunk_bytes);
1343   if (num_regions_removed > 0) {
1344     log_debug(gc, heap)("Uncommittable regions after shrink: %u", num_regions_removed);
1345     policy()->record_new_heap_size(num_regions());
1346   } else {
1347     log_debug(gc, ergo, heap)("Did not expand the heap (heap shrinking operation failed)");
1348   }
1349 }
1350 
1351 void G1CollectedHeap::shrink(size_t shrink_bytes) {
1352   _verifier->verify_region_sets_optional();
1353 
1354   // We should only reach here at the end of a Full GC or during Remark which
1355   // means we should not not be holding to any GC alloc regions. The method
1356   // below will make sure of that and do any remaining clean up.
1357   _allocator->abandon_gc_alloc_regions();
1358 
1359   // Instead of tearing down / rebuilding the free lists here, we
1360   // could instead use the remove_all_pending() method on free_list to
1361   // remove only the ones that we need to remove.
1362   _hrm.remove_all_free_regions();
1363   shrink_helper(shrink_bytes);
1364   rebuild_region_sets(true /* free_list_only */);
1365 
1366   _hrm.verify_optional();
1367   _verifier->verify_region_sets_optional();
1368 }
1369 
1370 class OldRegionSetChecker : public HeapRegionSetChecker {
1371 public:
1372   void check_mt_safety() {
1373     // Master Old Set MT safety protocol:
1374     // (a) If we're at a safepoint, operations on the master old set
1375     // should be invoked:
1376     // - by the VM thread (which will serialize them), or
1377     // - by the GC workers while holding the FreeList_lock, if we're
1378     //   at a safepoint for an evacuation pause (this lock is taken
1379     //   anyway when an GC alloc region is retired so that a new one
1380     //   is allocated from the free list), or
1381     // - by the GC workers while holding the OldSets_lock, if we're at a
1382     //   safepoint for a cleanup pause.
1383     // (b) If we're not at a safepoint, operations on the master old set
1384     // should be invoked while holding the Heap_lock.
1385 
1386     if (SafepointSynchronize::is_at_safepoint()) {
1387       guarantee(Thread::current()->is_VM_thread() ||
1388                 FreeList_lock->owned_by_self() || OldSets_lock->owned_by_self(),
1389                 "master old set MT safety protocol at a safepoint");
1390     } else {
1391       guarantee(Heap_lock->owned_by_self(), "master old set MT safety protocol outside a safepoint");
1392     }
1393   }
1394   bool is_correct_type(HeapRegion* hr) { return hr->is_old(); }
1395   const char* get_description() { return "Old Regions"; }
1396 };
1397 
1398 class ArchiveRegionSetChecker : public HeapRegionSetChecker {
1399 public:
1400   void check_mt_safety() {
1401     guarantee(!Universe::is_fully_initialized() || SafepointSynchronize::is_at_safepoint(),
1402               "May only change archive regions during initialization or safepoint.");
1403   }
1404   bool is_correct_type(HeapRegion* hr) { return hr->is_archive(); }
1405   const char* get_description() { return "Archive Regions"; }
1406 };
1407 
1408 class HumongousRegionSetChecker : public HeapRegionSetChecker {
1409 public:
1410   void check_mt_safety() {
1411     // Humongous Set MT safety protocol:
1412     // (a) If we're at a safepoint, operations on the master humongous
1413     // set should be invoked by either the VM thread (which will
1414     // serialize them) or by the GC workers while holding the
1415     // OldSets_lock.
1416     // (b) If we're not at a safepoint, operations on the master
1417     // humongous set should be invoked while holding the Heap_lock.
1418 
1419     if (SafepointSynchronize::is_at_safepoint()) {
1420       guarantee(Thread::current()->is_VM_thread() ||
1421                 OldSets_lock->owned_by_self(),
1422                 "master humongous set MT safety protocol at a safepoint");
1423     } else {
1424       guarantee(Heap_lock->owned_by_self(),
1425                 "master humongous set MT safety protocol outside a safepoint");
1426     }
1427   }
1428   bool is_correct_type(HeapRegion* hr) { return hr->is_humongous(); }
1429   const char* get_description() { return "Humongous Regions"; }
1430 };
1431 
1432 G1CollectedHeap::G1CollectedHeap() :
1433   CollectedHeap(),
1434   _service_thread(NULL),
1435   _periodic_gc_task(NULL),
1436   _free_segmented_array_memory_task(NULL),
1437   _workers(NULL),
1438   _card_table(NULL),
1439   _collection_pause_end(Ticks::now()),
1440   _soft_ref_policy(),
1441   _old_set("Old Region Set", new OldRegionSetChecker()),
1442   _archive_set("Archive Region Set", new ArchiveRegionSetChecker()),
1443   _humongous_set("Humongous Region Set", new HumongousRegionSetChecker()),
1444   _bot(NULL),
1445   _listener(),
1446   _numa(G1NUMA::create()),
1447   _hrm(),
1448   _allocator(NULL),
1449   _evac_failure_injector(),
1450   _verifier(NULL),
1451   _summary_bytes_used(0),
1452   _bytes_used_during_gc(0),
1453   _archive_allocator(nullptr),
1454   _survivor_evac_stats("Young", YoungPLABSize, PLABWeight),
1455   _old_evac_stats("Old", OldPLABSize, PLABWeight),
1456   _monitoring_support(nullptr),
1457   _humongous_reclaim_candidates(),
1458   _num_humongous_objects(0),
1459   _num_humongous_reclaim_candidates(0),
1460   _hr_printer(),
1461   _collector_state(),
1462   _old_marking_cycles_started(0),
1463   _old_marking_cycles_completed(0),
1464   _eden(),
1465   _survivor(),
1466   _gc_timer_stw(new (ResourceObj::C_HEAP, mtGC) STWGCTimer()),
1467   _gc_tracer_stw(new (ResourceObj::C_HEAP, mtGC) G1NewTracer()),
1468   _policy(new G1Policy(_gc_timer_stw)),
1469   _heap_sizing_policy(NULL),
1470   _collection_set(this, _policy),
1471   _hot_card_cache(NULL),
1472   _rem_set(NULL),
1473   _card_set_config(),
1474   _cm(NULL),
1475   _cm_thread(NULL),
1476   _cr(NULL),
1477   _task_queues(NULL),
1478   _ref_processor_stw(NULL),
1479   _is_alive_closure_stw(this),
1480   _is_subject_to_discovery_stw(this),
1481   _ref_processor_cm(NULL),
1482   _is_alive_closure_cm(this),
1483   _is_subject_to_discovery_cm(this),
1484   _region_attr() {
1485 
1486   _verifier = new G1HeapVerifier(this);
1487 
1488   _allocator = new G1Allocator(this);
1489 
1490   _heap_sizing_policy = G1HeapSizingPolicy::create(this, _policy->analytics());
1491 
1492   _humongous_object_threshold_in_words = humongous_threshold_for(HeapRegion::GrainWords);
1493 
1494   // Override the default _filler_array_max_size so that no humongous filler
1495   // objects are created.
1496   _filler_array_max_size = _humongous_object_threshold_in_words;
1497 
1498   uint n_queues = ParallelGCThreads;
1499   _task_queues = new G1ScannerTasksQueueSet(n_queues);
1500 
1501   for (uint i = 0; i < n_queues; i++) {
1502     G1ScannerTasksQueue* q = new G1ScannerTasksQueue();
1503     _task_queues->register_queue(i, q);
1504   }
1505 
1506   _gc_tracer_stw->initialize();
1507 
1508   guarantee(_task_queues != NULL, "task_queues allocation failure.");
1509 }
1510 
1511 G1RegionToSpaceMapper* G1CollectedHeap::create_aux_memory_mapper(const char* description,
1512                                                                  size_t size,
1513                                                                  size_t translation_factor) {
1514   size_t preferred_page_size = os::page_size_for_region_unaligned(size, 1);
1515   // Allocate a new reserved space, preferring to use large pages.
1516   ReservedSpace rs(size, preferred_page_size);
1517   size_t page_size = rs.page_size();
1518   G1RegionToSpaceMapper* result  =
1519     G1RegionToSpaceMapper::create_mapper(rs,
1520                                          size,
1521                                          page_size,
1522                                          HeapRegion::GrainBytes,
1523                                          translation_factor,
1524                                          mtGC);
1525 
1526   os::trace_page_sizes_for_requested_size(description,
1527                                           size,
1528                                           page_size,
1529                                           preferred_page_size,
1530                                           rs.base(),
1531                                           rs.size());
1532 
1533   return result;
1534 }
1535 
1536 jint G1CollectedHeap::initialize_concurrent_refinement() {
1537   jint ecode = JNI_OK;
1538   _cr = G1ConcurrentRefine::create(&ecode);
1539   return ecode;
1540 }
1541 
1542 jint G1CollectedHeap::initialize_service_thread() {
1543   _service_thread = new G1ServiceThread();
1544   if (_service_thread->osthread() == NULL) {
1545     vm_shutdown_during_initialization("Could not create G1ServiceThread");
1546     return JNI_ENOMEM;
1547   }
1548   return JNI_OK;
1549 }
1550 
1551 jint G1CollectedHeap::initialize() {
1552 
1553   // Necessary to satisfy locking discipline assertions.
1554 
1555   MutexLocker x(Heap_lock);
1556 
1557   // While there are no constraints in the GC code that HeapWordSize
1558   // be any particular value, there are multiple other areas in the
1559   // system which believe this to be true (e.g. oop->object_size in some
1560   // cases incorrectly returns the size in wordSize units rather than
1561   // HeapWordSize).
1562   guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
1563 
1564   size_t init_byte_size = InitialHeapSize;
1565   size_t reserved_byte_size = G1Arguments::heap_reserved_size_bytes();
1566 
1567   // Ensure that the sizes are properly aligned.
1568   Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");
1569   Universe::check_alignment(reserved_byte_size, HeapRegion::GrainBytes, "g1 heap");
1570   Universe::check_alignment(reserved_byte_size, HeapAlignment, "g1 heap");
1571 
1572   // Reserve the maximum.
1573 
1574   // When compressed oops are enabled, the preferred heap base
1575   // is calculated by subtracting the requested size from the
1576   // 32Gb boundary and using the result as the base address for
1577   // heap reservation. If the requested size is not aligned to
1578   // HeapRegion::GrainBytes (i.e. the alignment that is passed
1579   // into the ReservedHeapSpace constructor) then the actual
1580   // base of the reserved heap may end up differing from the
1581   // address that was requested (i.e. the preferred heap base).
1582   // If this happens then we could end up using a non-optimal
1583   // compressed oops mode.
1584 
1585   ReservedHeapSpace heap_rs = Universe::reserve_heap(reserved_byte_size,
1586                                                      HeapAlignment);
1587 
1588   initialize_reserved_region(heap_rs);
1589 
1590   _forwarding = new SlidingForwarding(heap_rs.region(), HeapRegion::LogOfHRGrainBytes - LogHeapWordSize);
1591 
1592   // Create the barrier set for the entire reserved region.
1593   G1CardTable* ct = new G1CardTable(heap_rs.region());
1594   ct->initialize();
1595   G1BarrierSet* bs = new G1BarrierSet(ct);
1596   bs->initialize();
1597   assert(bs->is_a(BarrierSet::G1BarrierSet), "sanity");
1598   BarrierSet::set_barrier_set(bs);
1599   _card_table = ct;
1600 
1601   {
1602     G1SATBMarkQueueSet& satbqs = bs->satb_mark_queue_set();
1603     satbqs.set_process_completed_buffers_threshold(G1SATBProcessCompletedThreshold);
1604     satbqs.set_buffer_enqueue_threshold_percentage(G1SATBBufferEnqueueingThresholdPercent);
1605   }
1606 
1607   // Create the hot card cache.
1608   _hot_card_cache = new G1HotCardCache(this);
1609 
1610   // Create space mappers.
1611   size_t page_size = heap_rs.page_size();
1612   G1RegionToSpaceMapper* heap_storage =
1613     G1RegionToSpaceMapper::create_mapper(heap_rs,
1614                                          heap_rs.size(),
1615                                          page_size,
1616                                          HeapRegion::GrainBytes,
1617                                          1,
1618                                          mtJavaHeap);
1619   if(heap_storage == NULL) {
1620     vm_shutdown_during_initialization("Could not initialize G1 heap");
1621     return JNI_ERR;
1622   }
1623 
1624   os::trace_page_sizes("Heap",
1625                        MinHeapSize,
1626                        reserved_byte_size,
1627                        page_size,
1628                        heap_rs.base(),
1629                        heap_rs.size());
1630   heap_storage->set_mapping_changed_listener(&_listener);
1631 
1632   // Create storage for the BOT, card table, card counts table (hot card cache) and the bitmaps.
1633   G1RegionToSpaceMapper* bot_storage =
1634     create_aux_memory_mapper("Block Offset Table",
1635                              G1BlockOffsetTable::compute_size(heap_rs.size() / HeapWordSize),
1636                              G1BlockOffsetTable::heap_map_factor());
1637 
1638   G1RegionToSpaceMapper* cardtable_storage =
1639     create_aux_memory_mapper("Card Table",
1640                              G1CardTable::compute_size(heap_rs.size() / HeapWordSize),
1641                              G1CardTable::heap_map_factor());
1642 
1643   G1RegionToSpaceMapper* card_counts_storage =
1644     create_aux_memory_mapper("Card Counts Table",
1645                              G1CardCounts::compute_size(heap_rs.size() / HeapWordSize),
1646                              G1CardCounts::heap_map_factor());
1647 
1648   size_t bitmap_size = G1CMBitMap::compute_size(heap_rs.size());
1649   G1RegionToSpaceMapper* prev_bitmap_storage =
1650     create_aux_memory_mapper("Prev Bitmap", bitmap_size, G1CMBitMap::heap_map_factor());
1651   G1RegionToSpaceMapper* next_bitmap_storage =
1652     create_aux_memory_mapper("Next Bitmap", bitmap_size, G1CMBitMap::heap_map_factor());
1653 
1654   _hrm.initialize(heap_storage, prev_bitmap_storage, next_bitmap_storage, bot_storage, cardtable_storage, card_counts_storage);
1655   _card_table->initialize(cardtable_storage);
1656 
1657   // Do later initialization work for concurrent refinement.
1658   _hot_card_cache->initialize(card_counts_storage);
1659 
1660   // 6843694 - ensure that the maximum region index can fit
1661   // in the remembered set structures.
1662   const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;
1663   guarantee((max_reserved_regions() - 1) <= max_region_idx, "too many regions");
1664 
1665   // The G1FromCardCache reserves card with value 0 as "invalid", so the heap must not
1666   // start within the first card.
1667   guarantee((uintptr_t)(heap_rs.base()) >= G1CardTable::card_size(), "Java heap must not start within the first card.");
1668   G1FromCardCache::initialize(max_reserved_regions());
1669   // Also create a G1 rem set.
1670   _rem_set = new G1RemSet(this, _card_table, _hot_card_cache);
1671   _rem_set->initialize(max_reserved_regions());
1672 
1673   size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1;
1674   guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized");
1675   guarantee(HeapRegion::CardsPerRegion < max_cards_per_region,
1676             "too many cards per region");
1677 
1678   HeapRegionRemSet::initialize(_reserved);
1679 
1680   FreeRegionList::set_unrealistically_long_length(max_regions() + 1);
1681 
1682   _bot = new G1BlockOffsetTable(reserved(), bot_storage);
1683 
1684   {
1685     size_t granularity = HeapRegion::GrainBytes;
1686 
1687     _region_attr.initialize(reserved(), granularity);
1688     _humongous_reclaim_candidates.initialize(reserved(), granularity);
1689   }
1690 
1691   _workers = new WorkerThreads("GC Thread", ParallelGCThreads);
1692   if (_workers == NULL) {
1693     return JNI_ENOMEM;
1694   }
1695   _workers->initialize_workers();
1696 
1697   _numa->set_region_info(HeapRegion::GrainBytes, page_size);
1698 
1699   // Create the G1ConcurrentMark data structure and thread.
1700   // (Must do this late, so that "max_[reserved_]regions" is defined.)
1701   _cm = new G1ConcurrentMark(this, prev_bitmap_storage, next_bitmap_storage);
1702   _cm_thread = _cm->cm_thread();
1703 
1704   // Now expand into the initial heap size.
1705   if (!expand(init_byte_size, _workers)) {
1706     vm_shutdown_during_initialization("Failed to allocate initial heap.");
1707     return JNI_ENOMEM;
1708   }
1709 
1710   // Perform any initialization actions delegated to the policy.
1711   policy()->init(this, &_collection_set);
1712 
1713   jint ecode = initialize_concurrent_refinement();
1714   if (ecode != JNI_OK) {
1715     return ecode;
1716   }
1717 
1718   ecode = initialize_service_thread();
1719   if (ecode != JNI_OK) {
1720     return ecode;
1721   }
1722 
1723   // Initialize and schedule sampling task on service thread.
1724   _rem_set->initialize_sampling_task(service_thread());
1725 
1726   // Create and schedule the periodic gc task on the service thread.
1727   _periodic_gc_task = new G1PeriodicGCTask("Periodic GC Task");
1728   _service_thread->register_task(_periodic_gc_task);
1729 
1730   _free_segmented_array_memory_task = new G1SegmentedArrayFreeMemoryTask("Card Set Free Memory Task");
1731   _service_thread->register_task(_free_segmented_array_memory_task);
1732 
1733   // Here we allocate the dummy HeapRegion that is required by the
1734   // G1AllocRegion class.
1735   HeapRegion* dummy_region = _hrm.get_dummy_region();
1736 
1737   // We'll re-use the same region whether the alloc region will
1738   // require BOT updates or not and, if it doesn't, then a non-young
1739   // region will complain that it cannot support allocations without
1740   // BOT updates. So we'll tag the dummy region as eden to avoid that.
1741   dummy_region->set_eden();
1742   // Make sure it's full.
1743   dummy_region->set_top(dummy_region->end());
1744   G1AllocRegion::setup(this, dummy_region);
1745 
1746   _allocator->init_mutator_alloc_regions();
1747 
1748   // Do create of the monitoring and management support so that
1749   // values in the heap have been properly initialized.
1750   _monitoring_support = new G1MonitoringSupport(this);
1751 
1752   _collection_set.initialize(max_reserved_regions());
1753 
1754   evac_failure_injector()->reset();
1755 
1756   G1InitLogger::print();
1757 
1758   return JNI_OK;
1759 }
1760 
1761 bool G1CollectedHeap::concurrent_mark_is_terminating() const {
1762   return _cm_thread->should_terminate();
1763 }
1764 
1765 void G1CollectedHeap::stop() {
1766   // Stop all concurrent threads. We do this to make sure these threads
1767   // do not continue to execute and access resources (e.g. logging)
1768   // that are destroyed during shutdown.
1769   _cr->stop();
1770   _service_thread->stop();
1771   _cm_thread->stop();
1772 }
1773 
1774 void G1CollectedHeap::safepoint_synchronize_begin() {
1775   SuspendibleThreadSet::synchronize();
1776 }
1777 
1778 void G1CollectedHeap::safepoint_synchronize_end() {
1779   SuspendibleThreadSet::desynchronize();
1780 }
1781 
1782 void G1CollectedHeap::post_initialize() {
1783   CollectedHeap::post_initialize();
1784   ref_processing_init();
1785 }
1786 
1787 void G1CollectedHeap::ref_processing_init() {
1788   // Reference processing in G1 currently works as follows:
1789   //
1790   // * There are two reference processor instances. One is
1791   //   used to record and process discovered references
1792   //   during concurrent marking; the other is used to
1793   //   record and process references during STW pauses
1794   //   (both full and incremental).
1795   // * Both ref processors need to 'span' the entire heap as
1796   //   the regions in the collection set may be dotted around.
1797   //
1798   // * For the concurrent marking ref processor:
1799   //   * Reference discovery is enabled at concurrent start.
1800   //   * Reference discovery is disabled and the discovered
1801   //     references processed etc during remarking.
1802   //   * Reference discovery is MT (see below).
1803   //   * Reference discovery requires a barrier (see below).
1804   //   * Reference processing may or may not be MT
1805   //     (depending on the value of ParallelRefProcEnabled
1806   //     and ParallelGCThreads).
1807   //   * A full GC disables reference discovery by the CM
1808   //     ref processor and abandons any entries on it's
1809   //     discovered lists.
1810   //
1811   // * For the STW processor:
1812   //   * Non MT discovery is enabled at the start of a full GC.
1813   //   * Processing and enqueueing during a full GC is non-MT.
1814   //   * During a full GC, references are processed after marking.
1815   //
1816   //   * Discovery (may or may not be MT) is enabled at the start
1817   //     of an incremental evacuation pause.
1818   //   * References are processed near the end of a STW evacuation pause.
1819   //   * For both types of GC:
1820   //     * Discovery is atomic - i.e. not concurrent.
1821   //     * Reference discovery will not need a barrier.
1822 
1823   // Concurrent Mark ref processor
1824   _ref_processor_cm =
1825     new ReferenceProcessor(&_is_subject_to_discovery_cm,
1826                            ParallelGCThreads,                              // degree of mt processing
1827                            // We discover with the gc worker threads during Remark, so both
1828                            // thread counts must be considered for discovery.
1829                            MAX2(ParallelGCThreads, ConcGCThreads),         // degree of mt discovery
1830                            true,                                           // Reference discovery is concurrent
1831                            &_is_alive_closure_cm);                         // is alive closure
1832 
1833   // STW ref processor
1834   _ref_processor_stw =
1835     new ReferenceProcessor(&_is_subject_to_discovery_stw,
1836                            ParallelGCThreads,                    // degree of mt processing
1837                            ParallelGCThreads,                    // degree of mt discovery
1838                            false,                                // Reference discovery is not concurrent
1839                            &_is_alive_closure_stw);              // is alive closure
1840 }
1841 
1842 SoftRefPolicy* G1CollectedHeap::soft_ref_policy() {
1843   return &_soft_ref_policy;
1844 }
1845 
1846 size_t G1CollectedHeap::capacity() const {
1847   return _hrm.length() * HeapRegion::GrainBytes;
1848 }
1849 
1850 size_t G1CollectedHeap::unused_committed_regions_in_bytes() const {
1851   return _hrm.total_free_bytes();
1852 }
1853 
1854 void G1CollectedHeap::iterate_hcc_closure(G1CardTableEntryClosure* cl, uint worker_id) {
1855   _hot_card_cache->drain(cl, worker_id);
1856 }
1857 
1858 // Computes the sum of the storage used by the various regions.
1859 size_t G1CollectedHeap::used() const {
1860   size_t result = _summary_bytes_used + _allocator->used_in_alloc_regions();
1861   assert(_archive_allocator == nullptr, "must be, should not contribute to used");
1862   return result;
1863 }
1864 
1865 size_t G1CollectedHeap::used_unlocked() const {
1866   return _summary_bytes_used;
1867 }
1868 
1869 class SumUsedClosure: public HeapRegionClosure {
1870   size_t _used;
1871 public:
1872   SumUsedClosure() : _used(0) {}
1873   bool do_heap_region(HeapRegion* r) {
1874     _used += r->used();
1875     return false;
1876   }
1877   size_t result() { return _used; }
1878 };
1879 
1880 size_t G1CollectedHeap::recalculate_used() const {
1881   SumUsedClosure blk;
1882   heap_region_iterate(&blk);
1883   return blk.result();
1884 }
1885 
1886 bool  G1CollectedHeap::is_user_requested_concurrent_full_gc(GCCause::Cause cause) {
1887   switch (cause) {
1888     case GCCause::_java_lang_system_gc:                 return ExplicitGCInvokesConcurrent;
1889     case GCCause::_dcmd_gc_run:                         return ExplicitGCInvokesConcurrent;
1890     case GCCause::_wb_conc_mark:                        return true;
1891     default :                                           return false;
1892   }
1893 }
1894 
1895 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
1896   switch (cause) {
1897     case GCCause::_g1_humongous_allocation: return true;
1898     case GCCause::_g1_periodic_collection:  return G1PeriodicGCInvokesConcurrent;
1899     case GCCause::_wb_breakpoint:           return true;
1900     default:                                return is_user_requested_concurrent_full_gc(cause);
1901   }
1902 }
1903 
1904 #ifndef PRODUCT
1905 void G1CollectedHeap::allocate_dummy_regions() {
1906   // Let's fill up most of the region
1907   size_t word_size = HeapRegion::GrainWords - 1024;
1908   // And as a result the region we'll allocate will be humongous.
1909   guarantee(is_humongous(word_size), "sanity");
1910 
1911   // _filler_array_max_size is set to humongous object threshold
1912   // but temporarily change it to use CollectedHeap::fill_with_object().
1913   AutoModifyRestore<size_t> temporarily(_filler_array_max_size, word_size);
1914 
1915   for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) {
1916     // Let's use the existing mechanism for the allocation
1917     HeapWord* dummy_obj = humongous_obj_allocate(word_size);
1918     if (dummy_obj != NULL) {
1919       MemRegion mr(dummy_obj, word_size);
1920       CollectedHeap::fill_with_object(mr);
1921     } else {
1922       // If we can't allocate once, we probably cannot allocate
1923       // again. Let's get out of the loop.
1924       break;
1925     }
1926   }
1927 }
1928 #endif // !PRODUCT
1929 
1930 void G1CollectedHeap::increment_old_marking_cycles_started() {
1931   assert(_old_marking_cycles_started == _old_marking_cycles_completed ||
1932          _old_marking_cycles_started == _old_marking_cycles_completed + 1,
1933          "Wrong marking cycle count (started: %d, completed: %d)",
1934          _old_marking_cycles_started, _old_marking_cycles_completed);
1935 
1936   _old_marking_cycles_started++;
1937 }
1938 
1939 void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent,
1940                                                              bool whole_heap_examined) {
1941   MonitorLocker ml(G1OldGCCount_lock, Mutex::_no_safepoint_check_flag);
1942 
1943   // We assume that if concurrent == true, then the caller is a
1944   // concurrent thread that was joined the Suspendible Thread
1945   // Set. If there's ever a cheap way to check this, we should add an
1946   // assert here.
1947 
1948   // Given that this method is called at the end of a Full GC or of a
1949   // concurrent cycle, and those can be nested (i.e., a Full GC can
1950   // interrupt a concurrent cycle), the number of full collections
1951   // completed should be either one (in the case where there was no
1952   // nesting) or two (when a Full GC interrupted a concurrent cycle)
1953   // behind the number of full collections started.
1954 
1955   // This is the case for the inner caller, i.e. a Full GC.
1956   assert(concurrent ||
1957          (_old_marking_cycles_started == _old_marking_cycles_completed + 1) ||
1958          (_old_marking_cycles_started == _old_marking_cycles_completed + 2),
1959          "for inner caller (Full GC): _old_marking_cycles_started = %u "
1960          "is inconsistent with _old_marking_cycles_completed = %u",
1961          _old_marking_cycles_started, _old_marking_cycles_completed);
1962 
1963   // This is the case for the outer caller, i.e. the concurrent cycle.
1964   assert(!concurrent ||
1965          (_old_marking_cycles_started == _old_marking_cycles_completed + 1),
1966          "for outer caller (concurrent cycle): "
1967          "_old_marking_cycles_started = %u "
1968          "is inconsistent with _old_marking_cycles_completed = %u",
1969          _old_marking_cycles_started, _old_marking_cycles_completed);
1970 
1971   _old_marking_cycles_completed += 1;
1972   if (whole_heap_examined) {
1973     // Signal that we have completed a visit to all live objects.
1974     record_whole_heap_examined_timestamp();
1975   }
1976 
1977   // We need to clear the "in_progress" flag in the CM thread before
1978   // we wake up any waiters (especially when ExplicitInvokesConcurrent
1979   // is set) so that if a waiter requests another System.gc() it doesn't
1980   // incorrectly see that a marking cycle is still in progress.
1981   if (concurrent) {
1982     _cm_thread->set_idle();
1983   }
1984 
1985   // Notify threads waiting in System.gc() (with ExplicitGCInvokesConcurrent)
1986   // for a full GC to finish that their wait is over.
1987   ml.notify_all();
1988 }
1989 
1990 // Helper for collect().
1991 static G1GCCounters collection_counters(G1CollectedHeap* g1h) {
1992   MutexLocker ml(Heap_lock);
1993   return G1GCCounters(g1h);
1994 }
1995 
1996 void G1CollectedHeap::collect(GCCause::Cause cause) {
1997   try_collect(cause, collection_counters(this));
1998 }
1999 
2000 // Return true if (x < y) with allowance for wraparound.
2001 static bool gc_counter_less_than(uint x, uint y) {
2002   return (x - y) > (UINT_MAX/2);
2003 }
2004 
2005 // LOG_COLLECT_CONCURRENTLY(cause, msg, args...)
2006 // Macro so msg printing is format-checked.
2007 #define LOG_COLLECT_CONCURRENTLY(cause, ...)                            \
2008   do {                                                                  \
2009     LogTarget(Trace, gc) LOG_COLLECT_CONCURRENTLY_lt;                   \
2010     if (LOG_COLLECT_CONCURRENTLY_lt.is_enabled()) {                     \
2011       ResourceMark rm; /* For thread name. */                           \
2012       LogStream LOG_COLLECT_CONCURRENTLY_s(&LOG_COLLECT_CONCURRENTLY_lt); \
2013       LOG_COLLECT_CONCURRENTLY_s.print("%s: Try Collect Concurrently (%s): ", \
2014                                        Thread::current()->name(),       \
2015                                        GCCause::to_string(cause));      \
2016       LOG_COLLECT_CONCURRENTLY_s.print(__VA_ARGS__);                    \
2017     }                                                                   \
2018   } while (0)
2019 
2020 #define LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, result) \
2021   LOG_COLLECT_CONCURRENTLY(cause, "complete %s", BOOL_TO_STR(result))
2022 
2023 bool G1CollectedHeap::try_collect_concurrently(GCCause::Cause cause,
2024                                                uint gc_counter,
2025                                                uint old_marking_started_before) {
2026   assert_heap_not_locked();
2027   assert(should_do_concurrent_full_gc(cause),
2028          "Non-concurrent cause %s", GCCause::to_string(cause));
2029 
2030   for (uint i = 1; true; ++i) {
2031     // Try to schedule concurrent start evacuation pause that will
2032     // start a concurrent cycle.
2033     LOG_COLLECT_CONCURRENTLY(cause, "attempt %u", i);
2034     VM_G1TryInitiateConcMark op(gc_counter,
2035                                 cause,
2036                                 policy()->max_pause_time_ms());
2037     VMThread::execute(&op);
2038 
2039     // Request is trivially finished.
2040     if (cause == GCCause::_g1_periodic_collection) {
2041       LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, op.gc_succeeded());
2042       return op.gc_succeeded();
2043     }
2044 
2045     // If VMOp skipped initiating concurrent marking cycle because
2046     // we're terminating, then we're done.
2047     if (op.terminating()) {
2048       LOG_COLLECT_CONCURRENTLY(cause, "skipped: terminating");
2049       return false;
2050     }
2051 
2052     // Lock to get consistent set of values.
2053     uint old_marking_started_after;
2054     uint old_marking_completed_after;
2055     {
2056       MutexLocker ml(Heap_lock);
2057       // Update gc_counter for retrying VMOp if needed. Captured here to be
2058       // consistent with the values we use below for termination tests.  If
2059       // a retry is needed after a possible wait, and another collection
2060       // occurs in the meantime, it will cause our retry to be skipped and
2061       // we'll recheck for termination with updated conditions from that
2062       // more recent collection.  That's what we want, rather than having
2063       // our retry possibly perform an unnecessary collection.
2064       gc_counter = total_collections();
2065       old_marking_started_after = _old_marking_cycles_started;
2066       old_marking_completed_after = _old_marking_cycles_completed;
2067     }
2068 
2069     if (cause == GCCause::_wb_breakpoint) {
2070       if (op.gc_succeeded()) {
2071         LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
2072         return true;
2073       }
2074       // When _wb_breakpoint there can't be another cycle or deferred.
2075       assert(!op.cycle_already_in_progress(), "invariant");
2076       assert(!op.whitebox_attached(), "invariant");
2077       // Concurrent cycle attempt might have been cancelled by some other
2078       // collection, so retry.  Unlike other cases below, we want to retry
2079       // even if cancelled by a STW full collection, because we really want
2080       // to start a concurrent cycle.
2081       if (old_marking_started_before != old_marking_started_after) {
2082         LOG_COLLECT_CONCURRENTLY(cause, "ignoring STW full GC");
2083         old_marking_started_before = old_marking_started_after;
2084       }
2085     } else if (!GCCause::is_user_requested_gc(cause)) {
2086       // For an "automatic" (not user-requested) collection, we just need to
2087       // ensure that progress is made.
2088       //
2089       // Request is finished if any of
2090       // (1) the VMOp successfully performed a GC,
2091       // (2) a concurrent cycle was already in progress,
2092       // (3) whitebox is controlling concurrent cycles,
2093       // (4) a new cycle was started (by this thread or some other), or
2094       // (5) a Full GC was performed.
2095       // Cases (4) and (5) are detected together by a change to
2096       // _old_marking_cycles_started.
2097       //
2098       // Note that (1) does not imply (4).  If we're still in the mixed
2099       // phase of an earlier concurrent collection, the request to make the
2100       // collection a concurrent start won't be honored.  If we don't check for
2101       // both conditions we'll spin doing back-to-back collections.
2102       if (op.gc_succeeded() ||
2103           op.cycle_already_in_progress() ||
2104           op.whitebox_attached() ||
2105           (old_marking_started_before != old_marking_started_after)) {
2106         LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
2107         return true;
2108       }
2109     } else {                    // User-requested GC.
2110       // For a user-requested collection, we want to ensure that a complete
2111       // full collection has been performed before returning, but without
2112       // waiting for more than needed.
2113 
2114       // For user-requested GCs (unlike non-UR), a successful VMOp implies a
2115       // new cycle was started.  That's good, because it's not clear what we
2116       // should do otherwise.  Trying again just does back to back GCs.
2117       // Can't wait for someone else to start a cycle.  And returning fails
2118       // to meet the goal of ensuring a full collection was performed.
2119       assert(!op.gc_succeeded() ||
2120              (old_marking_started_before != old_marking_started_after),
2121              "invariant: succeeded %s, started before %u, started after %u",
2122              BOOL_TO_STR(op.gc_succeeded()),
2123              old_marking_started_before, old_marking_started_after);
2124 
2125       // Request is finished if a full collection (concurrent or stw)
2126       // was started after this request and has completed, e.g.
2127       // started_before < completed_after.
2128       if (gc_counter_less_than(old_marking_started_before,
2129                                old_marking_completed_after)) {
2130         LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
2131         return true;
2132       }
2133 
2134       if (old_marking_started_after != old_marking_completed_after) {
2135         // If there is an in-progress cycle (possibly started by us), then
2136         // wait for that cycle to complete, e.g.
2137         // while completed_now < started_after.
2138         LOG_COLLECT_CONCURRENTLY(cause, "wait");
2139         MonitorLocker ml(G1OldGCCount_lock);
2140         while (gc_counter_less_than(_old_marking_cycles_completed,
2141                                     old_marking_started_after)) {
2142           ml.wait();
2143         }
2144         // Request is finished if the collection we just waited for was
2145         // started after this request.
2146         if (old_marking_started_before != old_marking_started_after) {
2147           LOG_COLLECT_CONCURRENTLY(cause, "complete after wait");
2148           return true;
2149         }
2150       }
2151 
2152       // If VMOp was successful then it started a new cycle that the above
2153       // wait &etc should have recognized as finishing this request.  This
2154       // differs from a non-user-request, where gc_succeeded does not imply
2155       // a new cycle was started.
2156       assert(!op.gc_succeeded(), "invariant");
2157 
2158       if (op.cycle_already_in_progress()) {
2159         // If VMOp failed because a cycle was already in progress, it
2160         // is now complete.  But it didn't finish this user-requested
2161         // GC, so try again.
2162         LOG_COLLECT_CONCURRENTLY(cause, "retry after in-progress");
2163         continue;
2164       } else if (op.whitebox_attached()) {
2165         // If WhiteBox wants control, wait for notification of a state
2166         // change in the controller, then try again.  Don't wait for
2167         // release of control, since collections may complete while in
2168         // control.  Note: This won't recognize a STW full collection
2169         // while waiting; we can't wait on multiple monitors.
2170         LOG_COLLECT_CONCURRENTLY(cause, "whitebox control stall");
2171         MonitorLocker ml(ConcurrentGCBreakpoints::monitor());
2172         if (ConcurrentGCBreakpoints::is_controlled()) {
2173           ml.wait();
2174         }
2175         continue;
2176       }
2177     }
2178 
2179     // Collection failed and should be retried.
2180     assert(op.transient_failure(), "invariant");
2181 
2182     if (GCLocker::is_active_and_needs_gc()) {
2183       // If GCLocker is active, wait until clear before retrying.
2184       LOG_COLLECT_CONCURRENTLY(cause, "gc-locker stall");
2185       GCLocker::stall_until_clear();
2186     }
2187 
2188     LOG_COLLECT_CONCURRENTLY(cause, "retry");
2189   }
2190 }
2191 
2192 bool G1CollectedHeap::try_collect(GCCause::Cause cause,
2193                                   const G1GCCounters& counters_before) {
2194   if (should_do_concurrent_full_gc(cause)) {
2195     return try_collect_concurrently(cause,
2196                                     counters_before.total_collections(),
2197                                     counters_before.old_marking_cycles_started());
2198   } else if (GCLocker::should_discard(cause, counters_before.total_collections())) {
2199     // Indicate failure to be consistent with VMOp failure due to
2200     // another collection slipping in after our gc_count but before
2201     // our request is processed.
2202     return false;
2203   } else if (cause == GCCause::_gc_locker || cause == GCCause::_wb_young_gc
2204              DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) {
2205 
2206     // Schedule a standard evacuation pause. We're setting word_size
2207     // to 0 which means that we are not requesting a post-GC allocation.
2208     VM_G1CollectForAllocation op(0,     /* word_size */
2209                                  counters_before.total_collections(),
2210                                  cause,
2211                                  policy()->max_pause_time_ms());
2212     VMThread::execute(&op);
2213     return op.gc_succeeded();
2214   } else {
2215     // Schedule a Full GC.
2216     VM_G1CollectFull op(counters_before.total_collections(),
2217                         counters_before.total_full_collections(),
2218                         cause);
2219     VMThread::execute(&op);
2220     return op.gc_succeeded();
2221   }
2222 }
2223 
2224 void G1CollectedHeap::start_concurrent_gc_for_metadata_allocation(GCCause::Cause gc_cause) {
2225   GCCauseSetter x(this, gc_cause);
2226 
2227   // At this point we are supposed to start a concurrent cycle. We
2228   // will do so if one is not already in progress.
2229   bool should_start = policy()->force_concurrent_start_if_outside_cycle(gc_cause);
2230   if (should_start) {
2231     double pause_target = policy()->max_pause_time_ms();
2232     do_collection_pause_at_safepoint(pause_target);
2233   }
2234 }
2235 
2236 bool G1CollectedHeap::is_in(const void* p) const {
2237   return is_in_reserved(p) && _hrm.is_available(addr_to_region((HeapWord*)p));
2238 }
2239 
2240 // Iteration functions.
2241 
2242 // Iterates an ObjectClosure over all objects within a HeapRegion.
2243 
2244 class IterateObjectClosureRegionClosure: public HeapRegionClosure {
2245   ObjectClosure* _cl;
2246 public:
2247   IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
2248   bool do_heap_region(HeapRegion* r) {
2249     if (!r->is_continues_humongous()) {
2250       r->object_iterate(_cl);
2251     }
2252     return false;
2253   }
2254 };
2255 
2256 void G1CollectedHeap::object_iterate(ObjectClosure* cl) {
2257   IterateObjectClosureRegionClosure blk(cl);
2258   heap_region_iterate(&blk);
2259 }
2260 
2261 class G1ParallelObjectIterator : public ParallelObjectIteratorImpl {
2262 private:
2263   G1CollectedHeap*  _heap;
2264   HeapRegionClaimer _claimer;
2265 
2266 public:
2267   G1ParallelObjectIterator(uint thread_num) :
2268       _heap(G1CollectedHeap::heap()),
2269       _claimer(thread_num == 0 ? G1CollectedHeap::heap()->workers()->active_workers() : thread_num) {}
2270 
2271   virtual void object_iterate(ObjectClosure* cl, uint worker_id) {
2272     _heap->object_iterate_parallel(cl, worker_id, &_claimer);
2273   }
2274 };
2275 
2276 ParallelObjectIteratorImpl* G1CollectedHeap::parallel_object_iterator(uint thread_num) {
2277   return new G1ParallelObjectIterator(thread_num);
2278 }
2279 
2280 void G1CollectedHeap::object_iterate_parallel(ObjectClosure* cl, uint worker_id, HeapRegionClaimer* claimer) {
2281   IterateObjectClosureRegionClosure blk(cl);
2282   heap_region_par_iterate_from_worker_offset(&blk, claimer, worker_id);
2283 }
2284 
2285 void G1CollectedHeap::keep_alive(oop obj) {
2286   G1BarrierSet::enqueue_preloaded(obj);
2287 }
2288 
2289 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const {
2290   _hrm.iterate(cl);
2291 }
2292 
2293 void G1CollectedHeap::heap_region_par_iterate_from_worker_offset(HeapRegionClosure* cl,
2294                                                                  HeapRegionClaimer *hrclaimer,
2295                                                                  uint worker_id) const {
2296   _hrm.par_iterate(cl, hrclaimer, hrclaimer->offset_for_worker(worker_id));
2297 }
2298 
2299 void G1CollectedHeap::heap_region_par_iterate_from_start(HeapRegionClosure* cl,
2300                                                          HeapRegionClaimer *hrclaimer) const {
2301   _hrm.par_iterate(cl, hrclaimer, 0);
2302 }
2303 
2304 void G1CollectedHeap::collection_set_iterate_all(HeapRegionClosure* cl) {
2305   _collection_set.iterate(cl);
2306 }
2307 
2308 void G1CollectedHeap::collection_set_par_iterate_all(HeapRegionClosure* cl,
2309                                                      HeapRegionClaimer* hr_claimer,
2310                                                      uint worker_id) {
2311   _collection_set.par_iterate(cl, hr_claimer, worker_id);
2312 }
2313 
2314 void G1CollectedHeap::collection_set_iterate_increment_from(HeapRegionClosure *cl,
2315                                                             HeapRegionClaimer* hr_claimer,
2316                                                             uint worker_id) {
2317   _collection_set.iterate_incremental_part_from(cl, hr_claimer, worker_id);
2318 }
2319 
2320 void G1CollectedHeap::par_iterate_regions_array(HeapRegionClosure* cl,
2321                                                 HeapRegionClaimer* hr_claimer,
2322                                                 const uint regions[],
2323                                                 size_t length,
2324                                                 uint worker_id) const {
2325   assert_at_safepoint();
2326   if (length == 0) {
2327     return;
2328   }
2329   uint total_workers = workers()->active_workers();
2330 
2331   size_t start_pos = (worker_id * length) / total_workers;
2332   size_t cur_pos = start_pos;
2333 
2334   do {
2335     uint region_idx = regions[cur_pos];
2336     if (hr_claimer == NULL || hr_claimer->claim_region(region_idx)) {
2337       HeapRegion* r = region_at(region_idx);
2338       bool result = cl->do_heap_region(r);
2339       guarantee(!result, "Must not cancel iteration");
2340     }
2341 
2342     cur_pos++;
2343     if (cur_pos == length) {
2344       cur_pos = 0;
2345     }
2346   } while (cur_pos != start_pos);
2347 }
2348 
2349 HeapWord* G1CollectedHeap::block_start(const void* addr) const {
2350   HeapRegion* hr = heap_region_containing(addr);
2351   return hr->block_start(addr);
2352 }
2353 
2354 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
2355   HeapRegion* hr = heap_region_containing(addr);
2356   return hr->block_is_obj(addr);
2357 }
2358 
2359 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {
2360   return (_policy->young_list_target_length() - _survivor.length()) * HeapRegion::GrainBytes;
2361 }
2362 
2363 size_t G1CollectedHeap::tlab_used(Thread* ignored) const {
2364   return _eden.length() * HeapRegion::GrainBytes;
2365 }
2366 
2367 // For G1 TLABs should not contain humongous objects, so the maximum TLAB size
2368 // must be equal to the humongous object limit.
2369 size_t G1CollectedHeap::max_tlab_size() const {
2370   return align_down(_humongous_object_threshold_in_words, MinObjAlignment);
2371 }
2372 
2373 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {
2374   return _allocator->unsafe_max_tlab_alloc();
2375 }
2376 
2377 size_t G1CollectedHeap::max_capacity() const {
2378   return max_regions() * HeapRegion::GrainBytes;
2379 }
2380 
2381 void G1CollectedHeap::prepare_for_verify() {
2382   _verifier->prepare_for_verify();
2383 }
2384 
2385 void G1CollectedHeap::verify(VerifyOption vo) {
2386   _verifier->verify(vo);
2387 }
2388 
2389 bool G1CollectedHeap::supports_concurrent_gc_breakpoints() const {
2390   return true;
2391 }
2392 
2393 bool G1CollectedHeap::is_archived_object(oop object) const {
2394   return object != NULL && heap_region_containing(object)->is_archive();
2395 }
2396 
2397 class PrintRegionClosure: public HeapRegionClosure {
2398   outputStream* _st;
2399 public:
2400   PrintRegionClosure(outputStream* st) : _st(st) {}
2401   bool do_heap_region(HeapRegion* r) {
2402     r->print_on(_st);
2403     return false;
2404   }
2405 };
2406 
2407 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
2408                                        const HeapRegion* hr,
2409                                        const VerifyOption vo) const {
2410   switch (vo) {
2411   case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj, hr);
2412   case VerifyOption_G1UseFullMarking: return is_obj_dead_full(obj, hr);
2413   default:                            ShouldNotReachHere();
2414   }
2415   return false; // keep some compilers happy
2416 }
2417 
2418 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
2419                                        const VerifyOption vo) const {
2420   switch (vo) {
2421   case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj);
2422   case VerifyOption_G1UseFullMarking: return is_obj_dead_full(obj);
2423   default:                            ShouldNotReachHere();
2424   }
2425   return false; // keep some compilers happy
2426 }
2427 
2428 void G1CollectedHeap::print_heap_regions() const {
2429   LogTarget(Trace, gc, heap, region) lt;
2430   if (lt.is_enabled()) {
2431     LogStream ls(lt);
2432     print_regions_on(&ls);
2433   }
2434 }
2435 
2436 void G1CollectedHeap::print_on(outputStream* st) const {
2437   size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked();
2438   st->print(" %-20s", "garbage-first heap");
2439   st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",
2440             capacity()/K, heap_used/K);
2441   st->print(" [" PTR_FORMAT ", " PTR_FORMAT ")",
2442             p2i(_hrm.reserved().start()),
2443             p2i(_hrm.reserved().end()));
2444   st->cr();
2445   st->print("  region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K);
2446   uint young_regions = young_regions_count();
2447   st->print("%u young (" SIZE_FORMAT "K), ", young_regions,
2448             (size_t) young_regions * HeapRegion::GrainBytes / K);
2449   uint survivor_regions = survivor_regions_count();
2450   st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions,
2451             (size_t) survivor_regions * HeapRegion::GrainBytes / K);
2452   st->cr();
2453   if (_numa->is_enabled()) {
2454     uint num_nodes = _numa->num_active_nodes();
2455     st->print("  remaining free region(s) on each NUMA node: ");
2456     const int* node_ids = _numa->node_ids();
2457     for (uint node_index = 0; node_index < num_nodes; node_index++) {
2458       uint num_free_regions = _hrm.num_free_regions(node_index);
2459       st->print("%d=%u ", node_ids[node_index], num_free_regions);
2460     }
2461     st->cr();
2462   }
2463   MetaspaceUtils::print_on(st);
2464 }
2465 
2466 void G1CollectedHeap::print_regions_on(outputStream* st) const {
2467   st->print_cr("Heap Regions: E=young(eden), S=young(survivor), O=old, "
2468                "HS=humongous(starts), HC=humongous(continues), "
2469                "CS=collection set, F=free, "
2470                "OA=open archive, CA=closed archive, "
2471                "TAMS=top-at-mark-start (previous, next)");
2472   PrintRegionClosure blk(st);
2473   heap_region_iterate(&blk);
2474 }
2475 
2476 void G1CollectedHeap::print_extended_on(outputStream* st) const {
2477   print_on(st);
2478 
2479   // Print the per-region information.
2480   st->cr();
2481   print_regions_on(st);
2482 }
2483 
2484 void G1CollectedHeap::print_on_error(outputStream* st) const {
2485   this->CollectedHeap::print_on_error(st);
2486 
2487   if (_cm != NULL) {
2488     st->cr();
2489     _cm->print_on_error(st);
2490   }
2491 }
2492 
2493 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
2494   workers()->threads_do(tc);
2495   tc->do_thread(_cm_thread);
2496   _cm->threads_do(tc);
2497   _cr->threads_do(tc);
2498   tc->do_thread(_service_thread);
2499 }
2500 
2501 void G1CollectedHeap::print_tracing_info() const {
2502   rem_set()->print_summary_info();
2503   concurrent_mark()->print_summary_info();
2504 }
2505 
2506 #ifndef PRODUCT
2507 // Helpful for debugging RSet issues.
2508 
2509 class PrintRSetsClosure : public HeapRegionClosure {
2510 private:
2511   const char* _msg;
2512   size_t _occupied_sum;
2513 
2514 public:
2515   bool do_heap_region(HeapRegion* r) {
2516     HeapRegionRemSet* hrrs = r->rem_set();
2517     size_t occupied = hrrs->occupied();
2518     _occupied_sum += occupied;
2519 
2520     tty->print_cr("Printing RSet for region " HR_FORMAT, HR_FORMAT_PARAMS(r));
2521     if (occupied == 0) {
2522       tty->print_cr("  RSet is empty");
2523     } else {
2524       hrrs->print();
2525     }
2526     tty->print_cr("----------");
2527     return false;
2528   }
2529 
2530   PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) {
2531     tty->cr();
2532     tty->print_cr("========================================");
2533     tty->print_cr("%s", msg);
2534     tty->cr();
2535   }
2536 
2537   ~PrintRSetsClosure() {
2538     tty->print_cr("Occupied Sum: " SIZE_FORMAT, _occupied_sum);
2539     tty->print_cr("========================================");
2540     tty->cr();
2541   }
2542 };
2543 
2544 void G1CollectedHeap::print_cset_rsets() {
2545   PrintRSetsClosure cl("Printing CSet RSets");
2546   collection_set_iterate_all(&cl);
2547 }
2548 
2549 void G1CollectedHeap::print_all_rsets() {
2550   PrintRSetsClosure cl("Printing All RSets");;
2551   heap_region_iterate(&cl);
2552 }
2553 #endif // PRODUCT
2554 
2555 bool G1CollectedHeap::print_location(outputStream* st, void* addr) const {
2556   return BlockLocationPrinter<G1CollectedHeap>::print_location(st, addr);
2557 }
2558 
2559 G1HeapSummary G1CollectedHeap::create_g1_heap_summary() {
2560 
2561   size_t eden_used_bytes = _eden.used_bytes();
2562   size_t survivor_used_bytes = _survivor.used_bytes();
2563   size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked();
2564 
2565   size_t eden_capacity_bytes =
2566     (policy()->young_list_target_length() * HeapRegion::GrainBytes) - survivor_used_bytes;
2567 
2568   VirtualSpaceSummary heap_summary = create_heap_space_summary();
2569   return G1HeapSummary(heap_summary, heap_used, eden_used_bytes,
2570                        eden_capacity_bytes, survivor_used_bytes, num_regions());
2571 }
2572 
2573 G1EvacSummary G1CollectedHeap::create_g1_evac_summary(G1EvacStats* stats) {
2574   return G1EvacSummary(stats->allocated(), stats->wasted(), stats->undo_wasted(),
2575                        stats->unused(), stats->used(), stats->region_end_waste(),
2576                        stats->regions_filled(), stats->direct_allocated(),
2577                        stats->failure_used(), stats->failure_waste());
2578 }
2579 
2580 void G1CollectedHeap::trace_heap(GCWhen::Type when, const GCTracer* gc_tracer) {
2581   const G1HeapSummary& heap_summary = create_g1_heap_summary();
2582   gc_tracer->report_gc_heap_summary(when, heap_summary);
2583 
2584   const MetaspaceSummary& metaspace_summary = create_metaspace_summary();
2585   gc_tracer->report_metaspace_summary(when, metaspace_summary);
2586 }
2587 
2588 void G1CollectedHeap::gc_prologue(bool full) {
2589   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
2590 
2591   // Update common counters.
2592   increment_total_collections(full /* full gc */);
2593   if (full || collector_state()->in_concurrent_start_gc()) {
2594     increment_old_marking_cycles_started();
2595   }
2596 }
2597 
2598 void G1CollectedHeap::gc_epilogue(bool full) {
2599   // Update common counters.
2600   if (full) {
2601     // Update the number of full collections that have been completed.
2602     increment_old_marking_cycles_completed(false /* concurrent */, true /* liveness_completed */);
2603   }
2604 
2605 #if COMPILER2_OR_JVMCI
2606   assert(DerivedPointerTable::is_empty(), "derived pointer present");
2607 #endif
2608 
2609   // We have just completed a GC. Update the soft reference
2610   // policy with the new heap occupancy
2611   Universe::heap()->update_capacity_and_used_at_gc();
2612 
2613   _collection_pause_end = Ticks::now();
2614 
2615   _free_segmented_array_memory_task->notify_new_stats(&_young_gen_card_set_stats,
2616                                                       &_collection_set_candidates_card_set_stats);
2617 }
2618 
2619 uint G1CollectedHeap::uncommit_regions(uint region_limit) {
2620   return _hrm.uncommit_inactive_regions(region_limit);
2621 }
2622 
2623 bool G1CollectedHeap::has_uncommittable_regions() {
2624   return _hrm.has_inactive_regions();
2625 }
2626 
2627 void G1CollectedHeap::uncommit_regions_if_necessary() {
2628   if (has_uncommittable_regions()) {
2629     G1UncommitRegionTask::enqueue();
2630   }
2631 }
2632 
2633 void G1CollectedHeap::verify_numa_regions(const char* desc) {
2634   LogTarget(Trace, gc, heap, verify) lt;
2635 
2636   if (lt.is_enabled()) {
2637     LogStream ls(lt);
2638     // Iterate all heap regions to print matching between preferred numa id and actual numa id.
2639     G1NodeIndexCheckClosure cl(desc, _numa, &ls);
2640     heap_region_iterate(&cl);
2641   }
2642 }
2643 
2644 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
2645                                                uint gc_count_before,
2646                                                bool* succeeded,
2647                                                GCCause::Cause gc_cause) {
2648   assert_heap_not_locked_and_not_at_safepoint();
2649   VM_G1CollectForAllocation op(word_size,
2650                                gc_count_before,
2651                                gc_cause,
2652                                policy()->max_pause_time_ms());
2653   VMThread::execute(&op);
2654 
2655   HeapWord* result = op.result();
2656   bool ret_succeeded = op.prologue_succeeded() && op.gc_succeeded();
2657   assert(result == NULL || ret_succeeded,
2658          "the result should be NULL if the VM did not succeed");
2659   *succeeded = ret_succeeded;
2660 
2661   assert_heap_not_locked();
2662   return result;
2663 }
2664 
2665 void G1CollectedHeap::start_concurrent_cycle(bool concurrent_operation_is_full_mark) {
2666   assert(!_cm_thread->in_progress(), "Can not start concurrent operation while in progress");
2667 
2668   MutexLocker x(CGC_lock, Mutex::_no_safepoint_check_flag);
2669   if (concurrent_operation_is_full_mark) {
2670     _cm->post_concurrent_mark_start();
2671     _cm_thread->start_full_mark();
2672   } else {
2673     _cm->post_concurrent_undo_start();
2674     _cm_thread->start_undo_mark();
2675   }
2676   CGC_lock->notify();
2677 }
2678 
2679 bool G1CollectedHeap::is_potential_eager_reclaim_candidate(HeapRegion* r) const {
2680   // We don't nominate objects with many remembered set entries, on
2681   // the assumption that such objects are likely still live.
2682   HeapRegionRemSet* rem_set = r->rem_set();
2683 
2684   return G1EagerReclaimHumongousObjectsWithStaleRefs ?
2685          rem_set->occupancy_less_or_equal_than(G1EagerReclaimRemSetThreshold) :
2686          G1EagerReclaimHumongousObjects && rem_set->is_empty();
2687 }
2688 
2689 #ifndef PRODUCT
2690 void G1CollectedHeap::verify_region_attr_remset_is_tracked() {
2691   class VerifyRegionAttrRemSet : public HeapRegionClosure {
2692   public:
2693     virtual bool do_heap_region(HeapRegion* r) {
2694       G1CollectedHeap* g1h = G1CollectedHeap::heap();
2695       bool const remset_is_tracked = g1h->region_attr(r->bottom()).remset_is_tracked();
2696       assert(r->rem_set()->is_tracked() == remset_is_tracked,
2697              "Region %u remset tracking status (%s) different to region attribute (%s)",
2698              r->hrm_index(), BOOL_TO_STR(r->rem_set()->is_tracked()), BOOL_TO_STR(remset_is_tracked));
2699       return false;
2700     }
2701   } cl;
2702   heap_region_iterate(&cl);
2703 }
2704 #endif
2705 
2706 class VerifyRegionRemSetClosure : public HeapRegionClosure {
2707   public:
2708     bool do_heap_region(HeapRegion* hr) {
2709       if (!hr->is_archive() && !hr->is_continues_humongous()) {
2710         hr->verify_rem_set();
2711       }
2712       return false;
2713     }
2714 };
2715 
2716 void G1CollectedHeap::start_new_collection_set() {
2717   double start = os::elapsedTime();
2718 
2719   collection_set()->start_incremental_building();
2720 
2721   clear_region_attr();
2722 
2723   guarantee(_eden.length() == 0, "eden should have been cleared");
2724   policy()->transfer_survivors_to_cset(survivor());
2725 
2726   // We redo the verification but now wrt to the new CSet which
2727   // has just got initialized after the previous CSet was freed.
2728   _cm->verify_no_collection_set_oops();
2729 
2730   phase_times()->record_start_new_cset_time_ms((os::elapsedTime() - start) * 1000.0);
2731 }
2732 
2733 G1HeapVerifier::G1VerifyType G1CollectedHeap::young_collection_verify_type() const {
2734   if (collector_state()->in_concurrent_start_gc()) {
2735     return G1HeapVerifier::G1VerifyConcurrentStart;
2736   } else if (collector_state()->in_young_only_phase()) {
2737     return G1HeapVerifier::G1VerifyYoungNormal;
2738   } else {
2739     return G1HeapVerifier::G1VerifyMixed;
2740   }
2741 }
2742 
2743 void G1CollectedHeap::verify_before_young_collection(G1HeapVerifier::G1VerifyType type) {
2744   if (!VerifyBeforeGC) {
2745     return;
2746   }
2747   Ticks start = Ticks::now();
2748   _verifier->prepare_for_verify();
2749   _verifier->verify_region_sets_optional();
2750   _verifier->verify_dirty_young_regions();
2751   if (VerifyRememberedSets) {
2752     log_info(gc, verify)("[Verifying RemSets before GC]");
2753     VerifyRegionRemSetClosure v_cl;
2754     heap_region_iterate(&v_cl);
2755   }
2756   _verifier->verify_before_gc(type);
2757   _verifier->check_bitmaps("GC Start");
2758   verify_numa_regions("GC Start");
2759   phase_times()->record_verify_before_time_ms((Ticks::now() - start).seconds() * MILLIUNITS);
2760 }
2761 
2762 void G1CollectedHeap::verify_after_young_collection(G1HeapVerifier::G1VerifyType type) {
2763   if (!VerifyAfterGC) {
2764     return;
2765   }
2766   Ticks start = Ticks::now();
2767   if (VerifyRememberedSets) {
2768     log_info(gc, verify)("[Verifying RemSets after GC]");
2769     VerifyRegionRemSetClosure v_cl;
2770     heap_region_iterate(&v_cl);
2771   }
2772   _verifier->verify_after_gc(type);
2773   _verifier->check_bitmaps("GC End");
2774   verify_numa_regions("GC End");
2775   _verifier->verify_region_sets_optional();
2776   phase_times()->record_verify_after_time_ms((Ticks::now() - start).seconds() * MILLIUNITS);
2777 }
2778 
2779 void G1CollectedHeap::expand_heap_after_young_collection(){
2780   size_t expand_bytes = _heap_sizing_policy->young_collection_expansion_amount();
2781   if (expand_bytes > 0) {
2782     // No need for an ergo logging here,
2783     // expansion_amount() does this when it returns a value > 0.
2784     double expand_ms = 0.0;
2785     if (!expand(expand_bytes, _workers, &expand_ms)) {
2786       // We failed to expand the heap. Cannot do anything about it.
2787     }
2788     phase_times()->record_expand_heap_time(expand_ms);
2789   }
2790 }
2791 
2792 bool G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
2793   assert_at_safepoint_on_vm_thread();
2794   guarantee(!is_gc_active(), "collection is not reentrant");
2795 
2796   if (GCLocker::check_active_before_gc()) {
2797     return false;
2798   }
2799 
2800   do_collection_pause_at_safepoint_helper(target_pause_time_ms);
2801   return true;
2802 }
2803 
2804 G1HeapPrinterMark::G1HeapPrinterMark(G1CollectedHeap* g1h) : _g1h(g1h), _heap_transition(g1h) {
2805   // This summary needs to be printed before incrementing total collections.
2806   _g1h->rem_set()->print_periodic_summary_info("Before GC RS summary", _g1h->total_collections());
2807   _g1h->print_heap_before_gc();
2808   _g1h->print_heap_regions();
2809 }
2810 
2811 G1HeapPrinterMark::~G1HeapPrinterMark() {
2812   _g1h->policy()->print_age_table();
2813   _g1h->rem_set()->print_coarsen_stats();
2814   // We are at the end of the GC. Total collections has already been increased.
2815   _g1h->rem_set()->print_periodic_summary_info("After GC RS summary", _g1h->total_collections() - 1);
2816 
2817   _heap_transition.print();
2818   _g1h->print_heap_regions();
2819   _g1h->print_heap_after_gc();
2820   // Print NUMA statistics.
2821   _g1h->numa()->print_statistics();
2822 }
2823 
2824 G1JFRTracerMark::G1JFRTracerMark(STWGCTimer* timer, GCTracer* tracer) :
2825   _timer(timer), _tracer(tracer) {
2826 
2827   _timer->register_gc_start();
2828   _tracer->report_gc_start(G1CollectedHeap::heap()->gc_cause(), _timer->gc_start());
2829   G1CollectedHeap::heap()->trace_heap_before_gc(_tracer);
2830 }
2831 
2832 G1JFRTracerMark::~G1JFRTracerMark() {
2833   G1CollectedHeap::heap()->trace_heap_after_gc(_tracer);
2834   _timer->register_gc_end();
2835   _tracer->report_gc_end(_timer->gc_end(), _timer->time_partitions());
2836 }
2837 
2838 void G1CollectedHeap::prepare_tlabs_for_mutator() {
2839   Ticks start = Ticks::now();
2840 
2841   _survivor_evac_stats.adjust_desired_plab_sz();
2842   _old_evac_stats.adjust_desired_plab_sz();
2843 
2844   allocate_dummy_regions();
2845 
2846   _allocator->init_mutator_alloc_regions();
2847 
2848   resize_all_tlabs();
2849 
2850   phase_times()->record_resize_tlab_time_ms((Ticks::now() - start).seconds() * 1000.0);
2851 }
2852 
2853 void G1CollectedHeap::retire_tlabs() {
2854   ensure_parsability(true);
2855 }
2856 
2857 void G1CollectedHeap::do_collection_pause_at_safepoint_helper(double target_pause_time_ms) {
2858   ResourceMark rm;
2859 
2860   IsGCActiveMark active_gc_mark;
2861   GCIdMark gc_id_mark;
2862   SvcGCMarker sgcm(SvcGCMarker::MINOR);
2863 
2864   GCTraceCPUTime tcpu;
2865 
2866   _bytes_used_during_gc = 0;
2867 
2868   policy()->decide_on_concurrent_start_pause();
2869   // Record whether this pause may need to trigger a concurrent operation. Later,
2870   // when we signal the G1ConcurrentMarkThread, the collector state has already
2871   // been reset for the next pause.
2872   bool should_start_concurrent_mark_operation = collector_state()->in_concurrent_start_gc();
2873 
2874   // Perform the collection.
2875   G1YoungCollector collector(gc_cause(), target_pause_time_ms);
2876   collector.collect();
2877 
2878   // It should now be safe to tell the concurrent mark thread to start
2879   // without its logging output interfering with the logging output
2880   // that came from the pause.
2881   if (should_start_concurrent_mark_operation) {
2882     // CAUTION: after the start_concurrent_cycle() call below, the concurrent marking
2883     // thread(s) could be running concurrently with us. Make sure that anything
2884     // after this point does not assume that we are the only GC thread running.
2885     // Note: of course, the actual marking work will not start until the safepoint
2886     // itself is released in SuspendibleThreadSet::desynchronize().
2887     start_concurrent_cycle(collector.concurrent_operation_is_full_mark());
2888     ConcurrentGCBreakpoints::notify_idle_to_active();
2889   }
2890 }
2891 
2892 void G1CollectedHeap::complete_cleaning(BoolObjectClosure* is_alive,
2893                                         bool class_unloading_occurred) {
2894   uint num_workers = workers()->active_workers();
2895   G1ParallelCleaningTask unlink_task(is_alive, num_workers, class_unloading_occurred);
2896   workers()->run_task(&unlink_task);
2897 }
2898 
2899 bool G1STWSubjectToDiscoveryClosure::do_object_b(oop obj) {
2900   assert(obj != NULL, "must not be NULL");
2901   assert(_g1h->is_in_reserved(obj), "Trying to discover obj " PTR_FORMAT " not in heap", p2i(obj));
2902   // The areas the CM and STW ref processor manage must be disjoint. The is_in_cset() below
2903   // may falsely indicate that this is not the case here: however the collection set only
2904   // contains old regions when concurrent mark is not running.
2905   return _g1h->is_in_cset(obj) || _g1h->heap_region_containing(obj)->is_survivor();
2906 }
2907 
2908 void G1CollectedHeap::make_pending_list_reachable() {
2909   if (collector_state()->in_concurrent_start_gc()) {
2910     oop pll_head = Universe::reference_pending_list();
2911     if (pll_head != NULL) {
2912       // Any valid worker id is fine here as we are in the VM thread and single-threaded.
2913       _cm->mark_in_next_bitmap(0 /* worker_id */, pll_head);
2914     }
2915   }
2916 }
2917 
2918 static bool do_humongous_object_logging() {
2919   return log_is_enabled(Debug, gc, humongous);
2920 }
2921 
2922 bool G1CollectedHeap::should_do_eager_reclaim() const {
2923   // As eager reclaim logging also gives information about humongous objects in
2924   // the heap in general, always do the eager reclaim pass even without known
2925   // candidates.
2926   return (G1EagerReclaimHumongousObjects &&
2927           (has_humongous_reclaim_candidates() || do_humongous_object_logging()));
2928 }
2929 
2930 void G1CollectedHeap::set_humongous_stats(uint num_humongous_total, uint num_humongous_candidates) {
2931   _num_humongous_objects = num_humongous_total;
2932   _num_humongous_reclaim_candidates = num_humongous_candidates;
2933 }
2934 
2935 bool G1CollectedHeap::should_sample_collection_set_candidates() const {
2936   G1CollectionSetCandidates* candidates = G1CollectedHeap::heap()->collection_set()->candidates();
2937   return candidates != NULL && candidates->num_remaining() > 0;
2938 }
2939 
2940 void G1CollectedHeap::set_collection_set_candidates_stats(G1SegmentedArrayMemoryStats& stats) {
2941   _collection_set_candidates_card_set_stats = stats;
2942 }
2943 
2944 void G1CollectedHeap::set_young_gen_card_set_stats(const G1SegmentedArrayMemoryStats& stats) {
2945   _young_gen_card_set_stats = stats;
2946 }
2947 
2948 void G1CollectedHeap::record_obj_copy_mem_stats() {
2949   policy()->old_gen_alloc_tracker()->
2950     add_allocated_bytes_since_last_gc(_old_evac_stats.allocated() * HeapWordSize);
2951 
2952   _gc_tracer_stw->report_evacuation_statistics(create_g1_evac_summary(&_survivor_evac_stats),
2953                                                create_g1_evac_summary(&_old_evac_stats));
2954 }
2955 
2956 void G1CollectedHeap::clear_prev_bitmap_for_region(HeapRegion* hr) {
2957   MemRegion mr(hr->bottom(), hr->end());
2958   concurrent_mark()->clear_range_in_prev_bitmap(mr);
2959 }
2960 
2961 void G1CollectedHeap::free_region(HeapRegion* hr, FreeRegionList* free_list) {
2962   assert(!hr->is_free(), "the region should not be free");
2963   assert(!hr->is_empty(), "the region should not be empty");
2964   assert(_hrm.is_available(hr->hrm_index()), "region should be committed");
2965 
2966   if (G1VerifyBitmaps) {
2967     clear_prev_bitmap_for_region(hr);
2968   }
2969 
2970   // Clear the card counts for this region.
2971   // Note: we only need to do this if the region is not young
2972   // (since we don't refine cards in young regions).
2973   if (!hr->is_young()) {
2974     _hot_card_cache->reset_card_counts(hr);
2975   }
2976 
2977   // Reset region metadata to allow reuse.
2978   hr->hr_clear(true /* clear_space */);
2979   _policy->remset_tracker()->update_at_free(hr);
2980 
2981   if (free_list != NULL) {
2982     free_list->add_ordered(hr);
2983   }
2984 }
2985 
2986 void G1CollectedHeap::free_humongous_region(HeapRegion* hr,
2987                                             FreeRegionList* free_list) {
2988   assert(hr->is_humongous(), "this is only for humongous regions");
2989   hr->clear_humongous();
2990   free_region(hr, free_list);
2991 }
2992 
2993 void G1CollectedHeap::remove_from_old_gen_sets(const uint old_regions_removed,
2994                                                const uint archive_regions_removed,
2995                                                const uint humongous_regions_removed) {
2996   if (old_regions_removed > 0 || archive_regions_removed > 0 || humongous_regions_removed > 0) {
2997     MutexLocker x(OldSets_lock, Mutex::_no_safepoint_check_flag);
2998     _old_set.bulk_remove(old_regions_removed);
2999     _archive_set.bulk_remove(archive_regions_removed);
3000     _humongous_set.bulk_remove(humongous_regions_removed);
3001   }
3002 
3003 }
3004 
3005 void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) {
3006   assert(list != NULL, "list can't be null");
3007   if (!list->is_empty()) {
3008     MutexLocker x(FreeList_lock, Mutex::_no_safepoint_check_flag);
3009     _hrm.insert_list_into_free_list(list);
3010   }
3011 }
3012 
3013 void G1CollectedHeap::decrement_summary_bytes(size_t bytes) {
3014   decrease_used(bytes);
3015 }
3016 
3017 void G1CollectedHeap::clear_eden() {
3018   _eden.clear();
3019 }
3020 
3021 void G1CollectedHeap::clear_collection_set() {
3022   collection_set()->clear();
3023 }
3024 
3025 void G1CollectedHeap::rebuild_free_region_list() {
3026   Ticks start = Ticks::now();
3027   _hrm.rebuild_free_list(workers());
3028   phase_times()->record_total_rebuild_freelist_time_ms((Ticks::now() - start).seconds() * 1000.0);
3029 }
3030 
3031 class G1AbandonCollectionSetClosure : public HeapRegionClosure {
3032 public:
3033   virtual bool do_heap_region(HeapRegion* r) {
3034     assert(r->in_collection_set(), "Region %u must have been in collection set", r->hrm_index());
3035     G1CollectedHeap::heap()->clear_region_attr(r);
3036     r->clear_young_index_in_cset();
3037     return false;
3038   }
3039 };
3040 
3041 void G1CollectedHeap::abandon_collection_set(G1CollectionSet* collection_set) {
3042   G1AbandonCollectionSetClosure cl;
3043   collection_set_iterate_all(&cl);
3044 
3045   collection_set->clear();
3046   collection_set->stop_incremental_building();
3047 }
3048 
3049 bool G1CollectedHeap::is_old_gc_alloc_region(HeapRegion* hr) {
3050   return _allocator->is_retained_old_region(hr);
3051 }
3052 
3053 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {
3054   _eden.add(hr);
3055   _policy->set_region_eden(hr);
3056 }
3057 
3058 #ifdef ASSERT
3059 
3060 class NoYoungRegionsClosure: public HeapRegionClosure {
3061 private:
3062   bool _success;
3063 public:
3064   NoYoungRegionsClosure() : _success(true) { }
3065   bool do_heap_region(HeapRegion* r) {
3066     if (r->is_young()) {
3067       log_error(gc, verify)("Region [" PTR_FORMAT ", " PTR_FORMAT ") tagged as young",
3068                             p2i(r->bottom()), p2i(r->end()));
3069       _success = false;
3070     }
3071     return false;
3072   }
3073   bool success() { return _success; }
3074 };
3075 
3076 bool G1CollectedHeap::check_young_list_empty() {
3077   bool ret = (young_regions_count() == 0);
3078 
3079   NoYoungRegionsClosure closure;
3080   heap_region_iterate(&closure);
3081   ret = ret && closure.success();
3082 
3083   return ret;
3084 }
3085 
3086 #endif // ASSERT
3087 
3088 // Remove the given HeapRegion from the appropriate region set.
3089 void G1CollectedHeap::prepare_region_for_full_compaction(HeapRegion* hr) {
3090    if (hr->is_archive()) {
3091     _archive_set.remove(hr);
3092   } else if (hr->is_humongous()) {
3093     _humongous_set.remove(hr);
3094   } else if (hr->is_old()) {
3095     _old_set.remove(hr);
3096   } else if (hr->is_young()) {
3097     // Note that emptying the eden and survivor lists is postponed and instead
3098     // done as the first step when rebuilding the regions sets again. The reason
3099     // for this is that during a full GC string deduplication needs to know if
3100     // a collected region was young or old when the full GC was initiated.
3101     hr->uninstall_surv_rate_group();
3102   } else {
3103     // We ignore free regions, we'll empty the free list afterwards.
3104     assert(hr->is_free(), "it cannot be another type");
3105   }
3106 }
3107 
3108 void G1CollectedHeap::increase_used(size_t bytes) {
3109   _summary_bytes_used += bytes;
3110 }
3111 
3112 void G1CollectedHeap::decrease_used(size_t bytes) {
3113   assert(_summary_bytes_used >= bytes,
3114          "invariant: _summary_bytes_used: " SIZE_FORMAT " should be >= bytes: " SIZE_FORMAT,
3115          _summary_bytes_used, bytes);
3116   _summary_bytes_used -= bytes;
3117 }
3118 
3119 void G1CollectedHeap::set_used(size_t bytes) {
3120   _summary_bytes_used = bytes;
3121 }
3122 
3123 class RebuildRegionSetsClosure : public HeapRegionClosure {
3124 private:
3125   bool _free_list_only;
3126 
3127   HeapRegionSet* _old_set;
3128   HeapRegionSet* _archive_set;
3129   HeapRegionSet* _humongous_set;
3130 
3131   HeapRegionManager* _hrm;
3132 
3133   size_t _total_used;
3134 
3135 public:
3136   RebuildRegionSetsClosure(bool free_list_only,
3137                            HeapRegionSet* old_set,
3138                            HeapRegionSet* archive_set,
3139                            HeapRegionSet* humongous_set,
3140                            HeapRegionManager* hrm) :
3141     _free_list_only(free_list_only), _old_set(old_set), _archive_set(archive_set),
3142     _humongous_set(humongous_set), _hrm(hrm), _total_used(0) {
3143     assert(_hrm->num_free_regions() == 0, "pre-condition");
3144     if (!free_list_only) {
3145       assert(_old_set->is_empty(), "pre-condition");
3146       assert(_archive_set->is_empty(), "pre-condition");
3147       assert(_humongous_set->is_empty(), "pre-condition");
3148     }
3149   }
3150 
3151   bool do_heap_region(HeapRegion* r) {
3152     if (r->is_empty()) {
3153       assert(r->rem_set()->is_empty(), "Empty regions should have empty remembered sets.");
3154       // Add free regions to the free list
3155       r->set_free();
3156       _hrm->insert_into_free_list(r);
3157     } else if (!_free_list_only) {
3158       assert(r->rem_set()->is_empty(), "At this point remembered sets must have been cleared.");
3159 
3160       if (r->is_humongous()) {
3161         _humongous_set->add(r);
3162       } else if (r->is_archive()) {
3163         _archive_set->add(r);
3164       } else {
3165         assert(r->is_young() || r->is_free() || r->is_old(), "invariant");
3166         // We now move all (non-humongous, non-old, non-archive) regions to old gen,
3167         // and register them as such.
3168         r->move_to_old();
3169         _old_set->add(r);
3170       }
3171       _total_used += r->used();
3172     }
3173 
3174     return false;
3175   }
3176 
3177   size_t total_used() {
3178     return _total_used;
3179   }
3180 };
3181 
3182 void G1CollectedHeap::rebuild_region_sets(bool free_list_only) {
3183   assert_at_safepoint_on_vm_thread();
3184 
3185   if (!free_list_only) {
3186     _eden.clear();
3187     _survivor.clear();
3188   }
3189 
3190   RebuildRegionSetsClosure cl(free_list_only,
3191                               &_old_set, &_archive_set, &_humongous_set,
3192                               &_hrm);
3193   heap_region_iterate(&cl);
3194 
3195   if (!free_list_only) {
3196     set_used(cl.total_used());
3197     assert(_archive_allocator == nullptr, "must be, should not contribute to used");
3198   }
3199   assert_used_and_recalculate_used_equal(this);
3200 }
3201 
3202 // Methods for the mutator alloc region
3203 
3204 HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size,
3205                                                       bool force,
3206                                                       uint node_index) {
3207   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
3208   bool should_allocate = policy()->should_allocate_mutator_region();
3209   if (force || should_allocate) {
3210     HeapRegion* new_alloc_region = new_region(word_size,
3211                                               HeapRegionType::Eden,
3212                                               false /* do_expand */,
3213                                               node_index);
3214     if (new_alloc_region != NULL) {
3215       set_region_short_lived_locked(new_alloc_region);
3216       _hr_printer.alloc(new_alloc_region, !should_allocate);
3217       _verifier->check_bitmaps("Mutator Region Allocation", new_alloc_region);
3218       _policy->remset_tracker()->update_at_allocate(new_alloc_region);
3219       return new_alloc_region;
3220     }
3221   }
3222   return NULL;
3223 }
3224 
3225 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region,
3226                                                   size_t allocated_bytes) {
3227   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
3228   assert(alloc_region->is_eden(), "all mutator alloc regions should be eden");
3229 
3230   collection_set()->add_eden_region(alloc_region);
3231   increase_used(allocated_bytes);
3232   _eden.add_used_bytes(allocated_bytes);
3233   _hr_printer.retire(alloc_region);
3234 
3235   // We update the eden sizes here, when the region is retired,
3236   // instead of when it's allocated, since this is the point that its
3237   // used space has been recorded in _summary_bytes_used.
3238   monitoring_support()->update_eden_size();
3239 }
3240 
3241 // Methods for the GC alloc regions
3242 
3243 bool G1CollectedHeap::has_more_regions(G1HeapRegionAttr dest) {
3244   if (dest.is_old()) {
3245     return true;
3246   } else {
3247     return survivor_regions_count() < policy()->max_survivor_regions();
3248   }
3249 }
3250 
3251 HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size, G1HeapRegionAttr dest, uint node_index) {
3252   assert(FreeList_lock->owned_by_self(), "pre-condition");
3253 
3254   if (!has_more_regions(dest)) {
3255     return NULL;
3256   }
3257 
3258   HeapRegionType type;
3259   if (dest.is_young()) {
3260     type = HeapRegionType::Survivor;
3261   } else {
3262     type = HeapRegionType::Old;
3263   }
3264 
3265   HeapRegion* new_alloc_region = new_region(word_size,
3266                                             type,
3267                                             true /* do_expand */,
3268                                             node_index);
3269 
3270   if (new_alloc_region != NULL) {
3271     if (type.is_survivor()) {
3272       new_alloc_region->set_survivor();
3273       _survivor.add(new_alloc_region);
3274       _verifier->check_bitmaps("Survivor Region Allocation", new_alloc_region);
3275       register_new_survivor_region_with_region_attr(new_alloc_region);
3276     } else {
3277       new_alloc_region->set_old();
3278       _verifier->check_bitmaps("Old Region Allocation", new_alloc_region);
3279     }
3280     _policy->remset_tracker()->update_at_allocate(new_alloc_region);
3281     register_region_with_region_attr(new_alloc_region);
3282     _hr_printer.alloc(new_alloc_region);
3283     return new_alloc_region;
3284   }
3285   return NULL;
3286 }
3287 
3288 void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region,
3289                                              size_t allocated_bytes,
3290                                              G1HeapRegionAttr dest) {
3291   _bytes_used_during_gc += allocated_bytes;
3292   if (dest.is_old()) {
3293     old_set_add(alloc_region);
3294   } else {
3295     assert(dest.is_young(), "Retiring alloc region should be young (%d)", dest.type());
3296     _survivor.add_used_bytes(allocated_bytes);
3297   }
3298 
3299   bool const during_im = collector_state()->in_concurrent_start_gc();
3300   if (during_im && allocated_bytes > 0) {
3301     _cm->root_regions()->add(alloc_region->next_top_at_mark_start(), alloc_region->top());
3302   }
3303   _hr_printer.retire(alloc_region);
3304 }
3305 
3306 HeapRegion* G1CollectedHeap::alloc_highest_free_region() {
3307   bool expanded = false;
3308   uint index = _hrm.find_highest_free(&expanded);
3309 
3310   if (index != G1_NO_HRM_INDEX) {
3311     if (expanded) {
3312       log_debug(gc, ergo, heap)("Attempt heap expansion (requested address range outside heap bounds). region size: " SIZE_FORMAT "B",
3313                                 HeapRegion::GrainWords * HeapWordSize);
3314     }
3315     return _hrm.allocate_free_regions_starting_at(index, 1);
3316   }
3317   return NULL;
3318 }
3319 
3320 void G1CollectedHeap::mark_evac_failure_object(const oop obj, uint worker_id) const {
3321   // All objects failing evacuation are live. What we'll do is
3322   // that we'll update the prev marking info so that they are
3323   // all under PTAMS and explicitly marked.
3324   _cm->par_mark_in_prev_bitmap(obj);
3325 }
3326 
3327 // Optimized nmethod scanning
3328 
3329 class RegisterNMethodOopClosure: public OopClosure {
3330   G1CollectedHeap* _g1h;
3331   nmethod* _nm;
3332 
3333 public:
3334   RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
3335     _g1h(g1h), _nm(nm) {}
3336 
3337   void do_oop(oop* p) {
3338     oop heap_oop = RawAccess<>::oop_load(p);
3339     if (!CompressedOops::is_null(heap_oop)) {
3340       oop obj = CompressedOops::decode_not_null(heap_oop);
3341       HeapRegion* hr = _g1h->heap_region_containing(obj);
3342       assert(!hr->is_continues_humongous(),
3343              "trying to add code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT
3344              " starting at " HR_FORMAT,
3345              p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()));
3346 
3347       // HeapRegion::add_code_root_locked() avoids adding duplicate entries.
3348       hr->add_code_root_locked(_nm);
3349     }
3350   }
3351 
3352   void do_oop(narrowOop* p) { ShouldNotReachHere(); }
3353 };
3354 
3355 class UnregisterNMethodOopClosure: public OopClosure {
3356   G1CollectedHeap* _g1h;
3357   nmethod* _nm;
3358 
3359 public:
3360   UnregisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
3361     _g1h(g1h), _nm(nm) {}
3362 
3363   void do_oop(oop* p) {
3364     oop heap_oop = RawAccess<>::oop_load(p);
3365     if (!CompressedOops::is_null(heap_oop)) {
3366       oop obj = CompressedOops::decode_not_null(heap_oop);
3367       HeapRegion* hr = _g1h->heap_region_containing(obj);
3368       assert(!hr->is_continues_humongous(),
3369              "trying to remove code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT
3370              " starting at " HR_FORMAT,
3371              p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()));
3372 
3373       hr->remove_code_root(_nm);
3374     }
3375   }
3376 
3377   void do_oop(narrowOop* p) { ShouldNotReachHere(); }
3378 };
3379 
3380 void G1CollectedHeap::register_nmethod(nmethod* nm) {
3381   guarantee(nm != NULL, "sanity");
3382   RegisterNMethodOopClosure reg_cl(this, nm);
3383   nm->oops_do(&reg_cl);
3384 }
3385 
3386 void G1CollectedHeap::unregister_nmethod(nmethod* nm) {
3387   guarantee(nm != NULL, "sanity");
3388   UnregisterNMethodOopClosure reg_cl(this, nm);
3389   nm->oops_do(&reg_cl, true);
3390 }
3391 
3392 void G1CollectedHeap::update_used_after_gc(bool evacuation_failed) {
3393   if (evacuation_failed) {
3394     // Reset the G1EvacuationFailureALot counters and flags
3395     evac_failure_injector()->reset();
3396 
3397     set_used(recalculate_used());
3398 
3399     assert(_archive_allocator == nullptr, "must be, should not contribute to used");
3400   } else {
3401     // The "used" of the the collection set have already been subtracted
3402     // when they were freed.  Add in the bytes used.
3403     increase_used(_bytes_used_during_gc);
3404   }
3405 }
3406 
3407 void G1CollectedHeap::reset_hot_card_cache() {
3408   _hot_card_cache->reset_hot_cache();
3409   _hot_card_cache->set_use_cache(true);
3410 }
3411 
3412 void G1CollectedHeap::purge_code_root_memory() {
3413   G1CodeRootSet::purge();
3414 }
3415 
3416 class RebuildCodeRootClosure: public CodeBlobClosure {
3417   G1CollectedHeap* _g1h;
3418 
3419 public:
3420   RebuildCodeRootClosure(G1CollectedHeap* g1h) :
3421     _g1h(g1h) {}
3422 
3423   void do_code_blob(CodeBlob* cb) {
3424     nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL;
3425     if (nm == NULL) {
3426       return;
3427     }
3428 
3429     _g1h->register_nmethod(nm);
3430   }
3431 };
3432 
3433 void G1CollectedHeap::rebuild_code_roots() {
3434   RebuildCodeRootClosure blob_cl(this);
3435   CodeCache::blobs_do(&blob_cl);
3436 }
3437 
3438 void G1CollectedHeap::initialize_serviceability() {
3439   _monitoring_support->initialize_serviceability();
3440 }
3441 
3442 MemoryUsage G1CollectedHeap::memory_usage() {
3443   return _monitoring_support->memory_usage();
3444 }
3445 
3446 GrowableArray<GCMemoryManager*> G1CollectedHeap::memory_managers() {
3447   return _monitoring_support->memory_managers();
3448 }
3449 
3450 GrowableArray<MemoryPool*> G1CollectedHeap::memory_pools() {
3451   return _monitoring_support->memory_pools();
3452 }
3453 
3454 void G1CollectedHeap::fill_with_dummy_object(HeapWord* start, HeapWord* end, bool zap) {
3455   HeapRegion* region = heap_region_containing(start);
3456   region->fill_with_dummy_object(start, pointer_delta(end, start), zap);
3457 }