1 /*
   2  * Copyright (c) 2014, 2021, 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 "compiler/oopMap.hpp"
  28 #include "gc/shared/continuationGCSupport.hpp"
  29 #include "gc/shared/gcTraceTime.inline.hpp"
  30 #include "gc/shared/preservedMarks.inline.hpp"
  31 #include "gc/shared/slidingForwarding.inline.hpp"
  32 #include "gc/shared/tlab_globals.hpp"
  33 #include "gc/shared/workerThread.hpp"
  34 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
  35 #include "gc/shenandoah/shenandoahConcurrentGC.hpp"
  36 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  37 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  38 #include "gc/shenandoah/shenandoahFullGC.hpp"
  39 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  40 #include "gc/shenandoah/shenandoahMark.inline.hpp"
  41 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
  42 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  43 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  44 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
  45 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  46 #include "gc/shenandoah/shenandoahMetrics.hpp"
  47 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
  48 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
  49 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
  50 #include "gc/shenandoah/shenandoahSTWMark.hpp"
  51 #include "gc/shenandoah/shenandoahUtils.hpp"
  52 #include "gc/shenandoah/shenandoahVerifier.hpp"
  53 #include "gc/shenandoah/shenandoahVMOperations.hpp"
  54 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
  55 #include "memory/metaspaceUtils.hpp"
  56 #include "memory/universe.hpp"
  57 #include "oops/compressedOops.inline.hpp"
  58 #include "oops/oop.inline.hpp"
  59 #include "runtime/javaThread.hpp"
  60 #include "runtime/orderAccess.hpp"
  61 #include "runtime/vmThread.hpp"
  62 #include "utilities/copy.hpp"
  63 #include "utilities/events.hpp"
  64 #include "utilities/growableArray.hpp"
  65 
  66 ShenandoahFullGC::ShenandoahFullGC() :
  67   _gc_timer(ShenandoahHeap::heap()->gc_timer()),
  68   _preserved_marks(new PreservedMarksSet(true)) {}
  69 
  70 ShenandoahFullGC::~ShenandoahFullGC() {
  71   delete _preserved_marks;
  72 }
  73 
  74 bool ShenandoahFullGC::collect(GCCause::Cause cause) {
  75   vmop_entry_full(cause);
  76   // Always success
  77   return true;
  78 }
  79 
  80 void ShenandoahFullGC::vmop_entry_full(GCCause::Cause cause) {
  81   ShenandoahHeap* const heap = ShenandoahHeap::heap();
  82   TraceCollectorStats tcs(heap->monitoring_support()->full_stw_collection_counters());
  83   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::full_gc_gross);
  84 
  85   heap->try_inject_alloc_failure();
  86   VM_ShenandoahFullGC op(cause, this);
  87   VMThread::execute(&op);
  88 }
  89 
  90 void ShenandoahFullGC::entry_full(GCCause::Cause cause) {
  91   static const char* msg = "Pause Full";
  92   ShenandoahPausePhase gc_phase(msg, ShenandoahPhaseTimings::full_gc, true /* log_heap_usage */);
  93   EventMark em("%s", msg);
  94 
  95   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
  96                               ShenandoahWorkerPolicy::calc_workers_for_fullgc(),
  97                               "full gc");
  98 
  99   op_full(cause);
 100 }
 101 
 102 void ShenandoahFullGC::op_full(GCCause::Cause cause) {
 103   ShenandoahMetricsSnapshot metrics;
 104   metrics.snap_before();
 105 
 106   // Perform full GC
 107   do_it(cause);
 108 
 109   metrics.snap_after();
 110 
 111   if (metrics.is_good_progress()) {
 112     ShenandoahHeap::heap()->notify_gc_progress();
 113   } else {
 114     // Nothing to do. Tell the allocation path that we have failed to make
 115     // progress, and it can finally fail.
 116     ShenandoahHeap::heap()->notify_gc_no_progress();
 117   }
 118 }
 119 
 120 void ShenandoahFullGC::do_it(GCCause::Cause gc_cause) {
 121   ShenandoahHeap* heap = ShenandoahHeap::heap();
 122 
 123   if (ShenandoahVerify) {
 124     heap->verifier()->verify_before_fullgc();
 125   }
 126 
 127   if (VerifyBeforeGC) {
 128     Universe::verify();
 129   }
 130 
 131   // Degenerated GC may carry concurrent root flags when upgrading to
 132   // full GC. We need to reset it before mutators resume.
 133   heap->set_concurrent_strong_root_in_progress(false);
 134   heap->set_concurrent_weak_root_in_progress(false);
 135 
 136   heap->set_full_gc_in_progress(true);
 137 
 138   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at a safepoint");
 139   assert(Thread::current()->is_VM_thread(), "Do full GC only while world is stopped");
 140 
 141   {
 142     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdump_pre);
 143     heap->pre_full_gc_dump(_gc_timer);
 144   }
 145 
 146   {
 147     ShenandoahGCPhase prepare_phase(ShenandoahPhaseTimings::full_gc_prepare);
 148     // Full GC is supposed to recover from any GC state:
 149 
 150     // a0. Remember if we have forwarded objects
 151     bool has_forwarded_objects = heap->has_forwarded_objects();
 152 
 153     // a1. Cancel evacuation, if in progress
 154     if (heap->is_evacuation_in_progress()) {
 155       heap->set_evacuation_in_progress(false);
 156     }
 157     assert(!heap->is_evacuation_in_progress(), "sanity");
 158 
 159     // a2. Cancel update-refs, if in progress
 160     if (heap->is_update_refs_in_progress()) {
 161       heap->set_update_refs_in_progress(false);
 162     }
 163     assert(!heap->is_update_refs_in_progress(), "sanity");
 164 
 165     // b. Cancel concurrent mark, if in progress
 166     if (heap->is_concurrent_mark_in_progress()) {
 167       ShenandoahConcurrentGC::cancel();
 168       heap->set_concurrent_mark_in_progress(false);
 169     }
 170     assert(!heap->is_concurrent_mark_in_progress(), "sanity");
 171 
 172     // c. Update roots if this full GC is due to evac-oom, which may carry from-space pointers in roots.
 173     if (has_forwarded_objects) {
 174       update_roots(true /*full_gc*/);
 175     }
 176 
 177     // d. Reset the bitmaps for new marking
 178     heap->reset_mark_bitmap();
 179     assert(heap->marking_context()->is_bitmap_clear(), "sanity");
 180     assert(!heap->marking_context()->is_complete(), "sanity");
 181 
 182     // e. Abandon reference discovery and clear all discovered references.
 183     ShenandoahReferenceProcessor* rp = heap->ref_processor();
 184     rp->abandon_partial_discovery();
 185 
 186     // f. Sync pinned region status from the CP marks
 187     heap->sync_pinned_region_status();
 188 
 189     // The rest of prologue:
 190     _preserved_marks->init(heap->workers()->active_workers());
 191 
 192     assert(heap->has_forwarded_objects() == has_forwarded_objects, "This should not change");
 193   }
 194 
 195   if (UseTLAB) {
 196     heap->gclabs_retire(ResizeTLAB);
 197     heap->tlabs_retire(ResizeTLAB);
 198   }
 199 
 200   OrderAccess::fence();
 201 
 202   phase1_mark_heap();
 203 
 204   // Once marking is done, which may have fixed up forwarded objects, we can drop it.
 205   // Coming out of Full GC, we would not have any forwarded objects.
 206   // This also prevents resolves with fwdptr from kicking in while adjusting pointers in phase3.
 207   heap->set_has_forwarded_objects(false);
 208 
 209   heap->set_full_gc_move_in_progress(true);
 210 
 211   // Setup workers for the rest
 212   OrderAccess::fence();
 213 
 214   // Initialize worker slices
 215   ShenandoahHeapRegionSet** worker_slices = NEW_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, heap->max_workers(), mtGC);
 216   for (uint i = 0; i < heap->max_workers(); i++) {
 217     worker_slices[i] = new ShenandoahHeapRegionSet();
 218   }
 219 
 220   {
 221     // The rest of code performs region moves, where region status is undefined
 222     // until all phases run together.
 223     ShenandoahHeapLocker lock(heap->lock());
 224 
 225     SlidingForwarding::begin();
 226 
 227     phase2_calculate_target_addresses(worker_slices);
 228 
 229     OrderAccess::fence();
 230 
 231     phase3_update_references();
 232 
 233     phase4_compact_objects(worker_slices);
 234   }
 235 
 236   {
 237     // Epilogue
 238     _preserved_marks->restore(heap->workers());
 239     _preserved_marks->reclaim();
 240     SlidingForwarding::end();
 241   }
 242 
 243   // Resize metaspace
 244   MetaspaceGC::compute_new_size();
 245 
 246   // Free worker slices
 247   for (uint i = 0; i < heap->max_workers(); i++) {
 248     delete worker_slices[i];
 249   }
 250   FREE_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, worker_slices);
 251 
 252   heap->set_full_gc_move_in_progress(false);
 253   heap->set_full_gc_in_progress(false);
 254 
 255   if (ShenandoahVerify) {
 256     heap->verifier()->verify_after_fullgc();
 257   }
 258 
 259   if (VerifyAfterGC) {
 260     Universe::verify();
 261   }
 262 
 263   {
 264     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdump_post);
 265     heap->post_full_gc_dump(_gc_timer);
 266   }
 267 }
 268 
 269 class ShenandoahPrepareForMarkClosure: public ShenandoahHeapRegionClosure {
 270 private:
 271   ShenandoahMarkingContext* const _ctx;
 272 
 273 public:
 274   ShenandoahPrepareForMarkClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
 275 
 276   void heap_region_do(ShenandoahHeapRegion *r) {
 277     _ctx->capture_top_at_mark_start(r);
 278     r->clear_live_data();
 279   }
 280 };
 281 
 282 void ShenandoahFullGC::phase1_mark_heap() {
 283   GCTraceTime(Info, gc, phases) time("Phase 1: Mark live objects", _gc_timer);
 284   ShenandoahGCPhase mark_phase(ShenandoahPhaseTimings::full_gc_mark);
 285 
 286   ShenandoahHeap* heap = ShenandoahHeap::heap();
 287 
 288   ShenandoahPrepareForMarkClosure cl;
 289   heap->heap_region_iterate(&cl);
 290 
 291   heap->set_unload_classes(heap->heuristics()->can_unload_classes());
 292 
 293   ShenandoahReferenceProcessor* rp = heap->ref_processor();
 294   // enable ("weak") refs discovery
 295   rp->set_soft_reference_policy(true); // forcefully purge all soft references
 296 
 297   ShenandoahSTWMark mark(true /*full_gc*/);
 298   mark.mark();
 299   heap->parallel_cleaning(true /* full_gc */);
 300 }
 301 
 302 template <bool ALT_FWD>
 303 class ShenandoahPrepareForCompactionObjectClosure : public ObjectClosure {
 304 private:
 305   PreservedMarks*          const _preserved_marks;
 306   ShenandoahHeap*          const _heap;
 307   GrowableArray<ShenandoahHeapRegion*>& _empty_regions;
 308   int _empty_regions_pos;
 309   ShenandoahHeapRegion*          _to_region;
 310   ShenandoahHeapRegion*          _from_region;
 311   HeapWord* _compact_point;
 312 
 313 public:
 314   ShenandoahPrepareForCompactionObjectClosure(PreservedMarks* preserved_marks,
 315                                               GrowableArray<ShenandoahHeapRegion*>& empty_regions,
 316                                               ShenandoahHeapRegion* to_region) :
 317     _preserved_marks(preserved_marks),
 318     _heap(ShenandoahHeap::heap()),
 319     _empty_regions(empty_regions),
 320     _empty_regions_pos(0),
 321     _to_region(to_region),
 322     _from_region(nullptr),
 323     _compact_point(to_region->bottom()) {}
 324 
 325   void set_from_region(ShenandoahHeapRegion* from_region) {
 326     _from_region = from_region;
 327   }
 328 
 329   void finish_region() {
 330     assert(_to_region != nullptr, "should not happen");
 331     _to_region->set_new_top(_compact_point);
 332   }
 333 
 334   bool is_compact_same_region() {
 335     return _from_region == _to_region;
 336   }
 337 
 338   int empty_regions_pos() {
 339     return _empty_regions_pos;
 340   }
 341 
 342   void do_object(oop p) {
 343     assert(_from_region != nullptr, "must set before work");
 344     assert(_heap->complete_marking_context()->is_marked(p), "must be marked");
 345     assert(!_heap->complete_marking_context()->allocated_after_mark_start(p), "must be truly marked");
 346 
 347     size_t obj_size = p->size();
 348     if (_compact_point + obj_size > _to_region->end()) {
 349       finish_region();
 350 
 351       // Object doesn't fit. Pick next empty region and start compacting there.
 352       ShenandoahHeapRegion* new_to_region;
 353       if (_empty_regions_pos < _empty_regions.length()) {
 354         new_to_region = _empty_regions.at(_empty_regions_pos);
 355         _empty_regions_pos++;
 356       } else {
 357         // Out of empty region? Compact within the same region.
 358         new_to_region = _from_region;
 359       }
 360 
 361       assert(new_to_region != _to_region, "must not reuse same to-region");
 362       assert(new_to_region != nullptr, "must not be null");
 363       _to_region = new_to_region;
 364       _compact_point = _to_region->bottom();
 365     }
 366 
 367     // Object fits into current region, record new location:
 368     assert(_compact_point + obj_size <= _to_region->end(), "must fit");
 369     shenandoah_assert_not_forwarded(nullptr, p);
 370     _preserved_marks->push_if_necessary(p, p->mark());
 371     SlidingForwarding::forward_to<ALT_FWD>(p, cast_to_oop(_compact_point));
 372     _compact_point += obj_size;
 373   }
 374 };
 375 
 376 class ShenandoahPrepareForCompactionTask : public WorkerTask {
 377 private:
 378   PreservedMarksSet*        const _preserved_marks;
 379   ShenandoahHeap*           const _heap;
 380   ShenandoahHeapRegionSet** const _worker_slices;
 381 
 382 public:
 383   ShenandoahPrepareForCompactionTask(PreservedMarksSet *preserved_marks, ShenandoahHeapRegionSet **worker_slices) :
 384     WorkerTask("Shenandoah Prepare For Compaction"),
 385     _preserved_marks(preserved_marks),
 386     _heap(ShenandoahHeap::heap()), _worker_slices(worker_slices) {
 387   }
 388 
 389   static bool is_candidate_region(ShenandoahHeapRegion* r) {
 390     // Empty region: get it into the slice to defragment the slice itself.
 391     // We could have skipped this without violating correctness, but we really
 392     // want to compact all live regions to the start of the heap, which sometimes
 393     // means moving them into the fully empty regions.
 394     if (r->is_empty()) return true;
 395 
 396     // Can move the region, and this is not the humongous region. Humongous
 397     // moves are special cased here, because their moves are handled separately.
 398     return r->is_stw_move_allowed() && !r->is_humongous();
 399   }
 400 
 401   void work(uint worker_id) {
 402     if (UseAltGCForwarding) {
 403       work_impl<true>(worker_id);
 404     } else {
 405       work_impl<false>(worker_id);
 406     }
 407   }
 408 
 409 private:
 410   template <bool ALT_FWD>
 411   void work_impl(uint worker_id) {
 412     ShenandoahParallelWorkerSession worker_session(worker_id);
 413     ShenandoahHeapRegionSet* slice = _worker_slices[worker_id];
 414     ShenandoahHeapRegionSetIterator it(slice);
 415     ShenandoahHeapRegion* from_region = it.next();
 416     // No work?
 417     if (from_region == nullptr) {
 418        return;
 419     }
 420 
 421     // Sliding compaction. Walk all regions in the slice, and compact them.
 422     // Remember empty regions and reuse them as needed.
 423     ResourceMark rm;
 424 
 425     GrowableArray<ShenandoahHeapRegion*> empty_regions((int)_heap->num_regions());
 426 
 427     ShenandoahPrepareForCompactionObjectClosure<ALT_FWD> cl(_preserved_marks->get(worker_id), empty_regions, from_region);
 428 
 429     while (from_region != nullptr) {
 430       assert(is_candidate_region(from_region), "Sanity");
 431 
 432       cl.set_from_region(from_region);
 433       if (from_region->has_live()) {
 434         _heap->marked_object_iterate(from_region, &cl);
 435       }
 436 
 437       // Compacted the region to somewhere else? From-region is empty then.
 438       if (!cl.is_compact_same_region()) {
 439         empty_regions.append(from_region);
 440       }
 441       from_region = it.next();
 442     }
 443     cl.finish_region();
 444 
 445     // Mark all remaining regions as empty
 446     for (int pos = cl.empty_regions_pos(); pos < empty_regions.length(); ++pos) {
 447       ShenandoahHeapRegion* r = empty_regions.at(pos);
 448       r->set_new_top(r->bottom());
 449     }
 450   }
 451 };
 452 
 453 template <bool ALT_FWD>
 454 void ShenandoahFullGC::calculate_target_humongous_objects_impl() {
 455   ShenandoahHeap* heap = ShenandoahHeap::heap();
 456 
 457   // Compute the new addresses for humongous objects. We need to do this after addresses
 458   // for regular objects are calculated, and we know what regions in heap suffix are
 459   // available for humongous moves.
 460   //
 461   // Scan the heap backwards, because we are compacting humongous regions towards the end.
 462   // Maintain the contiguous compaction window in [to_begin; to_end), so that we can slide
 463   // humongous start there.
 464   //
 465   // The complication is potential non-movable regions during the scan. If such region is
 466   // detected, then sliding restarts towards that non-movable region.
 467 
 468   size_t to_begin = heap->num_regions();
 469   size_t to_end = heap->num_regions();
 470 
 471   for (size_t c = heap->num_regions(); c > 0; c--) {
 472     ShenandoahHeapRegion *r = heap->get_region(c - 1);
 473     if (r->is_humongous_continuation() || (r->new_top() == r->bottom())) {
 474       // To-region candidate: record this, and continue scan
 475       to_begin = r->index();
 476       continue;
 477     }
 478 
 479     if (r->is_humongous_start() && r->is_stw_move_allowed()) {
 480       // From-region candidate: movable humongous region
 481       oop old_obj = cast_to_oop(r->bottom());
 482       size_t words_size = old_obj->size();
 483       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
 484 
 485       size_t start = to_end - num_regions;
 486 
 487       if (start >= to_begin && start != r->index()) {
 488         // Fits into current window, and the move is non-trivial. Record the move then, and continue scan.
 489         _preserved_marks->get(0)->push_if_necessary(old_obj, old_obj->mark());
 490         SlidingForwarding::forward_to<ALT_FWD>(old_obj, cast_to_oop(heap->get_region(start)->bottom()));
 491         to_end = start;
 492         continue;
 493       }
 494     }
 495 
 496     // Failed to fit. Scan starting from current region.
 497     to_begin = r->index();
 498     to_end = r->index();
 499   }
 500 }
 501 
 502 void ShenandoahFullGC::calculate_target_humongous_objects() {
 503   if (UseAltGCForwarding) {
 504     calculate_target_humongous_objects_impl<true>();
 505   } else {
 506     calculate_target_humongous_objects_impl<false>();
 507   }
 508 }
 509 
 510 class ShenandoahEnsureHeapActiveClosure: public ShenandoahHeapRegionClosure {
 511 private:
 512   ShenandoahHeap* const _heap;
 513 
 514 public:
 515   ShenandoahEnsureHeapActiveClosure() : _heap(ShenandoahHeap::heap()) {}
 516   void heap_region_do(ShenandoahHeapRegion* r) {
 517     if (r->is_trash()) {
 518       r->recycle();
 519     }
 520     if (r->is_cset()) {
 521       r->make_regular_bypass();
 522     }
 523     if (r->is_empty_uncommitted()) {
 524       r->make_committed_bypass();
 525     }
 526     assert (r->is_committed(), "only committed regions in heap now, see region " SIZE_FORMAT, r->index());
 527 
 528     // Record current region occupancy: this communicates empty regions are free
 529     // to the rest of Full GC code.
 530     r->set_new_top(r->top());
 531   }
 532 };
 533 
 534 class ShenandoahTrashImmediateGarbageClosure: public ShenandoahHeapRegionClosure {
 535 private:
 536   ShenandoahHeap* const _heap;
 537   ShenandoahMarkingContext* const _ctx;
 538 
 539 public:
 540   ShenandoahTrashImmediateGarbageClosure() :
 541     _heap(ShenandoahHeap::heap()),
 542     _ctx(ShenandoahHeap::heap()->complete_marking_context()) {}
 543 
 544   void heap_region_do(ShenandoahHeapRegion* r) {
 545     if (r->is_humongous_start()) {
 546       oop humongous_obj = cast_to_oop(r->bottom());
 547       if (!_ctx->is_marked(humongous_obj)) {
 548         assert(!r->has_live(),
 549                "Region " SIZE_FORMAT " is not marked, should not have live", r->index());
 550         _heap->trash_humongous_region_at(r);
 551       } else {
 552         assert(r->has_live(),
 553                "Region " SIZE_FORMAT " should have live", r->index());
 554       }
 555     } else if (r->is_humongous_continuation()) {
 556       // If we hit continuation, the non-live humongous starts should have been trashed already
 557       assert(r->humongous_start_region()->has_live(),
 558              "Region " SIZE_FORMAT " should have live", r->index());
 559     } else if (r->is_regular()) {
 560       if (!r->has_live()) {
 561         r->make_trash_immediate();
 562       }
 563     }
 564   }
 565 };
 566 
 567 void ShenandoahFullGC::distribute_slices(ShenandoahHeapRegionSet** worker_slices) {
 568   ShenandoahHeap* heap = ShenandoahHeap::heap();
 569 
 570   uint n_workers = heap->workers()->active_workers();
 571   size_t n_regions = heap->num_regions();
 572 
 573   // What we want to accomplish: have the dense prefix of data, while still balancing
 574   // out the parallel work.
 575   //
 576   // Assuming the amount of work is driven by the live data that needs moving, we can slice
 577   // the entire heap into equal-live-sized prefix slices, and compact into them. So, each
 578   // thread takes all regions in its prefix subset, and then it takes some regions from
 579   // the tail.
 580   //
 581   // Tail region selection becomes interesting.
 582   //
 583   // First, we want to distribute the regions fairly between the workers, and those regions
 584   // might have different amount of live data. So, until we sure no workers need live data,
 585   // we need to only take what the worker needs.
 586   //
 587   // Second, since we slide everything to the left in each slice, the most busy regions
 588   // would be the ones on the left. Which means we want to have all workers have their after-tail
 589   // regions as close to the left as possible.
 590   //
 591   // The easiest way to do this is to distribute after-tail regions in round-robin between
 592   // workers that still need live data.
 593   //
 594   // Consider parallel workers A, B, C, then the target slice layout would be:
 595   //
 596   //  AAAAAAAABBBBBBBBCCCCCCCC|ABCABCABCABCABCABCABCABABABABABABABABABABAAAAA
 597   //
 598   //  (.....dense-prefix.....) (.....................tail...................)
 599   //  [all regions fully live] [left-most regions are fuller that right-most]
 600   //
 601 
 602   // Compute how much live data is there. This would approximate the size of dense prefix
 603   // we target to create.
 604   size_t total_live = 0;
 605   for (size_t idx = 0; idx < n_regions; idx++) {
 606     ShenandoahHeapRegion *r = heap->get_region(idx);
 607     if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
 608       total_live += r->get_live_data_words();
 609     }
 610   }
 611 
 612   // Estimate the size for the dense prefix. Note that we specifically count only the
 613   // "full" regions, so there would be some non-full regions in the slice tail.
 614   size_t live_per_worker = total_live / n_workers;
 615   size_t prefix_regions_per_worker = live_per_worker / ShenandoahHeapRegion::region_size_words();
 616   size_t prefix_regions_total = prefix_regions_per_worker * n_workers;
 617   prefix_regions_total = MIN2(prefix_regions_total, n_regions);
 618   assert(prefix_regions_total <= n_regions, "Sanity");
 619 
 620   // There might be non-candidate regions in the prefix. To compute where the tail actually
 621   // ends up being, we need to account those as well.
 622   size_t prefix_end = prefix_regions_total;
 623   for (size_t idx = 0; idx < prefix_regions_total; idx++) {
 624     ShenandoahHeapRegion *r = heap->get_region(idx);
 625     if (!ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
 626       prefix_end++;
 627     }
 628   }
 629   prefix_end = MIN2(prefix_end, n_regions);
 630   assert(prefix_end <= n_regions, "Sanity");
 631 
 632   // Distribute prefix regions per worker: each thread definitely gets its own same-sized
 633   // subset of dense prefix.
 634   size_t prefix_idx = 0;
 635 
 636   size_t* live = NEW_C_HEAP_ARRAY(size_t, n_workers, mtGC);
 637 
 638   for (size_t wid = 0; wid < n_workers; wid++) {
 639     ShenandoahHeapRegionSet* slice = worker_slices[wid];
 640 
 641     live[wid] = 0;
 642     size_t regs = 0;
 643 
 644     // Add all prefix regions for this worker
 645     while (prefix_idx < prefix_end && regs < prefix_regions_per_worker) {
 646       ShenandoahHeapRegion *r = heap->get_region(prefix_idx);
 647       if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
 648         slice->add_region(r);
 649         live[wid] += r->get_live_data_words();
 650         regs++;
 651       }
 652       prefix_idx++;
 653     }
 654   }
 655 
 656   // Distribute the tail among workers in round-robin fashion.
 657   size_t wid = n_workers - 1;
 658 
 659   for (size_t tail_idx = prefix_end; tail_idx < n_regions; tail_idx++) {
 660     ShenandoahHeapRegion *r = heap->get_region(tail_idx);
 661     if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {
 662       assert(wid < n_workers, "Sanity");
 663 
 664       size_t live_region = r->get_live_data_words();
 665 
 666       // Select next worker that still needs live data.
 667       size_t old_wid = wid;
 668       do {
 669         wid++;
 670         if (wid == n_workers) wid = 0;
 671       } while (live[wid] + live_region >= live_per_worker && old_wid != wid);
 672 
 673       if (old_wid == wid) {
 674         // Circled back to the same worker? This means liveness data was
 675         // miscalculated. Bump the live_per_worker limit so that
 676         // everyone gets a piece of the leftover work.
 677         live_per_worker += ShenandoahHeapRegion::region_size_words();
 678       }
 679 
 680       worker_slices[wid]->add_region(r);
 681       live[wid] += live_region;
 682     }
 683   }
 684 
 685   FREE_C_HEAP_ARRAY(size_t, live);
 686 
 687 #ifdef ASSERT
 688   ResourceBitMap map(n_regions);
 689   for (size_t wid = 0; wid < n_workers; wid++) {
 690     ShenandoahHeapRegionSetIterator it(worker_slices[wid]);
 691     ShenandoahHeapRegion* r = it.next();
 692     while (r != nullptr) {
 693       size_t idx = r->index();
 694       assert(ShenandoahPrepareForCompactionTask::is_candidate_region(r), "Sanity: " SIZE_FORMAT, idx);
 695       assert(!map.at(idx), "No region distributed twice: " SIZE_FORMAT, idx);
 696       map.at_put(idx, true);
 697       r = it.next();
 698     }
 699   }
 700 
 701   for (size_t rid = 0; rid < n_regions; rid++) {
 702     bool is_candidate = ShenandoahPrepareForCompactionTask::is_candidate_region(heap->get_region(rid));
 703     bool is_distributed = map.at(rid);
 704     assert(is_distributed || !is_candidate, "All candidates are distributed: " SIZE_FORMAT, rid);
 705   }
 706 #endif
 707 }
 708 
 709 void ShenandoahFullGC::phase2_calculate_target_addresses(ShenandoahHeapRegionSet** worker_slices) {
 710   GCTraceTime(Info, gc, phases) time("Phase 2: Compute new object addresses", _gc_timer);
 711   ShenandoahGCPhase calculate_address_phase(ShenandoahPhaseTimings::full_gc_calculate_addresses);
 712 
 713   ShenandoahHeap* heap = ShenandoahHeap::heap();
 714 
 715   // About to figure out which regions can be compacted, make sure pinning status
 716   // had been updated in GC prologue.
 717   heap->assert_pinned_region_status();
 718 
 719   {
 720     // Trash the immediately collectible regions before computing addresses
 721     ShenandoahTrashImmediateGarbageClosure tigcl;
 722     heap->heap_region_iterate(&tigcl);
 723 
 724     // Make sure regions are in good state: committed, active, clean.
 725     // This is needed because we are potentially sliding the data through them.
 726     ShenandoahEnsureHeapActiveClosure ecl;
 727     heap->heap_region_iterate(&ecl);
 728   }
 729 
 730   // Compute the new addresses for regular objects
 731   {
 732     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_regular);
 733 
 734     distribute_slices(worker_slices);
 735 
 736     ShenandoahPrepareForCompactionTask task(_preserved_marks, worker_slices);
 737     heap->workers()->run_task(&task);
 738   }
 739 
 740   // Compute the new addresses for humongous objects
 741   {
 742     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_humong);
 743     calculate_target_humongous_objects();
 744   }
 745 }
 746 
 747 template <bool ALT_FWD>
 748 class ShenandoahAdjustPointersClosure : public MetadataVisitingOopIterateClosure {
 749 private:
 750   ShenandoahHeap* const _heap;
 751   ShenandoahMarkingContext* const _ctx;
 752 
 753   template <class T>
 754   inline void do_oop_work(T* p) {
 755     T o = RawAccess<>::oop_load(p);
 756     if (!CompressedOops::is_null(o)) {
 757       oop obj = CompressedOops::decode_not_null(o);
 758       assert(_ctx->is_marked(obj), "must be marked");
 759       if (SlidingForwarding::is_forwarded(obj)) {
 760         oop forw = SlidingForwarding::forwardee<ALT_FWD>(obj);
 761         RawAccess<IS_NOT_NULL>::oop_store(p, forw);
 762       }
 763     }
 764   }
 765 
 766 public:
 767   ShenandoahAdjustPointersClosure() :
 768     _heap(ShenandoahHeap::heap()),
 769     _ctx(ShenandoahHeap::heap()->complete_marking_context()) {}
 770 
 771   void do_oop(oop* p)       { do_oop_work(p); }
 772   void do_oop(narrowOop* p) { do_oop_work(p); }
 773   void do_method(Method* m) {}
 774   void do_nmethod(nmethod* nm) {}
 775 };
 776 
 777 template <bool ALT_FWD>
 778 class ShenandoahAdjustPointersObjectClosure : public ObjectClosure {
 779 private:
 780   ShenandoahHeap* const _heap;
 781   ShenandoahAdjustPointersClosure<ALT_FWD> _cl;
 782 
 783 public:
 784   ShenandoahAdjustPointersObjectClosure() :
 785     _heap(ShenandoahHeap::heap()) {
 786   }
 787   void do_object(oop p) {
 788     assert(_heap->complete_marking_context()->is_marked(p), "must be marked");
 789     p->oop_iterate(&_cl);
 790   }
 791 };
 792 
 793 class ShenandoahAdjustPointersTask : public WorkerTask {
 794 private:
 795   ShenandoahHeap*          const _heap;
 796   ShenandoahRegionIterator       _regions;
 797 
 798 public:
 799   ShenandoahAdjustPointersTask() :
 800     WorkerTask("Shenandoah Adjust Pointers"),
 801     _heap(ShenandoahHeap::heap()) {
 802   }
 803 
 804 private:
 805   template <bool ALT_FWD>
 806   void work_impl(uint worker_id) {
 807     ShenandoahParallelWorkerSession worker_session(worker_id);
 808     ShenandoahAdjustPointersObjectClosure<ALT_FWD> obj_cl;
 809     ShenandoahHeapRegion* r = _regions.next();
 810     while (r != nullptr) {
 811       if (!r->is_humongous_continuation() && r->has_live()) {
 812         _heap->marked_object_iterate(r, &obj_cl);
 813       }
 814       r = _regions.next();
 815     }
 816   }
 817 
 818 public:
 819   void work(uint worker_id) {
 820     if (UseAltGCForwarding) {
 821       work_impl<true>(worker_id);
 822     } else {
 823       work_impl<false>(worker_id);
 824     }
 825   }
 826 };
 827 
 828 class ShenandoahAdjustRootPointersTask : public WorkerTask {
 829 private:
 830   ShenandoahRootAdjuster* _rp;
 831   PreservedMarksSet* _preserved_marks;
 832 
 833 public:
 834   ShenandoahAdjustRootPointersTask(ShenandoahRootAdjuster* rp, PreservedMarksSet* preserved_marks) :
 835     WorkerTask("Shenandoah Adjust Root Pointers"),
 836     _rp(rp),
 837     _preserved_marks(preserved_marks) {}
 838 
 839 private:
 840   template <bool ALT_FWD>
 841   void work_impl(uint worker_id) {
 842     ShenandoahParallelWorkerSession worker_session(worker_id);
 843     ShenandoahAdjustPointersClosure<ALT_FWD> cl;
 844     _rp->roots_do(worker_id, &cl);
 845     _preserved_marks->get(worker_id)->adjust_during_full_gc();
 846   }
 847 
 848 public:
 849   void work(uint worker_id) {
 850     if (UseAltGCForwarding) {
 851       work_impl<true>(worker_id);
 852     } else {
 853       work_impl<false>(worker_id);
 854     }
 855   }
 856 };
 857 
 858 void ShenandoahFullGC::phase3_update_references() {
 859   GCTraceTime(Info, gc, phases) time("Phase 3: Adjust pointers", _gc_timer);
 860   ShenandoahGCPhase adjust_pointer_phase(ShenandoahPhaseTimings::full_gc_adjust_pointers);
 861 
 862   ShenandoahHeap* heap = ShenandoahHeap::heap();
 863 
 864   WorkerThreads* workers = heap->workers();
 865   uint nworkers = workers->active_workers();
 866   {
 867 #if COMPILER2_OR_JVMCI
 868     DerivedPointerTable::clear();
 869 #endif
 870     ShenandoahRootAdjuster rp(nworkers, ShenandoahPhaseTimings::full_gc_adjust_roots);
 871     ShenandoahAdjustRootPointersTask task(&rp, _preserved_marks);
 872     workers->run_task(&task);
 873 #if COMPILER2_OR_JVMCI
 874     DerivedPointerTable::update_pointers();
 875 #endif
 876   }
 877 
 878   ShenandoahAdjustPointersTask adjust_pointers_task;
 879   workers->run_task(&adjust_pointers_task);
 880 }
 881 
 882 template <bool ALT_FWD>
 883 class ShenandoahCompactObjectsClosure : public ObjectClosure {
 884 private:
 885   ShenandoahHeap* const _heap;
 886   uint            const _worker_id;
 887 
 888 public:
 889   ShenandoahCompactObjectsClosure(uint worker_id) :
 890     _heap(ShenandoahHeap::heap()), _worker_id(worker_id) {}
 891 
 892   void do_object(oop p) {
 893     assert(_heap->complete_marking_context()->is_marked(p), "must be marked");
 894     size_t size = p->size();
 895     if (SlidingForwarding::is_forwarded(p)) {
 896       HeapWord* compact_from = cast_from_oop<HeapWord*>(p);
 897       HeapWord* compact_to = cast_from_oop<HeapWord*>(SlidingForwarding::forwardee<ALT_FWD>(p));
 898       Copy::aligned_conjoint_words(compact_from, compact_to, size);
 899       oop new_obj = cast_to_oop(compact_to);
 900 
 901       ContinuationGCSupport::relativize_stack_chunk(new_obj);
 902       new_obj->init_mark();
 903     }
 904   }
 905 };
 906 
 907 class ShenandoahCompactObjectsTask : public WorkerTask {
 908 private:
 909   ShenandoahHeap* const _heap;
 910   ShenandoahHeapRegionSet** const _worker_slices;
 911 
 912 public:
 913   ShenandoahCompactObjectsTask(ShenandoahHeapRegionSet** worker_slices) :
 914     WorkerTask("Shenandoah Compact Objects"),
 915     _heap(ShenandoahHeap::heap()),
 916     _worker_slices(worker_slices) {
 917   }
 918 
 919 private:
 920   template <bool ALT_FWD>
 921   void work_impl(uint worker_id) {
 922     ShenandoahParallelWorkerSession worker_session(worker_id);
 923     ShenandoahHeapRegionSetIterator slice(_worker_slices[worker_id]);
 924 
 925     ShenandoahCompactObjectsClosure<ALT_FWD> cl(worker_id);
 926     ShenandoahHeapRegion* r = slice.next();
 927     while (r != nullptr) {
 928       assert(!r->is_humongous(), "must not get humongous regions here");
 929       if (r->has_live()) {
 930         _heap->marked_object_iterate(r, &cl);
 931       }
 932       r->set_top(r->new_top());
 933       r = slice.next();
 934     }
 935   }
 936 
 937 public:
 938   void work(uint worker_id) {
 939     if (UseAltGCForwarding) {
 940       work_impl<true>(worker_id);
 941     } else {
 942       work_impl<false>(worker_id);
 943     }
 944   }
 945 };
 946 
 947 class ShenandoahPostCompactClosure : public ShenandoahHeapRegionClosure {
 948 private:
 949   ShenandoahHeap* const _heap;
 950   size_t _live;
 951 
 952 public:
 953   ShenandoahPostCompactClosure() : _heap(ShenandoahHeap::heap()), _live(0) {
 954     _heap->free_set()->clear();
 955   }
 956 
 957   void heap_region_do(ShenandoahHeapRegion* r) {
 958     assert (!r->is_cset(), "cset regions should have been demoted already");
 959 
 960     // Need to reset the complete-top-at-mark-start pointer here because
 961     // the complete marking bitmap is no longer valid. This ensures
 962     // size-based iteration in marked_object_iterate().
 963     // NOTE: See blurb at ShenandoahMCResetCompleteBitmapTask on why we need to skip
 964     // pinned regions.
 965     if (!r->is_pinned()) {
 966       _heap->complete_marking_context()->reset_top_at_mark_start(r);
 967     }
 968 
 969     size_t live = r->used();
 970 
 971     // Make empty regions that have been allocated into regular
 972     if (r->is_empty() && live > 0) {
 973       r->make_regular_bypass();
 974       if (ZapUnusedHeapArea) {
 975         SpaceMangler::mangle_region(MemRegion(r->top(), r->end()));
 976       }
 977     }
 978 
 979     // Reclaim regular regions that became empty
 980     if (r->is_regular() && live == 0) {
 981       r->make_trash();
 982     }
 983 
 984     // Recycle all trash regions
 985     if (r->is_trash()) {
 986       live = 0;
 987       r->recycle();
 988     }
 989 
 990     r->set_live_data(live);
 991     r->reset_alloc_metadata();
 992     _live += live;
 993   }
 994 
 995   size_t get_live() {
 996     return _live;
 997   }
 998 };
 999 
