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