1 /*
   2  * Copyright (c) 2001, 2021, 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/g1CollectedHeap.inline.hpp"
  36 #include "gc/g1/g1CollectionSet.hpp"
  37 #include "gc/g1/g1CollectorState.hpp"
  38 #include "gc/g1/g1ConcurrentRefine.hpp"
  39 #include "gc/g1/g1ConcurrentRefineThread.hpp"
  40 #include "gc/g1/g1ConcurrentMarkThread.inline.hpp"
  41 #include "gc/g1/g1DirtyCardQueue.hpp"
  42 #include "gc/g1/g1EvacStats.inline.hpp"
  43 #include "gc/g1/g1FullCollector.hpp"
  44 #include "gc/g1/g1GCParPhaseTimesTracker.hpp"
  45 #include "gc/g1/g1GCPhaseTimes.hpp"
  46 #include "gc/g1/g1GCPauseType.hpp"
  47 #include "gc/g1/g1HeapSizingPolicy.hpp"
  48 #include "gc/g1/g1HeapTransition.hpp"
  49 #include "gc/g1/g1HeapVerifier.hpp"
  50 #include "gc/g1/g1HotCardCache.hpp"
  51 #include "gc/g1/g1InitLogger.hpp"
  52 #include "gc/g1/g1MemoryPool.hpp"
  53 #include "gc/g1/g1OopClosures.inline.hpp"
  54 #include "gc/g1/g1ParallelCleaning.hpp"
  55 #include "gc/g1/g1ParScanThreadState.inline.hpp"
  56 #include "gc/g1/g1PeriodicGCTask.hpp"
  57 #include "gc/g1/g1Policy.hpp"
  58 #include "gc/g1/g1RedirtyCardsQueue.hpp"
  59 #include "gc/g1/g1RegionToSpaceMapper.hpp"
  60 #include "gc/g1/g1RemSet.hpp"
  61 #include "gc/g1/g1RootClosures.hpp"
  62 #include "gc/g1/g1RootProcessor.hpp"
  63 #include "gc/g1/g1SATBMarkQueueSet.hpp"
  64 #include "gc/g1/g1ThreadLocalData.hpp"
  65 #include "gc/g1/g1Trace.hpp"
  66 #include "gc/g1/g1ServiceThread.hpp"
  67 #include "gc/g1/g1UncommitRegionTask.hpp"
  68 #include "gc/g1/g1VMOperations.hpp"
  69 #include "gc/g1/g1YoungGCPostEvacuateTasks.hpp"
  70 #include "gc/g1/heapRegion.inline.hpp"
  71 #include "gc/g1/heapRegionRemSet.hpp"
  72 #include "gc/g1/heapRegionSet.inline.hpp"
  73 #include "gc/shared/concurrentGCBreakpoints.hpp"
  74 #include "gc/shared/gcBehaviours.hpp"
  75 #include "gc/shared/gcHeapSummary.hpp"
  76 #include "gc/shared/gcId.hpp"
  77 #include "gc/shared/gcLocker.hpp"
  78 #include "gc/shared/gcTimer.hpp"
  79 #include "gc/shared/gcTraceTime.inline.hpp"
  80 #include "gc/shared/generationSpec.hpp"
  81 #include "gc/shared/isGCActiveMark.hpp"
  82 #include "gc/shared/locationPrinter.inline.hpp"
  83 #include "gc/shared/oopStorageParState.hpp"
  84 #include "gc/shared/preservedMarks.inline.hpp"
  85 #include "gc/shared/slidingForwarding.hpp"
  86 #include "gc/shared/suspendibleThreadSet.hpp"
  87 #include "gc/shared/referenceProcessor.inline.hpp"
  88 #include "gc/shared/taskTerminator.hpp"
  89 #include "gc/shared/taskqueue.inline.hpp"
  90 #include "gc/shared/tlab_globals.hpp"
  91 #include "gc/shared/weakProcessor.inline.hpp"
  92 #include "gc/shared/workerPolicy.hpp"
  93 #include "logging/log.hpp"
  94 #include "memory/allocation.hpp"
  95 #include "memory/iterator.hpp"
  96 #include "memory/heapInspection.hpp"
  97 #include "memory/metaspaceUtils.hpp"
  98 #include "memory/resourceArea.hpp"
  99 #include "memory/universe.hpp"
 100 #include "oops/access.inline.hpp"
 101 #include "oops/compressedOops.inline.hpp"
 102 #include "oops/oop.inline.hpp"
 103 #include "runtime/atomic.hpp"
 104 #include "runtime/handles.inline.hpp"
 105 #include "runtime/init.hpp"
 106 #include "runtime/java.hpp"
 107 #include "runtime/orderAccess.hpp"
 108 #include "runtime/threadSMR.hpp"
 109 #include "runtime/vmThread.hpp"
 110 #include "utilities/align.hpp"
 111 #include "utilities/autoRestore.hpp"
 112 #include "utilities/bitMap.inline.hpp"
 113 #include "utilities/globalDefinitions.hpp"
 114 #include "utilities/stack.inline.hpp"
 115 
 116 size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
 117 
 118 // INVARIANTS/NOTES
 119 //
 120 // All allocation activity covered by the G1CollectedHeap interface is
 121 // serialized by acquiring the HeapLock.  This happens in mem_allocate
 122 // and allocate_new_tlab, which are the "entry" points to the
 123 // allocation code from the rest of the JVM.  (Note that this does not
 124 // apply to TLAB allocation, which is not part of this interface: it
 125 // is done by clients of this interface.)
 126 
 127 void G1RegionMappingChangedListener::reset_from_card_cache(uint start_idx, size_t num_regions) {
 128   HeapRegionRemSet::invalidate_from_card_cache(start_idx, num_regions);
 129 }
 130 
 131 void G1RegionMappingChangedListener::on_commit(uint start_idx, size_t num_regions, bool zero_filled) {
 132   // The from card cache is not the memory that is actually committed. So we cannot
 133   // take advantage of the zero_filled parameter.
 134   reset_from_card_cache(start_idx, num_regions);
 135 }
 136 
 137 Tickspan G1CollectedHeap::run_task_timed(AbstractGangTask* task) {
 138   Ticks start = Ticks::now();
 139   workers()->run_task(task);
 140   return Ticks::now() - start;
 141 }
 142 
 143 void G1CollectedHeap::run_batch_task(G1BatchedGangTask* cl) {
 144   uint num_workers = MAX2(1u, MIN2(cl->num_workers_estimate(), workers()->active_workers()));
 145   cl->set_max_workers(num_workers);
 146   workers()->run_task(cl, num_workers);
 147 }
 148 
 149 HeapRegion* G1CollectedHeap::new_heap_region(uint hrs_index,
 150                                              MemRegion mr) {
 151   return new HeapRegion(hrs_index, bot(), mr);
 152 }
 153 
 154 // Private methods.
 155 
 156 HeapRegion* G1CollectedHeap::new_region(size_t word_size,
 157                                         HeapRegionType type,
 158                                         bool do_expand,
 159                                         uint node_index) {
 160   assert(!is_humongous(word_size) || word_size <= HeapRegion::GrainWords,
 161          "the only time we use this to allocate a humongous region is "
 162          "when we are allocating a single humongous region");
 163 
 164   HeapRegion* res = _hrm.allocate_free_region(type, node_index);
 165 
 166   if (res == NULL && do_expand && _expand_heap_after_alloc_failure) {
 167     // Currently, only attempts to allocate GC alloc regions set
 168     // do_expand to true. So, we should only reach here during a
 169     // safepoint. If this assumption changes we might have to
 170     // reconsider the use of _expand_heap_after_alloc_failure.
 171     assert(SafepointSynchronize::is_at_safepoint(), "invariant");
 172 
 173     log_debug(gc, ergo, heap)("Attempt heap expansion (region allocation request failed). Allocation request: " SIZE_FORMAT "B",
 174                               word_size * HeapWordSize);
 175 
 176     assert(word_size * HeapWordSize < HeapRegion::GrainBytes,
 177            "This kind of expansion should never be more than one region. Size: " SIZE_FORMAT,
 178            word_size * HeapWordSize);
 179     if (expand_single_region(node_index)) {
 180       // Given that expand_single_region() succeeded in expanding the heap, and we
 181       // always expand the heap by an amount aligned to the heap
 182       // region size, the free list should in theory not be empty.
 183       // In either case allocate_free_region() will check for NULL.
 184       res = _hrm.allocate_free_region(type, node_index);
 185     } else {
 186       _expand_heap_after_alloc_failure = false;
 187     }
 188   }
 189   return res;
 190 }
 191 
 192 HeapWord*
 193 G1CollectedHeap::humongous_obj_allocate_initialize_regions(HeapRegion* first_hr,
 194                                                            uint num_regions,
 195                                                            size_t word_size) {
 196   assert(first_hr != NULL, "pre-condition");
 197   assert(is_humongous(word_size), "word_size should be humongous");
 198   assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition");
 199 
 200   // Index of last region in the series.
 201   uint first = first_hr->hrm_index();
 202   uint last = first + num_regions - 1;
 203 
 204   // We need to initialize the region(s) we just discovered. This is
 205   // a bit tricky given that it can happen concurrently with
 206   // refinement threads refining cards on these regions and
 207   // potentially wanting to refine the BOT as they are scanning
 208   // those cards (this can happen shortly after a cleanup; see CR
 209   // 6991377). So we have to set up the region(s) carefully and in
 210   // a specific order.
 211 
 212   // The word size sum of all the regions we will allocate.
 213   size_t word_size_sum = (size_t) num_regions * HeapRegion::GrainWords;
 214   assert(word_size <= word_size_sum, "sanity");
 215 
 216   // The passed in hr will be the "starts humongous" region. The header
 217   // of the new object will be placed at the bottom of this region.
 218   HeapWord* new_obj = first_hr->bottom();
 219   // This will be the new top of the new object.
 220   HeapWord* obj_top = new_obj + word_size;
 221 
 222   // First, we need to zero the header of the space that we will be
 223   // allocating. When we update top further down, some refinement
 224   // threads might try to scan the region. By zeroing the header we
 225   // ensure that any thread that will try to scan the region will
 226   // come across the zero klass word and bail out.
 227   //
 228   // NOTE: It would not have been correct to have used
 229   // CollectedHeap::fill_with_object() and make the space look like
 230   // an int array. The thread that is doing the allocation will
 231   // later update the object header to a potentially different array
 232   // type and, for a very short period of time, the klass and length
 233   // fields will be inconsistent. This could cause a refinement
 234   // thread to calculate the object size incorrectly.
 235   Copy::fill_to_words(new_obj, oopDesc::header_size(), 0);
 236 
 237   // Next, pad out the unused tail of the last region with filler
 238   // objects, for improved usage accounting.
 239   // How many words we use for filler objects.
 240   size_t word_fill_size = word_size_sum - word_size;
 241 
 242   // How many words memory we "waste" which cannot hold a filler object.
 243   size_t words_not_fillable = 0;
 244 
 245   if (word_fill_size >= min_fill_size()) {
 246     fill_with_objects(obj_top, word_fill_size);
 247   } else if (word_fill_size > 0) {
 248     // We have space to fill, but we cannot fit an object there.
 249     words_not_fillable = word_fill_size;
 250     word_fill_size = 0;
 251   }
 252 
 253   // We will set up the first region as "starts humongous". This
 254   // will also update the BOT covering all the regions to reflect
 255   // that there is a single object that starts at the bottom of the
 256   // first region.
 257   first_hr->set_starts_humongous(obj_top, word_fill_size);
 258   _policy->remset_tracker()->update_at_allocate(first_hr);
 259   // Then, if there are any, we will set up the "continues
 260   // humongous" regions.
 261   HeapRegion* hr = NULL;
 262   for (uint i = first + 1; i <= last; ++i) {
 263     hr = region_at(i);
 264     hr->set_continues_humongous(first_hr);
 265     _policy->remset_tracker()->update_at_allocate(hr);
 266   }
 267 
 268   // Up to this point no concurrent thread would have been able to
 269   // do any scanning on any region in this series. All the top
 270   // fields still point to bottom, so the intersection between
 271   // [bottom,top] and [card_start,card_end] will be empty. Before we
 272   // update the top fields, we'll do a storestore to make sure that
 273   // no thread sees the update to top before the zeroing of the
 274   // object header and the BOT initialization.
 275   OrderAccess::storestore();
 276 
 277   // Now, we will update the top fields of the "continues humongous"
 278   // regions except the last one.
 279   for (uint i = first; i < last; ++i) {
 280     hr = region_at(i);
 281     hr->set_top(hr->end());
 282   }
 283 
 284   hr = region_at(last);
 285   // If we cannot fit a filler object, we must set top to the end
 286   // of the humongous object, otherwise we cannot iterate the heap
 287   // and the BOT will not be complete.
 288   hr->set_top(hr->end() - words_not_fillable);
 289 
 290   assert(hr->bottom() < obj_top && obj_top <= hr->end(),
 291          "obj_top should be in last region");
 292 
 293   _verifier->check_bitmaps("Humongous Region Allocation", first_hr);
 294 
 295   assert(words_not_fillable == 0 ||
 296          first_hr->bottom() + word_size_sum - words_not_fillable == hr->top(),
 297          "Miscalculation in humongous allocation");
 298 
 299   increase_used((word_size_sum - words_not_fillable) * HeapWordSize);
 300 
 301   for (uint i = first; i <= last; ++i) {
 302     hr = region_at(i);
 303     _humongous_set.add(hr);
 304     _hr_printer.alloc(hr);
 305   }
 306 
 307   return new_obj;
 308 }
 309 
 310 size_t G1CollectedHeap::humongous_obj_size_in_regions(size_t word_size) {
 311   assert(is_humongous(word_size), "Object of size " SIZE_FORMAT " must be humongous here", word_size);
 312   return align_up(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords;
 313 }
 314 
 315 // If could fit into free regions w/o expansion, try.
 316 // Otherwise, if can expand, do so.
 317 // Otherwise, if using ex regions might help, try with ex given back.
 318 HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size) {
 319   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
 320 
 321   _verifier->verify_region_sets_optional();
 322 
 323   uint obj_regions = (uint) humongous_obj_size_in_regions(word_size);
 324 
 325   // Policy: First try to allocate a humongous object in the free list.
 326   HeapRegion* humongous_start = _hrm.allocate_humongous(obj_regions);
 327   if (humongous_start == NULL) {
 328     // Policy: We could not find enough regions for the humongous object in the
 329     // free list. Look through the heap to find a mix of free and uncommitted regions.
 330     // If so, expand the heap and allocate the humongous object.
 331     humongous_start = _hrm.expand_and_allocate_humongous(obj_regions);
 332     if (humongous_start != NULL) {
 333       // We managed to find a region by expanding the heap.
 334       log_debug(gc, ergo, heap)("Heap expansion (humongous allocation request). Allocation request: " SIZE_FORMAT "B",
 335                                 word_size * HeapWordSize);
 336       policy()->record_new_heap_size(num_regions());
 337     } else {
 338       // Policy: Potentially trigger a defragmentation GC.
 339     }
 340   }
 341 
 342   HeapWord* result = NULL;
 343   if (humongous_start != NULL) {
 344     result = humongous_obj_allocate_initialize_regions(humongous_start, obj_regions, word_size);
 345     assert(result != NULL, "it should always return a valid result");
 346 
 347     // A successful humongous object allocation changes the used space
 348     // information of the old generation so we need to recalculate the
 349     // sizes and update the jstat counters here.
 350     g1mm()->update_sizes();
 351   }
 352 
 353   _verifier->verify_region_sets_optional();
 354 
 355   return result;
 356 }
 357 
 358 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t min_size,
 359                                              size_t requested_size,
 360                                              size_t* actual_size) {
 361   assert_heap_not_locked_and_not_at_safepoint();
 362   assert(!is_humongous(requested_size), "we do not allow humongous TLABs");
 363 
 364   return attempt_allocation(min_size, requested_size, actual_size);
 365 }
 366 
 367 HeapWord*
 368 G1CollectedHeap::mem_allocate(size_t word_size,
 369                               bool*  gc_overhead_limit_was_exceeded) {
 370   assert_heap_not_locked_and_not_at_safepoint();
 371 
 372   if (is_humongous(word_size)) {
 373     return attempt_allocation_humongous(word_size);
 374   }
 375   size_t dummy = 0;
 376   return attempt_allocation(word_size, word_size, &dummy);
 377 }
 378 
 379 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size) {
 380   ResourceMark rm; // For retrieving the thread names in log messages.
 381 
 382   // Make sure you read the note in attempt_allocation_humongous().
 383 
 384   assert_heap_not_locked_and_not_at_safepoint();
 385   assert(!is_humongous(word_size), "attempt_allocation_slow() should not "
 386          "be called for humongous allocation requests");
 387 
 388   // We should only get here after the first-level allocation attempt
 389   // (attempt_allocation()) failed to allocate.
 390 
 391   // We will loop until a) we manage to successfully perform the
 392   // allocation or b) we successfully schedule a collection which
 393   // fails to perform the allocation. b) is the only case when we'll
 394   // return NULL.
 395   HeapWord* result = NULL;
 396   for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
 397     bool should_try_gc;
 398     bool preventive_collection_required = false;
 399     uint gc_count_before;
 400 
 401     {
 402       MutexLocker x(Heap_lock);
 403 
 404       // Now that we have the lock, we first retry the allocation in case another
 405       // thread changed the region while we were waiting to acquire the lock.
 406       size_t actual_size;
 407       result = _allocator->attempt_allocation(word_size, word_size, &actual_size);
 408       if (result != NULL) {
 409         return result;
 410       }
 411 
 412       preventive_collection_required = policy()->preventive_collection_required(1);
 413       if (!preventive_collection_required) {
 414         // We've already attempted a lock-free allocation above, so we don't want to
 415         // do it again. Let's jump straight to replacing the active region.
 416         result = _allocator->attempt_allocation_using_new_region(word_size);
 417         if (result != NULL) {
 418           return result;
 419         }
 420 
 421         // If the GCLocker is active and we are bound for a GC, try expanding young gen.
 422         // This is different to when only GCLocker::needs_gc() is set: try to avoid
 423         // waiting because the GCLocker is active to not wait too long.
 424         if (GCLocker::is_active_and_needs_gc() && policy()->can_expand_young_list()) {
 425           // No need for an ergo message here, can_expand_young_list() does this when
 426           // it returns true.
 427           result = _allocator->attempt_allocation_force(word_size);
 428           if (result != NULL) {
 429             return result;
 430           }
 431         }
 432       }
 433 
 434       // Only try a GC if the GCLocker does not signal the need for a GC. Wait until
 435       // the GCLocker initiated GC has been performed and then retry. This includes
 436       // the case when the GC Locker is not active but has not been performed.
 437       should_try_gc = !GCLocker::needs_gc();
 438       // Read the GC count while still holding the Heap_lock.
 439       gc_count_before = total_collections();
 440     }
 441 
 442     if (should_try_gc) {
 443       GCCause::Cause gc_cause = preventive_collection_required ? GCCause::_g1_preventive_collection
 444                                                               : GCCause::_g1_inc_collection_pause;
 445       bool succeeded;
 446       result = do_collection_pause(word_size, gc_count_before, &succeeded, gc_cause);
 447       if (result != NULL) {
 448         assert(succeeded, "only way to get back a non-NULL result");
 449         log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,
 450                              Thread::current()->name(), p2i(result));
 451         return result;
 452       }
 453 
 454       if (succeeded) {
 455         // We successfully scheduled a collection which failed to allocate. No
 456         // point in trying to allocate further. We'll just return NULL.
 457         log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "
 458                              SIZE_FORMAT " words", Thread::current()->name(), word_size);
 459         return NULL;
 460       }
 461       log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT " words",
 462                            Thread::current()->name(), word_size);
 463     } else {
 464       // Failed to schedule a collection.
 465       if (gclocker_retry_count > GCLockerRetryAllocationCount) {
 466         log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "
 467                                SIZE_FORMAT " words", Thread::current()->name(), word_size);
 468         return NULL;
 469       }
 470       log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());
 471       // The GCLocker is either active or the GCLocker initiated
 472       // GC has not yet been performed. Stall until it is and
 473       // then retry the allocation.
 474       GCLocker::stall_until_clear();
 475       gclocker_retry_count += 1;
 476     }
 477 
 478     // We can reach here if we were unsuccessful in scheduling a
 479     // collection (because another thread beat us to it) or if we were
 480     // stalled due to the GC locker. In either can we should retry the
 481     // allocation attempt in case another thread successfully
 482     // performed a collection and reclaimed enough space. We do the
 483     // first attempt (without holding the Heap_lock) here and the
 484     // follow-on attempt will be at the start of the next loop
 485     // iteration (after taking the Heap_lock).
 486     size_t dummy = 0;
 487     result = _allocator->attempt_allocation(word_size, word_size, &dummy);
 488     if (result != NULL) {
 489       return result;
 490     }
 491 
 492     // Give a warning if we seem to be looping forever.
 493     if ((QueuedAllocationWarningCount > 0) &&
 494         (try_count % QueuedAllocationWarningCount == 0)) {
 495       log_warning(gc, alloc)("%s:  Retried allocation %u times for " SIZE_FORMAT " words",
 496                              Thread::current()->name(), try_count, word_size);
 497     }
 498   }
 499 
 500   ShouldNotReachHere();
 501   return NULL;
 502 }
 503 
 504 void G1CollectedHeap::begin_archive_alloc_range(bool open) {
 505   assert_at_safepoint_on_vm_thread();
 506   if (_archive_allocator == NULL) {
 507     _archive_allocator = G1ArchiveAllocator::create_allocator(this, open);
 508   }
 509 }
 510 
 511 bool G1CollectedHeap::is_archive_alloc_too_large(size_t word_size) {
 512   // Allocations in archive regions cannot be of a size that would be considered
 513   // humongous even for a minimum-sized region, because G1 region sizes/boundaries
 514   // may be different at archive-restore time.
 515   return word_size >= humongous_threshold_for(HeapRegion::min_region_size_in_words());
 516 }
 517 
 518 HeapWord* G1CollectedHeap::archive_mem_allocate(size_t word_size) {
 519   assert_at_safepoint_on_vm_thread();
 520   assert(_archive_allocator != NULL, "_archive_allocator not initialized");
 521   if (is_archive_alloc_too_large(word_size)) {
 522     return NULL;
 523   }
 524   return _archive_allocator->archive_mem_allocate(word_size);
 525 }
 526 
 527 void G1CollectedHeap::end_archive_alloc_range(GrowableArray<MemRegion>* ranges,
 528                                               size_t end_alignment_in_bytes) {
 529   assert_at_safepoint_on_vm_thread();
 530   assert(_archive_allocator != NULL, "_archive_allocator not initialized");
 531 
 532   // Call complete_archive to do the real work, filling in the MemRegion
 533   // array with the archive regions.
 534   _archive_allocator->complete_archive(ranges, end_alignment_in_bytes);
 535   delete _archive_allocator;
 536   _archive_allocator = NULL;
 537 }
 538 
 539 bool G1CollectedHeap::check_archive_addresses(MemRegion* ranges, size_t count) {
 540   assert(ranges != NULL, "MemRegion array NULL");
 541   assert(count != 0, "No MemRegions provided");
 542   MemRegion reserved = _hrm.reserved();
 543   for (size_t i = 0; i < count; i++) {
 544     if (!reserved.contains(ranges[i].start()) || !reserved.contains(ranges[i].last())) {
 545       return false;
 546     }
 547   }
 548   return true;
 549 }
 550 
 551 bool G1CollectedHeap::alloc_archive_regions(MemRegion* ranges,
 552                                             size_t count,
 553                                             bool open) {
 554   assert(!is_init_completed(), "Expect to be called at JVM init time");
 555   assert(ranges != NULL, "MemRegion array NULL");
 556   assert(count != 0, "No MemRegions provided");
 557   MutexLocker x(Heap_lock);
 558 
 559   MemRegion reserved = _hrm.reserved();
 560   HeapWord* prev_last_addr = NULL;
 561   HeapRegion* prev_last_region = NULL;
 562 
 563   // Temporarily disable pretouching of heap pages. This interface is used
 564   // when mmap'ing archived heap data in, so pre-touching is wasted.
 565   FlagSetting fs(AlwaysPreTouch, false);
 566 
 567   // For each specified MemRegion range, allocate the corresponding G1
 568   // regions and mark them as archive regions. We expect the ranges
 569   // in ascending starting address order, without overlap.
 570   for (size_t i = 0; i < count; i++) {
 571     MemRegion curr_range = ranges[i];
 572     HeapWord* start_address = curr_range.start();
 573     size_t word_size = curr_range.word_size();
 574     HeapWord* last_address = curr_range.last();
 575     size_t commits = 0;
 576 
 577     guarantee(reserved.contains(start_address) && reserved.contains(last_address),
 578               "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
 579               p2i(start_address), p2i(last_address));
 580     guarantee(start_address > prev_last_addr,
 581               "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
 582               p2i(start_address), p2i(prev_last_addr));
 583     prev_last_addr = last_address;
 584 
 585     // Check for ranges that start in the same G1 region in which the previous
 586     // range ended, and adjust the start address so we don't try to allocate
 587     // the same region again. If the current range is entirely within that
 588     // region, skip it, just adjusting the recorded top.
 589     HeapRegion* start_region = _hrm.addr_to_region(start_address);
 590     if ((prev_last_region != NULL) && (start_region == prev_last_region)) {
 591       start_address = start_region->end();
 592       if (start_address > last_address) {
 593         increase_used(word_size * HeapWordSize);
 594         start_region->set_top(last_address + 1);
 595         continue;
 596       }
 597       start_region->set_top(start_address);
 598       curr_range = MemRegion(start_address, last_address + 1);
 599       start_region = _hrm.addr_to_region(start_address);
 600     }
 601 
 602     // Perform the actual region allocation, exiting if it fails.
 603     // Then note how much new space we have allocated.
 604     if (!_hrm.allocate_containing_regions(curr_range, &commits, workers())) {
 605       return false;
 606     }
 607     increase_used(word_size * HeapWordSize);
 608     if (commits != 0) {
 609       log_debug(gc, ergo, heap)("Attempt heap expansion (allocate archive regions). Total size: " SIZE_FORMAT "B",
 610                                 HeapRegion::GrainWords * HeapWordSize * commits);
 611 
 612     }
 613 
 614     // Mark each G1 region touched by the range as archive, add it to
 615     // the old set, and set top.
 616     HeapRegion* curr_region = _hrm.addr_to_region(start_address);
 617     HeapRegion* last_region = _hrm.addr_to_region(last_address);
 618     prev_last_region = last_region;
 619 
 620     while (curr_region != NULL) {
 621       assert(curr_region->is_empty() && !curr_region->is_pinned(),
 622              "Region already in use (index %u)", curr_region->hrm_index());
 623       if (open) {
 624         curr_region->set_open_archive();
 625       } else {
 626         curr_region->set_closed_archive();
 627       }
 628       _hr_printer.alloc(curr_region);
 629       _archive_set.add(curr_region);
 630       HeapWord* top;
 631       HeapRegion* next_region;
 632       if (curr_region != last_region) {
 633         top = curr_region->end();
 634         next_region = _hrm.next_region_in_heap(curr_region);
 635       } else {
 636         top = last_address + 1;
 637         next_region = NULL;
 638       }
 639       curr_region->set_top(top);
 640       curr_region = next_region;
 641     }
 642   }
 643   return true;
 644 }
 645 
 646 void G1CollectedHeap::fill_archive_regions(MemRegion* ranges, size_t count) {
 647   assert(!is_init_completed(), "Expect to be called at JVM init time");
 648   assert(ranges != NULL, "MemRegion array NULL");
 649   assert(count != 0, "No MemRegions provided");
 650   MemRegion reserved = _hrm.reserved();
 651   HeapWord *prev_last_addr = NULL;
 652   HeapRegion* prev_last_region = NULL;
 653 
 654   // For each MemRegion, create filler objects, if needed, in the G1 regions
 655   // that contain the address range. The address range actually within the
 656   // MemRegion will not be modified. That is assumed to have been initialized
 657   // elsewhere, probably via an mmap of archived heap data.
 658   MutexLocker x(Heap_lock);
 659   for (size_t i = 0; i < count; i++) {
 660     HeapWord* start_address = ranges[i].start();
 661     HeapWord* last_address = ranges[i].last();
 662 
 663     assert(reserved.contains(start_address) && reserved.contains(last_address),
 664            "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
 665            p2i(start_address), p2i(last_address));
 666     assert(start_address > prev_last_addr,
 667            "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
 668            p2i(start_address), p2i(prev_last_addr));
 669 
 670     HeapRegion* start_region = _hrm.addr_to_region(start_address);
 671     HeapRegion* last_region = _hrm.addr_to_region(last_address);
 672     HeapWord* bottom_address = start_region->bottom();
 673 
 674     // Check for a range beginning in the same region in which the
 675     // previous one ended.
 676     if (start_region == prev_last_region) {
 677       bottom_address = prev_last_addr + 1;
 678     }
 679 
 680     // Verify that the regions were all marked as archive regions by
 681     // alloc_archive_regions.
 682     HeapRegion* curr_region = start_region;
 683     while (curr_region != NULL) {
 684       guarantee(curr_region->is_archive(),
 685                 "Expected archive region at index %u", curr_region->hrm_index());
 686       if (curr_region != last_region) {
 687         curr_region = _hrm.next_region_in_heap(curr_region);
 688       } else {
 689         curr_region = NULL;
 690       }
 691     }
 692 
 693     prev_last_addr = last_address;
 694     prev_last_region = last_region;
 695 
 696     // Fill the memory below the allocated range with dummy object(s),
 697     // if the region bottom does not match the range start, or if the previous
 698     // range ended within the same G1 region, and there is a gap.
 699     assert(start_address >= bottom_address, "bottom address should not be greater than start address");
 700     if (start_address > bottom_address) {
 701       size_t fill_size = pointer_delta(start_address, bottom_address);
 702       G1CollectedHeap::fill_with_objects(bottom_address, fill_size);
 703       increase_used(fill_size * HeapWordSize);
 704     }
 705   }
 706 }
 707 
 708 inline HeapWord* G1CollectedHeap::attempt_allocation(size_t min_word_size,
 709                                                      size_t desired_word_size,
 710                                                      size_t* actual_word_size) {
 711   assert_heap_not_locked_and_not_at_safepoint();
 712   assert(!is_humongous(desired_word_size), "attempt_allocation() should not "
 713          "be called for humongous allocation requests");
 714 
 715   HeapWord* result = _allocator->attempt_allocation(min_word_size, desired_word_size, actual_word_size);
 716 
 717   if (result == NULL) {
 718     *actual_word_size = desired_word_size;
 719     result = attempt_allocation_slow(desired_word_size);
 720   }
 721 
 722   assert_heap_not_locked();
 723   if (result != NULL) {
 724     assert(*actual_word_size != 0, "Actual size must have been set here");
 725     dirty_young_block(result, *actual_word_size);
 726   } else {
 727     *actual_word_size = 0;
 728   }
 729 
 730   return result;
 731 }
 732 
 733 void G1CollectedHeap::populate_archive_regions_bot_part(MemRegion* ranges, size_t count) {
 734   assert(!is_init_completed(), "Expect to be called at JVM init time");
 735   assert(ranges != NULL, "MemRegion array NULL");
 736   assert(count != 0, "No MemRegions provided");
 737 
 738   HeapWord* st = ranges[0].start();
 739   HeapWord* last = ranges[count-1].last();
 740   HeapRegion* hr_st = _hrm.addr_to_region(st);
 741   HeapRegion* hr_last = _hrm.addr_to_region(last);
 742 
 743   HeapRegion* hr_curr = hr_st;
 744   while (hr_curr != NULL) {
 745     hr_curr->update_bot();
 746     if (hr_curr != hr_last) {
 747       hr_curr = _hrm.next_region_in_heap(hr_curr);
 748     } else {
 749       hr_curr = NULL;
 750     }
 751   }
 752 }
 753 
 754 void G1CollectedHeap::dealloc_archive_regions(MemRegion* ranges, size_t count) {
 755   assert(!is_init_completed(), "Expect to be called at JVM init time");
 756   assert(ranges != NULL, "MemRegion array NULL");
 757   assert(count != 0, "No MemRegions provided");
 758   MemRegion reserved = _hrm.reserved();
 759   HeapWord* prev_last_addr = NULL;
 760   HeapRegion* prev_last_region = NULL;
 761   size_t size_used = 0;
 762   uint shrink_count = 0;
 763 
 764   // For each Memregion, free the G1 regions that constitute it, and
 765   // notify mark-sweep that the range is no longer to be considered 'archive.'
 766   MutexLocker x(Heap_lock);
 767   for (size_t i = 0; i < count; i++) {
 768     HeapWord* start_address = ranges[i].start();
 769     HeapWord* last_address = ranges[i].last();
 770 
 771     assert(reserved.contains(start_address) && reserved.contains(last_address),
 772            "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]",
 773            p2i(start_address), p2i(last_address));
 774     assert(start_address > prev_last_addr,
 775            "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT ,
 776            p2i(start_address), p2i(prev_last_addr));
 777     size_used += ranges[i].byte_size();
 778     prev_last_addr = last_address;
 779 
 780     HeapRegion* start_region = _hrm.addr_to_region(start_address);
 781     HeapRegion* last_region = _hrm.addr_to_region(last_address);
 782 
 783     // Check for ranges that start in the same G1 region in which the previous
 784     // range ended, and adjust the start address so we don't try to free
 785     // the same region again. If the current range is entirely within that
 786     // region, skip it.
 787     if (start_region == prev_last_region) {
 788       start_address = start_region->end();
 789       if (start_address > last_address) {
 790         continue;
 791       }
 792       start_region = _hrm.addr_to_region(start_address);
 793     }
 794     prev_last_region = last_region;
 795 
 796     // After verifying that each region was marked as an archive region by
 797     // alloc_archive_regions, set it free and empty and uncommit it.
 798     HeapRegion* curr_region = start_region;
 799     while (curr_region != NULL) {
 800       guarantee(curr_region->is_archive(),
 801                 "Expected archive region at index %u", curr_region->hrm_index());
 802       uint curr_index = curr_region->hrm_index();
 803       _archive_set.remove(curr_region);
 804       curr_region->set_free();
 805       curr_region->set_top(curr_region->bottom());
 806       if (curr_region != last_region) {
 807         curr_region = _hrm.next_region_in_heap(curr_region);
 808       } else {
 809         curr_region = NULL;
 810       }
 811 
 812       _hrm.shrink_at(curr_index, 1);
 813       shrink_count++;
 814     }
 815   }
 816 
 817   if (shrink_count != 0) {
 818     log_debug(gc, ergo, heap)("Attempt heap shrinking (archive regions). Total size: " SIZE_FORMAT "B",
 819                               HeapRegion::GrainWords * HeapWordSize * shrink_count);
 820     // Explicit uncommit.
 821     uncommit_regions(shrink_count);
 822   }
 823   decrease_used(size_used);
 824 }
 825 
 826 HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size) {
 827   ResourceMark rm; // For retrieving the thread names in log messages.
 828 
 829   // The structure of this method has a lot of similarities to
 830   // attempt_allocation_slow(). The reason these two were not merged
 831   // into a single one is that such a method would require several "if
 832   // allocation is not humongous do this, otherwise do that"
 833   // conditional paths which would obscure its flow. In fact, an early
 834   // version of this code did use a unified method which was harder to
 835   // follow and, as a result, it had subtle bugs that were hard to
 836   // track down. So keeping these two methods separate allows each to
 837   // be more readable. It will be good to keep these two in sync as
 838   // much as possible.
 839 
 840   assert_heap_not_locked_and_not_at_safepoint();
 841   assert(is_humongous(word_size), "attempt_allocation_humongous() "
 842          "should only be called for humongous allocations");
 843 
 844   // Humongous objects can exhaust the heap quickly, so we should check if we
 845   // need to start a marking cycle at each humongous object allocation. We do
 846   // the check before we do the actual allocation. The reason for doing it
 847   // before the allocation is that we avoid having to keep track of the newly
 848   // allocated memory while we do a GC.
 849   if (policy()->need_to_start_conc_mark("concurrent humongous allocation",
 850                                         word_size)) {
 851     collect(GCCause::_g1_humongous_allocation);
 852   }
 853 
 854   // We will loop until a) we manage to successfully perform the
 855   // allocation or b) we successfully schedule a collection which
 856   // fails to perform the allocation. b) is the only case when we'll
 857   // return NULL.
 858   HeapWord* result = NULL;
 859   for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
 860     bool should_try_gc;
 861     bool preventive_collection_required = false;
 862     uint gc_count_before;
 863 
 864 
 865     {
 866       MutexLocker x(Heap_lock);
 867 
 868       size_t size_in_regions = humongous_obj_size_in_regions(word_size);
 869       preventive_collection_required = policy()->preventive_collection_required((uint)size_in_regions);
 870       if (!preventive_collection_required) {
 871         // Given that humongous objects are not allocated in young
 872         // regions, we'll first try to do the allocation without doing a
 873         // collection hoping that there's enough space in the heap.
 874         result = humongous_obj_allocate(word_size);
 875         if (result != NULL) {
 876           policy()->old_gen_alloc_tracker()->
 877             add_allocated_humongous_bytes_since_last_gc(size_in_regions * HeapRegion::GrainBytes);
 878           return result;
 879         }
 880       }
 881 
 882       // Only try a GC if the GCLocker does not signal the need for a GC. Wait until
 883       // the GCLocker initiated GC has been performed and then retry. This includes
 884       // the case when the GC Locker is not active but has not been performed.
 885       should_try_gc = !GCLocker::needs_gc();
 886       // Read the GC count while still holding the Heap_lock.
 887       gc_count_before = total_collections();
 888     }
 889 
 890     if (should_try_gc) {
 891       GCCause::Cause gc_cause = preventive_collection_required ? GCCause::_g1_preventive_collection
 892                                                               : GCCause::_g1_humongous_allocation;
 893       bool succeeded;
 894       result = do_collection_pause(word_size, gc_count_before, &succeeded, gc_cause);
 895       if (result != NULL) {
 896         assert(succeeded, "only way to get back a non-NULL result");
 897         log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT,
 898                              Thread::current()->name(), p2i(result));
 899         size_t size_in_regions = humongous_obj_size_in_regions(word_size);
 900         policy()->old_gen_alloc_tracker()->
 901           record_collection_pause_humongous_allocation(size_in_regions * HeapRegion::GrainBytes);
 902         return result;
 903       }
 904 
 905       if (succeeded) {
 906         // We successfully scheduled a collection which failed to allocate. No
 907         // point in trying to allocate further. We'll just return NULL.
 908         log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate "
 909                              SIZE_FORMAT " words", Thread::current()->name(), word_size);
 910         return NULL;
 911       }
 912       log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT "",
 913                            Thread::current()->name(), word_size);
 914     } else {
 915       // Failed to schedule a collection.
 916       if (gclocker_retry_count > GCLockerRetryAllocationCount) {
 917         log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating "
 918                                SIZE_FORMAT " words", Thread::current()->name(), word_size);
 919         return NULL;
 920       }
 921       log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name());
 922       // The GCLocker is either active or the GCLocker initiated
 923       // GC has not yet been performed. Stall until it is and
 924       // then retry the allocation.
 925       GCLocker::stall_until_clear();
 926       gclocker_retry_count += 1;
 927     }
 928 
 929 
 930     // We can reach here if we were unsuccessful in scheduling a
 931     // collection (because another thread beat us to it) or if we were
 932     // stalled due to the GC locker. In either can we should retry the
 933     // allocation attempt in case another thread successfully
 934     // performed a collection and reclaimed enough space.
 935     // Humongous object allocation always needs a lock, so we wait for the retry
 936     // in the next iteration of the loop, unlike for the regular iteration case.
 937     // Give a warning if we seem to be looping forever.
 938 
 939     if ((QueuedAllocationWarningCount > 0) &&
 940         (try_count % QueuedAllocationWarningCount == 0)) {
 941       log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words",
 942                              Thread::current()->name(), try_count, word_size);
 943     }
 944   }
 945 
 946   ShouldNotReachHere();
 947   return NULL;
 948 }
 949 
 950 HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size,
 951                                                            bool expect_null_mutator_alloc_region) {
 952   assert_at_safepoint_on_vm_thread();
 953   assert(!_allocator->has_mutator_alloc_region() || !expect_null_mutator_alloc_region,
 954          "the current alloc region was unexpectedly found to be non-NULL");
 955 
 956   if (!is_humongous(word_size)) {
 957     return _allocator->attempt_allocation_locked(word_size);
 958   } else {
 959     HeapWord* result = humongous_obj_allocate(word_size);
 960     if (result != NULL && policy()->need_to_start_conc_mark("STW humongous allocation")) {
 961       collector_state()->set_initiate_conc_mark_if_possible(true);
 962     }
 963     return result;
 964   }
 965 
 966   ShouldNotReachHere();
 967 }
 968 
 969 class PostCompactionPrinterClosure: public HeapRegionClosure {
 970 private:
 971   G1HRPrinter* _hr_printer;
 972 public:
 973   bool do_heap_region(HeapRegion* hr) {
 974     assert(!hr->is_young(), "not expecting to find young regions");
 975     _hr_printer->post_compaction(hr);
 976     return false;
 977   }
 978 
 979   PostCompactionPrinterClosure(G1HRPrinter* hr_printer)
 980     : _hr_printer(hr_printer) { }
 981 };
 982 
 983 void G1CollectedHeap::print_hrm_post_compaction() {
 984   if (_hr_printer.is_active()) {
 985     PostCompactionPrinterClosure cl(hr_printer());
 986     heap_region_iterate(&cl);
 987   }
 988 }
 989 
 990 void G1CollectedHeap::abort_concurrent_cycle() {
 991   // If we start the compaction before the CM threads finish
 992   // scanning the root regions we might trip them over as we'll
 993   // be moving objects / updating references. So let's wait until
 994   // they are done. By telling them to abort, they should complete
 995   // early.
 996   _cm->root_regions()->abort();
 997   _cm->root_regions()->wait_until_scan_finished();
 998 
 999   // Disable discovery and empty the discovered lists
1000   // for the CM ref processor.
1001   _ref_processor_cm->disable_discovery();
1002   _ref_processor_cm->abandon_partial_discovery();
1003   _ref_processor_cm->verify_no_references_recorded();
1004 
1005   // Abandon current iterations of concurrent marking and concurrent
1006   // refinement, if any are in progress.
1007   concurrent_mark()->concurrent_cycle_abort();
1008 }
1009 
1010 void G1CollectedHeap::prepare_heap_for_full_collection() {
1011   // Make sure we'll choose a new allocation region afterwards.
1012   _allocator->release_mutator_alloc_regions();
1013   _allocator->abandon_gc_alloc_regions();
1014 
1015   // We may have added regions to the current incremental collection
1016   // set between the last GC or pause and now. We need to clear the
1017   // incremental collection set and then start rebuilding it afresh
1018   // after this full GC.
1019   abandon_collection_set(collection_set());
1020 
1021   _hrm.remove_all_free_regions();
1022 }
1023 
1024 void G1CollectedHeap::verify_before_full_collection(bool explicit_gc) {
1025   assert(!GCCause::is_user_requested_gc(gc_cause()) || explicit_gc, "invariant");
1026   assert_used_and_recalculate_used_equal(this);
1027   _verifier->verify_region_sets_optional();
1028   _verifier->verify_before_gc(G1HeapVerifier::G1VerifyFull);
1029   _verifier->check_bitmaps("Full GC Start");
1030 }
1031 
1032 void G1CollectedHeap::prepare_heap_for_mutators() {
1033   // Delete metaspaces for unloaded class loaders and clean up loader_data graph
1034   ClassLoaderDataGraph::purge(/*at_safepoint*/true);
1035   DEBUG_ONLY(MetaspaceUtils::verify();)
1036 
1037   // Prepare heap for normal collections.
1038   assert(num_free_regions() == 0, "we should not have added any free regions");
1039   rebuild_region_sets(false /* free_list_only */);
1040   abort_refinement();
1041   resize_heap_if_necessary();
1042   uncommit_regions_if_necessary();
1043 
1044   // Rebuild the strong code root lists for each region
1045   rebuild_strong_code_roots();
1046 
1047   // Purge code root memory
1048   purge_code_root_memory();
1049 
1050   // Start a new incremental collection set for the next pause
1051   start_new_collection_set();
1052 
1053   _allocator->init_mutator_alloc_regions();
1054 
1055   // Post collection state updates.
1056   MetaspaceGC::compute_new_size();
1057 }
1058 
1059 void G1CollectedHeap::abort_refinement() {
1060   if (_hot_card_cache->use_cache()) {
1061     _hot_card_cache->reset_hot_cache();
1062   }
1063 
1064   // Discard all remembered set updates and reset refinement statistics.
1065   G1BarrierSet::dirty_card_queue_set().abandon_logs();
1066   assert(G1BarrierSet::dirty_card_queue_set().num_cards() == 0,
1067          "DCQS should be empty");
1068   concurrent_refine()->get_and_reset_refinement_stats();
1069 }
1070 
1071 void G1CollectedHeap::verify_after_full_collection() {
1072   _hrm.verify_optional();
1073   _verifier->verify_region_sets_optional();
1074   _verifier->verify_after_gc(G1HeapVerifier::G1VerifyFull);
1075 
1076   // This call implicitly verifies that the next bitmap is clear after Full GC.
1077   _verifier->check_bitmaps("Full GC End");
1078 
1079   // At this point there should be no regions in the
1080   // entire heap tagged as young.
1081   assert(check_young_list_empty(), "young list should be empty at this point");
1082 
1083   // Note: since we've just done a full GC, concurrent
1084   // marking is no longer active. Therefore we need not
1085   // re-enable reference discovery for the CM ref processor.
1086   // That will be done at the start of the next marking cycle.
1087   // We also know that the STW processor should no longer
1088   // discover any new references.
1089   assert(!_ref_processor_stw->discovery_enabled(), "Postcondition");
1090   assert(!_ref_processor_cm->discovery_enabled(), "Postcondition");
1091   _ref_processor_stw->verify_no_references_recorded();
1092   _ref_processor_cm->verify_no_references_recorded();
1093 }
1094 
1095 void G1CollectedHeap::print_heap_after_full_collection(G1HeapTransition* heap_transition) {
1096   // Post collection logging.
1097   // We should do this after we potentially resize the heap so
1098   // that all the COMMIT / UNCOMMIT events are generated before
1099   // the compaction events.
1100   print_hrm_post_compaction();
1101   heap_transition->print();
1102   print_heap_after_gc();
1103   print_heap_regions();
1104 }
1105 
1106 bool G1CollectedHeap::do_full_collection(bool explicit_gc,
1107                                          bool clear_all_soft_refs,
1108                                          bool do_maximum_compaction) {
1109   assert_at_safepoint_on_vm_thread();
1110 
1111   if (GCLocker::check_active_before_gc()) {
1112     // Full GC was not completed.
1113     return false;
1114   }
1115 
1116   const bool do_clear_all_soft_refs = clear_all_soft_refs ||
1117       soft_ref_policy()->should_clear_all_soft_refs();
1118 
1119   G1FullCollector collector(this, explicit_gc, do_clear_all_soft_refs, do_maximum_compaction);
1120   GCTraceTime(Info, gc) tm("Pause Full", NULL, gc_cause(), true);
1121 
1122   collector.prepare_collection();
1123   collector.collect();
1124   collector.complete_collection();
1125 
1126   // Full collection was successfully completed.
1127   return true;
1128 }
1129 
1130 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) {
1131   // Currently, there is no facility in the do_full_collection(bool) API to notify
1132   // the caller that the collection did not succeed (e.g., because it was locked
1133   // out by the GC locker). So, right now, we'll ignore the return value.
1134   // When clear_all_soft_refs is set we want to do a maximum compaction
1135   // not leaving any dead wood.
1136   bool do_maximum_compaction = clear_all_soft_refs;
1137   bool dummy = do_full_collection(true,                /* explicit_gc */
1138                                   clear_all_soft_refs,
1139                                   do_maximum_compaction);
1140 }
1141 
1142 bool G1CollectedHeap::upgrade_to_full_collection() {
1143   GCCauseSetter compaction(this, GCCause::_g1_compaction_pause);
1144   log_info(gc, ergo)("Attempting full compaction clearing soft references");
1145   bool success = do_full_collection(false /* explicit gc */,
1146                                     true  /* clear_all_soft_refs */,
1147                                     false /* do_maximum_compaction */);
1148   // do_full_collection only fails if blocked by GC locker and that can't
1149   // be the case here since we only call this when already completed one gc.
1150   assert(success, "invariant");
1151   return success;
1152 }
1153 
1154 void G1CollectedHeap::resize_heap_if_necessary() {
1155   assert_at_safepoint_on_vm_thread();
1156 
1157   bool should_expand;
1158   size_t resize_amount = _heap_sizing_policy->full_collection_resize_amount(should_expand);
1159 
1160   if (resize_amount == 0) {
1161     return;
1162   } else if (should_expand) {
1163     expand(resize_amount, _workers);
1164   } else {
1165     shrink(resize_amount);
1166   }
1167 }
1168 
1169 HeapWord* G1CollectedHeap::satisfy_failed_allocation_helper(size_t word_size,
1170                                                             bool do_gc,
1171                                                             bool maximum_compaction,
1172                                                             bool expect_null_mutator_alloc_region,
1173                                                             bool* gc_succeeded) {
1174   *gc_succeeded = true;
1175   // Let's attempt the allocation first.
1176   HeapWord* result =
1177     attempt_allocation_at_safepoint(word_size,
1178                                     expect_null_mutator_alloc_region);
1179   if (result != NULL) {
1180     return result;
1181   }
1182 
1183   // In a G1 heap, we're supposed to keep allocation from failing by
1184   // incremental pauses.  Therefore, at least for now, we'll favor
1185   // expansion over collection.  (This might change in the future if we can
1186   // do something smarter than full collection to satisfy a failed alloc.)
1187   result = expand_and_allocate(word_size);
1188   if (result != NULL) {
1189     return result;
1190   }
1191 
1192   if (do_gc) {
1193     GCCauseSetter compaction(this, GCCause::_g1_compaction_pause);
1194     // Expansion didn't work, we'll try to do a Full GC.
1195     // If maximum_compaction is set we clear all soft references and don't
1196     // allow any dead wood to be left on the heap.
1197     if (maximum_compaction) {
1198       log_info(gc, ergo)("Attempting maximum full compaction clearing soft references");
1199     } else {
1200       log_info(gc, ergo)("Attempting full compaction");
1201     }
1202     *gc_succeeded = do_full_collection(false, /* explicit_gc */
1203                                        maximum_compaction /* clear_all_soft_refs */ ,
1204                                        maximum_compaction /* do_maximum_compaction */);
1205   }
1206 
1207   return NULL;
1208 }
1209 
1210 HeapWord* G1CollectedHeap::satisfy_failed_allocation(size_t word_size,
1211                                                      bool* succeeded) {
1212   assert_at_safepoint_on_vm_thread();
1213 
1214   // Attempts to allocate followed by Full GC.
1215   HeapWord* result =
1216     satisfy_failed_allocation_helper(word_size,
1217                                      true,  /* do_gc */
1218                                      false, /* maximum_collection */
1219                                      false, /* expect_null_mutator_alloc_region */
1220                                      succeeded);
1221 
1222   if (result != NULL || !*succeeded) {
1223     return result;
1224   }
1225 
1226   // Attempts to allocate followed by Full GC that will collect all soft references.
1227   result = satisfy_failed_allocation_helper(word_size,
1228                                             true, /* do_gc */
1229                                             true, /* maximum_collection */
1230                                             true, /* expect_null_mutator_alloc_region */
1231                                             succeeded);
1232 
1233   if (result != NULL || !*succeeded) {
1234     return result;
1235   }
1236 
1237   // Attempts to allocate, no GC
1238   result = satisfy_failed_allocation_helper(word_size,
1239                                             false, /* do_gc */
1240                                             false, /* maximum_collection */
1241                                             true,  /* expect_null_mutator_alloc_region */
1242                                             succeeded);
1243 
1244   if (result != NULL) {
1245     return result;
1246   }
1247 
1248   assert(!soft_ref_policy()->should_clear_all_soft_refs(),
1249          "Flag should have been handled and cleared prior to this point");
1250 
1251   // What else?  We might try synchronous finalization later.  If the total
1252   // space available is large enough for the allocation, then a more
1253   // complete compaction phase than we've tried so far might be
1254   // appropriate.
1255   return NULL;
1256 }
1257 
1258 // Attempting to expand the heap sufficiently
1259 // to support an allocation of the given "word_size".  If
1260 // successful, perform the allocation and return the address of the
1261 // allocated block, or else "NULL".
1262 
1263 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) {
1264   assert_at_safepoint_on_vm_thread();
1265 
1266   _verifier->verify_region_sets_optional();
1267 
1268   size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes);
1269   log_debug(gc, ergo, heap)("Attempt heap expansion (allocation request failed). Allocation request: " SIZE_FORMAT "B",
1270                             word_size * HeapWordSize);
1271 
1272 
1273   if (expand(expand_bytes, _workers)) {
1274     _hrm.verify_optional();
1275     _verifier->verify_region_sets_optional();
1276     return attempt_allocation_at_safepoint(word_size,
1277                                            false /* expect_null_mutator_alloc_region */);
1278   }
1279   return NULL;
1280 }
1281 
1282 bool G1CollectedHeap::expand(size_t expand_bytes, WorkGang* pretouch_workers, double* expand_time_ms) {
1283   size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes);
1284   aligned_expand_bytes = align_up(aligned_expand_bytes,
1285                                        HeapRegion::GrainBytes);
1286 
1287   log_debug(gc, ergo, heap)("Expand the heap. requested expansion amount: " SIZE_FORMAT "B expansion amount: " SIZE_FORMAT "B",
1288                             expand_bytes, aligned_expand_bytes);
1289 
1290   if (is_maximal_no_gc()) {
1291     log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)");
1292     return false;
1293   }
1294 
1295   double expand_heap_start_time_sec = os::elapsedTime();
1296   uint regions_to_expand = (uint)(aligned_expand_bytes / HeapRegion::GrainBytes);
1297   assert(regions_to_expand > 0, "Must expand by at least one region");
1298 
1299   uint expanded_by = _hrm.expand_by(regions_to_expand, pretouch_workers);
1300   if (expand_time_ms != NULL) {
1301     *expand_time_ms = (os::elapsedTime() - expand_heap_start_time_sec) * MILLIUNITS;
1302   }
1303 
1304   if (expanded_by > 0) {
1305     size_t actual_expand_bytes = expanded_by * HeapRegion::GrainBytes;
1306     assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition");
1307     policy()->record_new_heap_size(num_regions());
1308   } else {
1309     log_debug(gc, ergo, heap)("Did not expand the heap (heap expansion operation failed)");
1310 
1311     // The expansion of the virtual storage space was unsuccessful.
1312     // Let's see if it was because we ran out of swap.
1313     if (G1ExitOnExpansionFailure &&
1314         _hrm.available() >= regions_to_expand) {
1315       // We had head room...
1316       vm_exit_out_of_memory(aligned_expand_bytes, OOM_MMAP_ERROR, "G1 heap expansion");
1317     }
1318   }
1319   return regions_to_expand > 0;
1320 }
1321 
1322 bool G1CollectedHeap::expand_single_region(uint node_index) {
1323   uint expanded_by = _hrm.expand_on_preferred_node(node_index);
1324 
1325   if (expanded_by == 0) {
1326     assert(is_maximal_no_gc(), "Should be no regions left, available: %u", _hrm.available());
1327     log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)");
1328     return false;
1329   }
1330 
1331   policy()->record_new_heap_size(num_regions());
1332   return true;
1333 }
1334 
1335 void G1CollectedHeap::shrink_helper(size_t shrink_bytes) {
1336   size_t aligned_shrink_bytes =
1337     ReservedSpace::page_align_size_down(shrink_bytes);
1338   aligned_shrink_bytes = align_down(aligned_shrink_bytes,
1339                                          HeapRegion::GrainBytes);
1340   uint num_regions_to_remove = (uint)(shrink_bytes / HeapRegion::GrainBytes);
1341 
1342   uint num_regions_removed = _hrm.shrink_by(num_regions_to_remove);
1343   size_t shrunk_bytes = num_regions_removed * HeapRegion::GrainBytes;
1344 
1345   log_debug(gc, ergo, heap)("Shrink the heap. requested shrinking amount: " SIZE_FORMAT "B aligned shrinking amount: " SIZE_FORMAT "B attempted shrinking amount: " SIZE_FORMAT "B",
1346                             shrink_bytes, aligned_shrink_bytes, shrunk_bytes);
1347   if (num_regions_removed > 0) {
1348     log_debug(gc, heap)("Uncommittable regions after shrink: %u", num_regions_removed);
1349     policy()->record_new_heap_size(num_regions());
1350   } else {
1351     log_debug(gc, ergo, heap)("Did not expand the heap (heap shrinking operation failed)");
1352   }
1353 }
1354 
1355 void G1CollectedHeap::shrink(size_t shrink_bytes) {
1356   _verifier->verify_region_sets_optional();
1357 
1358   // We should only reach here at the end of a Full GC or during Remark which
1359   // means we should not not be holding to any GC alloc regions. The method
1360   // below will make sure of that and do any remaining clean up.
1361   _allocator->abandon_gc_alloc_regions();
1362 
1363   // Instead of tearing down / rebuilding the free lists here, we
1364   // could instead use the remove_all_pending() method on free_list to
1365   // remove only the ones that we need to remove.
1366   _hrm.remove_all_free_regions();
1367   shrink_helper(shrink_bytes);
1368   rebuild_region_sets(true /* free_list_only */);
1369 
1370   _hrm.verify_optional();
1371   _verifier->verify_region_sets_optional();
1372 }
1373 
1374 class OldRegionSetChecker : public HeapRegionSetChecker {
1375 public:
1376   void check_mt_safety() {
1377     // Master Old Set MT safety protocol:
1378     // (a) If we're at a safepoint, operations on the master old set
1379     // should be invoked:
1380     // - by the VM thread (which will serialize them), or
1381     // - by the GC workers while holding the FreeList_lock, if we're
1382     //   at a safepoint for an evacuation pause (this lock is taken
1383     //   anyway when an GC alloc region is retired so that a new one
1384     //   is allocated from the free list), or
1385     // - by the GC workers while holding the OldSets_lock, if we're at a
1386     //   safepoint for a cleanup pause.
1387     // (b) If we're not at a safepoint, operations on the master old set
1388     // should be invoked while holding the Heap_lock.
1389 
1390     if (SafepointSynchronize::is_at_safepoint()) {
1391       guarantee(Thread::current()->is_VM_thread() ||
1392                 FreeList_lock->owned_by_self() || OldSets_lock->owned_by_self(),
1393                 "master old set MT safety protocol at a safepoint");
1394     } else {
1395       guarantee(Heap_lock->owned_by_self(), "master old set MT safety protocol outside a safepoint");
1396     }
1397   }
1398   bool is_correct_type(HeapRegion* hr) { return hr->is_old(); }
1399   const char* get_description() { return "Old Regions"; }
1400 };
1401 
1402 class ArchiveRegionSetChecker : public HeapRegionSetChecker {
1403 public:
1404   void check_mt_safety() {
1405     guarantee(!Universe::is_fully_initialized() || SafepointSynchronize::is_at_safepoint(),
1406               "May only change archive regions during initialization or safepoint.");
1407   }
1408   bool is_correct_type(HeapRegion* hr) { return hr->is_archive(); }
1409   const char* get_description() { return "Archive Regions"; }
1410 };
1411 
1412 class HumongousRegionSetChecker : public HeapRegionSetChecker {
1413 public:
1414   void check_mt_safety() {
1415     // Humongous Set MT safety protocol:
1416     // (a) If we're at a safepoint, operations on the master humongous
1417     // set should be invoked by either the VM thread (which will
1418     // serialize them) or by the GC workers while holding the
1419     // OldSets_lock.
1420     // (b) If we're not at a safepoint, operations on the master
1421     // humongous set should be invoked while holding the Heap_lock.
1422 
1423     if (SafepointSynchronize::is_at_safepoint()) {
1424       guarantee(Thread::current()->is_VM_thread() ||
1425                 OldSets_lock->owned_by_self(),
1426                 "master humongous set MT safety protocol at a safepoint");
1427     } else {
1428       guarantee(Heap_lock->owned_by_self(),
1429                 "master humongous set MT safety protocol outside a safepoint");
1430     }
1431   }
1432   bool is_correct_type(HeapRegion* hr) { return hr->is_humongous(); }
1433   const char* get_description() { return "Humongous Regions"; }
1434 };
1435 
1436 G1CollectedHeap::G1CollectedHeap() :
1437   CollectedHeap(),
1438   _service_thread(NULL),
1439   _periodic_gc_task(NULL),
1440   _workers(NULL),
1441   _card_table(NULL),
1442   _collection_pause_end(Ticks::now()),
1443   _soft_ref_policy(),
1444   _old_set("Old Region Set", new OldRegionSetChecker()),
1445   _archive_set("Archive Region Set", new ArchiveRegionSetChecker()),
1446   _humongous_set("Humongous Region Set", new HumongousRegionSetChecker()),
1447   _bot(NULL),
1448   _listener(),
1449   _numa(G1NUMA::create()),
1450   _hrm(),
1451   _allocator(NULL),
1452   _verifier(NULL),
1453   _summary_bytes_used(0),
1454   _bytes_used_during_gc(0),
1455   _archive_allocator(NULL),
1456   _survivor_evac_stats("Young", YoungPLABSize, PLABWeight),
1457   _old_evac_stats("Old", OldPLABSize, PLABWeight),
1458   _expand_heap_after_alloc_failure(true),
1459   _g1mm(NULL),
1460   _humongous_reclaim_candidates(),
1461   _num_humongous_objects(0),
1462   _num_humongous_reclaim_candidates(0),
1463   _hr_printer(),
1464   _collector_state(),
1465   _old_marking_cycles_started(0),
1466   _old_marking_cycles_completed(0),
1467   _eden(),
1468   _survivor(),
1469   _gc_timer_stw(new (ResourceObj::C_HEAP, mtGC) STWGCTimer()),
1470   _gc_tracer_stw(new (ResourceObj::C_HEAP, mtGC) G1NewTracer()),
1471   _policy(new G1Policy(_gc_timer_stw)),
1472   _heap_sizing_policy(NULL),
1473   _collection_set(this, _policy),
1474   _hot_card_cache(NULL),
1475   _rem_set(NULL),
1476   _cm(NULL),
1477   _cm_thread(NULL),
1478   _cr(NULL),
1479   _task_queues(NULL),
1480   _num_regions_failed_evacuation(0),
1481   _regions_failed_evacuation(NULL),
1482   _evacuation_failed_info_array(NULL),
1483   _preserved_marks_set(true /* in_c_heap */),
1484 #ifndef PRODUCT
1485   _evacuation_failure_alot_for_current_gc(false),
1486   _evacuation_failure_alot_gc_number(0),
1487   _evacuation_failure_alot_count(0),
1488 #endif
1489   _ref_processor_stw(NULL),
1490   _is_alive_closure_stw(this),
1491   _is_subject_to_discovery_stw(this),
1492   _ref_processor_cm(NULL),
1493   _is_alive_closure_cm(this),
1494   _is_subject_to_discovery_cm(this),
1495   _region_attr() {
1496 
1497   _verifier = new G1HeapVerifier(this);
1498 
1499   _allocator = new G1Allocator(this);
1500 
1501   _heap_sizing_policy = G1HeapSizingPolicy::create(this, _policy->analytics());
1502 
1503   _humongous_object_threshold_in_words = humongous_threshold_for(HeapRegion::GrainWords);
1504 
1505   // Override the default _filler_array_max_size so that no humongous filler
1506   // objects are created.
1507   _filler_array_max_size = _humongous_object_threshold_in_words;
1508 
1509   uint n_queues = ParallelGCThreads;
1510   _task_queues = new G1ScannerTasksQueueSet(n_queues);
1511 
1512   _evacuation_failed_info_array = NEW_C_HEAP_ARRAY(EvacuationFailedInfo, n_queues, mtGC);
1513 
1514   for (uint i = 0; i < n_queues; i++) {
1515     G1ScannerTasksQueue* q = new G1ScannerTasksQueue();
1516     q->initialize();
1517     _task_queues->register_queue(i, q);
1518     ::new (&_evacuation_failed_info_array[i]) EvacuationFailedInfo();
1519   }
1520 
1521   // Initialize the G1EvacuationFailureALot counters and flags.
1522   NOT_PRODUCT(reset_evacuation_should_fail();)
1523   _gc_tracer_stw->initialize();
1524 
1525   guarantee(_task_queues != NULL, "task_queues allocation failure.");
1526 }
1527 
1528 G1RegionToSpaceMapper* G1CollectedHeap::create_aux_memory_mapper(const char* description,
1529                                                                  size_t size,
1530                                                                  size_t translation_factor) {
1531   size_t preferred_page_size = os::page_size_for_region_unaligned(size, 1);
1532   // Allocate a new reserved space, preferring to use large pages.
1533   ReservedSpace rs(size, preferred_page_size);
1534   size_t page_size = rs.page_size();
1535   G1RegionToSpaceMapper* result  =
1536     G1RegionToSpaceMapper::create_mapper(rs,
1537                                          size,
1538                                          page_size,
1539                                          HeapRegion::GrainBytes,
1540                                          translation_factor,
1541                                          mtGC);
1542 
1543   os::trace_page_sizes_for_requested_size(description,
1544                                           size,
1545                                           page_size,
1546                                           preferred_page_size,
1547                                           rs.base(),
1548                                           rs.size());
1549 
1550   return result;
1551 }
1552 
1553 jint G1CollectedHeap::initialize_concurrent_refinement() {
1554   jint ecode = JNI_OK;
1555   _cr = G1ConcurrentRefine::create(&ecode);
1556   return ecode;
1557 }
1558 
1559 jint G1CollectedHeap::initialize_service_thread() {
1560   _service_thread = new G1ServiceThread();
1561   if (_service_thread->osthread() == NULL) {
1562     vm_shutdown_during_initialization("Could not create G1ServiceThread");
1563     return JNI_ENOMEM;
1564   }
1565   return JNI_OK;
1566 }
1567 
1568 jint G1CollectedHeap::initialize() {
1569 
1570   // Necessary to satisfy locking discipline assertions.
1571 
1572   MutexLocker x(Heap_lock);
1573 
1574   // While there are no constraints in the GC code that HeapWordSize
1575   // be any particular value, there are multiple other areas in the
1576   // system which believe this to be true (e.g. oop->object_size in some
1577   // cases incorrectly returns the size in wordSize units rather than
1578   // HeapWordSize).
1579   guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");
1580 
1581   size_t init_byte_size = InitialHeapSize;
1582   size_t reserved_byte_size = G1Arguments::heap_reserved_size_bytes();
1583 
1584   // Ensure that the sizes are properly aligned.
1585   Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap");
1586   Universe::check_alignment(reserved_byte_size, HeapRegion::GrainBytes, "g1 heap");
1587   Universe::check_alignment(reserved_byte_size, HeapAlignment, "g1 heap");
1588 
1589   // Reserve the maximum.
1590 
1591   // When compressed oops are enabled, the preferred heap base
1592   // is calculated by subtracting the requested size from the
1593   // 32Gb boundary and using the result as the base address for
1594   // heap reservation. If the requested size is not aligned to
1595   // HeapRegion::GrainBytes (i.e. the alignment that is passed
1596   // into the ReservedHeapSpace constructor) then the actual
1597   // base of the reserved heap may end up differing from the
1598   // address that was requested (i.e. the preferred heap base).
1599   // If this happens then we could end up using a non-optimal
1600   // compressed oops mode.
1601 
1602   ReservedHeapSpace heap_rs = Universe::reserve_heap(reserved_byte_size,
1603                                                      HeapAlignment);
1604 
1605   initialize_reserved_region(heap_rs);
1606 
1607   // Create the barrier set for the entire reserved region.
1608   G1CardTable* ct = new G1CardTable(heap_rs.region());
1609   ct->initialize();
1610   G1BarrierSet* bs = new G1BarrierSet(ct);
1611   bs->initialize();
1612   assert(bs->is_a(BarrierSet::G1BarrierSet), "sanity");
1613   BarrierSet::set_barrier_set(bs);
1614   _card_table = ct;
1615 
1616   {
1617     G1SATBMarkQueueSet& satbqs = bs->satb_mark_queue_set();
1618     satbqs.set_process_completed_buffers_threshold(G1SATBProcessCompletedThreshold);
1619     satbqs.set_buffer_enqueue_threshold_percentage(G1SATBBufferEnqueueingThresholdPercent);
1620   }
1621 
1622   // Create the hot card cache.
1623   _hot_card_cache = new G1HotCardCache(this);
1624 
1625   // Create space mappers.
1626   size_t page_size = heap_rs.page_size();
1627   G1RegionToSpaceMapper* heap_storage =
1628     G1RegionToSpaceMapper::create_mapper(heap_rs,
1629                                          heap_rs.size(),
1630                                          page_size,
1631                                          HeapRegion::GrainBytes,
1632                                          1,
1633                                          mtJavaHeap);
1634   if(heap_storage == NULL) {
1635     vm_shutdown_during_initialization("Could not initialize G1 heap");
1636     return JNI_ERR;
1637   }
1638 
1639   os::trace_page_sizes("Heap",
1640                        MinHeapSize,
1641                        reserved_byte_size,
1642                        page_size,
1643                        heap_rs.base(),
1644                        heap_rs.size());
1645   heap_storage->set_mapping_changed_listener(&_listener);
1646 
1647   // Create storage for the BOT, card table, card counts table (hot card cache) and the bitmaps.
1648   G1RegionToSpaceMapper* bot_storage =
1649     create_aux_memory_mapper("Block Offset Table",
1650                              G1BlockOffsetTable::compute_size(heap_rs.size() / HeapWordSize),
1651                              G1BlockOffsetTable::heap_map_factor());
1652 
1653   G1RegionToSpaceMapper* cardtable_storage =
1654     create_aux_memory_mapper("Card Table",
1655                              G1CardTable::compute_size(heap_rs.size() / HeapWordSize),
1656                              G1CardTable::heap_map_factor());
1657 
1658   G1RegionToSpaceMapper* card_counts_storage =
1659     create_aux_memory_mapper("Card Counts Table",
1660                              G1CardCounts::compute_size(heap_rs.size() / HeapWordSize),
1661                              G1CardCounts::heap_map_factor());
1662 
1663   size_t bitmap_size = G1CMBitMap::compute_size(heap_rs.size());
1664   G1RegionToSpaceMapper* prev_bitmap_storage =
1665     create_aux_memory_mapper("Prev Bitmap", bitmap_size, G1CMBitMap::heap_map_factor());
1666   G1RegionToSpaceMapper* next_bitmap_storage =
1667     create_aux_memory_mapper("Next Bitmap", bitmap_size, G1CMBitMap::heap_map_factor());
1668 
1669   _hrm.initialize(heap_storage, prev_bitmap_storage, next_bitmap_storage, bot_storage, cardtable_storage, card_counts_storage);
1670   _card_table->initialize(cardtable_storage);
1671 
1672   // Do later initialization work for concurrent refinement.
1673   _hot_card_cache->initialize(card_counts_storage);
1674 
1675   // 6843694 - ensure that the maximum region index can fit
1676   // in the remembered set structures.
1677   const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1;
1678   guarantee((max_reserved_regions() - 1) <= max_region_idx, "too many regions");
1679 
1680   // The G1FromCardCache reserves card with value 0 as "invalid", so the heap must not
1681   // start within the first card.
1682   guarantee(heap_rs.base() >= (char*)G1CardTable::card_size, "Java heap must not start within the first card.");
1683   G1FromCardCache::initialize(max_reserved_regions());
1684   // Also create a G1 rem set.
1685   _rem_set = new G1RemSet(this, _card_table, _hot_card_cache);
1686   _rem_set->initialize(max_reserved_regions());
1687 
1688   size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1;
1689   guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized");
1690   guarantee(HeapRegion::CardsPerRegion < max_cards_per_region,
1691             "too many cards per region");
1692 
1693   FreeRegionList::set_unrealistically_long_length(max_regions() + 1);
1694 
1695   _bot = new G1BlockOffsetTable(reserved(), bot_storage);
1696 
1697   {
1698     size_t granularity = HeapRegion::GrainBytes;
1699 
1700     _region_attr.initialize(reserved(), granularity);
1701     _humongous_reclaim_candidates.initialize(reserved(), granularity);
1702   }
1703 
1704   _workers = new WorkGang("GC Thread", ParallelGCThreads,
1705                           true /* are_GC_task_threads */,
1706                           false /* are_ConcurrentGC_threads */);
1707   if (_workers == NULL) {
1708     return JNI_ENOMEM;
1709   }
1710   _workers->initialize_workers();
1711 
1712   _numa->set_region_info(HeapRegion::GrainBytes, page_size);
1713 
1714   // Create the G1ConcurrentMark data structure and thread.
1715   // (Must do this late, so that "max_[reserved_]regions" is defined.)
1716   _cm = new G1ConcurrentMark(this, prev_bitmap_storage, next_bitmap_storage);
1717   _cm_thread = _cm->cm_thread();
1718 
1719   // Now expand into the initial heap size.
1720   if (!expand(init_byte_size, _workers)) {
1721     vm_shutdown_during_initialization("Failed to allocate initial heap.");
1722     return JNI_ENOMEM;
1723   }
1724 
1725   // Perform any initialization actions delegated to the policy.
1726   policy()->init(this, &_collection_set);
1727 
1728   jint ecode = initialize_concurrent_refinement();
1729   if (ecode != JNI_OK) {
1730     return ecode;
1731   }
1732 
1733   ecode = initialize_service_thread();
1734   if (ecode != JNI_OK) {
1735     return ecode;
1736   }
1737 
1738   // Initialize and schedule sampling task on service thread.
1739   _rem_set->initialize_sampling_task(service_thread());
1740 
1741   // Create and schedule the periodic gc task on the service thread.
1742   _periodic_gc_task = new G1PeriodicGCTask("Periodic GC Task");
1743   _service_thread->register_task(_periodic_gc_task);
1744 
1745   {
1746     G1DirtyCardQueueSet& dcqs = G1BarrierSet::dirty_card_queue_set();
1747     dcqs.set_process_cards_threshold(concurrent_refine()->yellow_zone());
1748     dcqs.set_max_cards(concurrent_refine()->red_zone());
1749   }
1750 
1751   // Here we allocate the dummy HeapRegion that is required by the
1752   // G1AllocRegion class.
1753   HeapRegion* dummy_region = _hrm.get_dummy_region();
1754 
1755   // We'll re-use the same region whether the alloc region will
1756   // require BOT updates or not and, if it doesn't, then a non-young
1757   // region will complain that it cannot support allocations without
1758   // BOT updates. So we'll tag the dummy region as eden to avoid that.
1759   dummy_region->set_eden();
1760   // Make sure it's full.
1761   dummy_region->set_top(dummy_region->end());
1762   G1AllocRegion::setup(this, dummy_region);
1763 
1764   _allocator->init_mutator_alloc_regions();
1765 
1766   // Do create of the monitoring and management support so that
1767   // values in the heap have been properly initialized.
1768   _g1mm = new G1MonitoringSupport(this);
1769 
1770   _preserved_marks_set.init(ParallelGCThreads);
1771 
1772   _collection_set.initialize(max_reserved_regions());
1773 
1774   _regions_failed_evacuation = NEW_C_HEAP_ARRAY(volatile bool, max_regions(), mtGC);
1775 
1776   G1InitLogger::print();
1777 
1778   SlidingForwarding::initialize(heap_rs.region(), HeapRegion::GrainWords);
1779 
1780   return JNI_OK;
1781 }
1782 
1783 void G1CollectedHeap::stop() {
1784   // Stop all concurrent threads. We do this to make sure these threads
1785   // do not continue to execute and access resources (e.g. logging)
1786   // that are destroyed during shutdown.
1787   _cr->stop();
1788   _service_thread->stop();
1789   _cm_thread->stop();
1790 }
1791 
1792 void G1CollectedHeap::safepoint_synchronize_begin() {
1793   SuspendibleThreadSet::synchronize();
1794 }
1795 
1796 void G1CollectedHeap::safepoint_synchronize_end() {
1797   SuspendibleThreadSet::desynchronize();
1798 }
1799 
1800 void G1CollectedHeap::post_initialize() {
1801   CollectedHeap::post_initialize();
1802   ref_processing_init();
1803 }
1804 
1805 void G1CollectedHeap::ref_processing_init() {
1806   // Reference processing in G1 currently works as follows:
1807   //
1808   // * There are two reference processor instances. One is
1809   //   used to record and process discovered references
1810   //   during concurrent marking; the other is used to
1811   //   record and process references during STW pauses
1812   //   (both full and incremental).
1813   // * Both ref processors need to 'span' the entire heap as
1814   //   the regions in the collection set may be dotted around.
1815   //
1816   // * For the concurrent marking ref processor:
1817   //   * Reference discovery is enabled at concurrent start.
1818   //   * Reference discovery is disabled and the discovered
1819   //     references processed etc during remarking.
1820   //   * Reference discovery is MT (see below).
1821   //   * Reference discovery requires a barrier (see below).
1822   //   * Reference processing may or may not be MT
1823   //     (depending on the value of ParallelRefProcEnabled
1824   //     and ParallelGCThreads).
1825   //   * A full GC disables reference discovery by the CM
1826   //     ref processor and abandons any entries on it's
1827   //     discovered lists.
1828   //
1829   // * For the STW processor:
1830   //   * Non MT discovery is enabled at the start of a full GC.
1831   //   * Processing and enqueueing during a full GC is non-MT.
1832   //   * During a full GC, references are processed after marking.
1833   //
1834   //   * Discovery (may or may not be MT) is enabled at the start
1835   //     of an incremental evacuation pause.
1836   //   * References are processed near the end of a STW evacuation pause.
1837   //   * For both types of GC:
1838   //     * Discovery is atomic - i.e. not concurrent.
1839   //     * Reference discovery will not need a barrier.
1840 
1841   // Concurrent Mark ref processor
1842   _ref_processor_cm =
1843     new ReferenceProcessor(&_is_subject_to_discovery_cm,
1844                            ParallelGCThreads,                              // degree of mt processing
1845                            (ParallelGCThreads > 1) || (ConcGCThreads > 1), // mt discovery
1846                            MAX2(ParallelGCThreads, ConcGCThreads),         // degree of mt discovery
1847                            false,                                          // Reference discovery is not atomic
1848                            &_is_alive_closure_cm);                         // is alive closure
1849 
1850   // STW ref processor
1851   _ref_processor_stw =
1852     new ReferenceProcessor(&_is_subject_to_discovery_stw,
1853                            ParallelGCThreads,                    // degree of mt processing
1854                            (ParallelGCThreads > 1),              // mt discovery
1855                            ParallelGCThreads,                    // degree of mt discovery
1856                            true,                                 // Reference discovery is atomic
1857                            &_is_alive_closure_stw);              // is alive closure
1858 }
1859 
1860 SoftRefPolicy* G1CollectedHeap::soft_ref_policy() {
1861   return &_soft_ref_policy;
1862 }
1863 
1864 size_t G1CollectedHeap::capacity() const {
1865   return _hrm.length() * HeapRegion::GrainBytes;
1866 }
1867 
1868 size_t G1CollectedHeap::unused_committed_regions_in_bytes() const {
1869   return _hrm.total_free_bytes();
1870 }
1871 
1872 void G1CollectedHeap::iterate_hcc_closure(G1CardTableEntryClosure* cl, uint worker_id) {
1873   _hot_card_cache->drain(cl, worker_id);
1874 }
1875 
1876 // Computes the sum of the storage used by the various regions.
1877 size_t G1CollectedHeap::used() const {
1878   size_t result = _summary_bytes_used + _allocator->used_in_alloc_regions();
1879   if (_archive_allocator != NULL) {
1880     result += _archive_allocator->used();
1881   }
1882   return result;
1883 }
1884 
1885 size_t G1CollectedHeap::used_unlocked() const {
1886   return _summary_bytes_used;
1887 }
1888 
1889 class SumUsedClosure: public HeapRegionClosure {
1890   size_t _used;
1891 public:
1892   SumUsedClosure() : _used(0) {}
1893   bool do_heap_region(HeapRegion* r) {
1894     _used += r->used();
1895     return false;
1896   }
1897   size_t result() { return _used; }
1898 };
1899 
1900 size_t G1CollectedHeap::recalculate_used() const {
1901   SumUsedClosure blk;
1902   heap_region_iterate(&blk);
1903   return blk.result();
1904 }
1905 
1906 bool  G1CollectedHeap::is_user_requested_concurrent_full_gc(GCCause::Cause cause) {
1907   switch (cause) {
1908     case GCCause::_java_lang_system_gc:                 return ExplicitGCInvokesConcurrent;
1909     case GCCause::_dcmd_gc_run:                         return ExplicitGCInvokesConcurrent;
1910     case GCCause::_wb_conc_mark:                        return true;
1911     default :                                           return false;
1912   }
1913 }
1914 
1915 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {
1916   switch (cause) {
1917     case GCCause::_g1_humongous_allocation: return true;
1918     case GCCause::_g1_periodic_collection:  return G1PeriodicGCInvokesConcurrent;
1919     case GCCause::_wb_breakpoint:           return true;
1920     default:                                return is_user_requested_concurrent_full_gc(cause);
1921   }
1922 }
1923 
1924 #ifndef PRODUCT
1925 void G1CollectedHeap::allocate_dummy_regions() {
1926   // Let's fill up most of the region
1927   size_t word_size = HeapRegion::GrainWords - 1024;
1928   // And as a result the region we'll allocate will be humongous.
1929   guarantee(is_humongous(word_size), "sanity");
1930 
1931   // _filler_array_max_size is set to humongous object threshold
1932   // but temporarily change it to use CollectedHeap::fill_with_object().
1933   AutoModifyRestore<size_t> temporarily(_filler_array_max_size, word_size);
1934 
1935   for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) {
1936     // Let's use the existing mechanism for the allocation
1937     HeapWord* dummy_obj = humongous_obj_allocate(word_size);
1938     if (dummy_obj != NULL) {
1939       MemRegion mr(dummy_obj, word_size);
1940       CollectedHeap::fill_with_object(mr);
1941     } else {
1942       // If we can't allocate once, we probably cannot allocate
1943       // again. Let's get out of the loop.
1944       break;
1945     }
1946   }
1947 }
1948 #endif // !PRODUCT
1949 
1950 void G1CollectedHeap::increment_old_marking_cycles_started() {
1951   assert(_old_marking_cycles_started == _old_marking_cycles_completed ||
1952          _old_marking_cycles_started == _old_marking_cycles_completed + 1,
1953          "Wrong marking cycle count (started: %d, completed: %d)",
1954          _old_marking_cycles_started, _old_marking_cycles_completed);
1955 
1956   _old_marking_cycles_started++;
1957 }
1958 
1959 void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent,
1960                                                              bool whole_heap_examined) {
1961   MonitorLocker ml(G1OldGCCount_lock, Mutex::_no_safepoint_check_flag);
1962 
1963   // We assume that if concurrent == true, then the caller is a
1964   // concurrent thread that was joined the Suspendible Thread
1965   // Set. If there's ever a cheap way to check this, we should add an
1966   // assert here.
1967 
1968   // Given that this method is called at the end of a Full GC or of a
1969   // concurrent cycle, and those can be nested (i.e., a Full GC can
1970   // interrupt a concurrent cycle), the number of full collections
1971   // completed should be either one (in the case where there was no
1972   // nesting) or two (when a Full GC interrupted a concurrent cycle)
1973   // behind the number of full collections started.
1974 
1975   // This is the case for the inner caller, i.e. a Full GC.
1976   assert(concurrent ||
1977          (_old_marking_cycles_started == _old_marking_cycles_completed + 1) ||
1978          (_old_marking_cycles_started == _old_marking_cycles_completed + 2),
1979          "for inner caller (Full GC): _old_marking_cycles_started = %u "
1980          "is inconsistent with _old_marking_cycles_completed = %u",
1981          _old_marking_cycles_started, _old_marking_cycles_completed);
1982 
1983   // This is the case for the outer caller, i.e. the concurrent cycle.
1984   assert(!concurrent ||
1985          (_old_marking_cycles_started == _old_marking_cycles_completed + 1),
1986          "for outer caller (concurrent cycle): "
1987          "_old_marking_cycles_started = %u "
1988          "is inconsistent with _old_marking_cycles_completed = %u",
1989          _old_marking_cycles_started, _old_marking_cycles_completed);
1990 
1991   _old_marking_cycles_completed += 1;
1992   if (whole_heap_examined) {
1993     // Signal that we have completed a visit to all live objects.
1994     record_whole_heap_examined_timestamp();
1995   }
1996 
1997   // We need to clear the "in_progress" flag in the CM thread before
1998   // we wake up any waiters (especially when ExplicitInvokesConcurrent
1999   // is set) so that if a waiter requests another System.gc() it doesn't
2000   // incorrectly see that a marking cycle is still in progress.
2001   if (concurrent) {
2002     _cm_thread->set_idle();
2003   }
2004 
2005   // Notify threads waiting in System.gc() (with ExplicitGCInvokesConcurrent)
2006   // for a full GC to finish that their wait is over.
2007   ml.notify_all();
2008 }
2009 
2010 void G1CollectedHeap::collect(GCCause::Cause cause) {
2011   try_collect(cause);
2012 }
2013 
2014 // Return true if (x < y) with allowance for wraparound.
2015 static bool gc_counter_less_than(uint x, uint y) {
2016   return (x - y) > (UINT_MAX/2);
2017 }
2018 
2019 // LOG_COLLECT_CONCURRENTLY(cause, msg, args...)
2020 // Macro so msg printing is format-checked.
2021 #define LOG_COLLECT_CONCURRENTLY(cause, ...)                            \
2022   do {                                                                  \
2023     LogTarget(Trace, gc) LOG_COLLECT_CONCURRENTLY_lt;                   \
2024     if (LOG_COLLECT_CONCURRENTLY_lt.is_enabled()) {                     \
2025       ResourceMark rm; /* For thread name. */                           \
2026       LogStream LOG_COLLECT_CONCURRENTLY_s(&LOG_COLLECT_CONCURRENTLY_lt); \
2027       LOG_COLLECT_CONCURRENTLY_s.print("%s: Try Collect Concurrently (%s): ", \
2028                                        Thread::current()->name(),       \
2029                                        GCCause::to_string(cause));      \
2030       LOG_COLLECT_CONCURRENTLY_s.print(__VA_ARGS__);                    \
2031     }                                                                   \
2032   } while (0)
2033 
2034 #define LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, result) \
2035   LOG_COLLECT_CONCURRENTLY(cause, "complete %s", BOOL_TO_STR(result))
2036 
2037 bool G1CollectedHeap::try_collect_concurrently(GCCause::Cause cause,
2038                                                uint gc_counter,
2039                                                uint old_marking_started_before) {
2040   assert_heap_not_locked();
2041   assert(should_do_concurrent_full_gc(cause),
2042          "Non-concurrent cause %s", GCCause::to_string(cause));
2043 
2044   for (uint i = 1; true; ++i) {
2045     // Try to schedule concurrent start evacuation pause that will
2046     // start a concurrent cycle.
2047     LOG_COLLECT_CONCURRENTLY(cause, "attempt %u", i);
2048     VM_G1TryInitiateConcMark op(gc_counter,
2049                                 cause,
2050                                 policy()->max_pause_time_ms());
2051     VMThread::execute(&op);
2052 
2053     // Request is trivially finished.
2054     if (cause == GCCause::_g1_periodic_collection) {
2055       LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, op.gc_succeeded());
2056       return op.gc_succeeded();
2057     }
2058 
2059     // If VMOp skipped initiating concurrent marking cycle because
2060     // we're terminating, then we're done.
2061     if (op.terminating()) {
2062       LOG_COLLECT_CONCURRENTLY(cause, "skipped: terminating");
2063       return false;
2064     }
2065 
2066     // Lock to get consistent set of values.
2067     uint old_marking_started_after;
2068     uint old_marking_completed_after;
2069     {
2070       MutexLocker ml(Heap_lock);
2071       // Update gc_counter for retrying VMOp if needed. Captured here to be
2072       // consistent with the values we use below for termination tests.  If
2073       // a retry is needed after a possible wait, and another collection
2074       // occurs in the meantime, it will cause our retry to be skipped and
2075       // we'll recheck for termination with updated conditions from that
2076       // more recent collection.  That's what we want, rather than having
2077       // our retry possibly perform an unnecessary collection.
2078       gc_counter = total_collections();
2079       old_marking_started_after = _old_marking_cycles_started;
2080       old_marking_completed_after = _old_marking_cycles_completed;
2081     }
2082 
2083     if (cause == GCCause::_wb_breakpoint) {
2084       if (op.gc_succeeded()) {
2085         LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
2086         return true;
2087       }
2088       // When _wb_breakpoint there can't be another cycle or deferred.
2089       assert(!op.cycle_already_in_progress(), "invariant");
2090       assert(!op.whitebox_attached(), "invariant");
2091       // Concurrent cycle attempt might have been cancelled by some other
2092       // collection, so retry.  Unlike other cases below, we want to retry
2093       // even if cancelled by a STW full collection, because we really want
2094       // to start a concurrent cycle.
2095       if (old_marking_started_before != old_marking_started_after) {
2096         LOG_COLLECT_CONCURRENTLY(cause, "ignoring STW full GC");
2097         old_marking_started_before = old_marking_started_after;
2098       }
2099     } else if (!GCCause::is_user_requested_gc(cause)) {
2100       // For an "automatic" (not user-requested) collection, we just need to
2101       // ensure that progress is made.
2102       //
2103       // Request is finished if any of
2104       // (1) the VMOp successfully performed a GC,
2105       // (2) a concurrent cycle was already in progress,
2106       // (3) whitebox is controlling concurrent cycles,
2107       // (4) a new cycle was started (by this thread or some other), or
2108       // (5) a Full GC was performed.
2109       // Cases (4) and (5) are detected together by a change to
2110       // _old_marking_cycles_started.
2111       //
2112       // Note that (1) does not imply (4).  If we're still in the mixed
2113       // phase of an earlier concurrent collection, the request to make the
2114       // collection a concurrent start won't be honored.  If we don't check for
2115       // both conditions we'll spin doing back-to-back collections.
2116       if (op.gc_succeeded() ||
2117           op.cycle_already_in_progress() ||
2118           op.whitebox_attached() ||
2119           (old_marking_started_before != old_marking_started_after)) {
2120         LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
2121         return true;
2122       }
2123     } else {                    // User-requested GC.
2124       // For a user-requested collection, we want to ensure that a complete
2125       // full collection has been performed before returning, but without
2126       // waiting for more than needed.
2127 
2128       // For user-requested GCs (unlike non-UR), a successful VMOp implies a
2129       // new cycle was started.  That's good, because it's not clear what we
2130       // should do otherwise.  Trying again just does back to back GCs.
2131       // Can't wait for someone else to start a cycle.  And returning fails
2132       // to meet the goal of ensuring a full collection was performed.
2133       assert(!op.gc_succeeded() ||
2134              (old_marking_started_before != old_marking_started_after),
2135              "invariant: succeeded %s, started before %u, started after %u",
2136              BOOL_TO_STR(op.gc_succeeded()),
2137              old_marking_started_before, old_marking_started_after);
2138 
2139       // Request is finished if a full collection (concurrent or stw)
2140       // was started after this request and has completed, e.g.
2141       // started_before < completed_after.
2142       if (gc_counter_less_than(old_marking_started_before,
2143                                old_marking_completed_after)) {
2144         LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true);
2145         return true;
2146       }
2147 
2148       if (old_marking_started_after != old_marking_completed_after) {
2149         // If there is an in-progress cycle (possibly started by us), then
2150         // wait for that cycle to complete, e.g.
2151         // while completed_now < started_after.
2152         LOG_COLLECT_CONCURRENTLY(cause, "wait");
2153         MonitorLocker ml(G1OldGCCount_lock);
2154         while (gc_counter_less_than(_old_marking_cycles_completed,
2155                                     old_marking_started_after)) {
2156           ml.wait();
2157         }
2158         // Request is finished if the collection we just waited for was
2159         // started after this request.
2160         if (old_marking_started_before != old_marking_started_after) {
2161           LOG_COLLECT_CONCURRENTLY(cause, "complete after wait");
2162           return true;
2163         }
2164       }
2165 
2166       // If VMOp was successful then it started a new cycle that the above
2167       // wait &etc should have recognized as finishing this request.  This
2168       // differs from a non-user-request, where gc_succeeded does not imply
2169       // a new cycle was started.
2170       assert(!op.gc_succeeded(), "invariant");
2171 
2172       if (op.cycle_already_in_progress()) {
2173         // If VMOp failed because a cycle was already in progress, it
2174         // is now complete.  But it didn't finish this user-requested
2175         // GC, so try again.
2176         LOG_COLLECT_CONCURRENTLY(cause, "retry after in-progress");
2177         continue;
2178       } else if (op.whitebox_attached()) {
2179         // If WhiteBox wants control, wait for notification of a state
2180         // change in the controller, then try again.  Don't wait for
2181         // release of control, since collections may complete while in
2182         // control.  Note: This won't recognize a STW full collection
2183         // while waiting; we can't wait on multiple monitors.
2184         LOG_COLLECT_CONCURRENTLY(cause, "whitebox control stall");
2185         MonitorLocker ml(ConcurrentGCBreakpoints::monitor());
2186         if (ConcurrentGCBreakpoints::is_controlled()) {
2187           ml.wait();
2188         }
2189         continue;
2190       }
2191     }
2192 
2193     // Collection failed and should be retried.
2194     assert(op.transient_failure(), "invariant");
2195 
2196     if (GCLocker::is_active_and_needs_gc()) {
2197       // If GCLocker is active, wait until clear before retrying.
2198       LOG_COLLECT_CONCURRENTLY(cause, "gc-locker stall");
2199       GCLocker::stall_until_clear();
2200     }
2201 
2202     LOG_COLLECT_CONCURRENTLY(cause, "retry");
2203   }
2204 }
2205 
2206 bool G1CollectedHeap::try_collect(GCCause::Cause cause) {
2207   assert_heap_not_locked();
2208 
2209   // Lock to get consistent set of values.
2210   uint gc_count_before;
2211   uint full_gc_count_before;
2212   uint old_marking_started_before;
2213   {
2214     MutexLocker ml(Heap_lock);
2215     gc_count_before = total_collections();
2216     full_gc_count_before = total_full_collections();
2217     old_marking_started_before = _old_marking_cycles_started;
2218   }
2219 
2220   if (should_do_concurrent_full_gc(cause)) {
2221     return try_collect_concurrently(cause,
2222                                     gc_count_before,
2223                                     old_marking_started_before);
2224   } else if (GCLocker::should_discard(cause, gc_count_before)) {
2225     // Indicate failure to be consistent with VMOp failure due to
2226     // another collection slipping in after our gc_count but before
2227     // our request is processed.
2228     return false;
2229   } else if (cause == GCCause::_gc_locker || cause == GCCause::_wb_young_gc
2230              DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) {
2231 
2232     // Schedule a standard evacuation pause. We're setting word_size
2233     // to 0 which means that we are not requesting a post-GC allocation.
2234     VM_G1CollectForAllocation op(0,     /* word_size */
2235                                  gc_count_before,
2236                                  cause,
2237                                  policy()->max_pause_time_ms());
2238     VMThread::execute(&op);
2239     return op.gc_succeeded();
2240   } else {
2241     // Schedule a Full GC.
2242     VM_G1CollectFull op(gc_count_before, full_gc_count_before, cause);
2243     VMThread::execute(&op);
2244     return op.gc_succeeded();
2245   }
2246 }
2247 
2248 bool G1CollectedHeap::is_in(const void* p) const {
2249   return is_in_reserved(p) && _hrm.is_available(addr_to_region((HeapWord*)p));
2250 }
2251 
2252 // Iteration functions.
2253 
2254 // Iterates an ObjectClosure over all objects within a HeapRegion.
2255 
2256 class IterateObjectClosureRegionClosure: public HeapRegionClosure {
2257   ObjectClosure* _cl;
2258 public:
2259   IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
2260   bool do_heap_region(HeapRegion* r) {
2261     if (!r->is_continues_humongous()) {
2262       r->object_iterate(_cl);
2263     }
2264     return false;
2265   }
2266 };
2267 
2268 void G1CollectedHeap::object_iterate(ObjectClosure* cl) {
2269   IterateObjectClosureRegionClosure blk(cl);
2270   heap_region_iterate(&blk);
2271 }
2272 
2273 class G1ParallelObjectIterator : public ParallelObjectIteratorImpl {
2274 private:
2275   G1CollectedHeap*  _heap;
2276   HeapRegionClaimer _claimer;
2277 
2278 public:
2279   G1ParallelObjectIterator(uint thread_num) :
2280       _heap(G1CollectedHeap::heap()),
2281       _claimer(thread_num == 0 ? G1CollectedHeap::heap()->workers()->active_workers() : thread_num) {}
2282 
2283   virtual void object_iterate(ObjectClosure* cl, uint worker_id) {
2284     _heap->object_iterate_parallel(cl, worker_id, &_claimer);
2285   }
2286 };
2287 
2288 ParallelObjectIteratorImpl* G1CollectedHeap::parallel_object_iterator(uint thread_num) {
2289   return new G1ParallelObjectIterator(thread_num);
2290 }
2291 
2292 void G1CollectedHeap::object_iterate_parallel(ObjectClosure* cl, uint worker_id, HeapRegionClaimer* claimer) {
2293   IterateObjectClosureRegionClosure blk(cl);
2294   heap_region_par_iterate_from_worker_offset(&blk, claimer, worker_id);
2295 }
2296 
2297 void G1CollectedHeap::keep_alive(oop obj) {
2298   G1BarrierSet::enqueue_preloaded(obj);
2299 }
2300 
2301 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const {
2302   _hrm.iterate(cl);
2303 }
2304 
2305 void G1CollectedHeap::heap_region_par_iterate_from_worker_offset(HeapRegionClosure* cl,
2306                                                                  HeapRegionClaimer *hrclaimer,
2307                                                                  uint worker_id) const {
2308   _hrm.par_iterate(cl, hrclaimer, hrclaimer->offset_for_worker(worker_id));
2309 }
2310 
2311 void G1CollectedHeap::heap_region_par_iterate_from_start(HeapRegionClosure* cl,
2312                                                          HeapRegionClaimer *hrclaimer) const {
2313   _hrm.par_iterate(cl, hrclaimer, 0);
2314 }
2315 
2316 void G1CollectedHeap::collection_set_iterate_all(HeapRegionClosure* cl) {
2317   _collection_set.iterate(cl);
2318 }
2319 
2320 void G1CollectedHeap::collection_set_par_iterate_all(HeapRegionClosure* cl, HeapRegionClaimer* hr_claimer, uint worker_id) {
2321   _collection_set.par_iterate(cl, hr_claimer, worker_id, workers()->active_workers());
2322 }
2323 
2324 void G1CollectedHeap::collection_set_iterate_increment_from(HeapRegionClosure *cl, HeapRegionClaimer* hr_claimer, uint worker_id) {
2325   _collection_set.iterate_incremental_part_from(cl, hr_claimer, worker_id, workers()->active_workers());
2326 }
2327 
2328 HeapWord* G1CollectedHeap::block_start(const void* addr) const {
2329   HeapRegion* hr = heap_region_containing(addr);
2330   return hr->block_start(addr);
2331 }
2332 
2333 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const {
2334   HeapRegion* hr = heap_region_containing(addr);
2335   return hr->block_is_obj(addr);
2336 }
2337 
2338 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const {
2339   return (_policy->young_list_target_length() - _survivor.length()) * HeapRegion::GrainBytes;
2340 }
2341 
2342 size_t G1CollectedHeap::tlab_used(Thread* ignored) const {
2343   return _eden.length() * HeapRegion::GrainBytes;
2344 }
2345 
2346 // For G1 TLABs should not contain humongous objects, so the maximum TLAB size
2347 // must be equal to the humongous object limit.
2348 size_t G1CollectedHeap::max_tlab_size() const {
2349   return align_down(_humongous_object_threshold_in_words, MinObjAlignment);
2350 }
2351 
2352 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const {
2353   return _allocator->unsafe_max_tlab_alloc();
2354 }
2355 
2356 size_t G1CollectedHeap::max_capacity() const {
2357   return max_regions() * HeapRegion::GrainBytes;
2358 }
2359 
2360 void G1CollectedHeap::prepare_for_verify() {
2361   _verifier->prepare_for_verify();
2362 }
2363 
2364 void G1CollectedHeap::verify(VerifyOption vo) {
2365   _verifier->verify(vo);
2366 }
2367 
2368 bool G1CollectedHeap::supports_concurrent_gc_breakpoints() const {
2369   return true;
2370 }
2371 
2372 bool G1CollectedHeap::is_archived_object(oop object) const {
2373   return object != NULL && heap_region_containing(object)->is_archive();
2374 }
2375 
2376 class PrintRegionClosure: public HeapRegionClosure {
2377   outputStream* _st;
2378 public:
2379   PrintRegionClosure(outputStream* st) : _st(st) {}
2380   bool do_heap_region(HeapRegion* r) {
2381     r->print_on(_st);
2382     return false;
2383   }
2384 };
2385 
2386 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
2387                                        const HeapRegion* hr,
2388                                        const VerifyOption vo) const {
2389   switch (vo) {
2390   case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj, hr);
2391   case VerifyOption_G1UseNextMarking: return is_obj_ill(obj, hr);
2392   case VerifyOption_G1UseFullMarking: return is_obj_dead_full(obj, hr);
2393   default:                            ShouldNotReachHere();
2394   }
2395   return false; // keep some compilers happy
2396 }
2397 
2398 bool G1CollectedHeap::is_obj_dead_cond(const oop obj,
2399                                        const VerifyOption vo) const {
2400   switch (vo) {
2401   case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj);
2402   case VerifyOption_G1UseNextMarking: return is_obj_ill(obj);
2403   case VerifyOption_G1UseFullMarking: return is_obj_dead_full(obj);
2404   default:                            ShouldNotReachHere();
2405   }
2406   return false; // keep some compilers happy
2407 }
2408 
2409 void G1CollectedHeap::print_heap_regions() const {
2410   LogTarget(Trace, gc, heap, region) lt;
2411   if (lt.is_enabled()) {
2412     LogStream ls(lt);
2413     print_regions_on(&ls);
2414   }
2415 }
2416 
2417 void G1CollectedHeap::print_on(outputStream* st) const {
2418   size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked();
2419   st->print(" %-20s", "garbage-first heap");
2420   st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K",
2421             capacity()/K, heap_used/K);
2422   st->print(" [" PTR_FORMAT ", " PTR_FORMAT ")",
2423             p2i(_hrm.reserved().start()),
2424             p2i(_hrm.reserved().end()));
2425   st->cr();
2426   st->print("  region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K);
2427   uint young_regions = young_regions_count();
2428   st->print("%u young (" SIZE_FORMAT "K), ", young_regions,
2429             (size_t) young_regions * HeapRegion::GrainBytes / K);
2430   uint survivor_regions = survivor_regions_count();
2431   st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions,
2432             (size_t) survivor_regions * HeapRegion::GrainBytes / K);
2433   st->cr();
2434   if (_numa->is_enabled()) {
2435     uint num_nodes = _numa->num_active_nodes();
2436     st->print("  remaining free region(s) on each NUMA node: ");
2437     const int* node_ids = _numa->node_ids();
2438     for (uint node_index = 0; node_index < num_nodes; node_index++) {
2439       uint num_free_regions = _hrm.num_free_regions(node_index);
2440       st->print("%d=%u ", node_ids[node_index], num_free_regions);
2441     }
2442     st->cr();
2443   }
2444   MetaspaceUtils::print_on(st);
2445 }
2446 
2447 void G1CollectedHeap::print_regions_on(outputStream* st) const {
2448   st->print_cr("Heap Regions: E=young(eden), S=young(survivor), O=old, "
2449                "HS=humongous(starts), HC=humongous(continues), "
2450                "CS=collection set, F=free, "
2451                "OA=open archive, CA=closed archive, "
2452                "TAMS=top-at-mark-start (previous, next)");
2453   PrintRegionClosure blk(st);
2454   heap_region_iterate(&blk);
2455 }
2456 
2457 void G1CollectedHeap::print_extended_on(outputStream* st) const {
2458   print_on(st);
2459 
2460   // Print the per-region information.
2461   st->cr();
2462   print_regions_on(st);
2463 }
2464 
2465 void G1CollectedHeap::print_on_error(outputStream* st) const {
2466   this->CollectedHeap::print_on_error(st);
2467 
2468   if (_cm != NULL) {
2469     st->cr();
2470     _cm->print_on_error(st);
2471   }
2472 }
2473 
2474 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const {
2475   workers()->threads_do(tc);
2476   tc->do_thread(_cm_thread);
2477   _cm->threads_do(tc);
2478   _cr->threads_do(tc);
2479   tc->do_thread(_service_thread);
2480 }
2481 
2482 void G1CollectedHeap::print_tracing_info() const {
2483   rem_set()->print_summary_info();
2484   concurrent_mark()->print_summary_info();
2485 }
2486 
2487 #ifndef PRODUCT
2488 // Helpful for debugging RSet issues.
2489 
2490 class PrintRSetsClosure : public HeapRegionClosure {
2491 private:
2492   const char* _msg;
2493   size_t _occupied_sum;
2494 
2495 public:
2496   bool do_heap_region(HeapRegion* r) {
2497     HeapRegionRemSet* hrrs = r->rem_set();
2498     size_t occupied = hrrs->occupied();
2499     _occupied_sum += occupied;
2500 
2501     tty->print_cr("Printing RSet for region " HR_FORMAT, HR_FORMAT_PARAMS(r));
2502     if (occupied == 0) {
2503       tty->print_cr("  RSet is empty");
2504     } else {
2505       hrrs->print();
2506     }
2507     tty->print_cr("----------");
2508     return false;
2509   }
2510 
2511   PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) {
2512     tty->cr();
2513     tty->print_cr("========================================");
2514     tty->print_cr("%s", msg);
2515     tty->cr();
2516   }
2517 
2518   ~PrintRSetsClosure() {
2519     tty->print_cr("Occupied Sum: " SIZE_FORMAT, _occupied_sum);
2520     tty->print_cr("========================================");
2521     tty->cr();
2522   }
2523 };
2524 
2525 void G1CollectedHeap::print_cset_rsets() {
2526   PrintRSetsClosure cl("Printing CSet RSets");
2527   collection_set_iterate_all(&cl);
2528 }
2529 
2530 void G1CollectedHeap::print_all_rsets() {
2531   PrintRSetsClosure cl("Printing All RSets");;
2532   heap_region_iterate(&cl);
2533 }
2534 #endif // PRODUCT
2535 
2536 bool G1CollectedHeap::print_location(outputStream* st, void* addr) const {
2537   return BlockLocationPrinter<G1CollectedHeap>::print_location(st, addr);
2538 }
2539 
2540 G1HeapSummary G1CollectedHeap::create_g1_heap_summary() {
2541 
2542   size_t eden_used_bytes = _eden.used_bytes();
2543   size_t survivor_used_bytes = _survivor.used_bytes();
2544   size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked();
2545 
2546   size_t eden_capacity_bytes =
2547     (policy()->young_list_target_length() * HeapRegion::GrainBytes) - survivor_used_bytes;
2548 
2549   VirtualSpaceSummary heap_summary = create_heap_space_summary();
2550   return G1HeapSummary(heap_summary, heap_used, eden_used_bytes,
2551                        eden_capacity_bytes, survivor_used_bytes, num_regions());
2552 }
2553 
2554 G1EvacSummary G1CollectedHeap::create_g1_evac_summary(G1EvacStats* stats) {
2555   return G1EvacSummary(stats->allocated(), stats->wasted(), stats->undo_wasted(),
2556                        stats->unused(), stats->used(), stats->region_end_waste(),
2557                        stats->regions_filled(), stats->direct_allocated(),
2558                        stats->failure_used(), stats->failure_waste());
2559 }
2560 
2561 void G1CollectedHeap::trace_heap(GCWhen::Type when, const GCTracer* gc_tracer) {
2562   const G1HeapSummary& heap_summary = create_g1_heap_summary();
2563   gc_tracer->report_gc_heap_summary(when, heap_summary);
2564 
2565   const MetaspaceSummary& metaspace_summary = create_metaspace_summary();
2566   gc_tracer->report_metaspace_summary(when, metaspace_summary);
2567 }
2568 
2569 void G1CollectedHeap::gc_prologue(bool full) {
2570   assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");
2571 
2572   // This summary needs to be printed before incrementing total collections.
2573   rem_set()->print_periodic_summary_info("Before GC RS summary", total_collections());
2574 
2575   // Update common counters.
2576   increment_total_collections(full /* full gc */);
2577   if (full || collector_state()->in_concurrent_start_gc()) {
2578     increment_old_marking_cycles_started();
2579   }
2580 
2581   // Fill TLAB's and such
2582   {
2583     Ticks start = Ticks::now();
2584     ensure_parsability(true);
2585     Tickspan dt = Ticks::now() - start;
2586     phase_times()->record_prepare_tlab_time_ms(dt.seconds() * MILLIUNITS);
2587   }
2588 
2589   if (!full) {
2590     // Flush dirty card queues to qset, so later phases don't need to account
2591     // for partially filled per-thread queues and such.  Not needed for full
2592     // collections, which ignore those logs.
2593     Ticks start = Ticks::now();
2594     G1BarrierSet::dirty_card_queue_set().concatenate_logs();
2595     Tickspan dt = Ticks::now() - start;
2596     phase_times()->record_concatenate_dirty_card_logs_time_ms(dt.seconds() * MILLIUNITS);
2597   }
2598 }
2599 
2600 void G1CollectedHeap::gc_epilogue(bool full) {
2601   // Update common counters.
2602   if (full) {
2603     // Update the number of full collections that have been completed.
2604     increment_old_marking_cycles_completed(false /* concurrent */, true /* liveness_completed */);
2605   }
2606 
2607   // We are at the end of the GC. Total collections has already been increased.
2608   rem_set()->print_periodic_summary_info("After GC RS summary", total_collections() - 1);
2609 
2610 #if COMPILER2_OR_JVMCI
2611   assert(DerivedPointerTable::is_empty(), "derived pointer present");
2612 #endif
2613 
2614   double start = os::elapsedTime();
2615   resize_all_tlabs();
2616   phase_times()->record_resize_tlab_time_ms((os::elapsedTime() - start) * 1000.0);
2617 
2618   MemoryService::track_memory_usage();
2619   // We have just completed a GC. Update the soft reference
2620   // policy with the new heap occupancy
2621   Universe::heap()->update_capacity_and_used_at_gc();
2622 
2623   // Print NUMA statistics.
2624   _numa->print_statistics();
2625 
2626   _collection_pause_end = Ticks::now();
2627 }
2628 
2629 uint G1CollectedHeap::uncommit_regions(uint region_limit) {
2630   return _hrm.uncommit_inactive_regions(region_limit);
2631 }
2632 
2633 bool G1CollectedHeap::has_uncommittable_regions() {
2634   return _hrm.has_inactive_regions();
2635 }
2636 
2637 void G1CollectedHeap::uncommit_regions_if_necessary() {
2638   if (has_uncommittable_regions()) {
2639     G1UncommitRegionTask::enqueue();
2640   }
2641 }
2642 
2643 void G1CollectedHeap::verify_numa_regions(const char* desc) {
2644   LogTarget(Trace, gc, heap, verify) lt;
2645 
2646   if (lt.is_enabled()) {
2647     LogStream ls(lt);
2648     // Iterate all heap regions to print matching between preferred numa id and actual numa id.
2649     G1NodeIndexCheckClosure cl(desc, _numa, &ls);
2650     heap_region_iterate(&cl);
2651   }
2652 }
2653 
2654 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size,
2655                                                uint gc_count_before,
2656                                                bool* succeeded,
2657                                                GCCause::Cause gc_cause) {
2658   assert_heap_not_locked_and_not_at_safepoint();
2659   VM_G1CollectForAllocation op(word_size,
2660                                gc_count_before,
2661                                gc_cause,
2662                                policy()->max_pause_time_ms());
2663   VMThread::execute(&op);
2664 
2665   HeapWord* result = op.result();
2666   bool ret_succeeded = op.prologue_succeeded() && op.gc_succeeded();
2667   assert(result == NULL || ret_succeeded,
2668          "the result should be NULL if the VM did not succeed");
2669   *succeeded = ret_succeeded;
2670 
2671   assert_heap_not_locked();
2672   return result;
2673 }
2674 
2675 void G1CollectedHeap::start_concurrent_cycle(bool concurrent_operation_is_full_mark) {
2676   assert(!_cm_thread->in_progress(), "Can not start concurrent operation while in progress");
2677 
2678   MutexLocker x(CGC_lock, Mutex::_no_safepoint_check_flag);
2679   if (concurrent_operation_is_full_mark) {
2680     _cm->post_concurrent_mark_start();
2681     _cm_thread->start_full_mark();
2682   } else {
2683     _cm->post_concurrent_undo_start();
2684     _cm_thread->start_undo_mark();
2685   }
2686   CGC_lock->notify();
2687 }
2688 
2689 bool G1CollectedHeap::is_potential_eager_reclaim_candidate(HeapRegion* r) const {
2690   // We don't nominate objects with many remembered set entries, on
2691   // the assumption that such objects are likely still live.
2692   HeapRegionRemSet* rem_set = r->rem_set();
2693 
2694   return G1EagerReclaimHumongousObjectsWithStaleRefs ?
2695          rem_set->occupancy_less_or_equal_than(G1EagerReclaimRemSetThreshold) :
2696          G1EagerReclaimHumongousObjects && rem_set->is_empty();
2697 }
2698 
2699 #ifndef PRODUCT
2700 void G1CollectedHeap::verify_region_attr_remset_update() {
2701   class VerifyRegionAttrRemSet : public HeapRegionClosure {
2702   public:
2703     virtual bool do_heap_region(HeapRegion* r) {
2704       G1CollectedHeap* g1h = G1CollectedHeap::heap();
2705       bool const needs_remset_update = g1h->region_attr(r->bottom()).needs_remset_update();
2706       assert(r->rem_set()->is_tracked() == needs_remset_update,
2707              "Region %u remset tracking status (%s) different to region attribute (%s)",
2708              r->hrm_index(), BOOL_TO_STR(r->rem_set()->is_tracked()), BOOL_TO_STR(needs_remset_update));
2709       return false;
2710     }
2711   } cl;
2712   heap_region_iterate(&cl);
2713 }
2714 #endif
2715 
2716 class VerifyRegionRemSetClosure : public HeapRegionClosure {
2717   public:
2718     bool do_heap_region(HeapRegion* hr) {
2719       if (!hr->is_archive() && !hr->is_continues_humongous()) {
2720         hr->verify_rem_set();
2721       }
2722       return false;
2723     }
2724 };
2725 
2726 uint G1CollectedHeap::num_task_queues() const {
2727   return _task_queues->size();
2728 }
2729 
2730 #if TASKQUEUE_STATS
2731 void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) {
2732   st->print_raw_cr("GC Task Stats");
2733   st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();
2734   st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();
2735 }
2736 
2737 void G1CollectedHeap::print_taskqueue_stats() const {
2738   if (!log_is_enabled(Trace, gc, task, stats)) {
2739     return;
2740   }
2741   Log(gc, task, stats) log;
2742   ResourceMark rm;
2743   LogStream ls(log.trace());
2744   outputStream* st = &ls;
2745 
2746   print_taskqueue_stats_hdr(st);
2747 
2748   TaskQueueStats totals;
2749   const uint n = num_task_queues();
2750   for (uint i = 0; i < n; ++i) {
2751     st->print("%3u ", i); task_queue(i)->stats.print(st); st->cr();
2752     totals += task_queue(i)->stats;
2753   }
2754   st->print_raw("tot "); totals.print(st); st->cr();
2755 
2756   DEBUG_ONLY(totals.verify());
2757 }
2758 
2759 void G1CollectedHeap::reset_taskqueue_stats() {
2760   const uint n = num_task_queues();
2761   for (uint i = 0; i < n; ++i) {
2762     task_queue(i)->stats.reset();
2763   }
2764 }
2765 #endif // TASKQUEUE_STATS
2766 
2767 void G1CollectedHeap::wait_for_root_region_scanning() {
2768   double scan_wait_start = os::elapsedTime();
2769   // We have to wait until the CM threads finish scanning the
2770   // root regions as it's the only way to ensure that all the
2771   // objects on them have been correctly scanned before we start
2772   // moving them during the GC.
2773   bool waited = _cm->root_regions()->wait_until_scan_finished();
2774   double wait_time_ms = 0.0;
2775   if (waited) {
2776     double scan_wait_end = os::elapsedTime();
2777     wait_time_ms = (scan_wait_end - scan_wait_start) * 1000.0;
2778   }
2779   phase_times()->record_root_region_scan_wait_time(wait_time_ms);
2780 }
2781 
2782 class G1PrintCollectionSetClosure : public HeapRegionClosure {
2783 private:
2784   G1HRPrinter* _hr_printer;
2785 public:
2786   G1PrintCollectionSetClosure(G1HRPrinter* hr_printer) : HeapRegionClosure(), _hr_printer(hr_printer) { }
2787 
2788   virtual bool do_heap_region(HeapRegion* r) {
2789     _hr_printer->cset(r);
2790     return false;
2791   }
2792 };
2793 
2794 void G1CollectedHeap::start_new_collection_set() {
2795   double start = os::elapsedTime();
2796 
2797   collection_set()->start_incremental_building();
2798 
2799   clear_region_attr();
2800 
2801   guarantee(_eden.length() == 0, "eden should have been cleared");
2802   policy()->transfer_survivors_to_cset(survivor());
2803 
2804   // We redo the verification but now wrt to the new CSet which
2805   // has just got initialized after the previous CSet was freed.
2806   _cm->verify_no_collection_set_oops();
2807 
2808   phase_times()->record_start_new_cset_time_ms((os::elapsedTime() - start) * 1000.0);
2809 }
2810 
2811 void G1CollectedHeap::calculate_collection_set(G1EvacuationInfo& evacuation_info, double target_pause_time_ms) {
2812 
2813   _collection_set.finalize_initial_collection_set(target_pause_time_ms, &_survivor);
2814   evacuation_info.set_collectionset_regions(collection_set()->region_length() +
2815                                             collection_set()->optional_region_length());
2816 
2817   _cm->verify_no_collection_set_oops();
2818 
2819   if (_hr_printer.is_active()) {
2820     G1PrintCollectionSetClosure cl(&_hr_printer);
2821     _collection_set.iterate(&cl);
2822     _collection_set.iterate_optional(&cl);
2823   }
2824 }
2825 
2826 G1HeapVerifier::G1VerifyType G1CollectedHeap::young_collection_verify_type() const {
2827   if (collector_state()->in_concurrent_start_gc()) {
2828     return G1HeapVerifier::G1VerifyConcurrentStart;
2829   } else if (collector_state()->in_young_only_phase()) {
2830     return G1HeapVerifier::G1VerifyYoungNormal;
2831   } else {
2832     return G1HeapVerifier::G1VerifyMixed;
2833   }
2834 }
2835 
2836 void G1CollectedHeap::verify_before_young_collection(G1HeapVerifier::G1VerifyType type) {
2837   if (VerifyRememberedSets) {
2838     log_info(gc, verify)("[Verifying RemSets before GC]");
2839     VerifyRegionRemSetClosure v_cl;
2840     heap_region_iterate(&v_cl);
2841   }
2842   _verifier->verify_before_gc(type);
2843   _verifier->check_bitmaps("GC Start");
2844   verify_numa_regions("GC Start");
2845 }
2846 
2847 void G1CollectedHeap::verify_after_young_collection(G1HeapVerifier::G1VerifyType type) {
2848   if (VerifyRememberedSets) {
2849     log_info(gc, verify)("[Verifying RemSets after GC]");
2850     VerifyRegionRemSetClosure v_cl;
2851     heap_region_iterate(&v_cl);
2852   }
2853   _verifier->verify_after_gc(type);
2854   _verifier->check_bitmaps("GC End");
2855   verify_numa_regions("GC End");
2856 }
2857 
2858 void G1CollectedHeap::expand_heap_after_young_collection(){
2859   size_t expand_bytes = _heap_sizing_policy->young_collection_expansion_amount();
2860   if (expand_bytes > 0) {
2861     // No need for an ergo logging here,
2862     // expansion_amount() does this when it returns a value > 0.
2863     double expand_ms = 0.0;
2864     if (!expand(expand_bytes, _workers, &expand_ms)) {
2865       // We failed to expand the heap. Cannot do anything about it.
2866     }
2867     phase_times()->record_expand_heap_time(expand_ms);
2868   }
2869 }
2870 
2871 void G1CollectedHeap::set_young_gc_name(char* young_gc_name) {
2872   G1GCPauseType pause_type =
2873     // The strings for all Concurrent Start pauses are the same, so the parameter
2874     // does not matter here.
2875     collector_state()->young_gc_pause_type(false /* concurrent_operation_is_full_mark */);
2876   snprintf(young_gc_name,
2877            MaxYoungGCNameLength,
2878            "Pause Young (%s)",
2879            G1GCPauseTypeHelper::to_string(pause_type));
2880 }
2881 
2882 bool G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
2883   assert_at_safepoint_on_vm_thread();
2884   guarantee(!is_gc_active(), "collection is not reentrant");
2885 
2886   if (GCLocker::check_active_before_gc()) {
2887     return false;
2888   }
2889 
2890   do_collection_pause_at_safepoint_helper(target_pause_time_ms);
2891   return true;
2892 }
2893 
2894 void G1CollectedHeap::gc_tracer_report_gc_start() {
2895   _gc_timer_stw->register_gc_start();
2896   _gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start());
2897 }
2898 
2899 void G1CollectedHeap::gc_tracer_report_gc_end(bool concurrent_operation_is_full_mark,
2900                                               G1EvacuationInfo& evacuation_info) {
2901   _gc_tracer_stw->report_evacuation_info(&evacuation_info);
2902   _gc_tracer_stw->report_tenuring_threshold(_policy->tenuring_threshold());
2903 
2904   _gc_timer_stw->register_gc_end();
2905   _gc_tracer_stw->report_gc_end(_gc_timer_stw->gc_end(),
2906   _gc_timer_stw->time_partitions());
2907 }
2908 
2909 void G1CollectedHeap::do_collection_pause_at_safepoint_helper(double target_pause_time_ms) {
2910   GCIdMark gc_id_mark;
2911 
2912   SvcGCMarker sgcm(SvcGCMarker::MINOR);
2913   ResourceMark rm;
2914 
2915   policy()->note_gc_start();
2916 
2917   gc_tracer_report_gc_start();
2918 
2919   wait_for_root_region_scanning();
2920 
2921   print_heap_before_gc();
2922   print_heap_regions();
2923   trace_heap_before_gc(_gc_tracer_stw);
2924 
2925   _verifier->verify_region_sets_optional();
2926   _verifier->verify_dirty_young_regions();
2927 
2928   // We should not be doing concurrent start unless the concurrent mark thread is running
2929   if (!_cm_thread->should_terminate()) {
2930     // This call will decide whether this pause is a concurrent start
2931     // pause. If it is, in_concurrent_start_gc() will return true
2932     // for the duration of this pause.
2933     policy()->decide_on_conc_mark_initiation();
2934   }
2935 
2936   // We do not allow concurrent start to be piggy-backed on a mixed GC.
2937   assert(!collector_state()->in_concurrent_start_gc() ||
2938          collector_state()->in_young_only_phase(), "sanity");
2939   // We also do not allow mixed GCs during marking.
2940   assert(!collector_state()->mark_or_rebuild_in_progress() || collector_state()->in_young_only_phase(), "sanity");
2941 
2942   // Record whether this pause may need to trigger a concurrent operation. Later,
2943   // when we signal the G1ConcurrentMarkThread, the collector state has already
2944   // been reset for the next pause.
2945   bool should_start_concurrent_mark_operation = collector_state()->in_concurrent_start_gc();
2946   bool concurrent_operation_is_full_mark = false;
2947 
2948   // Inner scope for scope based logging, timers, and stats collection
2949   {
2950     G1EvacuationInfo evacuation_info;
2951 
2952     GCTraceCPUTime tcpu;
2953 
2954     char young_gc_name[MaxYoungGCNameLength];
2955     set_young_gc_name(young_gc_name);
2956 
2957     GCTraceTime(Info, gc) tm(young_gc_name, NULL, gc_cause(), true);
2958 
2959     uint active_workers = WorkerPolicy::calc_active_workers(workers()->total_workers(),
2960                                                             workers()->active_workers(),
2961                                                             Threads::number_of_non_daemon_threads());
2962     active_workers = workers()->update_active_workers(active_workers);
2963     log_info(gc,task)("Using %u workers of %u for evacuation", active_workers, workers()->total_workers());
2964 
2965     G1MonitoringScope ms(g1mm(),
2966                          false /* full_gc */,
2967                          collector_state()->in_mixed_phase() /* all_memory_pools_affected */);
2968 
2969     G1HeapTransition heap_transition(this);
2970 
2971     {
2972       IsGCActiveMark x;
2973 
2974       gc_prologue(false);
2975 
2976       G1HeapVerifier::G1VerifyType verify_type = young_collection_verify_type();
2977       verify_before_young_collection(verify_type);
2978 
2979       {
2980         // The elapsed time induced by the start time below deliberately elides
2981         // the possible verification above.
2982         double sample_start_time_sec = os::elapsedTime();
2983 
2984         // Please see comment in g1CollectedHeap.hpp and
2985         // G1CollectedHeap::ref_processing_init() to see how
2986         // reference processing currently works in G1.
2987         _ref_processor_stw->enable_discovery();
2988 
2989         // We want to temporarily turn off discovery by the
2990         // CM ref processor, if necessary, and turn it back on
2991         // on again later if we do. Using a scoped
2992         // NoRefDiscovery object will do this.
2993         NoRefDiscovery no_cm_discovery(_ref_processor_cm);
2994 
2995         policy()->record_collection_pause_start(sample_start_time_sec);
2996 
2997         // Forget the current allocation region (we might even choose it to be part
2998         // of the collection set!).
2999         _allocator->release_mutator_alloc_regions();
3000 
3001         calculate_collection_set(evacuation_info, target_pause_time_ms);
3002 
3003         G1RedirtyCardsQueueSet rdcqs(G1BarrierSet::dirty_card_queue_set().allocator());
3004         G1ParScanThreadStateSet per_thread_states(this,
3005                                                   &rdcqs,
3006                                                   workers()->active_workers(),
3007                                                   collection_set()->young_region_length(),
3008                                                   collection_set()->optional_region_length());
3009         pre_evacuate_collection_set(evacuation_info, &per_thread_states);
3010 
3011         bool may_do_optional_evacuation = _collection_set.optional_region_length() != 0;
3012         // Actually do the work...
3013         evacuate_initial_collection_set(&per_thread_states, may_do_optional_evacuation);
3014 
3015         if (may_do_optional_evacuation) {
3016           evacuate_optional_collection_set(&per_thread_states);
3017         }
3018         post_evacuate_collection_set(evacuation_info, &rdcqs, &per_thread_states);
3019 
3020         start_new_collection_set();
3021 
3022         _survivor_evac_stats.adjust_desired_plab_sz();
3023         _old_evac_stats.adjust_desired_plab_sz();
3024 
3025         allocate_dummy_regions();
3026 
3027         _allocator->init_mutator_alloc_regions();
3028 
3029         expand_heap_after_young_collection();
3030 
3031         // Refine the type of a concurrent mark operation now that we did the
3032         // evacuation, eventually aborting it.
3033         concurrent_operation_is_full_mark = policy()->concurrent_operation_is_full_mark("Revise IHOP");
3034 
3035         // Need to report the collection pause now since record_collection_pause_end()
3036         // modifies it to the next state.
3037         _gc_tracer_stw->report_young_gc_pause(collector_state()->young_gc_pause_type(concurrent_operation_is_full_mark));
3038 
3039         double sample_end_time_sec = os::elapsedTime();
3040         double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS;
3041         policy()->record_collection_pause_end(pause_time_ms, concurrent_operation_is_full_mark);
3042       }
3043 
3044       verify_after_young_collection(verify_type);
3045 
3046       gc_epilogue(false);
3047     }
3048 
3049     // Print the remainder of the GC log output.
3050     if (evacuation_failed()) {
3051       log_info(gc)("To-space exhausted");
3052     }
3053 
3054     policy()->print_phases();
3055     heap_transition.print();
3056 
3057     _hrm.verify_optional();
3058     _verifier->verify_region_sets_optional();
3059 
3060     TASKQUEUE_STATS_ONLY(print_taskqueue_stats());
3061     TASKQUEUE_STATS_ONLY(reset_taskqueue_stats());
3062 
3063     print_heap_after_gc();
3064     print_heap_regions();
3065     trace_heap_after_gc(_gc_tracer_stw);
3066 
3067     // We must call G1MonitoringSupport::update_sizes() in the same scoping level
3068     // as an active TraceMemoryManagerStats object (i.e. before the destructor for the
3069     // TraceMemoryManagerStats is called) so that the G1 memory pools are updated
3070     // before any GC notifications are raised.
3071     g1mm()->update_sizes();
3072 
3073     gc_tracer_report_gc_end(concurrent_operation_is_full_mark, evacuation_info);
3074   }
3075   // It should now be safe to tell the concurrent mark thread to start
3076   // without its logging output interfering with the logging output
3077   // that came from the pause.
3078 
3079   if (should_start_concurrent_mark_operation) {
3080     // CAUTION: after the start_concurrent_cycle() call below, the concurrent marking
3081     // thread(s) could be running concurrently with us. Make sure that anything
3082     // after this point does not assume that we are the only GC thread running.
3083     // Note: of course, the actual marking work will not start until the safepoint
3084     // itself is released in SuspendibleThreadSet::desynchronize().
3085     start_concurrent_cycle(concurrent_operation_is_full_mark);
3086     ConcurrentGCBreakpoints::notify_idle_to_active();
3087   }
3088 }
3089 
3090 void G1CollectedHeap::preserve_mark_during_evac_failure(uint worker_id, oop obj, markWord m) {
3091   _evacuation_failed_info_array[worker_id].register_copy_failure(obj->size());
3092   _preserved_marks_set.get(worker_id)->push_if_necessary(obj, m);
3093 }
3094 
3095 bool G1ParEvacuateFollowersClosure::offer_termination() {
3096   EventGCPhaseParallel event;
3097   G1ParScanThreadState* const pss = par_scan_state();
3098   start_term_time();
3099   const bool res = (terminator() == nullptr) ? true : terminator()->offer_termination();
3100   end_term_time();
3101   event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(G1GCPhaseTimes::Termination));
3102   return res;
3103 }
3104 
3105 void G1ParEvacuateFollowersClosure::do_void() {
3106   EventGCPhaseParallel event;
3107   G1ParScanThreadState* const pss = par_scan_state();
3108   pss->trim_queue();
3109   event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase));
3110   do {
3111     EventGCPhaseParallel event;
3112     pss->steal_and_trim_queue(queues());
3113     event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase));
3114   } while (!offer_termination());
3115 }
3116 
3117 void G1CollectedHeap::complete_cleaning(BoolObjectClosure* is_alive,
3118                                         bool class_unloading_occurred) {
3119   uint num_workers = workers()->active_workers();
3120   G1ParallelCleaningTask unlink_task(is_alive, num_workers, class_unloading_occurred);
3121   workers()->run_task(&unlink_task);
3122 }
3123 
3124 // Weak Reference Processing support
3125 
3126 bool G1STWIsAliveClosure::do_object_b(oop p) {
3127   // An object is reachable if it is outside the collection set,
3128   // or is inside and copied.
3129   return !_g1h->is_in_cset(p) || p->is_forwarded();
3130 }
3131 
3132 bool G1STWSubjectToDiscoveryClosure::do_object_b(oop obj) {
3133   assert(obj != NULL, "must not be NULL");
3134   assert(_g1h->is_in_reserved(obj), "Trying to discover obj " PTR_FORMAT " not in heap", p2i(obj));
3135   // The areas the CM and STW ref processor manage must be disjoint. The is_in_cset() below
3136   // may falsely indicate that this is not the case here: however the collection set only
3137   // contains old regions when concurrent mark is not running.
3138   return _g1h->is_in_cset(obj) || _g1h->heap_region_containing(obj)->is_survivor();
3139 }
3140 
3141 // Non Copying Keep Alive closure
3142 class G1KeepAliveClosure: public OopClosure {
3143   G1CollectedHeap*_g1h;
3144 public:
3145   G1KeepAliveClosure(G1CollectedHeap* g1h) :_g1h(g1h) {}
3146   void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }
3147   void do_oop(oop* p) {
3148     oop obj = *p;
3149     assert(obj != NULL, "the caller should have filtered out NULL values");
3150 
3151     const G1HeapRegionAttr region_attr =_g1h->region_attr(obj);
3152     if (!region_attr.is_in_cset_or_humongous()) {
3153       return;
3154     }
3155     if (region_attr.is_in_cset()) {
3156       assert( obj->is_forwarded(), "invariant" );
3157       *p = obj->forwardee();
3158     } else {
3159       assert(!obj->is_forwarded(), "invariant" );
3160       assert(region_attr.is_humongous(),
3161              "Only allowed G1HeapRegionAttr state is IsHumongous, but is %d", region_attr.type());
3162      _g1h->set_humongous_is_live(obj);
3163     }
3164   }
3165 };
3166 
3167 // Copying Keep Alive closure - can be called from both
3168 // serial and parallel code as long as different worker
3169 // threads utilize different G1ParScanThreadState instances
3170 // and different queues.
3171 
3172 class G1CopyingKeepAliveClosure: public OopClosure {
3173   G1CollectedHeap*         _g1h;
3174   G1ParScanThreadState*    _par_scan_state;
3175 
3176 public:
3177   G1CopyingKeepAliveClosure(G1CollectedHeap* g1h,
3178                             G1ParScanThreadState* pss):
3179     _g1h(g1h),
3180     _par_scan_state(pss)
3181   {}
3182 
3183   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
3184   virtual void do_oop(      oop* p) { do_oop_work(p); }
3185 
3186   template <class T> void do_oop_work(T* p) {
3187     oop obj = RawAccess<>::oop_load(p);
3188 
3189     if (_g1h->is_in_cset_or_humongous(obj)) {
3190       // If the referent object has been forwarded (either copied
3191       // to a new location or to itself in the event of an
3192       // evacuation failure) then we need to update the reference
3193       // field and, if both reference and referent are in the G1
3194       // heap, update the RSet for the referent.
3195       //
3196       // If the referent has not been forwarded then we have to keep
3197       // it alive by policy. Therefore we have copy the referent.
3198       //
3199       // When the queue is drained (after each phase of reference processing)
3200       // the object and it's followers will be copied, the reference field set
3201       // to point to the new location, and the RSet updated.
3202       _par_scan_state->push_on_queue(ScannerTask(p));
3203     }
3204   }
3205 };
3206 
3207 // Special closure for enqueuing discovered fields: during enqueue the card table
3208 // may not be in shape to properly handle normal barrier calls (e.g. card marks
3209 // in regions that failed evacuation, scribbling of various values by card table
3210 // scan code). Additionally the regular barrier enqueues into the "global"
3211 // DCQS, but during GC we need these to-be-refined entries in the GC local queue
3212 // so that after clearing the card table, the redirty cards phase will properly
3213 // mark all dirty cards to be picked up by refinement.
3214 class G1EnqueueDiscoveredFieldClosure : public EnqueueDiscoveredFieldClosure {
3215   G1CollectedHeap* _g1h;
3216   G1ParScanThreadState* _pss;
3217 
3218 public:
3219   G1EnqueueDiscoveredFieldClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) : _g1h(g1h), _pss(pss) { }
3220 
3221   virtual void enqueue(HeapWord* discovered_field_addr, oop value) {
3222     assert(_g1h->is_in(discovered_field_addr), PTR_FORMAT " is not in heap ", p2i(discovered_field_addr));
3223     // Store the value first, whatever it is.
3224     RawAccess<>::oop_store(discovered_field_addr, value);
3225     if (value == NULL) {
3226       return;
3227     }
3228     _pss->write_ref_field_post(discovered_field_addr, value);
3229   }
3230 };
3231 
3232 // Serial drain queue closure. Called as the 'complete_gc'
3233 // closure for each discovered list in some of the
3234 // reference processing phases.
3235 
3236 class G1STWDrainQueueClosure: public VoidClosure {
3237 protected:
3238   G1CollectedHeap* _g1h;
3239   G1ParScanThreadState* _par_scan_state;
3240 
3241   G1ParScanThreadState*   par_scan_state() { return _par_scan_state; }
3242 
3243 public:
3244   G1STWDrainQueueClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) :
3245     _g1h(g1h),
3246     _par_scan_state(pss)
3247   { }
3248 
3249   void do_void() {
3250     G1ParScanThreadState* const pss = par_scan_state();
3251     pss->trim_queue();
3252   }
3253 };
3254 
3255 class G1STWRefProcProxyTask : public RefProcProxyTask {
3256   G1CollectedHeap& _g1h;
3257   G1ParScanThreadStateSet& _pss;
3258   TaskTerminator _terminator;
3259   G1ScannerTasksQueueSet& _task_queues;
3260 
3261 public:
3262   G1STWRefProcProxyTask(uint max_workers, G1CollectedHeap& g1h, G1ParScanThreadStateSet& pss, G1ScannerTasksQueueSet& task_queues)
3263     : RefProcProxyTask("G1STWRefProcProxyTask", max_workers),
3264       _g1h(g1h),
3265       _pss(pss),
3266       _terminator(max_workers, &task_queues),
3267       _task_queues(task_queues) {}
3268 
3269   void work(uint worker_id) override {
3270     assert(worker_id < _max_workers, "sanity");
3271     uint index = (_tm == RefProcThreadModel::Single) ? 0 : worker_id;
3272     _pss.state_for_worker(index)->set_ref_discoverer(nullptr);
3273     G1STWIsAliveClosure is_alive(&_g1h);
3274     G1CopyingKeepAliveClosure keep_alive(&_g1h, _pss.state_for_worker(index));
3275     G1ParEvacuateFollowersClosure complete_gc(&_g1h, _pss.state_for_worker(index), &_task_queues, _tm == RefProcThreadModel::Single ? nullptr : &_terminator, G1GCPhaseTimes::ObjCopy);
3276     G1EnqueueDiscoveredFieldClosure enqueue(&_g1h, _pss.state_for_worker(index));
3277     _rp_task->rp_work(worker_id, &is_alive, &keep_alive, &enqueue, &complete_gc);
3278   }
3279 
3280   void prepare_run_task_hook() override {
3281     _terminator.reset_for_reuse(_queue_count);
3282   }
3283 };
3284 
3285 // End of weak reference support closures
3286 
3287 void G1CollectedHeap::process_discovered_references(G1ParScanThreadStateSet* per_thread_states) {
3288   double ref_proc_start = os::elapsedTime();
3289 
3290   ReferenceProcessor* rp = _ref_processor_stw;
3291   assert(rp->discovery_enabled(), "should have been enabled");
3292 
3293   // Use only a single queue for this PSS.
3294   G1ParScanThreadState*          pss = per_thread_states->state_for_worker(0);
3295   pss->set_ref_discoverer(NULL);
3296   assert(pss->queue_is_empty(), "pre-condition");
3297 
3298   // Setup the soft refs policy...
3299   rp->setup_policy(false);
3300 
3301   ReferenceProcessorPhaseTimes& pt = *phase_times()->ref_phase_times();
3302 
3303   ReferenceProcessorStats stats;
3304   uint no_of_gc_workers = workers()->active_workers();
3305 
3306   // Parallel reference processing
3307   assert(no_of_gc_workers <= rp->max_num_queues(),
3308          "Mismatch between the number of GC workers %u and the maximum number of Reference process queues %u",
3309          no_of_gc_workers,  rp->max_num_queues());
3310 
3311   rp->set_active_mt_degree(no_of_gc_workers);
3312   G1STWRefProcProxyTask task(rp->max_num_queues(), *this, *per_thread_states, *_task_queues);
3313   stats = rp->process_discovered_references(task, pt);
3314 
3315   _gc_tracer_stw->report_gc_reference_stats(stats);
3316 
3317   // We have completed copying any necessary live referent objects.
3318   assert(pss->queue_is_empty(), "both queue and overflow should be empty");
3319 
3320   make_pending_list_reachable();
3321 
3322   assert(!rp->discovery_enabled(), "Postcondition");
3323   rp->verify_no_references_recorded();
3324 
3325   double ref_proc_time = os::elapsedTime() - ref_proc_start;
3326   phase_times()->record_ref_proc_time(ref_proc_time * 1000.0);
3327 }
3328 
3329 void G1CollectedHeap::make_pending_list_reachable() {
3330   if (collector_state()->in_concurrent_start_gc()) {
3331     oop pll_head = Universe::reference_pending_list();
3332     if (pll_head != NULL) {
3333       // Any valid worker id is fine here as we are in the VM thread and single-threaded.
3334       _cm->mark_in_next_bitmap(0 /* worker_id */, pll_head);
3335     }
3336   }
3337 }
3338 
3339 static bool do_humongous_object_logging() {
3340   return log_is_enabled(Debug, gc, humongous);
3341 }
3342 
3343 bool G1CollectedHeap::should_do_eager_reclaim() const {
3344   // As eager reclaim logging also gives information about humongous objects in
3345   // the heap in general, always do the eager reclaim pass even without known
3346   // candidates.
3347   return (G1EagerReclaimHumongousObjects &&
3348           (has_humongous_reclaim_candidates() || do_humongous_object_logging()));
3349 }
3350 
3351 class G1PrepareEvacuationTask : public AbstractGangTask {
3352   class G1PrepareRegionsClosure : public HeapRegionClosure {
3353     G1CollectedHeap* _g1h;
3354     G1PrepareEvacuationTask* _parent_task;
3355     uint _worker_humongous_total;
3356     uint _worker_humongous_candidates;
3357 
3358     bool humongous_region_is_candidate(HeapRegion* region) const {
3359       assert(region->is_starts_humongous(), "Must start a humongous object");
3360 
3361       oop obj = cast_to_oop(region->bottom());
3362 
3363       // Dead objects cannot be eager reclaim candidates. Due to class
3364       // unloading it is unsafe to query their classes so we return early.
3365       if (_g1h->is_obj_dead(obj, region)) {
3366         return false;
3367       }
3368 
3369       // If we do not have a complete remembered set for the region, then we can
3370       // not be sure that we have all references to it.
3371       if (!region->rem_set()->is_complete()) {
3372         return false;
3373       }
3374       // Candidate selection must satisfy the following constraints
3375       // while concurrent marking is in progress:
3376       //
3377       // * In order to maintain SATB invariants, an object must not be
3378       // reclaimed if it was allocated before the start of marking and
3379       // has not had its references scanned.  Such an object must have
3380       // its references (including type metadata) scanned to ensure no
3381       // live objects are missed by the marking process.  Objects
3382       // allocated after the start of concurrent marking don't need to
3383       // be scanned.
3384       //
3385       // * An object must not be reclaimed if it is on the concurrent
3386       // mark stack.  Objects allocated after the start of concurrent
3387       // marking are never pushed on the mark stack.
3388       //
3389       // Nominating only objects allocated after the start of concurrent
3390       // marking is sufficient to meet both constraints.  This may miss
3391       // some objects that satisfy the constraints, but the marking data
3392       // structures don't support efficiently performing the needed
3393       // additional tests or scrubbing of the mark stack.
3394       //
3395       // However, we presently only nominate is_typeArray() objects.
3396       // A humongous object containing references induces remembered
3397       // set entries on other regions.  In order to reclaim such an
3398       // object, those remembered sets would need to be cleaned up.
3399       //
3400       // We also treat is_typeArray() objects specially, allowing them
3401       // to be reclaimed even if allocated before the start of
3402       // concurrent mark.  For this we rely on mark stack insertion to
3403       // exclude is_typeArray() objects, preventing reclaiming an object
3404       // that is in the mark stack.  We also rely on the metadata for
3405       // such objects to be built-in and so ensured to be kept live.
3406       // Frequent allocation and drop of large binary blobs is an
3407       // important use case for eager reclaim, and this special handling
3408       // may reduce needed headroom.
3409 
3410       return obj->is_typeArray() &&
3411              _g1h->is_potential_eager_reclaim_candidate(region);
3412     }
3413 
3414   public:
3415     G1PrepareRegionsClosure(G1CollectedHeap* g1h, G1PrepareEvacuationTask* parent_task) :
3416       _g1h(g1h),
3417       _parent_task(parent_task),
3418       _worker_humongous_total(0),
3419       _worker_humongous_candidates(0) { }
3420 
3421     ~G1PrepareRegionsClosure() {
3422       _parent_task->add_humongous_candidates(_worker_humongous_candidates);
3423       _parent_task->add_humongous_total(_worker_humongous_total);
3424     }
3425 
3426     virtual bool do_heap_region(HeapRegion* hr) {
3427       // First prepare the region for scanning
3428       _g1h->rem_set()->prepare_region_for_scan(hr);
3429 
3430       // Now check if region is a humongous candidate
3431       if (!hr->is_starts_humongous()) {
3432         _g1h->register_region_with_region_attr(hr);
3433         return false;
3434       }
3435 
3436       uint index = hr->hrm_index();
3437       if (humongous_region_is_candidate(hr)) {
3438         _g1h->set_humongous_reclaim_candidate(index, true);
3439         _g1h->register_humongous_region_with_region_attr(index);
3440         _worker_humongous_candidates++;
3441         // We will later handle the remembered sets of these regions.
3442       } else {
3443         _g1h->set_humongous_reclaim_candidate(index, false);
3444         _g1h->register_region_with_region_attr(hr);
3445       }
3446       log_debug(gc, humongous)("Humongous region %u (object size " SIZE_FORMAT " @ " PTR_FORMAT ") remset " SIZE_FORMAT " code roots " SIZE_FORMAT " marked %d reclaim candidate %d type array %d",
3447                                index,
3448                                (size_t)cast_to_oop(hr->bottom())->size() * HeapWordSize,
3449                                p2i(hr->bottom()),
3450                                hr->rem_set()->occupied(),
3451                                hr->rem_set()->strong_code_roots_list_length(),
3452                                _g1h->concurrent_mark()->next_mark_bitmap()->is_marked(hr->bottom()),
3453                                _g1h->is_humongous_reclaim_candidate(index),
3454                                cast_to_oop(hr->bottom())->is_typeArray()
3455                               );
3456       _worker_humongous_total++;
3457 
3458       return false;
3459     }
3460   };
3461 
3462   G1CollectedHeap* _g1h;
3463   HeapRegionClaimer _claimer;
3464   volatile uint _humongous_total;
3465   volatile uint _humongous_candidates;
3466 public:
3467   G1PrepareEvacuationTask(G1CollectedHeap* g1h) :
3468     AbstractGangTask("Prepare Evacuation"),
3469     _g1h(g1h),
3470     _claimer(_g1h->workers()->active_workers()),
3471     _humongous_total(0),
3472     _humongous_candidates(0) { }
3473 
3474   void work(uint worker_id) {
3475     G1PrepareRegionsClosure cl(_g1h, this);
3476     _g1h->heap_region_par_iterate_from_worker_offset(&cl, &_claimer, worker_id);
3477   }
3478 
3479   void add_humongous_candidates(uint candidates) {
3480     Atomic::add(&_humongous_candidates, candidates);
3481   }
3482 
3483   void add_humongous_total(uint total) {
3484     Atomic::add(&_humongous_total, total);
3485   }
3486 
3487   uint humongous_candidates() {
3488     return _humongous_candidates;
3489   }
3490 
3491   uint humongous_total() {
3492     return _humongous_total;
3493   }
3494 };
3495 
3496 void G1CollectedHeap::pre_evacuate_collection_set(G1EvacuationInfo& evacuation_info, G1ParScanThreadStateSet* per_thread_states) {
3497   _bytes_used_during_gc = 0;
3498 
3499   _expand_heap_after_alloc_failure = true;
3500   Atomic::store(&_num_regions_failed_evacuation, 0u);
3501 
3502   memset((void*)_regions_failed_evacuation, false, sizeof(bool) * max_regions());
3503 
3504   // Disable the hot card cache.
3505   _hot_card_cache->reset_hot_cache_claimed_index();
3506   _hot_card_cache->set_use_cache(false);
3507 
3508   // Initialize the GC alloc regions.
3509   _allocator->init_gc_alloc_regions(evacuation_info);
3510 
3511   {
3512     Ticks start = Ticks::now();
3513     rem_set()->prepare_for_scan_heap_roots();
3514     phase_times()->record_prepare_heap_roots_time_ms((Ticks::now() - start).seconds() * 1000.0);
3515   }
3516 
3517   {
3518     G1PrepareEvacuationTask g1_prep_task(this);
3519     Tickspan task_time = run_task_timed(&g1_prep_task);
3520 
3521     phase_times()->record_register_regions(task_time.seconds() * 1000.0);
3522     _num_humongous_objects = g1_prep_task.humongous_total();
3523     _num_humongous_reclaim_candidates = g1_prep_task.humongous_candidates();
3524   }
3525 
3526   assert(_verifier->check_region_attr_table(), "Inconsistency in the region attributes table.");
3527   _preserved_marks_set.assert_empty();
3528 
3529 #if COMPILER2_OR_JVMCI
3530   DerivedPointerTable::clear();
3531 #endif
3532 
3533   // Concurrent start needs claim bits to keep track of the marked-through CLDs.
3534   if (collector_state()->in_concurrent_start_gc()) {
3535     concurrent_mark()->pre_concurrent_start(gc_cause());
3536 
3537     double start_clear_claimed_marks = os::elapsedTime();
3538 
3539     ClassLoaderDataGraph::clear_claimed_marks();
3540 
3541     double recorded_clear_claimed_marks_time_ms = (os::elapsedTime() - start_clear_claimed_marks) * 1000.0;
3542     phase_times()->record_clear_claimed_marks_time_ms(recorded_clear_claimed_marks_time_ms);
3543   }
3544 
3545   // Should G1EvacuationFailureALot be in effect for this GC?
3546   NOT_PRODUCT(set_evacuation_failure_alot_for_current_gc();)
3547 }
3548 
3549 class G1EvacuateRegionsBaseTask : public AbstractGangTask {
3550 protected:
3551   G1CollectedHeap* _g1h;
3552   G1ParScanThreadStateSet* _per_thread_states;
3553   G1ScannerTasksQueueSet* _task_queues;
3554   TaskTerminator _terminator;
3555   uint _num_workers;
3556 
3557   void evacuate_live_objects(G1ParScanThreadState* pss,
3558                              uint worker_id,
3559                              G1GCPhaseTimes::GCParPhases objcopy_phase,
3560                              G1GCPhaseTimes::GCParPhases termination_phase) {
3561     G1GCPhaseTimes* p = _g1h->phase_times();
3562 
3563     Ticks start = Ticks::now();
3564     G1ParEvacuateFollowersClosure cl(_g1h, pss, _task_queues, &_terminator, objcopy_phase);
3565     cl.do_void();
3566 
3567     assert(pss->queue_is_empty(), "should be empty");
3568 
3569     Tickspan evac_time = (Ticks::now() - start);
3570     p->record_or_add_time_secs(objcopy_phase, worker_id, evac_time.seconds() - cl.term_time());
3571 
3572     if (termination_phase == G1GCPhaseTimes::Termination) {
3573       p->record_time_secs(termination_phase, worker_id, cl.term_time());
3574       p->record_thread_work_item(termination_phase, worker_id, cl.term_attempts());
3575     } else {
3576       p->record_or_add_time_secs(termination_phase, worker_id, cl.term_time());
3577       p->record_or_add_thread_work_item(termination_phase, worker_id, cl.term_attempts());
3578     }
3579     assert(pss->trim_ticks().value() == 0,
3580            "Unexpected partial trimming during evacuation value " JLONG_FORMAT,
3581            pss->trim_ticks().value());
3582   }
3583 
3584   virtual void start_work(uint worker_id) { }
3585 
3586   virtual void end_work(uint worker_id) { }
3587 
3588   virtual void scan_roots(G1ParScanThreadState* pss, uint worker_id) = 0;
3589 
3590   virtual void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) = 0;
3591 
3592 public:
3593   G1EvacuateRegionsBaseTask(const char* name,
3594                             G1ParScanThreadStateSet* per_thread_states,
3595                             G1ScannerTasksQueueSet* task_queues,
3596                             uint num_workers) :
3597     AbstractGangTask(name),
3598     _g1h(G1CollectedHeap::heap()),
3599     _per_thread_states(per_thread_states),
3600     _task_queues(task_queues),
3601     _terminator(num_workers, _task_queues),
3602     _num_workers(num_workers)
3603   { }
3604 
3605   void work(uint worker_id) {
3606     start_work(worker_id);
3607 
3608     {
3609       ResourceMark rm;
3610 
3611       G1ParScanThreadState* pss = _per_thread_states->state_for_worker(worker_id);
3612       pss->set_ref_discoverer(_g1h->ref_processor_stw());
3613 
3614       scan_roots(pss, worker_id);
3615       evacuate_live_objects(pss, worker_id);
3616     }
3617 
3618     end_work(worker_id);
3619   }
3620 };
3621 
3622 class G1EvacuateRegionsTask : public G1EvacuateRegionsBaseTask {
3623   G1RootProcessor* _root_processor;
3624   bool _has_optional_evacuation_work;
3625 
3626   void scan_roots(G1ParScanThreadState* pss, uint worker_id) {
3627     _root_processor->evacuate_roots(pss, worker_id);
3628     _g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::ScanHR, G1GCPhaseTimes::ObjCopy, _has_optional_evacuation_work);
3629     _g1h->rem_set()->scan_collection_set_regions(pss, worker_id, G1GCPhaseTimes::ScanHR, G1GCPhaseTimes::CodeRoots, G1GCPhaseTimes::ObjCopy);
3630   }
3631 
3632   void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) {
3633     G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::ObjCopy, G1GCPhaseTimes::Termination);
3634   }
3635 
3636   void start_work(uint worker_id) {
3637     _g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerStart, worker_id, Ticks::now().seconds());
3638   }
3639 
3640   void end_work(uint worker_id) {
3641     _g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerEnd, worker_id, Ticks::now().seconds());
3642   }
3643 
3644 public:
3645   G1EvacuateRegionsTask(G1CollectedHeap* g1h,
3646                         G1ParScanThreadStateSet* per_thread_states,
3647                         G1ScannerTasksQueueSet* task_queues,
3648                         G1RootProcessor* root_processor,
3649                         uint num_workers,
3650                         bool has_optional_evacuation_work) :
3651     G1EvacuateRegionsBaseTask("G1 Evacuate Regions", per_thread_states, task_queues, num_workers),
3652     _root_processor(root_processor),
3653     _has_optional_evacuation_work(has_optional_evacuation_work)
3654   { }
3655 };
3656 
3657 void G1CollectedHeap::evacuate_initial_collection_set(G1ParScanThreadStateSet* per_thread_states,
3658                                                       bool has_optional_evacuation_work) {
3659   G1GCPhaseTimes* p = phase_times();
3660 
3661   {
3662     Ticks start = Ticks::now();
3663     rem_set()->merge_heap_roots(true /* initial_evacuation */);
3664     p->record_merge_heap_roots_time((Ticks::now() - start).seconds() * 1000.0);
3665   }
3666 
3667   Tickspan task_time;
3668   const uint num_workers = workers()->active_workers();
3669 
3670   Ticks start_processing = Ticks::now();
3671   {
3672     G1RootProcessor root_processor(this, num_workers);
3673     G1EvacuateRegionsTask g1_par_task(this,
3674                                       per_thread_states,
3675                                       _task_queues,
3676                                       &root_processor,
3677                                       num_workers,
3678                                       has_optional_evacuation_work);
3679     task_time = run_task_timed(&g1_par_task);
3680     // Closing the inner scope will execute the destructor for the G1RootProcessor object.
3681     // To extract its code root fixup time we measure total time of this scope and
3682     // subtract from the time the WorkGang task took.
3683   }
3684   Tickspan total_processing = Ticks::now() - start_processing;
3685 
3686   p->record_initial_evac_time(task_time.seconds() * 1000.0);
3687   p->record_or_add_code_root_fixup_time((total_processing - task_time).seconds() * 1000.0);
3688 
3689   rem_set()->complete_evac_phase(has_optional_evacuation_work);
3690 }
3691 
3692 class G1EvacuateOptionalRegionsTask : public G1EvacuateRegionsBaseTask {
3693 
3694   void scan_roots(G1ParScanThreadState* pss, uint worker_id) {
3695     _g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::OptObjCopy, true /* remember_already_scanned_cards */);
3696     _g1h->rem_set()->scan_collection_set_regions(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::OptCodeRoots, G1GCPhaseTimes::OptObjCopy);
3697   }
3698 
3699   void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) {
3700     G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::OptObjCopy, G1GCPhaseTimes::OptTermination);
3701   }
3702 
3703 public:
3704   G1EvacuateOptionalRegionsTask(G1ParScanThreadStateSet* per_thread_states,
3705                                 G1ScannerTasksQueueSet* queues,
3706                                 uint num_workers) :
3707     G1EvacuateRegionsBaseTask("G1 Evacuate Optional Regions", per_thread_states, queues, num_workers) {
3708   }
3709 };
3710 
3711 void G1CollectedHeap::evacuate_next_optional_regions(G1ParScanThreadStateSet* per_thread_states) {
3712   class G1MarkScope : public MarkScope { };
3713 
3714   Tickspan task_time;
3715 
3716   Ticks start_processing = Ticks::now();
3717   {
3718     G1MarkScope code_mark_scope;
3719     G1EvacuateOptionalRegionsTask task(per_thread_states, _task_queues, workers()->active_workers());
3720     task_time = run_task_timed(&task);
3721     // See comment in evacuate_collection_set() for the reason of the scope.
3722   }
3723   Tickspan total_processing = Ticks::now() - start_processing;
3724 
3725   G1GCPhaseTimes* p = phase_times();
3726   p->record_or_add_code_root_fixup_time((total_processing - task_time).seconds() * 1000.0);
3727 }
3728 
3729 void G1CollectedHeap::evacuate_optional_collection_set(G1ParScanThreadStateSet* per_thread_states) {
3730   const double gc_start_time_ms = phase_times()->cur_collection_start_sec() * 1000.0;
3731 
3732   while (!evacuation_failed() && _collection_set.optional_region_length() > 0) {
3733 
3734     double time_used_ms = os::elapsedTime() * 1000.0 - gc_start_time_ms;
3735     double time_left_ms = MaxGCPauseMillis - time_used_ms;
3736 
3737     if (time_left_ms < 0 ||
3738         !_collection_set.finalize_optional_for_evacuation(time_left_ms * policy()->optional_evacuation_fraction())) {
3739       log_trace(gc, ergo, cset)("Skipping evacuation of %u optional regions, no more regions can be evacuated in %.3fms",
3740                                 _collection_set.optional_region_length(), time_left_ms);
3741       break;
3742     }
3743 
3744     {
3745       Ticks start = Ticks::now();
3746       rem_set()->merge_heap_roots(false /* initial_evacuation */);
3747       phase_times()->record_or_add_optional_merge_heap_roots_time((Ticks::now() - start).seconds() * 1000.0);
3748     }
3749 
3750     {
3751       Ticks start = Ticks::now();
3752       evacuate_next_optional_regions(per_thread_states);
3753       phase_times()->record_or_add_optional_evac_time((Ticks::now() - start).seconds() * 1000.0);
3754     }
3755 
3756     rem_set()->complete_evac_phase(true /* has_more_than_one_evacuation_phase */);
3757   }
3758 
3759   _collection_set.abandon_optional_collection_set(per_thread_states);
3760 }
3761 
3762 void G1CollectedHeap::post_evacuate_collection_set(G1EvacuationInfo& evacuation_info,
3763                                                    G1RedirtyCardsQueueSet* rdcqs,
3764                                                    G1ParScanThreadStateSet* per_thread_states) {
3765   G1GCPhaseTimes* p = phase_times();
3766 
3767   // Process any discovered reference objects - we have
3768   // to do this _before_ we retire the GC alloc regions
3769   // as we may have to copy some 'reachable' referent
3770   // objects (and their reachable sub-graphs) that were
3771   // not copied during the pause.
3772   process_discovered_references(per_thread_states);
3773 
3774   G1STWIsAliveClosure is_alive(this);
3775   G1KeepAliveClosure keep_alive(this);
3776 
3777   WeakProcessor::weak_oops_do(workers(), &is_alive, &keep_alive, p->weak_phase_times());
3778 
3779   _allocator->release_gc_alloc_regions(evacuation_info);
3780 
3781   post_evacuate_cleanup_1(per_thread_states, rdcqs);
3782 
3783   post_evacuate_cleanup_2(&_preserved_marks_set, rdcqs, &evacuation_info, per_thread_states->surviving_young_words());
3784 
3785   assert_used_and_recalculate_used_equal(this);
3786 
3787   rebuild_free_region_list();
3788 
3789   record_obj_copy_mem_stats();
3790 
3791   evacuation_info.set_collectionset_used_before(collection_set()->bytes_used_before());
3792   evacuation_info.set_bytes_used(_bytes_used_during_gc);
3793 
3794   policy()->print_age_table();
3795 }
3796 
3797 void G1CollectedHeap::record_obj_copy_mem_stats() {
3798   policy()->old_gen_alloc_tracker()->
3799     add_allocated_bytes_since_last_gc(_old_evac_stats.allocated() * HeapWordSize);
3800 
3801   _gc_tracer_stw->report_evacuation_statistics(create_g1_evac_summary(&_survivor_evac_stats),
3802                                                create_g1_evac_summary(&_old_evac_stats));
3803 }
3804 
3805 void G1CollectedHeap::free_region(HeapRegion* hr, FreeRegionList* free_list) {
3806   assert(!hr->is_free(), "the region should not be free");
3807   assert(!hr->is_empty(), "the region should not be empty");
3808   assert(_hrm.is_available(hr->hrm_index()), "region should be committed");
3809 
3810   if (G1VerifyBitmaps) {
3811     MemRegion mr(hr->bottom(), hr->end());
3812     concurrent_mark()->clear_range_in_prev_bitmap(mr);
3813   }
3814 
3815   // Clear the card counts for this region.
3816   // Note: we only need to do this if the region is not young
3817   // (since we don't refine cards in young regions).
3818   if (!hr->is_young()) {
3819     _hot_card_cache->reset_card_counts(hr);
3820   }
3821 
3822   // Reset region metadata to allow reuse.
3823   hr->hr_clear(true /* clear_space */);
3824   _policy->remset_tracker()->update_at_free(hr);
3825 
3826   if (free_list != NULL) {
3827     free_list->add_ordered(hr);
3828   }
3829 }
3830 
3831 void G1CollectedHeap::free_humongous_region(HeapRegion* hr,
3832                                             FreeRegionList* free_list) {
3833   assert(hr->is_humongous(), "this is only for humongous regions");
3834   hr->clear_humongous();
3835   free_region(hr, free_list);
3836 }
3837 
3838 void G1CollectedHeap::remove_from_old_gen_sets(const uint old_regions_removed,
3839                                                const uint archive_regions_removed,
3840                                                const uint humongous_regions_removed) {
3841   if (old_regions_removed > 0 || archive_regions_removed > 0 || humongous_regions_removed > 0) {
3842     MutexLocker x(OldSets_lock, Mutex::_no_safepoint_check_flag);
3843     _old_set.bulk_remove(old_regions_removed);
3844     _archive_set.bulk_remove(archive_regions_removed);
3845     _humongous_set.bulk_remove(humongous_regions_removed);
3846   }
3847 
3848 }
3849 
3850 void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) {
3851   assert(list != NULL, "list can't be null");
3852   if (!list->is_empty()) {
3853     MutexLocker x(FreeList_lock, Mutex::_no_safepoint_check_flag);
3854     _hrm.insert_list_into_free_list(list);
3855   }
3856 }
3857 
3858 void G1CollectedHeap::decrement_summary_bytes(size_t bytes) {
3859   decrease_used(bytes);
3860 }
3861 
3862 void G1CollectedHeap::post_evacuate_cleanup_1(G1ParScanThreadStateSet* per_thread_states,
3863                                               G1RedirtyCardsQueueSet* rdcqs) {
3864   Ticks start = Ticks::now();
3865   {
3866     G1PostEvacuateCollectionSetCleanupTask1 cl(per_thread_states, rdcqs);
3867     run_batch_task(&cl);
3868   }
3869   phase_times()->record_post_evacuate_cleanup_task_1_time((Ticks::now() - start).seconds() * 1000.0);
3870 }
3871 
3872 void G1CollectedHeap::post_evacuate_cleanup_2(PreservedMarksSet* preserved_marks,
3873                                               G1RedirtyCardsQueueSet* rdcqs,
3874                                               G1EvacuationInfo* evacuation_info,
3875                                               const size_t* surviving_young_words) {
3876   Ticks start = Ticks::now();
3877   {
3878     G1PostEvacuateCollectionSetCleanupTask2 cl(preserved_marks, rdcqs, evacuation_info, surviving_young_words);
3879     run_batch_task(&cl);
3880   }
3881   phase_times()->record_post_evacuate_cleanup_task_2_time((Ticks::now() - start).seconds() * 1000.0);
3882 }
3883 
3884 void G1CollectedHeap::clear_eden() {
3885   _eden.clear();
3886 }
3887 
3888 void G1CollectedHeap::clear_collection_set() {
3889   collection_set()->clear();
3890 }
3891 
3892 void G1CollectedHeap::rebuild_free_region_list() {
3893   Ticks start = Ticks::now();
3894   _hrm.rebuild_free_list(workers());
3895   phase_times()->record_total_rebuild_freelist_time_ms((Ticks::now() - start).seconds() * 1000.0);
3896 }
3897 
3898 class G1AbandonCollectionSetClosure : public HeapRegionClosure {
3899 public:
3900   virtual bool do_heap_region(HeapRegion* r) {
3901     assert(r->in_collection_set(), "Region %u must have been in collection set", r->hrm_index());
3902     G1CollectedHeap::heap()->clear_region_attr(r);
3903     r->clear_young_index_in_cset();
3904     return false;
3905   }
3906 };
3907 
3908 void G1CollectedHeap::abandon_collection_set(G1CollectionSet* collection_set) {
3909   G1AbandonCollectionSetClosure cl;
3910   collection_set_iterate_all(&cl);
3911 
3912   collection_set->clear();
3913   collection_set->stop_incremental_building();
3914 }
3915 
3916 bool G1CollectedHeap::is_old_gc_alloc_region(HeapRegion* hr) {
3917   return _allocator->is_retained_old_region(hr);
3918 }
3919 
3920 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) {
3921   _eden.add(hr);
3922   _policy->set_region_eden(hr);
3923 }
3924 
3925 #ifdef ASSERT
3926 
3927 class NoYoungRegionsClosure: public HeapRegionClosure {
3928 private:
3929   bool _success;
3930 public:
3931   NoYoungRegionsClosure() : _success(true) { }
3932   bool do_heap_region(HeapRegion* r) {
3933     if (r->is_young()) {
3934       log_error(gc, verify)("Region [" PTR_FORMAT ", " PTR_FORMAT ") tagged as young",
3935                             p2i(r->bottom()), p2i(r->end()));
3936       _success = false;
3937     }
3938     return false;
3939   }
3940   bool success() { return _success; }
3941 };
3942 
3943 bool G1CollectedHeap::check_young_list_empty() {
3944   bool ret = (young_regions_count() == 0);
3945 
3946   NoYoungRegionsClosure closure;
3947   heap_region_iterate(&closure);
3948   ret = ret && closure.success();
3949 
3950   return ret;
3951 }
3952 
3953 #endif // ASSERT
3954 
3955 // Remove the given HeapRegion from the appropriate region set.
3956 void G1CollectedHeap::prepare_region_for_full_compaction(HeapRegion* hr) {
3957    if (hr->is_archive()) {
3958     _archive_set.remove(hr);
3959   } else if (hr->is_humongous()) {
3960     _humongous_set.remove(hr);
3961   } else if (hr->is_old()) {
3962     _old_set.remove(hr);
3963   } else if (hr->is_young()) {
3964     // Note that emptying the eden and survivor lists is postponed and instead
3965     // done as the first step when rebuilding the regions sets again. The reason
3966     // for this is that during a full GC string deduplication needs to know if
3967     // a collected region was young or old when the full GC was initiated.
3968     hr->uninstall_surv_rate_group();
3969   } else {
3970     // We ignore free regions, we'll empty the free list afterwards.
3971     assert(hr->is_free(), "it cannot be another type");
3972   }
3973 }
3974 
3975 void G1CollectedHeap::increase_used(size_t bytes) {
3976   _summary_bytes_used += bytes;
3977 }
3978 
3979 void G1CollectedHeap::decrease_used(size_t bytes) {
3980   assert(_summary_bytes_used >= bytes,
3981          "invariant: _summary_bytes_used: " SIZE_FORMAT " should be >= bytes: " SIZE_FORMAT,
3982          _summary_bytes_used, bytes);
3983   _summary_bytes_used -= bytes;
3984 }
3985 
3986 void G1CollectedHeap::set_used(size_t bytes) {
3987   _summary_bytes_used = bytes;
3988 }
3989 
3990 class RebuildRegionSetsClosure : public HeapRegionClosure {
3991 private:
3992   bool _free_list_only;
3993 
3994   HeapRegionSet* _old_set;
3995   HeapRegionSet* _archive_set;
3996   HeapRegionSet* _humongous_set;
3997 
3998   HeapRegionManager* _hrm;
3999 
4000   size_t _total_used;
4001 
4002 public:
4003   RebuildRegionSetsClosure(bool free_list_only,
4004                            HeapRegionSet* old_set,
4005                            HeapRegionSet* archive_set,
4006                            HeapRegionSet* humongous_set,
4007                            HeapRegionManager* hrm) :
4008     _free_list_only(free_list_only), _old_set(old_set), _archive_set(archive_set),
4009     _humongous_set(humongous_set), _hrm(hrm), _total_used(0) {
4010     assert(_hrm->num_free_regions() == 0, "pre-condition");
4011     if (!free_list_only) {
4012       assert(_old_set->is_empty(), "pre-condition");
4013       assert(_archive_set->is_empty(), "pre-condition");
4014       assert(_humongous_set->is_empty(), "pre-condition");
4015     }
4016   }
4017 
4018   bool do_heap_region(HeapRegion* r) {
4019     if (r->is_empty()) {
4020       assert(r->rem_set()->is_empty(), "Empty regions should have empty remembered sets.");
4021       // Add free regions to the free list
4022       r->set_free();
4023       _hrm->insert_into_free_list(r);
4024     } else if (!_free_list_only) {
4025       assert(r->rem_set()->is_empty(), "At this point remembered sets must have been cleared.");
4026 
4027       if (r->is_humongous()) {
4028         _humongous_set->add(r);
4029       } else if (r->is_archive()) {
4030         _archive_set->add(r);
4031       } else {
4032         assert(r->is_young() || r->is_free() || r->is_old(), "invariant");
4033         // We now move all (non-humongous, non-old, non-archive) regions to old gen,
4034         // and register them as such.
4035         r->move_to_old();
4036         _old_set->add(r);
4037       }
4038       _total_used += r->used();
4039     }
4040 
4041     return false;
4042   }
4043 
4044   size_t total_used() {
4045     return _total_used;
4046   }
4047 };
4048 
4049 void G1CollectedHeap::rebuild_region_sets(bool free_list_only) {
4050   assert_at_safepoint_on_vm_thread();
4051 
4052   if (!free_list_only) {
4053     _eden.clear();
4054     _survivor.clear();
4055   }
4056 
4057   RebuildRegionSetsClosure cl(free_list_only,
4058                               &_old_set, &_archive_set, &_humongous_set,
4059                               &_hrm);
4060   heap_region_iterate(&cl);
4061 
4062   if (!free_list_only) {
4063     set_used(cl.total_used());
4064     if (_archive_allocator != NULL) {
4065       _archive_allocator->clear_used();
4066     }
4067   }
4068   assert_used_and_recalculate_used_equal(this);
4069 }
4070 
4071 // Methods for the mutator alloc region
4072 
4073 HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size,
4074                                                       bool force,
4075                                                       uint node_index) {
4076   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
4077   bool should_allocate = policy()->should_allocate_mutator_region();
4078   if (force || should_allocate) {
4079     HeapRegion* new_alloc_region = new_region(word_size,
4080                                               HeapRegionType::Eden,
4081                                               false /* do_expand */,
4082                                               node_index);
4083     if (new_alloc_region != NULL) {
4084       set_region_short_lived_locked(new_alloc_region);
4085       _hr_printer.alloc(new_alloc_region, !should_allocate);
4086       _verifier->check_bitmaps("Mutator Region Allocation", new_alloc_region);
4087       _policy->remset_tracker()->update_at_allocate(new_alloc_region);
4088       return new_alloc_region;
4089     }
4090   }
4091   return NULL;
4092 }
4093 
4094 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region,
4095                                                   size_t allocated_bytes) {
4096   assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */);
4097   assert(alloc_region->is_eden(), "all mutator alloc regions should be eden");
4098 
4099   collection_set()->add_eden_region(alloc_region);
4100   increase_used(allocated_bytes);
4101   _eden.add_used_bytes(allocated_bytes);
4102   _hr_printer.retire(alloc_region);
4103 
4104   // We update the eden sizes here, when the region is retired,
4105   // instead of when it's allocated, since this is the point that its
4106   // used space has been recorded in _summary_bytes_used.
4107   g1mm()->update_eden_size();
4108 }
4109 
4110 // Methods for the GC alloc regions
4111 
4112 bool G1CollectedHeap::has_more_regions(G1HeapRegionAttr dest) {
4113   if (dest.is_old()) {
4114     return true;
4115   } else {
4116     return survivor_regions_count() < policy()->max_survivor_regions();
4117   }
4118 }
4119 
4120 HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size, G1HeapRegionAttr dest, uint node_index) {
4121   assert(FreeList_lock->owned_by_self(), "pre-condition");
4122 
4123   if (!has_more_regions(dest)) {
4124     return NULL;
4125   }
4126 
4127   HeapRegionType type;
4128   if (dest.is_young()) {
4129     type = HeapRegionType::Survivor;
4130   } else {
4131     type = HeapRegionType::Old;
4132   }
4133 
4134   HeapRegion* new_alloc_region = new_region(word_size,
4135                                             type,
4136                                             true /* do_expand */,
4137                                             node_index);
4138 
4139   if (new_alloc_region != NULL) {
4140     if (type.is_survivor()) {
4141       new_alloc_region->set_survivor();
4142       _survivor.add(new_alloc_region);
4143       _verifier->check_bitmaps("Survivor Region Allocation", new_alloc_region);
4144     } else {
4145       new_alloc_region->set_old();
4146       _verifier->check_bitmaps("Old Region Allocation", new_alloc_region);
4147     }
4148     _policy->remset_tracker()->update_at_allocate(new_alloc_region);
4149     register_region_with_region_attr(new_alloc_region);
4150     _hr_printer.alloc(new_alloc_region);
4151     return new_alloc_region;
4152   }
4153   return NULL;
4154 }
4155 
4156 void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region,
4157                                              size_t allocated_bytes,
4158                                              G1HeapRegionAttr dest) {
4159   _bytes_used_during_gc += allocated_bytes;
4160   if (dest.is_old()) {
4161     old_set_add(alloc_region);
4162   } else {
4163     assert(dest.is_young(), "Retiring alloc region should be young (%d)", dest.type());
4164     _survivor.add_used_bytes(allocated_bytes);
4165   }
4166 
4167   bool const during_im = collector_state()->in_concurrent_start_gc();
4168   if (during_im && allocated_bytes > 0) {
4169     _cm->root_regions()->add(alloc_region->next_top_at_mark_start(), alloc_region->top());
4170   }
4171   _hr_printer.retire(alloc_region);
4172 }
4173 
4174 HeapRegion* G1CollectedHeap::alloc_highest_free_region() {
4175   bool expanded = false;
4176   uint index = _hrm.find_highest_free(&expanded);
4177 
4178   if (index != G1_NO_HRM_INDEX) {
4179     if (expanded) {
4180       log_debug(gc, ergo, heap)("Attempt heap expansion (requested address range outside heap bounds). region size: " SIZE_FORMAT "B",
4181                                 HeapRegion::GrainWords * HeapWordSize);
4182     }
4183     return _hrm.allocate_free_regions_starting_at(index, 1);
4184   }
4185   return NULL;
4186 }
4187 
4188 // Optimized nmethod scanning
4189 
4190 class RegisterNMethodOopClosure: public OopClosure {
4191   G1CollectedHeap* _g1h;
4192   nmethod* _nm;
4193 
4194   template <class T> void do_oop_work(T* p) {
4195     T heap_oop = RawAccess<>::oop_load(p);
4196     if (!CompressedOops::is_null(heap_oop)) {
4197       oop obj = CompressedOops::decode_not_null(heap_oop);
4198       HeapRegion* hr = _g1h->heap_region_containing(obj);
4199       assert(!hr->is_continues_humongous(),
4200              "trying to add code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT
4201              " starting at " HR_FORMAT,
4202              p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()));
4203 
4204       // HeapRegion::add_strong_code_root_locked() avoids adding duplicate entries.
4205       hr->add_strong_code_root_locked(_nm);
4206     }
4207   }
4208 
4209 public:
4210   RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
4211     _g1h(g1h), _nm(nm) {}
4212 
4213   void do_oop(oop* p)       { do_oop_work(p); }
4214   void do_oop(narrowOop* p) { do_oop_work(p); }
4215 };
4216 
4217 class UnregisterNMethodOopClosure: public OopClosure {
4218   G1CollectedHeap* _g1h;
4219   nmethod* _nm;
4220 
4221   template <class T> void do_oop_work(T* p) {
4222     T heap_oop = RawAccess<>::oop_load(p);
4223     if (!CompressedOops::is_null(heap_oop)) {
4224       oop obj = CompressedOops::decode_not_null(heap_oop);
4225       HeapRegion* hr = _g1h->heap_region_containing(obj);
4226       assert(!hr->is_continues_humongous(),
4227              "trying to remove code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT
4228              " starting at " HR_FORMAT,
4229              p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()));
4230 
4231       hr->remove_strong_code_root(_nm);
4232     }
4233   }
4234 
4235 public:
4236   UnregisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) :
4237     _g1h(g1h), _nm(nm) {}
4238 
4239   void do_oop(oop* p)       { do_oop_work(p); }
4240   void do_oop(narrowOop* p) { do_oop_work(p); }
4241 };
4242 
4243 void G1CollectedHeap::register_nmethod(nmethod* nm) {
4244   guarantee(nm != NULL, "sanity");
4245   RegisterNMethodOopClosure reg_cl(this, nm);
4246   nm->oops_do(&reg_cl);
4247 }
4248 
4249 void G1CollectedHeap::unregister_nmethod(nmethod* nm) {
4250   guarantee(nm != NULL, "sanity");
4251   UnregisterNMethodOopClosure reg_cl(this, nm);
4252   nm->oops_do(&reg_cl, true);
4253 }
4254 
4255 void G1CollectedHeap::update_used_after_gc() {
4256   if (evacuation_failed()) {
4257     // Reset the G1EvacuationFailureALot counters and flags
4258     NOT_PRODUCT(reset_evacuation_should_fail();)
4259 
4260     set_used(recalculate_used());
4261 
4262     if (_archive_allocator != NULL) {
4263       _archive_allocator->clear_used();
4264     }
4265     for (uint i = 0; i < ParallelGCThreads; i++) {
4266       if (_evacuation_failed_info_array[i].has_failed()) {
4267         _gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]);
4268       }
4269     }
4270   } else {
4271     // The "used" of the the collection set have already been subtracted
4272     // when they were freed.  Add in the bytes used.
4273     increase_used(_bytes_used_during_gc);
4274   }
4275 }
4276 
4277 void G1CollectedHeap::reset_hot_card_cache() {
4278   _hot_card_cache->reset_hot_cache();
4279   _hot_card_cache->set_use_cache(true);
4280 }
4281 
4282 void G1CollectedHeap::purge_code_root_memory() {
4283   G1CodeRootSet::purge();
4284 }
4285 
4286 class RebuildStrongCodeRootClosure: public CodeBlobClosure {
4287   G1CollectedHeap* _g1h;
4288 
4289 public:
4290   RebuildStrongCodeRootClosure(G1CollectedHeap* g1h) :
4291     _g1h(g1h) {}
4292 
4293   void do_code_blob(CodeBlob* cb) {
4294     nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL;
4295     if (nm == NULL) {
4296       return;
4297     }
4298 
4299     _g1h->register_nmethod(nm);
4300   }
4301 };
4302 
4303 void G1CollectedHeap::rebuild_strong_code_roots() {
4304   RebuildStrongCodeRootClosure blob_cl(this);
4305   CodeCache::blobs_do(&blob_cl);
4306 }
4307 
4308 void G1CollectedHeap::initialize_serviceability() {
4309   _g1mm->initialize_serviceability();
4310 }
4311 
4312 MemoryUsage G1CollectedHeap::memory_usage() {
4313   return _g1mm->memory_usage();
4314 }
4315 
4316 GrowableArray<GCMemoryManager*> G1CollectedHeap::memory_managers() {
4317   return _g1mm->memory_managers();
4318 }
4319 
4320 GrowableArray<MemoryPool*> G1CollectedHeap::memory_pools() {
4321   return _g1mm->memory_pools();
4322 }