1000 template <bool ALT_FWD>
1001 void ShenandoahFullGC::compact_humongous_objects_impl() {
1002   // Compact humongous regions, based on their fwdptr objects.
1003   //
1004   // This code is serial, because doing the in-slice parallel sliding is tricky. In most cases,
1005   // humongous regions are already compacted, and do not require further moves, which alleviates
1006   // sliding costs. We may consider doing this in parallel in future.
1007 
1008   ShenandoahHeap* heap = ShenandoahHeap::heap();
1009 
1010   for (size_t c = heap->num_regions(); c > 0; c--) {
1011     ShenandoahHeapRegion* r = heap->get_region(c - 1);
1012     if (r->is_humongous_start()) {
1013       oop old_obj = cast_to_oop(r->bottom());
1014       if (SlidingForwarding::is_not_forwarded(old_obj)) {
1015         // No need to move the object, it stays at the same slot
1016         continue;
1017       }
1018       size_t words_size = old_obj->size();
1019       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
1020 
1021       size_t old_start = r->index();
1022       size_t old_end   = old_start + num_regions - 1;
1023       size_t new_start = heap->heap_region_index_containing(SlidingForwarding::forwardee<ALT_FWD>(old_obj));
1024       size_t new_end   = new_start + num_regions - 1;
1025       assert(old_start != new_start, "must be real move");
1026       assert(r->is_stw_move_allowed(), "Region " SIZE_FORMAT " should be movable", r->index());
1027 
1028       Copy::aligned_conjoint_words(r->bottom(), heap->get_region(new_start)->bottom(), words_size);
1029       ContinuationGCSupport::relativize_stack_chunk(cast_to_oop<HeapWord*>(r->bottom()));
1030 
1031       oop new_obj = cast_to_oop(heap->get_region(new_start)->bottom());
1032       new_obj->init_mark();
1033 
1034       {
1035         for (size_t c = old_start; c <= old_end; c++) {
1036           ShenandoahHeapRegion* r = heap->get_region(c);
1037           r->make_regular_bypass();
1038           r->set_top(r->bottom());
1039         }
1040 
1041         for (size_t c = new_start; c <= new_end; c++) {
1042           ShenandoahHeapRegion* r = heap->get_region(c);
1043           if (c == new_start) {
1044             r->make_humongous_start_bypass();
1045           } else {
1046             r->make_humongous_cont_bypass();
1047           }
1048 
1049           // Trailing region may be non-full, record the remainder there
1050           size_t remainder = words_size & ShenandoahHeapRegion::region_size_words_mask();
1051           if ((c == new_end) && (remainder != 0)) {
1052             r->set_top(r->bottom() + remainder);
1053           } else {
1054             r->set_top(r->end());
1055           }
1056 
1057           r->reset_alloc_metadata();
1058         }
1059       }
1060     }
1061   }
1062 }
1063 
1064 void ShenandoahFullGC::compact_humongous_objects() {
1065   if (UseAltGCForwarding) {
1066     compact_humongous_objects_impl<true>();
1067   } else {
1068     compact_humongous_objects_impl<false>();
1069   }
1070 }
1071 
1072 // This is slightly different to ShHeap::reset_next_mark_bitmap:
1073 // we need to remain able to walk pinned regions.
1074 // Since pinned region do not move and don't get compacted, we will get holes with
1075 // unreachable objects in them (which may have pointers to unloaded Klasses and thus
1076 // cannot be iterated over using oop->size(). The only way to safely iterate over those is using
1077 // a valid marking bitmap and valid TAMS pointer. This class only resets marking
1078 // bitmaps for un-pinned regions, and later we only reset TAMS for unpinned regions.
1079 class ShenandoahMCResetCompleteBitmapTask : public WorkerTask {
1080 private:
1081   ShenandoahRegionIterator _regions;
1082 
1083 public:
1084   ShenandoahMCResetCompleteBitmapTask() :
1085     WorkerTask("Shenandoah Reset Bitmap") {
1086   }
1087 
1088   void work(uint worker_id) {
1089     ShenandoahParallelWorkerSession worker_session(worker_id);
1090     ShenandoahHeapRegion* region = _regions.next();
1091     ShenandoahHeap* heap = ShenandoahHeap::heap();
1092     ShenandoahMarkingContext* const ctx = heap->complete_marking_context();
1093     while (region != nullptr) {
1094       if (heap->is_bitmap_slice_committed(region) && !region->is_pinned() && region->has_live()) {
1095         ctx->clear_bitmap(region);
1096       }
1097       region = _regions.next();
1098     }
1099   }
1100 };
1101 
1102 void ShenandoahFullGC::phase4_compact_objects(ShenandoahHeapRegionSet** worker_slices) {
1103   GCTraceTime(Info, gc, phases) time("Phase 4: Move objects", _gc_timer);
1104   ShenandoahGCPhase compaction_phase(ShenandoahPhaseTimings::full_gc_copy_objects);
1105 
1106   ShenandoahHeap* heap = ShenandoahHeap::heap();
1107 
1108   // Compact regular objects first
1109   {
1110     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_regular);
1111     ShenandoahCompactObjectsTask compact_task(worker_slices);
1112     heap->workers()->run_task(&compact_task);
1113   }
1114 
1115   // Compact humongous objects after regular object moves
1116   {
1117     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_humong);
1118     compact_humongous_objects();
1119   }
1120 
1121   // Reset complete bitmap. We're about to reset the complete-top-at-mark-start pointer
1122   // and must ensure the bitmap is in sync.
1123   {
1124     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_reset_complete);
1125     ShenandoahMCResetCompleteBitmapTask task;
1126     heap->workers()->run_task(&task);
1127   }
1128 
1129   // Bring regions in proper states after the collection, and set heap properties.
1130   {
1131     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_rebuild);
1132 
1133     ShenandoahPostCompactClosure post_compact;
1134     heap->heap_region_iterate(&post_compact);
1135     heap->set_used(post_compact.get_live());
1136 
1137     heap->collection_set()->clear();
1138     heap->free_set()->rebuild();
1139   }
1140 
1141   heap->clear_cancelled_gc();
1142 }