1 /* 2 * Copyright (c) 2013, 2020, Red Hat, Inc. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "precompiled.hpp" 26 27 #include "classfile/symbolTable.hpp" 28 #include "classfile/systemDictionary.hpp" 29 #include "code/codeCache.hpp" 30 31 #include "gc/shared/weakProcessor.inline.hpp" 32 #include "gc/shared/gcTimer.hpp" 33 #include "gc/shared/gcTrace.hpp" 34 #include "gc/shared/referenceProcessor.hpp" 35 #include "gc/shared/referenceProcessorPhaseTimes.hpp" 36 #include "gc/shared/strongRootsScope.hpp" 37 38 #include "gc/shenandoah/shenandoahBarrierSet.inline.hpp" 39 #include "gc/shenandoah/shenandoahClosures.inline.hpp" 40 #include "gc/shenandoah/shenandoahConcurrentMark.inline.hpp" 41 #include "gc/shenandoah/shenandoahMarkCompact.hpp" 42 #include "gc/shenandoah/shenandoahHeap.inline.hpp" 43 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp" 44 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp" 45 #include "gc/shenandoah/shenandoahPhaseTimings.hpp" 46 #include "gc/shenandoah/shenandoahTaskqueue.inline.hpp" 47 #include "gc/shenandoah/shenandoahUtils.hpp" 48 49 #include "memory/iterator.inline.hpp" 50 #include "memory/metaspace.hpp" 51 #include "memory/resourceArea.hpp" 52 #include "oops/oop.inline.hpp" 53 #include "runtime/handles.inline.hpp" 54 55 template<UpdateRefsMode UPDATE_REFS> 56 class ShenandoahInitMarkRootsClosure : public OopClosure { 57 private: 58 ShenandoahObjToScanQueue* _queue; 59 ShenandoahHeap* _heap; 60 ShenandoahMarkingContext* const _mark_context; 61 62 template <class T> 63 inline void do_oop_work(T* p) { 64 ShenandoahConcurrentMark::mark_through_ref<T, UPDATE_REFS, NO_DEDUP>(p, _heap, _queue, _mark_context); 65 } 66 67 public: 68 ShenandoahInitMarkRootsClosure(ShenandoahObjToScanQueue* q) : 69 _queue(q), 70 _heap(ShenandoahHeap::heap()), 71 _mark_context(_heap->marking_context()) {}; 72 73 void do_oop(narrowOop* p) { do_oop_work(p); } 74 void do_oop(oop* p) { do_oop_work(p); } 75 }; 76 77 ShenandoahMarkRefsSuperClosure::ShenandoahMarkRefsSuperClosure(ShenandoahObjToScanQueue* q, ReferenceProcessor* rp) : 78 MetadataVisitingOopIterateClosure(rp), 79 _queue(q), 80 _heap(ShenandoahHeap::heap()), 81 _mark_context(_heap->marking_context()) 82 { } 83 84 template<UpdateRefsMode UPDATE_REFS> 85 class ShenandoahInitMarkRootsTask : public AbstractGangTask { 86 private: 87 ShenandoahRootScanner* _rp; 88 public: 89 ShenandoahInitMarkRootsTask(ShenandoahRootScanner* rp) : 90 AbstractGangTask("Shenandoah init mark roots task"), 91 _rp(rp) { 92 } 93 94 void work(uint worker_id) { 95 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at a safepoint"); 96 ShenandoahParallelWorkerSession worker_session(worker_id); 97 98 ShenandoahHeap* heap = ShenandoahHeap::heap(); 99 ShenandoahObjToScanQueueSet* queues = heap->concurrent_mark()->task_queues(); 100 assert(queues->get_reserved() > worker_id, "Queue has not been reserved for worker id: %d", worker_id); 101 102 ShenandoahObjToScanQueue* q = queues->queue(worker_id); 103 104 ShenandoahInitMarkRootsClosure<UPDATE_REFS> mark_cl(q); 105 do_work(heap, &mark_cl, worker_id); 106 } 107 108 private: 109 void do_work(ShenandoahHeap* heap, OopClosure* oops, uint worker_id) { 110 // The rationale for selecting the roots to scan is as follows: 111 // a. With unload_classes = true, we only want to scan the actual strong roots from the 112 // code cache. This will allow us to identify the dead classes, unload them, *and* 113 // invalidate the relevant code cache blobs. This could be only done together with 114 // class unloading. 115 // b. With unload_classes = false, we have to nominally retain all the references from code 116 // cache, because there could be the case of embedded class/oop in the generated code, 117 // which we will never visit during mark. Without code cache invalidation, as in (a), 118 // we risk executing that code cache blob, and crashing. 119 if (heap->unload_classes()) { 120 _rp->strong_roots_do(worker_id, oops); 121 } else { 122 _rp->roots_do(worker_id, oops); 123 } 124 } 125 }; 126 127 class ShenandoahUpdateRootsTask : public AbstractGangTask { 128 private: 129 ShenandoahRootUpdater* _root_updater; 130 bool _check_alive; 131 public: 132 ShenandoahUpdateRootsTask(ShenandoahRootUpdater* root_updater, bool check_alive) : 133 AbstractGangTask("Shenandoah update roots task"), 134 _root_updater(root_updater), 135 _check_alive(check_alive){ 136 } 137 138 void work(uint worker_id) { 139 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at a safepoint"); 140 ShenandoahParallelWorkerSession worker_session(worker_id); 141 142 ShenandoahHeap* heap = ShenandoahHeap::heap(); 143 ShenandoahUpdateRefsClosure cl; 144 if (_check_alive) { 145 ShenandoahForwardedIsAliveClosure is_alive; 146 _root_updater->roots_do<ShenandoahForwardedIsAliveClosure, ShenandoahUpdateRefsClosure>(worker_id, &is_alive, &cl); 147 } else { 148 AlwaysTrueClosure always_true;; 149 _root_updater->roots_do<AlwaysTrueClosure, ShenandoahUpdateRefsClosure>(worker_id, &always_true, &cl); 150 } 151 } 152 }; 153 154 class ShenandoahConcurrentMarkingTask : public AbstractGangTask { 155 private: 156 ShenandoahConcurrentMark* _cm; 157 TaskTerminator* _terminator; 158 159 public: 160 ShenandoahConcurrentMarkingTask(ShenandoahConcurrentMark* cm, TaskTerminator* terminator) : 161 AbstractGangTask("Root Region Scan"), _cm(cm), _terminator(terminator) { 162 } 163 164 void work(uint worker_id) { 165 ShenandoahHeap* heap = ShenandoahHeap::heap(); 166 ShenandoahConcurrentWorkerSession worker_session(worker_id); 167 ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers); 168 ShenandoahObjToScanQueue* q = _cm->get_queue(worker_id); 169 ReferenceProcessor* rp; 170 if (heap->process_references()) { 171 rp = heap->ref_processor(); 172 shenandoah_assert_rp_isalive_installed(); 173 } else { 174 rp = NULL; 175 } 176 177 _cm->concurrent_scan_code_roots(worker_id, rp); 178 _cm->mark_loop(worker_id, _terminator, rp, 179 true, // cancellable 180 ShenandoahStringDedup::is_enabled()); // perform string dedup 181 } 182 }; 183 184 class ShenandoahSATBAndRemarkCodeRootsThreadsClosure : public ThreadClosure { 185 private: 186 ShenandoahSATBBufferClosure* _satb_cl; 187 OopClosure* const _cl; 188 MarkingCodeBlobClosure* _code_cl; 189 uintx _claim_token; 190 191 public: 192 ShenandoahSATBAndRemarkCodeRootsThreadsClosure(ShenandoahSATBBufferClosure* satb_cl, OopClosure* cl, MarkingCodeBlobClosure* code_cl) : 193 _satb_cl(satb_cl), _cl(cl), _code_cl(code_cl), 194 _claim_token(Threads::thread_claim_token()) {} 195 196 void do_thread(Thread* thread) { 197 if (thread->claim_threads_do(true, _claim_token)) { 198 ShenandoahThreadLocalData::satb_mark_queue(thread).apply_closure_and_empty(_satb_cl); 199 if (thread->is_Java_thread()) { 200 if (_cl != NULL) { 201 ResourceMark rm; 202 thread->oops_do(_cl, _code_cl); 203 } else if (_code_cl != NULL) { 204 // In theory it should not be neccessary to explicitly walk the nmethods to find roots for concurrent marking 205 // however the liveness of oops reachable from nmethods have very complex lifecycles: 206 // * Alive if on the stack of an executing method 207 // * Weakly reachable otherwise 208 // Some objects reachable from nmethods, such as the class loader (or klass_holder) of the receiver should be 209 // live by the SATB invariant but other oops recorded in nmethods may behave differently. 210 JavaThread* jt = (JavaThread*)thread; 211 jt->nmethods_do(_code_cl); 212 } 213 } 214 } 215 } 216 }; 217 218 class ShenandoahFinalMarkingTask : public AbstractGangTask { 219 private: 220 ShenandoahConcurrentMark* _cm; 221 TaskTerminator* _terminator; 222 bool _dedup_string; 223 224 public: 225 ShenandoahFinalMarkingTask(ShenandoahConcurrentMark* cm, TaskTerminator* terminator, bool dedup_string) : 226 AbstractGangTask("Shenandoah Final Marking"), _cm(cm), _terminator(terminator), _dedup_string(dedup_string) { 227 } 228 229 void work(uint worker_id) { 230 ShenandoahHeap* heap = ShenandoahHeap::heap(); 231 232 ShenandoahParallelWorkerSession worker_session(worker_id); 233 ReferenceProcessor* rp; 234 if (heap->process_references()) { 235 rp = heap->ref_processor(); 236 shenandoah_assert_rp_isalive_installed(); 237 } else { 238 rp = NULL; 239 } 240 241 // First drain remaining SATB buffers. 242 // Notice that this is not strictly necessary for mark-compact. But since 243 // it requires a StrongRootsScope around the task, we need to claim the 244 // threads, and performance-wise it doesn't really matter. Adds about 1ms to 245 // full-gc. 246 { 247 ShenandoahObjToScanQueue* q = _cm->get_queue(worker_id); 248 249 ShenandoahSATBBufferClosure cl(q); 250 SATBMarkQueueSet& satb_mq_set = ShenandoahBarrierSet::satb_mark_queue_set(); 251 while (satb_mq_set.apply_closure_to_completed_buffer(&cl)); 252 bool do_nmethods = heap->unload_classes() && !ShenandoahConcurrentRoots::can_do_concurrent_class_unloading(); 253 if (heap->has_forwarded_objects()) { 254 ShenandoahMarkResolveRefsClosure resolve_mark_cl(q, rp); 255 MarkingCodeBlobClosure blobsCl(&resolve_mark_cl, !CodeBlobToOopClosure::FixRelocations); 256 ShenandoahSATBAndRemarkCodeRootsThreadsClosure tc(&cl, 257 ShenandoahStoreValEnqueueBarrier ? &resolve_mark_cl : NULL, 258 do_nmethods ? &blobsCl : NULL); 259 Threads::threads_do(&tc); 260 } else { 261 ShenandoahMarkRefsClosure mark_cl(q, rp); 262 MarkingCodeBlobClosure blobsCl(&mark_cl, !CodeBlobToOopClosure::FixRelocations); 263 ShenandoahSATBAndRemarkCodeRootsThreadsClosure tc(&cl, 264 ShenandoahStoreValEnqueueBarrier ? &mark_cl : NULL, 265 do_nmethods ? &blobsCl : NULL); 266 Threads::threads_do(&tc); 267 } 268 } 269 270 if (heap->is_degenerated_gc_in_progress() || heap->is_full_gc_in_progress()) { 271 // Full GC does not execute concurrent cycle. 272 // Degenerated cycle may bypass concurrent cycle. 273 // So code roots might not be scanned, let's scan here. 274 _cm->concurrent_scan_code_roots(worker_id, rp); 275 } 276 277 _cm->mark_loop(worker_id, _terminator, rp, 278 false, // not cancellable 279 _dedup_string); 280 281 assert(_cm->task_queues()->is_empty(), "Should be empty"); 282 } 283 }; 284 285 void ShenandoahConcurrentMark::mark_roots(ShenandoahPhaseTimings::Phase root_phase) { 286 assert(Thread::current()->is_VM_thread(), "can only do this in VMThread"); 287 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at a safepoint"); 288 289 ShenandoahHeap* heap = ShenandoahHeap::heap(); 290 291 ShenandoahGCPhase phase(root_phase); 292 293 WorkGang* workers = heap->workers(); 294 uint nworkers = workers->active_workers(); 295 296 assert(nworkers <= task_queues()->size(), "Just check"); 297 298 ShenandoahRootScanner root_proc(nworkers, root_phase); 299 TASKQUEUE_STATS_ONLY(task_queues()->reset_taskqueue_stats()); 300 task_queues()->reserve(nworkers); 301 302 if (heap->has_forwarded_objects()) { 303 ShenandoahInitMarkRootsTask<RESOLVE> mark_roots(&root_proc); 304 workers->run_task(&mark_roots); 305 } else { 306 // No need to update references, which means the heap is stable. 307 // Can save time not walking through forwarding pointers. 308 ShenandoahInitMarkRootsTask<NONE> mark_roots(&root_proc); 309 workers->run_task(&mark_roots); 310 } 311 312 clear_claim_codecache(); 313 } 314 315 void ShenandoahConcurrentMark::update_roots(ShenandoahPhaseTimings::Phase root_phase) { 316 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at a safepoint"); 317 assert(root_phase == ShenandoahPhaseTimings::full_gc_update_roots || 318 root_phase == ShenandoahPhaseTimings::degen_gc_update_roots, 319 "Only for these phases"); 320 321 ShenandoahGCPhase phase(root_phase); 322 323 bool check_alive = root_phase == ShenandoahPhaseTimings::degen_gc_update_roots; 324 325 #if COMPILER2_OR_JVMCI 326 DerivedPointerTable::clear(); 327 #endif 328 329 uint nworkers = _heap->workers()->active_workers(); 330 331 ShenandoahRootUpdater root_updater(nworkers, root_phase); 332 ShenandoahUpdateRootsTask update_roots(&root_updater, check_alive); 333 _heap->workers()->run_task(&update_roots); 334 335 #if COMPILER2_OR_JVMCI 336 DerivedPointerTable::update_pointers(); 337 #endif 338 } 339 340 class ShenandoahUpdateThreadRootsTask : public AbstractGangTask { 341 private: 342 ShenandoahThreadRoots _thread_roots; 343 ShenandoahPhaseTimings::Phase _phase; 344 ShenandoahGCWorkerPhase _worker_phase; 345 public: 346 ShenandoahUpdateThreadRootsTask(bool is_par, ShenandoahPhaseTimings::Phase phase) : 347 AbstractGangTask("Shenandoah Update Thread Roots"), 348 _thread_roots(phase, is_par), 349 _phase(phase), 350 _worker_phase(phase) {} 351 352 void work(uint worker_id) { 353 ShenandoahParallelWorkerSession worker_session(worker_id); 354 ShenandoahUpdateRefsClosure cl; 355 _thread_roots.oops_do(&cl, NULL, worker_id); 356 } 357 }; 358 359 void ShenandoahConcurrentMark::update_thread_roots(ShenandoahPhaseTimings::Phase root_phase) { 360 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at a safepoint"); 361 362 ShenandoahGCPhase phase(root_phase); 363 364 #if COMPILER2_OR_JVMCI 365 DerivedPointerTable::clear(); 366 #endif 367 368 WorkGang* workers = _heap->workers(); 369 bool is_par = workers->active_workers() > 1; 370 371 ShenandoahUpdateThreadRootsTask task(is_par, root_phase); 372 workers->run_task(&task); 373 374 #if COMPILER2_OR_JVMCI 375 DerivedPointerTable::update_pointers(); 376 #endif 377 } 378 379 void ShenandoahConcurrentMark::initialize(uint workers) { 380 _heap = ShenandoahHeap::heap(); 381 382 uint num_queues = MAX2(workers, 1U); 383 384 _task_queues = new ShenandoahObjToScanQueueSet((int) num_queues); 385 386 for (uint i = 0; i < num_queues; ++i) { 387 ShenandoahObjToScanQueue* task_queue = new ShenandoahObjToScanQueue(); 388 task_queue->initialize(); 389 _task_queues->register_queue(i, task_queue); 390 } 391 } 392 393 void ShenandoahConcurrentMark::concurrent_scan_code_roots(uint worker_id, ReferenceProcessor* rp) { 394 if (_heap->unload_classes()) { 395 return; 396 } 397 398 if (claim_codecache()) { 399 ShenandoahObjToScanQueue* q = task_queues()->queue(worker_id); 400 MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag); 401 // TODO: We can not honor StringDeduplication here, due to lock ranking 402 // inversion. So, we may miss some deduplication candidates. 403 if (_heap->has_forwarded_objects()) { 404 ShenandoahMarkResolveRefsClosure cl(q, rp); 405 CodeBlobToOopClosure blobs(&cl, !CodeBlobToOopClosure::FixRelocations); 406 CodeCache::blobs_do(&blobs); 407 } else { 408 ShenandoahMarkRefsClosure cl(q, rp); 409 CodeBlobToOopClosure blobs(&cl, !CodeBlobToOopClosure::FixRelocations); 410 CodeCache::blobs_do(&blobs); 411 } 412 } 413 } 414 415 void ShenandoahConcurrentMark::mark_from_roots() { 416 WorkGang* workers = _heap->workers(); 417 uint nworkers = workers->active_workers(); 418 419 if (_heap->process_references()) { 420 ReferenceProcessor* rp = _heap->ref_processor(); 421 rp->set_active_mt_degree(nworkers); 422 423 // enable ("weak") refs discovery 424 rp->enable_discovery(true /*verify_no_refs*/); 425 rp->setup_policy(_heap->soft_ref_policy()->should_clear_all_soft_refs()); 426 } 427 428 shenandoah_assert_rp_isalive_not_installed(); 429 ShenandoahIsAliveSelector is_alive; 430 ReferenceProcessorIsAliveMutator fix_isalive(_heap->ref_processor(), is_alive.is_alive_closure()); 431 432 task_queues()->reserve(nworkers); 433 434 { 435 TaskTerminator terminator(nworkers, task_queues()); 436 ShenandoahConcurrentMarkingTask task(this, &terminator); 437 workers->run_task(&task); 438 } 439 440 assert(task_queues()->is_empty() || _heap->cancelled_gc(), "Should be empty when not cancelled"); 441 } 442 443 void ShenandoahConcurrentMark::finish_mark_from_roots(bool full_gc) { 444 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at a safepoint"); 445 446 uint nworkers = _heap->workers()->active_workers(); 447 448 // Finally mark everything else we've got in our queues during the previous steps. 449 // It does two different things for concurrent vs. mark-compact GC: 450 // - For concurrent GC, it starts with empty task queues, drains the remaining 451 // SATB buffers, and then completes the marking closure. 452 // - For mark-compact GC, it starts out with the task queues seeded by initial 453 // root scan, and completes the closure, thus marking through all live objects 454 // The implementation is the same, so it's shared here. 455 { 456 ShenandoahGCPhase phase(full_gc ? 457 ShenandoahPhaseTimings::full_gc_mark_finish_queues : 458 ShenandoahPhaseTimings::finish_queues); 459 task_queues()->reserve(nworkers); 460 461 shenandoah_assert_rp_isalive_not_installed(); 462 ShenandoahIsAliveSelector is_alive; 463 ReferenceProcessorIsAliveMutator fix_isalive(_heap->ref_processor(), is_alive.is_alive_closure()); 464 465 StrongRootsScope scope(nworkers); 466 TaskTerminator terminator(nworkers, task_queues()); 467 ShenandoahFinalMarkingTask task(this, &terminator, ShenandoahStringDedup::is_enabled()); 468 _heap->workers()->run_task(&task); 469 } 470 471 assert(task_queues()->is_empty(), "Should be empty"); 472 473 // When we're done marking everything, we process weak references. 474 if (_heap->process_references()) { 475 weak_refs_work(full_gc); 476 } 477 478 assert(task_queues()->is_empty(), "Should be empty"); 479 TASKQUEUE_STATS_ONLY(task_queues()->print_taskqueue_stats()); 480 TASKQUEUE_STATS_ONLY(task_queues()->reset_taskqueue_stats()); 481 } 482 483 // Weak Reference Closures 484 class ShenandoahCMDrainMarkingStackClosure: public VoidClosure { 485 uint _worker_id; 486 TaskTerminator* _terminator; 487 bool _reset_terminator; 488 489 public: 490 ShenandoahCMDrainMarkingStackClosure(uint worker_id, TaskTerminator* t, bool reset_terminator = false): 491 _worker_id(worker_id), 492 _terminator(t), 493 _reset_terminator(reset_terminator) { 494 } 495 496 void do_void() { 497 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at a safepoint"); 498 499 ShenandoahHeap* sh = ShenandoahHeap::heap(); 500 ShenandoahConcurrentMark* scm = sh->concurrent_mark(); 501 assert(sh->process_references(), "why else would we be here?"); 502 ReferenceProcessor* rp = sh->ref_processor(); 503 504 shenandoah_assert_rp_isalive_installed(); 505 506 scm->mark_loop(_worker_id, _terminator, rp, 507 false, // not cancellable 508 false); // do not do strdedup 509 510 if (_reset_terminator) { 511 _terminator->reset_for_reuse(); 512 } 513 } 514 }; 515 516 class ShenandoahCMKeepAliveClosure : public OopClosure { 517 private: 518 ShenandoahObjToScanQueue* _queue; 519 ShenandoahHeap* _heap; 520 ShenandoahMarkingContext* const _mark_context; 521 522 template <class T> 523 inline void do_oop_work(T* p) { 524 ShenandoahConcurrentMark::mark_through_ref<T, NONE, NO_DEDUP>(p, _heap, _queue, _mark_context); 525 } 526 527 public: 528 ShenandoahCMKeepAliveClosure(ShenandoahObjToScanQueue* q) : 529 _queue(q), 530 _heap(ShenandoahHeap::heap()), 531 _mark_context(_heap->marking_context()) {} 532 533 void do_oop(narrowOop* p) { do_oop_work(p); } 534 void do_oop(oop* p) { do_oop_work(p); } 535 }; 536 537 class ShenandoahCMKeepAliveUpdateClosure : public OopClosure { 538 private: 539 ShenandoahObjToScanQueue* _queue; 540 ShenandoahHeap* _heap; 541 ShenandoahMarkingContext* const _mark_context; 542 543 template <class T> 544 inline void do_oop_work(T* p) { 545 ShenandoahConcurrentMark::mark_through_ref<T, SIMPLE, NO_DEDUP>(p, _heap, _queue, _mark_context); 546 } 547 548 public: 549 ShenandoahCMKeepAliveUpdateClosure(ShenandoahObjToScanQueue* q) : 550 _queue(q), 551 _heap(ShenandoahHeap::heap()), 552 _mark_context(_heap->marking_context()) {} 553 554 void do_oop(narrowOop* p) { do_oop_work(p); } 555 void do_oop(oop* p) { do_oop_work(p); } 556 }; 557 558 class ShenandoahWeakUpdateClosure : public OopClosure { 559 private: 560 ShenandoahHeap* const _heap; 561 562 template <class T> 563 inline void do_oop_work(T* p) { 564 oop o = _heap->maybe_update_with_forwarded(p); 565 shenandoah_assert_marked_except(p, o, o == NULL); 566 } 567 568 public: 569 ShenandoahWeakUpdateClosure() : _heap(ShenandoahHeap::heap()) {} 570 571 void do_oop(narrowOop* p) { do_oop_work(p); } 572 void do_oop(oop* p) { do_oop_work(p); } 573 }; 574 575 class ShenandoahRefProcTaskProxy : public AbstractGangTask { 576 private: 577 AbstractRefProcTaskExecutor::ProcessTask& _proc_task; 578 TaskTerminator* _terminator; 579 580 public: 581 ShenandoahRefProcTaskProxy(AbstractRefProcTaskExecutor::ProcessTask& proc_task, 582 TaskTerminator* t) : 583 AbstractGangTask("Process reference objects in parallel"), 584 _proc_task(proc_task), 585 _terminator(t) { 586 } 587 588 void work(uint worker_id) { 589 ResourceMark rm; 590 HandleMark hm; 591 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at a safepoint"); 592 ShenandoahHeap* heap = ShenandoahHeap::heap(); 593 ShenandoahParallelWorkerSession worker_session(worker_id); 594 ShenandoahCMDrainMarkingStackClosure complete_gc(worker_id, _terminator); 595 if (heap->has_forwarded_objects()) { 596 ShenandoahForwardedIsAliveClosure is_alive; 597 ShenandoahCMKeepAliveUpdateClosure keep_alive(heap->concurrent_mark()->get_queue(worker_id)); 598 _proc_task.work(worker_id, is_alive, keep_alive, complete_gc); 599 } else { 600 ShenandoahIsAliveClosure is_alive; 601 ShenandoahCMKeepAliveClosure keep_alive(heap->concurrent_mark()->get_queue(worker_id)); 602 _proc_task.work(worker_id, is_alive, keep_alive, complete_gc); 603 } 604 } 605 }; 606 607 class ShenandoahRefProcTaskExecutor : public AbstractRefProcTaskExecutor { 608 private: 609 WorkGang* _workers; 610 611 public: 612 ShenandoahRefProcTaskExecutor(WorkGang* workers) : 613 _workers(workers) { 614 } 615 616 // Executes a task using worker threads. 617 void execute(ProcessTask& task, uint ergo_workers) { 618 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at a safepoint"); 619 620 ShenandoahHeap* heap = ShenandoahHeap::heap(); 621 ShenandoahConcurrentMark* cm = heap->concurrent_mark(); 622 ShenandoahPushWorkerQueuesScope scope(_workers, cm->task_queues(), 623 ergo_workers, 624 /* do_check = */ false); 625 uint nworkers = _workers->active_workers(); 626 cm->task_queues()->reserve(nworkers); 627 TaskTerminator terminator(nworkers, cm->task_queues()); 628 ShenandoahRefProcTaskProxy proc_task_proxy(task, &terminator); 629 _workers->run_task(&proc_task_proxy); 630 } 631 }; 632 633 void ShenandoahConcurrentMark::weak_refs_work(bool full_gc) { 634 assert(_heap->process_references(), "sanity"); 635 636 ShenandoahPhaseTimings::Phase phase_root = 637 full_gc ? 638 ShenandoahPhaseTimings::full_gc_weakrefs : 639 ShenandoahPhaseTimings::weakrefs; 640 641 ShenandoahGCPhase phase(phase_root); 642 643 ReferenceProcessor* rp = _heap->ref_processor(); 644 645 // NOTE: We cannot shortcut on has_discovered_references() here, because 646 // we will miss marking JNI Weak refs then, see implementation in 647 // ReferenceProcessor::process_discovered_references. 648 weak_refs_work_doit(full_gc); 649 650 rp->verify_no_references_recorded(); 651 assert(!rp->discovery_enabled(), "Post condition"); 652 653 } 654 655 void ShenandoahConcurrentMark::weak_refs_work_doit(bool full_gc) { 656 ReferenceProcessor* rp = _heap->ref_processor(); 657 658 ShenandoahPhaseTimings::Phase phase_process = 659 full_gc ? 660 ShenandoahPhaseTimings::full_gc_weakrefs_process : 661 ShenandoahPhaseTimings::weakrefs_process; 662 663 shenandoah_assert_rp_isalive_not_installed(); 664 ShenandoahIsAliveSelector is_alive; 665 ReferenceProcessorIsAliveMutator fix_isalive(rp, is_alive.is_alive_closure()); 666 667 WorkGang* workers = _heap->workers(); 668 uint nworkers = workers->active_workers(); 669 670 rp->setup_policy(_heap->soft_ref_policy()->should_clear_all_soft_refs()); 671 rp->set_active_mt_degree(nworkers); 672 673 assert(task_queues()->is_empty(), "Should be empty"); 674 675 // complete_gc and keep_alive closures instantiated here are only needed for 676 // single-threaded path in RP. They share the queue 0 for tracking work, which 677 // simplifies implementation. Since RP may decide to call complete_gc several 678 // times, we need to be able to reuse the terminator. 679 uint serial_worker_id = 0; 680 TaskTerminator terminator(1, task_queues()); 681 ShenandoahCMDrainMarkingStackClosure complete_gc(serial_worker_id, &terminator, /* reset_terminator = */ true); 682 683 ShenandoahRefProcTaskExecutor executor(workers); 684 685 ReferenceProcessorPhaseTimes pt(_heap->gc_timer(), rp->num_queues()); 686 687 { 688 // Note: Don't emit JFR event for this phase, to avoid overflow nesting phase level. 689 // Reference Processor emits 2 levels JFR event, that can get us over the JFR 690 // event nesting level limits, in case of degenerated GC gets upgraded to 691 // full GC. 692 ShenandoahTimingsTracker phase_timing(phase_process); 693 694 if (_heap->has_forwarded_objects()) { 695 ShenandoahCMKeepAliveUpdateClosure keep_alive(get_queue(serial_worker_id)); 696 const ReferenceProcessorStats& stats = 697 rp->process_discovered_references(is_alive.is_alive_closure(), &keep_alive, 698 &complete_gc, &executor, 699 &pt); 700 _heap->tracer()->report_gc_reference_stats(stats); 701 } else { 702 ShenandoahCMKeepAliveClosure keep_alive(get_queue(serial_worker_id)); 703 const ReferenceProcessorStats& stats = 704 rp->process_discovered_references(is_alive.is_alive_closure(), &keep_alive, 705 &complete_gc, &executor, 706 &pt); 707 _heap->tracer()->report_gc_reference_stats(stats); 708 } 709 710 pt.print_all_references(); 711 712 assert(task_queues()->is_empty(), "Should be empty"); 713 } 714 } 715 716 class ShenandoahCancelledGCYieldClosure : public YieldClosure { 717 private: 718 ShenandoahHeap* const _heap; 719 public: 720 ShenandoahCancelledGCYieldClosure() : _heap(ShenandoahHeap::heap()) {}; 721 virtual bool should_return() { return _heap->cancelled_gc(); } 722 }; 723 724 class ShenandoahPrecleanCompleteGCClosure : public VoidClosure { 725 public: 726 void do_void() { 727 ShenandoahHeap* sh = ShenandoahHeap::heap(); 728 ShenandoahConcurrentMark* scm = sh->concurrent_mark(); 729 assert(sh->process_references(), "why else would we be here?"); 730 TaskTerminator terminator(1, scm->task_queues()); 731 732 ReferenceProcessor* rp = sh->ref_processor(); 733 shenandoah_assert_rp_isalive_installed(); 734 735 scm->mark_loop(0, &terminator, rp, 736 false, // not cancellable 737 false); // do not do strdedup 738 } 739 }; 740 741 class ShenandoahPrecleanTask : public AbstractGangTask { 742 private: 743 ReferenceProcessor* _rp; 744 745 public: 746 ShenandoahPrecleanTask(ReferenceProcessor* rp) : 747 AbstractGangTask("Precleaning task"), 748 _rp(rp) {} 749 750 void work(uint worker_id) { 751 assert(worker_id == 0, "The code below is single-threaded, only one worker is expected"); 752 ShenandoahParallelWorkerSession worker_session(worker_id); 753 754 ShenandoahHeap* sh = ShenandoahHeap::heap(); 755 assert(!sh->has_forwarded_objects(), "No forwarded objects expected here"); 756 757 ShenandoahObjToScanQueue* q = sh->concurrent_mark()->get_queue(worker_id); 758 759 ShenandoahCancelledGCYieldClosure yield; 760 ShenandoahPrecleanCompleteGCClosure complete_gc; 761 762 ShenandoahIsAliveClosure is_alive; 763 ShenandoahCMKeepAliveClosure keep_alive(q); 764 ResourceMark rm; 765 _rp->preclean_discovered_references(&is_alive, &keep_alive, 766 &complete_gc, &yield, 767 NULL); 768 } 769 }; 770 771 void ShenandoahConcurrentMark::preclean_weak_refs() { 772 // Pre-cleaning weak references before diving into STW makes sense at the 773 // end of concurrent mark. This will filter out the references which referents 774 // are alive. Note that ReferenceProcessor already filters out these on reference 775 // discovery, and the bulk of work is done here. This phase processes leftovers 776 // that missed the initial filtering, i.e. when referent was marked alive after 777 // reference was discovered by RP. 778 779 assert(_heap->process_references(), "sanity"); 780 781 // Shortcut if no references were discovered to avoid winding up threads. 782 ReferenceProcessor* rp = _heap->ref_processor(); 783 if (!rp->has_discovered_references()) { 784 return; 785 } 786 787 assert(task_queues()->is_empty(), "Should be empty"); 788 789 ReferenceProcessorMTDiscoveryMutator fix_mt_discovery(rp, false); 790 791 shenandoah_assert_rp_isalive_not_installed(); 792 ShenandoahIsAliveSelector is_alive; 793 ReferenceProcessorIsAliveMutator fix_isalive(rp, is_alive.is_alive_closure()); 794 795 // Execute precleaning in the worker thread: it will give us GCLABs, String dedup 796 // queues and other goodies. When upstream ReferenceProcessor starts supporting 797 // parallel precleans, we can extend this to more threads. 798 WorkGang* workers = _heap->workers(); 799 uint nworkers = workers->active_workers(); 800 assert(nworkers == 1, "This code uses only a single worker"); 801 task_queues()->reserve(nworkers); 802 803 ShenandoahPrecleanTask task(rp); 804 workers->run_task(&task); 805 806 assert(task_queues()->is_empty(), "Should be empty"); 807 } 808 809 void ShenandoahConcurrentMark::cancel() { 810 // Clean up marking stacks. 811 ShenandoahObjToScanQueueSet* queues = task_queues(); 812 queues->clear(); 813 814 // Cancel SATB buffers. 815 ShenandoahBarrierSet::satb_mark_queue_set().abandon_partial_marking(); 816 } 817 818 ShenandoahObjToScanQueue* ShenandoahConcurrentMark::get_queue(uint worker_id) { 819 assert(task_queues()->get_reserved() > worker_id, "No reserved queue for worker id: %d", worker_id); 820 return _task_queues->queue(worker_id); 821 } 822 823 template <bool CANCELLABLE> 824 void ShenandoahConcurrentMark::mark_loop_prework(uint w, TaskTerminator *t, ReferenceProcessor *rp, 825 bool strdedup) { 826 ShenandoahObjToScanQueue* q = get_queue(w); 827 828 ShenandoahLiveData* ld = _heap->get_liveness_cache(w); 829 830 // TODO: We can clean up this if we figure out how to do templated oop closures that 831 // play nice with specialized_oop_iterators. 832 if (_heap->unload_classes()) { 833 if (_heap->has_forwarded_objects()) { 834 if (strdedup) { 835 ShenandoahMarkUpdateRefsMetadataDedupClosure cl(q, rp); 836 mark_loop_work<ShenandoahMarkUpdateRefsMetadataDedupClosure, CANCELLABLE>(&cl, ld, w, t); 837 } else { 838 ShenandoahMarkUpdateRefsMetadataClosure cl(q, rp); 839 mark_loop_work<ShenandoahMarkUpdateRefsMetadataClosure, CANCELLABLE>(&cl, ld, w, t); 840 } 841 } else { 842 if (strdedup) { 843 ShenandoahMarkRefsMetadataDedupClosure cl(q, rp); 844 mark_loop_work<ShenandoahMarkRefsMetadataDedupClosure, CANCELLABLE>(&cl, ld, w, t); 845 } else { 846 ShenandoahMarkRefsMetadataClosure cl(q, rp); 847 mark_loop_work<ShenandoahMarkRefsMetadataClosure, CANCELLABLE>(&cl, ld, w, t); 848 } 849 } 850 } else { 851 if (_heap->has_forwarded_objects()) { 852 if (strdedup) { 853 ShenandoahMarkUpdateRefsDedupClosure cl(q, rp); 854 mark_loop_work<ShenandoahMarkUpdateRefsDedupClosure, CANCELLABLE>(&cl, ld, w, t); 855 } else { 856 ShenandoahMarkUpdateRefsClosure cl(q, rp); 857 mark_loop_work<ShenandoahMarkUpdateRefsClosure, CANCELLABLE>(&cl, ld, w, t); 858 } 859 } else { 860 if (strdedup) { 861 ShenandoahMarkRefsDedupClosure cl(q, rp); 862 mark_loop_work<ShenandoahMarkRefsDedupClosure, CANCELLABLE>(&cl, ld, w, t); 863 } else { 864 ShenandoahMarkRefsClosure cl(q, rp); 865 mark_loop_work<ShenandoahMarkRefsClosure, CANCELLABLE>(&cl, ld, w, t); 866 } 867 } 868 } 869 870 _heap->flush_liveness_cache(w); 871 } 872 873 template <class T, bool CANCELLABLE> 874 void ShenandoahConcurrentMark::mark_loop_work(T* cl, ShenandoahLiveData* live_data, uint worker_id, TaskTerminator *terminator) { 875 uintx stride = ShenandoahMarkLoopStride; 876 877 ShenandoahHeap* heap = ShenandoahHeap::heap(); 878 ShenandoahObjToScanQueueSet* queues = task_queues(); 879 ShenandoahObjToScanQueue* q; 880 ShenandoahMarkTask t; 881 882 /* 883 * Process outstanding queues, if any. 884 * 885 * There can be more queues than workers. To deal with the imbalance, we claim 886 * extra queues first. Since marking can push new tasks into the queue associated 887 * with this worker id, we come back to process this queue in the normal loop. 888 */ 889 assert(queues->get_reserved() == heap->workers()->active_workers(), 890 "Need to reserve proper number of queues: reserved: %u, active: %u", queues->get_reserved(), heap->workers()->active_workers()); 891 892 q = queues->claim_next(); 893 while (q != NULL) { 894 if (CANCELLABLE && heap->check_cancelled_gc_and_yield()) { 895 return; 896 } 897 898 for (uint i = 0; i < stride; i++) { 899 if (q->pop(t)) { 900 do_task<T>(q, cl, live_data, &t); 901 } else { 902 assert(q->is_empty(), "Must be empty"); 903 q = queues->claim_next(); 904 break; 905 } 906 } 907 } 908 q = get_queue(worker_id); 909 910 ShenandoahSATBBufferClosure drain_satb(q); 911 SATBMarkQueueSet& satb_mq_set = ShenandoahBarrierSet::satb_mark_queue_set(); 912 913 /* 914 * Normal marking loop: 915 */ 916 while (true) { 917 if (CANCELLABLE && heap->check_cancelled_gc_and_yield()) { 918 return; 919 } 920 921 while (satb_mq_set.completed_buffers_num() > 0) { 922 satb_mq_set.apply_closure_to_completed_buffer(&drain_satb); 923 } 924 925 uint work = 0; 926 for (uint i = 0; i < stride; i++) { 927 if (q->pop(t) || 928 queues->steal(worker_id, t)) { 929 do_task<T>(q, cl, live_data, &t); 930 work++; 931 } else { 932 break; 933 } 934 } 935 936 if (work == 0) { 937 // No work encountered in current stride, try to terminate. 938 // Need to leave the STS here otherwise it might block safepoints. 939 ShenandoahSuspendibleThreadSetLeaver stsl(CANCELLABLE && ShenandoahSuspendibleWorkers); 940 ShenandoahTerminatorTerminator tt(heap); 941 if (terminator->offer_termination(&tt)) return; 942 } 943 } 944 } 945 946 bool ShenandoahConcurrentMark::claim_codecache() { 947 return _claimed_codecache.try_set(); 948 } 949 950 void ShenandoahConcurrentMark::clear_claim_codecache() { 951 _claimed_codecache.unset(); 952 }