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   OopClosure*            const _cl;
 187   MarkingCodeBlobClosure*      _code_cl;
 188   uintx _claim_token;
 189 
 190 public:
 191   ShenandoahSATBAndRemarkCodeRootsThreadsClosure(ShenandoahSATBBufferClosure* satb_cl, OopClosure* cl, MarkingCodeBlobClosure* code_cl) :
 192     _satb_cl(satb_cl), _cl(cl), _code_cl(code_cl),
 193     _claim_token(Threads::thread_claim_token()) {}
 194 
 195   void do_thread(Thread* thread) {
 196     if (thread->claim_threads_do(true, _claim_token)) {
 197       ShenandoahThreadLocalData::satb_mark_queue(thread).apply_closure_and_empty(_satb_cl);
 198       if (thread->is_Java_thread()) {
 199         if (_cl != NULL) {
 200           ResourceMark rm;
 201           thread->oops_do(_cl, _code_cl);
 202         } else  if (_code_cl != NULL) {
 203           // In theory it should not be neccessary to explicitly walk the nmethods to find roots for concurrent marking
 204           // however the liveness of oops reachable from nmethods have very complex lifecycles:
 205           // * Alive if on the stack of an executing method
 206           // * Weakly reachable otherwise
 207           // Some objects reachable from nmethods, such as the class loader (or klass_holder) of the receiver should be
 208           // live by the SATB invariant but other oops recorded in nmethods may behave differently.
 209           JavaThread* jt = (JavaThread*)thread;
 210           jt->nmethods_do(_code_cl);
 211         }
 212       }
 213     }
 214   }
 215 };
 216 
 217 class ShenandoahFinalMarkingTask : public AbstractGangTask {
 218 private:
 219   ShenandoahConcurrentMark* _cm;
 220   TaskTerminator*           _terminator;
 221   bool _dedup_string;
 222 
 223 public:
 224   ShenandoahFinalMarkingTask(ShenandoahConcurrentMark* cm, TaskTerminator* terminator, bool dedup_string) :
 225     AbstractGangTask("Shenandoah Final Marking"), _cm(cm), _terminator(terminator), _dedup_string(dedup_string) {
 226   }
 227 
 228   void work(uint worker_id) {
 229     ShenandoahHeap* heap = ShenandoahHeap::heap();
 230 
 231     ShenandoahParallelWorkerSession worker_session(worker_id);
 232     ReferenceProcessor* rp;
 233     if (heap->process_references()) {
 234       rp = heap->ref_processor();
 235       shenandoah_assert_rp_isalive_installed();
 236     } else {
 237       rp = NULL;
 238     }
 239 
 240     // First drain remaining SATB buffers.
 241     // Notice that this is not strictly necessary for mark-compact. But since
 242     // it requires a StrongRootsScope around the task, we need to claim the
 243     // threads, and performance-wise it doesn't really matter. Adds about 1ms to
 244     // full-gc.
 245     {
 246       ShenandoahObjToScanQueue* q = _cm->get_queue(worker_id);
 247 
 248       ShenandoahSATBBufferClosure cl(q);
 249       SATBMarkQueueSet& satb_mq_set = ShenandoahBarrierSet::satb_mark_queue_set();
 250       while (satb_mq_set.apply_closure_to_completed_buffer(&cl));
 251       bool do_nmethods = heap->unload_classes() && !ShenandoahConcurrentRoots::can_do_concurrent_class_unloading();
 252       if (heap->has_forwarded_objects()) {
 253         ShenandoahMarkResolveRefsClosure resolve_mark_cl(q, rp);
 254         MarkingCodeBlobClosure blobsCl(&resolve_mark_cl, !CodeBlobToOopClosure::FixRelocations);
 255         ShenandoahSATBAndRemarkCodeRootsThreadsClosure tc(&cl,
 256                                                           ShenandoahStoreValEnqueueBarrier ? &resolve_mark_cl : NULL,
 257                                                           do_nmethods ? &blobsCl : NULL);
 258         Threads::threads_do(&tc);
 259       } else {
 260         ShenandoahMarkRefsClosure mark_cl(q, rp);
 261         MarkingCodeBlobClosure blobsCl(&mark_cl, !CodeBlobToOopClosure::FixRelocations);
 262         ShenandoahSATBAndRemarkCodeRootsThreadsClosure tc(&cl,
 263                                                           ShenandoahStoreValEnqueueBarrier ? &mark_cl : NULL,
 264                                                           &blobsCl);
 265         Threads::threads_do(&tc);
 266       }
 267     }
 268 
 269     if (heap->is_degenerated_gc_in_progress()) {
 270       // Degenerated cycle may bypass concurrent cycle, so code roots might not be scanned,
 271       // let's check here.
 272       _cm->concurrent_scan_code_roots(worker_id, rp);
 273     }
 274 
 275     _cm->mark_loop(worker_id, _terminator, rp,
 276                    false, // not cancellable
 277                    _dedup_string);
 278 
 279     assert(_cm->task_queues()->is_empty(), "Should be empty");
 280   }
 281 };
 282 
 283 void ShenandoahConcurrentMark::mark_roots(ShenandoahPhaseTimings::Phase root_phase) {
 284   assert(Thread::current()->is_VM_thread(), "can only do this in VMThread");
 285   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at a safepoint");
 286 
 287   ShenandoahHeap* heap = ShenandoahHeap::heap();
 288 
 289   ShenandoahGCPhase phase(root_phase);
 290 
 291   WorkGang* workers = heap->workers();
 292   uint nworkers = workers->active_workers();
 293 
 294   assert(nworkers <= task_queues()->size(), "Just check");
 295 
 296   ShenandoahAllRootScanner root_proc(nworkers, root_phase);
 297   TASKQUEUE_STATS_ONLY(task_queues()->reset_taskqueue_stats());
 298   task_queues()->reserve(nworkers);
 299 
 300   if (heap->has_forwarded_objects()) {
 301     ShenandoahInitMarkRootsTask<RESOLVE> mark_roots(&root_proc);
 302     workers->run_task(&mark_roots);
 303   } else {
 304     // No need to update references, which means the heap is stable.
 305     // Can save time not walking through forwarding pointers.
 306     ShenandoahInitMarkRootsTask<NONE> mark_roots(&root_proc);
 307     workers->run_task(&mark_roots);
 308   }
 309 
 310   if (ShenandoahConcurrentScanCodeRoots) {
 311     clear_claim_codecache();
 312   }
 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_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(is_par),
 349     _phase(phase),
 350     _worker_phase(phase) {}
 351 
 352   void work(uint worker_id) {
 353     ShenandoahUpdateRefsClosure cl;
 354     _thread_roots.oops_do(&cl, NULL, worker_id);
 355   }
 356 };
 357 
 358 void ShenandoahConcurrentMark::update_thread_roots(ShenandoahPhaseTimings::Phase root_phase) {
 359   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at a safepoint");
 360 
 361   ShenandoahGCPhase phase(root_phase);
 362 
 363 #if COMPILER2_OR_JVMCI
 364   DerivedPointerTable::clear();
 365 #endif
 366 
 367   WorkGang* workers = _heap->workers();
 368   bool is_par = workers->active_workers() > 1;
 369 
 370   ShenandoahUpdateThreadRootsTask task(is_par, root_phase);
 371   workers->run_task(&task);
 372 
 373 #if COMPILER2_OR_JVMCI
 374   DerivedPointerTable::update_pointers();
 375 #endif
 376 }
 377 
 378 void ShenandoahConcurrentMark::initialize(uint workers) {
 379   _heap = ShenandoahHeap::heap();
 380 
 381   uint num_queues = MAX2(workers, 1U);
 382 
 383   _task_queues = new ShenandoahObjToScanQueueSet((int) num_queues);
 384 
 385   for (uint i = 0; i < num_queues; ++i) {
 386     ShenandoahObjToScanQueue* task_queue = new ShenandoahObjToScanQueue();
 387     task_queue->initialize();
 388     _task_queues->register_queue(i, task_queue);
 389   }
 390 }
 391 
 392 void ShenandoahConcurrentMark::concurrent_scan_code_roots(uint worker_id, ReferenceProcessor* rp) {
 393   if (ShenandoahConcurrentScanCodeRoots && claim_codecache()) {
 394     ShenandoahObjToScanQueue* q = task_queues()->queue(worker_id);
 395     if (!_heap->unload_classes()) {
 396       MutexLocker mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 397       // TODO: We can not honor StringDeduplication here, due to lock ranking
 398       // inversion. So, we may miss some deduplication candidates.
 399       if (_heap->has_forwarded_objects()) {
 400         ShenandoahMarkResolveRefsClosure cl(q, rp);
 401         CodeBlobToOopClosure blobs(&cl, !CodeBlobToOopClosure::FixRelocations);
 402         CodeCache::blobs_do(&blobs);
 403       } else {
 404         ShenandoahMarkRefsClosure cl(q, rp);
 405         CodeBlobToOopClosure blobs(&cl, !CodeBlobToOopClosure::FixRelocations);
 406         CodeCache::blobs_do(&blobs);
 407       }
 408     }
 409   }
 410 }
 411 
 412 void ShenandoahConcurrentMark::mark_from_roots() {
 413   WorkGang* workers = _heap->workers();
 414   uint nworkers = workers->active_workers();
 415 
 416   ShenandoahGCPhase conc_mark_phase(ShenandoahPhaseTimings::conc_mark);
 417 
 418   if (_heap->process_references()) {
 419     ReferenceProcessor* rp = _heap->ref_processor();
 420     rp->set_active_mt_degree(nworkers);
 421 
 422     // enable ("weak") refs discovery
 423     rp->enable_discovery(true /*verify_no_refs*/);
 424     rp->setup_policy(_heap->soft_ref_policy()->should_clear_all_soft_refs());
 425   }
 426 
 427   shenandoah_assert_rp_isalive_not_installed();
 428   ShenandoahIsAliveSelector is_alive;
 429   ReferenceProcessorIsAliveMutator fix_isalive(_heap->ref_processor(), is_alive.is_alive_closure());
 430 
 431   task_queues()->reserve(nworkers);
 432 
 433   {
 434     TaskTerminator terminator(nworkers, task_queues());
 435     ShenandoahConcurrentMarkingTask task(this, &terminator);
 436     workers->run_task(&task);
 437   }
 438 
 439   assert(task_queues()->is_empty() || _heap->cancelled_gc(), "Should be empty when not cancelled");
 440 }
 441 
 442 void ShenandoahConcurrentMark::finish_mark_from_roots(bool full_gc) {
 443   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at a safepoint");
 444 
 445   uint nworkers = _heap->workers()->active_workers();
 446 
 447   // Finally mark everything else we've got in our queues during the previous steps.
 448   // It does two different things for concurrent vs. mark-compact GC:
 449   // - For concurrent GC, it starts with empty task queues, drains the remaining
 450   //   SATB buffers, and then completes the marking closure.
 451   // - For mark-compact GC, it starts out with the task queues seeded by initial
 452   //   root scan, and completes the closure, thus marking through all live objects
 453   // The implementation is the same, so it's shared here.
 454   {
 455     ShenandoahGCPhase phase(full_gc ?
 456                             ShenandoahPhaseTimings::full_gc_mark_finish_queues :
 457                             ShenandoahPhaseTimings::finish_queues);
 458     task_queues()->reserve(nworkers);
 459 
 460     shenandoah_assert_rp_isalive_not_installed();
 461     ShenandoahIsAliveSelector is_alive;
 462     ReferenceProcessorIsAliveMutator fix_isalive(_heap->ref_processor(), is_alive.is_alive_closure());
 463 
 464     StrongRootsScope scope(nworkers);
 465     TaskTerminator terminator(nworkers, task_queues());
 466     ShenandoahFinalMarkingTask task(this, &terminator, ShenandoahStringDedup::is_enabled());
 467     _heap->workers()->run_task(&task);
 468   }
 469 
 470   assert(task_queues()->is_empty(), "Should be empty");
 471 
 472   // When we're done marking everything, we process weak references.
 473   if (_heap->process_references()) {
 474     weak_refs_work(full_gc);
 475   }
 476 
 477   assert(task_queues()->is_empty(), "Should be empty");
 478   TASKQUEUE_STATS_ONLY(task_queues()->print_taskqueue_stats());
 479   TASKQUEUE_STATS_ONLY(task_queues()->reset_taskqueue_stats());
 480 }
 481 
 482 // Weak Reference Closures
 483 class ShenandoahCMDrainMarkingStackClosure: public VoidClosure {
 484   uint _worker_id;
 485   TaskTerminator* _terminator;
 486   bool _reset_terminator;
 487 
 488 public:
 489   ShenandoahCMDrainMarkingStackClosure(uint worker_id, TaskTerminator* 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   TaskTerminator* _terminator;
 578 
 579 public:
 580   ShenandoahRefProcTaskProxy(AbstractRefProcTaskExecutor::ProcessTask& proc_task,
 581                              TaskTerminator* 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     TaskTerminator 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   TaskTerminator 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       rp->process_discovered_references(is_alive.is_alive_closure(), &keep_alive,
 691                                         &complete_gc, &executor,
 692                                         &pt);
 693 
 694     } else {
 695       ShenandoahCMKeepAliveClosure keep_alive(get_queue(serial_worker_id));
 696       rp->process_discovered_references(is_alive.is_alive_closure(), &keep_alive,
 697                                         &complete_gc, &executor,
 698                                         &pt);
 699 
 700     }
 701 
 702     pt.print_all_references();
 703 
 704     assert(task_queues()->is_empty(), "Should be empty");
 705   }
 706 }
 707 
 708 class ShenandoahCancelledGCYieldClosure : public YieldClosure {
 709 private:
 710   ShenandoahHeap* const _heap;
 711 public:
 712   ShenandoahCancelledGCYieldClosure() : _heap(ShenandoahHeap::heap()) {};
 713   virtual bool should_return() { return _heap->cancelled_gc(); }
 714 };
 715 
 716 class ShenandoahPrecleanCompleteGCClosure : public VoidClosure {
 717 public:
 718   void do_void() {
 719     ShenandoahHeap* sh = ShenandoahHeap::heap();
 720     ShenandoahConcurrentMark* scm = sh->concurrent_mark();
 721     assert(sh->process_references(), "why else would we be here?");
 722     TaskTerminator terminator(1, scm->task_queues());
 723 
 724     ReferenceProcessor* rp = sh->ref_processor();
 725     shenandoah_assert_rp_isalive_installed();
 726 
 727     scm->mark_loop(0, &terminator, rp,
 728                    false, // not cancellable
 729                    false); // do not do strdedup
 730   }
 731 };
 732 
 733 class ShenandoahPrecleanTask : public AbstractGangTask {
 734 private:
 735   ReferenceProcessor* _rp;
 736 
 737 public:
 738   ShenandoahPrecleanTask(ReferenceProcessor* rp) :
 739           AbstractGangTask("Precleaning task"),
 740           _rp(rp) {}
 741 
 742   void work(uint worker_id) {
 743     assert(worker_id == 0, "The code below is single-threaded, only one worker is expected");
 744     ShenandoahParallelWorkerSession worker_session(worker_id);
 745 
 746     ShenandoahHeap* sh = ShenandoahHeap::heap();
 747     assert(!sh->has_forwarded_objects(), "No forwarded objects expected here");
 748 
 749     ShenandoahObjToScanQueue* q = sh->concurrent_mark()->get_queue(worker_id);
 750 
 751     ShenandoahCancelledGCYieldClosure yield;
 752     ShenandoahPrecleanCompleteGCClosure complete_gc;
 753 
 754     ShenandoahIsAliveClosure is_alive;
 755     ShenandoahCMKeepAliveClosure keep_alive(q);
 756     ResourceMark rm;
 757     _rp->preclean_discovered_references(&is_alive, &keep_alive,
 758                                         &complete_gc, &yield,
 759                                         NULL);
 760   }
 761 };
 762 
 763 void ShenandoahConcurrentMark::preclean_weak_refs() {
 764   // Pre-cleaning weak references before diving into STW makes sense at the
 765   // end of concurrent mark. This will filter out the references which referents
 766   // are alive. Note that ReferenceProcessor already filters out these on reference
 767   // discovery, and the bulk of work is done here. This phase processes leftovers
 768   // that missed the initial filtering, i.e. when referent was marked alive after
 769   // reference was discovered by RP.
 770 
 771   assert(_heap->process_references(), "sanity");
 772 
 773   // Shortcut if no references were discovered to avoid winding up threads.
 774   ReferenceProcessor* rp = _heap->ref_processor();
 775   if (!rp->has_discovered_references()) {
 776     return;
 777   }
 778 
 779   assert(task_queues()->is_empty(), "Should be empty");
 780 
 781   ReferenceProcessorMTDiscoveryMutator fix_mt_discovery(rp, false);
 782 
 783   shenandoah_assert_rp_isalive_not_installed();
 784   ShenandoahIsAliveSelector is_alive;
 785   ReferenceProcessorIsAliveMutator fix_isalive(rp, is_alive.is_alive_closure());
 786 
 787   // Execute precleaning in the worker thread: it will give us GCLABs, String dedup
 788   // queues and other goodies. When upstream ReferenceProcessor starts supporting
 789   // parallel precleans, we can extend this to more threads.
 790   WorkGang* workers = _heap->workers();
 791   uint nworkers = workers->active_workers();
 792   assert(nworkers == 1, "This code uses only a single worker");
 793   task_queues()->reserve(nworkers);
 794 
 795   ShenandoahPrecleanTask task(rp);
 796   workers->run_task(&task);
 797 
 798   assert(task_queues()->is_empty(), "Should be empty");
 799 }
 800 
 801 void ShenandoahConcurrentMark::cancel() {
 802   // Clean up marking stacks.
 803   ShenandoahObjToScanQueueSet* queues = task_queues();
 804   queues->clear();
 805 
 806   // Cancel SATB buffers.
 807   ShenandoahBarrierSet::satb_mark_queue_set().abandon_partial_marking();
 808 }
 809 
 810 ShenandoahObjToScanQueue* ShenandoahConcurrentMark::get_queue(uint worker_id) {
 811   assert(task_queues()->get_reserved() > worker_id, "No reserved queue for worker id: %d", worker_id);
 812   return _task_queues->queue(worker_id);
 813 }
 814 
 815 template <bool CANCELLABLE>
 816 void ShenandoahConcurrentMark::mark_loop_prework(uint w, TaskTerminator *t, ReferenceProcessor *rp,
 817                                                  bool strdedup) {
 818   ShenandoahObjToScanQueue* q = get_queue(w);
 819 
 820   jushort* ld = _heap->get_liveness_cache(w);
 821 
 822   // TODO: We can clean up this if we figure out how to do templated oop closures that
 823   // play nice with specialized_oop_iterators.
 824   if (_heap->unload_classes()) {
 825     if (_heap->has_forwarded_objects()) {
 826       if (strdedup) {
 827         ShenandoahMarkUpdateRefsMetadataDedupClosure cl(q, rp);
 828         mark_loop_work<ShenandoahMarkUpdateRefsMetadataDedupClosure, CANCELLABLE>(&cl, ld, w, t);
 829       } else {
 830         ShenandoahMarkUpdateRefsMetadataClosure cl(q, rp);
 831         mark_loop_work<ShenandoahMarkUpdateRefsMetadataClosure, CANCELLABLE>(&cl, ld, w, t);
 832       }
 833     } else {
 834       if (strdedup) {
 835         ShenandoahMarkRefsMetadataDedupClosure cl(q, rp);
 836         mark_loop_work<ShenandoahMarkRefsMetadataDedupClosure, CANCELLABLE>(&cl, ld, w, t);
 837       } else {
 838         ShenandoahMarkRefsMetadataClosure cl(q, rp);
 839         mark_loop_work<ShenandoahMarkRefsMetadataClosure, CANCELLABLE>(&cl, ld, w, t);
 840       }
 841     }
 842   } else {
 843     if (_heap->has_forwarded_objects()) {
 844       if (strdedup) {
 845         ShenandoahMarkUpdateRefsDedupClosure cl(q, rp);
 846         mark_loop_work<ShenandoahMarkUpdateRefsDedupClosure, CANCELLABLE>(&cl, ld, w, t);
 847       } else {
 848         ShenandoahMarkUpdateRefsClosure cl(q, rp);
 849         mark_loop_work<ShenandoahMarkUpdateRefsClosure, CANCELLABLE>(&cl, ld, w, t);
 850       }
 851     } else {
 852       if (strdedup) {
 853         ShenandoahMarkRefsDedupClosure cl(q, rp);
 854         mark_loop_work<ShenandoahMarkRefsDedupClosure, CANCELLABLE>(&cl, ld, w, t);
 855       } else {
 856         ShenandoahMarkRefsClosure cl(q, rp);
 857         mark_loop_work<ShenandoahMarkRefsClosure, CANCELLABLE>(&cl, ld, w, t);
 858       }
 859     }
 860   }
 861 
 862   _heap->flush_liveness_cache(w);
 863 }
 864 
 865 template <class T, bool CANCELLABLE>
 866 void ShenandoahConcurrentMark::mark_loop_work(T* cl, jushort* live_data, uint worker_id, TaskTerminator *terminator) {
 867   uintx stride = ShenandoahMarkLoopStride;
 868 
 869   ShenandoahHeap* heap = ShenandoahHeap::heap();
 870   ShenandoahObjToScanQueueSet* queues = task_queues();
 871   ShenandoahObjToScanQueue* q;
 872   ShenandoahMarkTask t;
 873 
 874   /*
 875    * Process outstanding queues, if any.
 876    *
 877    * There can be more queues than workers. To deal with the imbalance, we claim
 878    * extra queues first. Since marking can push new tasks into the queue associated
 879    * with this worker id, we come back to process this queue in the normal loop.
 880    */
 881   assert(queues->get_reserved() == heap->workers()->active_workers(),
 882          "Need to reserve proper number of queues: reserved: %u, active: %u", queues->get_reserved(), heap->workers()->active_workers());
 883 
 884   q = queues->claim_next();
 885   while (q != NULL) {
 886     if (CANCELLABLE && heap->check_cancelled_gc_and_yield()) {
 887       return;
 888     }
 889 
 890     for (uint i = 0; i < stride; i++) {
 891       if (q->pop(t)) {
 892         do_task<T>(q, cl, live_data, &t);
 893       } else {
 894         assert(q->is_empty(), "Must be empty");
 895         q = queues->claim_next();
 896         break;
 897       }
 898     }
 899   }
 900   q = get_queue(worker_id);
 901 
 902   ShenandoahSATBBufferClosure drain_satb(q);
 903   SATBMarkQueueSet& satb_mq_set = ShenandoahBarrierSet::satb_mark_queue_set();
 904 
 905   /*
 906    * Normal marking loop:
 907    */
 908   while (true) {
 909     if (CANCELLABLE && heap->check_cancelled_gc_and_yield()) {
 910       return;
 911     }
 912 
 913     while (satb_mq_set.completed_buffers_num() > 0) {
 914       satb_mq_set.apply_closure_to_completed_buffer(&drain_satb);
 915     }
 916 
 917     uint work = 0;
 918     for (uint i = 0; i < stride; i++) {
 919       if (q->pop(t) ||
 920           queues->steal(worker_id, t)) {
 921         do_task<T>(q, cl, live_data, &t);
 922         work++;
 923       } else {
 924         break;
 925       }
 926     }
 927 
 928     if (work == 0) {
 929       // No work encountered in current stride, try to terminate.
 930       // Need to leave the STS here otherwise it might block safepoints.
 931       ShenandoahSuspendibleThreadSetLeaver stsl(CANCELLABLE && ShenandoahSuspendibleWorkers);
 932       ShenandoahTerminatorTerminator tt(heap);
 933       if (terminator->offer_termination(&tt)) return;
 934     }
 935   }
 936 }
 937 
 938 bool ShenandoahConcurrentMark::claim_codecache() {
 939   assert(ShenandoahConcurrentScanCodeRoots, "must not be called otherwise");
 940   return _claimed_codecache.try_set();
 941 }
 942 
 943 void ShenandoahConcurrentMark::clear_claim_codecache() {
 944   assert(ShenandoahConcurrentScanCodeRoots, "must not be called otherwise");
 945   _claimed_codecache.unset();
 946 }