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   ShenandoahConcurrentPhase 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   ShenandoahConcurrentPhase 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   ShenandoahBreakpointGCScope breakpoint_gc_scope(cause);
 141 
 142   // Reset for upcoming marking
 143   entry_reset();
 144 
 145   // Start initial mark under STW
 146   vmop_entry_init_mark();
 147 
 148   {
 149     ShenandoahBreakpointMarkScope breakpoint_mark_scope(cause);
 150 
 151     // Reset task queue stats here, rather than in mark_concurrent_roots,
 152     // because remembered set scan will `push` oops into the queues and
 153     // resetting after this happens will lose those counts.
 154     TASKQUEUE_STATS_ONLY(_mark.task_queues()->reset_taskqueue_stats());
 155 
 156     // Concurrent remembered set scanning
 157     entry_scan_remembered_set();
 158 
 159     // Concurrent mark roots
 160     entry_mark_roots();
 161     if (check_cancellation_and_abort(ShenandoahDegenPoint::_degenerated_roots)) {
 162       return false;
 163     }
 164 
 165     // Continue concurrent mark
 166     entry_mark();
 167     if (check_cancellation_and_abort(ShenandoahDegenPoint::_degenerated_mark)) {
 168       return false;
 169     }
 170   }
 171 
 172   // Complete marking under STW, and start evacuation
 173   vmop_entry_final_mark();
 174 
 175   // If the GC was cancelled before final mark, nothing happens on the safepoint. We are still
 176   // in the marking phase and must resume the degenerated cycle from there. If the GC was cancelled
 177   // after final mark, then we've entered the evacuation phase and must resume the degenerated cycle
 178   // from that phase.
 179   if (_generation->is_concurrent_mark_in_progress()) {
 180     bool cancelled = check_cancellation_and_abort(ShenandoahDegenPoint::_degenerated_mark);
 181     assert(cancelled, "GC must have been cancelled between concurrent and final mark");
 182     return false;
 183   }
 184 
 185   assert(heap->is_concurrent_weak_root_in_progress(), "Must be doing weak roots now");
 186 
 187   // Finish all thread/stack roots if needed. This completes stack watermark processing.
 188   if (heap->is_evacuation_in_progress()) {
 189     entry_thread_roots();
 190   }
 191 
 192   // Process weak roots that might still point to regions that would be broken by cleanup.
 193   // We cannot recycle regions because weak roots need to know what is marked in trashed regions.
 194   entry_weak_refs();
 195   entry_weak_roots();
 196 
 197   // Perform concurrent class unloading before any regions get recycled. Class unloading may
 198   // need to inspect unmarked objects in trashed regions.
 199   if (heap->unload_classes()) {
 200     entry_class_unloading();
 201   }
 202 
 203   // Final mark might have reclaimed some immediate garbage, kick cleanup to reclaim
 204   // the space. This would be the last action if there is nothing to evacuate.  Note that
 205   // we will not age young-gen objects in the case that we skip evacuation.
 206   entry_cleanup_early();
 207 
 208   // Processing strong roots
 209   // This may be skipped if there is nothing to update/evacuate.
 210   // If so, strong_root_in_progress would be unset.
 211   if (heap->is_concurrent_strong_root_in_progress()) {
 212     entry_strong_roots();
 213   }
 214 
 215   // Roots processing is complete, put the weak roots flag down.
 216   entry_final_roots();
 217 
 218   // Continue the cycle with evacuation and optional update-refs.
 219   // This may be skipped if there is nothing to evacuate.
 220   // If so, evac_in_progress would be unset by collection set preparation code.
 221   if (heap->is_evacuation_in_progress()) {
 222     // Concurrently evacuate
 223     entry_evacuate();
 224     if (check_cancellation_and_abort(ShenandoahDegenPoint::_degenerated_evac)) {
 225       return false;
 226     }
 227 
 228     // Perform update-refs phase.
 229     entry_concurrent_update_refs_prepare(heap);
 230 
 231     if (ShenandoahHeap::heap()->mode()->is_generational()) {
 232       entry_update_card_table();
 233     }
 234 
 235     if (ShenandoahVerify) {
 236       vmop_entry_init_update_refs();
 237     }
 238 
 239     entry_update_refs();
 240     if (check_cancellation_and_abort(ShenandoahDegenPoint::_degenerated_update_refs)) {
 241       return false;
 242     }
 243 
 244     // Concurrent update thread roots
 245     entry_update_thread_roots();
 246     if (check_cancellation_and_abort(ShenandoahDegenPoint::_degenerated_update_refs)) {
 247       return false;
 248     }
 249 
 250     vmop_entry_final_update_refs();
 251 
 252     // Update references freed up collection set, kick the cleanup to reclaim the space.
 253     entry_cleanup_complete();
 254   } else {
 255     _abbreviated = true;
 256 
 257     if (heap->mode()->is_generational()) {
 258       entry_complete_abbreviated_cycle();
 259 
 260       // If the promote-in-place operation was cancelled, we can have the degenerated
 261       // cycle complete the operation. It will see that no evacuations are in progress,
 262       // and that there are regions wanting promotion. The risk with not handling the
 263       // cancellation would be failing to restore top for these regions and leaving
 264       // them unable to serve allocations for the old generation.
 265       if (check_cancellation_and_abort(ShenandoahDegenPoint::_degenerated_evac)) {
 266         return false;
 267       }
 268     }
 269 
 270     // In normal cycle, final-update-refs would verify at the end of the cycle.
 271     // In abbreviated cycle, we need to verify separately.
 272     if (ShenandoahVerify) {
 273       vmop_entry_final_verify();
 274     }
 275   }
 276 
 277   // We defer generation resizing actions until after cset regions have been recycled.  We do this even following an
 278   // abbreviated cycle.
 279   if (heap->mode()->is_generational()) {
 280     ShenandoahGenerationalHeap::heap()->complete_concurrent_cycle();
 281   }
 282 
 283   // Instead of always resetting immediately before the start of a new GC, we can often reset at the end of the
 284   // previous GC. This allows us to start the next GC cycle more quickly after a trigger condition is detected,
 285   // reducing the likelihood that GC will degenerate.
 286   entry_reset_after_collect();
 287 
 288   return true;
 289 }
 290 
 291 void ShenandoahConcurrentGC::entry_complete_abbreviated_cycle() {
 292   shenandoah_assert_generational();
 293 
 294   ShenandoahGenerationalHeap* const heap = ShenandoahGenerationalHeap::heap();
 295 
 296   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 297   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent complete abbreviated cycle", "");
 298   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::complete_abbreviated);
 299   EventMark em("%s", msg);
 300 
 301   ShenandoahWorkerScope scope(heap->workers(),
 302                               ShenandoahWorkerPolicy::calc_workers_for_conc_evac(),
 303                               msg);
 304 
 305   heap->try_inject_pin();
 306   // We chose not to evacuate because we found sufficient immediate garbage.
 307   // However, there may still be regions to promote in place, so do that now.
 308   if (heap->old_generation()->has_in_place_promotions()) {
 309     ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::complete_abbreviated_promote_in_place);
 310     ShenandoahGCWorkerPhase worker_phase(ShenandoahPhaseTimings::complete_abbreviated_promote_in_place);
 311     heap->promote_regions_in_place(_generation, true);
 312   }
 313 
 314   // At this point, the cycle is effectively complete. If the cycle has been cancelled here,
 315   // the control thread will detect it on its next iteration and run a degenerated young cycle.
 316   if (!heap->cancelled_gc() && !_generation->is_old()) {
 317     ShenandoahTimingsTracker tracker(ShenandoahPhaseTimings::complete_abbreviated_update_region_ages);
 318     heap->update_region_ages(_generation->complete_marking_context());
 319   }
 320 }
 321 
 322 void ShenandoahConcurrentGC::vmop_entry_init_mark() {
 323   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 324   TraceCollectorStats tcs(heap->monitoring_support()->stw_collection_counters());
 325   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::init_mark_gross);
 326 
 327   heap->try_inject_alloc_failure();
 328   VM_ShenandoahInitMark op(this);
 329   VMThread::execute(&op); // jump to entry_init_mark() under safepoint
 330 }
 331 
 332 void ShenandoahConcurrentGC::vmop_entry_final_mark() {
 333   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 334   TraceCollectorStats tcs(heap->monitoring_support()->stw_collection_counters());
 335   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::final_mark_gross);
 336 
 337   heap->try_inject_alloc_failure();
 338   VM_ShenandoahFinalMarkStartEvac op(this);
 339   VMThread::execute(&op); // jump to entry_final_mark under safepoint
 340   heap->try_inject_pin();
 341 }
 342 
 343 void ShenandoahConcurrentGC::vmop_entry_init_update_refs() {
 344   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 345   TraceCollectorStats tcs(heap->monitoring_support()->stw_collection_counters());
 346   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::init_update_refs_gross);
 347 
 348   heap->try_inject_alloc_failure();
 349   heap->try_inject_pin();
 350   VM_ShenandoahInitUpdateRefs op(this);
 351   VMThread::execute(&op);
 352 }
 353 
 354 void ShenandoahConcurrentGC::vmop_entry_final_update_refs() {
 355   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 356   TraceCollectorStats tcs(heap->monitoring_support()->stw_collection_counters());
 357   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::final_update_refs_gross);
 358 
 359   heap->try_inject_alloc_failure();
 360   heap->try_inject_pin();
 361   VM_ShenandoahFinalUpdateRefs op(this);
 362   VMThread::execute(&op);
 363 }
 364 











 365 void ShenandoahConcurrentGC::vmop_entry_final_verify() {
 366   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 367   TraceCollectorStats tcs(heap->monitoring_support()->stw_collection_counters());
 368   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::final_verify_gross);
 369 
 370   // This phase does not use workers, no need for setup
 371   heap->try_inject_alloc_failure();
 372   heap->try_inject_pin();
 373   VM_ShenandoahFinalVerify op(this);
 374   VMThread::execute(&op);
 375 }
 376 
 377 void ShenandoahConcurrentGC::entry_init_mark() {
 378   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 379   assert(!heap->has_forwarded_objects(), "Should not have forwarded objects here");
 380 
 381   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Pause Init Mark", "");
 382   ShenandoahPausePhase gc_phase(msg, ShenandoahPhaseTimings::init_mark);
 383   EventMark em("%s", msg);
 384 
 385   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
 386                               ShenandoahWorkerPolicy::calc_workers_for_init_marking(),
 387                               "init marking");
 388 
 389   op_init_mark();
 390 }
 391 
 392 void ShenandoahConcurrentGC::entry_final_mark() {
 393   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 394   assert(!heap->has_forwarded_objects() || heap->is_concurrent_old_mark_in_progress(),
 395          "Should not have forwarded objects during final mark, unless old gen concurrent mark is running");
 396 
 397   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Pause Final Mark", "");
 398   ShenandoahPausePhase gc_phase(msg, ShenandoahPhaseTimings::final_mark);
 399   EventMark em("%s", msg);
 400 
 401   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
 402                               ShenandoahWorkerPolicy::calc_workers_for_final_marking(),
 403                               "final marking");
 404 
 405   op_final_mark();
 406 }
 407 
 408 void ShenandoahConcurrentGC::entry_init_update_refs() {
 409   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Pause Init Update Refs", "");
 410   ShenandoahPausePhase gc_phase(msg, ShenandoahPhaseTimings::init_update_refs);
 411   EventMark em("%s", msg);
 412 
 413   // No workers used in this phase, no setup required
 414   op_init_update_refs();
 415 }
 416 
 417 void ShenandoahConcurrentGC::entry_final_update_refs() {
 418   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Pause Final Update Refs", "");
 419   ShenandoahPausePhase gc_phase(msg, ShenandoahPhaseTimings::final_update_refs);
 420   EventMark em("%s", msg);
 421 
 422   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
 423                               ShenandoahWorkerPolicy::calc_workers_for_final_update_ref(),
 424                               "final reference update");
 425 
 426   op_final_update_refs();
 427 }
 428 
 429 void ShenandoahConcurrentGC::entry_final_verify() {
 430   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Pause Verify Final", "");
 431   ShenandoahPausePhase gc_phase(msg, ShenandoahPhaseTimings::final_verify);
 432   EventMark em("%s", msg);
 433 
 434   op_verify_final();
 435 }
 436 
 437 void ShenandoahConcurrentGC::entry_reset() {
 438   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 439   heap->release_injected_pins();
 440   heap->try_inject_alloc_failure();
 441 
 442   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 443   {
 444     SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent reset", "");
 445     ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_reset);
 446     EventMark em("%s", msg);
 447 
 448     ShenandoahWorkerScope scope(heap->workers(),
 449                                 ShenandoahWorkerPolicy::calc_workers_for_conc_reset(),
 450                                 msg);
 451     op_reset();
 452   }
 453 }
 454 
 455 void ShenandoahConcurrentGC::entry_scan_remembered_set() {
 456   if (_generation->is_young()) {
 457     ShenandoahHeap* const heap = ShenandoahHeap::heap();
 458     TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 459 
 460     SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent remembered set scanning", "");
 461     ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::init_scan_rset);
 462     EventMark em("%s", msg);
 463 
 464     ShenandoahWorkerScope scope(heap->workers(),
 465                                 ShenandoahWorkerPolicy::calc_workers_for_rs_scanning(),
 466                                 msg);
 467 
 468     heap->try_inject_alloc_failure();
 469     _generation->scan_remembered_set(true /* is_concurrent */);
 470   }
 471 }
 472 
 473 void ShenandoahConcurrentGC::entry_mark_roots() {
 474   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 475   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 476   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent marking roots", "");
 477   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_mark_roots);
 478   EventMark em("%s", msg);
 479 
 480   ShenandoahWorkerScope scope(heap->workers(),
 481                               ShenandoahWorkerPolicy::calc_workers_for_conc_marking(),
 482                               "concurrent marking roots");
 483 
 484   heap->try_inject_alloc_failure();
 485   op_mark_roots();
 486 }
 487 
 488 void ShenandoahConcurrentGC::entry_mark() {
 489   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 490   assert(!heap->has_forwarded_objects() || heap->is_concurrent_old_mark_in_progress(),
 491          "Should not have forwarded objects concurrent mark, unless old gen concurrent mark is running");
 492 
 493   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 494   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent marking", "");
 495   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_mark);
 496   EventMark em("%s", msg);
 497 
 498   ShenandoahWorkerScope scope(heap->workers(),
 499                               ShenandoahWorkerPolicy::calc_workers_for_conc_marking(),
 500                               "concurrent marking");
 501 
 502   heap->try_inject_alloc_failure();
 503   op_mark();
 504   heap->try_inject_pin();
 505 }
 506 
 507 void ShenandoahConcurrentGC::entry_thread_roots() {
 508   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 509   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent thread roots", "");
 510   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_thread_roots);
 511   EventMark em("%s", msg);
 512 
 513   ShenandoahWorkerScope scope(heap->workers(),
 514                               ShenandoahWorkerPolicy::calc_workers_for_conc_root_processing(),
 515                               msg);
 516 
 517   heap->try_inject_alloc_failure();
 518   heap->try_inject_pin();
 519   op_thread_roots();
 520 }
 521 
 522 void ShenandoahConcurrentGC::entry_weak_refs() {
 523   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 524   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent weak references", "");
 525   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_weak_refs);
 526   EventMark em("%s", msg);
 527 
 528   ShenandoahWorkerScope scope(heap->workers(),
 529                               ShenandoahWorkerPolicy::calc_workers_for_conc_refs_processing(),
 530                               "concurrent weak references");
 531 
 532   heap->try_inject_alloc_failure();
 533   heap->try_inject_pin();
 534   op_weak_refs();
 535 }
 536 
 537 void ShenandoahConcurrentGC::entry_weak_roots() {
 538   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 539   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 540   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent weak roots", "");
 541   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_weak_roots);
 542   EventMark em("%s", msg);
 543 
 544   ShenandoahWorkerScope scope(heap->workers(),
 545                               ShenandoahWorkerPolicy::calc_workers_for_conc_root_processing(),
 546                               "concurrent weak root");
 547 
 548   heap->try_inject_alloc_failure();
 549   heap->try_inject_pin();
 550   op_weak_roots();
 551 }
 552 
 553 void ShenandoahConcurrentGC::entry_class_unloading() {
 554   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 555   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 556   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent class unloading", "");
 557   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_class_unload);
 558   EventMark em("%s", msg);
 559 
 560   ShenandoahWorkerScope scope(heap->workers(),
 561                               ShenandoahWorkerPolicy::calc_workers_for_conc_root_processing(),
 562                               "concurrent class unloading");
 563 
 564   heap->try_inject_alloc_failure();
 565   heap->try_inject_pin();
 566   op_class_unloading();
 567 }
 568 
 569 void ShenandoahConcurrentGC::entry_strong_roots() {
 570   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 571   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 572   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent strong roots", "");
 573   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_strong_roots);
 574   EventMark em("%s", msg);
 575 
 576   ShenandoahGCWorkerPhase worker_phase(ShenandoahPhaseTimings::conc_strong_roots);
 577 
 578   ShenandoahWorkerScope scope(heap->workers(),
 579                               ShenandoahWorkerPolicy::calc_workers_for_conc_root_processing(),
 580                               "concurrent strong root");
 581 
 582   heap->try_inject_alloc_failure();
 583   heap->try_inject_pin();
 584   op_strong_roots();
 585 }
 586 
 587 void ShenandoahConcurrentGC::entry_cleanup_early() {
 588   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 589   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 590   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent cleanup", "");
 591   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_cleanup_early, true /* log_heap_usage */);
 592   EventMark em("%s", msg);
 593 
 594   // This phase does not use workers, no need for setup
 595   heap->try_inject_alloc_failure();
 596   heap->try_inject_pin();
 597   op_cleanup_early();
 598   if (!heap->is_evacuation_in_progress()) {
 599     // This is an abbreviated cycle.  Rebuild the freeset in order to establish reserves for the next GC cycle.  Doing
 600     // the rebuild ASAP also expedites availability of immediate trash, reducing the likelihood that we will degenerate
 601     // during promote-in-place processing.
 602     heap->rebuild_free_set(true /*concurrent*/);
 603   }
 604 }
 605 
 606 void ShenandoahConcurrentGC::entry_evacuate() {
 607   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 608   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 609   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent evacuation", "");
 610   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_evac);
 611   EventMark em("%s", msg);
 612 
 613   ShenandoahWorkerScope scope(heap->workers(),
 614                               ShenandoahWorkerPolicy::calc_workers_for_conc_evac(),
 615                               "concurrent evacuation");
 616 
 617   heap->try_inject_alloc_failure();
 618   heap->try_inject_pin();
 619   op_evacuate();
 620 }
 621 
 622 void ShenandoahConcurrentGC::entry_update_thread_roots() {
 623   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 624   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 625   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent update thread roots", "");
 626   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_update_thread_roots);
 627   EventMark em("%s", msg);
 628 
 629   // No workers used in this phase, no setup required
 630   heap->try_inject_alloc_failure();
 631   heap->try_inject_pin();
 632   op_update_thread_roots();
 633 }
 634 
 635 void ShenandoahConcurrentGC::entry_update_refs() {
 636   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 637   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 638   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent update references", "");
 639   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_update_refs);
 640   EventMark em("%s", msg);
 641 
 642   ShenandoahWorkerScope scope(heap->workers(),
 643                               ShenandoahWorkerPolicy::calc_workers_for_conc_update_ref(),
 644                               "concurrent reference update");
 645 
 646   heap->try_inject_alloc_failure();
 647   heap->try_inject_pin();
 648   op_update_refs();
 649 }
 650 
 651 void ShenandoahConcurrentGC::entry_cleanup_complete() {
 652   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 653   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 654   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent cleanup", "");
 655   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_cleanup_complete, true /* log_heap_usage */);
 656   EventMark em("%s", msg);
 657 
 658   // This phase does not use workers, no need for setup
 659   heap->try_inject_alloc_failure();
 660   op_cleanup_complete();
 661 }
 662 
 663 void ShenandoahConcurrentGC::entry_reset_after_collect() {
 664   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 665   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
 666   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent reset after collect", "");
 667   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_reset_after_collect);
 668   EventMark em("%s", msg);
 669 
 670   op_reset_after_collect();
 671 }
 672 
 673 void ShenandoahConcurrentGC::op_reset() {
 674   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 675 
 676   // If it is old GC bootstrap cycle, always clear bitmap for global gen
 677   // to ensure bitmap for old gen is clear for old GC cycle after this.
 678   if (_do_old_gc_bootstrap) {
 679     assert(!heap->is_prepare_for_old_mark_in_progress(), "Cannot reset old without making it parsable");
 680     heap->global_generation()->prepare_gc();
 681   } else {
 682     _generation->prepare_gc();
 683   }
 684 
 685   if (heap->mode()->is_generational()) {
 686     heap->old_generation()->card_scan()->mark_read_table_as_clean();
 687   }
 688 }
 689 
 690 class ShenandoahInitMarkUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
 691 private:
 692   ShenandoahMarkingContext* const _ctx;
 693 public:
 694   ShenandoahInitMarkUpdateRegionStateClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
 695 
 696   void heap_region_do(ShenandoahHeapRegion* r) {
 697     assert(!r->has_live(), "Region %zu should have no live data", r->index());
 698     if (r->is_active()) {
 699       // Check if region needs updating its TAMS. We have updated it already during concurrent
 700       // reset, so it is very likely we don't need to do another write here.  Since most regions
 701       // are not "active", this path is relatively rare.
 702       if (_ctx->top_at_mark_start(r) != r->top()) {
 703         _ctx->capture_top_at_mark_start(r);
 704       }
 705     } else {
 706       assert(_ctx->top_at_mark_start(r) == r->top(),
 707              "Region %zu should already have correct TAMS", r->index());
 708     }
 709   }
 710 
 711   bool is_thread_safe() { return true; }
 712 };
 713 
 714 void ShenandoahConcurrentGC::start_mark() {
 715   _mark.start_mark();
 716 }
 717 
 718 void ShenandoahConcurrentGC::op_init_mark() {
 719   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 720   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
 721   assert(Thread::current()->is_VM_thread(), "can only do this in VMThread");
 722 
 723   assert(_generation->is_bitmap_clear(), "need clear marking bitmap");
 724   assert(!_generation->is_mark_complete(), "should not be complete");
 725   assert(!heap->has_forwarded_objects(), "No forwarded objects on this path");
 726 
 727   if (heap->mode()->is_generational()) {
 728     if (_generation->is_global()) {
 729       heap->old_generation()->cancel_gc();
 730     }
 731 
 732     {
 733       // After we swap card table below, the write-table is all clean, and the read table holds
 734       // cards dirty prior to the start of GC. Young and bootstrap collection will update
 735       // the write card table as a side effect of remembered set scanning. Global collection will
 736       // update the card table as a side effect of global marking of old objects.
 737       ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_swap_rset);
 738       _generation->swap_card_tables();
 739     }
 740   }
 741 
 742   if (ShenandoahVerify) {
 743     ShenandoahTimingsTracker v(ShenandoahPhaseTimings::init_mark_verify);
 744     heap->verifier()->verify_before_concmark(_generation);
 745   }
 746 
 747   if (VerifyBeforeGC) {
 748     Universe::verify();
 749   }
 750 
 751   _generation->set_concurrent_mark_in_progress(true);
 752 
 753   start_mark();
 754 
 755   if (_do_old_gc_bootstrap) {
 756     shenandoah_assert_generational();
 757     // Update region state for both young and old regions
 758     ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_region_states);
 759     ShenandoahInitMarkUpdateRegionStateClosure cl;
 760     heap->parallel_heap_region_iterate(&cl);
 761     heap->old_generation()->ref_processor()->reset_thread_locals();
 762   } else {
 763     // Update region state for only young regions
 764     ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_region_states);
 765     ShenandoahInitMarkUpdateRegionStateClosure cl;
 766     _generation->parallel_heap_region_iterate(&cl);
 767   }
 768 
 769   // Weak reference processing
 770   ShenandoahReferenceProcessor* rp = _generation->ref_processor();
 771   rp->reset_thread_locals();
 772 
 773   // Make above changes visible to worker threads
 774   OrderAccess::fence();
 775 
 776   // Arm nmethods/stack for concurrent processing
 777   ShenandoahCodeRoots::arm_nmethods();
 778   ShenandoahStackWatermark::change_epoch_id();
 779 
 780   {
 781     ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::init_propagate_gc_state);
 782     heap->propagate_gc_state_to_all_threads();
 783   }
 784 }
 785 
 786 void ShenandoahConcurrentGC::op_mark_roots() {
 787   _mark.mark_concurrent_roots();
 788 }
 789 
 790 void ShenandoahConcurrentGC::op_mark() {
 791   _mark.concurrent_mark();
 792 }
 793 
 794 void ShenandoahConcurrentGC::op_final_mark() {
 795   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 796   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
 797   assert(!heap->has_forwarded_objects(), "No forwarded objects on this path");
 798 
 799   if (ShenandoahVerify) {
 800     heap->verifier()->verify_roots_no_forwarded(_generation);
 801   }
 802 
 803   if (!heap->cancelled_gc()) {
 804     _mark.finish_mark();
 805     assert(!heap->cancelled_gc(), "STW mark cannot OOM");
 806 
 807     // Notify JVMTI that the tagmap table will need cleaning.
 808     JvmtiTagMap::set_needs_cleaning();
 809 
 810     // The collection set is chosen by prepare_regions_and_collection_set(). Additionally, certain parameters have been
 811     // established to govern the evacuation efforts that are about to begin.  Refer to comments on reserve members in
 812     // ShenandoahGeneration and ShenandoahOldGeneration for more detail.
 813     _generation->prepare_regions_and_collection_set(true /*concurrent*/);
 814 
 815     // Has to be done after cset selection
 816     heap->prepare_concurrent_roots();
 817 
 818     if (!heap->collection_set()->is_empty()) {
 819       LogTarget(Debug, gc, cset) lt;
 820       if (lt.is_enabled()) {
 821         ResourceMark rm;
 822         LogStream ls(lt);
 823         heap->collection_set()->print_on(&ls);
 824       }
 825 
 826       if (ShenandoahVerify) {
 827         ShenandoahTimingsTracker v(ShenandoahPhaseTimings::final_mark_verify);
 828         heap->verifier()->verify_before_evacuation(_generation);
 829       }
 830 
 831       heap->set_evacuation_in_progress(true);
 832       // From here on, we need to update references.
 833       heap->set_has_forwarded_objects(true);
 834 
 835       // Arm nmethods/stack for concurrent processing
 836       ShenandoahCodeRoots::arm_nmethods();
 837       ShenandoahStackWatermark::change_epoch_id();
 838 
 839     } else {
 840       if (ShenandoahVerify) {
 841         ShenandoahTimingsTracker v(ShenandoahPhaseTimings::final_mark_verify);
 842         if (has_in_place_promotions(heap)) {
 843           heap->verifier()->verify_after_concmark_with_promotions(_generation);
 844         } else {
 845           heap->verifier()->verify_after_concmark(_generation);
 846         }
 847       }
 848     }
 849   }
 850 



 851   {
 852     ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::final_mark_propagate_gc_state);
 853     heap->propagate_gc_state_to_all_threads();
 854   }
 855 }
 856 
 857 bool ShenandoahConcurrentGC::has_in_place_promotions(ShenandoahHeap* heap) {
 858   return heap->mode()->is_generational() && heap->old_generation()->has_in_place_promotions();
 859 }
 860 
 861 class ShenandoahConcurrentEvacThreadClosure : public ThreadClosure {
 862 private:
 863   OopClosure* const _oops;
 864 public:
 865   explicit ShenandoahConcurrentEvacThreadClosure(OopClosure* oops) : _oops(oops) {}
 866 
 867   void do_thread(Thread* thread) override {
 868     JavaThread* const jt = JavaThread::cast(thread);
 869     StackWatermarkSet::finish_processing(jt, _oops, StackWatermarkKind::gc);
 870   }
 871 };
 872 
 873 class ShenandoahConcurrentEvacUpdateThreadTask : public WorkerTask {
 874 private:
 875   ShenandoahJavaThreadsIterator _java_threads;
 876 
 877 public:
 878   explicit ShenandoahConcurrentEvacUpdateThreadTask(uint n_workers) :
 879     WorkerTask("Shenandoah Evacuate/Update Concurrent Thread Roots"),
 880     _java_threads(ShenandoahPhaseTimings::conc_thread_roots, n_workers) {
 881   }
 882 
 883   void work(uint worker_id) override {
 884     ShenandoahContextEvacuateUpdateRootsClosure oops_cl;
 885     ShenandoahConcurrentEvacThreadClosure thr_cl(&oops_cl);
 886     _java_threads.threads_do(&thr_cl, worker_id);
 887   }
 888 };
 889 
 890 void ShenandoahConcurrentGC::op_thread_roots() {
 891   const ShenandoahHeap* const heap = ShenandoahHeap::heap();
 892   assert(heap->is_evacuation_in_progress(), "Checked by caller");
 893   ShenandoahGCWorkerPhase worker_phase(ShenandoahPhaseTimings::conc_thread_roots);
 894   ShenandoahConcurrentEvacUpdateThreadTask task(heap->workers()->active_workers());
 895   heap->workers()->run_task(&task);
 896 }
 897 
 898 void ShenandoahConcurrentGC::op_weak_refs() {
 899   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 900   assert(heap->is_concurrent_weak_root_in_progress(), "Only during this phase");
 901   // Concurrent weak refs processing
 902   ShenandoahGCWorkerPhase worker_phase(ShenandoahPhaseTimings::conc_weak_refs);
 903   if (heap->gc_cause() == GCCause::_wb_breakpoint) {
 904     ShenandoahBreakpoint::at_after_reference_processing_started();
 905   }
 906   _generation->ref_processor()->process_references(ShenandoahPhaseTimings::conc_weak_refs, heap->workers(), true /* concurrent */);
 907 }
 908 
 909 class ShenandoahEvacUpdateCleanupOopStorageRootsClosure : public BasicOopIterateClosure {
 910 private:
 911   ShenandoahHeap* const _heap;
 912   ShenandoahGeneration* const _generation;
 913   ShenandoahMarkingContext* const _mark_context;
 914   bool  _evac_in_progress;
 915   Thread* const _thread;
 916 
 917 public:
 918   explicit ShenandoahEvacUpdateCleanupOopStorageRootsClosure(ShenandoahGeneration* generation);
 919   void do_oop(oop* p);
 920   void do_oop(narrowOop* p);
 921 };
 922 
 923 ShenandoahEvacUpdateCleanupOopStorageRootsClosure::ShenandoahEvacUpdateCleanupOopStorageRootsClosure(ShenandoahGeneration* generation) :
 924   _heap(ShenandoahHeap::heap()),
 925   _generation(generation),
 926   _mark_context(ShenandoahHeap::heap()->marking_context()),
 927   _evac_in_progress(ShenandoahHeap::heap()->is_evacuation_in_progress()),
 928   _thread(Thread::current()) {
 929 }
 930 
 931 void ShenandoahEvacUpdateCleanupOopStorageRootsClosure::do_oop(oop* p) {
 932   const oop obj = RawAccess<>::oop_load(p);
 933   if (!CompressedOops::is_null(obj)) {
 934     if (!_mark_context->is_marked(obj)) {
 935       if (_generation->contains(obj)) {
 936         // Note: The obj is dead here. Do not touch it, just clear.
 937         ShenandoahHeap::atomic_clear_oop(p, obj);
 938       }
 939     } else if (_evac_in_progress && _heap->in_collection_set(obj)) {
 940       oop resolved = ShenandoahForwarding::get_forwardee(obj);
 941       if (resolved == obj) {
 942         resolved = _heap->evacuate_object(obj, _thread);
 943       }
 944       shenandoah_assert_not_in_cset_except(p, resolved, _heap->cancelled_gc());
 945       ShenandoahHeap::atomic_update_oop(resolved, p, obj);
 946     }
 947   }
 948 }
 949 
 950 void ShenandoahEvacUpdateCleanupOopStorageRootsClosure::do_oop(narrowOop* p) {
 951   ShouldNotReachHere();
 952 }
 953 
 954 class ShenandoahIsCLDAliveClosure : public CLDClosure {
 955 public:
 956   void do_cld(ClassLoaderData* cld) {
 957     cld->is_alive();
 958   }
 959 };
 960 
 961 class ShenandoahIsNMethodAliveClosure: public NMethodClosure {
 962 public:
 963   void do_nmethod(nmethod* n) {
 964     n->is_unloading();
 965   }
 966 };
 967 
 968 // This task not only evacuates/updates marked weak roots, but also "null"
 969 // dead weak roots.
 970 class ShenandoahConcurrentWeakRootsEvacUpdateTask : public WorkerTask {
 971 private:
 972   ShenandoahVMWeakRoots<true /*concurrent*/> _vm_roots;
 973 
 974   // Roots related to concurrent class unloading
 975   ShenandoahClassLoaderDataRoots<true /* concurrent */>
 976                                              _cld_roots;
 977   ShenandoahConcurrentNMethodIterator        _nmethod_itr;
 978   ShenandoahGeneration*                      _generation;
 979   ShenandoahPhaseTimings::Phase              _phase;
 980 
 981 public:
 982   ShenandoahConcurrentWeakRootsEvacUpdateTask(ShenandoahGeneration* generation, ShenandoahPhaseTimings::Phase phase) :
 983     WorkerTask("Shenandoah Evacuate/Update Concurrent Weak Roots"),
 984     _vm_roots(phase),
 985     _cld_roots(phase, ShenandoahHeap::heap()->workers()->active_workers(), false /*heap iteration*/),
 986     _nmethod_itr(ShenandoahCodeRoots::table()),
 987     _generation(generation),
 988     _phase(phase) {}
 989 
 990   ~ShenandoahConcurrentWeakRootsEvacUpdateTask() {
 991     // Notify runtime data structures of potentially dead oops
 992     _vm_roots.report_num_dead();
 993   }
 994 
 995   void work(uint worker_id) override {
 996     ShenandoahConcurrentWorkerSession worker_session(worker_id);
 997     SuspendibleThreadSetJoiner sts_join;
 998     {
 999       // jni_roots and weak_roots are OopStorage backed roots, concurrent iteration
1000       // may race against OopStorage::release() calls.
1001       ShenandoahEvacUpdateCleanupOopStorageRootsClosure cl(_generation);
1002       _vm_roots.oops_do(&cl, worker_id);
1003     }
1004 
1005     // If we are going to perform concurrent class unloading later on, we need to
1006     // clean up the weak oops in CLD and determine nmethod's unloading state, so that we
1007     // can clean up immediate garbage sooner.
1008     if (ShenandoahHeap::heap()->unload_classes()) {
1009       // Applies ShenandoahIsCLDAlive closure to CLDs, native barrier will either null the
1010       // CLD's holder or evacuate it.
1011       {
1012         ShenandoahIsCLDAliveClosure is_cld_alive;
1013         _cld_roots.cld_do(&is_cld_alive, worker_id);
1014       }
1015 
1016       // Applies ShenandoahIsNMethodAliveClosure to registered nmethods.
1017       // The closure calls nmethod->is_unloading(). The is_unloading
1018       // state is cached, therefore, during concurrent class unloading phase,
1019       // we will not touch the metadata of unloading nmethods
1020       {
1021         ShenandoahWorkerTimingsTracker timer(_phase, ShenandoahPhaseTimings::CodeCache, worker_id);
1022         ShenandoahIsNMethodAliveClosure is_nmethod_alive;
1023         _nmethod_itr.nmethods_do(&is_nmethod_alive);
1024       }
1025     }
1026   }
1027 };
1028 
1029 void ShenandoahConcurrentGC::op_weak_roots() {
1030   ShenandoahHeap* const heap = ShenandoahHeap::heap();
1031   assert(heap->is_concurrent_weak_root_in_progress(), "Only during this phase");
1032   {
1033     // Concurrent weak root processing
1034     ShenandoahGCWorkerPhase worker_phase(ShenandoahPhaseTimings::conc_weak_roots);
1035     ShenandoahConcurrentWeakRootsEvacUpdateTask task(_generation, ShenandoahPhaseTimings::conc_weak_roots);
1036     heap->workers()->run_task(&task);
1037   }
1038 
1039   {
1040     // It is possible for mutators executing the load reference barrier to have
1041     // loaded an oop through a weak handle that has since been nulled out by
1042     // weak root processing. Handshaking here forces them to complete the
1043     // barrier before the GC cycle continues and does something that would
1044     // change the evaluation of the barrier (for example, resetting the TAMS
1045     // on trashed regions could make an oop appear to be marked _after_ the
1046     // region has been recycled).
1047     ShenandoahTimingsTracker t(ShenandoahPhaseTimings::conc_weak_roots_rendezvous);
1048     heap->rendezvous_threads("Shenandoah Concurrent Weak Roots");
1049   }
1050 }
1051 
1052 void ShenandoahConcurrentGC::op_class_unloading() {
1053   ShenandoahHeap* const heap = ShenandoahHeap::heap();
1054   assert (heap->is_concurrent_weak_root_in_progress() &&
1055           heap->unload_classes(),
1056           "Checked by caller");
1057   heap->do_class_unloading();
1058 }
1059 
1060 class ShenandoahEvacUpdateCodeCacheClosure : public NMethodClosure {
1061 private:
1062   ShenandoahEvacuateUpdateMetadataClosure   _cl;
1063 
1064 public:
1065   ShenandoahEvacUpdateCodeCacheClosure() : _cl() {}
1066 
1067   void do_nmethod(nmethod* n) {
1068     ShenandoahNMethod* data = ShenandoahNMethod::gc_data(n);
1069     ShenandoahNMethodLocker locker(data->lock());
1070     data->oops_do(&_cl, /* fix_relocations = */ true);
1071     ShenandoahNMethod::disarm_nmethod(n);
1072   }
1073 };
1074 
1075 class ShenandoahConcurrentRootsEvacUpdateTask : public WorkerTask {
1076 private:
1077   ShenandoahPhaseTimings::Phase                 _phase;
1078   ShenandoahVMRoots<true /*concurrent*/>        _vm_roots;
1079   ShenandoahClassLoaderDataRoots<true /*concurrent*/>
1080                                                 _cld_roots;
1081   ShenandoahConcurrentNMethodIterator           _nmethod_itr;
1082 
1083 public:
1084   ShenandoahConcurrentRootsEvacUpdateTask(ShenandoahPhaseTimings::Phase phase) :
1085     WorkerTask("Shenandoah Evacuate/Update Concurrent Strong Roots"),
1086     _phase(phase),
1087     _vm_roots(phase),
1088     _cld_roots(phase, ShenandoahHeap::heap()->workers()->active_workers(), false /*heap iteration*/),
1089     _nmethod_itr(ShenandoahCodeRoots::table()) {}
1090 
1091   void work(uint worker_id) {
1092     ShenandoahConcurrentWorkerSession worker_session(worker_id);
1093     {
1094       {
1095         // vm_roots and weak_roots are OopStorage backed roots, concurrent iteration
1096         // may race against OopStorage::release() calls.
1097         ShenandoahContextEvacuateUpdateRootsClosure cl;
1098         _vm_roots.oops_do<ShenandoahContextEvacuateUpdateRootsClosure>(&cl, worker_id);
1099       }
1100 
1101       {
1102         ShenandoahEvacuateUpdateMetadataClosure cl;
1103         CLDToOopClosure clds(&cl, ClassLoaderData::_claim_strong);
1104         _cld_roots.cld_do(&clds, worker_id);
1105       }
1106     }
1107 
1108     if (!ShenandoahHeap::heap()->unload_classes()) {
1109       ShenandoahWorkerTimingsTracker timer(_phase, ShenandoahPhaseTimings::CodeCache, worker_id);
1110       ShenandoahEvacUpdateCodeCacheClosure cl;
1111       _nmethod_itr.nmethods_do(&cl);
1112     }
1113   }
1114 };
1115 
1116 void ShenandoahConcurrentGC::op_strong_roots() {
1117   ShenandoahHeap* const heap = ShenandoahHeap::heap();
1118   assert(heap->is_concurrent_strong_root_in_progress(), "Checked by caller");
1119   ShenandoahConcurrentRootsEvacUpdateTask task(ShenandoahPhaseTimings::conc_strong_roots);
1120   heap->workers()->run_task(&task);
1121   heap->set_concurrent_strong_root_in_progress(false);
1122 }
1123 
1124 void ShenandoahConcurrentGC::op_cleanup_early() {
1125   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
1126                               ShenandoahWorkerPolicy::calc_workers_for_conc_cleanup(),
1127                               "cleanup early.");
1128   ShenandoahHeap::heap()->recycle_trash();
1129 }
1130 
1131 void ShenandoahConcurrentGC::op_evacuate() {
1132   ShenandoahHeap::heap()->evacuate_collection_set(_generation, true /*concurrent*/);
1133 }
1134 
1135 void ShenandoahConcurrentGC::op_init_update_refs() {
1136   if (ShenandoahVerify) {
1137     ShenandoahHeap* const heap = ShenandoahHeap::heap();
1138     ShenandoahTimingsTracker v(ShenandoahPhaseTimings::init_update_refs_verify);
1139     heap->verifier()->verify_before_update_refs(_generation);
1140   }
1141 }
1142 
1143 void ShenandoahConcurrentGC::op_update_refs() {
1144   ShenandoahHeap::heap()->update_heap_references(_generation, true /*concurrent*/);
1145 }
1146 
1147 class ShenandoahUpdateThreadHandshakeClosure : public HandshakeClosure {
1148 private:
1149   // This closure runs when thread is stopped for handshake, which means
1150   // we can use non-concurrent closure here, as long as it only updates
1151   // locations modified by the thread itself, i.e. stack locations.
1152   ShenandoahNonConcUpdateRefsClosure _cl;
1153 public:
1154   ShenandoahUpdateThreadHandshakeClosure();
1155   void do_thread(Thread* thread) override;
1156 };
1157 
1158 ShenandoahUpdateThreadHandshakeClosure::ShenandoahUpdateThreadHandshakeClosure() :
1159   HandshakeClosure("Shenandoah Update Thread Roots") {
1160 }
1161 
1162 void ShenandoahUpdateThreadHandshakeClosure::do_thread(Thread* thread) {
1163   if (thread->is_Java_thread()) {
1164     JavaThread* jt = JavaThread::cast(thread);
1165     ResourceMark rm;
1166     jt->oops_do(&_cl, nullptr);
1167   }
1168 }
1169 
1170 class ShenandoahUpdateThreadRootsAndFlushOldSatbBuffers final : public HandshakeClosure {
1171   // When Shenandoah is marking the old generation, it is possible for the SATB barrier
1172   // to pick up overwritten pointers that point into a cset region. If these pointers
1173   // are accessed by mark threads, they will crash. Once update refs has completed, it is
1174   // no longer possible for a mutator thread to overwrite a pointer into a cset region.
1175   //
1176   // Therefore, at the end of update refs, we use this closure to update the thread roots
1177   // and 'complete' all the thread local SATB buffers. Completing these will filter out
1178   // anything that has already been marked or anything that points to a region which is
1179   // not old. We do not need to worry about ABA situations where a region may become old
1180   // after the pointer is enqueued but before it is filtered. There are only two ways a
1181   // region may become old:
1182   //  1. The region is promoted in place. This is safe because such regions will never
1183   //     be in the collection set. If this happens, the pointer will be preserved, essentially
1184   //     becoming part of the old snapshot.
1185   //  2. The region is allocated during evacuation of old. This is also not a concern because
1186   //     we haven't yet finished marking old so no mixed evacuations will happen.
1187   ShenandoahUpdateThreadHandshakeClosure _update_roots;
1188   ShenandoahFlushSATB _flush_all_satb;
1189 
1190 public:
1191   ShenandoahUpdateThreadRootsAndFlushOldSatbBuffers() :
1192     HandshakeClosure("Shenandoah Update Thread Roots and Flush SATB"),
1193     _flush_all_satb(ShenandoahBarrierSet::satb_mark_queue_set()) {
1194     assert(ShenandoahBarrierSet::satb_mark_queue_set().get_filter_out_young(),
1195            "Should be filtering pointers outside of old during old marking");
1196   }
1197 
1198   void do_thread(Thread* thread) override {
1199     _update_roots.do_thread(thread);
1200     _flush_all_satb.do_thread(thread);
1201   }
1202 };
1203 
1204 void ShenandoahConcurrentGC::op_update_thread_roots() {
1205   ShenandoahHeap* const heap = ShenandoahHeap::heap();
1206   if (heap->is_concurrent_old_mark_in_progress()) {
1207     ShenandoahUpdateThreadRootsAndFlushOldSatbBuffers cl;
1208     Handshake::execute(&cl);
1209   } else {
1210     ShenandoahUpdateThreadHandshakeClosure cl;
1211     Handshake::execute(&cl);
1212   }
1213 }
1214 
1215 void ShenandoahConcurrentGC::op_final_update_refs() {
1216   ShenandoahHeap* const heap = ShenandoahHeap::heap();
1217   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
1218   assert(!heap->_update_refs_iterator.has_next(), "Should have finished update references");
1219 
1220   heap->finish_concurrent_roots();
1221 
1222   // Clear cancelled GC, if set. On cancellation path, the block before would handle
1223   // everything.
1224   if (heap->cancelled_gc()) {
1225     heap->clear_cancelled_gc();
1226   }
1227 
1228   // Has to be done before cset is clear
1229   if (ShenandoahVerify) {
1230     heap->verifier()->verify_roots_in_to_space(_generation);
1231   }
1232 
1233   // If we are running in generational mode, this will also age active regions that
1234   // haven't been used for allocation.
1235   heap->update_heap_region_states(true /*concurrent*/);
1236 
1237   heap->set_update_refs_in_progress(false);
1238   heap->set_has_forwarded_objects(false);
1239 
1240   if (ShenandoahVerify) {
1241     ShenandoahTimingsTracker v(ShenandoahPhaseTimings::final_update_refs_verify);
1242     heap->verifier()->verify_after_update_refs(_generation);
1243   }
1244 
1245   if (VerifyAfterGC) {
1246     Universe::verify();
1247   }
1248 
1249   heap->rebuild_free_set(true /*concurrent*/);
1250   _generation->heuristics()->start_idle_span();
1251 



1252   {
1253     ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::final_update_refs_propagate_gc_state);
1254     heap->propagate_gc_state_to_all_threads();
1255   }
1256 }
1257 
1258 void ShenandoahConcurrentGC::entry_final_roots() {
1259   ShenandoahHeap* const heap = ShenandoahHeap::heap();
1260   TraceCollectorStats tcs(heap->monitoring_support()->concurrent_collection_counters());
1261   SHENANDOAH_EVENT_MESSAGE(msg, _generation->type(), "Concurrent final roots", "");
1262   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_final_roots);
1263   EventMark em("%s", msg);
1264 
1265   heap->concurrent_final_roots();
1266 }
1267 
1268 void ShenandoahConcurrentGC::op_verify_final() {
1269   assert(ShenandoahVerify, "Should have been checked before");
1270   ShenandoahHeap* const heap = ShenandoahHeap::heap();
1271   heap->verifier()->verify_after_gc(_generation);
1272 }
1273 
1274 void ShenandoahConcurrentGC::op_cleanup_complete() {
1275   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
1276                               ShenandoahWorkerPolicy::calc_workers_for_conc_cleanup(),
1277                               "cleanup complete.");
1278   ShenandoahHeap::heap()->recycle_trash();
1279 }
1280 
1281 void ShenandoahConcurrentGC::op_reset_after_collect() {
1282   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
1283                           ShenandoahWorkerPolicy::calc_workers_for_conc_reset(),
1284                           "reset after collection.");
1285 
1286   ShenandoahHeap* const heap = ShenandoahHeap::heap();
1287   if (heap->mode()->is_generational()) {
1288     // If we are in the midst of an old gc bootstrap or an old marking, we want to leave the mark bit map of
1289     // the young generation intact. In particular, reference processing in the old generation may potentially
1290     // need the reachability of a young generation referent of a Reference object in the old generation.
1291     if (!_do_old_gc_bootstrap && !heap->is_concurrent_old_mark_in_progress()) {
1292       heap->young_generation()->reset_mark_bitmap<false>();
1293     }
1294   } else {
1295     _generation->reset_mark_bitmap<false>();
1296   }
1297 }
1298 
1299 bool ShenandoahConcurrentGC::check_cancellation_and_abort(ShenandoahDegenPoint point) {
1300   if (ShenandoahHeap::heap()->cancelled_gc()) {
1301     _degen_point = point;
1302     return true;
1303   }
1304   return false;
1305 }
--- EOF ---