< prev index next >

src/hotspot/share/gc/shenandoah/shenandoahFullGC.cpp

Print this page

  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/tlab_globals.hpp"
  32 #include "gc/shared/workerThread.hpp"
  33 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
  34 #include "gc/shenandoah/shenandoahConcurrentGC.hpp"
  35 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  36 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  37 #include "gc/shenandoah/shenandoahFullGC.hpp"

  38 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  39 #include "gc/shenandoah/shenandoahMark.inline.hpp"
  40 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
  41 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  42 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  43 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
  44 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  45 #include "gc/shenandoah/shenandoahMetrics.hpp"

  46 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
  47 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
  48 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
  49 #include "gc/shenandoah/shenandoahSTWMark.hpp"
  50 #include "gc/shenandoah/shenandoahUtils.hpp"
  51 #include "gc/shenandoah/shenandoahVerifier.hpp"
  52 #include "gc/shenandoah/shenandoahVMOperations.hpp"
  53 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"

  54 #include "memory/metaspaceUtils.hpp"
  55 #include "memory/universe.hpp"
  56 #include "oops/compressedOops.inline.hpp"
  57 #include "oops/oop.inline.hpp"
  58 #include "runtime/javaThread.hpp"
  59 #include "runtime/orderAccess.hpp"
  60 #include "runtime/vmThread.hpp"
  61 #include "utilities/copy.hpp"
  62 #include "utilities/events.hpp"
  63 #include "utilities/growableArray.hpp"
  64 































































  65 ShenandoahFullGC::ShenandoahFullGC() :
  66   _gc_timer(ShenandoahHeap::heap()->gc_timer()),
  67   _preserved_marks(new PreservedMarksSet(true)) {}
  68 
  69 bool ShenandoahFullGC::collect(GCCause::Cause cause) {
  70   vmop_entry_full(cause);
  71   // Always success
  72   return true;
  73 }
  74 
  75 void ShenandoahFullGC::vmop_entry_full(GCCause::Cause cause) {
  76   ShenandoahHeap* const heap = ShenandoahHeap::heap();
  77   TraceCollectorStats tcs(heap->monitoring_support()->full_stw_collection_counters());
  78   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::full_gc_gross);
  79 
  80   heap->try_inject_alloc_failure();
  81   VM_ShenandoahFullGC op(cause, this);
  82   VMThread::execute(&op);
  83 }
  84 
  85 void ShenandoahFullGC::entry_full(GCCause::Cause cause) {
  86   static const char* msg = "Pause Full";
  87   ShenandoahPausePhase gc_phase(msg, ShenandoahPhaseTimings::full_gc, true /* log_heap_usage */);
  88   EventMark em("%s", msg);
  89 
  90   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
  91                               ShenandoahWorkerPolicy::calc_workers_for_fullgc(),
  92                               "full gc");
  93 
  94   op_full(cause);
  95 }
  96 
  97 void ShenandoahFullGC::op_full(GCCause::Cause cause) {

  98   ShenandoahMetricsSnapshot metrics;
  99   metrics.snap_before();
 100 
 101   // Perform full GC
 102   do_it(cause);
 103 
 104   metrics.snap_after();
 105 






 106   if (metrics.is_good_progress()) {
 107     ShenandoahHeap::heap()->notify_gc_progress();
 108   } else {
 109     // Nothing to do. Tell the allocation path that we have failed to make
 110     // progress, and it can finally fail.
 111     ShenandoahHeap::heap()->notify_gc_no_progress();
 112   }
 113 }
 114 
 115 void ShenandoahFullGC::do_it(GCCause::Cause gc_cause) {
 116   ShenandoahHeap* heap = ShenandoahHeap::heap();


















 117 
 118   if (ShenandoahVerify) {
 119     heap->verifier()->verify_before_fullgc();
 120   }
 121 
 122   if (VerifyBeforeGC) {
 123     Universe::verify();
 124   }
 125 
 126   // Degenerated GC may carry concurrent root flags when upgrading to
 127   // full GC. We need to reset it before mutators resume.
 128   heap->set_concurrent_strong_root_in_progress(false);
 129   heap->set_concurrent_weak_root_in_progress(false);
 130 
 131   heap->set_full_gc_in_progress(true);
 132 
 133   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at a safepoint");
 134   assert(Thread::current()->is_VM_thread(), "Do full GC only while world is stopped");
 135 
 136   {

 140 
 141   {
 142     ShenandoahGCPhase prepare_phase(ShenandoahPhaseTimings::full_gc_prepare);
 143     // Full GC is supposed to recover from any GC state:
 144 
 145     // a0. Remember if we have forwarded objects
 146     bool has_forwarded_objects = heap->has_forwarded_objects();
 147 
 148     // a1. Cancel evacuation, if in progress
 149     if (heap->is_evacuation_in_progress()) {
 150       heap->set_evacuation_in_progress(false);
 151     }
 152     assert(!heap->is_evacuation_in_progress(), "sanity");
 153 
 154     // a2. Cancel update-refs, if in progress
 155     if (heap->is_update_refs_in_progress()) {
 156       heap->set_update_refs_in_progress(false);
 157     }
 158     assert(!heap->is_update_refs_in_progress(), "sanity");
 159 
 160     // b. Cancel concurrent mark, if in progress
 161     if (heap->is_concurrent_mark_in_progress()) {
 162       ShenandoahConcurrentGC::cancel();
 163       heap->set_concurrent_mark_in_progress(false);
 164     }
 165     assert(!heap->is_concurrent_mark_in_progress(), "sanity");
 166 
 167     // c. Update roots if this full GC is due to evac-oom, which may carry from-space pointers in roots.
 168     if (has_forwarded_objects) {
 169       update_roots(true /*full_gc*/);
 170     }
 171 
 172     // d. Reset the bitmaps for new marking
 173     heap->reset_mark_bitmap();
 174     assert(heap->marking_context()->is_bitmap_clear(), "sanity");
 175     assert(!heap->marking_context()->is_complete(), "sanity");
 176 
 177     // e. Abandon reference discovery and clear all discovered references.
 178     ShenandoahReferenceProcessor* rp = heap->ref_processor();
 179     rp->abandon_partial_discovery();
 180 
 181     // f. Sync pinned region status from the CP marks
 182     heap->sync_pinned_region_status();
 183 
 184     // The rest of prologue:
 185     _preserved_marks->init(heap->workers()->active_workers());
 186 
 187     assert(heap->has_forwarded_objects() == has_forwarded_objects, "This should not change");
 188   }
 189 
 190   if (UseTLAB) {

 191     heap->gclabs_retire(ResizeTLAB);
 192     heap->tlabs_retire(ResizeTLAB);
 193   }
 194 
 195   OrderAccess::fence();
 196 
 197   phase1_mark_heap();
 198 
 199   // Once marking is done, which may have fixed up forwarded objects, we can drop it.
 200   // Coming out of Full GC, we would not have any forwarded objects.
 201   // This also prevents resolves with fwdptr from kicking in while adjusting pointers in phase3.
 202   heap->set_has_forwarded_objects(false);
 203 
 204   heap->set_full_gc_move_in_progress(true);
 205 
 206   // Setup workers for the rest
 207   OrderAccess::fence();
 208 
 209   // Initialize worker slices
 210   ShenandoahHeapRegionSet** worker_slices = NEW_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, heap->max_workers(), mtGC);

 213   }
 214 
 215   {
 216     // The rest of code performs region moves, where region status is undefined
 217     // until all phases run together.
 218     ShenandoahHeapLocker lock(heap->lock());
 219 
 220     phase2_calculate_target_addresses(worker_slices);
 221 
 222     OrderAccess::fence();
 223 
 224     phase3_update_references();
 225 
 226     phase4_compact_objects(worker_slices);
 227   }
 228 
 229   {
 230     // Epilogue
 231     _preserved_marks->restore(heap->workers());
 232     _preserved_marks->reclaim();






 233   }
 234 
 235   // Resize metaspace
 236   MetaspaceGC::compute_new_size();
 237 
 238   // Free worker slices
 239   for (uint i = 0; i < heap->max_workers(); i++) {
 240     delete worker_slices[i];
 241   }
 242   FREE_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, worker_slices);
 243 
 244   heap->set_full_gc_move_in_progress(false);
 245   heap->set_full_gc_in_progress(false);
 246 
 247   if (ShenandoahVerify) {
 248     heap->verifier()->verify_after_fullgc();




 249   }
 250 
 251   if (VerifyAfterGC) {
 252     Universe::verify();
 253   }
 254 
 255   {
 256     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdump_post);
 257     heap->post_full_gc_dump(_gc_timer);
 258   }
 259 }
 260 
 261 class ShenandoahPrepareForMarkClosure: public ShenandoahHeapRegionClosure {
 262 private:
 263   ShenandoahMarkingContext* const _ctx;
 264 
 265 public:
 266   ShenandoahPrepareForMarkClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
 267 
 268   void heap_region_do(ShenandoahHeapRegion *r) {
 269     _ctx->capture_top_at_mark_start(r);
 270     r->clear_live_data();


 271   }


 272 };
 273 
 274 void ShenandoahFullGC::phase1_mark_heap() {
 275   GCTraceTime(Info, gc, phases) time("Phase 1: Mark live objects", _gc_timer);
 276   ShenandoahGCPhase mark_phase(ShenandoahPhaseTimings::full_gc_mark);
 277 
 278   ShenandoahHeap* heap = ShenandoahHeap::heap();
 279 
 280   ShenandoahPrepareForMarkClosure cl;
 281   heap->heap_region_iterate(&cl);
 282 
 283   heap->set_unload_classes(heap->heuristics()->can_unload_classes());
 284 
 285   ShenandoahReferenceProcessor* rp = heap->ref_processor();
 286   // enable ("weak") refs discovery
 287   rp->set_soft_reference_policy(true); // forcefully purge all soft references
 288 
 289   ShenandoahSTWMark mark(true /*full_gc*/);
 290   mark.mark();
 291   heap->parallel_cleaning(true /* full_gc */);
 292 }
 293 



































































































































































































































 294 class ShenandoahPrepareForCompactionObjectClosure : public ObjectClosure {
 295 private:
 296   PreservedMarks*          const _preserved_marks;
 297   ShenandoahHeap*          const _heap;
 298   GrowableArray<ShenandoahHeapRegion*>& _empty_regions;
 299   int _empty_regions_pos;
 300   ShenandoahHeapRegion*          _to_region;
 301   ShenandoahHeapRegion*          _from_region;
 302   HeapWord* _compact_point;
 303 
 304 public:
 305   ShenandoahPrepareForCompactionObjectClosure(PreservedMarks* preserved_marks,
 306                                               GrowableArray<ShenandoahHeapRegion*>& empty_regions,
 307                                               ShenandoahHeapRegion* to_region) :
 308     _preserved_marks(preserved_marks),
 309     _heap(ShenandoahHeap::heap()),
 310     _empty_regions(empty_regions),
 311     _empty_regions_pos(0),
 312     _to_region(to_region),
 313     _from_region(NULL),
 314     _compact_point(to_region->bottom()) {}
 315 
 316   void set_from_region(ShenandoahHeapRegion* from_region) {
 317     _from_region = from_region;
 318   }
 319 
 320   void finish_region() {
 321     assert(_to_region != NULL, "should not happen");

 322     _to_region->set_new_top(_compact_point);
 323   }
 324 
 325   bool is_compact_same_region() {
 326     return _from_region == _to_region;
 327   }
 328 
 329   int empty_regions_pos() {
 330     return _empty_regions_pos;
 331   }
 332 
 333   void do_object(oop p) {
 334     assert(_from_region != NULL, "must set before work");
 335     assert(_heap->complete_marking_context()->is_marked(p), "must be marked");
 336     assert(!_heap->complete_marking_context()->allocated_after_mark_start(p), "must be truly marked");
 337 
 338     size_t obj_size = p->size();
 339     if (_compact_point + obj_size > _to_region->end()) {
 340       finish_region();
 341 

 347       } else {
 348         // Out of empty region? Compact within the same region.
 349         new_to_region = _from_region;
 350       }
 351 
 352       assert(new_to_region != _to_region, "must not reuse same to-region");
 353       assert(new_to_region != NULL, "must not be NULL");
 354       _to_region = new_to_region;
 355       _compact_point = _to_region->bottom();
 356     }
 357 
 358     // Object fits into current region, record new location:
 359     assert(_compact_point + obj_size <= _to_region->end(), "must fit");
 360     shenandoah_assert_not_forwarded(NULL, p);
 361     _preserved_marks->push_if_necessary(p, p->mark());
 362     p->forward_to(cast_to_oop(_compact_point));
 363     _compact_point += obj_size;
 364   }
 365 };
 366 
 367 class ShenandoahPrepareForCompactionTask : public WorkerTask {
 368 private:
 369   PreservedMarksSet*        const _preserved_marks;
 370   ShenandoahHeap*           const _heap;
 371   ShenandoahHeapRegionSet** const _worker_slices;
 372 
 373 public:
 374   ShenandoahPrepareForCompactionTask(PreservedMarksSet *preserved_marks, ShenandoahHeapRegionSet **worker_slices) :

 375     WorkerTask("Shenandoah Prepare For Compaction"),
 376     _preserved_marks(preserved_marks),
 377     _heap(ShenandoahHeap::heap()), _worker_slices(worker_slices) {










 378   }
 379 
 380   static bool is_candidate_region(ShenandoahHeapRegion* r) {
 381     // Empty region: get it into the slice to defragment the slice itself.
 382     // We could have skipped this without violating correctness, but we really
 383     // want to compact all live regions to the start of the heap, which sometimes
 384     // means moving them into the fully empty regions.
 385     if (r->is_empty()) return true;
 386 
 387     // Can move the region, and this is not the humongous region. Humongous
 388     // moves are special cased here, because their moves are handled separately.
 389     return r->is_stw_move_allowed() && !r->is_humongous();
 390   }
 391 
 392   void work(uint worker_id) {
 393     ShenandoahParallelWorkerSession worker_session(worker_id);
 394     ShenandoahHeapRegionSet* slice = _worker_slices[worker_id];
 395     ShenandoahHeapRegionSetIterator it(slice);
 396     ShenandoahHeapRegion* from_region = it.next();
 397     // No work?
 398     if (from_region == NULL) {
 399        return;
 400     }
 401 
 402     // Sliding compaction. Walk all regions in the slice, and compact them.
 403     // Remember empty regions and reuse them as needed.
 404     ResourceMark rm;

 405 
 406     GrowableArray<ShenandoahHeapRegion*> empty_regions((int)_heap->num_regions());






 407 






 408     ShenandoahPrepareForCompactionObjectClosure cl(_preserved_marks->get(worker_id), empty_regions, from_region);
 409 
 410     while (from_region != NULL) {
 411       assert(is_candidate_region(from_region), "Sanity");
 412 
 413       cl.set_from_region(from_region);
 414       if (from_region->has_live()) {
 415         _heap->marked_object_iterate(from_region, &cl);
 416       }
 417 
 418       // Compacted the region to somewhere else? From-region is empty then.
 419       if (!cl.is_compact_same_region()) {
 420         empty_regions.append(from_region);
 421       }
 422       from_region = it.next();
 423     }
 424     cl.finish_region();
 425 
 426     // Mark all remaining regions as empty
 427     for (int pos = cl.empty_regions_pos(); pos < empty_regions.length(); ++pos) {
 428       ShenandoahHeapRegion* r = empty_regions.at(pos);
 429       r->set_new_top(r->bottom());
 430     }
 431   }
 432 };
 433 
 434 void ShenandoahFullGC::calculate_target_humongous_objects() {
 435   ShenandoahHeap* heap = ShenandoahHeap::heap();
 436 
 437   // Compute the new addresses for humongous objects. We need to do this after addresses
 438   // for regular objects are calculated, and we know what regions in heap suffix are
 439   // available for humongous moves.
 440   //
 441   // Scan the heap backwards, because we are compacting humongous regions towards the end.
 442   // Maintain the contiguous compaction window in [to_begin; to_end), so that we can slide
 443   // humongous start there.
 444   //
 445   // The complication is potential non-movable regions during the scan. If such region is
 446   // detected, then sliding restarts towards that non-movable region.
 447 
 448   size_t to_begin = heap->num_regions();
 449   size_t to_end = heap->num_regions();
 450 

 451   for (size_t c = heap->num_regions(); c > 0; c--) {
 452     ShenandoahHeapRegion *r = heap->get_region(c - 1);
 453     if (r->is_humongous_continuation() || (r->new_top() == r->bottom())) {
 454       // To-region candidate: record this, and continue scan
 455       to_begin = r->index();
 456       continue;
 457     }
 458 
 459     if (r->is_humongous_start() && r->is_stw_move_allowed()) {
 460       // From-region candidate: movable humongous region
 461       oop old_obj = cast_to_oop(r->bottom());
 462       size_t words_size = old_obj->size();
 463       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
 464 
 465       size_t start = to_end - num_regions;
 466 
 467       if (start >= to_begin && start != r->index()) {
 468         // Fits into current window, and the move is non-trivial. Record the move then, and continue scan.
 469         _preserved_marks->get(0)->push_if_necessary(old_obj, old_obj->mark());
 470         old_obj->forward_to(cast_to_oop(heap->get_region(start)->bottom()));
 471         to_end = start;
 472         continue;
 473       }
 474     }
 475 
 476     // Failed to fit. Scan starting from current region.
 477     to_begin = r->index();
 478     to_end = r->index();
 479   }
 480 }
 481 
 482 class ShenandoahEnsureHeapActiveClosure: public ShenandoahHeapRegionClosure {
 483 private:
 484   ShenandoahHeap* const _heap;
 485 
 486 public:
 487   ShenandoahEnsureHeapActiveClosure() : _heap(ShenandoahHeap::heap()) {}
 488   void heap_region_do(ShenandoahHeapRegion* r) {

 489     if (r->is_trash()) {
 490       r->recycle();
 491     }
 492     if (r->is_cset()) {

 493       r->make_regular_bypass();
 494     }
 495     if (r->is_empty_uncommitted()) {
 496       r->make_committed_bypass();
 497     }
 498     assert (r->is_committed(), "only committed regions in heap now, see region " SIZE_FORMAT, r->index());
 499 
 500     // Record current region occupancy: this communicates empty regions are free
 501     // to the rest of Full GC code.
 502     r->set_new_top(r->top());
 503   }
 504 };
 505 
 506 class ShenandoahTrashImmediateGarbageClosure: public ShenandoahHeapRegionClosure {
 507 private:
 508   ShenandoahHeap* const _heap;
 509   ShenandoahMarkingContext* const _ctx;
 510 
 511 public:
 512   ShenandoahTrashImmediateGarbageClosure() :
 513     _heap(ShenandoahHeap::heap()),
 514     _ctx(ShenandoahHeap::heap()->complete_marking_context()) {}
 515 
 516   void heap_region_do(ShenandoahHeapRegion* r) {
 517     if (r->is_humongous_start()) {
 518       oop humongous_obj = cast_to_oop(r->bottom());
 519       if (!_ctx->is_marked(humongous_obj)) {
 520         assert(!r->has_live(),
 521                "Region " SIZE_FORMAT " is not marked, should not have live", r->index());
 522         _heap->trash_humongous_region_at(r);
 523       } else {
 524         assert(r->has_live(),
 525                "Region " SIZE_FORMAT " should have live", r->index());
 526       }
 527     } else if (r->is_humongous_continuation()) {
 528       // If we hit continuation, the non-live humongous starts should have been trashed already
 529       assert(r->humongous_start_region()->has_live(),
 530              "Region " SIZE_FORMAT " should have live", r->index());
 531     } else if (r->is_regular()) {
 532       if (!r->has_live()) {
 533         r->make_trash_immediate();





 534       }
 535     }


 536   }
 537 };
 538 
 539 void ShenandoahFullGC::distribute_slices(ShenandoahHeapRegionSet** worker_slices) {
 540   ShenandoahHeap* heap = ShenandoahHeap::heap();
 541 
 542   uint n_workers = heap->workers()->active_workers();
 543   size_t n_regions = heap->num_regions();
 544 
 545   // What we want to accomplish: have the dense prefix of data, while still balancing
 546   // out the parallel work.
 547   //
 548   // Assuming the amount of work is driven by the live data that needs moving, we can slice
 549   // the entire heap into equal-live-sized prefix slices, and compact into them. So, each
 550   // thread takes all regions in its prefix subset, and then it takes some regions from
 551   // the tail.
 552   //
 553   // Tail region selection becomes interesting.
 554   //
 555   // First, we want to distribute the regions fairly between the workers, and those regions

 682   GCTraceTime(Info, gc, phases) time("Phase 2: Compute new object addresses", _gc_timer);
 683   ShenandoahGCPhase calculate_address_phase(ShenandoahPhaseTimings::full_gc_calculate_addresses);
 684 
 685   ShenandoahHeap* heap = ShenandoahHeap::heap();
 686 
 687   // About to figure out which regions can be compacted, make sure pinning status
 688   // had been updated in GC prologue.
 689   heap->assert_pinned_region_status();
 690 
 691   {
 692     // Trash the immediately collectible regions before computing addresses
 693     ShenandoahTrashImmediateGarbageClosure tigcl;
 694     heap->heap_region_iterate(&tigcl);
 695 
 696     // Make sure regions are in good state: committed, active, clean.
 697     // This is needed because we are potentially sliding the data through them.
 698     ShenandoahEnsureHeapActiveClosure ecl;
 699     heap->heap_region_iterate(&ecl);
 700   }
 701 





 702   // Compute the new addresses for regular objects
 703   {
 704     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_regular);
 705 
 706     distribute_slices(worker_slices);
 707 
 708     ShenandoahPrepareForCompactionTask task(_preserved_marks, worker_slices);



 709     heap->workers()->run_task(&task);
 710   }
 711 
 712   // Compute the new addresses for humongous objects
 713   {
 714     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_humong);
 715     calculate_target_humongous_objects();
 716   }
 717 }
 718 
 719 class ShenandoahAdjustPointersClosure : public MetadataVisitingOopIterateClosure {
 720 private:
 721   ShenandoahHeap* const _heap;
 722   ShenandoahMarkingContext* const _ctx;
 723 
 724   template <class T>
 725   inline void do_oop_work(T* p) {
 726     T o = RawAccess<>::oop_load(p);
 727     if (!CompressedOops::is_null(o)) {
 728       oop obj = CompressedOops::decode_not_null(o);

 762 
 763 class ShenandoahAdjustPointersTask : public WorkerTask {
 764 private:
 765   ShenandoahHeap*          const _heap;
 766   ShenandoahRegionIterator       _regions;
 767 
 768 public:
 769   ShenandoahAdjustPointersTask() :
 770     WorkerTask("Shenandoah Adjust Pointers"),
 771     _heap(ShenandoahHeap::heap()) {
 772   }
 773 
 774   void work(uint worker_id) {
 775     ShenandoahParallelWorkerSession worker_session(worker_id);
 776     ShenandoahAdjustPointersObjectClosure obj_cl;
 777     ShenandoahHeapRegion* r = _regions.next();
 778     while (r != NULL) {
 779       if (!r->is_humongous_continuation() && r->has_live()) {
 780         _heap->marked_object_iterate(r, &obj_cl);
 781       }







 782       r = _regions.next();
 783     }
 784   }
 785 };
 786 
 787 class ShenandoahAdjustRootPointersTask : public WorkerTask {
 788 private:
 789   ShenandoahRootAdjuster* _rp;
 790   PreservedMarksSet* _preserved_marks;
 791 public:
 792   ShenandoahAdjustRootPointersTask(ShenandoahRootAdjuster* rp, PreservedMarksSet* preserved_marks) :
 793     WorkerTask("Shenandoah Adjust Root Pointers"),
 794     _rp(rp),
 795     _preserved_marks(preserved_marks) {}
 796 
 797   void work(uint worker_id) {
 798     ShenandoahParallelWorkerSession worker_session(worker_id);
 799     ShenandoahAdjustPointersClosure cl;
 800     _rp->roots_do(worker_id, &cl);
 801     _preserved_marks->get(worker_id)->adjust_during_full_gc();

 874         _heap->marked_object_iterate(r, &cl);
 875       }
 876       r->set_top(r->new_top());
 877       r = slice.next();
 878     }
 879   }
 880 };
 881 
 882 class ShenandoahPostCompactClosure : public ShenandoahHeapRegionClosure {
 883 private:
 884   ShenandoahHeap* const _heap;
 885   size_t _live;
 886 
 887 public:
 888   ShenandoahPostCompactClosure() : _heap(ShenandoahHeap::heap()), _live(0) {
 889     _heap->free_set()->clear();
 890   }
 891 
 892   void heap_region_do(ShenandoahHeapRegion* r) {
 893     assert (!r->is_cset(), "cset regions should have been demoted already");

 894 
 895     // Need to reset the complete-top-at-mark-start pointer here because
 896     // the complete marking bitmap is no longer valid. This ensures
 897     // size-based iteration in marked_object_iterate().
 898     // NOTE: See blurb at ShenandoahMCResetCompleteBitmapTask on why we need to skip
 899     // pinned regions.
 900     if (!r->is_pinned()) {
 901       _heap->complete_marking_context()->reset_top_at_mark_start(r);
 902     }
 903 
 904     size_t live = r->used();
 905 
 906     // Make empty regions that have been allocated into regular
 907     if (r->is_empty() && live > 0) {




 908       r->make_regular_bypass();
 909     }
 910 
 911     // Reclaim regular regions that became empty
 912     if (r->is_regular() && live == 0) {
 913       r->make_trash();
 914     }
 915 
 916     // Recycle all trash regions
 917     if (r->is_trash()) {
 918       live = 0;
 919       r->recycle();
 920     }
 921 









 922     r->set_live_data(live);
 923     r->reset_alloc_metadata();
 924     _live += live;
 925   }
 926 
 927   size_t get_live() {
 928     return _live;
 929   }
 930 };
 931 
 932 void ShenandoahFullGC::compact_humongous_objects() {
 933   // Compact humongous regions, based on their fwdptr objects.
 934   //
 935   // This code is serial, because doing the in-slice parallel sliding is tricky. In most cases,
 936   // humongous regions are already compacted, and do not require further moves, which alleviates
 937   // sliding costs. We may consider doing this in parallel in future.
 938 
 939   ShenandoahHeap* heap = ShenandoahHeap::heap();
 940 
 941   for (size_t c = heap->num_regions(); c > 0; c--) {
 942     ShenandoahHeapRegion* r = heap->get_region(c - 1);
 943     if (r->is_humongous_start()) {
 944       oop old_obj = cast_to_oop(r->bottom());
 945       if (!old_obj->is_forwarded()) {
 946         // No need to move the object, it stays at the same slot
 947         continue;
 948       }
 949       size_t words_size = old_obj->size();
 950       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
 951 
 952       size_t old_start = r->index();
 953       size_t old_end   = old_start + num_regions - 1;
 954       size_t new_start = heap->heap_region_index_containing(old_obj->forwardee());
 955       size_t new_end   = new_start + num_regions - 1;
 956       assert(old_start != new_start, "must be real move");
 957       assert(r->is_stw_move_allowed(), "Region " SIZE_FORMAT " should be movable", r->index());
 958 
 959       Copy::aligned_conjoint_words(r->bottom(), heap->get_region(new_start)->bottom(), words_size);
 960       ContinuationGCSupport::relativize_stack_chunk(cast_to_oop<HeapWord*>(r->bottom()));





 961 
 962       oop new_obj = cast_to_oop(heap->get_region(new_start)->bottom());
 963       new_obj->init_mark();
 964 
 965       {

 966         for (size_t c = old_start; c <= old_end; c++) {
 967           ShenandoahHeapRegion* r = heap->get_region(c);

 968           r->make_regular_bypass();
 969           r->set_top(r->bottom());
 970         }
 971 
 972         for (size_t c = new_start; c <= new_end; c++) {
 973           ShenandoahHeapRegion* r = heap->get_region(c);
 974           if (c == new_start) {
 975             r->make_humongous_start_bypass();
 976           } else {
 977             r->make_humongous_cont_bypass();
 978           }
 979 
 980           // Trailing region may be non-full, record the remainder there
 981           size_t remainder = words_size & ShenandoahHeapRegion::region_size_words_mask();
 982           if ((c == new_end) && (remainder != 0)) {
 983             r->set_top(r->bottom() + remainder);
 984           } else {
 985             r->set_top(r->end());
 986           }
 987 
 988           r->reset_alloc_metadata();
 989         }
 990       }
 991     }
 992   }
 993 }
 994 
 995 // This is slightly different to ShHeap::reset_next_mark_bitmap:
 996 // we need to remain able to walk pinned regions.
 997 // Since pinned region do not move and don't get compacted, we will get holes with

1036   }
1037 
1038   // Compact humongous objects after regular object moves
1039   {
1040     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_humong);
1041     compact_humongous_objects();
1042   }
1043 
1044   // Reset complete bitmap. We're about to reset the complete-top-at-mark-start pointer
1045   // and must ensure the bitmap is in sync.
1046   {
1047     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_reset_complete);
1048     ShenandoahMCResetCompleteBitmapTask task;
1049     heap->workers()->run_task(&task);
1050   }
1051 
1052   // Bring regions in proper states after the collection, and set heap properties.
1053   {
1054     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_rebuild);
1055 





