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