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