1056     ShenandoahPostCompactClosure post_compact;
1057     heap->heap_region_iterate(&post_compact);
1058     heap->set_used(post_compact.get_live());




1059 
1060     heap->collection_set()->clear();
1061     heap->free_set()->rebuild();
1062   }
1063 
1064   heap->clear_cancelled_gc();
1065 }

  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/tlab_globals.hpp"
  32 #include "gc/shared/workerThread.hpp"
  33 #include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"
  34 #include "gc/shenandoah/shenandoahConcurrentGC.hpp"
  35 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  36 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  37 #include "gc/shenandoah/shenandoahFullGC.hpp"
  38 #include "gc/shenandoah/shenandoahGeneration.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/shenandoahOldGeneration.hpp"
  48 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
  49 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
  50 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
  51 #include "gc/shenandoah/shenandoahSTWMark.hpp"
  52 #include "gc/shenandoah/shenandoahUtils.hpp"
  53 #include "gc/shenandoah/shenandoahVerifier.hpp"
  54 #include "gc/shenandoah/shenandoahVMOperations.hpp"
  55 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
  56 #include "gc/shenandoah/shenandoahYoungGeneration.hpp"
  57 #include "memory/metaspaceUtils.hpp"
  58 #include "memory/universe.hpp"
  59 #include "oops/compressedOops.inline.hpp"
  60 #include "oops/oop.inline.hpp"
  61 #include "runtime/javaThread.hpp"
  62 #include "runtime/orderAccess.hpp"
  63 #include "runtime/vmThread.hpp"
  64 #include "utilities/copy.hpp"
  65 #include "utilities/events.hpp"
  66 #include "utilities/growableArray.hpp"
  67 
  68 // After Full GC is done, reconstruct the remembered set by iterating over OLD regions,
  69 // registering all objects between bottom() and top(), and setting remembered set cards to
  70 // DIRTY if they hold interesting pointers.
  71 class ShenandoahReconstructRememberedSetTask : public WorkerTask {
  72 private:
  73   ShenandoahRegionIterator _regions;
  74 
  75 public:
  76   ShenandoahReconstructRememberedSetTask() :
  77     WorkerTask("Shenandoah Reset Bitmap") { }
  78 
  79   void work(uint worker_id) {
  80     ShenandoahParallelWorkerSession worker_session(worker_id);
  81     ShenandoahHeapRegion* r = _regions.next();
  82     ShenandoahHeap* heap = ShenandoahHeap::heap();
  83     RememberedScanner* scanner = heap->card_scan();
  84     ShenandoahSetRememberedCardsToDirtyClosure dirty_cards_for_interesting_pointers;
  85 
  86     while (r != NULL) {
  87       if (r->is_old() && r->is_active()) {
  88         HeapWord* obj_addr = r->bottom();
  89         if (r->is_humongous_start()) {
  90           // First, clear the remembered set
  91           oop obj = cast_to_oop(obj_addr);
  92           size_t size = obj->size();
  93           HeapWord* end_object = r->bottom() + size;
  94 
  95           // First, clear the remembered set for all spanned humongous regions
  96           size_t num_regions = (size + ShenandoahHeapRegion::region_size_words() - 1) / ShenandoahHeapRegion::region_size_words();
  97           size_t region_span = num_regions * ShenandoahHeapRegion::region_size_words();
  98           scanner->reset_remset(r->bottom(), region_span);
  99           size_t region_index = r->index();
 100           ShenandoahHeapRegion* humongous_region = heap->get_region(region_index);
 101           while (num_regions-- != 0) {
 102             scanner->reset_object_range(humongous_region->bottom(), humongous_region->end());
 103             region_index++;
 104             humongous_region = heap->get_region(region_index);
 105           }
 106 
 107           // Then register the humongous object and DIRTY relevant remembered set cards
 108           scanner->register_object_wo_lock(obj_addr);
 109           obj->oop_iterate(&dirty_cards_for_interesting_pointers);
 110         } else if (!r->is_humongous()) {
 111           // First, clear the remembered set
 112           scanner->reset_remset(r->bottom(), ShenandoahHeapRegion::region_size_words());
 113           scanner->reset_object_range(r->bottom(), r->end());
 114 
 115           // Then iterate over all objects, registering object and DIRTYing relevant remembered set cards
 116           HeapWord* t = r->top();
 117           while (obj_addr < t) {
 118             oop obj = cast_to_oop(obj_addr);
 119             size_t size = obj->size();
 120             scanner->register_object_wo_lock(obj_addr);
 121             obj_addr += obj->oop_iterate_size(&dirty_cards_for_interesting_pointers);
 122           }
 123         } // else, ignore humongous continuation region
 124       }
 125       // else, this region is FREE or YOUNG or inactive and we can ignore it.
 126       r = _regions.next();
 127     }
 128   }
 129 };
 130 
 131 ShenandoahFullGC::ShenandoahFullGC() :
 132   _gc_timer(ShenandoahHeap::heap()->gc_timer()),
 133   _preserved_marks(new PreservedMarksSet(true)) {}
 134 
 135 bool ShenandoahFullGC::collect(GCCause::Cause cause) {
 136   vmop_entry_full(cause);
 137   // Always success
 138   return true;
 139 }
 140 
 141 void ShenandoahFullGC::vmop_entry_full(GCCause::Cause cause) {
 142   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 143   TraceCollectorStats tcs(heap->monitoring_support()->full_stw_collection_counters());
 144   ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::full_gc_gross);
 145 
 146   heap->try_inject_alloc_failure();
 147   VM_ShenandoahFullGC op(cause, this);
 148   VMThread::execute(&op);
 149 }
 150 
 151 void ShenandoahFullGC::entry_full(GCCause::Cause cause) {
 152   static const char* msg = "Pause Full";
 153   ShenandoahPausePhase gc_phase(msg, ShenandoahPhaseTimings::full_gc, true /* log_heap_usage */);
 154   EventMark em("%s", msg);
 155 
 156   ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),
 157                               ShenandoahWorkerPolicy::calc_workers_for_fullgc(),
 158                               "full gc");
 159 
 160   op_full(cause);
 161 }
 162 
 163 void ShenandoahFullGC::op_full(GCCause::Cause cause) {
 164   ShenandoahHeap* const heap = ShenandoahHeap::heap();
 165   ShenandoahMetricsSnapshot metrics;
 166   metrics.snap_before();
 167 
 168   // Perform full GC
 169   do_it(cause);
 170 
 171   metrics.snap_after();
 172   if (heap->mode()->is_generational()) {
 173     size_t old_available = heap->old_generation()->available();
 174     size_t young_available = heap->young_generation()->available();
 175     log_info(gc, ergo)("At end of Full GC, old_available: " SIZE_FORMAT "%s, young_available: " SIZE_FORMAT "%s",
 176                        byte_size_in_proper_unit(old_available), proper_unit_for_byte_size(old_available),
 177                        byte_size_in_proper_unit(young_available), proper_unit_for_byte_size(young_available));
 178   }
 179   if (metrics.is_good_progress()) {
 180     ShenandoahHeap::heap()->notify_gc_progress();
 181   } else {
 182     // Nothing to do. Tell the allocation path that we have failed to make
 183     // progress, and it can finally fail.
 184     ShenandoahHeap::heap()->notify_gc_no_progress();
 185   }
 186 }
 187 
 188 void ShenandoahFullGC::do_it(GCCause::Cause gc_cause) {
 189   ShenandoahHeap* heap = ShenandoahHeap::heap();
 190   // Since we may arrive here from degenerated GC failure of either young or old, establish generation as GLOBAL.
 191   heap->set_gc_generation(heap->global_generation());
 192 
 193   if (heap->mode()->is_generational()) {
 194     // There will be no concurrent allocations during full GC so reset these coordination variables.
 195     heap->young_generation()->unadjust_available();
 196     heap->old_generation()->unadjust_available();
 197     // No need to old_gen->increase_used().  That was done when plabs were allocated, accounting for both old evacs and promotions.
 198 
 199     heap->set_alloc_supplement_reserve(0);
 200     heap->set_young_evac_reserve(0);
 201     heap->set_old_evac_reserve(0);
 202     heap->reset_old_evac_expended();
 203     heap->set_promoted_reserve(0);
 204 
 205     // Full GC supersedes any marking or coalescing in old generation.
 206     heap->cancel_old_gc();
 207   }
 208 
 209   if (ShenandoahVerify) {
 210     heap->verifier()->verify_before_fullgc();
 211   }
 212 
 213   if (VerifyBeforeGC) {
 214     Universe::verify();
 215   }
 216 
 217   // Degenerated GC may carry concurrent root flags when upgrading to
 218   // full GC. We need to reset it before mutators resume.
 219   heap->set_concurrent_strong_root_in_progress(false);
 220   heap->set_concurrent_weak_root_in_progress(false);
 221 
 222   heap->set_full_gc_in_progress(true);
 223 
 224   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at a safepoint");
 225   assert(Thread::current()->is_VM_thread(), "Do full GC only while world is stopped");
 226 
 227   {

 231 
 232   {
 233     ShenandoahGCPhase prepare_phase(ShenandoahPhaseTimings::full_gc_prepare);
 234     // Full GC is supposed to recover from any GC state:
 235 
 236     // a0. Remember if we have forwarded objects
 237     bool has_forwarded_objects = heap->has_forwarded_objects();
 238 
 239     // a1. Cancel evacuation, if in progress
 240     if (heap->is_evacuation_in_progress()) {
 241       heap->set_evacuation_in_progress(false);
 242     }
 243     assert(!heap->is_evacuation_in_progress(), "sanity");
 244 
 245     // a2. Cancel update-refs, if in progress
 246     if (heap->is_update_refs_in_progress()) {
 247       heap->set_update_refs_in_progress(false);
 248     }
 249     assert(!heap->is_update_refs_in_progress(), "sanity");
 250 
 251     // b. Cancel all concurrent marks, if in progress
 252     if (heap->is_concurrent_mark_in_progress()) {
 253       heap->cancel_concurrent_mark();

 254     }
 255     assert(!heap->is_concurrent_mark_in_progress(), "sanity");
 256 
 257     // c. Update roots if this full GC is due to evac-oom, which may carry from-space pointers in roots.
 258     if (has_forwarded_objects) {
 259       update_roots(true /*full_gc*/);
 260     }
 261 
 262     // d. Reset the bitmaps for new marking
 263     heap->global_generation()->reset_mark_bitmap();
 264     assert(heap->marking_context()->is_bitmap_clear(), "sanity");
 265     assert(!heap->global_generation()->is_mark_complete(), "sanity");
 266 
 267     // e. Abandon reference discovery and clear all discovered references.
 268     ShenandoahReferenceProcessor* rp = heap->global_generation()->ref_processor();
 269     rp->abandon_partial_discovery();
 270 
 271     // f. Sync pinned region status from the CP marks
 272     heap->sync_pinned_region_status();
 273 
 274     // The rest of prologue:
 275     _preserved_marks->init(heap->workers()->active_workers());
 276 
 277     assert(heap->has_forwarded_objects() == has_forwarded_objects, "This should not change");
 278   }
 279 
 280   if (UseTLAB) {
 281     // TODO: Do we need to explicitly retire PLABs?
 282     heap->gclabs_retire(ResizeTLAB);
 283     heap->tlabs_retire(ResizeTLAB);
 284   }
 285 
 286   OrderAccess::fence();
 287 
 288   phase1_mark_heap();
 289 
 290   // Once marking is done, which may have fixed up forwarded objects, we can drop it.
 291   // Coming out of Full GC, we would not have any forwarded objects.
 292   // This also prevents resolves with fwdptr from kicking in while adjusting pointers in phase3.
 293   heap->set_has_forwarded_objects(false);
 294 
 295   heap->set_full_gc_move_in_progress(true);
 296 
 297   // Setup workers for the rest
 298   OrderAccess::fence();
 299 
 300   // Initialize worker slices
 301   ShenandoahHeapRegionSet** worker_slices = NEW_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, heap->max_workers(), mtGC);

 304   }
 305 
 306   {
 307     // The rest of code performs region moves, where region status is undefined
 308     // until all phases run together.
 309     ShenandoahHeapLocker lock(heap->lock());
 310 
 311     phase2_calculate_target_addresses(worker_slices);
 312 
 313     OrderAccess::fence();
 314 
 315     phase3_update_references();
 316 
 317     phase4_compact_objects(worker_slices);
 318   }
 319 
 320   {
 321     // Epilogue
 322     _preserved_marks->restore(heap->workers());
 323     _preserved_marks->reclaim();
 324 
 325     if (heap->mode()->is_generational()) {
 326       ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_reconstruct_remembered_set);
 327       ShenandoahReconstructRememberedSetTask task;
 328       heap->workers()->run_task(&task);
 329     }
 330   }
 331 
 332   // Resize metaspace
 333   MetaspaceGC::compute_new_size();
 334 
 335   // Free worker slices
 336   for (uint i = 0; i < heap->max_workers(); i++) {
 337     delete worker_slices[i];
 338   }
 339   FREE_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, worker_slices);
 340 
 341   heap->set_full_gc_move_in_progress(false);
 342   heap->set_full_gc_in_progress(false);
 343 
 344   if (ShenandoahVerify) {
 345     if (heap->mode()->is_generational()) {
 346       heap->verifier()->verify_after_generational_fullgc();
 347     } else {
 348       heap->verifier()->verify_after_fullgc();
 349     }
 350   }
 351 
 352   if (VerifyAfterGC) {
 353     Universe::verify();
 354   }
 355 
 356   {
 357     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdump_post);
 358     heap->post_full_gc_dump(_gc_timer);
 359   }
 360 }
 361 
 362 class ShenandoahPrepareForMarkClosure: public ShenandoahHeapRegionClosure {
 363 private:
 364   ShenandoahMarkingContext* const _ctx;
 365 
 366 public:
 367   ShenandoahPrepareForMarkClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
 368 
 369   void heap_region_do(ShenandoahHeapRegion *r) {
 370     if (r->affiliation() != FREE) {
 371       _ctx->capture_top_at_mark_start(r);
 372       r->clear_live_data();
 373     }
 374   }
 375 
 376   bool is_thread_safe() { return true; }
 377 };
 378 
 379 void ShenandoahFullGC::phase1_mark_heap() {
 380   GCTraceTime(Info, gc, phases) time("Phase 1: Mark live objects", _gc_timer);
 381   ShenandoahGCPhase mark_phase(ShenandoahPhaseTimings::full_gc_mark);
 382 
 383   ShenandoahHeap* heap = ShenandoahHeap::heap();
 384 
 385   ShenandoahPrepareForMarkClosure cl;
 386   heap->parallel_heap_region_iterate(&cl);
 387 
 388   heap->set_unload_classes(heap->global_generation()->heuristics()->can_unload_classes());
 389 
 390   ShenandoahReferenceProcessor* rp = heap->global_generation()->ref_processor();
 391   // enable ("weak") refs discovery
 392   rp->set_soft_reference_policy(true); // forcefully purge all soft references
 393 
 394   ShenandoahSTWMark mark(heap->global_generation(), true /*full_gc*/);
 395   mark.mark();
 396   heap->parallel_cleaning(true /* full_gc */);
 397 }
 398 
 399 class ShenandoahPrepareForCompactionTask : public WorkerTask {
 400 private:
 401   PreservedMarksSet*        const _preserved_marks;
 402   ShenandoahHeap*           const _heap;
 403   ShenandoahHeapRegionSet** const _worker_slices;
 404   size_t                    const _num_workers;
 405 
 406 public:
 407   ShenandoahPrepareForCompactionTask(PreservedMarksSet *preserved_marks, ShenandoahHeapRegionSet **worker_slices,
 408                                      size_t num_workers);
 409 
 410   static bool is_candidate_region(ShenandoahHeapRegion* r) {
 411     // Empty region: get it into the slice to defragment the slice itself.
 412     // We could have skipped this without violating correctness, but we really
 413     // want to compact all live regions to the start of the heap, which sometimes
 414     // means moving them into the fully empty regions.
 415     if (r->is_empty()) return true;
 416 
 417     // Can move the region, and this is not the humongous region. Humongous
 418     // moves are special cased here, because their moves are handled separately.
 419     return r->is_stw_move_allowed() && !r->is_humongous();
 420   }
 421 
 422   void work(uint worker_id);
 423 };
 424 
 425 class ShenandoahPrepareForGenerationalCompactionObjectClosure : public ObjectClosure {
 426 private:
 427   ShenandoahPrepareForCompactionTask* _compactor;
 428   PreservedMarks*          const _preserved_marks;
 429   ShenandoahHeap*          const _heap;
 430 
 431   // _empty_regions is a thread-local list of heap regions that have been completely emptied by this worker thread's
 432   // compaction efforts.  The worker thread that drives these efforts adds compacted regions to this list if the
 433   // region has not been compacted onto itself.
 434   GrowableArray<ShenandoahHeapRegion*>& _empty_regions;
 435   int _empty_regions_pos;
 436   ShenandoahHeapRegion*          _old_to_region;
 437   ShenandoahHeapRegion*          _young_to_region;
 438   ShenandoahHeapRegion*          _from_region;
 439   ShenandoahRegionAffiliation    _from_affiliation;
 440   HeapWord*                      _old_compact_point;
 441   HeapWord*                      _young_compact_point;
 442   uint                           _worker_id;
 443 
 444 public:
 445   ShenandoahPrepareForGenerationalCompactionObjectClosure(ShenandoahPrepareForCompactionTask* compactor,
 446                                                           PreservedMarks* preserved_marks,
 447                                                           GrowableArray<ShenandoahHeapRegion*>& empty_regions,
 448                                                           ShenandoahHeapRegion* old_to_region,
 449                                                           ShenandoahHeapRegion* young_to_region, uint worker_id) :
 450       _compactor(compactor),
 451       _preserved_marks(preserved_marks),
 452       _heap(ShenandoahHeap::heap()),
 453       _empty_regions(empty_regions),
 454       _empty_regions_pos(0),
 455       _old_to_region(old_to_region),
 456       _young_to_region(young_to_region),
 457       _from_region(NULL),
 458       _old_compact_point((old_to_region != nullptr)? old_to_region->bottom(): nullptr),
 459       _young_compact_point((young_to_region != nullptr)? young_to_region->bottom(): nullptr),
 460       _worker_id(worker_id) {}
 461 
 462   void set_from_region(ShenandoahHeapRegion* from_region) {
 463     _from_region = from_region;
 464     _from_affiliation = from_region->affiliation();
 465     if (_from_region->has_live()) {
 466       if (_from_affiliation == ShenandoahRegionAffiliation::OLD_GENERATION) {
 467         if (_old_to_region == nullptr) {
 468           _old_to_region = from_region;
 469           _old_compact_point = from_region->bottom();
 470         }
 471       } else {
 472         assert(_from_affiliation == ShenandoahRegionAffiliation::YOUNG_GENERATION, "from_region must be OLD or YOUNG");
 473         if (_young_to_region == nullptr) {
 474           _young_to_region = from_region;
 475           _young_compact_point = from_region->bottom();
 476         }
 477       }
 478     } // else, we won't iterate over this _from_region so we don't need to set up to region to hold copies
 479   }
 480 
 481   void finish() {
 482     finish_old_region();
 483     finish_young_region();
 484   }
 485 
 486   void finish_old_region() {
 487     if (_old_to_region != nullptr) {
 488       log_debug(gc)("Planned compaction into Old Region " SIZE_FORMAT ", used: " SIZE_FORMAT " tabulated by worker %u",
 489                     _old_to_region->index(), _old_compact_point - _old_to_region->bottom(), _worker_id);
 490       _old_to_region->set_new_top(_old_compact_point);
 491       _old_to_region = nullptr;
 492     }
 493   }
 494 
 495   void finish_young_region() {
 496     if (_young_to_region != nullptr) {
 497       log_debug(gc)("Worker %u planned compaction into Young Region " SIZE_FORMAT ", used: " SIZE_FORMAT,
 498                     _worker_id, _young_to_region->index(), _young_compact_point - _young_to_region->bottom());
 499       _young_to_region->set_new_top(_young_compact_point);
 500       _young_to_region = nullptr;
 501     }
 502   }
 503 
 504   bool is_compact_same_region() {
 505     return (_from_region == _old_to_region) || (_from_region == _young_to_region);
 506   }
 507 
 508   int empty_regions_pos() {
 509     return _empty_regions_pos;
 510   }
 511 
 512   void do_object(oop p) {
 513     assert(_from_region != NULL, "must set before work");
 514     assert((_from_region->bottom() <= cast_from_oop<HeapWord*>(p)) && (cast_from_oop<HeapWord*>(p) < _from_region->top()),
 515            "Object must reside in _from_region");
 516     assert(_heap->complete_marking_context()->is_marked(p), "must be marked");
 517     assert(!_heap->complete_marking_context()->allocated_after_mark_start(p), "must be truly marked");
 518 
 519     size_t obj_size = p->size();
 520     uint from_region_age = _from_region->age();
 521     uint object_age = p->age();
 522 
 523     bool promote_object = false;
 524     if ((_from_affiliation == ShenandoahRegionAffiliation::YOUNG_GENERATION) &&
 525         (from_region_age + object_age >= InitialTenuringThreshold)) {
 526       if ((_old_to_region != nullptr) && (_old_compact_point + obj_size > _old_to_region->end())) {
 527         finish_old_region();
 528         _old_to_region = nullptr;
 529       }
 530       if (_old_to_region == nullptr) {
 531         if (_empty_regions_pos < _empty_regions.length()) {
 532           ShenandoahHeapRegion* new_to_region = _empty_regions.at(_empty_regions_pos);
 533           _empty_regions_pos++;
 534           new_to_region->set_affiliation(OLD_GENERATION);
 535           _old_to_region = new_to_region;
 536           _old_compact_point = _old_to_region->bottom();
 537           promote_object = true;
 538         }
 539         // Else this worker thread does not yet have any empty regions into which this aged object can be promoted so
 540         // we leave promote_object as false, deferring the promotion.
 541       } else {
 542         promote_object = true;
 543       }
 544     }
 545 
 546     if (promote_object || (_from_affiliation == ShenandoahRegionAffiliation::OLD_GENERATION)) {
 547       assert(_old_to_region != nullptr, "_old_to_region should not be NULL when evacuating to OLD region");
 548       if (_old_compact_point + obj_size > _old_to_region->end()) {
 549         ShenandoahHeapRegion* new_to_region;
 550 
 551         log_debug(gc)("Worker %u finishing old region " SIZE_FORMAT ", compact_point: " PTR_FORMAT ", obj_size: " SIZE_FORMAT
 552                       ", &compact_point[obj_size]: " PTR_FORMAT ", region end: " PTR_FORMAT,  _worker_id, _old_to_region->index(),
 553                       p2i(_old_compact_point), obj_size, p2i(_old_compact_point + obj_size), p2i(_old_to_region->end()));
 554 
 555         // Object does not fit.  Get a new _old_to_region.
 556         finish_old_region();
 557         if (_empty_regions_pos < _empty_regions.length()) {
 558           new_to_region = _empty_regions.at(_empty_regions_pos);
 559           _empty_regions_pos++;
 560           new_to_region->set_affiliation(OLD_GENERATION);
 561         } else {
 562           // If we've exhausted the previously selected _old_to_region, we know that the _old_to_region is distinct
 563           // from _from_region.  That's because there is always room for _from_region to be compacted into itself.
 564           // Since we're out of empty regions, let's use _from_region to hold the results of its own compaction.
 565           new_to_region = _from_region;
 566         }
 567 
 568         assert(new_to_region != _old_to_region, "must not reuse same OLD to-region");
 569         assert(new_to_region != NULL, "must not be NULL");
 570         _old_to_region = new_to_region;
 571         _old_compact_point = _old_to_region->bottom();
 572       }
 573 
 574       // Object fits into current region, record new location:
 575       assert(_old_compact_point + obj_size <= _old_to_region->end(), "must fit");
 576       shenandoah_assert_not_forwarded(NULL, p);
 577       _preserved_marks->push_if_necessary(p, p->mark());
 578       p->forward_to(cast_to_oop(_old_compact_point));
 579       _old_compact_point += obj_size;
 580     } else {
 581       assert(_from_affiliation == ShenandoahRegionAffiliation::YOUNG_GENERATION,
 582              "_from_region must be OLD_GENERATION or YOUNG_GENERATION");
 583       assert(_young_to_region != nullptr, "_young_to_region should not be NULL when compacting YOUNG _from_region");
 584 
 585       // After full gc compaction, all regions have age 0.  Embed the region's age into the object's age in order to preserve
 586       // tenuring progress.
 587       _heap->increase_object_age(p, from_region_age + 1);
 588 
 589       if (_young_compact_point + obj_size > _young_to_region->end()) {
 590         ShenandoahHeapRegion* new_to_region;
 591 
 592         log_debug(gc)("Worker %u finishing young region " SIZE_FORMAT ", compact_point: " PTR_FORMAT ", obj_size: " SIZE_FORMAT
 593                       ", &compact_point[obj_size]: " PTR_FORMAT ", region end: " PTR_FORMAT,  _worker_id, _young_to_region->index(),
 594                       p2i(_young_compact_point), obj_size, p2i(_young_compact_point + obj_size), p2i(_young_to_region->end()));
 595 
 596         // Object does not fit.  Get a new _young_to_region.
 597         finish_young_region();
 598         if (_empty_regions_pos < _empty_regions.length()) {
 599           new_to_region = _empty_regions.at(_empty_regions_pos);
 600           _empty_regions_pos++;
 601           new_to_region->set_affiliation(YOUNG_GENERATION);
 602         } else {
 603           // If we've exhausted the previously selected _young_to_region, we know that the _young_to_region is distinct
 604           // from _from_region.  That's because there is always room for _from_region to be compacted into itself.
 605           // Since we're out of empty regions, let's use _from_region to hold the results of its own compaction.
 606           new_to_region = _from_region;
 607         }
 608 
 609         assert(new_to_region != _young_to_region, "must not reuse same OLD to-region");
 610         assert(new_to_region != NULL, "must not be NULL");
 611         _young_to_region = new_to_region;
 612         _young_compact_point = _young_to_region->bottom();
 613       }
 614 
 615       // Object fits into current region, record new location:
 616       assert(_young_compact_point + obj_size <= _young_to_region->end(), "must fit");
 617       shenandoah_assert_not_forwarded(NULL, p);
 618       _preserved_marks->push_if_necessary(p, p->mark());
 619       p->forward_to(cast_to_oop(_young_compact_point));
 620       _young_compact_point += obj_size;
 621     }
 622   }
 623 };
 624 
 625 
 626 class ShenandoahPrepareForCompactionObjectClosure : public ObjectClosure {
 627 private:
 628   PreservedMarks*          const _preserved_marks;
 629   ShenandoahHeap*          const _heap;
 630   GrowableArray<ShenandoahHeapRegion*>& _empty_regions;
 631   int _empty_regions_pos;
 632   ShenandoahHeapRegion*          _to_region;
 633   ShenandoahHeapRegion*          _from_region;
 634   HeapWord* _compact_point;
 635 
 636 public:
 637   ShenandoahPrepareForCompactionObjectClosure(PreservedMarks* preserved_marks,
 638                                               GrowableArray<ShenandoahHeapRegion*>& empty_regions,
 639                                               ShenandoahHeapRegion* to_region) :
 640     _preserved_marks(preserved_marks),
 641     _heap(ShenandoahHeap::heap()),
 642     _empty_regions(empty_regions),
 643     _empty_regions_pos(0),
 644     _to_region(to_region),
 645     _from_region(NULL),
 646     _compact_point(to_region->bottom()) {}
 647 
 648   void set_from_region(ShenandoahHeapRegion* from_region) {
 649     _from_region = from_region;
 650   }
 651 
 652   void finish_region() {
 653     assert(_to_region != NULL, "should not happen");
 654     assert(!_heap->mode()->is_generational(), "Generational GC should use different Closure");
 655     _to_region->set_new_top(_compact_point);
 656   }
 657 
 658   bool is_compact_same_region() {
 659     return _from_region == _to_region;
 660   }
 661 
 662   int empty_regions_pos() {
 663     return _empty_regions_pos;
 664   }
 665 
 666   void do_object(oop p) {
 667     assert(_from_region != NULL, "must set before work");
 668     assert(_heap->complete_marking_context()->is_marked(p), "must be marked");
 669     assert(!_heap->complete_marking_context()->allocated_after_mark_start(p), "must be truly marked");
 670 
 671     size_t obj_size = p->size();
 672     if (_compact_point + obj_size > _to_region->end()) {
 673       finish_region();
 674 

 680       } else {
 681         // Out of empty region? Compact within the same region.
 682         new_to_region = _from_region;
 683       }
 684 
 685       assert(new_to_region != _to_region, "must not reuse same to-region");
 686       assert(new_to_region != NULL, "must not be NULL");
 687       _to_region = new_to_region;
 688       _compact_point = _to_region->bottom();
 689     }
 690 
 691     // Object fits into current region, record new location:
 692     assert(_compact_point + obj_size <= _to_region->end(), "must fit");
 693     shenandoah_assert_not_forwarded(NULL, p);
 694     _preserved_marks->push_if_necessary(p, p->mark());
 695     p->forward_to(cast_to_oop(_compact_point));
 696     _compact_point += obj_size;
 697   }
 698 };
 699 





 700 
 701 ShenandoahPrepareForCompactionTask::ShenandoahPrepareForCompactionTask(PreservedMarksSet *preserved_marks,
 702                                                                        ShenandoahHeapRegionSet **worker_slices,
 703                                                                        size_t num_workers) :
 704     WorkerTask("Shenandoah Prepare For Compaction"),
 705     _preserved_marks(preserved_marks), _heap(ShenandoahHeap::heap()),
 706     _worker_slices(worker_slices), _num_workers(num_workers) { }
 707 
 708 
 709 void ShenandoahPrepareForCompactionTask::work(uint worker_id) {
 710   ShenandoahParallelWorkerSession worker_session(worker_id);
 711   ShenandoahHeapRegionSet* slice = _worker_slices[worker_id];
 712   ShenandoahHeapRegionSetIterator it(slice);
 713   ShenandoahHeapRegion* from_region = it.next();
 714   // No work?
 715   if (from_region == NULL) {
 716     return;
 717   }
 718 
 719   // Sliding compaction. Walk all regions in the slice, and compact them.
 720   // Remember empty regions and reuse them as needed.
 721   ResourceMark rm;



 722 
 723   GrowableArray<ShenandoahHeapRegion*> empty_regions((int)_heap->num_regions());



 724 
 725   if (_heap->mode()->is_generational()) {
 726     ShenandoahHeapRegion* old_to_region = (from_region->is_old())? from_region: nullptr;
 727     ShenandoahHeapRegion* young_to_region = (from_region->is_young())? from_region: nullptr;
 728     ShenandoahPrepareForGenerationalCompactionObjectClosure cl(this, _preserved_marks->get(worker_id), empty_regions,
 729                                                                old_to_region, young_to_region, worker_id);
 730     while (from_region != NULL) {
 731       assert(is_candidate_region(from_region), "Sanity");
 732       log_debug(gc)("Worker %u compacting %s Region " SIZE_FORMAT " which had used " SIZE_FORMAT " and %s live",
 733                     worker_id, affiliation_name(from_region->affiliation()),
 734                     from_region->index(), from_region->used(), from_region->has_live()? "has": "does not have");
 735       cl.set_from_region(from_region);
 736       if (from_region->has_live()) {
 737         _heap->marked_object_iterate(from_region, &cl);
 738       }
 739 
 740       // Compacted the region to somewhere else? From-region is empty then.
 741       if (!cl.is_compact_same_region()) {
 742         empty_regions.append(from_region);
 743       }
 744       from_region = it.next();
 745     }
 746     cl.finish();
 747 
 748     // Mark all remaining regions as empty
 749     for (int pos = cl.empty_regions_pos(); pos < empty_regions.length(); ++pos) {
 750       ShenandoahHeapRegion* r = empty_regions.at(pos);
 751       r->set_new_top(r->bottom());
 752     }
 753   } else {
 754     ShenandoahPrepareForCompactionObjectClosure cl(_preserved_marks->get(worker_id), empty_regions, from_region);

 755     while (from_region != NULL) {
 756       assert(is_candidate_region(from_region), "Sanity");

 757       cl.set_from_region(from_region);
 758       if (from_region->has_live()) {
 759         _heap->marked_object_iterate(from_region, &cl);
 760       }
 761 
 762       // Compacted the region to somewhere else? From-region is empty then.
 763       if (!cl.is_compact_same_region()) {
 764         empty_regions.append(from_region);
 765       }
 766       from_region = it.next();
 767     }
 768     cl.finish_region();
 769 
 770     // Mark all remaining regions as empty
 771     for (int pos = cl.empty_regions_pos(); pos < empty_regions.length(); ++pos) {
 772       ShenandoahHeapRegion* r = empty_regions.at(pos);
 773       r->set_new_top(r->bottom());
 774     }
 775   }
 776 }
 777 
 778 void ShenandoahFullGC::calculate_target_humongous_objects() {
 779   ShenandoahHeap* heap = ShenandoahHeap::heap();
 780 
 781   // Compute the new addresses for humongous objects. We need to do this after addresses
 782   // for regular objects are calculated, and we know what regions in heap suffix are
 783   // available for humongous moves.
 784   //
 785   // Scan the heap backwards, because we are compacting humongous regions towards the end.
 786   // Maintain the contiguous compaction window in [to_begin; to_end), so that we can slide
 787   // humongous start there.
 788   //
 789   // The complication is potential non-movable regions during the scan. If such region is
 790   // detected, then sliding restarts towards that non-movable region.
 791 
 792   size_t to_begin = heap->num_regions();
 793   size_t to_end = heap->num_regions();
 794 
 795   log_debug(gc)("Full GC calculating target humongous objects from end " SIZE_FORMAT, to_end);
 796   for (size_t c = heap->num_regions(); c > 0; c--) {
 797     ShenandoahHeapRegion *r = heap->get_region(c - 1);
 798     if (r->is_humongous_continuation() || (r->new_top() == r->bottom())) {
 799       // To-region candidate: record this, and continue scan
 800       to_begin = r->index();
 801       continue;
 802     }
 803 
 804     if (r->is_humongous_start() && r->is_stw_move_allowed()) {
 805       // From-region candidate: movable humongous region
 806       oop old_obj = cast_to_oop(r->bottom());
 807       size_t words_size = old_obj->size();
 808       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
 809 
 810       size_t start = to_end - num_regions;
 811 
 812       if (start >= to_begin && start != r->index()) {
 813         // Fits into current window, and the move is non-trivial. Record the move then, and continue scan.
 814         _preserved_marks->get(0)->push_if_necessary(old_obj, old_obj->mark());
 815         old_obj->forward_to(cast_to_oop(heap->get_region(start)->bottom()));
 816         to_end = start;
 817         continue;
 818       }
 819     }
 820 
 821     // Failed to fit. Scan starting from current region.
 822     to_begin = r->index();
 823     to_end = r->index();
 824   }
 825 }
 826 
 827 class ShenandoahEnsureHeapActiveClosure: public ShenandoahHeapRegionClosure {
 828 private:
 829   ShenandoahHeap* const _heap;
 830 
 831 public:
 832   ShenandoahEnsureHeapActiveClosure() : _heap(ShenandoahHeap::heap()) {}
 833   void heap_region_do(ShenandoahHeapRegion* r) {
 834     bool is_generational = _heap->mode()->is_generational();
 835     if (r->is_trash()) {
 836       r->recycle();
 837     }
 838     if (r->is_cset()) {
 839       // Leave afffiliation unchanged.
 840       r->make_regular_bypass();
 841     }
 842     if (r->is_empty_uncommitted()) {
 843       r->make_committed_bypass();
 844     }
 845     assert (r->is_committed(), "only committed regions in heap now, see region " SIZE_FORMAT, r->index());
 846 
 847     // Record current region occupancy: this communicates empty regions are free
 848     // to the rest of Full GC code.
 849     r->set_new_top(r->top());
 850   }
 851 };
 852 
 853 class ShenandoahTrashImmediateGarbageClosure: public ShenandoahHeapRegionClosure {
 854 private:
 855   ShenandoahHeap* const _heap;
 856   ShenandoahMarkingContext* const _ctx;
 857 
 858 public:
 859   ShenandoahTrashImmediateGarbageClosure() :
 860     _heap(ShenandoahHeap::heap()),
 861     _ctx(ShenandoahHeap::heap()->complete_marking_context()) {}
 862 
 863   void heap_region_do(ShenandoahHeapRegion* r) {
 864     if (r->affiliation() != FREE) {
 865       if (r->is_humongous_start()) {
 866         oop humongous_obj = cast_to_oop(r->bottom());
 867         if (!_ctx->is_marked(humongous_obj)) {
 868           assert(!r->has_live(),
 869                  "Humongous Start %s Region " SIZE_FORMAT " is not marked, should not have live",
 870                  affiliation_name(r->affiliation()),  r->index());
 871           log_debug(gc)("Trashing immediate humongous region " SIZE_FORMAT " because not marked", r->index());
 872           _heap->trash_humongous_region_at(r);
 873         } else {
 874           assert(r->has_live(),
 875                  "Humongous Start %s Region " SIZE_FORMAT " should have live", affiliation_name(r->affiliation()),  r->index());
 876         }
 877       } else if (r->is_humongous_continuation()) {
 878         // If we hit continuation, the non-live humongous starts should have been trashed already
 879         assert(r->humongous_start_region()->has_live(),
 880                "Humongous Continuation %s Region " SIZE_FORMAT " should have live", affiliation_name(r->affiliation()),  r->index());
 881       } else if (r->is_regular()) {
 882         if (!r->has_live()) {
 883           log_debug(gc)("Trashing immediate regular region " SIZE_FORMAT " because has no live", r->index());
 884           r->make_trash_immediate();
 885         }
 886       }
 887     }
 888     // else, ignore this FREE region.
 889     // TODO: change iterators so they do not process FREE regions.
 890   }
 891 };
 892 
 893 void ShenandoahFullGC::distribute_slices(ShenandoahHeapRegionSet** worker_slices) {
 894   ShenandoahHeap* heap = ShenandoahHeap::heap();
 895 
 896   uint n_workers = heap->workers()->active_workers();
 897   size_t n_regions = heap->num_regions();
 898 
 899   // What we want to accomplish: have the dense prefix of data, while still balancing
 900   // out the parallel work.
 901   //
 902   // Assuming the amount of work is driven by the live data that needs moving, we can slice
 903   // the entire heap into equal-live-sized prefix slices, and compact into them. So, each
 904   // thread takes all regions in its prefix subset, and then it takes some regions from
 905   // the tail.
 906   //
 907   // Tail region selection becomes interesting.
 908   //
 909   // First, we want to distribute the regions fairly between the workers, and those regions

1036   GCTraceTime(Info, gc, phases) time("Phase 2: Compute new object addresses", _gc_timer);
1037   ShenandoahGCPhase calculate_address_phase(ShenandoahPhaseTimings::full_gc_calculate_addresses);
1038 
1039   ShenandoahHeap* heap = ShenandoahHeap::heap();
1040 
1041   // About to figure out which regions can be compacted, make sure pinning status
1042   // had been updated in GC prologue.
1043   heap->assert_pinned_region_status();
1044 
1045   {
1046     // Trash the immediately collectible regions before computing addresses
1047     ShenandoahTrashImmediateGarbageClosure tigcl;
1048     heap->heap_region_iterate(&tigcl);
1049 
1050     // Make sure regions are in good state: committed, active, clean.
1051     // This is needed because we are potentially sliding the data through them.
1052     ShenandoahEnsureHeapActiveClosure ecl;
1053     heap->heap_region_iterate(&ecl);
1054   }
1055 
1056   if (heap->mode()->is_generational()) {
1057     heap->young_generation()->clear_used();
1058     heap->old_generation()->clear_used();
1059   }
1060 
1061   // Compute the new addresses for regular objects
1062   {
1063     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_regular);
1064 
1065     distribute_slices(worker_slices);
1066 
1067     size_t num_workers = heap->max_workers();
1068 
1069     ResourceMark rm;
1070     ShenandoahPrepareForCompactionTask task(_preserved_marks, worker_slices, num_workers);
1071     heap->workers()->run_task(&task);
1072   }
1073 
1074   // Compute the new addresses for humongous objects
1075   {
1076     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_humong);
1077     calculate_target_humongous_objects();
1078   }
1079 }
1080 
1081 class ShenandoahAdjustPointersClosure : public MetadataVisitingOopIterateClosure {
1082 private:
1083   ShenandoahHeap* const _heap;
1084   ShenandoahMarkingContext* const _ctx;
1085 
1086   template <class T>
1087   inline void do_oop_work(T* p) {
1088     T o = RawAccess<>::oop_load(p);
1089     if (!CompressedOops::is_null(o)) {
1090       oop obj = CompressedOops::decode_not_null(o);

1124 
1125 class ShenandoahAdjustPointersTask : public WorkerTask {
1126 private:
1127   ShenandoahHeap*          const _heap;
1128   ShenandoahRegionIterator       _regions;
1129 
1130 public:
1131   ShenandoahAdjustPointersTask() :
1132     WorkerTask("Shenandoah Adjust Pointers"),
1133     _heap(ShenandoahHeap::heap()) {
1134   }
1135 
1136   void work(uint worker_id) {
1137     ShenandoahParallelWorkerSession worker_session(worker_id);
1138     ShenandoahAdjustPointersObjectClosure obj_cl;
1139     ShenandoahHeapRegion* r = _regions.next();
1140     while (r != NULL) {
1141       if (!r->is_humongous_continuation() && r->has_live()) {
1142         _heap->marked_object_iterate(r, &obj_cl);
1143       }
1144       if (r->is_pinned() && r->is_old() && r->is_active() && !r->is_humongous()) {
1145         // Pinned regions are not compacted so they may still hold unmarked objects with
1146         // reference to reclaimed memory. Remembered set scanning will crash if it attempts
1147         // to iterate the oops in these objects.
1148         r->begin_preemptible_coalesce_and_fill();
1149         r->oop_fill_and_coalesce_wo_cancel();
1150       }
1151       r = _regions.next();
1152     }
1153   }
1154 };
1155 
1156 class ShenandoahAdjustRootPointersTask : public WorkerTask {
1157 private:
1158   ShenandoahRootAdjuster* _rp;
1159   PreservedMarksSet* _preserved_marks;
1160 public:
1161   ShenandoahAdjustRootPointersTask(ShenandoahRootAdjuster* rp, PreservedMarksSet* preserved_marks) :
1162     WorkerTask("Shenandoah Adjust Root Pointers"),
1163     _rp(rp),
1164     _preserved_marks(preserved_marks) {}
1165 
1166   void work(uint worker_id) {
1167     ShenandoahParallelWorkerSession worker_session(worker_id);
1168     ShenandoahAdjustPointersClosure cl;
1169     _rp->roots_do(worker_id, &cl);
1170     _preserved_marks->get(worker_id)->adjust_during_full_gc();

1243         _heap->marked_object_iterate(r, &cl);
1244       }
1245       r->set_top(r->new_top());
1246       r = slice.next();
1247     }
1248   }
1249 };
1250 
1251 class ShenandoahPostCompactClosure : public ShenandoahHeapRegionClosure {
1252 private:
1253   ShenandoahHeap* const _heap;
1254   size_t _live;
1255 
1256 public:
1257   ShenandoahPostCompactClosure() : _heap(ShenandoahHeap::heap()), _live(0) {
1258     _heap->free_set()->clear();
1259   }
1260 
1261   void heap_region_do(ShenandoahHeapRegion* r) {
1262     assert (!r->is_cset(), "cset regions should have been demoted already");
1263     bool is_generational = _heap->mode()->is_generational();
1264 
1265     // Need to reset the complete-top-at-mark-start pointer here because
1266     // the complete marking bitmap is no longer valid. This ensures
1267     // size-based iteration in marked_object_iterate().
1268     // NOTE: See blurb at ShenandoahMCResetCompleteBitmapTask on why we need to skip
1269     // pinned regions.
1270     if (!r->is_pinned()) {
1271       _heap->complete_marking_context()->reset_top_at_mark_start(r);
1272     }
1273 
1274     size_t live = r->used();
1275 
1276     // Make empty regions that have been allocated into regular
1277     if (r->is_empty() && live > 0) {
1278       if (!is_generational) {
1279         r->make_young_maybe();
1280       }
1281       // else, generational mode compaction has already established affiliation.
1282       r->make_regular_bypass();
1283     }
1284 
1285     // Reclaim regular regions that became empty
1286     if (r->is_regular() && live == 0) {
1287       r->make_trash();
1288     }
1289 
1290     // Recycle all trash regions
1291     if (r->is_trash()) {
1292       live = 0;
1293       r->recycle();
1294     }
1295 
1296     // Update final usage for generations
1297     if (is_generational && live != 0) {
1298       if (r->is_young()) {
1299         _heap->young_generation()->increase_used(live);
1300       } else if (r->is_old()) {
1301         _heap->old_generation()->increase_used(live);
1302       }
1303     }
1304 
1305     r->set_live_data(live);
1306     r->reset_alloc_metadata();
1307     _live += live;
1308   }
1309 
1310   size_t get_live() {
1311     return _live;
1312   }
1313 };
1314 
1315 void ShenandoahFullGC::compact_humongous_objects() {
1316   // Compact humongous regions, based on their fwdptr objects.
1317   //
1318   // This code is serial, because doing the in-slice parallel sliding is tricky. In most cases,
1319   // humongous regions are already compacted, and do not require further moves, which alleviates
1320   // sliding costs. We may consider doing this in parallel in future.
1321 
1322   ShenandoahHeap* heap = ShenandoahHeap::heap();
1323 
1324   for (size_t c = heap->num_regions(); c > 0; c--) {
1325     ShenandoahHeapRegion* r = heap->get_region(c - 1);
1326     if (r->is_humongous_start()) {
1327       oop old_obj = cast_to_oop(r->bottom());
1328       if (!old_obj->is_forwarded()) {
1329         // No need to move the object, it stays at the same slot
1330         continue;
1331       }
1332       size_t words_size = old_obj->size();
1333       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
1334 
1335       size_t old_start = r->index();
1336       size_t old_end   = old_start + num_regions - 1;
1337       size_t new_start = heap->heap_region_index_containing(old_obj->forwardee());
1338       size_t new_end   = new_start + num_regions - 1;
1339       assert(old_start != new_start, "must be real move");
1340       assert(r->is_stw_move_allowed(), "Region " SIZE_FORMAT " should be movable", r->index());
1341 
1342       ContinuationGCSupport::relativize_stack_chunk(cast_to_oop<HeapWord*>(heap->get_region(old_start)->bottom()));
1343       log_debug(gc)("Full GC compaction moves humongous object from region " SIZE_FORMAT " to region " SIZE_FORMAT,
1344                     old_start, new_start);
1345 
1346       Copy::aligned_conjoint_words(heap->get_region(old_start)->bottom(),
1347                                    heap->get_region(new_start)->bottom(),
1348                                    words_size);
1349 
1350       oop new_obj = cast_to_oop(heap->get_region(new_start)->bottom());
1351       new_obj->init_mark();
1352 
1353       {
1354         ShenandoahRegionAffiliation original_affiliation = r->affiliation();
1355         for (size_t c = old_start; c <= old_end; c++) {
1356           ShenandoahHeapRegion* r = heap->get_region(c);
1357           // Leave humongous region affiliation unchanged.
1358           r->make_regular_bypass();
1359           r->set_top(r->bottom());
1360         }
1361 
1362         for (size_t c = new_start; c <= new_end; c++) {
1363           ShenandoahHeapRegion* r = heap->get_region(c);
1364           if (c == new_start) {
1365             r->make_humongous_start_bypass(original_affiliation);
1366           } else {
1367             r->make_humongous_cont_bypass(original_affiliation);
1368           }
1369 
1370           // Trailing region may be non-full, record the remainder there
1371           size_t remainder = words_size & ShenandoahHeapRegion::region_size_words_mask();
1372           if ((c == new_end) && (remainder != 0)) {
1373             r->set_top(r->bottom() + remainder);
1374           } else {
1375             r->set_top(r->end());
1376           }
1377 
1378           r->reset_alloc_metadata();
1379         }
1380       }
1381     }
1382   }
1383 }
1384 
1385 // This is slightly different to ShHeap::reset_next_mark_bitmap:
1386 // we need to remain able to walk pinned regions.
1387 // Since pinned region do not move and don't get compacted, we will get holes with

1426   }
1427 
1428   // Compact humongous objects after regular object moves
1429   {
1430     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_humong);
1431     compact_humongous_objects();
1432   }
1433 
1434   // Reset complete bitmap. We're about to reset the complete-top-at-mark-start pointer
1435   // and must ensure the bitmap is in sync.
1436   {
1437     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_reset_complete);
1438     ShenandoahMCResetCompleteBitmapTask task;
1439     heap->workers()->run_task(&task);
1440   }
1441 
1442   // Bring regions in proper states after the collection, and set heap properties.
1443   {
1444     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_rebuild);
1445 
1446     if (heap->mode()->is_generational()) {
1447       heap->young_generation()->clear_used();
1448       heap->old_generation()->clear_used();
1449     }
1450 
1451     ShenandoahPostCompactClosure post_compact;
1452     heap->heap_region_iterate(&post_compact);
1453     heap->set_used(post_compact.get_live());
1454     if (heap->mode()->is_generational()) {
1455       log_info(gc)("FullGC done: GLOBAL usage: " SIZE_FORMAT ", young usage: " SIZE_FORMAT ", old usage: " SIZE_FORMAT,
1456                     post_compact.get_live(), heap->young_generation()->used(), heap->old_generation()->used());
1457     }
1458 
1459     heap->collection_set()->clear();
1460     heap->free_set()->rebuild();
1461   }
1462 
1463   heap->clear_cancelled_gc(true /* clear oom handler */);
1464 }
< prev index next >