Path: blob/master/src/hotspot/share/gc/shenandoah/shenandoahFullGC.cpp
40957 views
/*1* Copyright (c) 2014, 2021, Red Hat, Inc. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 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 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"2526#include "compiler/oopMap.hpp"27#include "gc/shared/gcTraceTime.inline.hpp"28#include "gc/shared/preservedMarks.inline.hpp"29#include "gc/shared/tlab_globals.hpp"30#include "gc/shenandoah/heuristics/shenandoahHeuristics.hpp"31#include "gc/shenandoah/shenandoahConcurrentGC.hpp"32#include "gc/shenandoah/shenandoahCollectionSet.hpp"33#include "gc/shenandoah/shenandoahFreeSet.hpp"34#include "gc/shenandoah/shenandoahFullGC.hpp"35#include "gc/shenandoah/shenandoahPhaseTimings.hpp"36#include "gc/shenandoah/shenandoahMark.inline.hpp"37#include "gc/shenandoah/shenandoahMonitoringSupport.hpp"38#include "gc/shenandoah/shenandoahHeapRegionSet.hpp"39#include "gc/shenandoah/shenandoahHeap.inline.hpp"40#include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"41#include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"42#include "gc/shenandoah/shenandoahMetrics.hpp"43#include "gc/shenandoah/shenandoahOopClosures.inline.hpp"44#include "gc/shenandoah/shenandoahReferenceProcessor.hpp"45#include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"46#include "gc/shenandoah/shenandoahSTWMark.hpp"47#include "gc/shenandoah/shenandoahUtils.hpp"48#include "gc/shenandoah/shenandoahVerifier.hpp"49#include "gc/shenandoah/shenandoahVMOperations.hpp"50#include "gc/shenandoah/shenandoahWorkerPolicy.hpp"51#include "memory/metaspaceUtils.hpp"52#include "memory/universe.hpp"53#include "oops/compressedOops.inline.hpp"54#include "oops/oop.inline.hpp"55#include "runtime/biasedLocking.hpp"56#include "runtime/orderAccess.hpp"57#include "runtime/thread.hpp"58#include "runtime/vmThread.hpp"59#include "utilities/copy.hpp"60#include "utilities/events.hpp"61#include "utilities/growableArray.hpp"62#include "gc/shared/workgroup.hpp"6364ShenandoahFullGC::ShenandoahFullGC() :65_gc_timer(ShenandoahHeap::heap()->gc_timer()),66_preserved_marks(new PreservedMarksSet(true)) {}6768bool ShenandoahFullGC::collect(GCCause::Cause cause) {69vmop_entry_full(cause);70// Always success71return true;72}7374void ShenandoahFullGC::vmop_entry_full(GCCause::Cause cause) {75ShenandoahHeap* const heap = ShenandoahHeap::heap();76TraceCollectorStats tcs(heap->monitoring_support()->full_stw_collection_counters());77ShenandoahTimingsTracker timing(ShenandoahPhaseTimings::full_gc_gross);7879heap->try_inject_alloc_failure();80VM_ShenandoahFullGC op(cause, this);81VMThread::execute(&op);82}8384void ShenandoahFullGC::entry_full(GCCause::Cause cause) {85static const char* msg = "Pause Full";86ShenandoahPausePhase gc_phase(msg, ShenandoahPhaseTimings::full_gc, true /* log_heap_usage */);87EventMark em("%s", msg);8889ShenandoahWorkerScope scope(ShenandoahHeap::heap()->workers(),90ShenandoahWorkerPolicy::calc_workers_for_fullgc(),91"full gc");9293op_full(cause);94}9596void ShenandoahFullGC::op_full(GCCause::Cause cause) {97ShenandoahMetricsSnapshot metrics;98metrics.snap_before();99100// Perform full GC101do_it(cause);102103metrics.snap_after();104105if (metrics.is_good_progress()) {106ShenandoahHeap::heap()->notify_gc_progress();107} else {108// Nothing to do. Tell the allocation path that we have failed to make109// progress, and it can finally fail.110ShenandoahHeap::heap()->notify_gc_no_progress();111}112}113114void ShenandoahFullGC::do_it(GCCause::Cause gc_cause) {115ShenandoahHeap* heap = ShenandoahHeap::heap();116117if (ShenandoahVerify) {118heap->verifier()->verify_before_fullgc();119}120121if (VerifyBeforeGC) {122Universe::verify();123}124125// Degenerated GC may carry concurrent root flags when upgrading to126// full GC. We need to reset it before mutators resume.127heap->set_concurrent_strong_root_in_progress(false);128heap->set_concurrent_weak_root_in_progress(false);129130heap->set_full_gc_in_progress(true);131132assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at a safepoint");133assert(Thread::current()->is_VM_thread(), "Do full GC only while world is stopped");134135{136ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdump_pre);137heap->pre_full_gc_dump(_gc_timer);138}139140{141ShenandoahGCPhase prepare_phase(ShenandoahPhaseTimings::full_gc_prepare);142// Full GC is supposed to recover from any GC state:143144// a0. Remember if we have forwarded objects145bool has_forwarded_objects = heap->has_forwarded_objects();146147// a1. Cancel evacuation, if in progress148if (heap->is_evacuation_in_progress()) {149heap->set_evacuation_in_progress(false);150}151assert(!heap->is_evacuation_in_progress(), "sanity");152153// a2. Cancel update-refs, if in progress154if (heap->is_update_refs_in_progress()) {155heap->set_update_refs_in_progress(false);156}157assert(!heap->is_update_refs_in_progress(), "sanity");158159// b. Cancel concurrent mark, if in progress160if (heap->is_concurrent_mark_in_progress()) {161ShenandoahConcurrentGC::cancel();162heap->set_concurrent_mark_in_progress(false);163}164assert(!heap->is_concurrent_mark_in_progress(), "sanity");165166// c. Update roots if this full GC is due to evac-oom, which may carry from-space pointers in roots.167if (has_forwarded_objects) {168update_roots(true /*full_gc*/);169}170171// d. Reset the bitmaps for new marking172heap->reset_mark_bitmap();173assert(heap->marking_context()->is_bitmap_clear(), "sanity");174assert(!heap->marking_context()->is_complete(), "sanity");175176// e. Abandon reference discovery and clear all discovered references.177ShenandoahReferenceProcessor* rp = heap->ref_processor();178rp->abandon_partial_discovery();179180// f. Sync pinned region status from the CP marks181heap->sync_pinned_region_status();182183// The rest of prologue:184BiasedLocking::preserve_marks();185_preserved_marks->init(heap->workers()->active_workers());186187assert(heap->has_forwarded_objects() == has_forwarded_objects, "This should not change");188}189190if (UseTLAB) {191heap->gclabs_retire(ResizeTLAB);192heap->tlabs_retire(ResizeTLAB);193}194195OrderAccess::fence();196197phase1_mark_heap();198199// 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.202heap->set_has_forwarded_objects(false);203204heap->set_full_gc_move_in_progress(true);205206// Setup workers for the rest207OrderAccess::fence();208209// Initialize worker slices210ShenandoahHeapRegionSet** worker_slices = NEW_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, heap->max_workers(), mtGC);211for (uint i = 0; i < heap->max_workers(); i++) {212worker_slices[i] = new ShenandoahHeapRegionSet();213}214215{216// The rest of code performs region moves, where region status is undefined217// until all phases run together.218ShenandoahHeapLocker lock(heap->lock());219220phase2_calculate_target_addresses(worker_slices);221222OrderAccess::fence();223224phase3_update_references();225226phase4_compact_objects(worker_slices);227}228229{230// Epilogue231_preserved_marks->restore(heap->workers());232BiasedLocking::restore_marks();233_preserved_marks->reclaim();234}235236// Resize metaspace237MetaspaceGC::compute_new_size();238239// Free worker slices240for (uint i = 0; i < heap->max_workers(); i++) {241delete worker_slices[i];242}243FREE_C_HEAP_ARRAY(ShenandoahHeapRegionSet*, worker_slices);244245heap->set_full_gc_move_in_progress(false);246heap->set_full_gc_in_progress(false);247248if (ShenandoahVerify) {249heap->verifier()->verify_after_fullgc();250}251252if (VerifyAfterGC) {253Universe::verify();254}255256{257ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_heapdump_post);258heap->post_full_gc_dump(_gc_timer);259}260}261262class ShenandoahPrepareForMarkClosure: public ShenandoahHeapRegionClosure {263private:264ShenandoahMarkingContext* const _ctx;265266public:267ShenandoahPrepareForMarkClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}268269void heap_region_do(ShenandoahHeapRegion *r) {270_ctx->capture_top_at_mark_start(r);271r->clear_live_data();272}273};274275void ShenandoahFullGC::phase1_mark_heap() {276GCTraceTime(Info, gc, phases) time("Phase 1: Mark live objects", _gc_timer);277ShenandoahGCPhase mark_phase(ShenandoahPhaseTimings::full_gc_mark);278279ShenandoahHeap* heap = ShenandoahHeap::heap();280281ShenandoahPrepareForMarkClosure cl;282heap->heap_region_iterate(&cl);283284heap->set_unload_classes(heap->heuristics()->can_unload_classes());285286ShenandoahReferenceProcessor* rp = heap->ref_processor();287// enable ("weak") refs discovery288rp->set_soft_reference_policy(true); // forcefully purge all soft references289290ShenandoahSTWMark mark(true /*full_gc*/);291mark.mark();292heap->parallel_cleaning(true /* full_gc */);293}294295class ShenandoahPrepareForCompactionObjectClosure : public ObjectClosure {296private:297PreservedMarks* const _preserved_marks;298ShenandoahHeap* const _heap;299GrowableArray<ShenandoahHeapRegion*>& _empty_regions;300int _empty_regions_pos;301ShenandoahHeapRegion* _to_region;302ShenandoahHeapRegion* _from_region;303HeapWord* _compact_point;304305public:306ShenandoahPrepareForCompactionObjectClosure(PreservedMarks* preserved_marks,307GrowableArray<ShenandoahHeapRegion*>& empty_regions,308ShenandoahHeapRegion* to_region) :309_preserved_marks(preserved_marks),310_heap(ShenandoahHeap::heap()),311_empty_regions(empty_regions),312_empty_regions_pos(0),313_to_region(to_region),314_from_region(NULL),315_compact_point(to_region->bottom()) {}316317void set_from_region(ShenandoahHeapRegion* from_region) {318_from_region = from_region;319}320321void finish_region() {322assert(_to_region != NULL, "should not happen");323_to_region->set_new_top(_compact_point);324}325326bool is_compact_same_region() {327return _from_region == _to_region;328}329330int empty_regions_pos() {331return _empty_regions_pos;332}333334void do_object(oop p) {335assert(_from_region != NULL, "must set before work");336assert(_heap->complete_marking_context()->is_marked(p), "must be marked");337assert(!_heap->complete_marking_context()->allocated_after_mark_start(p), "must be truly marked");338339size_t obj_size = p->size();340if (_compact_point + obj_size > _to_region->end()) {341finish_region();342343// Object doesn't fit. Pick next empty region and start compacting there.344ShenandoahHeapRegion* new_to_region;345if (_empty_regions_pos < _empty_regions.length()) {346new_to_region = _empty_regions.at(_empty_regions_pos);347_empty_regions_pos++;348} else {349// Out of empty region? Compact within the same region.350new_to_region = _from_region;351}352353assert(new_to_region != _to_region, "must not reuse same to-region");354assert(new_to_region != NULL, "must not be NULL");355_to_region = new_to_region;356_compact_point = _to_region->bottom();357}358359// Object fits into current region, record new location:360assert(_compact_point + obj_size <= _to_region->end(), "must fit");361shenandoah_assert_not_forwarded(NULL, p);362_preserved_marks->push_if_necessary(p, p->mark());363p->forward_to(cast_to_oop(_compact_point));364_compact_point += obj_size;365}366};367368class ShenandoahPrepareForCompactionTask : public AbstractGangTask {369private:370PreservedMarksSet* const _preserved_marks;371ShenandoahHeap* const _heap;372ShenandoahHeapRegionSet** const _worker_slices;373374public:375ShenandoahPrepareForCompactionTask(PreservedMarksSet *preserved_marks, ShenandoahHeapRegionSet **worker_slices) :376AbstractGangTask("Shenandoah Prepare For Compaction"),377_preserved_marks(preserved_marks),378_heap(ShenandoahHeap::heap()), _worker_slices(worker_slices) {379}380381static bool is_candidate_region(ShenandoahHeapRegion* r) {382// Empty region: get it into the slice to defragment the slice itself.383// We could have skipped this without violating correctness, but we really384// want to compact all live regions to the start of the heap, which sometimes385// means moving them into the fully empty regions.386if (r->is_empty()) return true;387388// Can move the region, and this is not the humongous region. Humongous389// moves are special cased here, because their moves are handled separately.390return r->is_stw_move_allowed() && !r->is_humongous();391}392393void work(uint worker_id) {394ShenandoahParallelWorkerSession worker_session(worker_id);395ShenandoahHeapRegionSet* slice = _worker_slices[worker_id];396ShenandoahHeapRegionSetIterator it(slice);397ShenandoahHeapRegion* from_region = it.next();398// No work?399if (from_region == NULL) {400return;401}402403// Sliding compaction. Walk all regions in the slice, and compact them.404// Remember empty regions and reuse them as needed.405ResourceMark rm;406407GrowableArray<ShenandoahHeapRegion*> empty_regions((int)_heap->num_regions());408409ShenandoahPrepareForCompactionObjectClosure cl(_preserved_marks->get(worker_id), empty_regions, from_region);410411while (from_region != NULL) {412assert(is_candidate_region(from_region), "Sanity");413414cl.set_from_region(from_region);415if (from_region->has_live()) {416_heap->marked_object_iterate(from_region, &cl);417}418419// Compacted the region to somewhere else? From-region is empty then.420if (!cl.is_compact_same_region()) {421empty_regions.append(from_region);422}423from_region = it.next();424}425cl.finish_region();426427// Mark all remaining regions as empty428for (int pos = cl.empty_regions_pos(); pos < empty_regions.length(); ++pos) {429ShenandoahHeapRegion* r = empty_regions.at(pos);430r->set_new_top(r->bottom());431}432}433};434435void ShenandoahFullGC::calculate_target_humongous_objects() {436ShenandoahHeap* heap = ShenandoahHeap::heap();437438// Compute the new addresses for humongous objects. We need to do this after addresses439// for regular objects are calculated, and we know what regions in heap suffix are440// available for humongous moves.441//442// Scan the heap backwards, because we are compacting humongous regions towards the end.443// Maintain the contiguous compaction window in [to_begin; to_end), so that we can slide444// humongous start there.445//446// The complication is potential non-movable regions during the scan. If such region is447// detected, then sliding restarts towards that non-movable region.448449size_t to_begin = heap->num_regions();450size_t to_end = heap->num_regions();451452for (size_t c = heap->num_regions(); c > 0; c--) {453ShenandoahHeapRegion *r = heap->get_region(c - 1);454if (r->is_humongous_continuation() || (r->new_top() == r->bottom())) {455// To-region candidate: record this, and continue scan456to_begin = r->index();457continue;458}459460if (r->is_humongous_start() && r->is_stw_move_allowed()) {461// From-region candidate: movable humongous region462oop old_obj = cast_to_oop(r->bottom());463size_t words_size = old_obj->size();464size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);465466size_t start = to_end - num_regions;467468if (start >= to_begin && start != r->index()) {469// Fits into current window, and the move is non-trivial. Record the move then, and continue scan.470_preserved_marks->get(0)->push_if_necessary(old_obj, old_obj->mark());471old_obj->forward_to(cast_to_oop(heap->get_region(start)->bottom()));472to_end = start;473continue;474}475}476477// Failed to fit. Scan starting from current region.478to_begin = r->index();479to_end = r->index();480}481}482483class ShenandoahEnsureHeapActiveClosure: public ShenandoahHeapRegionClosure {484private:485ShenandoahHeap* const _heap;486487public:488ShenandoahEnsureHeapActiveClosure() : _heap(ShenandoahHeap::heap()) {}489void heap_region_do(ShenandoahHeapRegion* r) {490if (r->is_trash()) {491r->recycle();492}493if (r->is_cset()) {494r->make_regular_bypass();495}496if (r->is_empty_uncommitted()) {497r->make_committed_bypass();498}499assert (r->is_committed(), "only committed regions in heap now, see region " SIZE_FORMAT, r->index());500501// Record current region occupancy: this communicates empty regions are free502// to the rest of Full GC code.503r->set_new_top(r->top());504}505};506507class ShenandoahTrashImmediateGarbageClosure: public ShenandoahHeapRegionClosure {508private:509ShenandoahHeap* const _heap;510ShenandoahMarkingContext* const _ctx;511512public:513ShenandoahTrashImmediateGarbageClosure() :514_heap(ShenandoahHeap::heap()),515_ctx(ShenandoahHeap::heap()->complete_marking_context()) {}516517void heap_region_do(ShenandoahHeapRegion* r) {518if (r->is_humongous_start()) {519oop humongous_obj = cast_to_oop(r->bottom());520if (!_ctx->is_marked(humongous_obj)) {521assert(!r->has_live(),522"Region " SIZE_FORMAT " is not marked, should not have live", r->index());523_heap->trash_humongous_region_at(r);524} else {525assert(r->has_live(),526"Region " SIZE_FORMAT " should have live", r->index());527}528} else if (r->is_humongous_continuation()) {529// If we hit continuation, the non-live humongous starts should have been trashed already530assert(r->humongous_start_region()->has_live(),531"Region " SIZE_FORMAT " should have live", r->index());532} else if (r->is_regular()) {533if (!r->has_live()) {534r->make_trash_immediate();535}536}537}538};539540void ShenandoahFullGC::distribute_slices(ShenandoahHeapRegionSet** worker_slices) {541ShenandoahHeap* heap = ShenandoahHeap::heap();542543uint n_workers = heap->workers()->active_workers();544size_t n_regions = heap->num_regions();545546// What we want to accomplish: have the dense prefix of data, while still balancing547// out the parallel work.548//549// Assuming the amount of work is driven by the live data that needs moving, we can slice550// the entire heap into equal-live-sized prefix slices, and compact into them. So, each551// thread takes all regions in its prefix subset, and then it takes some regions from552// the tail.553//554// Tail region selection becomes interesting.555//556// First, we want to distribute the regions fairly between the workers, and those regions557// might have different amount of live data. So, until we sure no workers need live data,558// we need to only take what the worker needs.559//560// Second, since we slide everything to the left in each slice, the most busy regions561// would be the ones on the left. Which means we want to have all workers have their after-tail562// regions as close to the left as possible.563//564// The easiest way to do this is to distribute after-tail regions in round-robin between565// workers that still need live data.566//567// Consider parallel workers A, B, C, then the target slice layout would be:568//569// AAAAAAAABBBBBBBBCCCCCCCC|ABCABCABCABCABCABCABCABABABABABABABABABABAAAAA570//571// (.....dense-prefix.....) (.....................tail...................)572// [all regions fully live] [left-most regions are fuller that right-most]573//574575// Compute how much live data is there. This would approximate the size of dense prefix576// we target to create.577size_t total_live = 0;578for (size_t idx = 0; idx < n_regions; idx++) {579ShenandoahHeapRegion *r = heap->get_region(idx);580if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {581total_live += r->get_live_data_words();582}583}584585// Estimate the size for the dense prefix. Note that we specifically count only the586// "full" regions, so there would be some non-full regions in the slice tail.587size_t live_per_worker = total_live / n_workers;588size_t prefix_regions_per_worker = live_per_worker / ShenandoahHeapRegion::region_size_words();589size_t prefix_regions_total = prefix_regions_per_worker * n_workers;590prefix_regions_total = MIN2(prefix_regions_total, n_regions);591assert(prefix_regions_total <= n_regions, "Sanity");592593// There might be non-candidate regions in the prefix. To compute where the tail actually594// ends up being, we need to account those as well.595size_t prefix_end = prefix_regions_total;596for (size_t idx = 0; idx < prefix_regions_total; idx++) {597ShenandoahHeapRegion *r = heap->get_region(idx);598if (!ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {599prefix_end++;600}601}602prefix_end = MIN2(prefix_end, n_regions);603assert(prefix_end <= n_regions, "Sanity");604605// Distribute prefix regions per worker: each thread definitely gets its own same-sized606// subset of dense prefix.607size_t prefix_idx = 0;608609size_t* live = NEW_C_HEAP_ARRAY(size_t, n_workers, mtGC);610611for (size_t wid = 0; wid < n_workers; wid++) {612ShenandoahHeapRegionSet* slice = worker_slices[wid];613614live[wid] = 0;615size_t regs = 0;616617// Add all prefix regions for this worker618while (prefix_idx < prefix_end && regs < prefix_regions_per_worker) {619ShenandoahHeapRegion *r = heap->get_region(prefix_idx);620if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {621slice->add_region(r);622live[wid] += r->get_live_data_words();623regs++;624}625prefix_idx++;626}627}628629// Distribute the tail among workers in round-robin fashion.630size_t wid = n_workers - 1;631632for (size_t tail_idx = prefix_end; tail_idx < n_regions; tail_idx++) {633ShenandoahHeapRegion *r = heap->get_region(tail_idx);634if (ShenandoahPrepareForCompactionTask::is_candidate_region(r)) {635assert(wid < n_workers, "Sanity");636637size_t live_region = r->get_live_data_words();638639// Select next worker that still needs live data.640size_t old_wid = wid;641do {642wid++;643if (wid == n_workers) wid = 0;644} while (live[wid] + live_region >= live_per_worker && old_wid != wid);645646if (old_wid == wid) {647// Circled back to the same worker? This means liveness data was648// miscalculated. Bump the live_per_worker limit so that649// everyone gets a piece of the leftover work.650live_per_worker += ShenandoahHeapRegion::region_size_words();651}652653worker_slices[wid]->add_region(r);654live[wid] += live_region;655}656}657658FREE_C_HEAP_ARRAY(size_t, live);659660#ifdef ASSERT661ResourceBitMap map(n_regions);662for (size_t wid = 0; wid < n_workers; wid++) {663ShenandoahHeapRegionSetIterator it(worker_slices[wid]);664ShenandoahHeapRegion* r = it.next();665while (r != NULL) {666size_t idx = r->index();667assert(ShenandoahPrepareForCompactionTask::is_candidate_region(r), "Sanity: " SIZE_FORMAT, idx);668assert(!map.at(idx), "No region distributed twice: " SIZE_FORMAT, idx);669map.at_put(idx, true);670r = it.next();671}672}673674for (size_t rid = 0; rid < n_regions; rid++) {675bool is_candidate = ShenandoahPrepareForCompactionTask::is_candidate_region(heap->get_region(rid));676bool is_distributed = map.at(rid);677assert(is_distributed || !is_candidate, "All candidates are distributed: " SIZE_FORMAT, rid);678}679#endif680}681682void ShenandoahFullGC::phase2_calculate_target_addresses(ShenandoahHeapRegionSet** worker_slices) {683GCTraceTime(Info, gc, phases) time("Phase 2: Compute new object addresses", _gc_timer);684ShenandoahGCPhase calculate_address_phase(ShenandoahPhaseTimings::full_gc_calculate_addresses);685686ShenandoahHeap* heap = ShenandoahHeap::heap();687688// About to figure out which regions can be compacted, make sure pinning status689// had been updated in GC prologue.690heap->assert_pinned_region_status();691692{693// Trash the immediately collectible regions before computing addresses694ShenandoahTrashImmediateGarbageClosure tigcl;695heap->heap_region_iterate(&tigcl);696697// Make sure regions are in good state: committed, active, clean.698// This is needed because we are potentially sliding the data through them.699ShenandoahEnsureHeapActiveClosure ecl;700heap->heap_region_iterate(&ecl);701}702703// Compute the new addresses for regular objects704{705ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_regular);706707distribute_slices(worker_slices);708709ShenandoahPrepareForCompactionTask task(_preserved_marks, worker_slices);710heap->workers()->run_task(&task);711}712713// Compute the new addresses for humongous objects714{715ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_calculate_addresses_humong);716calculate_target_humongous_objects();717}718}719720class ShenandoahAdjustPointersClosure : public MetadataVisitingOopIterateClosure {721private:722ShenandoahHeap* const _heap;723ShenandoahMarkingContext* const _ctx;724725template <class T>726inline void do_oop_work(T* p) {727T o = RawAccess<>::oop_load(p);728if (!CompressedOops::is_null(o)) {729oop obj = CompressedOops::decode_not_null(o);730assert(_ctx->is_marked(obj), "must be marked");731if (obj->is_forwarded()) {732oop forw = obj->forwardee();733RawAccess<IS_NOT_NULL>::oop_store(p, forw);734}735}736}737738public:739ShenandoahAdjustPointersClosure() :740_heap(ShenandoahHeap::heap()),741_ctx(ShenandoahHeap::heap()->complete_marking_context()) {}742743void do_oop(oop* p) { do_oop_work(p); }744void do_oop(narrowOop* p) { do_oop_work(p); }745};746747class ShenandoahAdjustPointersObjectClosure : public ObjectClosure {748private:749ShenandoahHeap* const _heap;750ShenandoahAdjustPointersClosure _cl;751752public:753ShenandoahAdjustPointersObjectClosure() :754_heap(ShenandoahHeap::heap()) {755}756void do_object(oop p) {757assert(_heap->complete_marking_context()->is_marked(p), "must be marked");758p->oop_iterate(&_cl);759}760};761762class ShenandoahAdjustPointersTask : public AbstractGangTask {763private:764ShenandoahHeap* const _heap;765ShenandoahRegionIterator _regions;766767public:768ShenandoahAdjustPointersTask() :769AbstractGangTask("Shenandoah Adjust Pointers"),770_heap(ShenandoahHeap::heap()) {771}772773void work(uint worker_id) {774ShenandoahParallelWorkerSession worker_session(worker_id);775ShenandoahAdjustPointersObjectClosure obj_cl;776ShenandoahHeapRegion* r = _regions.next();777while (r != NULL) {778if (!r->is_humongous_continuation() && r->has_live()) {779_heap->marked_object_iterate(r, &obj_cl);780}781r = _regions.next();782}783}784};785786class ShenandoahAdjustRootPointersTask : public AbstractGangTask {787private:788ShenandoahRootAdjuster* _rp;789PreservedMarksSet* _preserved_marks;790public:791ShenandoahAdjustRootPointersTask(ShenandoahRootAdjuster* rp, PreservedMarksSet* preserved_marks) :792AbstractGangTask("Shenandoah Adjust Root Pointers"),793_rp(rp),794_preserved_marks(preserved_marks) {}795796void work(uint worker_id) {797ShenandoahParallelWorkerSession worker_session(worker_id);798ShenandoahAdjustPointersClosure cl;799_rp->roots_do(worker_id, &cl);800_preserved_marks->get(worker_id)->adjust_during_full_gc();801}802};803804void ShenandoahFullGC::phase3_update_references() {805GCTraceTime(Info, gc, phases) time("Phase 3: Adjust pointers", _gc_timer);806ShenandoahGCPhase adjust_pointer_phase(ShenandoahPhaseTimings::full_gc_adjust_pointers);807808ShenandoahHeap* heap = ShenandoahHeap::heap();809810WorkGang* workers = heap->workers();811uint nworkers = workers->active_workers();812{813#if COMPILER2_OR_JVMCI814DerivedPointerTable::clear();815#endif816ShenandoahRootAdjuster rp(nworkers, ShenandoahPhaseTimings::full_gc_adjust_roots);817ShenandoahAdjustRootPointersTask task(&rp, _preserved_marks);818workers->run_task(&task);819#if COMPILER2_OR_JVMCI820DerivedPointerTable::update_pointers();821#endif822}823824ShenandoahAdjustPointersTask adjust_pointers_task;825workers->run_task(&adjust_pointers_task);826}827828class ShenandoahCompactObjectsClosure : public ObjectClosure {829private:830ShenandoahHeap* const _heap;831uint const _worker_id;832833public:834ShenandoahCompactObjectsClosure(uint worker_id) :835_heap(ShenandoahHeap::heap()), _worker_id(worker_id) {}836837void do_object(oop p) {838assert(_heap->complete_marking_context()->is_marked(p), "must be marked");839size_t size = (size_t)p->size();840if (p->is_forwarded()) {841HeapWord* compact_from = cast_from_oop<HeapWord*>(p);842HeapWord* compact_to = cast_from_oop<HeapWord*>(p->forwardee());843Copy::aligned_conjoint_words(compact_from, compact_to, size);844oop new_obj = cast_to_oop(compact_to);845new_obj->init_mark();846}847}848};849850class ShenandoahCompactObjectsTask : public AbstractGangTask {851private:852ShenandoahHeap* const _heap;853ShenandoahHeapRegionSet** const _worker_slices;854855public:856ShenandoahCompactObjectsTask(ShenandoahHeapRegionSet** worker_slices) :857AbstractGangTask("Shenandoah Compact Objects"),858_heap(ShenandoahHeap::heap()),859_worker_slices(worker_slices) {860}861862void work(uint worker_id) {863ShenandoahParallelWorkerSession worker_session(worker_id);864ShenandoahHeapRegionSetIterator slice(_worker_slices[worker_id]);865866ShenandoahCompactObjectsClosure cl(worker_id);867ShenandoahHeapRegion* r = slice.next();868while (r != NULL) {869assert(!r->is_humongous(), "must not get humongous regions here");870if (r->has_live()) {871_heap->marked_object_iterate(r, &cl);872}873r->set_top(r->new_top());874r = slice.next();875}876}877};878879class ShenandoahPostCompactClosure : public ShenandoahHeapRegionClosure {880private:881ShenandoahHeap* const _heap;882size_t _live;883884public:885ShenandoahPostCompactClosure() : _heap(ShenandoahHeap::heap()), _live(0) {886_heap->free_set()->clear();887}888889void heap_region_do(ShenandoahHeapRegion* r) {890assert (!r->is_cset(), "cset regions should have been demoted already");891892// Need to reset the complete-top-at-mark-start pointer here because893// the complete marking bitmap is no longer valid. This ensures894// size-based iteration in marked_object_iterate().895// NOTE: See blurb at ShenandoahMCResetCompleteBitmapTask on why we need to skip896// pinned regions.897if (!r->is_pinned()) {898_heap->complete_marking_context()->reset_top_at_mark_start(r);899}900901size_t live = r->used();902903// Make empty regions that have been allocated into regular904if (r->is_empty() && live > 0) {905r->make_regular_bypass();906}907908// Reclaim regular regions that became empty909if (r->is_regular() && live == 0) {910r->make_trash();911}912913// Recycle all trash regions914if (r->is_trash()) {915live = 0;916r->recycle();917}918919r->set_live_data(live);920r->reset_alloc_metadata();921_live += live;922}923924size_t get_live() {925return _live;926}927};928929void ShenandoahFullGC::compact_humongous_objects() {930// Compact humongous regions, based on their fwdptr objects.931//932// This code is serial, because doing the in-slice parallel sliding is tricky. In most cases,933// humongous regions are already compacted, and do not require further moves, which alleviates934// sliding costs. We may consider doing this in parallel in future.935936ShenandoahHeap* heap = ShenandoahHeap::heap();937938for (size_t c = heap->num_regions(); c > 0; c--) {939ShenandoahHeapRegion* r = heap->get_region(c - 1);940if (r->is_humongous_start()) {941oop old_obj = cast_to_oop(r->bottom());942if (!old_obj->is_forwarded()) {943// No need to move the object, it stays at the same slot944continue;945}946size_t words_size = old_obj->size();947size_t num_regions = ShenandoahHeapRegion::required_regions(words_size * HeapWordSize);948949size_t old_start = r->index();950size_t old_end = old_start + num_regions - 1;951size_t new_start = heap->heap_region_index_containing(old_obj->forwardee());952size_t new_end = new_start + num_regions - 1;953assert(old_start != new_start, "must be real move");954assert(r->is_stw_move_allowed(), "Region " SIZE_FORMAT " should be movable", r->index());955956Copy::aligned_conjoint_words(heap->get_region(old_start)->bottom(),957heap->get_region(new_start)->bottom(),958words_size);959960oop new_obj = cast_to_oop(heap->get_region(new_start)->bottom());961new_obj->init_mark();962963{964for (size_t c = old_start; c <= old_end; c++) {965ShenandoahHeapRegion* r = heap->get_region(c);966r->make_regular_bypass();967r->set_top(r->bottom());968}969970for (size_t c = new_start; c <= new_end; c++) {971ShenandoahHeapRegion* r = heap->get_region(c);972if (c == new_start) {973r->make_humongous_start_bypass();974} else {975r->make_humongous_cont_bypass();976}977978// Trailing region may be non-full, record the remainder there979size_t remainder = words_size & ShenandoahHeapRegion::region_size_words_mask();980if ((c == new_end) && (remainder != 0)) {981r->set_top(r->bottom() + remainder);982} else {983r->set_top(r->end());984}985986r->reset_alloc_metadata();987}988}989}990}991}992993// This is slightly different to ShHeap::reset_next_mark_bitmap:994// we need to remain able to walk pinned regions.995// Since pinned region do not move and don't get compacted, we will get holes with996// unreachable objects in them (which may have pointers to unloaded Klasses and thus997// cannot be iterated over using oop->size(). The only way to safely iterate over those is using998// a valid marking bitmap and valid TAMS pointer. This class only resets marking999// bitmaps for un-pinned regions, and later we only reset TAMS for unpinned regions.1000class ShenandoahMCResetCompleteBitmapTask : public AbstractGangTask {1001private:1002ShenandoahRegionIterator _regions;10031004public:1005ShenandoahMCResetCompleteBitmapTask() :1006AbstractGangTask("Shenandoah Reset Bitmap") {1007}10081009void work(uint worker_id) {1010ShenandoahParallelWorkerSession worker_session(worker_id);1011ShenandoahHeapRegion* region = _regions.next();1012ShenandoahHeap* heap = ShenandoahHeap::heap();1013ShenandoahMarkingContext* const ctx = heap->complete_marking_context();1014while (region != NULL) {1015if (heap->is_bitmap_slice_committed(region) && !region->is_pinned() && region->has_live()) {1016ctx->clear_bitmap(region);1017}1018region = _regions.next();1019}1020}1021};10221023void ShenandoahFullGC::phase4_compact_objects(ShenandoahHeapRegionSet** worker_slices) {1024GCTraceTime(Info, gc, phases) time("Phase 4: Move objects", _gc_timer);1025ShenandoahGCPhase compaction_phase(ShenandoahPhaseTimings::full_gc_copy_objects);10261027ShenandoahHeap* heap = ShenandoahHeap::heap();10281029// Compact regular objects first1030{1031ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_regular);1032ShenandoahCompactObjectsTask compact_task(worker_slices);1033heap->workers()->run_task(&compact_task);1034}10351036// Compact humongous objects after regular object moves1037{1038ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_humong);1039compact_humongous_objects();1040}10411042// Reset complete bitmap. We're about to reset the complete-top-at-mark-start pointer1043// and must ensure the bitmap is in sync.1044{1045ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_reset_complete);1046ShenandoahMCResetCompleteBitmapTask task;1047heap->workers()->run_task(&task);1048}10491050// Bring regions in proper states after the collection, and set heap properties.1051{1052ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_copy_objects_rebuild);10531054ShenandoahPostCompactClosure post_compact;1055heap->heap_region_iterate(&post_compact);1056heap->set_used(post_compact.get_live());10571058heap->collection_set()->clear();1059heap->free_set()->rebuild();1060}10611062heap->clear_cancelled_gc();1063}106410651066