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