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