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