1 /*
   2  * Copyright (c) 2024, 2026, Oracle and/or its affiliates. All rights reserved.
   3  * Copyright (c) 2021, 2022, Red Hat, Inc. All rights reserved.
   4  * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
   5  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   6  *
   7  * This code is free software; you can redistribute it and/or modify it
   8  * under the terms of the GNU General Public License version 2 only, as
   9  * published by the Free Software Foundation.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  *
  25  */
  26 
  27 
  28 #include "gc/shared/barrierSetNMethod.hpp"
  29 #include "gc/shared/collectorCounters.hpp"
  30 #include "gc/shared/continuationGCSupport.inline.hpp"
  31 #include "gc/shenandoah/shenandoahBreakpoint.hpp"
  32 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
  33 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
  34 #include "gc/shenandoah/shenandoahConcurrentGC.hpp"
  35 #include "gc/shenandoah/shenandoahForwarding.inline.hpp"
  36 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  37 #include "gc/shenandoah/shenandoahGeneration.hpp"
  38 #include "gc/shenandoah/shenandoahGenerationalHeap.hpp"
  39 #include "gc/shenandoah/shenandoahLock.hpp"
  40 #include "gc/shenandoah/shenandoahMark.inline.hpp"
  41 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
  42 #include "gc/shenandoah/shenandoahOldGeneration.hpp"
  43 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  44 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
  45 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
  46 #include "gc/shenandoah/shenandoahStackWatermark.hpp"
  47 #include "gc/shenandoah/shenandoahUtils.hpp"
  48 #include "gc/shenandoah/shenandoahVerifier.hpp"
  49 #include "gc/shenandoah/shenandoahVMOperations.hpp"
  50 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
  51 #include "gc/shenandoah/shenandoahWorkGroup.hpp"
  52 #include "gc/shenandoah/shenandoahYoungGeneration.hpp"
  53 #include "memory/allocation.hpp"
  54 #include "prims/jvmtiTagMap.hpp"
  55 #include "runtime/vmThread.hpp"
  56 #include "utilities/events.hpp"
  57 
  58 // Breakpoint support
  59 class ShenandoahBreakpointGCScope : public StackObj {
  60 private:
  61   const GCCause::Cause _cause;
  62 public:
  63   ShenandoahBreakpointGCScope(GCCause::Cause cause) : _cause(cause) {
  64     if (cause == GCCause::_wb_breakpoint) {
  65       ShenandoahBreakpoint::start_gc();
  66       ShenandoahBreakpoint::at_before_gc();
  67     }
  68   }
  69 
  70   ~ShenandoahBreakpointGCScope() {
  71     if (_cause == GCCause::_wb_breakpoint) {
  72       ShenandoahBreakpoint::at_after_gc();
  73     }
  74   }
  75 };
  76 
  77 class ShenandoahBreakpointMarkScope : public StackObj {
  78 private:
  79   const GCCause::Cause _cause;
  80 public:
  81   ShenandoahBreakpointMarkScope(GCCause::Cause cause) : _cause(cause) {
  82     if (_cause == GCCause::_wb_breakpoint) {
  83       ShenandoahBreakpoint::at_after_marking_started();
  84     }
  85   }
  86 
  87   ~ShenandoahBreakpointMarkScope() {
  88     if (_cause == GCCause::_wb_breakpoint) {
  89       ShenandoahBreakpoint::at_before_marking_completed();
  90     }
  91   }
  92 };
  93 
  94 ShenandoahConcurrentGC::ShenandoahConcurrentGC(ShenandoahGeneration* generation, bool do_old_gc_bootstrap) :
  95   ShenandoahGC(generation),
  96   _mark(generation),
  97   _degen_point(ShenandoahDegenPoint::_degenerated_unset),
  98   _abbreviated(false),
  99   _do_old_gc_bootstrap(do_old_gc_bootstrap) {
 100 }
 101 
 102 ShenandoahGC::ShenandoahDegenPoint ShenandoahConcurrentGC::degen_point() const {
 103   return _degen_point;
 104 }
 105 
 106 void ShenandoahConcurrentGC::entry_concurrent_update_refs_prepare(ShenandoahHeap* const heap) {
 107   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 108   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent init update refs", "");
 109   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_update_refs_prepare);
 110   EventMark em("%s", msg);
 111 
 112   heap->try_inject_pin();
 113   // Evacuation is complete, retire gc labs and change gc state
 114   heap->concurrent_prepare_for_update_refs();
 115 }
 116 
 117 void ShenandoahConcurrentGC::entry_update_card_table() {
 118   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 119   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 120   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent update cards", "");
 121   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_update_card_table);
 122   EventMark em("%s", msg);
 123 
 124   ShenandoahWorkerScope scope(heap->workers(),
 125                               ShenandoahWorkerPolicy::calc_workers_for_conc_evac(),
 126                               "concurrent update cards");
 127 
 128   heap->try_inject_pin();
 129   // Heap needs to be parsable here.
 130   // Also, parallel heap region iterate must have a phase set.
 131   assert(ShenandoahTimingsTracker::is_current_phase_valid(), "Current phase must be set");
 132   ShenandoahGenerationalHeap::heap()->old_generation()->update_card_table();
 133 }
 134 
 135 bool ShenandoahConcurrentGC::collect(GCCause::Cause cause) {
 136   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 137   _generation->ref_processor()->set_soft_reference_policy(
 138       GCCause::should_clear_all_soft_refs(cause));
 139 
 140   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent GC", "");
 141   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_gc, /* log_heap_usage = */ true);
 142 
 143   ShenandoahBreakpointGCScope breakpoint_gc_scope(cause);
 144 
 145   // Reset for upcoming marking
 146   entry_reset();
 147 
 148   // Start initial mark under STW
 149   vmop_entry_init_mark();
 150 
 151   {
 152     ShenandoahBreakpointMarkScope breakpoint_mark_scope(cause);
 153 
 154     // Reset task queue stats here, rather than in mark_concurrent_roots,
 155     // because remembered set scan will `push` oops into the queues and
 156     // resetting after this happens will lose those counts.
 157     TASKQUEUE_STATS_ONLY(_mark.task_queues()->reset_taskqueue_stats());
 158 
 159     // Concurrent remembered set scanning
 160     entry_scan_remembered_set();
 161 
 162     // Concurrent mark roots
 163     entry_mark_roots();
 164     if (check_cancellation_and_abort(ShenandoahDegenPoint::_degenerated_roots)) {
 165       return false;
 166     }
 167 
 168     // Continue concurrent mark
 169     entry_mark();
 170     if (check_cancellation_and_abort(ShenandoahDegenPoint::_degenerated_mark)) {
 171       return false;
 172     }
 173   }
 174 
 175   // Complete marking under STW, and start evacuation
 176   vmop_entry_final_mark();
 177 
 178   // If the GC was cancelled before final mark, nothing happens on the safepoint. We are still
 179   // in the marking phase and must resume the degenerated cycle from there. If the GC was cancelled
 180   // after final mark, then we've entered the evacuation phase and must resume the degenerated cycle
 181   // from that phase.
 182   if (_generation->is_concurrent_mark_in_progress()) {
 183     bool cancelled = check_cancellation_and_abort(ShenandoahDegenPoint::_degenerated_mark);
 184     assert(cancelled, "GC must have been cancelled between concurrent and final mark");
 185     return false;
 186   }
 187 
 188   assert(heap->is_concurrent_weak_root_in_progress(), "Must be doing weak roots now");
 189 
 190   // Finish all thread/stack roots if needed. This completes stack watermark processing.
 191   if (heap->is_evacuation_in_progress()) {
 192     entry_thread_roots();
 193   }
 194 
 195   // Process weak roots that might still point to regions that would be broken by cleanup.
 196   // We cannot recycle regions because weak roots need to know what is marked in trashed regions.
 197   entry_weak_refs();
 198   entry_weak_roots();
 199 
 200   // Perform concurrent class unloading before any regions get recycled. Class unloading may
 201   // need to inspect unmarked objects in trashed regions.
 202   if (heap->unload_classes()) {
 203     entry_class_unloading();
 204   }
 205 
 206   // Final mark might have reclaimed some immediate garbage, kick cleanup to reclaim
 207   // the space. This would be the last action if there is nothing to evacuate.  Note that
 208   // we will not age young-gen objects in the case that we skip evacuation.
 209   entry_cleanup_early();
 210 
 211   // Processing strong roots
 212   // This may be skipped if there is nothing to update/evacuate.
 213   // If so, strong_root_in_progress would be unset.
 214   if (heap->is_concurrent_strong_root_in_progress()) {
 215     entry_strong_roots();
 216   }
 217 
 218   // Roots processing is complete, put the weak roots flag down.
 219   entry_final_roots();
 220 
 221   // Continue the cycle with evacuation and optional update-refs.
 222   // This may be skipped if there is nothing to evacuate.
 223   // If so, evac_in_progress would be unset by collection set preparation code.
 224   if (heap->is_evacuation_in_progress()) {
 225     // Concurrently evacuate
 226     entry_evacuate();
 227     if (check_cancellation_and_abort(ShenandoahDegenPoint::_degenerated_evac)) {
 228       return false;
 229     }
 230 
 231     // Perform update-refs phase.
 232     entry_concurrent_update_refs_prepare(heap);
 233 
 234     if (ShenandoahHeap::heap()->mode()->is_generational()) {
 235       entry_update_card_table();
 236     }
 237 
 238     if (ShenandoahVerify) {
 239       vmop_entry_init_update_refs();
 240     }
 241 
 242     entry_update_refs();
 243     if (check_cancellation_and_abort(ShenandoahDegenPoint::_degenerated_update_refs)) {
 244       return false;
 245     }
 246 
 247     // Concurrent update thread roots
 248     entry_update_thread_roots();
 249     if (check_cancellation_and_abort(ShenandoahDegenPoint::_degenerated_update_refs)) {
 250       return false;
 251     }
 252 
 253     vmop_entry_final_update_refs();
 254 
 255     // Update references freed up collection set, kick the cleanup to reclaim the space.
 256     entry_cleanup_complete();
 257   } else {
 258     _abbreviated = true;
 259 
 260     if (heap->mode()->is_generational()) {
 261       entry_complete_abbreviated_cycle();
 262 
 263       // If the promote-in-place operation was cancelled, we can have the degenerated
 264       // cycle complete the operation. It will see that no evacuations are in progress,
 265       // and that there are regions wanting promotion. The risk with not handling the
 266       // cancellation would be failing to restore top for these regions and leaving
 267       // them unable to serve allocations for the old generation.
 268       if (check_cancellation_and_abort(ShenandoahDegenPoint::_degenerated_evac)) {
 269         return false;
 270       }
 271     }
 272 
 273     // In normal cycle, final-update-refs would verify at the end of the cycle.
 274     // In abbreviated cycle, we need to verify separately.
 275     if (ShenandoahVerify) {
 276       vmop_entry_final_verify();
 277     }
 278   }
 279 
 280   // We defer generation resizing actions until after cset regions have been recycled.  We do this even following an
 281   // abbreviated cycle.
 282   if (heap->mode()->is_generational()) {
 283     ShenandoahGenerationalHeap::heap()->complete_concurrent_cycle();
 284   }
 285 
 286   // Instead of always resetting immediately before the start of a new GC, we can often reset at the end of the
 287   // previous GC. This allows us to start the next GC cycle more quickly after a trigger condition is detected,
 288   // reducing the likelihood that GC will degenerate.
 289   entry_reset_after_collect();
 290 
 291   return true;
 292 }
 293 
 294 void ShenandoahConcurrentGC::entry_complete_abbreviated_cycle() {
 295   shenandoah_assert_generational();
 296 
 297   ShenandoahGenerationalHeap* const heap = ShenandoahGenerationalHeap::heap();
 298 
 299   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 300   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent complete abbreviated cycle", "");
 301   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::complete_abbreviated);
 302   EventMark em("%s", msg);
 303 
 304   ShenandoahWorkerScope scope(heap->workers(),
 305                               ShenandoahWorkerPolicy::calc_workers_for_conc_evac(),
 306                               msg);
 307 
 308   heap->try_inject_pin();
 309   // We chose not to evacuate because we found sufficient immediate garbage.
 310   // However, there may still be regions to promote in place, so do that now.
 311   if (heap->old_generation()->has_in_place_promotions()) {
 312     ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::complete_abbreviated_promote_in_place);
 313     ShenandoahGCWorkerPhase worker_phase(ShenandoahPhaseTimings::complete_abbreviated_promote_in_place);
 314     heap->promote_regions_in_place(_generation, true);
 315   }
 316 
 317   // At this point, the cycle is effectively complete. If the cycle has been cancelled here,
 318   // the control thread will detect it on its next iteration and run a degenerated young cycle.
 319   if (!heap->cancelled_gc() && !_generation->is_old()) {
 320     ShenandoahTimingsTracker tracker(ShenandoahPhaseTimings::complete_abbreviated_update_region_ages);
 321     heap->update_region_ages(_generation->complete_marking_context());
 322   }
 323 }
 324 
 325 void ShenandoahConcurrentGC::vmop_entry_init_mark() {
 326   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 327   TraceCollectorStats tcs(heap->monitoring_support()->stw_collection_counters());
 328   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::init_mark_gross);
 329 
 330   heap->try_inject_alloc_failure();
 331   VM_ShenandoahInitMark op(this);
 332   VMThread::execute(&op); // jump to entry_init_mark() under safepoint
 333 }
 334 
 335 void ShenandoahConcurrentGC::vmop_entry_final_mark() {
 336   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 337   TraceCollectorStats tcs(heap->monitoring_support()->stw_collection_counters());
 338   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::final_mark_gross);
 339 
 340   heap->try_inject_alloc_failure();
 341   VM_ShenandoahFinalMarkStartEvac op(this);
 342   VMThread::execute(&op); // jump to entry_final_mark under safepoint
 343   heap->try_inject_pin();
 344 }
 345 
 346 void ShenandoahConcurrentGC::vmop_entry_init_update_refs() {
 347   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 348   TraceCollectorStats tcs(heap->monitoring_support()->stw_collection_counters());
 349   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::init_update_refs_gross);
 350 
 351   heap->try_inject_alloc_failure();
 352   heap->try_inject_pin();
 353   VM_ShenandoahInitUpdateRefs op(this);
 354   VMThread::execute(&op);
 355 }
 356 
 357 void ShenandoahConcurrentGC::vmop_entry_final_update_refs() {
 358   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 359   TraceCollectorStats tcs(heap->monitoring_support()->stw_collection_counters());
 360   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::final_update_refs_gross);
 361 
 362   heap->try_inject_alloc_failure();
 363   heap->try_inject_pin();
 364   VM_ShenandoahFinalUpdateRefs op(this);
 365   VMThread::execute(&op);
 366 }
 367 
 368 void ShenandoahConcurrentGC::vmop_entry_final_verify() {
 369   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 370   TraceCollectorStats tcs(heap->monitoring_support()->stw_collection_counters());
 371   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::final_verify_gross);
 372 
 373   // This phase does not use workers, no need for setup
 374   heap->try_inject_alloc_failure();
 375   heap->try_inject_pin();
 376   VM_ShenandoahFinalVerify op(this);
 377   VMThread::execute(&op);
 378 }
 379 
 380 void ShenandoahConcurrentGC::entry_init_mark() {
 381   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 382   assert(!heap->has_forwarded_objects(), "Should not have forwarded objects here");
 383 
 384   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Pause Init Mark", "");
 385   ShenandoahPauseSubphase gc_phase(msg, ShenandoahPhaseTimings::init_mark);
 386   EventMark em("%s", msg);
 387 
 388   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
 389                               ShenandoahWorkerPolicy::calc_workers_for_init_marking(),
 390                               "init marking");
 391 
 392   op_init_mark();
 393 }
 394 
 395 void ShenandoahConcurrentGC::entry_final_mark() {
 396   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 397   assert(!heap->has_forwarded_objects() || heap->is_concurrent_old_mark_in_progress(),
 398          "Should not have forwarded objects during final mark, unless old gen concurrent mark is running");
 399 
 400   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Pause Final Mark", "");
 401   ShenandoahPauseSubphase gc_phase(msg, ShenandoahPhaseTimings::final_mark);
 402   EventMark em("%s", msg);
 403 
 404   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
 405                               ShenandoahWorkerPolicy::calc_workers_for_final_marking(),
 406                               "final marking");
 407 
 408   op_final_mark();
 409 }
 410 
 411 void ShenandoahConcurrentGC::entry_init_update_refs() {
 412   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Pause Init Update Refs", "");
 413   ShenandoahPauseSubphase gc_phase(msg, ShenandoahPhaseTimings::init_update_refs);
 414   EventMark em("%s", msg);
 415 
 416   // No workers used in this phase, no setup required
 417   op_init_update_refs();
 418 }
 419 
 420 void ShenandoahConcurrentGC::entry_final_update_refs() {
 421   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Pause Final Update Refs", "");
 422   ShenandoahPauseSubphase gc_phase(msg, ShenandoahPhaseTimings::final_update_refs);
 423   EventMark em("%s", msg);
 424 
 425   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
 426                               ShenandoahWorkerPolicy::calc_workers_for_final_update_ref(),
 427                               "final reference update");
 428 
 429   op_final_update_refs();
 430 }
 431 
 432 void ShenandoahConcurrentGC::entry_final_verify() {
 433   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Pause Verify Final", "");
 434   ShenandoahPauseSubphase gc_phase(msg, ShenandoahPhaseTimings::final_verify);
 435   EventMark em("%s", msg);
 436 
 437   op_verify_final();
 438 }
 439 
 440 void ShenandoahConcurrentGC::entry_reset() {
 441   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 442   heap->release_injected_pins();
 443   heap->try_inject_alloc_failure();
 444 
 445   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 446   {
 447     SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent reset", "");
 448     ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_reset);
 449     EventMark em("%s", msg);
 450 
 451     ShenandoahWorkerScope scope(heap->workers(),
 452                                 ShenandoahWorkerPolicy::calc_workers_for_conc_reset(),
 453                                 msg);
 454     op_reset();
 455   }
 456 }
 457 
 458 void ShenandoahConcurrentGC::entry_scan_remembered_set() {
 459   if (_generation->is_young()) {
 460     ShenandoahHeap* const heap = ShenandoahHeap::heap();
 461     TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 462 
 463     SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent remembered set scanning", "");
 464     ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::init_scan_rset);
 465     EventMark em("%s", msg);
 466 
 467     ShenandoahWorkerScope scope(heap->workers(),
 468                                 ShenandoahWorkerPolicy::calc_workers_for_rs_scanning(),
 469                                 msg);
 470 
 471     heap->try_inject_alloc_failure();
 472     _generation->scan_remembered_set(true /* is_concurrent */);
 473   }
 474 }
 475 
 476 void ShenandoahConcurrentGC::entry_mark_roots() {
 477   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 478   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 479   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent marking roots", "");
 480   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_mark_roots);
 481   EventMark em("%s", msg);
 482 
 483   ShenandoahWorkerScope scope(heap->workers(),
 484                               ShenandoahWorkerPolicy::calc_workers_for_conc_marking(),
 485                               "concurrent marking roots");
 486 
 487   heap->try_inject_alloc_failure();
 488   op_mark_roots();
 489 }
 490 
 491 void ShenandoahConcurrentGC::entry_mark() {
 492   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 493   assert(!heap->has_forwarded_objects() || heap->is_concurrent_old_mark_in_progress(),
 494          "Should not have forwarded objects concurrent mark, unless old gen concurrent mark is running");
 495 
 496   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 497   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent marking", "");
 498   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_mark);
 499   EventMark em("%s", msg);
 500 
 501   ShenandoahWorkerScope scope(heap->workers(),
 502                               ShenandoahWorkerPolicy::calc_workers_for_conc_marking(),
 503                               "concurrent marking");
 504 
 505   heap->try_inject_alloc_failure();
 506   op_mark();
 507   heap->try_inject_pin();
 508 }
 509 
 510 void ShenandoahConcurrentGC::entry_thread_roots() {
 511   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 512   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent thread roots", "");
 513   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_thread_roots);
 514   EventMark em("%s", msg);
 515 
 516   ShenandoahWorkerScope scope(heap->workers(),
 517                               ShenandoahWorkerPolicy::calc_workers_for_conc_root_processing(),
 518                               msg);
 519 
 520   heap->try_inject_alloc_failure();
 521   heap->try_inject_pin();
 522   op_thread_roots();
 523 }
 524 
 525 void ShenandoahConcurrentGC::entry_weak_refs() {
 526   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 527   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent weak references", "");
 528   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_weak_refs);
 529   EventMark em("%s", msg);
 530 
 531   ShenandoahWorkerScope scope(heap->workers(),
 532                               ShenandoahWorkerPolicy::calc_workers_for_conc_refs_processing(),
 533                               "concurrent weak references");
 534 
 535   heap->try_inject_alloc_failure();
 536   heap->try_inject_pin();
 537   op_weak_refs();
 538 }
 539 
 540 void ShenandoahConcurrentGC::entry_weak_roots() {
 541   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 542   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 543   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent weak roots", "");
 544   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_weak_roots);
 545   EventMark em("%s", msg);
 546 
 547   ShenandoahWorkerScope scope(heap->workers(),
 548                               ShenandoahWorkerPolicy::calc_workers_for_conc_root_processing(),
 549                               "concurrent weak root");
 550 
 551   heap->try_inject_alloc_failure();
 552   heap->try_inject_pin();
 553   op_weak_roots();
 554 }
 555 
 556 void ShenandoahConcurrentGC::entry_class_unloading() {
 557   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 558   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 559   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent class unloading", "");
 560   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_class_unload);
 561   EventMark em("%s", msg);
 562 
 563   ShenandoahWorkerScope scope(heap->workers(),
 564                               ShenandoahWorkerPolicy::calc_workers_for_conc_root_processing(),
 565                               "concurrent class unloading");
 566 
 567   heap->try_inject_alloc_failure();
 568   heap->try_inject_pin();
 569   op_class_unloading();
 570 }
 571 
 572 void ShenandoahConcurrentGC::entry_strong_roots() {
 573   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 574   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 575   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent strong roots", "");
 576   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_strong_roots);
 577   EventMark em("%s", msg);
 578 
 579   ShenandoahGCWorkerPhase worker_phase(ShenandoahPhaseTimings::conc_strong_roots);
 580 
 581   ShenandoahWorkerScope scope(heap->workers(),
 582                               ShenandoahWorkerPolicy::calc_workers_for_conc_root_processing(),
 583                               "concurrent strong root");
 584 
 585   heap->try_inject_alloc_failure();
 586   heap->try_inject_pin();
 587   op_strong_roots();
 588 }
 589 
 590 void ShenandoahConcurrentGC::entry_cleanup_early() {
 591   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 592   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 593   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent cleanup", "");
 594   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_cleanup_early, false /* log_heap_usage */);
 595   EventMark em("%s", msg);
 596 
 597   // This phase does not use workers, no need for setup
 598   heap->try_inject_alloc_failure();
 599   heap->try_inject_pin();
 600   op_cleanup_early();
 601   if (!heap->is_evacuation_in_progress()) {
 602     // This is an abbreviated cycle.  Rebuild the freeset in order to establish reserves for the next GC cycle.  Doing
 603     // the rebuild ASAP also expedites availability of immediate trash, reducing the likelihood that we will degenerate
 604     // during promote-in-place processing.
 605     heap->rebuild_free_set(true /*concurrent*/);
 606   }
 607 }
 608 
 609 void ShenandoahConcurrentGC::entry_evacuate() {
 610   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 611   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 612   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent evacuation", "");
 613   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_evac);
 614   EventMark em("%s", msg);
 615 
 616   ShenandoahWorkerScope scope(heap->workers(),
 617                               ShenandoahWorkerPolicy::calc_workers_for_conc_evac(),
 618                               "concurrent evacuation");
 619 
 620   heap->try_inject_alloc_failure();
 621   heap->try_inject_pin();
 622   op_evacuate();
 623 }
 624 
 625 void ShenandoahConcurrentGC::entry_update_thread_roots() {
 626   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 627   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 628   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent update thread roots", "");
 629   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_update_thread_roots);
 630   EventMark em("%s", msg);
 631 
 632   // No workers used in this phase, no setup required
 633   heap->try_inject_alloc_failure();
 634   heap->try_inject_pin();
 635   op_update_thread_roots();
 636 }
 637 
 638 void ShenandoahConcurrentGC::entry_update_refs() {
 639   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 640   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 641   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent update references", "");
 642   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_update_refs);
 643   EventMark em("%s", msg);
 644 
 645   ShenandoahWorkerScope scope(heap->workers(),
 646                               ShenandoahWorkerPolicy::calc_workers_for_conc_update_ref(),
 647                               "concurrent reference update");
 648 
 649   heap->try_inject_alloc_failure();
 650   heap->try_inject_pin();
 651   op_update_refs();
 652 }
 653 
 654 void ShenandoahConcurrentGC::entry_cleanup_complete() {
 655   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 656   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 657   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent cleanup", "");
 658   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_cleanup_complete, false /* log_heap_usage */);
 659   EventMark em("%s", msg);
 660 
 661   // This phase does not use workers, no need for setup
 662   heap->try_inject_alloc_failure();
 663   op_cleanup_complete();
 664 }
 665 
 666 void ShenandoahConcurrentGC::entry_reset_after_collect() {
 667   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 668   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 669   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent reset after collect", "");
 670   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_reset_after_collect);
 671   EventMark em("%s", msg);
 672 
 673   op_reset_after_collect();
 674 }
 675 
 676 void ShenandoahConcurrentGC::op_reset() {
 677   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 678 
 679   // If it is old GC bootstrap cycle, always clear bitmap for global gen
 680   // to ensure bitmap for old gen is clear for old GC cycle after this.
 681   if (_do_old_gc_bootstrap) {
 682     assert(!heap->is_prepare_for_old_mark_in_progress(), "Cannot reset old without making it parsable");
 683     heap->global_generation()->prepare_gc();
 684   } else {
 685     _generation->prepare_gc();
 686   }
 687 
 688   if (heap->mode()->is_generational()) {
 689     heap->old_generation()->card_scan()->mark_read_table_as_clean();
 690   }
 691 }
 692 
 693 class ShenandoahInitMarkUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
 694 private:
 695   ShenandoahMarkingContext* const _ctx;
 696 public:
 697   ShenandoahInitMarkUpdateRegionStateClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
 698 
 699   void heap_region_do(ShenandoahHeapRegion* r) {
 700     assert(!r->has_live(), "Region %zu should have no live data", r->index());
 701     if (r->is_active()) {
 702       // Check if region needs updating its TAMS. We have updated it already during concurrent
 703       // reset, so it is very likely we don't need to do another write here.  Since most regions
 704       // are not "active", this path is relatively rare.
 705       if (_ctx->top_at_mark_start(r) != r->top()) {
 706         _ctx->capture_top_at_mark_start(r);
 707       }
 708     } else {
 709       assert(_ctx->top_at_mark_start(r) == r->top(),
 710              "Region %zu should already have correct TAMS", r->index());
 711     }
 712   }
 713 
 714   bool is_thread_safe() { return true; }
 715 };
 716 
 717 void ShenandoahConcurrentGC::start_mark() {
 718   _mark.start_mark();
 719 }
 720 
 721 void ShenandoahConcurrentGC::op_init_mark() {
 722   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 723   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
 724   assert(Thread::current()->is_VM_thread(), "can only do this in VMThread");
 725 
 726   assert(_generation->is_bitmap_clear(), "need clear marking bitmap");
 727   assert(!_generation->is_mark_complete(), "should not be complete");
 728   assert(!heap->has_forwarded_objects(), "No forwarded objects on this path");
 729 
 730   if (heap->mode()->is_generational()) {
 731     if (_generation->is_global()) {
 732       heap->old_generation()->cancel_gc();
 733     }
 734 
 735     {
 736       // After we swap card table below, the write-table is all clean, and the read table holds
 737       // cards dirty prior to the start of GC. Young and bootstrap collection will update
 738       // the write card table as a side effect of remembered set scanning. Global collection will
 739       // update the card table as a side effect of global marking of old objects.
 740       ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_swap_rset);
 741       _generation->swap_card_tables();
 742     }
 743   }
 744 
 745   if (ShenandoahVerify) {
 746     ShenandoahTimingsTracker v(ShenandoahPhaseTimings::init_mark_verify);
 747     heap->verifier()->verify_before_concmark(_generation);
 748   }
 749 
 750   if (VerifyBeforeGC) {
 751     Universe::verify();
 752   }
 753 
 754   _generation->set_concurrent_mark_in_progress(true);
 755 
 756   start_mark();
 757 
 758   if (_do_old_gc_bootstrap) {
 759     shenandoah_assert_generational();
 760     // Update region state for both young and old regions
 761     ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_region_states);
 762     ShenandoahInitMarkUpdateRegionStateClosure cl;
 763     heap->parallel_heap_region_iterate(&cl);
 764     heap->old_generation()->ref_processor()->reset_thread_locals();
 765   } else {
 766     // Update region state for only young regions
 767     ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_region_states);
 768     ShenandoahInitMarkUpdateRegionStateClosure cl;
 769     _generation->parallel_heap_region_iterate(&cl);
 770   }
 771 
 772   // Weak reference processing
 773   ShenandoahReferenceProcessor* rp = _generation->ref_processor();
 774   rp->reset_thread_locals();
 775 
 776   // Make above changes visible to worker threads
 777   OrderAccess::fence();
 778 
 779   // Arm nmethods/stack for concurrent processing
 780   ShenandoahCodeRoots::arm_nmethods();
 781   ShenandoahStackWatermark::change_epoch_id();
 782 
 783   {
 784     ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::init_propagate_gc_state);
 785     heap->propagate_gc_state_to_all_threads();
 786   }
 787 }
 788 
 789 void ShenandoahConcurrentGC::op_mark_roots() {
 790   _mark.mark_concurrent_roots();
 791 }
 792 
 793 void ShenandoahConcurrentGC::op_mark() {
 794   _mark.concurrent_mark();
 795 }
 796 
 797 void ShenandoahConcurrentGC::op_final_mark() {
 798   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 799   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
 800   assert(!heap->has_forwarded_objects(), "No forwarded objects on this path");
 801 
 802   if (ShenandoahVerify) {
 803     heap->verifier()->verify_roots_no_forwarded(_generation);
 804   }
 805 
 806   if (!heap->cancelled_gc()) {
 807     _mark.finish_mark();
 808     assert(!heap->cancelled_gc(), "STW mark cannot OOM");
 809 
 810     // Notify JVMTI that the tagmap table will need cleaning.
 811     JvmtiTagMap::set_needs_cleaning();
 812 
 813     // The collection set is chosen by prepare_regions_and_collection_set(). Additionally, certain parameters have been
 814     // established to govern the evacuation efforts that are about to begin.  Refer to comments on reserve members in
 815     // ShenandoahGeneration and ShenandoahOldGeneration for more detail.
 816     _generation->prepare_regions_and_collection_set(true /*concurrent*/);
 817 
 818     // Has to be done after cset selection
 819     heap->prepare_concurrent_roots();
 820 
 821     if (!heap->collection_set()->is_empty()) {
 822       LogTarget(Debug, gc, cset) lt;
 823       if (lt.is_enabled()) {
 824         ResourceMark rm;
 825         LogStream ls(lt);
 826         heap->collection_set()->print_on(&ls);
 827       }
 828 
 829       if (ShenandoahVerify) {
 830         ShenandoahTimingsTracker v(ShenandoahPhaseTimings::final_mark_verify);
 831         heap->verifier()->verify_before_evacuation(_generation);
 832       }
 833 
 834       heap->set_evacuation_in_progress(true);
 835       // From here on, we need to update references.
 836       heap->set_has_forwarded_objects(true);
 837 
 838       // Arm nmethods/stack for concurrent processing
 839       ShenandoahCodeRoots::arm_nmethods();
 840       ShenandoahStackWatermark::change_epoch_id();
 841 
 842     } else {
 843       if (ShenandoahVerify) {
 844         ShenandoahTimingsTracker v(ShenandoahPhaseTimings::final_mark_verify);
 845         if (has_in_place_promotions(heap)) {
 846           heap->verifier()->verify_after_concmark_with_promotions(_generation);
 847         } else {
 848           heap->verifier()->verify_after_concmark(_generation);
 849         }
 850       }
 851     }
 852   }
 853 
 854   {
 855     ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::final_mark_propagate_gc_state);
 856     heap->propagate_gc_state_to_all_threads();
 857   }
 858 }
 859 
 860 bool ShenandoahConcurrentGC::has_in_place_promotions(ShenandoahHeap* heap) {
 861   return heap->mode()->is_generational() && heap->old_generation()->has_in_place_promotions();
 862 }
 863 
 864 class ShenandoahConcurrentEvacThreadClosure : public ThreadClosure {
 865 private:
 866   OopClosure* const _oops;
 867 public:
 868   explicit ShenandoahConcurrentEvacThreadClosure(OopClosure* oops) : _oops(oops) {}
 869 
 870   void do_thread(Thread* thread) override {
 871     JavaThread* const jt = JavaThread::cast(thread);
 872     StackWatermarkSet::finish_processing(jt, _oops, StackWatermarkKind::gc);
 873   }
 874 };
 875 
 876 class ShenandoahConcurrentEvacUpdateThreadTask : public WorkerTask {
 877 private:
 878   ShenandoahJavaThreadsIterator _java_threads;
 879 
 880 public:
 881   explicit ShenandoahConcurrentEvacUpdateThreadTask(uint n_workers) :
 882     WorkerTask("Shenandoah Evacuate/Update Concurrent Thread Roots"),
 883     _java_threads(ShenandoahPhaseTimings::conc_thread_roots, n_workers) {
 884   }
 885 
 886   void work(uint worker_id) override {
 887     ShenandoahContextEvacuateUpdateRootsClosure oops_cl;
 888     ShenandoahConcurrentEvacThreadClosure thr_cl(&oops_cl);
 889     _java_threads.threads_do(&thr_cl, worker_id);
 890   }
 891 };
 892 
 893 void ShenandoahConcurrentGC::op_thread_roots() {
 894   const ShenandoahHeap* const heap = ShenandoahHeap::heap();
 895   assert(heap->is_evacuation_in_progress(), "Checked by caller");
 896   ShenandoahGCWorkerPhase worker_phase(ShenandoahPhaseTimings::conc_thread_roots);
 897   ShenandoahConcurrentEvacUpdateThreadTask task(heap->workers()->active_workers());
 898   heap->workers()->run_task(&task);
 899 }
 900 
 901 void ShenandoahConcurrentGC::op_weak_refs() {
 902   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 903   assert(heap->is_concurrent_weak_root_in_progress(), "Only during this phase");
 904   // Concurrent weak refs processing
 905   ShenandoahGCWorkerPhase worker_phase(ShenandoahPhaseTimings::conc_weak_refs);
 906   if (heap->gc_cause() == GCCause::_wb_breakpoint) {
 907     ShenandoahBreakpoint::at_after_reference_processing_started();
 908   }
 909   _generation->ref_processor()->process_references(ShenandoahPhaseTimings::conc_weak_refs, heap->workers(), true /* concurrent */);
 910 }
 911 
 912 class ShenandoahEvacUpdateCleanupOopStorageRootsClosure : public BasicOopIterateClosure {
 913 private:
 914   ShenandoahHeap* const _heap;
 915   ShenandoahGeneration* const _generation;
 916   ShenandoahMarkingContext* const _mark_context;
 917   bool  _evac_in_progress;
 918   Thread* const _thread;
 919 
 920 public:
 921   explicit ShenandoahEvacUpdateCleanupOopStorageRootsClosure(ShenandoahGeneration* generation);
 922   void do_oop(oop* p);
 923   void do_oop(narrowOop* p);
 924 };
 925 
 926 ShenandoahEvacUpdateCleanupOopStorageRootsClosure::ShenandoahEvacUpdateCleanupOopStorageRootsClosure(ShenandoahGeneration* generation) :
 927   _heap(ShenandoahHeap::heap()),
 928   _generation(generation),
 929   _mark_context(ShenandoahHeap::heap()->marking_context()),
 930   _evac_in_progress(ShenandoahHeap::heap()->is_evacuation_in_progress()),
 931   _thread(Thread::current()) {
 932 }
 933 
 934 void ShenandoahEvacUpdateCleanupOopStorageRootsClosure::do_oop(oop* p) {
 935   const oop obj = RawAccess<>::oop_load(p);
 936   if (!CompressedOops::is_null(obj)) {
 937     if (!_mark_context->is_marked(obj)) {
 938       if (_generation->contains(obj)) {
 939         // Note: The obj is dead here. Do not touch it, just clear.
 940         ShenandoahHeap::atomic_clear_oop(p, obj);
 941       }
 942     } else if (_evac_in_progress && _heap->in_collection_set(obj)) {
 943       oop resolved = ShenandoahForwarding::get_forwardee(obj);
 944       if (resolved == obj) {
 945         resolved = _heap->evacuate_object(obj, _thread);
 946       }
 947       shenandoah_assert_not_in_cset_except(p, resolved, _heap->cancelled_gc());
 948       ShenandoahHeap::atomic_update_oop(resolved, p, obj);
 949     }
 950   }
 951 }
 952 
 953 void ShenandoahEvacUpdateCleanupOopStorageRootsClosure::do_oop(narrowOop* p) {
 954   ShouldNotReachHere();
 955 }
 956 
 957 class ShenandoahIsCLDAliveClosure : public CLDClosure {
 958 public:
 959   void do_cld(ClassLoaderData* cld) {
 960     cld->is_alive();
 961   }
 962 };
 963 
 964 class ShenandoahIsNMethodAliveClosure: public NMethodClosure {
 965 public:
 966   void do_nmethod(nmethod* n) {
 967     n->is_unloading();
 968   }
 969 };
 970 
 971 // This task not only evacuates/updates marked weak roots, but also "null"
 972 // dead weak roots.
 973 class ShenandoahConcurrentWeakRootsEvacUpdateTask : public WorkerTask {
 974 private:
 975   ShenandoahVMWeakRoots<true /*concurrent*/> _vm_roots;
 976 
 977   // Roots related to concurrent class unloading
 978   ShenandoahClassLoaderDataRoots<true /* concurrent */>
 979                                              _cld_roots;
 980   ShenandoahConcurrentNMethodIterator        _nmethod_itr;
 981   ShenandoahGeneration*                      _generation;
 982   ShenandoahPhaseTimings::Phase              _phase;
 983 
 984 public:
 985   ShenandoahConcurrentWeakRootsEvacUpdateTask(ShenandoahGeneration* generation, ShenandoahPhaseTimings::Phase phase) :
 986     WorkerTask("Shenandoah Evacuate/Update Concurrent Weak Roots"),
 987     _vm_roots(phase),
 988     _cld_roots(phase, ShenandoahHeap::heap()->workers()->active_workers(), false /*heap iteration*/),
 989     _nmethod_itr(ShenandoahCodeRoots::table()),
 990     _generation(generation),
 991     _phase(phase) {}
 992 
 993   ~ShenandoahConcurrentWeakRootsEvacUpdateTask() {
 994     // Notify runtime data structures of potentially dead oops
 995     _vm_roots.report_num_dead();
 996   }
 997 
 998   void work(uint worker_id) override {
 999     ShenandoahConcurrentWorkerSession worker_session(worker_id);
1000     SuspendibleThreadSetJoiner sts_join;
1001     {
1002       // jni_roots and weak_roots are OopStorage backed roots, concurrent iteration
1003       // may race against OopStorage::release() calls.
1004       ShenandoahEvacUpdateCleanupOopStorageRootsClosure cl(_generation);
1005       _vm_roots.oops_do(&cl, worker_id);
1006     }
1007 
1008     // If we are going to perform concurrent class unloading later on, we need to
1009     // clean up the weak oops in CLD and determine nmethod's unloading state, so that we
1010     // can clean up immediate garbage sooner.
1011     if (ShenandoahHeap::heap()->unload_classes()) {
1012       // Applies ShenandoahIsCLDAlive closure to CLDs, native barrier will either null the
1013       // CLD's holder or evacuate it.
1014       {
1015         ShenandoahIsCLDAliveClosure is_cld_alive;
1016         _cld_roots.cld_do(&is_cld_alive, worker_id);
1017       }
1018 
1019       // Applies ShenandoahIsNMethodAliveClosure to registered nmethods.
1020       // The closure calls nmethod->is_unloading(). The is_unloading
1021       // state is cached, therefore, during concurrent class unloading phase,
1022       // we will not touch the metadata of unloading nmethods
1023       {
1024         ShenandoahWorkerTimingsTracker timer(_phase, ShenandoahPhaseTimings::CodeCache, worker_id);
1025         ShenandoahIsNMethodAliveClosure is_nmethod_alive;
1026         _nmethod_itr.nmethods_do(&is_nmethod_alive);
1027       }
1028     }
1029   }
1030 };
1031 
1032 void ShenandoahConcurrentGC::op_weak_roots() {
1033   ShenandoahHeap* const heap = ShenandoahHeap::heap();
1034   assert(heap->is_concurrent_weak_root_in_progress(), "Only during this phase");
1035   {
1036     // Concurrent weak root processing
1037     ShenandoahGCWorkerPhase worker_phase(ShenandoahPhaseTimings::conc_weak_roots);
1038     ShenandoahConcurrentWeakRootsEvacUpdateTask task(_generation, ShenandoahPhaseTimings::conc_weak_roots);
1039     heap->workers()->run_task(&task);
1040   }
1041 
1042   {
1043     // It is possible for mutators executing the load reference barrier to have
1044     // loaded an oop through a weak handle that has since been nulled out by
1045     // weak root processing. Handshaking here forces them to complete the
1046     // barrier before the GC cycle continues and does something that would
1047     // change the evaluation of the barrier (for example, resetting the TAMS
1048     // on trashed regions could make an oop appear to be marked _after_ the
1049     // region has been recycled).
1050     ShenandoahTimingsTracker t(ShenandoahPhaseTimings::conc_weak_roots_rendezvous);
1051     heap->rendezvous_threads("Shenandoah Concurrent Weak Roots");
1052   }
1053 }
1054 
1055 void ShenandoahConcurrentGC::op_class_unloading() {
1056   ShenandoahHeap* const heap = ShenandoahHeap::heap();
1057   assert (heap->is_concurrent_weak_root_in_progress() &&
1058           heap->unload_classes(),
1059           "Checked by caller");
1060   heap->do_class_unloading();
1061 }
1062 
1063 class ShenandoahEvacUpdateCodeCacheClosure : public NMethodClosure {
1064 private:
1065   ShenandoahEvacuateUpdateMetadataClosure   _cl;
1066 
1067 public:
1068   ShenandoahEvacUpdateCodeCacheClosure() : _cl() {}
1069 
1070   void do_nmethod(nmethod* n) {
1071     ShenandoahNMethod* data = ShenandoahNMethod::gc_data(n);
1072     ShenandoahNMethodLocker locker(data->lock());
1073     data->oops_do(&_cl, /* fix_relocations = */ true);
1074     ShenandoahNMethod::disarm_nmethod(n);
1075   }
1076 };
1077 
1078 class ShenandoahConcurrentRootsEvacUpdateTask : public WorkerTask {
1079 private:
1080   ShenandoahPhaseTimings::Phase                 _phase;
1081   ShenandoahVMRoots<true /*concurrent*/>        _vm_roots;
1082   ShenandoahClassLoaderDataRoots<true /*concurrent*/>
1083                                                 _cld_roots;
1084   ShenandoahConcurrentNMethodIterator           _nmethod_itr;
1085 
1086 public:
1087   ShenandoahConcurrentRootsEvacUpdateTask(ShenandoahPhaseTimings::Phase phase) :
1088     WorkerTask("Shenandoah Evacuate/Update Concurrent Strong Roots"),
1089     _phase(phase),
1090     _vm_roots(phase),
1091     _cld_roots(phase, ShenandoahHeap::heap()->workers()->active_workers(), false /*heap iteration*/),
1092     _nmethod_itr(ShenandoahCodeRoots::table()) {}
1093 
1094   void work(uint worker_id) {
1095     ShenandoahConcurrentWorkerSession worker_session(worker_id);
1096     {
1097       {
1098         // vm_roots and weak_roots are OopStorage backed roots, concurrent iteration
1099         // may race against OopStorage::release() calls.
1100         ShenandoahContextEvacuateUpdateRootsClosure cl;
1101         _vm_roots.oops_do<ShenandoahContextEvacuateUpdateRootsClosure>(&cl, worker_id);
1102       }
1103 
1104       {
1105         ShenandoahEvacuateUpdateMetadataClosure cl;
1106         CLDToOopClosure clds(&cl, ClassLoaderData::_claim_strong);
1107         _cld_roots.cld_do(&clds, worker_id);
1108       }
1109     }
1110 
1111     if (!ShenandoahHeap::heap()->unload_classes()) {
1112       ShenandoahWorkerTimingsTracker timer(_phase, ShenandoahPhaseTimings::CodeCache, worker_id);
1113       ShenandoahEvacUpdateCodeCacheClosure cl;
1114       _nmethod_itr.nmethods_do(&cl);
1115     }
1116   }
1117 };
1118 
1119 void ShenandoahConcurrentGC::op_strong_roots() {
1120   ShenandoahHeap* const heap = ShenandoahHeap::heap();
1121   assert(heap->is_concurrent_strong_root_in_progress(), "Checked by caller");
1122   ShenandoahConcurrentRootsEvacUpdateTask task(ShenandoahPhaseTimings::conc_strong_roots);
1123   heap->workers()->run_task(&task);
1124   heap->set_concurrent_strong_root_in_progress(false);
1125 }
1126 
1127 void ShenandoahConcurrentGC::op_cleanup_early() {
1128   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
1129                               ShenandoahWorkerPolicy::calc_workers_for_conc_cleanup(),
1130                               "cleanup early.");
1131   ShenandoahHeap::heap()->recycle_trash();
1132 }
1133 
1134 void ShenandoahConcurrentGC::op_evacuate() {
1135   ShenandoahHeap::heap()->evacuate_collection_set(_generation, true /*concurrent*/);
1136 }
1137 
1138 void ShenandoahConcurrentGC::op_init_update_refs() {
1139   if (ShenandoahVerify) {
1140     ShenandoahHeap* const heap = ShenandoahHeap::heap();
1141     ShenandoahTimingsTracker v(ShenandoahPhaseTimings::init_update_refs_verify);
1142     heap->verifier()->verify_before_update_refs(_generation);
1143   }
1144 }
1145 
1146 void ShenandoahConcurrentGC::op_update_refs() {
1147   ShenandoahHeap::heap()->update_heap_references(_generation, true /*concurrent*/);
1148 }
1149 
1150 class ShenandoahUpdateThreadHandshakeClosure : public HandshakeClosure {
1151 private:
1152   // This closure runs when thread is stopped for handshake, which means
1153   // we can use non-concurrent closure here, as long as it only updates
1154   // locations modified by the thread itself, i.e. stack locations.
1155   ShenandoahNonConcUpdateRefsClosure _cl;
1156 public:
1157   ShenandoahUpdateThreadHandshakeClosure();
1158   void do_thread(Thread* thread) override;
1159 };
1160 
1161 ShenandoahUpdateThreadHandshakeClosure::ShenandoahUpdateThreadHandshakeClosure() :
1162   HandshakeClosure("Shenandoah Update Thread Roots") {
1163 }
1164 
1165 void ShenandoahUpdateThreadHandshakeClosure::do_thread(Thread* thread) {
1166   if (thread->is_Java_thread()) {
1167     JavaThread* jt = JavaThread::cast(thread);
1168     ResourceMark rm;
1169     jt->oops_do(&_cl, nullptr);
1170   }
1171 }
1172 
1173 class ShenandoahUpdateThreadRootsAndFlushOldSatbBuffers final : public HandshakeClosure {
1174   // When Shenandoah is marking the old generation, it is possible for the SATB barrier
1175   // to pick up overwritten pointers that point into a cset region. If these pointers
1176   // are accessed by mark threads, they will crash. Once update refs has completed, it is
1177   // no longer possible for a mutator thread to overwrite a pointer into a cset region.
1178   //
1179   // Therefore, at the end of update refs, we use this closure to update the thread roots
1180   // and 'complete' all the thread local SATB buffers. Completing these will filter out
1181   // anything that has already been marked or anything that points to a region which is
1182   // not old. We do not need to worry about ABA situations where a region may become old
1183   // after the pointer is enqueued but before it is filtered. There are only two ways a
1184   // region may become old:
1185   //  1. The region is promoted in place. This is safe because such regions will never
1186   //     be in the collection set. If this happens, the pointer will be preserved, essentially
1187   //     becoming part of the old snapshot.
1188   //  2. The region is allocated during evacuation of old. This is also not a concern because
1189   //     we haven't yet finished marking old so no mixed evacuations will happen.
1190   ShenandoahUpdateThreadHandshakeClosure _update_roots;
1191   ShenandoahFlushSATB _flush_all_satb;
1192 
1193 public:
1194   ShenandoahUpdateThreadRootsAndFlushOldSatbBuffers() :
1195     HandshakeClosure("Shenandoah Update Thread Roots and Flush SATB"),
1196     _flush_all_satb(ShenandoahBarrierSet::satb_mark_queue_set()) {
1197     assert(ShenandoahBarrierSet::satb_mark_queue_set().get_filter_out_young(),
1198            "Should be filtering pointers outside of old during old marking");
1199   }
1200 
1201   void do_thread(Thread* thread) override {
1202     _update_roots.do_thread(thread);
1203     _flush_all_satb.do_thread(thread);
1204   }
1205 };
1206 
1207 void ShenandoahConcurrentGC::op_update_thread_roots() {
1208   ShenandoahHeap* const heap = ShenandoahHeap::heap();
1209   if (heap->is_concurrent_old_mark_in_progress()) {
1210     ShenandoahUpdateThreadRootsAndFlushOldSatbBuffers cl;
1211     Handshake::execute(&cl);
1212   } else {
1213     ShenandoahUpdateThreadHandshakeClosure cl;
1214     Handshake::execute(&cl);
1215   }
1216 }
1217 
1218 void ShenandoahConcurrentGC::op_final_update_refs() {
1219   ShenandoahHeap* const heap = ShenandoahHeap::heap();
1220   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
1221   assert(!heap->_update_refs_iterator.has_next(), "Should have finished update references");
1222 
1223   heap->finish_concurrent_roots();
1224 
1225   // Clear cancelled GC, if set. On cancellation path, the block before would handle
1226   // everything.
1227   if (heap->cancelled_gc()) {
1228     heap->clear_cancelled_gc();
1229   }
1230 
1231   // Has to be done before cset is clear
1232   if (ShenandoahVerify) {
1233     heap->verifier()->verify_roots_in_to_space(_generation);
1234   }
1235 
1236   // If we are running in generational mode, this will also age active regions that
1237   // haven't been used for allocation.
1238   heap->update_heap_region_states(true /*concurrent*/);
1239 
1240   heap->set_update_refs_in_progress(false);
1241   heap->set_has_forwarded_objects(false);
1242 
1243   if (ShenandoahVerify) {
1244     ShenandoahTimingsTracker v(ShenandoahPhaseTimings::final_update_refs_verify);
1245     heap->verifier()->verify_after_update_refs(_generation);
1246   }
1247 
1248   if (VerifyAfterGC) {
1249     Universe::verify();
1250   }
1251 
1252   heap->rebuild_free_set(true /*concurrent*/);
1253   _generation->heuristics()->start_idle_span();
1254 
1255   {
1256     ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::final_update_refs_propagate_gc_state);
1257     heap->propagate_gc_state_to_all_threads();
1258   }
1259 }
1260 
1261 void ShenandoahConcurrentGC::entry_final_roots() {
1262   ShenandoahHeap* const heap = ShenandoahHeap::heap();
1263   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
1264   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent final roots", "");
1265   ShenandoahConcurrentSubphase gc_phase(msg, ShenandoahPhaseTimings::conc_final_roots);
1266   EventMark em("%s", msg);
1267 
1268   heap->concurrent_final_roots();
1269 }
1270 
1271 void ShenandoahConcurrentGC::op_verify_final() {
1272   assert(ShenandoahVerify, "Should have been checked before");
1273   ShenandoahHeap* const heap = ShenandoahHeap::heap();
1274   heap->verifier()->verify_after_gc(_generation);
1275 }
1276 
1277 void ShenandoahConcurrentGC::op_cleanup_complete() {
1278   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
1279                               ShenandoahWorkerPolicy::calc_workers_for_conc_cleanup(),
1280                               "cleanup complete.");
1281   ShenandoahHeap::heap()->recycle_trash();
1282 }
1283 
1284 void ShenandoahConcurrentGC::op_reset_after_collect() {
1285   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
1286                           ShenandoahWorkerPolicy::calc_workers_for_conc_reset(),
1287                           "reset after collection.");
1288 
1289   ShenandoahHeap* const heap = ShenandoahHeap::heap();
1290   if (heap->mode()->is_generational()) {
1291     // If we are in the midst of an old gc bootstrap or an old marking, we want to leave the mark bit map of
1292     // the young generation intact. In particular, reference processing in the old generation may potentially
1293     // need the reachability of a young generation referent of a Reference object in the old generation.
1294     if (!_do_old_gc_bootstrap && !heap->is_concurrent_old_mark_in_progress()) {
1295       heap->young_generation()->reset_mark_bitmap<false>();
1296     }
1297   } else {
1298     _generation->reset_mark_bitmap<false>();
1299   }
1300 }
1301 
1302 bool ShenandoahConcurrentGC::check_cancellation_and_abort(ShenandoahDegenPoint point) {
1303   if (ShenandoahHeap::heap()->cancelled_gc()) {
1304     _degen_point = point;
1305     return true;
1306   }
1307   return false;
1308 }