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