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