1 /*
   2  * Copyright (c) 2021, 2026, 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 
  26 #include "classfile/classLoaderDataGraph.inline.hpp"
  27 #include "classfile/javaClasses.inline.hpp"
  28 #include "code/nmethod.hpp"
  29 #include "compiler/oopMap.hpp"
  30 #include "gc/g1/g1Allocator.hpp"
  31 #include "gc/g1/g1CardSetMemory.hpp"
  32 #include "gc/g1/g1CollectedHeap.inline.hpp"
  33 #include "gc/g1/g1CollectionSetCandidates.inline.hpp"
  34 #include "gc/g1/g1CollectorState.inline.hpp"
  35 #include "gc/g1/g1ConcurrentMark.hpp"
  36 #include "gc/g1/g1EvacFailureRegions.inline.hpp"
  37 #include "gc/g1/g1EvacInfo.hpp"
  38 #include "gc/g1/g1GCPhaseTimes.hpp"
  39 #include "gc/g1/g1HeapRegion.inline.hpp"
  40 #include "gc/g1/g1HeapRegionPrinter.hpp"
  41 #include "gc/g1/g1MonitoringSupport.hpp"
  42 #include "gc/g1/g1ParScanThreadState.inline.hpp"
  43 #include "gc/g1/g1Policy.hpp"
  44 #include "gc/g1/g1RegionPinCache.inline.hpp"
  45 #include "gc/g1/g1RemSet.hpp"
  46 #include "gc/g1/g1RootProcessor.hpp"
  47 #include "gc/g1/g1Trace.hpp"
  48 #include "gc/g1/g1YoungCollector.hpp"
  49 #include "gc/g1/g1YoungGCAllocationFailureInjector.hpp"
  50 #include "gc/g1/g1YoungGCPostEvacuateTasks.hpp"
  51 #include "gc/g1/g1YoungGCPreEvacuateTasks.hpp"
  52 #include "gc/shared/concurrentGCBreakpoints.hpp"
  53 #include "gc/shared/gc_globals.hpp"
  54 #include "gc/shared/gcTimer.hpp"
  55 #include "gc/shared/gcTraceTime.inline.hpp"
  56 #include "gc/shared/referenceProcessor.hpp"
  57 #include "gc/shared/weakProcessor.inline.hpp"
  58 #include "gc/shared/workerPolicy.hpp"
  59 #include "gc/shared/workerThread.hpp"
  60 #include "jfr/jfrEvents.hpp"
  61 #include "memory/resourceArea.hpp"
  62 #include "runtime/atomic.hpp"
  63 #include "runtime/threads.hpp"
  64 #include "utilities/ticks.hpp"
  65 
  66 // GCTraceTime wrapper that constructs the message according to GC pause type and
  67 // GC cause.
  68 // The code relies on the fact that GCTraceTimeWrapper stores the string passed
  69 // initially as a reference only, so that we can modify it as needed.
  70 class G1YoungGCTraceTime {
  71   G1YoungCollector* _collector;
  72 
  73   GCCause::Cause _pause_cause;
  74 
  75   static const uint MaxYoungGCNameLength = 128;
  76   char _young_gc_name_data[MaxYoungGCNameLength];
  77 
  78   GCTraceTime(Info, gc) _tt;
  79 
  80   const char* update_young_gc_name() {
  81     char evacuation_failed_string[48];
  82     evacuation_failed_string[0] = '\0';
  83 
  84     if (_collector->evacuation_failed()) {
  85       os::snprintf_checked(evacuation_failed_string,
  86                            ARRAY_SIZE(evacuation_failed_string),
  87                            " (Evacuation Failure: %s%s%s)",
  88                            _collector->evacuation_alloc_failed() ? "Allocation" : "",
  89                            _collector->evacuation_alloc_failed() && _collector->evacuation_pinned() ? " / " : "",
  90                            _collector->evacuation_pinned() ? "Pinned" : "");
  91     }
  92     G1CollectorState::Pause pause = _collector->collector_state()->gc_pause_type(_collector->concurrent_operation_is_full_mark());
  93     os::snprintf_checked(_young_gc_name_data,
  94                          MaxYoungGCNameLength,
  95                          "Pause Young (%s) (%s)%s",
  96                          G1CollectorState::to_string(pause),
  97                          GCCause::to_string(_pause_cause),
  98                          evacuation_failed_string);
  99     return _young_gc_name_data;
 100   }
 101 
 102 public:
 103   G1YoungGCTraceTime(G1YoungCollector* collector, GCCause::Cause cause) :
 104     _collector(collector),
 105     _pause_cause(cause),
 106     // Fake a "no cause" and manually add the correct string in update_young_gc_name()
 107     // to make the string look more natural.
 108     _tt(update_young_gc_name(), nullptr, GCCause::_no_gc, true) {
 109   }
 110 
 111   ~G1YoungGCTraceTime() {
 112     update_young_gc_name();
 113   }
 114 };
 115 
 116 class G1YoungGCNotifyPauseMark : public StackObj {
 117   G1YoungCollector* _collector;
 118 
 119 public:
 120   G1YoungGCNotifyPauseMark(G1YoungCollector* collector) : _collector(collector) {
 121     G1CollectedHeap::heap()->policy()->record_young_gc_pause_start();
 122   }
 123 
 124   ~G1YoungGCNotifyPauseMark() {
 125     G1CollectedHeap::heap()->policy()->record_young_gc_pause_end(_collector->evacuation_failed());
 126   }
 127 };
 128 
 129 class G1YoungGCJFRTracerMark : public G1JFRTracerMark {
 130   G1YoungCollector* _young_collector;
 131   G1EvacInfo _evacuation_info;
 132 
 133   G1NewTracer* tracer() const { return (G1NewTracer*)_tracer; }
 134 
 135 public:
 136   G1EvacInfo* evacuation_info() { return &_evacuation_info; }
 137 
 138   G1YoungGCJFRTracerMark(G1YoungCollector* young_collector) :
 139     G1JFRTracerMark(young_collector->gc_timer_stw(), young_collector->gc_tracer_stw()),
 140     _young_collector(young_collector),
 141     _evacuation_info() { }
 142 
 143   ~G1YoungGCJFRTracerMark() {
 144     G1CollectedHeap* g1h = G1CollectedHeap::heap();
 145 
 146     tracer()->report_young_gc_pause(g1h->collector_state()->gc_pause_type(_young_collector->concurrent_operation_is_full_mark()));
 147     tracer()->report_evacuation_info(&_evacuation_info);
 148     tracer()->report_tenuring_threshold(g1h->policy()->tenuring_threshold());
 149   }
 150 };
 151 
 152 class G1YoungGCVerifierMark : public StackObj {
 153   G1YoungCollector* _collector;
 154   G1HeapVerifier::G1VerifyType _type;
 155 
 156   static G1HeapVerifier::G1VerifyType young_collection_verify_type() {
 157     G1CollectorState* state = G1CollectedHeap::heap()->collector_state();
 158     if (state->is_in_concurrent_start_gc()) {
 159       return G1HeapVerifier::G1VerifyConcurrentStart;
 160     } else if (state->is_in_young_only_phase()) {
 161       return G1HeapVerifier::G1VerifyYoungNormal;
 162     } else {
 163       return G1HeapVerifier::G1VerifyMixed;
 164     }
 165   }
 166 
 167 public:
 168   G1YoungGCVerifierMark(G1YoungCollector* collector) : _collector(collector), _type(young_collection_verify_type()) {
 169     G1CollectedHeap::heap()->verify_before_young_collection(_type);
 170   }
 171 
 172   ~G1YoungGCVerifierMark() {
 173     // Inject evacuation failure tag into type if needed.
 174     G1HeapVerifier::G1VerifyType type = _type;
 175     if (_collector->evacuation_failed()) {
 176       type = (G1HeapVerifier::G1VerifyType)(type | G1HeapVerifier::G1VerifyYoungEvacFail);
 177     }
 178     G1CollectedHeap::heap()->verify_after_young_collection(type);
 179   }
 180 };
 181 
 182 G1Allocator* G1YoungCollector::allocator() const {
 183   return _g1h->allocator();
 184 }
 185 
 186 G1CollectionSet* G1YoungCollector::collection_set() const {
 187   return _g1h->collection_set();
 188 }
 189 
 190 G1CollectorState* G1YoungCollector::collector_state() const {
 191   return _g1h->collector_state();
 192 }
 193 
 194 G1ConcurrentMark* G1YoungCollector::concurrent_mark() const {
 195   return _g1h->concurrent_mark();
 196 }
 197 
 198 STWGCTimer* G1YoungCollector::gc_timer_stw() const {
 199   return _g1h->gc_timer_stw();
 200 }
 201 
 202 G1NewTracer* G1YoungCollector::gc_tracer_stw() const {
 203   return _g1h->gc_tracer_stw();
 204 }
 205 
 206 G1Policy* G1YoungCollector::policy() const {
 207   return _g1h->policy();
 208 }
 209 
 210 G1GCPhaseTimes* G1YoungCollector::phase_times() const {
 211   return _g1h->phase_times();
 212 }
 213 
 214 G1MonitoringSupport* G1YoungCollector::monitoring_support() const {
 215   return _g1h->monitoring_support();
 216 }
 217 
 218 G1RemSet* G1YoungCollector::rem_set() const {
 219   return _g1h->rem_set();
 220 }
 221 
 222 G1ScannerTasksQueueSet* G1YoungCollector::task_queues() const {
 223   return _g1h->task_queues();
 224 }
 225 
 226 G1SurvivorRegions* G1YoungCollector::survivor_regions() const {
 227   return _g1h->survivor();
 228 }
 229 
 230 ReferenceProcessor* G1YoungCollector::ref_processor_stw() const {
 231   return _g1h->ref_processor_stw();
 232 }
 233 
 234 WorkerThreads* G1YoungCollector::workers() const {
 235   return _g1h->workers();
 236 }
 237 
 238 G1YoungGCAllocationFailureInjector* G1YoungCollector::allocation_failure_injector() const {
 239   return _g1h->allocation_failure_injector();
 240 }
 241 
 242 void G1YoungCollector::complete_root_region_scan() {
 243   Ticks start = Ticks::now();
 244   if (concurrent_mark()->complete_root_regions_scan_in_safepoint()) {
 245     phase_times()->record_root_region_scan_time((Ticks::now() - start).seconds() * MILLIUNITS);
 246   }
 247 }
 248 
 249 class G1PrintCollectionSetClosure : public G1HeapRegionClosure {
 250 public:
 251   virtual bool do_heap_region(G1HeapRegion* r) {
 252     G1HeapRegionPrinter::cset(r);
 253     return false;
 254   }
 255 };
 256 
 257 void G1YoungCollector::calculate_collection_set(G1EvacInfo* evacuation_info, double target_pause_time_ms) {
 258   // Forget the current allocation region (we might even choose it to be part
 259   // of the collection set!) before finalizing the collection set.
 260   allocator()->release_mutator_alloc_regions();
 261 
 262   collection_set()->finalize_initial_collection_set(target_pause_time_ms, survivor_regions());
 263   evacuation_info->set_collection_set_regions(collection_set()->initial_region_length() +
 264                                               collection_set()->num_optional_regions());
 265 
 266   concurrent_mark()->verify_no_collection_set_oops();
 267 
 268   if (G1HeapRegionPrinter::is_active()) {
 269     G1PrintCollectionSetClosure cl;
 270     collection_set()->iterate(&cl);
 271     collection_set()->iterate_optional(&cl);
 272   }
 273 }
 274 
 275 class G1PrepareEvacuationTask : public WorkerTask {
 276   class G1PrepareRegionsClosure : public G1HeapRegionClosure {
 277     G1CollectedHeap* _g1h;
 278     G1PrepareEvacuationTask* _parent_task;
 279     uint _worker_humongous_total;
 280     uint _worker_humongous_candidates;
 281 
 282     G1MonotonicArenaMemoryStats _humongous_card_set_stats;
 283 
 284     bool humongous_region_is_candidate(G1HeapRegion* region) const {
 285       assert(region->is_starts_humongous(), "Must start a humongous object");
 286 
 287       oop obj = cast_to_oop(region->bottom());
 288 
 289       // Dead objects cannot be eager reclaim candidates. Due to class
 290       // unloading it is unsafe to query their classes so we return early.
 291       if (_g1h->is_obj_dead(obj, region)) {
 292         return false;
 293       }
 294 
 295       // If we do not have a complete remembered set for the region, then we can
 296       // not be sure that we have all references to it.
 297       if (!region->rem_set()->is_complete()) {
 298         return false;
 299       }
 300       // We also cannot collect the humongous object if it is pinned.
 301       if (region->has_pinned_objects()) {
 302         return false;
 303       }
 304       // Candidate selection must satisfy the following constraints
 305       // while concurrent marking is in progress:
 306       //
 307       // * In order to maintain SATB invariants, an object must not be
 308       // reclaimed if it was allocated before the start of marking and
 309       // has not had its references scanned.  Such an object must have
 310       // its references (including type metadata) scanned to ensure no
 311       // live objects are missed by the marking process.  Objects
 312       // allocated after the start of concurrent marking don't need to
 313       // be scanned.
 314       //
 315       // * An object must not be reclaimed if it is on the concurrent
 316       // mark stack.  Objects allocated after the start of concurrent
 317       // marking are never pushed on the mark stack.
 318       //
 319       // Nominating only objects allocated after the start of concurrent
 320       // marking is sufficient to meet both constraints.  This may miss
 321       // some objects that satisfy the constraints, but the marking data
 322       // structures don't support efficiently performing the needed
 323       // additional tests or scrubbing of the mark stack.
 324       //
 325       // We handle humongous objects specially, because frequent allocation and
 326       // dropping of large binary blobs is an important use case for eager reclaim,
 327       // and this special handling increases needed headroom.
 328       // It also helps with G1 allocating humongous objects as old generation
 329       // objects although they might also die quite quickly.
 330       //
 331       // Humongous objects without oops (typeArrays, flatArrays without oops in
 332       // its elements) are allowed to be reclaimed even if allocated before
 333       // the start of concurrent mark.  For this we rely on mark stack insertion
 334       // to exclude them, preventing reclaiming an object
 335       // that is in the mark stack.  That code also ensures that metadata (klass)
 336       // is kept live.
 337       //
 338       // Other humongous objects that were allocated before marking are excluded from
 339       // eager reclaim during marking.  One issue is the problem described
 340       // above with scrubbing the mark stack, but there is also a problem
 341       // causing these humongous objects being collected incorrectly:
 342       //
 343       // E.g. if the mutator is running, we may have objects o1 and o2 in the same
 344       // region, where o1 has already been scanned and o2 is only reachable by
 345       // the candidate object h, which is humongous.
 346       //
 347       // If the mutator read the reference to o2 from h and installed it into o1,
 348       // no remembered set entry would be created for keeping alive o2, as o1 and
 349       // o2 are in the same region.  Object h might be reclaimed by the next
 350       // garbage collection. o1 still has the reference to o2, but since o1 had
 351       // already been scanned we do not detect o2 to be still live and reclaim it.
 352       //
 353       // There is another minor problem with these humongous objects with oops being
 354       // the source of remembered set entries in other region's remembered sets.
 355       // There are two cases: first, the remembered set entry is in a Free region
 356       // after reclaim.  We handle this case by ignoring these cards during merging
 357       // the remembered sets.
 358       //
 359       // Second, there may be cases where regions previously containing eagerly
 360       // reclaimed objects were already allocated into again.
 361       // This may cause scanning of these outdated remembered set entries,
 362       // containing some objects. But apart from extra work this does not cause
 363       // correctness issues.
 364       // There is no difference between scanning cards covering an effectively
 365       // dead humongous object vs. some other objects in reallocated regions.
 366       //
 367       // TAMSes are only reset after completing the entire mark cycle, during
 368       // bitmap clearing. It is worth to not wait until then, and allow reclamation
 369       // outside of actual (concurrent) SATB marking.
 370       // This also applies to the concurrent start pause - we only set
 371       // mark_in_progress() at the end of that GC: no mutator is running that can
 372       // sneakily install a new reference to the potentially reclaimed humongous
 373       // object.
 374       // During the concurrent start pause the situation described above where we
 375       // miss a reference can not happen. No mutator is modifying the object
 376       // graph to install such an overlooked reference.
 377       //
 378       // After the pause, having reclaimed h, obviously the mutator can't fetch
 379       // the reference from h any more.
 380       bool marked_immediately = _g1h->can_be_marked_through_immediately(obj);
 381       if (!marked_immediately) {
 382         // All regions that were allocated before marking have a TAMS != bottom.
 383         bool allocated_before_mark_start = region->bottom() != _g1h->concurrent_mark()->top_at_mark_start(region);
 384         bool mark_in_progress = _g1h->collector_state()->is_in_marking();
 385 
 386         if (allocated_before_mark_start && mark_in_progress) {
 387           return false;
 388         }
 389       }
 390       return _g1h->is_potential_eager_reclaim_candidate(region);
 391     }
 392 
 393   public:
 394     G1PrepareRegionsClosure(G1CollectedHeap* g1h, G1PrepareEvacuationTask* parent_task) :
 395       _g1h(g1h),
 396       _parent_task(parent_task),
 397       _worker_humongous_total(0),
 398       _worker_humongous_candidates(0),
 399       _humongous_card_set_stats() { }
 400 
 401     ~G1PrepareRegionsClosure() {
 402       _parent_task->add_humongous_candidates(_worker_humongous_candidates);
 403       _parent_task->add_humongous_total(_worker_humongous_total);
 404     }
 405 
 406     virtual bool do_heap_region(G1HeapRegion* hr) {
 407       // First prepare the region for scanning
 408       _g1h->rem_set()->prepare_region_for_scan(hr);
 409 
 410       // Now check if region is a humongous candidate
 411       if (!hr->is_starts_humongous()) {
 412         _g1h->update_region_attr(hr);
 413         return false;
 414       }
 415 
 416       uint index = hr->hrm_index();
 417       if (humongous_region_is_candidate(hr)) {
 418         _g1h->register_humongous_candidate_region_with_region_attr(index);
 419         _worker_humongous_candidates++;
 420         // We will later handle the remembered sets of these regions.
 421       } else {
 422         _g1h->update_region_attr(hr);
 423       }
 424 
 425       // Sample card set sizes for humongous regions before GC: this makes the policy
 426       // to give back memory to the OS keep the most recent amount of memory for these regions.
 427       _humongous_card_set_stats.add(hr->rem_set()->card_set_memory_stats());
 428 
 429       log_debug(gc, humongous)("Humongous region %u (object size %zu @ " PTR_FORMAT ") remset %zu code roots %zu "
 430                                "marked %d pinned count %zu reclaim candidate %d type %s",
 431                                index,
 432                                cast_to_oop(hr->bottom())->size() * HeapWordSize,
 433                                p2i(hr->bottom()),
 434                                hr->rem_set()->occupied(),
 435                                hr->rem_set()->code_roots_list_length(),
 436                                _g1h->concurrent_mark()->mark_bitmap()->is_marked(hr->bottom()),
 437                                hr->pinned_count(),
 438                                _g1h->is_humongous_reclaim_candidate(index),
 439                                cast_to_oop(hr->bottom())->is_typeArray() ? "tA"
 440                                                                          : (cast_to_oop(hr->bottom())->is_objArray() ? "oA" : "ob")
 441                               );
 442       _worker_humongous_total++;
 443 
 444       return false;
 445     }
 446 
 447     G1MonotonicArenaMemoryStats humongous_card_set_stats() const {
 448       return _humongous_card_set_stats;
 449     }
 450   };
 451 
 452   G1CollectedHeap* _g1h;
 453   G1HeapRegionClaimer _claimer;
 454   Atomic<uint> _humongous_total;
 455   Atomic<uint> _humongous_candidates;
 456 
 457   G1MonotonicArenaMemoryStats _all_card_set_stats;
 458 
 459 public:
 460   G1PrepareEvacuationTask(G1CollectedHeap* g1h) :
 461     WorkerTask("Prepare Evacuation"),
 462     _g1h(g1h),
 463     _claimer(_g1h->workers()->active_workers()),
 464     _humongous_total(0),
 465     _humongous_candidates(0) { }
 466 
 467   void work(uint worker_id) {
 468     G1PrepareRegionsClosure cl(_g1h, this);
 469     _g1h->heap_region_par_iterate_from_worker_offset(&cl, &_claimer, worker_id);
 470 
 471     MutexLocker x(G1RareEvent_lock, Mutex::_no_safepoint_check_flag);
 472     _all_card_set_stats.add(cl.humongous_card_set_stats());
 473   }
 474 
 475   void add_humongous_candidates(uint candidates) {
 476     _humongous_candidates.add_then_fetch(candidates);
 477   }
 478 
 479   void add_humongous_total(uint total) {
 480     _humongous_total.add_then_fetch(total);
 481   }
 482 
 483   uint humongous_candidates() {
 484     return _humongous_candidates.load_relaxed();
 485   }
 486 
 487   uint humongous_total() {
 488     return _humongous_total.load_relaxed();
 489   }
 490 
 491   const G1MonotonicArenaMemoryStats all_card_set_stats() const {
 492     return _all_card_set_stats;
 493   }
 494 };
 495 
 496 Tickspan G1YoungCollector::run_task_timed(WorkerTask* task) {
 497   Ticks start = Ticks::now();
 498   workers()->run_task(task);
 499   return Ticks::now() - start;
 500 }
 501 
 502 void G1YoungCollector::set_young_collection_default_active_worker_threads(){
 503   uint active_workers = WorkerPolicy::calc_active_workers(workers()->max_workers(),
 504                                                           workers()->active_workers(),
 505                                                           Threads::number_of_non_daemon_threads());
 506   active_workers = workers()->set_active_workers(active_workers);
 507   log_info(gc,task)("Using %u workers of %u for evacuation", active_workers, workers()->max_workers());
 508 }
 509 
 510 void G1YoungCollector::pre_evacuate_collection_set(G1EvacInfo* evacuation_info) {
 511   // Flush various data in thread-local buffers to be able to determine the collection
 512   // set
 513   {
 514     Ticks start = Ticks::now();
 515     G1PreEvacuateCollectionSetBatchTask cl;
 516     G1CollectedHeap::heap()->run_batch_task(&cl);
 517     phase_times()->record_pre_evacuate_prepare_time_ms((Ticks::now() - start).seconds() * 1000.0);
 518   }
 519 
 520   // Needs log buffers flushed.
 521   calculate_collection_set(evacuation_info, policy()->max_pause_time_ms());
 522 
 523   if (collector_state()->is_in_concurrent_start_gc()) {
 524     Ticks start = Ticks::now();
 525     concurrent_mark()->pre_concurrent_start(_gc_cause);
 526     phase_times()->record_prepare_concurrent_task_time_ms((Ticks::now() - start).seconds() * 1000.0);
 527   }
 528 
 529   // Please see comment in g1CollectedHeap.hpp and
 530   // G1CollectedHeap::ref_processing_init() to see how
 531   // reference processing currently works in G1.
 532   ref_processor_stw()->start_discovery(false /* always_clear */);
 533 
 534   _evac_failure_regions.pre_collection(_g1h->max_num_regions());
 535 
 536   _g1h->gc_prologue(false);
 537 
 538   // Initialize the GC alloc regions.
 539   allocator()->init_gc_alloc_regions(evacuation_info);
 540 
 541   {
 542     Ticks start = Ticks::now();
 543     rem_set()->prepare_for_scan_heap_roots();
 544 
 545     _g1h->collection_set()->prepare_for_scan();
 546 
 547     phase_times()->record_prepare_heap_roots_time_ms((Ticks::now() - start).seconds() * 1000.0);
 548   }
 549 
 550   {
 551     G1PrepareEvacuationTask g1_prep_task(_g1h);
 552     Tickspan task_time = run_task_timed(&g1_prep_task);
 553 
 554     G1MonotonicArenaMemoryStats sampled_card_set_stats = g1_prep_task.all_card_set_stats();
 555     sampled_card_set_stats.add(_g1h->young_regions_cset_group()->card_set_memory_stats());
 556     _g1h->set_young_gen_card_set_stats(sampled_card_set_stats);
 557     _g1h->set_humongous_stats(g1_prep_task.humongous_total(), g1_prep_task.humongous_candidates());
 558 
 559     phase_times()->record_register_regions(task_time.seconds() * 1000.0);
 560   }
 561 
 562   assert(_g1h->verifier()->check_region_attr_table(), "Inconsistency in the region attributes table.");
 563 
 564 #if COMPILER2_OR_JVMCI
 565   DerivedPointerTable::clear();
 566 #endif
 567 
 568   allocation_failure_injector()->arm_if_needed();
 569 }
 570 
 571 class G1ParEvacuateFollowersClosure : public VoidClosure {
 572   double _start_term;
 573   double _term_time;
 574   size_t _term_attempts;
 575 
 576   void start_term_time() { _term_attempts++; _start_term = os::elapsedTime(); }
 577   void end_term_time() { _term_time += (os::elapsedTime() - _start_term); }
 578 
 579   G1CollectedHeap*              _g1h;
 580   G1ParScanThreadState*         _par_scan_state;
 581   G1ScannerTasksQueueSet*       _queues;
 582   TaskTerminator*               _terminator;
 583   G1GCPhaseTimes::GCParPhases   _phase;
 584 
 585   G1ParScanThreadState*   par_scan_state() { return _par_scan_state; }
 586   G1ScannerTasksQueueSet* queues()         { return _queues; }
 587   TaskTerminator*         terminator()     { return _terminator; }
 588 
 589   inline bool offer_termination() {
 590     EventGCPhaseParallel event;
 591     G1ParScanThreadState* const pss = par_scan_state();
 592     start_term_time();
 593     const bool res = (terminator() == nullptr) ? true : terminator()->offer_termination();
 594     end_term_time();
 595     event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(G1GCPhaseTimes::Termination));
 596     return res;
 597   }
 598 
 599 public:
 600   G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h,
 601                                 G1ParScanThreadState* par_scan_state,
 602                                 G1ScannerTasksQueueSet* queues,
 603                                 TaskTerminator* terminator,
 604                                 G1GCPhaseTimes::GCParPhases phase)
 605     : _start_term(0.0), _term_time(0.0), _term_attempts(0),
 606       _g1h(g1h), _par_scan_state(par_scan_state),
 607       _queues(queues), _terminator(terminator), _phase(phase) {}
 608 
 609   void do_void() {
 610     EventGCPhaseParallel event;
 611     G1ParScanThreadState* const pss = par_scan_state();
 612     pss->trim_queue();
 613     event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase));
 614     do {
 615       EventGCPhaseParallel event;
 616       pss->steal_and_trim_queue(queues());
 617       event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase));
 618     } while (!offer_termination());
 619   }
 620 
 621   double term_time() const { return _term_time; }
 622   size_t term_attempts() const { return _term_attempts; }
 623 };
 624 
 625 class G1EvacuateRegionsBaseTask : public WorkerTask {
 626 
 627   // All pinned regions in the collection set must be registered as failed
 628   // regions as there is no guarantee that there is a reference reachable by
 629   // Java code (i.e. only by native code) that adds it to the evacuation failed
 630   // regions.
 631   void record_pinned_regions(G1ParScanThreadState* pss, uint worker_id) {
 632     class RecordPinnedRegionClosure : public G1HeapRegionClosure {
 633       G1ParScanThreadState* _pss;
 634       uint _worker_id;
 635 
 636     public:
 637       RecordPinnedRegionClosure(G1ParScanThreadState* pss, uint worker_id) : _pss(pss), _worker_id(worker_id) { }
 638 
 639       bool do_heap_region(G1HeapRegion* r) {
 640         if (r->has_pinned_objects()) {
 641           _pss->record_evacuation_failed_region(r, _worker_id, true /* cause_pinned */);
 642         }
 643         return false;
 644       }
 645     } cl(pss, worker_id);
 646 
 647     _g1h->collection_set_iterate_increment_from(&cl, worker_id);
 648   }
 649 
 650 protected:
 651   G1CollectedHeap* _g1h;
 652   G1ParScanThreadStateSet* _per_thread_states;
 653 
 654   G1ScannerTasksQueueSet* _task_queues;
 655   TaskTerminator _terminator;
 656 
 657   void evacuate_live_objects(G1ParScanThreadState* pss,
 658                              uint worker_id,
 659                              G1GCPhaseTimes::GCParPhases objcopy_phase,
 660                              G1GCPhaseTimes::GCParPhases termination_phase) {
 661     G1GCPhaseTimes* p = _g1h->phase_times();
 662 
 663     Ticks start = Ticks::now();
 664     G1ParEvacuateFollowersClosure cl(_g1h, pss, _task_queues, &_terminator, objcopy_phase);
 665     cl.do_void();
 666 
 667     assert(pss->queue_is_empty(), "should be empty");
 668 
 669     Tickspan evac_time = (Ticks::now() - start);
 670     p->record_or_add_time_secs(objcopy_phase, worker_id, evac_time.seconds() - cl.term_time());
 671 
 672     if (termination_phase == G1GCPhaseTimes::Termination) {
 673       p->record_time_secs(termination_phase, worker_id, cl.term_time());
 674       p->record_thread_work_item(termination_phase, worker_id, cl.term_attempts());
 675     } else {
 676       p->record_or_add_time_secs(termination_phase, worker_id, cl.term_time());
 677       p->record_or_add_thread_work_item(termination_phase, worker_id, cl.term_attempts());
 678     }
 679     assert(pss->trim_ticks().value() == 0,
 680            "Unexpected partial trimming during evacuation value " JLONG_FORMAT,
 681            pss->trim_ticks().value());
 682   }
 683 
 684   virtual void start_work(uint worker_id) { }
 685 
 686   virtual void end_work(uint worker_id) { }
 687 
 688   virtual void scan_roots(G1ParScanThreadState* pss, uint worker_id) = 0;
 689 
 690   virtual void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) = 0;
 691 
 692 private:
 693   Atomic<bool> _pinned_regions_recorded;
 694 
 695 public:
 696   G1EvacuateRegionsBaseTask(const char* name,
 697                             G1ParScanThreadStateSet* per_thread_states,
 698                             G1ScannerTasksQueueSet* task_queues,
 699                             uint num_workers) :
 700     WorkerTask(name),
 701     _g1h(G1CollectedHeap::heap()),
 702     _per_thread_states(per_thread_states),
 703     _task_queues(task_queues),
 704     _terminator(num_workers, _task_queues),
 705     _pinned_regions_recorded(false)
 706   { }
 707 
 708   void work(uint worker_id) {
 709     start_work(worker_id);
 710 
 711     {
 712       ResourceMark rm;
 713 
 714       G1ParScanThreadState* pss = _per_thread_states->state_for_worker(worker_id);
 715       pss->set_ref_discoverer(_g1h->ref_processor_stw());
 716 
 717       if (_pinned_regions_recorded.compare_set(false, true)) {
 718         record_pinned_regions(pss, worker_id);
 719       }
 720       scan_roots(pss, worker_id);
 721       evacuate_live_objects(pss, worker_id);
 722     }
 723 
 724     end_work(worker_id);
 725   }
 726 };
 727 
 728 class G1EvacuateRegionsTask : public G1EvacuateRegionsBaseTask {
 729   G1RootProcessor* _root_processor;
 730   bool _has_optional_evacuation_work;
 731 
 732   void scan_roots(G1ParScanThreadState* pss, uint worker_id) {
 733     _root_processor->evacuate_roots(pss, worker_id);
 734     _g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::ScanHR, G1GCPhaseTimes::ObjCopy, _has_optional_evacuation_work);
 735     _g1h->rem_set()->scan_collection_set_code_roots(pss, worker_id, G1GCPhaseTimes::CodeRoots, G1GCPhaseTimes::ObjCopy);
 736     // There are no optional roots to scan right now.
 737 #ifdef ASSERT
 738     class VerifyOptionalCollectionSetRootsEmptyClosure : public G1HeapRegionClosure {
 739       G1ParScanThreadState* _pss;
 740 
 741     public:
 742       VerifyOptionalCollectionSetRootsEmptyClosure(G1ParScanThreadState* pss) : _pss(pss) { }
 743 
 744       bool do_heap_region(G1HeapRegion* r) override {
 745         assert(!r->has_index_in_opt_cset(), "must be");
 746         return false;
 747       }
 748     } cl(pss);
 749     _g1h->collection_set_iterate_increment_from(&cl, worker_id);
 750 #endif
 751   }
 752 
 753   void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) {
 754     G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::ObjCopy, G1GCPhaseTimes::Termination);
 755   }
 756 
 757   void start_work(uint worker_id) {
 758     _g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerStart, worker_id, Ticks::now().seconds());
 759   }
 760 
 761   void end_work(uint worker_id) {
 762     _g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerEnd, worker_id, Ticks::now().seconds());
 763   }
 764 
 765 public:
 766   G1EvacuateRegionsTask(G1CollectedHeap* g1h,
 767                         G1ParScanThreadStateSet* per_thread_states,
 768                         G1ScannerTasksQueueSet* task_queues,
 769                         G1RootProcessor* root_processor,
 770                         uint num_workers,
 771                         bool has_optional_evacuation_work) :
 772     G1EvacuateRegionsBaseTask("G1 Evacuate Regions", per_thread_states, task_queues, num_workers),
 773     _root_processor(root_processor),
 774     _has_optional_evacuation_work(has_optional_evacuation_work)
 775   { }
 776 };
 777 
 778 void G1YoungCollector::evacuate_initial_collection_set(G1ParScanThreadStateSet* per_thread_states,
 779                                                       bool has_optional_evacuation_work) {
 780   G1GCPhaseTimes* p = phase_times();
 781 
 782   rem_set()->merge_heap_roots(true /* initial_evacuation */);
 783 
 784   Tickspan task_time;
 785   const uint num_workers = workers()->active_workers();
 786 
 787   Ticks start_processing = Ticks::now();
 788   {
 789     G1RootProcessor root_processor(_g1h, num_workers > 1 /* is_parallel */);
 790     G1EvacuateRegionsTask g1_par_task(_g1h,
 791                                       per_thread_states,
 792                                       task_queues(),
 793                                       &root_processor,
 794                                       num_workers,
 795                                       has_optional_evacuation_work);
 796     task_time = run_task_timed(&g1_par_task);
 797     // Closing the inner scope will execute the destructor for the
 798     // G1RootProcessor object. By subtracting the WorkerThreads task from the total
 799     // time of this scope, we get the "NMethod List Cleanup" time. This list is
 800     // constructed during "STW two-phase nmethod root processing", see more in
 801     // nmethod.hpp
 802   }
 803   Tickspan total_processing = Ticks::now() - start_processing;
 804 
 805   p->record_initial_evac_time(task_time.seconds() * 1000.0);
 806   p->record_or_add_nmethod_list_cleanup_time((total_processing - task_time).seconds() * 1000.0);
 807 
 808   rem_set()->complete_evac_phase(has_optional_evacuation_work);
 809 }
 810 
 811 class G1EvacuateOptionalRegionsTask : public G1EvacuateRegionsBaseTask {
 812 
 813   void scan_roots(G1ParScanThreadState* pss, uint worker_id) {
 814     _g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::OptObjCopy, true /* remember_already_scanned_cards */);
 815     _g1h->rem_set()->scan_collection_set_code_roots(pss, worker_id, G1GCPhaseTimes::OptCodeRoots, G1GCPhaseTimes::OptObjCopy);
 816     _g1h->rem_set()->scan_collection_set_optional_roots(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::ObjCopy);
 817   }
 818 
 819   void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) {
 820     G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::OptObjCopy, G1GCPhaseTimes::OptTermination);
 821   }
 822 
 823 public:
 824   G1EvacuateOptionalRegionsTask(G1ParScanThreadStateSet* per_thread_states,
 825                                 G1ScannerTasksQueueSet* queues,
 826                                 uint num_workers) :
 827     G1EvacuateRegionsBaseTask("G1 Evacuate Optional Regions", per_thread_states, queues, num_workers) {
 828   }
 829 };
 830 
 831 void G1YoungCollector::evacuate_next_optional_regions(G1ParScanThreadStateSet* per_thread_states) {
 832   Tickspan task_time;
 833 
 834   Ticks start_processing = Ticks::now();
 835   {
 836     NMethodMarkingScope nmethod_marking_scope;
 837     G1EvacuateOptionalRegionsTask task(per_thread_states, task_queues(), workers()->active_workers());
 838     task_time = run_task_timed(&task);
 839     // See comment in evacuate_initial_collection_set() for the reason of the scope.
 840   }
 841   Tickspan total_processing = Ticks::now() - start_processing;
 842 
 843   G1GCPhaseTimes* p = phase_times();
 844   p->record_or_add_optional_evac_time(task_time.seconds() * 1000.0);
 845   p->record_or_add_nmethod_list_cleanup_time((total_processing - task_time).seconds() * 1000.0);
 846 }
 847 
 848 void G1YoungCollector::evacuate_optional_collection_set(G1ParScanThreadStateSet* per_thread_states) {
 849   const double pause_start_time_ms = policy()->cur_pause_start_sec() * 1000.0;
 850   double target_pause_time_ms = MaxGCPauseMillis;
 851 
 852   if (G1ForceOptionalEvacuation) {
 853     target_pause_time_ms = DBL_MAX;
 854   }
 855 
 856   while (!evacuation_alloc_failed() && collection_set()->num_optional_regions() > 0) {
 857 
 858     double time_used_ms = os::elapsedTime() * 1000.0 - pause_start_time_ms;
 859     double time_left_ms = target_pause_time_ms - time_used_ms;
 860 
 861     if (time_left_ms <= 0 ||
 862         !collection_set()->finalize_optional_for_evacuation(time_left_ms * policy()->optional_evacuation_fraction())) {
 863       log_trace(gc, ergo, cset)("Skipping evacuation of %u optional regions, no more regions can be evacuated in %.3fms",
 864                                 collection_set()->num_optional_regions(), time_left_ms);
 865       break;
 866     }
 867 
 868     rem_set()->merge_heap_roots(false /* initial_evacuation */);
 869 
 870     evacuate_next_optional_regions(per_thread_states);
 871 
 872     rem_set()->complete_evac_phase(true /* has_more_than_one_evacuation_phase */);
 873   }
 874 
 875   collection_set()->abandon_optional_collection_set(per_thread_states);
 876 }
 877 
 878 // Non Copying Keep Alive closure
 879 class G1KeepAliveClosure: public OopClosure {
 880   G1CollectedHeap*_g1h;
 881 public:
 882   G1KeepAliveClosure(G1CollectedHeap* g1h) :_g1h(g1h) {}
 883   void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }
 884   void do_oop(oop* p) {
 885     oop obj = *p;
 886     assert(obj != nullptr, "the caller should have filtered out null values");
 887 
 888     const G1HeapRegionAttr region_attr =_g1h->region_attr(obj);
 889     assert(!region_attr.is_humongous_candidate(), "Humongous candidates should never be considered alive");
 890     if (region_attr.is_in_cset()) {
 891       assert(obj->is_forwarded(), "invariant" );
 892       *p = obj->forwardee();
 893     }
 894   }
 895 };
 896 
 897 // Copying Keep Alive closure - can be called from both
 898 // serial and parallel code as long as different worker
 899 // threads utilize different G1ParScanThreadState instances
 900 // and different queues.
 901 class G1CopyingKeepAliveClosure: public OopClosure {
 902   G1CollectedHeap* _g1h;
 903   G1ParScanThreadState*    _par_scan_state;
 904 
 905 public:
 906   G1CopyingKeepAliveClosure(G1CollectedHeap* g1h,
 907                             G1ParScanThreadState* pss):
 908     _g1h(g1h),
 909     _par_scan_state(pss)
 910   {}
 911 
 912   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
 913   virtual void do_oop(      oop* p) { do_oop_work(p); }
 914 
 915   template <class T> void do_oop_work(T* p) {
 916     oop obj = RawAccess<>::oop_load(p);
 917 
 918     assert(!_g1h->region_attr(obj).is_humongous_candidate(), "Humongous candidates should never be considered alive");
 919     if (_g1h->is_in_cset(obj)) {
 920       // If the referent object has been forwarded (either copied
 921       // to a new location or to itself in the event of an
 922       // evacuation failure) then we need to update the reference
 923       // field and, if both reference and referent are in the G1
 924       // heap, update the RSet for the referent.
 925       //
 926       // If the referent has not been forwarded then we have to keep
 927       // it alive by policy. Therefore we have copy the referent.
 928       //
 929       // When the queue is drained (after each phase of reference processing)
 930       // the object and it's followers will be copied, the reference field set
 931       // to point to the new location, and the RSet updated.
 932       _par_scan_state->push_on_queue(ScannerTask(p));
 933     }
 934   }
 935 };
 936 
 937 class G1STWRefProcProxyTask : public RefProcProxyTask {
 938   G1CollectedHeap& _g1h;
 939   G1ParScanThreadStateSet& _pss;
 940   TaskTerminator _terminator;
 941   G1ScannerTasksQueueSet& _task_queues;
 942 
 943   // G1 specific closure for marking discovered fields. Need to mark the card in the
 944   // refinement table as the card table is in use by garbage collection.
 945   class G1EnqueueDiscoveredFieldClosure : public EnqueueDiscoveredFieldClosure {
 946     G1CollectedHeap* _g1h;
 947     G1ParScanThreadState* _pss;
 948 
 949   public:
 950     G1EnqueueDiscoveredFieldClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) : _g1h(g1h), _pss(pss) { }
 951 
 952     void enqueue(HeapWord* discovered_field_addr, oop value) override {
 953       assert(_g1h->is_in(discovered_field_addr), PTR_FORMAT " is not in heap ", p2i(discovered_field_addr));
 954       // Store the value first, whatever it is.
 955       RawAccess<>::oop_store(discovered_field_addr, value);
 956       if (value == nullptr) {
 957         return;
 958       }
 959       _pss->write_ref_field_post(discovered_field_addr, value);
 960     }
 961   };
 962 
 963 public:
 964   G1STWRefProcProxyTask(uint max_workers, G1CollectedHeap& g1h, G1ParScanThreadStateSet& pss, G1ScannerTasksQueueSet& task_queues)
 965     : RefProcProxyTask("G1STWRefProcProxyTask", max_workers),
 966       _g1h(g1h),
 967       _pss(pss),
 968       _terminator(max_workers, &task_queues),
 969       _task_queues(task_queues) {}
 970 
 971   void work(uint worker_id) override {
 972     assert(worker_id < _max_workers, "sanity");
 973     uint index = (_tm == RefProcThreadModel::Single) ? 0 : worker_id;
 974 
 975     G1ParScanThreadState* pss = _pss.state_for_worker(index);
 976     pss->set_ref_discoverer(nullptr);
 977 
 978     G1STWIsAliveClosure is_alive(&_g1h);
 979     G1CopyingKeepAliveClosure keep_alive(&_g1h, pss);
 980     G1EnqueueDiscoveredFieldClosure enqueue(&_g1h, pss);
 981     G1ParEvacuateFollowersClosure complete_gc(&_g1h, pss, &_task_queues, _tm == RefProcThreadModel::Single ? nullptr : &_terminator, G1GCPhaseTimes::ObjCopy);
 982     _rp_task->rp_work(worker_id, &is_alive, &keep_alive, &enqueue, &complete_gc);
 983 
 984     // We have completed copying any necessary live referent objects.
 985     assert(pss->queue_is_empty(), "both queue and overflow should be empty");
 986   }
 987 
 988   void prepare_run_task_hook() override {
 989     _terminator.reset_for_reuse(_queue_count);
 990   }
 991 };
 992 
 993 void G1YoungCollector::process_discovered_references(G1ParScanThreadStateSet* per_thread_states) {
 994   Ticks start = Ticks::now();
 995 
 996   ReferenceProcessor* rp = ref_processor_stw();
 997   assert(rp->discovery_enabled(), "should have been enabled");
 998 
 999   G1STWRefProcProxyTask task(rp->max_num_queues(), *_g1h, *per_thread_states, *task_queues());
1000   ReferenceProcessorPhaseTimes& pt = *phase_times()->ref_phase_times();
1001   ReferenceProcessorStats stats = rp->process_discovered_references(task, _g1h->workers(), pt);
1002 
1003   gc_tracer_stw()->report_gc_reference_stats(stats);
1004 
1005   _g1h->make_pending_list_reachable();
1006 
1007   phase_times()->record_ref_proc_time((Ticks::now() - start).seconds() * MILLIUNITS);
1008 }
1009 
1010 void G1YoungCollector::post_evacuate_cleanup_1(G1ParScanThreadStateSet* per_thread_states) {
1011   Ticks start = Ticks::now();
1012   {
1013     G1PostEvacuateCollectionSetCleanupTask1 cl(per_thread_states, &_evac_failure_regions);
1014     _g1h->run_batch_task(&cl);
1015   }
1016   phase_times()->record_post_evacuate_cleanup_task_1_time((Ticks::now() - start).seconds() * 1000.0);
1017 }
1018 
1019 void G1YoungCollector::post_evacuate_cleanup_2(G1ParScanThreadStateSet* per_thread_states,
1020                                                G1EvacInfo* evacuation_info) {
1021   Ticks start = Ticks::now();
1022   {
1023     G1PostEvacuateCollectionSetCleanupTask2 cl(per_thread_states, evacuation_info, &_evac_failure_regions);
1024     _g1h->run_batch_task(&cl);
1025   }
1026   phase_times()->record_post_evacuate_cleanup_task_2_time((Ticks::now() - start).seconds() * 1000.0);
1027 }
1028 
1029 void G1YoungCollector::enqueue_candidates_as_root_regions() {
1030   assert(collector_state()->is_in_concurrent_start_gc(), "must be");
1031 
1032   G1CollectionSetCandidates* candidates = collection_set()->candidates();
1033   candidates->iterate_regions([&] (G1HeapRegion* r) {
1034     _g1h->concurrent_mark()->add_root_region(r);
1035   });
1036 }
1037 
1038 void G1YoungCollector::post_evacuate_collection_set(G1EvacInfo* evacuation_info,
1039                                                     G1ParScanThreadStateSet* per_thread_states) {
1040   G1GCPhaseTimes* p = phase_times();
1041 
1042   // Process any discovered reference objects - we have
1043   // to do this _before_ we retire the GC alloc regions
1044   // as we may have to copy some 'reachable' referent
1045   // objects (and their reachable sub-graphs) that were
1046   // not copied during the pause.
1047   process_discovered_references(per_thread_states);
1048 
1049   G1STWIsAliveClosure is_alive(_g1h);
1050   G1KeepAliveClosure keep_alive(_g1h);
1051 
1052   WeakProcessor::weak_oops_do(workers(), &is_alive, &keep_alive, p->weak_phase_times());
1053 
1054   allocator()->release_gc_alloc_regions(evacuation_info);
1055 
1056 #if TASKQUEUE_STATS
1057   _g1h->task_queues()->print_and_reset_taskqueue_stats("Young GC");
1058   // Logging uses thread states, which are deleted by cleanup, so this must
1059   // be done before cleanup.
1060   per_thread_states->print_partial_array_task_stats();
1061 #endif // TASKQUEUE_STATS
1062 
1063   post_evacuate_cleanup_1(per_thread_states);
1064 
1065   post_evacuate_cleanup_2(per_thread_states, evacuation_info);
1066 
1067   // Regions in the collection set candidates are roots for the marking (they are
1068   // not marked through considering they are very likely to be reclaimed soon.
1069   // They need to be enqueued explicitly compared to survivor regions.
1070   if (collector_state()->is_in_concurrent_start_gc()) {
1071     enqueue_candidates_as_root_regions();
1072   }
1073 
1074   _evac_failure_regions.post_collection();
1075 
1076   assert_used_and_recalculate_used_equal(_g1h);
1077 
1078   _g1h->rebuild_free_region_list();
1079 
1080   _g1h->record_obj_copy_mem_stats();
1081 
1082   evacuation_info->set_bytes_used(_g1h->bytes_used_during_gc());
1083 
1084   _g1h->prepare_for_mutator_after_young_collection();
1085 
1086   _g1h->gc_epilogue(false);
1087 
1088   _g1h->resize_heap_after_young_collection(_allocation_word_size);
1089 }
1090 
1091 bool G1YoungCollector::evacuation_failed() const {
1092   return _evac_failure_regions.has_regions_evac_failed();
1093 }
1094 
1095 bool G1YoungCollector::evacuation_pinned() const {
1096   return _evac_failure_regions.has_regions_evac_pinned();
1097 }
1098 
1099 bool G1YoungCollector::evacuation_alloc_failed() const {
1100   return _evac_failure_regions.has_regions_alloc_failed();
1101 }
1102 
1103 G1YoungCollector::G1YoungCollector(GCCause::Cause gc_cause,
1104                                    size_t allocation_word_size) :
1105   _g1h(G1CollectedHeap::heap()),
1106   _gc_cause(gc_cause),
1107   _allocation_word_size(allocation_word_size),
1108   _next_state(),
1109   _concurrent_operation_is_full_mark(false),
1110   _evac_failure_regions()
1111 {
1112 }
1113 
1114 void G1YoungCollector::collect() {
1115   // Do timing/tracing/statistics/pre- and post-logging/verification work not
1116   // directly related to the collection. They should not be accounted for in
1117   // collection work timing.
1118 
1119   // The G1YoungGCTraceTime message depends on collector state, so must come after
1120   // determining collector state.
1121   G1YoungGCTraceTime tm(this, _gc_cause);
1122 
1123   // JFR
1124   G1YoungGCJFRTracerMark jtm(this);
1125   // JStat/MXBeans
1126   G1YoungGCMonitoringScope ms(monitoring_support(),
1127                               !collection_set()->candidates()->is_empty() /* all_memory_pools_affected */);
1128   // Create the heap printer before internal pause timing to have
1129   // heap information printed as last part of detailed GC log.
1130   G1HeapPrinterMark hpm(_g1h);
1131   // Young GC internal pause timing
1132   G1YoungGCNotifyPauseMark npm(this);
1133 
1134   // Verification may use the workers, so they must be set up before.
1135   // Individual parallel phases may override this.
1136   set_young_collection_default_active_worker_threads();
1137 
1138   // Complete root region scan before moving any objects to preserve the SATB invariant.
1139   complete_root_region_scan();
1140 
1141   G1YoungGCVerifierMark vm(this);
1142   {
1143     // Actual collection work starts and is executed (only) in this scope.
1144 
1145     // Young GC internal collection timing. The elapsed time recorded in the
1146     // policy for the collection deliberately elides verification (and some
1147     // other trivial setup above).
1148     policy()->record_young_collection_start();
1149 
1150     pre_evacuate_collection_set(jtm.evacuation_info());
1151 
1152     G1ParScanThreadStateSet per_thread_states(_g1h,
1153                                               workers()->active_workers(),
1154                                               collection_set(),
1155                                               &_evac_failure_regions);
1156 
1157     bool may_do_optional_evacuation = collection_set()->num_optional_regions() != 0;
1158     // Actually do the work...
1159     evacuate_initial_collection_set(&per_thread_states, may_do_optional_evacuation);
1160 
1161     if (may_do_optional_evacuation) {
1162       evacuate_optional_collection_set(&per_thread_states);
1163     }
1164     post_evacuate_collection_set(jtm.evacuation_info(), &per_thread_states);
1165 
1166     // Refine the type of a concurrent mark operation now that we did the
1167     // evacuation, eventually aborting it.
1168     _concurrent_operation_is_full_mark = policy()->concurrent_operation_is_full_mark("Revise IHOP", _allocation_word_size);
1169 
1170     _next_state = policy()->record_young_collection_end(_concurrent_operation_is_full_mark, evacuation_alloc_failed(), _allocation_word_size);
1171   }
1172 }