1 /*
   2  * Copyright (c) 2014, 2017, Red Hat, Inc. and/or its affiliates.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.
   7  *
   8  * This code is distributed in the hope that it will be useful, but WITHOUT
   9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  11  * version 2 for more details (a copy is included in the LICENSE file that
  12  * accompanied this code).
  13  *
  14  * You should have received a copy of the GNU General Public License version
  15  * 2 along with this work; if not, write to the Free Software Foundation,
  16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  17  *
  18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19  * or visit www.oracle.com if you need additional information or have any
  20  * questions.
  21  *
  22  */
  23 
  24 #include "precompiled.hpp"
  25 
  26 #include "classfile/javaClasses.inline.hpp"
  27 #include "code/codeCache.hpp"
  28 #include "gc/shared/gcTraceTime.inline.hpp"
  29 #include "gc/shenandoah/brooksPointer.hpp"
  30 #include "gc/shenandoah/shenandoahConcurrentMark.inline.hpp"
  31 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  32 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  33 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  34 #include "gc/shenandoah/shenandoahMarkCompact.hpp"
  35 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
  36 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  37 #include "gc/shenandoah/shenandoahHeap.hpp"
  38 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  39 #include "gc/shenandoah/shenandoahRootProcessor.hpp"
  40 #include "gc/shenandoah/shenandoahTraversalGC.hpp"
  41 #include "gc/shenandoah/shenandoahUtils.hpp"
  42 #include "gc/shenandoah/shenandoahVerifier.hpp"
  43 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
  44 #include "gc/shenandoah/vm_operations_shenandoah.hpp"
  45 #include "oops/oop.inline.hpp"
  46 #include "runtime/biasedLocking.hpp"
  47 #include "runtime/thread.hpp"
  48 #include "utilities/copy.hpp"
  49 #include "utilities/growableArray.hpp"
  50 #include "gc/shared/taskqueue.inline.hpp"
  51 #include "gc/shared/workgroup.hpp"
  52 
  53 class ShenandoahClearRegionStatusClosure: public ShenandoahHeapRegionClosure {
  54 private:
  55   ShenandoahHeap* const _heap;
  56 
  57 public:
  58   ShenandoahClearRegionStatusClosure() : _heap(ShenandoahHeap::heap()) {}
  59 
  60   bool heap_region_do(ShenandoahHeapRegion *r) {
  61     _heap->set_next_top_at_mark_start(r->bottom(), r->top());
  62     r->clear_live_data();
  63     r->set_concurrent_iteration_safe_limit(r->top());
  64     return false;
  65   }
  66 };
  67 
  68 class ShenandoahEnsureHeapActiveClosure: public ShenandoahHeapRegionClosure {
  69 private:
  70   ShenandoahHeap* const _heap;
  71 
  72 public:
  73   ShenandoahEnsureHeapActiveClosure() : _heap(ShenandoahHeap::heap()) {}
  74   bool heap_region_do(ShenandoahHeapRegion* r) {
  75     if (r->is_trash()) {
  76       r->recycle();
  77     }
  78     if (r->is_cset()) {
  79       r->make_regular_bypass();
  80     }
  81     if (r->is_empty_uncommitted()) {
  82       r->make_committed_bypass();
  83     }
  84     assert (r->is_committed(), "only committed regions in heap now, see region " SIZE_FORMAT, r->region_number());
  85 
  86     // Record current region occupancy: this communicates empty regions are free
  87     // to the rest of Full GC code.
  88     r->set_new_top(r->top());
  89     return false;
  90   }
  91 };
  92 
  93 void ShenandoahMarkCompact::initialize(GCTimer* gc_timer) {
  94   _gc_timer = gc_timer;
  95 }
  96 
  97 void ShenandoahMarkCompact::do_it(GCCause::Cause gc_cause) {
  98   ShenandoahHeap* heap = ShenandoahHeap::heap();
  99 
 100   {
 101     if (ShenandoahVerify) {
 102       heap->verifier()->verify_before_fullgc();
 103     }
 104 
 105     heap->set_full_gc_in_progress(true);
 106 
 107     assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at a safepoint");
 108     assert(Thread::current()->is_VM_thread(), "Do full GC only while world is stopped");
 109 
 110     {
 111       ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdumps);
 112       heap->pre_full_gc_dump(_gc_timer);
 113     }
 114 
 115     {
 116       ShenandoahGCPhase prepare_phase(ShenandoahPhaseTimings::full_gc_prepare);
 117       // Full GC is supposed to recover from any GC state:
 118 
 119       // a1. Cancel evacuation, if in progress
 120       if (heap->is_evacuation_in_progress()) {
 121         heap->set_evacuation_in_progress(false);
 122       }
 123       assert(!heap->is_evacuation_in_progress(), "sanity");
 124 
 125       // a2. Cancel update-refs, if in progress
 126       if (heap->is_update_refs_in_progress()) {
 127         heap->set_update_refs_in_progress(false);
 128       }
 129       assert(!heap->is_update_refs_in_progress(), "sanity");
 130 
 131       // a3. Cancel concurrent traversal GC, if in progress
 132       if (heap->is_concurrent_traversal_in_progress()) {
 133         heap->traversal_gc()->reset();
 134         heap->set_concurrent_traversal_in_progress(false);
 135       }
 136 
 137       // b. Cancel concurrent mark, if in progress
 138       if (heap->is_concurrent_mark_in_progress()) {
 139         heap->concurrentMark()->cancel();
 140         heap->stop_concurrent_marking();
 141       }
 142       assert(!heap->is_concurrent_mark_in_progress(), "sanity");
 143 
 144       // c. Reset the bitmaps for new marking
 145       heap->reset_next_mark_bitmap();
 146       assert(heap->is_next_bitmap_clear(), "sanity");
 147 
 148       // d. Abandon reference discovery and clear all discovered references.
 149       ReferenceProcessor* rp = heap->ref_processor();
 150       rp->disable_discovery();
 151       rp->abandon_partial_discovery();
 152       rp->verify_no_references_recorded();
 153 
 154       {
 155         ShenandoahHeapLocker lock(heap->lock());
 156 
 157         // f. Make sure all regions are active. This is needed because we are potentially
 158         // sliding the data through them
 159         ShenandoahEnsureHeapActiveClosure ecl;
 160         heap->heap_region_iterate(&ecl, false, false);
 161 
 162         // g. Clear region statuses, including collection set status
 163         ShenandoahClearRegionStatusClosure cl;
 164         heap->heap_region_iterate(&cl, false, false);
 165       }
 166     }
 167 
 168     {
 169       if (UseTLAB) {
 170         heap->make_tlabs_parsable(true);
 171       }
 172 
 173       CodeCache::gc_prologue();
 174 
 175       // TODO: We don't necessarily need to update refs. We might want to clean
 176       // up managing has_forwarded_objects when diving into degen/full-gc.
 177       heap->set_has_forwarded_objects(true);
 178 
 179       OrderAccess::fence();
 180 
 181       phase1_mark_heap();
 182 
 183       // Prevent read-barrier from kicking in while adjusting pointers in phase3.
 184       heap->set_has_forwarded_objects(false);
 185 
 186       heap->set_full_gc_move_in_progress(true);
 187 
 188       // Setup workers for the rest
 189       {
 190         OrderAccess::fence();
 191 
 192         // Initialize worker slices
 193         ShenandoahHeapRegionSet** worker_slices = NEW_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, heap->max_workers(), mtGC);
 194         for (uint i = 0; i < heap->max_workers(); i++) {
 195           worker_slices[i] = new ShenandoahHeapRegionSet();
 196         }
 197 
 198         phase2_calculate_target_addresses(worker_slices);
 199 
 200         OrderAccess::fence();
 201 
 202         phase3_update_references();
 203 
 204         phase4_compact_objects(worker_slices);
 205 
 206         // Free worker slices
 207         for (uint i = 0; i < heap->max_workers(); i++) {
 208           delete worker_slices[i];
 209         }
 210         FREE_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, worker_slices);
 211 
 212         CodeCache::gc_epilogue();
 213         JvmtiExport::gc_epilogue();
 214       }
 215 
 216       heap->set_full_gc_move_in_progress(false);
 217       heap->set_full_gc_in_progress(false);
 218 
 219       if (ShenandoahVerify) {
 220         heap->verifier()->verify_after_fullgc();
 221       }
 222     }
 223 
 224     {
 225       ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdumps);
 226       heap->post_full_gc_dump(_gc_timer);
 227     }
 228   }
 229 
 230 
 231   if (UseShenandoahMatrix && PrintShenandoahMatrix) {
 232     LogTarget(Info, gc) lt;
 233     LogStream ls(lt);
 234     heap->connection_matrix()->print_on(&ls);
 235   }
 236 }
 237 
 238 void ShenandoahMarkCompact::phase1_mark_heap() {
 239   GCTraceTime(Info, gc, phases) time("Phase 1: Mark live objects", _gc_timer);
 240   ShenandoahGCPhase mark_phase(ShenandoahPhaseTimings::full_gc_mark);
 241 
 242   ShenandoahHeap* heap = ShenandoahHeap::heap();
 243 
 244   ShenandoahConcurrentMark* cm = heap->concurrentMark();
 245 
 246   // Do not trust heuristics, because this can be our last resort collection.
 247   // Only ignore processing references and class unloading if explicitly disabled.
 248   heap->set_process_references(ShenandoahRefProcFrequency != 0);
 249   heap->set_unload_classes(ShenandoahUnloadClassesFrequency != 0);
 250 
 251   ReferenceProcessor* rp = heap->ref_processor();
 252   // enable ("weak") refs discovery
 253   rp->enable_discovery(true /*verify_no_refs*/);
 254   rp->setup_policy(true); // snapshot the soft ref policy to be used in this cycle
 255   rp->set_active_mt_degree(heap->workers()->active_workers());
 256 
 257   cm->update_roots(ShenandoahPhaseTimings::full_gc_roots);
 258   cm->mark_roots(ShenandoahPhaseTimings::full_gc_roots);
 259   cm->shared_finish_mark_from_roots(/* full_gc = */ true);
 260 
 261   heap->swap_mark_bitmaps();
 262 
 263   if (UseShenandoahMatrix && PrintShenandoahMatrix) {
 264     LogTarget(Info, gc) lt;
 265     LogStream ls(lt);
 266     heap->connection_matrix()->print_on(&ls);
 267   }
 268 }
 269 
 270 class ShenandoahMCReclaimHumongousRegionClosure : public ShenandoahHeapRegionClosure {
 271 private:
 272   ShenandoahHeap* const _heap;
 273 public:
 274   ShenandoahMCReclaimHumongousRegionClosure() : _heap(ShenandoahHeap::heap()) {}
 275 
 276   bool heap_region_do(ShenandoahHeapRegion* r) {
 277     if (r->is_humongous_start()) {
 278       oop humongous_obj = oop(r->bottom() + BrooksPointer::word_size());
 279       if (!_heap->is_marked_complete(humongous_obj)) {
 280         _heap->trash_humongous_region_at(r);
 281       }
 282     }
 283     return false;
 284   }
 285 };
 286 
 287 class ShenandoahPrepareForCompactionObjectClosure : public ObjectClosure {
 288 private:
 289   ShenandoahHeap*          const _heap;
 290   GrowableArray<ShenandoahHeapRegion*>& _empty_regions;
 291   int _empty_regions_pos;
 292   ShenandoahHeapRegion*          _to_region;
 293   ShenandoahHeapRegion*          _from_region;
 294   HeapWord* _compact_point;
 295 
 296 public:
 297   ShenandoahPrepareForCompactionObjectClosure(GrowableArray<ShenandoahHeapRegion*>& empty_regions, ShenandoahHeapRegion* to_region) :
 298     _heap(ShenandoahHeap::heap()),
 299     _empty_regions(empty_regions),
 300     _empty_regions_pos(0),
 301     _to_region(to_region),
 302     _from_region(NULL),
 303     _compact_point(to_region->bottom()) {}
 304 
 305   void set_from_region(ShenandoahHeapRegion* from_region) {
 306     _from_region = from_region;
 307   }
 308 
 309   void finish_region() {
 310     assert(_to_region != NULL, "should not happen");
 311     _to_region->set_new_top(_compact_point);
 312   }
 313 
 314   bool is_compact_same_region() {
 315     return _from_region == _to_region;
 316   }
 317 
 318   int empty_regions_pos() {
 319     return _empty_regions_pos;
 320   }
 321 
 322   void do_object(oop p) {
 323     assert(_from_region != NULL, "must set before work");
 324     assert(_heap->is_marked_complete(p), "must be marked");
 325     assert(!_heap->allocated_after_complete_mark_start((HeapWord*) p), "must be truly marked");
 326 
 327     size_t obj_size = p->size() + BrooksPointer::word_size();
 328     if (_compact_point + obj_size > _to_region->end()) {
 329       finish_region();
 330 
 331       // Object doesn't fit. Pick next empty region and start compacting there.
 332       ShenandoahHeapRegion* new_to_region;
 333       if (_empty_regions_pos < _empty_regions.length()) {
 334         new_to_region = _empty_regions.at(_empty_regions_pos);
 335         _empty_regions_pos++;
 336       } else {
 337         // Out of empty region? Compact within the same region.
 338         new_to_region = _from_region;
 339       }
 340 
 341       assert(new_to_region != _to_region, "must not reuse same to-region");
 342       assert(new_to_region != NULL, "must not be NULL");
 343       _to_region = new_to_region;
 344       _compact_point = _to_region->bottom();
 345     }
 346 
 347     // Object fits into current region, record new location:
 348     assert(_compact_point + obj_size <= _to_region->end(), "must fit");
 349     shenandoah_assert_not_forwarded(NULL, p);
 350     BrooksPointer::set_raw(p, _compact_point + BrooksPointer::word_size());
 351     _compact_point += obj_size;
 352   }
 353 };
 354 
 355 class ShenandoahPrepareForCompactionTask : public AbstractGangTask {
 356 private:
 357   ShenandoahHeap*           const _heap;
 358   ShenandoahHeapRegionSet** const _worker_slices;
 359   ShenandoahRegionIterator        _heap_regions;
 360 
 361   ShenandoahHeapRegion* next_from_region(ShenandoahHeapRegionSet* slice) {
 362     ShenandoahHeapRegion* from_region = _heap_regions.next();
 363 
 364     while (from_region != NULL && (!from_region->is_move_allowed() || from_region->is_humongous())) {
 365       from_region = _heap_regions.next();
 366     }
 367 
 368     if (from_region != NULL) {
 369       assert(slice != NULL, "sanity");
 370       assert(!from_region->is_humongous(), "this path cannot handle humongous regions");
 371       assert(from_region->is_move_allowed(), "only regions that can be moved in mark-compact");
 372       slice->add_region(from_region);
 373     }
 374 
 375     return from_region;
 376   }
 377 
 378 public:
 379   ShenandoahPrepareForCompactionTask(ShenandoahHeapRegionSet** worker_slices) :
 380     AbstractGangTask("Shenandoah Prepare For Compaction Task"),
 381     _heap(ShenandoahHeap::heap()), _worker_slices(worker_slices) {
 382   }
 383 
 384   void work(uint worker_id) {
 385     ShenandoahHeapRegionSet* slice = _worker_slices[worker_id];
 386     ShenandoahHeapRegion* from_region = next_from_region(slice);
 387     // No work?
 388     if (from_region == NULL) {
 389       return;
 390     }
 391 
 392     // Sliding compaction. Walk all regions in the slice, and compact them.
 393     // Remember empty regions and reuse them as needed.
 394     ResourceMark rm;
 395     GrowableArray<ShenandoahHeapRegion*> empty_regions((int)_heap->num_regions());
 396     ShenandoahPrepareForCompactionObjectClosure cl(empty_regions, from_region);
 397     while (from_region != NULL) {
 398       cl.set_from_region(from_region);
 399       _heap->marked_object_iterate(from_region, &cl);
 400 
 401       // Compacted the region to somewhere else? From-region is empty then.
 402       if (!cl.is_compact_same_region()) {
 403         empty_regions.append(from_region);
 404       }
 405       from_region = next_from_region(slice);
 406     }
 407     cl.finish_region();
 408 
 409     // Mark all remaining regions as empty
 410     for (int pos = cl.empty_regions_pos(); pos < empty_regions.length(); ++pos) {
 411       ShenandoahHeapRegion* r = empty_regions.at(pos);
 412       r->set_new_top(r->bottom());
 413     }
 414   }
 415 };
 416 
 417 void ShenandoahMarkCompact::calculate_target_humongous_objects() {
 418   ShenandoahHeap* heap = ShenandoahHeap::heap();
 419 
 420   // Compute the new addresses for humongous objects. We need to do this after addresses
 421   // for regular objects are calculated, and we know what regions in heap suffix are
 422   // available for humongous moves.
 423   //
 424   // Scan the heap backwards, because we are compacting humongous regions towards the end.
 425   // Maintain the contiguous compaction window in [to_begin; to_end), so that we can slide
 426   // humongous start there.
 427   //
 428   // The complication is potential non-movable regions during the scan. If such region is
 429   // detected, then sliding restarts towards that non-movable region.
 430 
 431   size_t to_begin = heap->num_regions();
 432   size_t to_end = heap->num_regions();
 433 
 434   for (size_t c = heap->num_regions() - 1; c > 0; c--) {
 435     ShenandoahHeapRegion *r = heap->get_region(c);
 436     if (r->is_humongous_continuation() || (r->new_top() == r->bottom())) {
 437       // To-region candidate: record this, and continue scan
 438       to_begin = r->region_number();
 439       continue;
 440     }
 441 
 442     if (r->is_humongous_start() && r->is_move_allowed()) {
 443       // From-region candidate: movable humongous region
 444       oop old_obj = oop(r->bottom() + BrooksPointer::word_size());
 445       size_t words_size = old_obj->size() + BrooksPointer::word_size();
 446       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
 447 
 448       size_t start = to_end - num_regions;
 449 
 450       if (start >= to_begin && start != r->region_number()) {
 451         // Fits into current window, and the move is non-trivial. Record the move then, and continue scan.
 452         BrooksPointer::set_raw(old_obj, heap->get_region(start)->bottom() + BrooksPointer::word_size());
 453         to_end = start;
 454         continue;
 455       }
 456     }
 457 
 458     // Failed to fit. Scan starting from current region.
 459     to_begin = r->region_number();
 460     to_end = r->region_number();
 461   }
 462 }
 463 
 464 void ShenandoahMarkCompact::phase2_calculate_target_addresses(ShenandoahHeapRegionSet** worker_slices) {
 465   GCTraceTime(Info, gc, phases) time("Phase 2: Compute new object addresses", _gc_timer);
 466   ShenandoahGCPhase calculate_address_phase(ShenandoahPhaseTimings::full_gc_calculate_addresses);
 467 
 468   ShenandoahHeap* heap = ShenandoahHeap::heap();
 469 
 470   {
 471     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_regular);
 472 
 473     {
 474       ShenandoahHeapLocker lock(heap->lock());
 475 
 476       ShenandoahMCReclaimHumongousRegionClosure cl;
 477       heap->heap_region_iterate(&cl);
 478 
 479       // After some humongous regions were reclaimed, we need to ensure their
 480       // backing storage is active. This is needed because we are potentially
 481       // sliding the data through them.
 482       ShenandoahEnsureHeapActiveClosure ecl;
 483       heap->heap_region_iterate(&ecl, false, false);
 484     }
 485 
 486     // Compute the new addresses for regular objects
 487     ShenandoahPrepareForCompactionTask prepare_task(worker_slices);
 488     heap->workers()->run_task(&prepare_task);
 489   }
 490 
 491   // Compute the new addresses for humongous objects
 492   {
 493     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_humong);
 494     calculate_target_humongous_objects();
 495   }
 496 }
 497 
 498 class ShenandoahAdjustPointersClosure : public MetadataAwareOopClosure {
 499 private:
 500   ShenandoahHeap* const _heap;
 501   size_t _new_obj_offset;
 502 
 503   template <class T>
 504   inline void do_oop_work(T* p) {
 505     T o = oopDesc::load_heap_oop(p);
 506     if (! oopDesc::is_null(o)) {
 507       oop obj = oopDesc::decode_heap_oop_not_null(o);
 508       assert(_heap->is_marked_complete(obj), "must be marked");
 509       oop forw = oop(BrooksPointer::get_raw(obj));
 510       oopDesc::encode_store_heap_oop(p, forw);
 511       if (UseShenandoahMatrix) {
 512         if (_heap->is_in_reserved(p)) {
 513           assert(_heap->is_in_reserved(forw), "must be in heap");
 514           assert(_new_obj_offset != SIZE_MAX, "should be set");
 515           // We're moving a to a', which points to b, about to be moved to b'.
 516           // We already know b' from the fwd pointer of b.
 517           // In the object closure, we see a, and we know a' (by looking at its
 518           // fwd ptr). We store the offset in the OopClosure, which is going
 519           // to visit all of a's fields, and then, when we see each field, we
 520           // subtract the offset from each field address to get the final ptr.
 521           _heap->connection_matrix()->set_connected(((HeapWord*) p) - _new_obj_offset, forw);
 522         }
 523       }
 524     }
 525   }
 526 
 527 public:
 528   ShenandoahAdjustPointersClosure() : _heap(ShenandoahHeap::heap()), _new_obj_offset(SIZE_MAX)  {}
 529 
 530   void do_oop(oop* p)       { do_oop_work(p); }
 531   void do_oop(narrowOop* p) { do_oop_work(p); }
 532 
 533   void set_new_obj_offset(size_t new_obj_offset) {
 534     _new_obj_offset = new_obj_offset;
 535   }
 536 };
 537 
 538 class ShenandoahAdjustPointersObjectClosure : public ObjectClosure {
 539 private:
 540   ShenandoahHeap* const _heap;
 541   ShenandoahAdjustPointersClosure _cl;
 542 
 543 public:
 544   ShenandoahAdjustPointersObjectClosure() :
 545     _heap(ShenandoahHeap::heap()) {
 546   }
 547   void do_object(oop p) {
 548     assert(_heap->is_marked_complete(p), "must be marked");
 549     HeapWord* forw = BrooksPointer::get_raw(p);
 550     _cl.set_new_obj_offset(pointer_delta((HeapWord*) p, forw));
 551     p->oop_iterate(&_cl);
 552   }
 553 };
 554 
 555 class ShenandoahAdjustPointersTask : public AbstractGangTask {
 556 private:
 557   ShenandoahHeap*          const _heap;
 558   ShenandoahRegionIterator       _regions;
 559 
 560 public:
 561   ShenandoahAdjustPointersTask() :
 562     AbstractGangTask("Shenandoah Adjust Pointers Task"),
 563     _heap(ShenandoahHeap::heap()) {
 564   }
 565 
 566   void work(uint worker_id) {
 567     ShenandoahAdjustPointersObjectClosure obj_cl;
 568     ShenandoahHeapRegion* r = _regions.next();
 569     while (r != NULL) {
 570       if (!r->is_humongous_continuation()) {
 571         _heap->marked_object_iterate(r, &obj_cl);
 572       }
 573       r = _regions.next();
 574     }
 575   }
 576 };
 577 
 578 class ShenandoahAdjustRootPointersTask : public AbstractGangTask {
 579 private:
 580   ShenandoahRootProcessor* _rp;
 581 
 582 public:
 583   ShenandoahAdjustRootPointersTask(ShenandoahRootProcessor* rp) :
 584     AbstractGangTask("Shenandoah Adjust Root Pointers Task"),
 585     _rp(rp) {}
 586 
 587   void work(uint worker_id) {
 588     ShenandoahAdjustPointersClosure cl;
 589     CLDToOopClosure adjust_cld_closure(&cl, true);
 590     MarkingCodeBlobClosure adjust_code_closure(&cl,
 591                                              CodeBlobToOopClosure::FixRelocations);
 592 
 593     _rp->process_all_roots(&cl, &cl,
 594                            &adjust_cld_closure,
 595                            &adjust_code_closure, NULL, worker_id);
 596   }
 597 };
 598 
 599 void ShenandoahMarkCompact::phase3_update_references() {
 600   GCTraceTime(Info, gc, phases) time("Phase 3: Adjust pointers", _gc_timer);
 601   ShenandoahGCPhase adjust_pointer_phase(ShenandoahPhaseTimings::full_gc_adjust_pointers);
 602 
 603   ShenandoahHeap* heap = ShenandoahHeap::heap();
 604 
 605   if (UseShenandoahMatrix) {
 606     heap->connection_matrix()->clear_all();
 607   }
 608 
 609   WorkGang* workers = heap->workers();
 610   uint nworkers = workers->active_workers();
 611   {
 612 #if COMPILER2_OR_JVMCI
 613     DerivedPointerTable::clear();
 614 #endif
 615     ShenandoahRootProcessor rp(heap, nworkers, ShenandoahPhaseTimings::full_gc_roots);
 616     ShenandoahAdjustRootPointersTask task(&rp);
 617     workers->run_task(&task);
 618 #if COMPILER2_OR_JVMCI
 619     DerivedPointerTable::update_pointers();
 620 #endif
 621   }
 622 
 623   ShenandoahAdjustPointersTask adjust_pointers_task;
 624   workers->run_task(&adjust_pointers_task);
 625 }
 626 
 627 class ShenandoahCompactObjectsClosure : public ObjectClosure {
 628 private:
 629   ShenandoahHeap* const _heap;
 630   uint            const _worker_id;
 631 
 632 public:
 633   ShenandoahCompactObjectsClosure(uint worker_id) :
 634     _heap(ShenandoahHeap::heap()), _worker_id(worker_id) {}
 635 
 636   void do_object(oop p) {
 637     assert(_heap->is_marked_complete(p), "must be marked");
 638     size_t size = (size_t)p->size();
 639     HeapWord* compact_to = BrooksPointer::get_raw(p);
 640     HeapWord* compact_from = (HeapWord*) p;
 641     if (compact_from != compact_to) {
 642       Copy::aligned_conjoint_words(compact_from, compact_to, size);
 643     }
 644     oop new_obj = oop(compact_to);
 645     BrooksPointer::initialize(new_obj);
 646   }
 647 };
 648 
 649 class ShenandoahCompactObjectsTask : public AbstractGangTask {
 650 private:
 651   ShenandoahHeap* const _heap;
 652   ShenandoahHeapRegionSet** const _worker_slices;
 653 
 654 public:
 655   ShenandoahCompactObjectsTask(ShenandoahHeapRegionSet** worker_slices) :
 656     AbstractGangTask("Shenandoah Compact Objects Task"),
 657     _heap(ShenandoahHeap::heap()),
 658     _worker_slices(worker_slices) {
 659   }
 660 
 661   void work(uint worker_id) {
 662     ShenandoahHeapRegionSetIterator slice(_worker_slices[worker_id]);
 663 
 664     ShenandoahCompactObjectsClosure cl(worker_id);
 665     ShenandoahHeapRegion* r = slice.next();
 666     while (r != NULL) {
 667       assert(!r->is_humongous(), "must not get humongous regions here");
 668       _heap->marked_object_iterate(r, &cl);
 669       r->set_top(r->new_top());
 670       r = slice.next();
 671     }
 672   }
 673 };
 674 
 675 class ShenandoahPostCompactClosure : public ShenandoahHeapRegionClosure {
 676 private:
 677   ShenandoahHeap* const _heap;
 678   size_t _live;
 679 
 680 public:
 681   ShenandoahPostCompactClosure() : _live(0), _heap(ShenandoahHeap::heap()) {
 682     _heap->free_set()->clear();
 683   }
 684 
 685   bool heap_region_do(ShenandoahHeapRegion* r) {
 686     assert (!r->is_cset(), "cset regions should have been demoted already");
 687 
 688     // Need to reset the complete-top-at-mark-start pointer here because
 689     // the complete marking bitmap is no longer valid. This ensures
 690     // size-based iteration in marked_object_iterate().
 691     // NOTE: See blurb at ShenandoahMCResetCompleteBitmapTask on why we need to skip
 692     // pinned regions.
 693     if (!r->is_pinned()) {
 694       _heap->set_complete_top_at_mark_start(r->bottom(), r->bottom());
 695     }
 696 
 697     size_t live = r->used();
 698 
 699     // Make empty regions that have been allocated into regular
 700     if (r->is_empty() && live > 0) {
 701       r->make_regular_bypass();
 702     }
 703 
 704     // Reclaim regular regions that became empty
 705     if (r->is_regular() && live == 0) {
 706       r->make_trash();
 707     }
 708 
 709     // Recycle all trash regions
 710     if (r->is_trash()) {
 711       live = 0;
 712       r->recycle();
 713     }
 714 
 715     r->set_live_data(live);
 716     r->reset_alloc_metadata_to_shared();
 717     _live += live;
 718     return false;
 719   }
 720 
 721   size_t get_live() {
 722     return _live;
 723   }
 724 };
 725 
 726 void ShenandoahMarkCompact::compact_humongous_objects() {
 727   // Compact humongous regions, based on their fwdptr objects.
 728   //
 729   // This code is serial, because doing the in-slice parallel sliding is tricky. In most cases,
 730   // humongous regions are already compacted, and do not require further moves, which alleviates
 731   // sliding costs. We may consider doing this in parallel in future.
 732 
 733   ShenandoahHeap* heap = ShenandoahHeap::heap();
 734 
 735   for (size_t c = heap->num_regions() - 1; c > 0; c--) {
 736     ShenandoahHeapRegion* r = heap->get_region(c);
 737     if (r->is_humongous_start()) {
 738       oop old_obj = oop(r->bottom() + BrooksPointer::word_size());
 739       size_t words_size = old_obj->size() + BrooksPointer::word_size();
 740       size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);
 741 
 742       size_t old_start = r->region_number();
 743       size_t old_end   = old_start + num_regions - 1;
 744       size_t new_start = heap->heap_region_index_containing(BrooksPointer::get_raw(old_obj));
 745       size_t new_end   = new_start + num_regions - 1;
 746 
 747       if (old_start == new_start) {
 748         // No need to move the object, it stays at the same slot
 749         continue;
 750       }
 751 
 752       assert (r->is_move_allowed(), "should be movable");
 753 
 754       Copy::aligned_conjoint_words(heap->get_region(old_start)->bottom(),
 755                                    heap->get_region(new_start)->bottom(),
 756                                    ShenandoahHeapRegion::region_size_words()*num_regions);
 757 
 758       oop new_obj = oop(heap->get_region(new_start)->bottom() + BrooksPointer::word_size());
 759       BrooksPointer::initialize(new_obj);
 760 
 761       {
 762         ShenandoahHeapLocker lock(heap->lock());
 763 
 764         for (size_t c = old_start; c <= old_end; c++) {
 765           ShenandoahHeapRegion* r = heap->get_region(c);
 766           r->make_regular_bypass();
 767           r->set_top(r->bottom());
 768         }
 769 
 770         for (size_t c = new_start; c <= new_end; c++) {
 771           ShenandoahHeapRegion* r = heap->get_region(c);
 772           if (c == new_start) {
 773             r->make_humongous_start_bypass();
 774           } else {
 775             r->make_humongous_cont_bypass();
 776           }
 777 
 778           // Trailing region may be non-full, record the remainder there
 779           size_t remainder = words_size & ShenandoahHeapRegion::region_size_words_mask();
 780           if ((c == new_end) && (remainder != 0)) {
 781             r->set_top(r->bottom() + remainder);
 782           } else {
 783             r->set_top(r->end());
 784           }
 785 
 786           r->reset_alloc_metadata_to_shared();
 787         }
 788       }
 789     }
 790   }
 791 }
 792 
 793 // This is slightly different to ShHeap::reset_next_mark_bitmap:
 794 // we need to remain able to walk pinned regions.
 795 // Since pinned region do not move and don't get compacted, we will get holes with
 796 // unreachable objects in them (which may have pointers to unloaded Klasses and thus
 797 // cannot be iterated over using oop->size(). The only way to safely iterate over those is using
 798 // a valid marking bitmap and valid TAMS pointer. This class only resets marking
 799 // bitmaps for un-pinned regions, and later we only reset TAMS for unpinned regions.
 800 class ShenandoahMCResetCompleteBitmapTask : public AbstractGangTask {
 801 private:
 802   ShenandoahRegionIterator _regions;
 803 
 804 public:
 805   ShenandoahMCResetCompleteBitmapTask() :
 806     AbstractGangTask("Parallel Reset Bitmap Task") {
 807   }
 808 
 809   void work(uint worker_id) {
 810     ShenandoahHeapRegion* region = _regions.next();
 811     ShenandoahHeap* heap = ShenandoahHeap::heap();
 812     while (region != NULL) {
 813       if (heap->is_bitmap_slice_committed(region) && !region->is_pinned()) {
 814         HeapWord* bottom = region->bottom();
 815         HeapWord* top = heap->complete_top_at_mark_start(region->bottom());
 816         if (top > bottom) {
 817           heap->complete_mark_bit_map()->clear_range_large(MemRegion(bottom, top));
 818         }
 819         assert(heap->is_complete_bitmap_clear_range(bottom, region->end()), "must be clear");
 820       }
 821       region = _regions.next();
 822     }
 823   }
 824 };
 825 
 826 void ShenandoahMarkCompact::phase4_compact_objects(ShenandoahHeapRegionSet** worker_slices) {
 827   GCTraceTime(Info, gc, phases) time("Phase 4: Move objects", _gc_timer);
 828   ShenandoahGCPhase compaction_phase(ShenandoahPhaseTimings::full_gc_copy_objects);
 829 
 830   ShenandoahHeap* heap = ShenandoahHeap::heap();
 831 
 832   // Compact regular objects first
 833   {
 834     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_regular);
 835     ShenandoahCompactObjectsTask compact_task(worker_slices);
 836     heap->workers()->run_task(&compact_task);
 837   }
 838 
 839   // Compact humongous objects after regular object moves
 840   {
 841     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_humong);
 842     compact_humongous_objects();
 843   }
 844 
 845   // Reset complete bitmap. We're about to reset the complete-top-at-mark-start pointer
 846   // and must ensure the bitmap is in sync.
 847   ShenandoahMCResetCompleteBitmapTask task;
 848   heap->workers()->run_task(&task);
 849 
 850   // Bring regions in proper states after the collection, and set heap properties.
 851   {
 852     ShenandoahHeapLocker lock(heap->lock());
 853     ShenandoahPostCompactClosure post_compact;
 854     heap->heap_region_iterate(&post_compact);
 855     heap->set_used(post_compact.get_live());
 856 
 857     heap->collection_set()->clear();
 858     heap->free_set()->rebuild();
 859   }
 860 
 861   heap->clear_cancelled_concgc();
 862 
 863   // Also clear the next bitmap in preparation for next marking.
 864   heap->reset_next_mark_bitmap();
 865 }