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