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