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