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