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()->num_initial_regions() +
 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       // TypeArray objects are allowed to be reclaimed even if allocated before
 332       // the start of concurrent mark.  For this we rely on mark stack insertion
 333       // to exclude is_typeArray() objects, preventing reclaiming an object
 334       // that is in the mark stack.  We also rely on the metadata for
 335       // such objects to be built-in and so ensured to be kept live.
 336       //
 337       // Non-typeArrays that were allocated before marking are excluded from
 338       // eager reclaim during marking.  One issue is the problem described
 339       // above with scrubbing the mark stack, but there is also a problem
 340       // causing these humongous objects being collected incorrectly:
 341       //
 342       // E.g. if the mutator is running, we may have objects o1 and o2 in the same
 343       // region, where o1 has already been scanned and o2 is only reachable by
 344       // the candidate object h, which is humongous.
 345       //
 346       // If the mutator read the reference to o2 from h and installed it into o1,
 347       // no remembered set entry would be created for keeping alive o2, as o1 and
 348       // o2 are in the same region.  Object h might be reclaimed by the next
 349       // garbage collection. o1 still has the reference to o2, but since o1 had
 350       // already been scanned we do not detect o2 to be still live and reclaim it.
 351       //
 352       // There is another minor problem with non-typeArray regions being the source
 353       // of remembered set entries in other region's remembered sets.  There are
 354       // two cases: first, the remembered set entry is in a Free region after reclaim.
 355       // We handle this case by ignoring these cards during merging the remembered
 356       // sets.
 357       //
 358       // Second, there may be cases where eagerly reclaimed regions were already
 359       // reallocated.  This may cause scanning of these outdated remembered set
 360       // entries, containing some objects. But apart from extra work this does
 361       // not cause correctness issues.
 362       // There is no difference between scanning cards covering an effectively
 363       // dead humongous object vs. some other objects in reallocated regions.
 364       //
 365       // TAMSes are only reset in the Concurrent Start pause and when they are
 366       // reclaimed/freed. It is worth to not wait for TAMS updates until either
 367       // of these conditions applies and allow reclamation as much as possible.
 368       // This also applies to the concurrent start pause - we only set
 369       // is_in_marking() at the end of that GC: no mutator is running that can
 370       // sneakily install a new reference to the potentially reclaimed humongous
 371       // object.
 372       //
 373       // During the concurrent start pause the situation described above where we
 374       // miss a reference can not happen. No mutator is modifying the object
 375       // graph to install such an overlooked reference.
 376       //
 377       // After the pause, having reclaimed h, obviously the mutator can't fetch
 378       // the reference from h any more.
 379       if (!obj->is_typeArray()) {
 380         bool mark_in_progress = _g1h->collector_state()->is_in_marking();
 381         // top_at_mark_start() will assert outside of marking, so check first.
 382         if (mark_in_progress) {
 383           // All regions that were allocated before marking have a TAMS != bottom.
 384           G1ConcurrentMark* cm = _g1h->concurrent_mark();
 385           bool allocated_before_mark_start = region->bottom() != cm->top_at_mark_start(region);
 386           if (allocated_before_mark_start) {
 387             return false;
 388           }
 389         }
 390       }
 391       return _g1h->is_potential_eager_reclaim_candidate(region);
 392     }
 393 
 394   public:
 395     G1PrepareRegionsClosure(G1CollectedHeap* g1h, G1PrepareEvacuationTask* parent_task) :
 396       _g1h(g1h),
 397       _parent_task(parent_task),
 398       _worker_humongous_total(0),
 399       _worker_humongous_candidates(0),
 400       _humongous_card_set_stats() { }
 401 
 402     ~G1PrepareRegionsClosure() {
 403       _parent_task->add_humongous_candidates(_worker_humongous_candidates);
 404       _parent_task->add_humongous_total(_worker_humongous_total);
 405     }
 406 
 407     virtual bool do_heap_region(G1HeapRegion* hr) {
 408       // First prepare the region for scanning
 409       _g1h->rem_set()->prepare_region_for_scan(hr);
 410 
 411       // Now check if region is a humongous candidate
 412       if (!hr->is_starts_humongous()) {
 413         _g1h->update_region_attr(hr);
 414         return false;
 415       }
 416 
 417       uint index = hr->hrm_index();
 418       if (humongous_region_is_candidate(hr)) {
 419         _g1h->register_humongous_candidate_region_with_region_attr(index);
 420         _worker_humongous_candidates++;
 421         // We will later handle the remembered sets of these regions.
 422       } else {
 423         _g1h->update_region_attr(hr);
 424       }
 425 
 426       // Sample card set sizes for humongous regions before GC: this makes the policy
 427       // to give back memory to the OS keep the most recent amount of memory for these regions.
 428       _humongous_card_set_stats.add(hr->rem_set()->card_set_memory_stats());
 429 
 430       log_debug(gc, humongous)("Humongous region %u (object size %zu @ " PTR_FORMAT ") remset %zu code roots %zu "
 431                                "marked %d pinned count %zu reclaim candidate %d type %s",
 432                                index,
 433                                cast_to_oop(hr->bottom())->size() * HeapWordSize,
 434                                p2i(hr->bottom()),
 435                                hr->rem_set()->occupied(),
 436                                hr->rem_set()->code_roots_list_length(),
 437                                _g1h->concurrent_mark()->mark_bitmap()->is_marked(hr->bottom()),
 438                                hr->pinned_count(),
 439                                _g1h->is_humongous_reclaim_candidate(index),
 440                                cast_to_oop(hr->bottom())->is_typeArray() ? "tA"
 441                                                                          : (cast_to_oop(hr->bottom())->is_objArray() ? "oA" : "ob")
 442                               );
 443       _worker_humongous_total++;
 444 
 445       return false;
 446     }
 447 
 448     G1MonotonicArenaMemoryStats humongous_card_set_stats() const {
 449       return _humongous_card_set_stats;
 450     }
 451   };
 452 
 453   G1CollectedHeap* _g1h;
 454   G1HeapRegionClaimer _claimer;
 455   Atomic<uint> _humongous_total;
 456   Atomic<uint> _humongous_candidates;
 457 
 458   G1MonotonicArenaMemoryStats _all_card_set_stats;
 459 
 460 public:
 461   G1PrepareEvacuationTask(G1CollectedHeap* g1h) :
 462     WorkerTask("Prepare Evacuation"),
 463     _g1h(g1h),
 464     _claimer(_g1h->workers()->active_workers()),
 465     _humongous_total(0),
 466     _humongous_candidates(0) { }
 467 
 468   void work(uint worker_id) {
 469     G1PrepareRegionsClosure cl(_g1h, this);
 470     _g1h->heap_region_par_iterate_from_worker_offset(&cl, &_claimer, worker_id);
 471 
 472     MutexLocker x(G1RareEvent_lock, Mutex::_no_safepoint_check_flag);
 473     _all_card_set_stats.add(cl.humongous_card_set_stats());
 474   }
 475 
 476   void add_humongous_candidates(uint candidates) {
 477     _humongous_candidates.add_then_fetch(candidates);
 478   }
 479 
 480   void add_humongous_total(uint total) {
 481     _humongous_total.add_then_fetch(total);
 482   }
 483 
 484   uint humongous_candidates() {
 485     return _humongous_candidates.load_relaxed();
 486   }
 487 
 488   uint humongous_total() {
 489     return _humongous_total.load_relaxed();
 490   }
 491 
 492   const G1MonotonicArenaMemoryStats all_card_set_stats() const {
 493     return _all_card_set_stats;
 494   }
 495 };
 496 
 497 Tickspan G1YoungCollector::run_task_timed(WorkerTask* task) {
 498   Ticks start = Ticks::now();
 499   workers()->run_task(task);
 500   return Ticks::now() - start;
 501 }
 502 
 503 void G1YoungCollector::set_young_collection_default_active_worker_threads(){
 504   uint active_workers = WorkerPolicy::calc_active_workers(workers()->max_workers(),
 505                                                           workers()->active_workers(),
 506                                                           Threads::number_of_non_daemon_threads());
 507   active_workers = workers()->set_active_workers(active_workers);
 508   log_info(gc,task)("Using %u workers of %u for evacuation", active_workers, workers()->max_workers());
 509 }
 510 
 511 void G1YoungCollector::pre_evacuate_collection_set(G1EvacInfo* evacuation_info) {
 512   // Flush various data in thread-local buffers to be able to determine the collection
 513   // set
 514   {
 515     Ticks start = Ticks::now();
 516     G1PreEvacuateCollectionSetBatchTask cl;
 517     G1CollectedHeap::heap()->run_batch_task(&cl);
 518     phase_times()->record_pre_evacuate_prepare_time_ms((Ticks::now() - start).seconds() * 1000.0);
 519   }
 520 
 521   // Needs log buffers flushed.
 522   calculate_collection_set(evacuation_info, policy()->max_pause_time_ms());
 523 
 524   if (collector_state()->is_in_concurrent_start_gc()) {
 525     Ticks start = Ticks::now();
 526     concurrent_mark()->pre_concurrent_start(_gc_cause);
 527     phase_times()->record_prepare_concurrent_task_time_ms((Ticks::now() - start).seconds() * 1000.0);
 528   }
 529 
 530   // Please see comment in g1CollectedHeap.hpp and
 531   // G1CollectedHeap::ref_processing_init() to see how
 532   // reference processing currently works in G1.
 533   ref_processor_stw()->start_discovery(false /* always_clear */);
 534 
 535   _evac_failure_regions.pre_collection(_g1h->max_num_regions());
 536 
 537   _g1h->gc_prologue(false);
 538 
 539   // Initialize the GC alloc regions.
 540   allocator()->init_gc_alloc_regions(evacuation_info);
 541 
 542   {
 543     Ticks start = Ticks::now();
 544     rem_set()->prepare_for_scan_heap_roots();
 545 
 546     _g1h->collection_set()->prepare_for_scan();
 547 
 548     phase_times()->record_prepare_heap_roots_time_ms((Ticks::now() - start).seconds() * 1000.0);
 549   }
 550 
 551   {
 552     G1PrepareEvacuationTask g1_prep_task(_g1h);
 553     Tickspan task_time = run_task_timed(&g1_prep_task);
 554 
 555     G1MonotonicArenaMemoryStats sampled_card_set_stats = g1_prep_task.all_card_set_stats();
 556     sampled_card_set_stats.add(_g1h->young_regions_cset_group()->card_set_memory_stats());
 557     _g1h->set_young_gen_card_set_stats(sampled_card_set_stats);
 558     _g1h->set_humongous_stats(g1_prep_task.humongous_total(), g1_prep_task.humongous_candidates());
 559 
 560     phase_times()->record_register_regions(task_time.seconds() * 1000.0);
 561   }
 562 
 563   assert(_g1h->verifier()->check_region_attr_table(), "Inconsistency in the region attributes table.");
 564 
 565 #ifdef COMPILER2
 566   DerivedPointerTable::clear();
 567 #endif // COMPILER2
 568 
 569   allocation_failure_injector()->arm_if_needed();
 570 }
 571 
 572 class G1ParEvacuateFollowersClosure : public VoidClosure {
 573   double _start_term;
 574   double _term_time;
 575   size_t _term_attempts;
 576 
 577   void start_term_time() { _term_attempts++; _start_term = os::elapsedTime(); }
 578   void end_term_time() { _term_time += (os::elapsedTime() - _start_term); }
 579 
 580   G1CollectedHeap*              _g1h;
 581   G1ParScanThreadState*         _par_scan_state;
 582   G1ScannerTasksQueueSet*       _queues;
 583   TaskTerminator*               _terminator;
 584   G1GCPhaseTimes::GCParPhases   _phase;
 585 
 586   G1ParScanThreadState*   par_scan_state() { return _par_scan_state; }
 587   G1ScannerTasksQueueSet* queues()         { return _queues; }
 588   TaskTerminator*         terminator()     { return _terminator; }
 589 
 590   inline bool offer_termination() {
 591     EventGCPhaseParallel event;
 592     G1ParScanThreadState* const pss = par_scan_state();
 593     start_term_time();
 594     const bool res = (terminator() == nullptr) ? true : terminator()->offer_termination();
 595     end_term_time();
 596     event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(G1GCPhaseTimes::Termination));
 597     return res;
 598   }
 599 
 600 public:
 601   G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h,
 602                                 G1ParScanThreadState* par_scan_state,
 603                                 G1ScannerTasksQueueSet* queues,
 604                                 TaskTerminator* terminator,
 605                                 G1GCPhaseTimes::GCParPhases phase)
 606     : _start_term(0.0), _term_time(0.0), _term_attempts(0),
 607       _g1h(g1h), _par_scan_state(par_scan_state),
 608       _queues(queues), _terminator(terminator), _phase(phase) {}
 609 
 610   void do_void() {
 611     EventGCPhaseParallel event;
 612     G1ParScanThreadState* const pss = par_scan_state();
 613     pss->trim_queue();
 614     event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase));
 615     do {
 616       EventGCPhaseParallel event;
 617       pss->steal_and_trim_queue(queues());
 618       event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase));
 619     } while (!offer_termination());
 620   }
 621 
 622   double term_time() const { return _term_time; }
 623   size_t term_attempts() const { return _term_attempts; }
 624 };
 625 
 626 class G1EvacuateRegionsBaseTask : public WorkerTask {
 627 
 628   // All pinned regions in the collection set must be registered as failed
 629   // regions as there is no guarantee that there is a reference reachable by
 630   // Java code (i.e. only by native code) that adds it to the evacuation failed
 631   // regions.
 632   void record_pinned_regions(G1ParScanThreadState* pss, uint worker_id) {
 633     class RecordPinnedRegionClosure : public G1HeapRegionClosure {
 634       G1ParScanThreadState* _pss;
 635       uint _worker_id;
 636 
 637     public:
 638       RecordPinnedRegionClosure(G1ParScanThreadState* pss, uint worker_id) : _pss(pss), _worker_id(worker_id) { }
 639 
 640       bool do_heap_region(G1HeapRegion* r) {
 641         if (r->has_pinned_objects()) {
 642           _pss->record_evacuation_failed_region(r, _worker_id, true /* cause_pinned */);
 643         }
 644         return false;
 645       }
 646     } cl(pss, worker_id);
 647 
 648     _g1h->collection_set_iterate_increment_from(&cl, worker_id);
 649   }
 650 
 651 protected:
 652   G1CollectedHeap* _g1h;
 653   G1ParScanThreadStateSet* _per_thread_states;
 654 
 655   G1ScannerTasksQueueSet* _task_queues;
 656   TaskTerminator _terminator;
 657 
 658   void evacuate_live_objects(G1ParScanThreadState* pss,
 659                              uint worker_id,
 660                              G1GCPhaseTimes::GCParPhases objcopy_phase,
 661                              G1GCPhaseTimes::GCParPhases termination_phase) {
 662     G1GCPhaseTimes* p = _g1h->phase_times();
 663 
 664     Ticks start = Ticks::now();
 665     G1ParEvacuateFollowersClosure cl(_g1h, pss, _task_queues, &_terminator, objcopy_phase);
 666     cl.do_void();
 667 
 668     assert(pss->queue_is_empty(), "should be empty");
 669 
 670     Tickspan evac_time = (Ticks::now() - start);
 671     p->record_or_add_time_secs(objcopy_phase, worker_id, evac_time.seconds() - cl.term_time());
 672 
 673     if (termination_phase == G1GCPhaseTimes::Termination) {
 674       p->record_time_secs(termination_phase, worker_id, cl.term_time());
 675       p->record_thread_work_item(termination_phase, worker_id, cl.term_attempts());
 676     } else {
 677       p->record_or_add_time_secs(termination_phase, worker_id, cl.term_time());
 678       p->record_or_add_thread_work_item(termination_phase, worker_id, cl.term_attempts());
 679     }
 680     assert(pss->trim_ticks().value() == 0,
 681            "Unexpected partial trimming during evacuation value " JLONG_FORMAT,
 682            pss->trim_ticks().value());
 683   }
 684 
 685   virtual void start_work(uint worker_id) { }
 686 
 687   virtual void end_work(uint worker_id) { }
 688 
 689   virtual void scan_roots(G1ParScanThreadState* pss, uint worker_id) = 0;
 690 
 691   virtual void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) = 0;
 692 
 693 private:
 694   Atomic<bool> _pinned_regions_recorded;
 695 
 696 public:
 697   G1EvacuateRegionsBaseTask(const char* name,
 698                             G1ParScanThreadStateSet* per_thread_states,
 699                             G1ScannerTasksQueueSet* task_queues,
 700                             uint num_workers) :
 701     WorkerTask(name),
 702     _g1h(G1CollectedHeap::heap()),
 703     _per_thread_states(per_thread_states),
 704     _task_queues(task_queues),
 705     _terminator(num_workers, _task_queues),
 706     _pinned_regions_recorded(false)
 707   { }
 708 
 709   void work(uint worker_id) {
 710     start_work(worker_id);
 711 
 712     {
 713       ResourceMark rm;
 714 
 715       G1ParScanThreadState* pss = _per_thread_states->state_for_worker(worker_id);
 716       pss->set_ref_discoverer(_g1h->ref_processor_stw());
 717 
 718       if (_pinned_regions_recorded.compare_set(false, true)) {
 719         record_pinned_regions(pss, worker_id);
 720       }
 721       scan_roots(pss, worker_id);
 722       evacuate_live_objects(pss, worker_id);
 723     }
 724 
 725     end_work(worker_id);
 726   }
 727 };
 728 
 729 class G1EvacuateRegionsTask : public G1EvacuateRegionsBaseTask {
 730   G1RootProcessor* _root_processor;
 731   bool _has_optional_evacuation_work;
 732 
 733   void scan_roots(G1ParScanThreadState* pss, uint worker_id) {
 734     _root_processor->evacuate_roots(pss, worker_id);
 735     _g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::ScanHR, G1GCPhaseTimes::ObjCopy, _has_optional_evacuation_work);
 736     _g1h->rem_set()->scan_collection_set_code_roots(pss, worker_id, G1GCPhaseTimes::CodeRoots, G1GCPhaseTimes::ObjCopy);
 737     // There are no optional roots to scan right now.
 738 #ifdef ASSERT
 739     class VerifyOptionalCollectionSetRootsEmptyClosure : public G1HeapRegionClosure {
 740       G1ParScanThreadState* _pss;
 741 
 742     public:
 743       VerifyOptionalCollectionSetRootsEmptyClosure(G1ParScanThreadState* pss) : _pss(pss) { }
 744 
 745       bool do_heap_region(G1HeapRegion* r) override {
 746         assert(!r->has_index_in_opt_cset(), "must be");
 747         return false;
 748       }
 749     } cl(pss);
 750     _g1h->collection_set_iterate_increment_from(&cl, worker_id);
 751 #endif
 752   }
 753 
 754   void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) {
 755     G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::ObjCopy, G1GCPhaseTimes::Termination);
 756   }
 757 
 758   void start_work(uint worker_id) {
 759     _g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerStart, worker_id, Ticks::now().seconds());
 760   }
 761 
 762   void end_work(uint worker_id) {
 763     _g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerEnd, worker_id, Ticks::now().seconds());
 764   }
 765 
 766 public:
 767   G1EvacuateRegionsTask(G1CollectedHeap* g1h,
 768                         G1ParScanThreadStateSet* per_thread_states,
 769                         G1ScannerTasksQueueSet* task_queues,
 770                         G1RootProcessor* root_processor,
 771                         uint num_workers,
 772                         bool has_optional_evacuation_work) :
 773     G1EvacuateRegionsBaseTask("G1 Evacuate Regions", per_thread_states, task_queues, num_workers),
 774     _root_processor(root_processor),
 775     _has_optional_evacuation_work(has_optional_evacuation_work)
 776   { }
 777 };
 778 
 779 void G1YoungCollector::evacuate_initial_collection_set(G1ParScanThreadStateSet* per_thread_states,
 780                                                       bool has_optional_evacuation_work) {
 781   G1GCPhaseTimes* p = phase_times();
 782 
 783   rem_set()->merge_heap_roots(true /* initial_evacuation */);
 784 
 785   Tickspan task_time;
 786   const uint num_workers = workers()->active_workers();
 787 
 788   Ticks start_processing = Ticks::now();
 789   {
 790     G1RootProcessor root_processor(_g1h, num_workers > 1 /* is_parallel */);
 791     G1EvacuateRegionsTask g1_par_task(_g1h,
 792                                       per_thread_states,
 793                                       task_queues(),
 794                                       &root_processor,
 795                                       num_workers,
 796                                       has_optional_evacuation_work);
 797     task_time = run_task_timed(&g1_par_task);
 798     // Closing the inner scope will execute the destructor for the
 799     // G1RootProcessor object. By subtracting the WorkerThreads task from the total
 800     // time of this scope, we get the "NMethod List Cleanup" time. This list is
 801     // constructed during "STW two-phase nmethod root processing", see more in
 802     // nmethod.hpp
 803   }
 804   Tickspan total_processing = Ticks::now() - start_processing;
 805 
 806   p->record_initial_evac_time(task_time.seconds() * 1000.0);
 807   p->record_or_add_nmethod_list_cleanup_time((total_processing - task_time).seconds() * 1000.0);
 808 
 809   rem_set()->complete_evac_phase(has_optional_evacuation_work);
 810 }
 811 
 812 class G1EvacuateOptionalRegionsTask : public G1EvacuateRegionsBaseTask {
 813 
 814   void scan_roots(G1ParScanThreadState* pss, uint worker_id) {
 815     _g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::OptObjCopy, true /* remember_already_scanned_cards */);
 816     _g1h->rem_set()->scan_collection_set_code_roots(pss, worker_id, G1GCPhaseTimes::OptCodeRoots, G1GCPhaseTimes::OptObjCopy);
 817     _g1h->rem_set()->scan_collection_set_optional_roots(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::ObjCopy);
 818   }
 819 
 820   void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) {
 821     G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::OptObjCopy, G1GCPhaseTimes::OptTermination);
 822   }
 823 
 824 public:
 825   G1EvacuateOptionalRegionsTask(G1ParScanThreadStateSet* per_thread_states,
 826                                 G1ScannerTasksQueueSet* queues,
 827                                 uint num_workers) :
 828     G1EvacuateRegionsBaseTask("G1 Evacuate Optional Regions", per_thread_states, queues, num_workers) {
 829   }
 830 };
 831 
 832 void G1YoungCollector::evacuate_next_optional_regions(G1ParScanThreadStateSet* per_thread_states) {
 833   Tickspan task_time;
 834 
 835   Ticks start_processing = Ticks::now();
 836   {
 837     NMethodMarkingScope nmethod_marking_scope;
 838     G1EvacuateOptionalRegionsTask task(per_thread_states, task_queues(), workers()->active_workers());
 839     task_time = run_task_timed(&task);
 840     // See comment in evacuate_initial_collection_set() for the reason of the scope.
 841   }
 842   Tickspan total_processing = Ticks::now() - start_processing;
 843 
 844   G1GCPhaseTimes* p = phase_times();
 845   p->record_or_add_optional_evac_time(task_time.seconds() * 1000.0);
 846   p->record_or_add_nmethod_list_cleanup_time((total_processing - task_time).seconds() * 1000.0);
 847 }
 848 
 849 void G1YoungCollector::evacuate_optional_collection_set(G1ParScanThreadStateSet* per_thread_states) {
 850   const double pause_start_time_ms = policy()->cur_pause_start_sec() * 1000.0;
 851   double target_pause_time_ms = MaxGCPauseMillis;
 852 
 853   if (G1ForceOptionalEvacuation) {
 854     target_pause_time_ms = DBL_MAX;
 855   }
 856 
 857   while (!evacuation_alloc_failed() && collection_set()->num_optional_regions() > 0) {
 858 
 859     double time_used_ms = os::elapsedTime() * 1000.0 - pause_start_time_ms;
 860     double time_left_ms = target_pause_time_ms - time_used_ms;
 861 
 862     if (time_left_ms <= 0 ||
 863         !collection_set()->finalize_optional_for_evacuation(time_left_ms * policy()->optional_evacuation_fraction())) {
 864       log_trace(gc, ergo, cset)("Skipping evacuation of %u optional regions, no more regions can be evacuated in %.3fms",
 865                                 collection_set()->num_optional_regions(), time_left_ms);
 866       break;
 867     }
 868 
 869     rem_set()->merge_heap_roots(false /* initial_evacuation */);
 870 
 871     evacuate_next_optional_regions(per_thread_states);
 872 
 873     rem_set()->complete_evac_phase(true /* has_more_than_one_evacuation_phase */);
 874   }
 875 
 876   collection_set()->abandon_optional_collection_set(per_thread_states);
 877 }
 878 
 879 // Non Copying Keep Alive closure
 880 class G1KeepAliveClosure: public OopClosure {
 881   G1CollectedHeap*_g1h;
 882 public:
 883   G1KeepAliveClosure(G1CollectedHeap* g1h) :_g1h(g1h) {}
 884   void do_oop(narrowOop* p) { guarantee(false, "Not needed"); }
 885   void do_oop(oop* p) {
 886     oop obj = *p;
 887     assert(obj != nullptr, "the caller should have filtered out null values");
 888 
 889     const G1HeapRegionAttr region_attr =_g1h->region_attr(obj);
 890     assert(!region_attr.is_humongous_candidate(), "Humongous candidates should never be considered alive");
 891     if (region_attr.is_in_cset()) {
 892       assert(obj->is_forwarded(), "invariant" );
 893       *p = obj->forwardee();
 894     }
 895   }
 896 };
 897 
 898 // Copying Keep Alive closure - can be called from both
 899 // serial and parallel code as long as different worker
 900 // threads utilize different G1ParScanThreadState instances
 901 // and different queues.
 902 class G1CopyingKeepAliveClosure: public OopClosure {
 903   G1CollectedHeap* _g1h;
 904   G1ParScanThreadState*    _par_scan_state;
 905 
 906 public:
 907   G1CopyingKeepAliveClosure(G1CollectedHeap* g1h,
 908                             G1ParScanThreadState* pss):
 909     _g1h(g1h),
 910     _par_scan_state(pss)
 911   {}
 912 
 913   virtual void do_oop(narrowOop* p) { do_oop_work(p); }
 914   virtual void do_oop(      oop* p) { do_oop_work(p); }
 915 
 916   template <class T> void do_oop_work(T* p) {
 917     oop obj = RawAccess<>::oop_load(p);
 918 
 919     assert(!_g1h->region_attr(obj).is_humongous_candidate(), "Humongous candidates should never be considered alive");
 920     if (_g1h->is_in_cset(obj)) {
 921       // If the referent object has been forwarded (either copied
 922       // to a new location or to itself in the event of an
 923       // evacuation failure) then we need to update the reference
 924       // field and, if both reference and referent are in the G1
 925       // heap, update the RSet for the referent.
 926       //
 927       // If the referent has not been forwarded then we have to keep
 928       // it alive by policy. Therefore we have copy the referent.
 929       //
 930       // When the queue is drained (after each phase of reference processing)
 931       // the object and it's followers will be copied, the reference field set
 932       // to point to the new location, and the RSet updated.
 933       _par_scan_state->push_on_queue(ScannerTask(p));
 934     }
 935   }
 936 };
 937 
 938 class G1STWRefProcProxyTask : public RefProcProxyTask {
 939   G1CollectedHeap& _g1h;
 940   G1ParScanThreadStateSet& _pss;
 941   TaskTerminator _terminator;
 942   G1ScannerTasksQueueSet& _task_queues;
 943 
 944   // G1 specific closure for marking discovered fields. Need to mark the card in the
 945   // refinement table as the card table is in use by garbage collection.
 946   class G1EnqueueDiscoveredFieldClosure : public EnqueueDiscoveredFieldClosure {
 947     G1CollectedHeap* _g1h;
 948     G1ParScanThreadState* _pss;
 949 
 950   public:
 951     G1EnqueueDiscoveredFieldClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) : _g1h(g1h), _pss(pss) { }
 952 
 953     void enqueue(HeapWord* discovered_field_addr, oop value) override {
 954       assert(_g1h->is_in(discovered_field_addr), PTR_FORMAT " is not in heap ", p2i(discovered_field_addr));
 955       // Store the value first, whatever it is.
 956       RawAccess<>::oop_store(discovered_field_addr, value);
 957       if (value == nullptr) {
 958         return;
 959       }
 960       _pss->write_ref_field_post(discovered_field_addr, value);
 961     }
 962   };
 963 
 964 public:
 965   G1STWRefProcProxyTask(uint max_workers, G1CollectedHeap& g1h, G1ParScanThreadStateSet& pss, G1ScannerTasksQueueSet& task_queues)
 966     : RefProcProxyTask("G1STWRefProcProxyTask", max_workers),
 967       _g1h(g1h),
 968       _pss(pss),
 969       _terminator(max_workers, &task_queues),
 970       _task_queues(task_queues) {}
 971 
 972   void work(uint worker_id) override {
 973     assert(worker_id < _max_workers, "sanity");
 974     uint index = (_tm == RefProcThreadModel::Single) ? 0 : worker_id;
 975 
 976     G1ParScanThreadState* pss = _pss.state_for_worker(index);
 977     pss->set_ref_discoverer(nullptr);
 978 
 979     G1STWIsAliveClosure is_alive(&_g1h);
 980     G1CopyingKeepAliveClosure keep_alive(&_g1h, pss);
 981     G1EnqueueDiscoveredFieldClosure enqueue(&_g1h, pss);
 982     G1ParEvacuateFollowersClosure complete_gc(&_g1h, pss, &_task_queues, _tm == RefProcThreadModel::Single ? nullptr : &_terminator, G1GCPhaseTimes::ObjCopy);
 983     _rp_task->rp_work(worker_id, &is_alive, &keep_alive, &enqueue, &complete_gc);
 984 
 985     // We have completed copying any necessary live referent objects.
 986     assert(pss->queue_is_empty(), "both queue and overflow should be empty");
 987   }
 988 
 989   void prepare_run_task_hook() override {
 990     _terminator.reset_for_reuse(_queue_count);
 991   }
 992 };
 993 
 994 void G1YoungCollector::process_discovered_references(G1ParScanThreadStateSet* per_thread_states) {
 995   Ticks start = Ticks::now();
 996 
 997   ReferenceProcessor* rp = ref_processor_stw();
 998   assert(rp->discovery_enabled(), "should have been enabled");
 999 
1000   G1STWRefProcProxyTask task(rp->max_num_queues(), *_g1h, *per_thread_states, *task_queues());
1001   ReferenceProcessorPhaseTimes& pt = *phase_times()->ref_phase_times();
1002   ReferenceProcessorStats stats = rp->process_discovered_references(task, _g1h->workers(), pt);
1003 
1004   gc_tracer_stw()->report_gc_reference_stats(stats);
1005 
1006   _g1h->make_pending_list_reachable();
1007 
1008   phase_times()->record_ref_proc_time((Ticks::now() - start).seconds() * MILLIUNITS);
1009 }
1010 
1011 void G1YoungCollector::post_evacuate_cleanup_1(G1ParScanThreadStateSet* per_thread_states) {
1012   Ticks start = Ticks::now();
1013   {
1014     G1PostEvacuateCollectionSetCleanupTask1 cl(per_thread_states, &_evac_failure_regions);
1015     _g1h->run_batch_task(&cl);
1016   }
1017   phase_times()->record_post_evacuate_cleanup_task_1_time((Ticks::now() - start).seconds() * 1000.0);
1018 }
1019 
1020 void G1YoungCollector::post_evacuate_cleanup_2(G1ParScanThreadStateSet* per_thread_states,
1021                                                G1EvacInfo* evacuation_info) {
1022   Ticks start = Ticks::now();
1023   {
1024     G1PostEvacuateCollectionSetCleanupTask2 cl(per_thread_states, evacuation_info, &_evac_failure_regions);
1025     _g1h->run_batch_task(&cl);
1026   }
1027   phase_times()->record_post_evacuate_cleanup_task_2_time((Ticks::now() - start).seconds() * 1000.0);
1028 }
1029 
1030 void G1YoungCollector::enqueue_candidates_as_root_regions() {
1031   assert(collector_state()->is_in_concurrent_start_gc(), "must be");
1032 
1033   G1CollectionSetCandidates* candidates = collection_set()->candidates();
1034   candidates->iterate_regions([&] (G1HeapRegion* r) {
1035     _g1h->concurrent_mark()->add_root_region_set_bottom(r);
1036   });
1037 }
1038 
1039 void G1YoungCollector::post_evacuate_collection_set(G1EvacInfo* evacuation_info,
1040                                                     G1ParScanThreadStateSet* per_thread_states) {
1041   G1GCPhaseTimes* p = phase_times();
1042 
1043   // Process any discovered reference objects - we have
1044   // to do this _before_ we retire the GC alloc regions
1045   // as we may have to copy some 'reachable' referent
1046   // objects (and their reachable sub-graphs) that were
1047   // not copied during the pause.
1048   process_discovered_references(per_thread_states);
1049 
1050   G1STWIsAliveClosure is_alive(_g1h);
1051   G1KeepAliveClosure keep_alive(_g1h);
1052 
1053   WeakProcessor::weak_oops_do(workers(), &is_alive, &keep_alive, p->weak_phase_times());
1054 
1055   allocator()->release_gc_alloc_regions(evacuation_info);
1056 
1057 #if TASKQUEUE_STATS
1058   _g1h->task_queues()->print_and_reset_taskqueue_stats("Young GC");
1059   // Logging uses thread states, which are deleted by cleanup, so this must
1060   // be done before cleanup.
1061   per_thread_states->print_partial_array_task_stats();
1062 #endif // TASKQUEUE_STATS
1063 
1064   post_evacuate_cleanup_1(per_thread_states);
1065 
1066   post_evacuate_cleanup_2(per_thread_states, evacuation_info);
1067 
1068   // Regions in the collection set candidates are roots for the marking (they are
1069   // not marked through considering they are very likely to be reclaimed soon.
1070   // They need to be enqueued explicitly compared to survivor regions.
1071   if (collector_state()->is_in_concurrent_start_gc()) {
1072     enqueue_candidates_as_root_regions();
1073   }
1074 
1075   _evac_failure_regions.post_collection();
1076 
1077   assert_used_and_recalculate_used_equal(_g1h);
1078 
1079   _g1h->rebuild_free_region_list();
1080 
1081   _g1h->record_obj_copy_mem_stats();
1082 
1083   evacuation_info->set_bytes_used(_g1h->bytes_used_during_gc());
1084 
1085   _g1h->prepare_for_mutator_after_young_collection();
1086 
1087   _g1h->gc_epilogue(false);
1088 
1089   _g1h->resize_heap_after_young_collection(_allocation_word_size);
1090 }
1091 
1092 bool G1YoungCollector::evacuation_failed() const {
1093   return _evac_failure_regions.has_regions_evac_failed();
1094 }
1095 
1096 bool G1YoungCollector::evacuation_pinned() const {
1097   return _evac_failure_regions.has_regions_evac_pinned();
1098 }
1099 
1100 bool G1YoungCollector::evacuation_alloc_failed() const {
1101   return _evac_failure_regions.has_regions_alloc_failed();
1102 }
1103 
1104 G1YoungCollector::G1YoungCollector(GCCause::Cause gc_cause,
1105                                    size_t allocation_word_size) :
1106   _g1h(G1CollectedHeap::heap()),
1107   _gc_cause(gc_cause),
1108   _allocation_word_size(allocation_word_size),
1109   _next_state(),
1110   _concurrent_operation_is_full_mark(false),
1111   _evac_failure_regions()
1112 {
1113 }
1114 
1115 void G1YoungCollector::collect() {
1116   // Do timing/tracing/statistics/pre- and post-logging/verification work not
1117   // directly related to the collection. They should not be accounted for in
1118   // collection work timing.
1119 
1120   // The G1YoungGCTraceTime message depends on collector state, so must come after
1121   // determining collector state.
1122   G1YoungGCTraceTime tm(this, _gc_cause);
1123 
1124   // JFR
1125   G1YoungGCJFRTracerMark jtm(this);
1126   // JStat/MXBeans
1127   G1YoungGCMonitoringScope ms(monitoring_support(),
1128                               !collection_set()->candidates()->is_empty() /* all_memory_pools_affected */);
1129   // Create the heap printer before internal pause timing to have
1130   // heap information printed as last part of detailed GC log.
1131   G1HeapPrinterMark hpm(_g1h);
1132   // Young GC internal pause timing
1133   G1YoungGCNotifyPauseMark npm(this);
1134 
1135   // Verification may use the workers, so they must be set up before.
1136   // Individual parallel phases may override this.
1137   set_young_collection_default_active_worker_threads();
1138 
1139   // Complete root region scan before moving any objects to preserve the SATB invariant.
1140   complete_root_region_scan();
1141 
1142   G1YoungGCVerifierMark vm(this);
1143   {
1144     // Actual collection work starts and is executed (only) in this scope.
1145 
1146     // Young GC internal collection timing. The elapsed time recorded in the
1147     // policy for the collection deliberately elides verification (and some
1148     // other trivial setup above).
1149     policy()->record_young_collection_start();
1150 
1151     pre_evacuate_collection_set(jtm.evacuation_info());
1152 
1153     G1ParScanThreadStateSet per_thread_states(_g1h,
1154                                               workers()->active_workers(),
1155                                               collection_set(),
1156                                               &_evac_failure_regions);
1157 
1158     bool may_do_optional_evacuation = collection_set()->num_optional_regions() != 0;
1159     // Actually do the work...
1160     evacuate_initial_collection_set(&per_thread_states, may_do_optional_evacuation);
1161 
1162     if (may_do_optional_evacuation) {
1163       evacuate_optional_collection_set(&per_thread_states);
1164     }
1165     post_evacuate_collection_set(jtm.evacuation_info(), &per_thread_states);
1166 
1167     // Refine the type of a concurrent mark operation now that we did the
1168     // evacuation, eventually aborting it.
1169     _concurrent_operation_is_full_mark = policy()->concurrent_operation_is_full_mark("Revise IHOP", _allocation_word_size);
1170 
1171     _next_state = policy()->record_young_collection_end(_concurrent_operation_is_full_mark, evacuation_alloc_failed(), _allocation_word_size);
1172   }
1173 }