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