Path: blob/master/src/hotspot/share/gc/shenandoah/shenandoahHeap.cpp
40957 views
/*1* Copyright (c) 2013, 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"25#include "memory/allocation.hpp"26#include "memory/universe.hpp"2728#include "gc/shared/gcArguments.hpp"29#include "gc/shared/gcTimer.hpp"30#include "gc/shared/gcTraceTime.inline.hpp"31#include "gc/shared/locationPrinter.inline.hpp"32#include "gc/shared/memAllocator.hpp"33#include "gc/shared/plab.hpp"34#include "gc/shared/tlab_globals.hpp"3536#include "gc/shenandoah/shenandoahBarrierSet.hpp"37#include "gc/shenandoah/shenandoahClosures.inline.hpp"38#include "gc/shenandoah/shenandoahCollectionSet.hpp"39#include "gc/shenandoah/shenandoahCollectorPolicy.hpp"40#include "gc/shenandoah/shenandoahConcurrentMark.hpp"41#include "gc/shenandoah/shenandoahControlThread.hpp"42#include "gc/shenandoah/shenandoahFreeSet.hpp"43#include "gc/shenandoah/shenandoahPhaseTimings.hpp"44#include "gc/shenandoah/shenandoahHeap.inline.hpp"45#include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"46#include "gc/shenandoah/shenandoahHeapRegionSet.hpp"47#include "gc/shenandoah/shenandoahInitLogger.hpp"48#include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"49#include "gc/shenandoah/shenandoahMemoryPool.hpp"50#include "gc/shenandoah/shenandoahMetrics.hpp"51#include "gc/shenandoah/shenandoahMonitoringSupport.hpp"52#include "gc/shenandoah/shenandoahOopClosures.inline.hpp"53#include "gc/shenandoah/shenandoahPacer.inline.hpp"54#include "gc/shenandoah/shenandoahPadding.hpp"55#include "gc/shenandoah/shenandoahParallelCleaning.inline.hpp"56#include "gc/shenandoah/shenandoahReferenceProcessor.hpp"57#include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"58#include "gc/shenandoah/shenandoahStringDedup.hpp"59#include "gc/shenandoah/shenandoahSTWMark.hpp"60#include "gc/shenandoah/shenandoahUtils.hpp"61#include "gc/shenandoah/shenandoahVerifier.hpp"62#include "gc/shenandoah/shenandoahCodeRoots.hpp"63#include "gc/shenandoah/shenandoahVMOperations.hpp"64#include "gc/shenandoah/shenandoahWorkGroup.hpp"65#include "gc/shenandoah/shenandoahWorkerPolicy.hpp"66#include "gc/shenandoah/mode/shenandoahIUMode.hpp"67#include "gc/shenandoah/mode/shenandoahPassiveMode.hpp"68#include "gc/shenandoah/mode/shenandoahSATBMode.hpp"69#if INCLUDE_JFR70#include "gc/shenandoah/shenandoahJfrSupport.hpp"71#endif7273#include "classfile/systemDictionary.hpp"74#include "memory/classLoaderMetaspace.hpp"75#include "memory/metaspaceUtils.hpp"76#include "oops/compressedOops.inline.hpp"77#include "prims/jvmtiTagMap.hpp"78#include "runtime/atomic.hpp"79#include "runtime/globals.hpp"80#include "runtime/interfaceSupport.inline.hpp"81#include "runtime/java.hpp"82#include "runtime/orderAccess.hpp"83#include "runtime/safepointMechanism.hpp"84#include "runtime/vmThread.hpp"85#include "services/mallocTracker.hpp"86#include "services/memTracker.hpp"87#include "utilities/events.hpp"88#include "utilities/powerOfTwo.hpp"8990class ShenandoahPretouchHeapTask : public AbstractGangTask {91private:92ShenandoahRegionIterator _regions;93const size_t _page_size;94public:95ShenandoahPretouchHeapTask(size_t page_size) :96AbstractGangTask("Shenandoah Pretouch Heap"),97_page_size(page_size) {}9899virtual void work(uint worker_id) {100ShenandoahHeapRegion* r = _regions.next();101while (r != NULL) {102if (r->is_committed()) {103os::pretouch_memory(r->bottom(), r->end(), _page_size);104}105r = _regions.next();106}107}108};109110class ShenandoahPretouchBitmapTask : public AbstractGangTask {111private:112ShenandoahRegionIterator _regions;113char* _bitmap_base;114const size_t _bitmap_size;115const size_t _page_size;116public:117ShenandoahPretouchBitmapTask(char* bitmap_base, size_t bitmap_size, size_t page_size) :118AbstractGangTask("Shenandoah Pretouch Bitmap"),119_bitmap_base(bitmap_base),120_bitmap_size(bitmap_size),121_page_size(page_size) {}122123virtual void work(uint worker_id) {124ShenandoahHeapRegion* r = _regions.next();125while (r != NULL) {126size_t start = r->index() * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();127size_t end = (r->index() + 1) * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();128assert (end <= _bitmap_size, "end is sane: " SIZE_FORMAT " < " SIZE_FORMAT, end, _bitmap_size);129130if (r->is_committed()) {131os::pretouch_memory(_bitmap_base + start, _bitmap_base + end, _page_size);132}133134r = _regions.next();135}136}137};138139jint ShenandoahHeap::initialize() {140//141// Figure out heap sizing142//143144size_t init_byte_size = InitialHeapSize;145size_t min_byte_size = MinHeapSize;146size_t max_byte_size = MaxHeapSize;147size_t heap_alignment = HeapAlignment;148149size_t reg_size_bytes = ShenandoahHeapRegion::region_size_bytes();150151Universe::check_alignment(max_byte_size, reg_size_bytes, "Shenandoah heap");152Universe::check_alignment(init_byte_size, reg_size_bytes, "Shenandoah heap");153154_num_regions = ShenandoahHeapRegion::region_count();155assert(_num_regions == (max_byte_size / reg_size_bytes),156"Regions should cover entire heap exactly: " SIZE_FORMAT " != " SIZE_FORMAT "/" SIZE_FORMAT,157_num_regions, max_byte_size, reg_size_bytes);158159// Now we know the number of regions, initialize the heuristics.160initialize_heuristics();161162size_t num_committed_regions = init_byte_size / reg_size_bytes;163num_committed_regions = MIN2(num_committed_regions, _num_regions);164assert(num_committed_regions <= _num_regions, "sanity");165_initial_size = num_committed_regions * reg_size_bytes;166167size_t num_min_regions = min_byte_size / reg_size_bytes;168num_min_regions = MIN2(num_min_regions, _num_regions);169assert(num_min_regions <= _num_regions, "sanity");170_minimum_size = num_min_regions * reg_size_bytes;171172// Default to max heap size.173_soft_max_size = _num_regions * reg_size_bytes;174175_committed = _initial_size;176177size_t heap_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();178size_t bitmap_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();179size_t region_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();180181//182// Reserve and commit memory for heap183//184185ReservedHeapSpace heap_rs = Universe::reserve_heap(max_byte_size, heap_alignment);186initialize_reserved_region(heap_rs);187_heap_region = MemRegion((HeapWord*)heap_rs.base(), heap_rs.size() / HeapWordSize);188_heap_region_special = heap_rs.special();189190assert((((size_t) base()) & ShenandoahHeapRegion::region_size_bytes_mask()) == 0,191"Misaligned heap: " PTR_FORMAT, p2i(base()));192193#if SHENANDOAH_OPTIMIZED_MARKTASK194// The optimized ShenandoahMarkTask takes some bits away from the full object bits.195// Fail if we ever attempt to address more than we can.196if ((uintptr_t)heap_rs.end() >= ShenandoahMarkTask::max_addressable()) {197FormatBuffer<512> buf("Shenandoah reserved [" PTR_FORMAT ", " PTR_FORMAT") for the heap, \n"198"but max object address is " PTR_FORMAT ". Try to reduce heap size, or try other \n"199"VM options that allocate heap at lower addresses (HeapBaseMinAddress, AllocateHeapAt, etc).",200p2i(heap_rs.base()), p2i(heap_rs.end()), ShenandoahMarkTask::max_addressable());201vm_exit_during_initialization("Fatal Error", buf);202}203#endif204205ReservedSpace sh_rs = heap_rs.first_part(max_byte_size);206if (!_heap_region_special) {207os::commit_memory_or_exit(sh_rs.base(), _initial_size, heap_alignment, false,208"Cannot commit heap memory");209}210211//212// Reserve and commit memory for bitmap(s)213//214215_bitmap_size = ShenandoahMarkBitMap::compute_size(heap_rs.size());216_bitmap_size = align_up(_bitmap_size, bitmap_page_size);217218size_t bitmap_bytes_per_region = reg_size_bytes / ShenandoahMarkBitMap::heap_map_factor();219220guarantee(bitmap_bytes_per_region != 0,221"Bitmap bytes per region should not be zero");222guarantee(is_power_of_2(bitmap_bytes_per_region),223"Bitmap bytes per region should be power of two: " SIZE_FORMAT, bitmap_bytes_per_region);224225if (bitmap_page_size > bitmap_bytes_per_region) {226_bitmap_regions_per_slice = bitmap_page_size / bitmap_bytes_per_region;227_bitmap_bytes_per_slice = bitmap_page_size;228} else {229_bitmap_regions_per_slice = 1;230_bitmap_bytes_per_slice = bitmap_bytes_per_region;231}232233guarantee(_bitmap_regions_per_slice >= 1,234"Should have at least one region per slice: " SIZE_FORMAT,235_bitmap_regions_per_slice);236237guarantee(((_bitmap_bytes_per_slice) % bitmap_page_size) == 0,238"Bitmap slices should be page-granular: bps = " SIZE_FORMAT ", page size = " SIZE_FORMAT,239_bitmap_bytes_per_slice, bitmap_page_size);240241ReservedSpace bitmap(_bitmap_size, bitmap_page_size);242MemTracker::record_virtual_memory_type(bitmap.base(), mtGC);243_bitmap_region = MemRegion((HeapWord*) bitmap.base(), bitmap.size() / HeapWordSize);244_bitmap_region_special = bitmap.special();245246size_t bitmap_init_commit = _bitmap_bytes_per_slice *247align_up(num_committed_regions, _bitmap_regions_per_slice) / _bitmap_regions_per_slice;248bitmap_init_commit = MIN2(_bitmap_size, bitmap_init_commit);249if (!_bitmap_region_special) {250os::commit_memory_or_exit((char *) _bitmap_region.start(), bitmap_init_commit, bitmap_page_size, false,251"Cannot commit bitmap memory");252}253254_marking_context = new ShenandoahMarkingContext(_heap_region, _bitmap_region, _num_regions, _max_workers);255256if (ShenandoahVerify) {257ReservedSpace verify_bitmap(_bitmap_size, bitmap_page_size);258if (!verify_bitmap.special()) {259os::commit_memory_or_exit(verify_bitmap.base(), verify_bitmap.size(), bitmap_page_size, false,260"Cannot commit verification bitmap memory");261}262MemTracker::record_virtual_memory_type(verify_bitmap.base(), mtGC);263MemRegion verify_bitmap_region = MemRegion((HeapWord *) verify_bitmap.base(), verify_bitmap.size() / HeapWordSize);264_verification_bit_map.initialize(_heap_region, verify_bitmap_region);265_verifier = new ShenandoahVerifier(this, &_verification_bit_map);266}267268// Reserve aux bitmap for use in object_iterate(). We don't commit it here.269ReservedSpace aux_bitmap(_bitmap_size, bitmap_page_size);270MemTracker::record_virtual_memory_type(aux_bitmap.base(), mtGC);271_aux_bitmap_region = MemRegion((HeapWord*) aux_bitmap.base(), aux_bitmap.size() / HeapWordSize);272_aux_bitmap_region_special = aux_bitmap.special();273_aux_bit_map.initialize(_heap_region, _aux_bitmap_region);274275//276// Create regions and region sets277//278size_t region_align = align_up(sizeof(ShenandoahHeapRegion), SHENANDOAH_CACHE_LINE_SIZE);279size_t region_storage_size = align_up(region_align * _num_regions, region_page_size);280region_storage_size = align_up(region_storage_size, os::vm_allocation_granularity());281282ReservedSpace region_storage(region_storage_size, region_page_size);283MemTracker::record_virtual_memory_type(region_storage.base(), mtGC);284if (!region_storage.special()) {285os::commit_memory_or_exit(region_storage.base(), region_storage_size, region_page_size, false,286"Cannot commit region memory");287}288289// Try to fit the collection set bitmap at lower addresses. This optimizes code generation for cset checks.290// Go up until a sensible limit (subject to encoding constraints) and try to reserve the space there.291// If not successful, bite a bullet and allocate at whatever address.292{293size_t cset_align = MAX2<size_t>(os::vm_page_size(), os::vm_allocation_granularity());294size_t cset_size = align_up(((size_t) sh_rs.base() + sh_rs.size()) >> ShenandoahHeapRegion::region_size_bytes_shift(), cset_align);295296uintptr_t min = round_up_power_of_2(cset_align);297uintptr_t max = (1u << 30u);298299for (uintptr_t addr = min; addr <= max; addr <<= 1u) {300char* req_addr = (char*)addr;301assert(is_aligned(req_addr, cset_align), "Should be aligned");302ReservedSpace cset_rs(cset_size, cset_align, os::vm_page_size(), req_addr);303if (cset_rs.is_reserved()) {304assert(cset_rs.base() == req_addr, "Allocated where requested: " PTR_FORMAT ", " PTR_FORMAT, p2i(cset_rs.base()), addr);305_collection_set = new ShenandoahCollectionSet(this, cset_rs, sh_rs.base());306break;307}308}309310if (_collection_set == NULL) {311ReservedSpace cset_rs(cset_size, cset_align, os::vm_page_size());312_collection_set = new ShenandoahCollectionSet(this, cset_rs, sh_rs.base());313}314}315316_regions = NEW_C_HEAP_ARRAY(ShenandoahHeapRegion*, _num_regions, mtGC);317_free_set = new ShenandoahFreeSet(this, _num_regions);318319{320ShenandoahHeapLocker locker(lock());321322for (size_t i = 0; i < _num_regions; i++) {323HeapWord* start = (HeapWord*)sh_rs.base() + ShenandoahHeapRegion::region_size_words() * i;324bool is_committed = i < num_committed_regions;325void* loc = region_storage.base() + i * region_align;326327ShenandoahHeapRegion* r = new (loc) ShenandoahHeapRegion(start, i, is_committed);328assert(is_aligned(r, SHENANDOAH_CACHE_LINE_SIZE), "Sanity");329330_marking_context->initialize_top_at_mark_start(r);331_regions[i] = r;332assert(!collection_set()->is_in(i), "New region should not be in collection set");333}334335// Initialize to complete336_marking_context->mark_complete();337338_free_set->rebuild();339}340341if (AlwaysPreTouch) {342// For NUMA, it is important to pre-touch the storage under bitmaps with worker threads,343// before initialize() below zeroes it with initializing thread. For any given region,344// we touch the region and the corresponding bitmaps from the same thread.345ShenandoahPushWorkerScope scope(workers(), _max_workers, false);346347_pretouch_heap_page_size = heap_page_size;348_pretouch_bitmap_page_size = bitmap_page_size;349350#ifdef LINUX351// UseTransparentHugePages would madvise that backing memory can be coalesced into huge352// pages. But, the kernel needs to know that every small page is used, in order to coalesce353// them into huge one. Therefore, we need to pretouch with smaller pages.354if (UseTransparentHugePages) {355_pretouch_heap_page_size = (size_t)os::vm_page_size();356_pretouch_bitmap_page_size = (size_t)os::vm_page_size();357}358#endif359360// OS memory managers may want to coalesce back-to-back pages. Make their jobs361// simpler by pre-touching continuous spaces (heap and bitmap) separately.362363ShenandoahPretouchBitmapTask bcl(bitmap.base(), _bitmap_size, _pretouch_bitmap_page_size);364_workers->run_task(&bcl);365366ShenandoahPretouchHeapTask hcl(_pretouch_heap_page_size);367_workers->run_task(&hcl);368}369370//371// Initialize the rest of GC subsystems372//373374_liveness_cache = NEW_C_HEAP_ARRAY(ShenandoahLiveData*, _max_workers, mtGC);375for (uint worker = 0; worker < _max_workers; worker++) {376_liveness_cache[worker] = NEW_C_HEAP_ARRAY(ShenandoahLiveData, _num_regions, mtGC);377Copy::fill_to_bytes(_liveness_cache[worker], _num_regions * sizeof(ShenandoahLiveData));378}379380// There should probably be Shenandoah-specific options for these,381// just as there are G1-specific options.382{383ShenandoahSATBMarkQueueSet& satbqs = ShenandoahBarrierSet::satb_mark_queue_set();384satbqs.set_process_completed_buffers_threshold(20); // G1SATBProcessCompletedThreshold385satbqs.set_buffer_enqueue_threshold_percentage(60); // G1SATBBufferEnqueueingThresholdPercent386}387388_monitoring_support = new ShenandoahMonitoringSupport(this);389_phase_timings = new ShenandoahPhaseTimings(max_workers());390ShenandoahCodeRoots::initialize();391392if (ShenandoahPacing) {393_pacer = new ShenandoahPacer(this);394_pacer->setup_for_idle();395} else {396_pacer = NULL;397}398399_control_thread = new ShenandoahControlThread();400401ShenandoahInitLogger::print();402403return JNI_OK;404}405406void ShenandoahHeap::initialize_mode() {407if (ShenandoahGCMode != NULL) {408if (strcmp(ShenandoahGCMode, "satb") == 0) {409_gc_mode = new ShenandoahSATBMode();410} else if (strcmp(ShenandoahGCMode, "iu") == 0) {411_gc_mode = new ShenandoahIUMode();412} else if (strcmp(ShenandoahGCMode, "passive") == 0) {413_gc_mode = new ShenandoahPassiveMode();414} else {415vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option");416}417} else {418ShouldNotReachHere();419}420_gc_mode->initialize_flags();421if (_gc_mode->is_diagnostic() && !UnlockDiagnosticVMOptions) {422vm_exit_during_initialization(423err_msg("GC mode \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",424_gc_mode->name()));425}426if (_gc_mode->is_experimental() && !UnlockExperimentalVMOptions) {427vm_exit_during_initialization(428err_msg("GC mode \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",429_gc_mode->name()));430}431}432433void ShenandoahHeap::initialize_heuristics() {434assert(_gc_mode != NULL, "Must be initialized");435_heuristics = _gc_mode->initialize_heuristics();436437if (_heuristics->is_diagnostic() && !UnlockDiagnosticVMOptions) {438vm_exit_during_initialization(439err_msg("Heuristics \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",440_heuristics->name()));441}442if (_heuristics->is_experimental() && !UnlockExperimentalVMOptions) {443vm_exit_during_initialization(444err_msg("Heuristics \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",445_heuristics->name()));446}447}448449#ifdef _MSC_VER450#pragma warning( push )451#pragma warning( disable:4355 ) // 'this' : used in base member initializer list452#endif453454ShenandoahHeap::ShenandoahHeap(ShenandoahCollectorPolicy* policy) :455CollectedHeap(),456_initial_size(0),457_used(0),458_committed(0),459_bytes_allocated_since_gc_start(0),460_max_workers(MAX2(ConcGCThreads, ParallelGCThreads)),461_workers(NULL),462_safepoint_workers(NULL),463_heap_region_special(false),464_num_regions(0),465_regions(NULL),466_update_refs_iterator(this),467_control_thread(NULL),468_shenandoah_policy(policy),469_gc_mode(NULL),470_heuristics(NULL),471_free_set(NULL),472_pacer(NULL),473_verifier(NULL),474_phase_timings(NULL),475_monitoring_support(NULL),476_memory_pool(NULL),477_stw_memory_manager("Shenandoah Pauses", "end of GC pause"),478_cycle_memory_manager("Shenandoah Cycles", "end of GC cycle"),479_gc_timer(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),480_soft_ref_policy(),481_log_min_obj_alignment_in_bytes(LogMinObjAlignmentInBytes),482_ref_processor(new ShenandoahReferenceProcessor(MAX2(_max_workers, 1U))),483_marking_context(NULL),484_bitmap_size(0),485_bitmap_regions_per_slice(0),486_bitmap_bytes_per_slice(0),487_bitmap_region_special(false),488_aux_bitmap_region_special(false),489_liveness_cache(NULL),490_collection_set(NULL)491{492// Initialize GC mode early, so we can adjust barrier support493initialize_mode();494BarrierSet::set_barrier_set(new ShenandoahBarrierSet(this));495496_max_workers = MAX2(_max_workers, 1U);497_workers = new ShenandoahWorkGang("Shenandoah GC Threads", _max_workers,498/* are_GC_task_threads */ true,499/* are_ConcurrentGC_threads */ true);500if (_workers == NULL) {501vm_exit_during_initialization("Failed necessary allocation.");502} else {503_workers->initialize_workers();504}505506if (ParallelGCThreads > 1) {507_safepoint_workers = new ShenandoahWorkGang("Safepoint Cleanup Thread",508ParallelGCThreads,509/* are_GC_task_threads */ false,510/* are_ConcurrentGC_threads */ false);511_safepoint_workers->initialize_workers();512}513}514515#ifdef _MSC_VER516#pragma warning( pop )517#endif518519class ShenandoahResetBitmapTask : public AbstractGangTask {520private:521ShenandoahRegionIterator _regions;522523public:524ShenandoahResetBitmapTask() :525AbstractGangTask("Shenandoah Reset Bitmap") {}526527void work(uint worker_id) {528ShenandoahHeapRegion* region = _regions.next();529ShenandoahHeap* heap = ShenandoahHeap::heap();530ShenandoahMarkingContext* const ctx = heap->marking_context();531while (region != NULL) {532if (heap->is_bitmap_slice_committed(region)) {533ctx->clear_bitmap(region);534}535region = _regions.next();536}537}538};539540void ShenandoahHeap::reset_mark_bitmap() {541assert_gc_workers(_workers->active_workers());542mark_incomplete_marking_context();543544ShenandoahResetBitmapTask task;545_workers->run_task(&task);546}547548void ShenandoahHeap::print_on(outputStream* st) const {549st->print_cr("Shenandoah Heap");550st->print_cr(" " SIZE_FORMAT "%s max, " SIZE_FORMAT "%s soft max, " SIZE_FORMAT "%s committed, " SIZE_FORMAT "%s used",551byte_size_in_proper_unit(max_capacity()), proper_unit_for_byte_size(max_capacity()),552byte_size_in_proper_unit(soft_max_capacity()), proper_unit_for_byte_size(soft_max_capacity()),553byte_size_in_proper_unit(committed()), proper_unit_for_byte_size(committed()),554byte_size_in_proper_unit(used()), proper_unit_for_byte_size(used()));555st->print_cr(" " SIZE_FORMAT " x " SIZE_FORMAT"%s regions",556num_regions(),557byte_size_in_proper_unit(ShenandoahHeapRegion::region_size_bytes()),558proper_unit_for_byte_size(ShenandoahHeapRegion::region_size_bytes()));559560st->print("Status: ");561if (has_forwarded_objects()) st->print("has forwarded objects, ");562if (is_concurrent_mark_in_progress()) st->print("marking, ");563if (is_evacuation_in_progress()) st->print("evacuating, ");564if (is_update_refs_in_progress()) st->print("updating refs, ");565if (is_degenerated_gc_in_progress()) st->print("degenerated gc, ");566if (is_full_gc_in_progress()) st->print("full gc, ");567if (is_full_gc_move_in_progress()) st->print("full gc move, ");568if (is_concurrent_weak_root_in_progress()) st->print("concurrent weak roots, ");569if (is_concurrent_strong_root_in_progress() &&570!is_concurrent_weak_root_in_progress()) st->print("concurrent strong roots, ");571572if (cancelled_gc()) {573st->print("cancelled");574} else {575st->print("not cancelled");576}577st->cr();578579st->print_cr("Reserved region:");580st->print_cr(" - [" PTR_FORMAT ", " PTR_FORMAT ") ",581p2i(reserved_region().start()),582p2i(reserved_region().end()));583584ShenandoahCollectionSet* cset = collection_set();585st->print_cr("Collection set:");586if (cset != NULL) {587st->print_cr(" - map (vanilla): " PTR_FORMAT, p2i(cset->map_address()));588st->print_cr(" - map (biased): " PTR_FORMAT, p2i(cset->biased_map_address()));589} else {590st->print_cr(" (NULL)");591}592593st->cr();594MetaspaceUtils::print_on(st);595596if (Verbose) {597print_heap_regions_on(st);598}599}600601class ShenandoahInitWorkerGCLABClosure : public ThreadClosure {602public:603void do_thread(Thread* thread) {604assert(thread != NULL, "Sanity");605assert(thread->is_Worker_thread(), "Only worker thread expected");606ShenandoahThreadLocalData::initialize_gclab(thread);607}608};609610void ShenandoahHeap::post_initialize() {611CollectedHeap::post_initialize();612MutexLocker ml(Threads_lock);613614ShenandoahInitWorkerGCLABClosure init_gclabs;615_workers->threads_do(&init_gclabs);616617// gclab can not be initialized early during VM startup, as it can not determinate its max_size.618// Now, we will let WorkGang to initialize gclab when new worker is created.619_workers->set_initialize_gclab();620if (_safepoint_workers != NULL) {621_safepoint_workers->threads_do(&init_gclabs);622_safepoint_workers->set_initialize_gclab();623}624625_heuristics->initialize();626627JFR_ONLY(ShenandoahJFRSupport::register_jfr_type_serializers());628}629630size_t ShenandoahHeap::used() const {631return Atomic::load(&_used);632}633634size_t ShenandoahHeap::committed() const {635return Atomic::load(&_committed);636}637638void ShenandoahHeap::increase_committed(size_t bytes) {639shenandoah_assert_heaplocked_or_safepoint();640_committed += bytes;641}642643void ShenandoahHeap::decrease_committed(size_t bytes) {644shenandoah_assert_heaplocked_or_safepoint();645_committed -= bytes;646}647648void ShenandoahHeap::increase_used(size_t bytes) {649Atomic::add(&_used, bytes, memory_order_relaxed);650}651652void ShenandoahHeap::set_used(size_t bytes) {653Atomic::store(&_used, bytes);654}655656void ShenandoahHeap::decrease_used(size_t bytes) {657assert(used() >= bytes, "never decrease heap size by more than we've left");658Atomic::sub(&_used, bytes, memory_order_relaxed);659}660661void ShenandoahHeap::increase_allocated(size_t bytes) {662Atomic::add(&_bytes_allocated_since_gc_start, bytes, memory_order_relaxed);663}664665void ShenandoahHeap::notify_mutator_alloc_words(size_t words, bool waste) {666size_t bytes = words * HeapWordSize;667if (!waste) {668increase_used(bytes);669}670increase_allocated(bytes);671if (ShenandoahPacing) {672control_thread()->pacing_notify_alloc(words);673if (waste) {674pacer()->claim_for_alloc(words, true);675}676}677}678679size_t ShenandoahHeap::capacity() const {680return committed();681}682683size_t ShenandoahHeap::max_capacity() const {684return _num_regions * ShenandoahHeapRegion::region_size_bytes();685}686687size_t ShenandoahHeap::soft_max_capacity() const {688size_t v = Atomic::load(&_soft_max_size);689assert(min_capacity() <= v && v <= max_capacity(),690"Should be in bounds: " SIZE_FORMAT " <= " SIZE_FORMAT " <= " SIZE_FORMAT,691min_capacity(), v, max_capacity());692return v;693}694695void ShenandoahHeap::set_soft_max_capacity(size_t v) {696assert(min_capacity() <= v && v <= max_capacity(),697"Should be in bounds: " SIZE_FORMAT " <= " SIZE_FORMAT " <= " SIZE_FORMAT,698min_capacity(), v, max_capacity());699Atomic::store(&_soft_max_size, v);700}701702size_t ShenandoahHeap::min_capacity() const {703return _minimum_size;704}705706size_t ShenandoahHeap::initial_capacity() const {707return _initial_size;708}709710bool ShenandoahHeap::is_in(const void* p) const {711HeapWord* heap_base = (HeapWord*) base();712HeapWord* last_region_end = heap_base + ShenandoahHeapRegion::region_size_words() * num_regions();713return p >= heap_base && p < last_region_end;714}715716void ShenandoahHeap::op_uncommit(double shrink_before, size_t shrink_until) {717assert (ShenandoahUncommit, "should be enabled");718719// Application allocates from the beginning of the heap, and GC allocates at720// the end of it. It is more efficient to uncommit from the end, so that applications721// could enjoy the near committed regions. GC allocations are much less frequent,722// and therefore can accept the committing costs.723724size_t count = 0;725for (size_t i = num_regions(); i > 0; i--) { // care about size_t underflow726ShenandoahHeapRegion* r = get_region(i - 1);727if (r->is_empty_committed() && (r->empty_time() < shrink_before)) {728ShenandoahHeapLocker locker(lock());729if (r->is_empty_committed()) {730if (committed() < shrink_until + ShenandoahHeapRegion::region_size_bytes()) {731break;732}733734r->make_uncommitted();735count++;736}737}738SpinPause(); // allow allocators to take the lock739}740741if (count > 0) {742control_thread()->notify_heap_changed();743}744}745746HeapWord* ShenandoahHeap::allocate_from_gclab_slow(Thread* thread, size_t size) {747// New object should fit the GCLAB size748size_t min_size = MAX2(size, PLAB::min_size());749750// Figure out size of new GCLAB, looking back at heuristics. Expand aggressively.751size_t new_size = ShenandoahThreadLocalData::gclab_size(thread) * 2;752new_size = MIN2(new_size, PLAB::max_size());753new_size = MAX2(new_size, PLAB::min_size());754755// Record new heuristic value even if we take any shortcut. This captures756// the case when moderately-sized objects always take a shortcut. At some point,757// heuristics should catch up with them.758ShenandoahThreadLocalData::set_gclab_size(thread, new_size);759760if (new_size < size) {761// New size still does not fit the object. Fall back to shared allocation.762// This avoids retiring perfectly good GCLABs, when we encounter a large object.763return NULL;764}765766// Retire current GCLAB, and allocate a new one.767PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);768gclab->retire();769770size_t actual_size = 0;771HeapWord* gclab_buf = allocate_new_gclab(min_size, new_size, &actual_size);772if (gclab_buf == NULL) {773return NULL;774}775776assert (size <= actual_size, "allocation should fit");777778if (ZeroTLAB) {779// ..and clear it.780Copy::zero_to_words(gclab_buf, actual_size);781} else {782// ...and zap just allocated object.783#ifdef ASSERT784// Skip mangling the space corresponding to the object header to785// ensure that the returned space is not considered parsable by786// any concurrent GC thread.787size_t hdr_size = oopDesc::header_size();788Copy::fill_to_words(gclab_buf + hdr_size, actual_size - hdr_size, badHeapWordVal);789#endif // ASSERT790}791gclab->set_buf(gclab_buf, actual_size);792return gclab->allocate(size);793}794795HeapWord* ShenandoahHeap::allocate_new_tlab(size_t min_size,796size_t requested_size,797size_t* actual_size) {798ShenandoahAllocRequest req = ShenandoahAllocRequest::for_tlab(min_size, requested_size);799HeapWord* res = allocate_memory(req);800if (res != NULL) {801*actual_size = req.actual_size();802} else {803*actual_size = 0;804}805return res;806}807808HeapWord* ShenandoahHeap::allocate_new_gclab(size_t min_size,809size_t word_size,810size_t* actual_size) {811ShenandoahAllocRequest req = ShenandoahAllocRequest::for_gclab(min_size, word_size);812HeapWord* res = allocate_memory(req);813if (res != NULL) {814*actual_size = req.actual_size();815} else {816*actual_size = 0;817}818return res;819}820821HeapWord* ShenandoahHeap::allocate_memory(ShenandoahAllocRequest& req) {822intptr_t pacer_epoch = 0;823bool in_new_region = false;824HeapWord* result = NULL;825826if (req.is_mutator_alloc()) {827if (ShenandoahPacing) {828pacer()->pace_for_alloc(req.size());829pacer_epoch = pacer()->epoch();830}831832if (!ShenandoahAllocFailureALot || !should_inject_alloc_failure()) {833result = allocate_memory_under_lock(req, in_new_region);834}835836// Allocation failed, block until control thread reacted, then retry allocation.837//838// It might happen that one of the threads requesting allocation would unblock839// way later after GC happened, only to fail the second allocation, because840// other threads have already depleted the free storage. In this case, a better841// strategy is to try again, as long as GC makes progress.842//843// Then, we need to make sure the allocation was retried after at least one844// Full GC, which means we want to try more than ShenandoahFullGCThreshold times.845846size_t tries = 0;847848while (result == NULL && _progress_last_gc.is_set()) {849tries++;850control_thread()->handle_alloc_failure(req);851result = allocate_memory_under_lock(req, in_new_region);852}853854while (result == NULL && tries <= ShenandoahFullGCThreshold) {855tries++;856control_thread()->handle_alloc_failure(req);857result = allocate_memory_under_lock(req, in_new_region);858}859860} else {861assert(req.is_gc_alloc(), "Can only accept GC allocs here");862result = allocate_memory_under_lock(req, in_new_region);863// Do not call handle_alloc_failure() here, because we cannot block.864// The allocation failure would be handled by the LRB slowpath with handle_alloc_failure_evac().865}866867if (in_new_region) {868control_thread()->notify_heap_changed();869}870871if (result != NULL) {872size_t requested = req.size();873size_t actual = req.actual_size();874875assert (req.is_lab_alloc() || (requested == actual),876"Only LAB allocations are elastic: %s, requested = " SIZE_FORMAT ", actual = " SIZE_FORMAT,877ShenandoahAllocRequest::alloc_type_to_string(req.type()), requested, actual);878879if (req.is_mutator_alloc()) {880notify_mutator_alloc_words(actual, false);881882// If we requested more than we were granted, give the rest back to pacer.883// This only matters if we are in the same pacing epoch: do not try to unpace884// over the budget for the other phase.885if (ShenandoahPacing && (pacer_epoch > 0) && (requested > actual)) {886pacer()->unpace_for_alloc(pacer_epoch, requested - actual);887}888} else {889increase_used(actual*HeapWordSize);890}891}892893return result;894}895896HeapWord* ShenandoahHeap::allocate_memory_under_lock(ShenandoahAllocRequest& req, bool& in_new_region) {897ShenandoahHeapLocker locker(lock());898return _free_set->allocate(req, in_new_region);899}900901HeapWord* ShenandoahHeap::mem_allocate(size_t size,902bool* gc_overhead_limit_was_exceeded) {903ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared(size);904return allocate_memory(req);905}906907MetaWord* ShenandoahHeap::satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,908size_t size,909Metaspace::MetadataType mdtype) {910MetaWord* result;911912// Inform metaspace OOM to GC heuristics if class unloading is possible.913if (heuristics()->can_unload_classes()) {914ShenandoahHeuristics* h = heuristics();915h->record_metaspace_oom();916}917918// Expand and retry allocation919result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);920if (result != NULL) {921return result;922}923924// Start full GC925collect(GCCause::_metadata_GC_clear_soft_refs);926927// Retry allocation928result = loader_data->metaspace_non_null()->allocate(size, mdtype);929if (result != NULL) {930return result;931}932933// Expand and retry allocation934result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);935if (result != NULL) {936return result;937}938939// Out of memory940return NULL;941}942943class ShenandoahConcurrentEvacuateRegionObjectClosure : public ObjectClosure {944private:945ShenandoahHeap* const _heap;946Thread* const _thread;947public:948ShenandoahConcurrentEvacuateRegionObjectClosure(ShenandoahHeap* heap) :949_heap(heap), _thread(Thread::current()) {}950951void do_object(oop p) {952shenandoah_assert_marked(NULL, p);953if (!p->is_forwarded()) {954_heap->evacuate_object(p, _thread);955}956}957};958959class ShenandoahEvacuationTask : public AbstractGangTask {960private:961ShenandoahHeap* const _sh;962ShenandoahCollectionSet* const _cs;963bool _concurrent;964public:965ShenandoahEvacuationTask(ShenandoahHeap* sh,966ShenandoahCollectionSet* cs,967bool concurrent) :968AbstractGangTask("Shenandoah Evacuation"),969_sh(sh),970_cs(cs),971_concurrent(concurrent)972{}973974void work(uint worker_id) {975if (_concurrent) {976ShenandoahConcurrentWorkerSession worker_session(worker_id);977ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);978ShenandoahEvacOOMScope oom_evac_scope;979do_work();980} else {981ShenandoahParallelWorkerSession worker_session(worker_id);982ShenandoahEvacOOMScope oom_evac_scope;983do_work();984}985}986987private:988void do_work() {989ShenandoahConcurrentEvacuateRegionObjectClosure cl(_sh);990ShenandoahHeapRegion* r;991while ((r =_cs->claim_next()) != NULL) {992assert(r->has_live(), "Region " SIZE_FORMAT " should have been reclaimed early", r->index());993_sh->marked_object_iterate(r, &cl);994995if (ShenandoahPacing) {996_sh->pacer()->report_evac(r->used() >> LogHeapWordSize);997}998999if (_sh->check_cancelled_gc_and_yield(_concurrent)) {1000break;1001}1002}1003}1004};10051006void ShenandoahHeap::evacuate_collection_set(bool concurrent) {1007ShenandoahEvacuationTask task(this, _collection_set, concurrent);1008workers()->run_task(&task);1009}10101011void ShenandoahHeap::trash_cset_regions() {1012ShenandoahHeapLocker locker(lock());10131014ShenandoahCollectionSet* set = collection_set();1015ShenandoahHeapRegion* r;1016set->clear_current_index();1017while ((r = set->next()) != NULL) {1018r->make_trash();1019}1020collection_set()->clear();1021}10221023void ShenandoahHeap::print_heap_regions_on(outputStream* st) const {1024st->print_cr("Heap Regions:");1025st->print_cr("EU=empty-uncommitted, EC=empty-committed, R=regular, H=humongous start, HC=humongous continuation, CS=collection set, T=trash, P=pinned");1026st->print_cr("BTE=bottom/top/end, U=used, T=TLAB allocs, G=GCLAB allocs, S=shared allocs, L=live data");1027st->print_cr("R=root, CP=critical pins, TAMS=top-at-mark-start, UWM=update watermark");1028st->print_cr("SN=alloc sequence number");10291030for (size_t i = 0; i < num_regions(); i++) {1031get_region(i)->print_on(st);1032}1033}10341035void ShenandoahHeap::trash_humongous_region_at(ShenandoahHeapRegion* start) {1036assert(start->is_humongous_start(), "reclaim regions starting with the first one");10371038oop humongous_obj = cast_to_oop(start->bottom());1039size_t size = humongous_obj->size();1040size_t required_regions = ShenandoahHeapRegion::required_regions(size * HeapWordSize);1041size_t index = start->index() + required_regions - 1;10421043assert(!start->has_live(), "liveness must be zero");10441045for(size_t i = 0; i < required_regions; i++) {1046// Reclaim from tail. Otherwise, assertion fails when printing region to trace log,1047// as it expects that every region belongs to a humongous region starting with a humongous start region.1048ShenandoahHeapRegion* region = get_region(index --);10491050assert(region->is_humongous(), "expect correct humongous start or continuation");1051assert(!region->is_cset(), "Humongous region should not be in collection set");10521053region->make_trash_immediate();1054}1055}10561057class ShenandoahCheckCleanGCLABClosure : public ThreadClosure {1058public:1059ShenandoahCheckCleanGCLABClosure() {}1060void do_thread(Thread* thread) {1061PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);1062assert(gclab != NULL, "GCLAB should be initialized for %s", thread->name());1063assert(gclab->words_remaining() == 0, "GCLAB should not need retirement");1064}1065};10661067class ShenandoahRetireGCLABClosure : public ThreadClosure {1068private:1069bool const _resize;1070public:1071ShenandoahRetireGCLABClosure(bool resize) : _resize(resize) {}1072void do_thread(Thread* thread) {1073PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);1074assert(gclab != NULL, "GCLAB should be initialized for %s", thread->name());1075gclab->retire();1076if (_resize && ShenandoahThreadLocalData::gclab_size(thread) > 0) {1077ShenandoahThreadLocalData::set_gclab_size(thread, 0);1078}1079}1080};10811082void ShenandoahHeap::labs_make_parsable() {1083assert(UseTLAB, "Only call with UseTLAB");10841085ShenandoahRetireGCLABClosure cl(false);10861087for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {1088ThreadLocalAllocBuffer& tlab = t->tlab();1089tlab.make_parsable();1090cl.do_thread(t);1091}10921093workers()->threads_do(&cl);1094}10951096void ShenandoahHeap::tlabs_retire(bool resize) {1097assert(UseTLAB, "Only call with UseTLAB");1098assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled");10991100ThreadLocalAllocStats stats;11011102for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {1103ThreadLocalAllocBuffer& tlab = t->tlab();1104tlab.retire(&stats);1105if (resize) {1106tlab.resize();1107}1108}11091110stats.publish();11111112#ifdef ASSERT1113ShenandoahCheckCleanGCLABClosure cl;1114for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {1115cl.do_thread(t);1116}1117workers()->threads_do(&cl);1118#endif1119}11201121void ShenandoahHeap::gclabs_retire(bool resize) {1122assert(UseTLAB, "Only call with UseTLAB");1123assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled");11241125ShenandoahRetireGCLABClosure cl(resize);1126for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {1127cl.do_thread(t);1128}1129workers()->threads_do(&cl);11301131if (safepoint_workers() != NULL) {1132safepoint_workers()->threads_do(&cl);1133}1134}11351136// Returns size in bytes1137size_t ShenandoahHeap::unsafe_max_tlab_alloc(Thread *thread) const {1138if (ShenandoahElasticTLAB) {1139// With Elastic TLABs, return the max allowed size, and let the allocation path1140// figure out the safe size for current allocation.1141return ShenandoahHeapRegion::max_tlab_size_bytes();1142} else {1143return MIN2(_free_set->unsafe_peek_free(), ShenandoahHeapRegion::max_tlab_size_bytes());1144}1145}11461147size_t ShenandoahHeap::max_tlab_size() const {1148// Returns size in words1149return ShenandoahHeapRegion::max_tlab_size_words();1150}11511152void ShenandoahHeap::collect(GCCause::Cause cause) {1153control_thread()->request_gc(cause);1154}11551156void ShenandoahHeap::do_full_collection(bool clear_all_soft_refs) {1157//assert(false, "Shouldn't need to do full collections");1158}11591160HeapWord* ShenandoahHeap::block_start(const void* addr) const {1161ShenandoahHeapRegion* r = heap_region_containing(addr);1162if (r != NULL) {1163return r->block_start(addr);1164}1165return NULL;1166}11671168bool ShenandoahHeap::block_is_obj(const HeapWord* addr) const {1169ShenandoahHeapRegion* r = heap_region_containing(addr);1170return r->block_is_obj(addr);1171}11721173bool ShenandoahHeap::print_location(outputStream* st, void* addr) const {1174return BlockLocationPrinter<ShenandoahHeap>::print_location(st, addr);1175}11761177void ShenandoahHeap::prepare_for_verify() {1178if (SafepointSynchronize::is_at_safepoint() && UseTLAB) {1179labs_make_parsable();1180}1181}11821183void ShenandoahHeap::gc_threads_do(ThreadClosure* tcl) const {1184workers()->threads_do(tcl);1185if (_safepoint_workers != NULL) {1186_safepoint_workers->threads_do(tcl);1187}1188if (ShenandoahStringDedup::is_enabled()) {1189ShenandoahStringDedup::threads_do(tcl);1190}1191}11921193void ShenandoahHeap::print_tracing_info() const {1194LogTarget(Info, gc, stats) lt;1195if (lt.is_enabled()) {1196ResourceMark rm;1197LogStream ls(lt);11981199phase_timings()->print_global_on(&ls);12001201ls.cr();1202ls.cr();12031204shenandoah_policy()->print_gc_stats(&ls);12051206ls.cr();1207ls.cr();1208}1209}12101211void ShenandoahHeap::verify(VerifyOption vo) {1212if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {1213if (ShenandoahVerify) {1214verifier()->verify_generic(vo);1215} else {1216// TODO: Consider allocating verification bitmaps on demand,1217// and turn this on unconditionally.1218}1219}1220}1221size_t ShenandoahHeap::tlab_capacity(Thread *thr) const {1222return _free_set->capacity();1223}12241225class ObjectIterateScanRootClosure : public BasicOopIterateClosure {1226private:1227MarkBitMap* _bitmap;1228ShenandoahScanObjectStack* _oop_stack;1229ShenandoahHeap* const _heap;1230ShenandoahMarkingContext* const _marking_context;12311232template <class T>1233void do_oop_work(T* p) {1234T o = RawAccess<>::oop_load(p);1235if (!CompressedOops::is_null(o)) {1236oop obj = CompressedOops::decode_not_null(o);1237if (_heap->is_concurrent_weak_root_in_progress() && !_marking_context->is_marked(obj)) {1238// There may be dead oops in weak roots in concurrent root phase, do not touch them.1239return;1240}1241obj = ShenandoahBarrierSet::resolve_forwarded_not_null(obj);12421243assert(oopDesc::is_oop(obj), "must be a valid oop");1244if (!_bitmap->is_marked(obj)) {1245_bitmap->mark(obj);1246_oop_stack->push(obj);1247}1248}1249}1250public:1251ObjectIterateScanRootClosure(MarkBitMap* bitmap, ShenandoahScanObjectStack* oop_stack) :1252_bitmap(bitmap), _oop_stack(oop_stack), _heap(ShenandoahHeap::heap()),1253_marking_context(_heap->marking_context()) {}1254void do_oop(oop* p) { do_oop_work(p); }1255void do_oop(narrowOop* p) { do_oop_work(p); }1256};12571258/*1259* This is public API, used in preparation of object_iterate().1260* Since we don't do linear scan of heap in object_iterate() (see comment below), we don't1261* need to make the heap parsable. For Shenandoah-internal linear heap scans that we can1262* control, we call SH::tlabs_retire, SH::gclabs_retire.1263*/1264void ShenandoahHeap::ensure_parsability(bool retire_tlabs) {1265// No-op.1266}12671268/*1269* Iterates objects in the heap. This is public API, used for, e.g., heap dumping.1270*1271* We cannot safely iterate objects by doing a linear scan at random points in time. Linear1272* scanning needs to deal with dead objects, which may have dead Klass* pointers (e.g.1273* calling oopDesc::size() would crash) or dangling reference fields (crashes) etc. Linear1274* scanning therefore depends on having a valid marking bitmap to support it. However, we only1275* have a valid marking bitmap after successful marking. In particular, we *don't* have a valid1276* marking bitmap during marking, after aborted marking or during/after cleanup (when we just1277* wiped the bitmap in preparation for next marking).1278*1279* For all those reasons, we implement object iteration as a single marking traversal, reporting1280* objects as we mark+traverse through the heap, starting from GC roots. JVMTI IterateThroughHeap1281* is allowed to report dead objects, but is not required to do so.1282*/1283void ShenandoahHeap::object_iterate(ObjectClosure* cl) {1284// Reset bitmap1285if (!prepare_aux_bitmap_for_iteration())1286return;12871288ShenandoahScanObjectStack oop_stack;1289ObjectIterateScanRootClosure oops(&_aux_bit_map, &oop_stack);1290// Seed the stack with root scan1291scan_roots_for_iteration(&oop_stack, &oops);12921293// Work through the oop stack to traverse heap1294while (! oop_stack.is_empty()) {1295oop obj = oop_stack.pop();1296assert(oopDesc::is_oop(obj), "must be a valid oop");1297cl->do_object(obj);1298obj->oop_iterate(&oops);1299}13001301assert(oop_stack.is_empty(), "should be empty");1302// Reclaim bitmap1303reclaim_aux_bitmap_for_iteration();1304}13051306bool ShenandoahHeap::prepare_aux_bitmap_for_iteration() {1307assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");13081309if (!_aux_bitmap_region_special && !os::commit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size(), false)) {1310log_warning(gc)("Could not commit native memory for auxiliary marking bitmap for heap iteration");1311return false;1312}1313// Reset bitmap1314_aux_bit_map.clear();1315return true;1316}13171318void ShenandoahHeap::scan_roots_for_iteration(ShenandoahScanObjectStack* oop_stack, ObjectIterateScanRootClosure* oops) {1319// Process GC roots according to current GC cycle1320// This populates the work stack with initial objects1321// It is important to relinquish the associated locks before diving1322// into heap dumper1323ShenandoahHeapIterationRootScanner rp;1324rp.roots_do(oops);1325}13261327void ShenandoahHeap::reclaim_aux_bitmap_for_iteration() {1328if (!_aux_bitmap_region_special && !os::uncommit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size())) {1329log_warning(gc)("Could not uncommit native memory for auxiliary marking bitmap for heap iteration");1330}1331}13321333// Closure for parallelly iterate objects1334class ShenandoahObjectIterateParScanClosure : public BasicOopIterateClosure {1335private:1336MarkBitMap* _bitmap;1337ShenandoahObjToScanQueue* _queue;1338ShenandoahHeap* const _heap;1339ShenandoahMarkingContext* const _marking_context;13401341template <class T>1342void do_oop_work(T* p) {1343T o = RawAccess<>::oop_load(p);1344if (!CompressedOops::is_null(o)) {1345oop obj = CompressedOops::decode_not_null(o);1346if (_heap->is_concurrent_weak_root_in_progress() && !_marking_context->is_marked(obj)) {1347// There may be dead oops in weak roots in concurrent root phase, do not touch them.1348return;1349}1350obj = ShenandoahBarrierSet::resolve_forwarded_not_null(obj);13511352assert(oopDesc::is_oop(obj), "Must be a valid oop");1353if (_bitmap->par_mark(obj)) {1354_queue->push(ShenandoahMarkTask(obj));1355}1356}1357}1358public:1359ShenandoahObjectIterateParScanClosure(MarkBitMap* bitmap, ShenandoahObjToScanQueue* q) :1360_bitmap(bitmap), _queue(q), _heap(ShenandoahHeap::heap()),1361_marking_context(_heap->marking_context()) {}1362void do_oop(oop* p) { do_oop_work(p); }1363void do_oop(narrowOop* p) { do_oop_work(p); }1364};13651366// Object iterator for parallel heap iteraion.1367// The root scanning phase happenes in construction as a preparation of1368// parallel marking queues.1369// Every worker processes it's own marking queue. work-stealing is used1370// to balance workload.1371class ShenandoahParallelObjectIterator : public ParallelObjectIterator {1372private:1373uint _num_workers;1374bool _init_ready;1375MarkBitMap* _aux_bit_map;1376ShenandoahHeap* _heap;1377ShenandoahScanObjectStack _roots_stack; // global roots stack1378ShenandoahObjToScanQueueSet* _task_queues;1379public:1380ShenandoahParallelObjectIterator(uint num_workers, MarkBitMap* bitmap) :1381_num_workers(num_workers),1382_init_ready(false),1383_aux_bit_map(bitmap),1384_heap(ShenandoahHeap::heap()) {1385// Initialize bitmap1386_init_ready = _heap->prepare_aux_bitmap_for_iteration();1387if (!_init_ready) {1388return;1389}13901391ObjectIterateScanRootClosure oops(_aux_bit_map, &_roots_stack);1392_heap->scan_roots_for_iteration(&_roots_stack, &oops);13931394_init_ready = prepare_worker_queues();1395}13961397~ShenandoahParallelObjectIterator() {1398// Reclaim bitmap1399_heap->reclaim_aux_bitmap_for_iteration();1400// Reclaim queue for workers1401if (_task_queues!= NULL) {1402for (uint i = 0; i < _num_workers; ++i) {1403ShenandoahObjToScanQueue* q = _task_queues->queue(i);1404if (q != NULL) {1405delete q;1406_task_queues->register_queue(i, NULL);1407}1408}1409delete _task_queues;1410_task_queues = NULL;1411}1412}14131414virtual void object_iterate(ObjectClosure* cl, uint worker_id) {1415if (_init_ready) {1416object_iterate_parallel(cl, worker_id, _task_queues);1417}1418}14191420private:1421// Divide global root_stack into worker queues1422bool prepare_worker_queues() {1423_task_queues = new ShenandoahObjToScanQueueSet((int) _num_workers);1424// Initialize queues for every workers1425for (uint i = 0; i < _num_workers; ++i) {1426ShenandoahObjToScanQueue* task_queue = new ShenandoahObjToScanQueue();1427task_queue->initialize();1428_task_queues->register_queue(i, task_queue);1429}1430// Divide roots among the workers. Assume that object referencing distribution1431// is related with root kind, use round-robin to make every worker have same chance1432// to process every kind of roots1433size_t roots_num = _roots_stack.size();1434if (roots_num == 0) {1435// No work to do1436return false;1437}14381439for (uint j = 0; j < roots_num; j++) {1440uint stack_id = j % _num_workers;1441oop obj = _roots_stack.pop();1442_task_queues->queue(stack_id)->push(ShenandoahMarkTask(obj));1443}1444return true;1445}14461447void object_iterate_parallel(ObjectClosure* cl,1448uint worker_id,1449ShenandoahObjToScanQueueSet* queue_set) {1450assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");1451assert(queue_set != NULL, "task queue must not be NULL");14521453ShenandoahObjToScanQueue* q = queue_set->queue(worker_id);1454assert(q != NULL, "object iterate queue must not be NULL");14551456ShenandoahMarkTask t;1457ShenandoahObjectIterateParScanClosure oops(_aux_bit_map, q);14581459// Work through the queue to traverse heap.1460// Steal when there is no task in queue.1461while (q->pop(t) || queue_set->steal(worker_id, t)) {1462oop obj = t.obj();1463assert(oopDesc::is_oop(obj), "must be a valid oop");1464cl->do_object(obj);1465obj->oop_iterate(&oops);1466}1467assert(q->is_empty(), "should be empty");1468}1469};14701471ParallelObjectIterator* ShenandoahHeap::parallel_object_iterator(uint workers) {1472return new ShenandoahParallelObjectIterator(workers, &_aux_bit_map);1473}14741475// Keep alive an object that was loaded with AS_NO_KEEPALIVE.1476void ShenandoahHeap::keep_alive(oop obj) {1477if (is_concurrent_mark_in_progress() && (obj != NULL)) {1478ShenandoahBarrierSet::barrier_set()->enqueue(obj);1479}1480}14811482void ShenandoahHeap::heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {1483for (size_t i = 0; i < num_regions(); i++) {1484ShenandoahHeapRegion* current = get_region(i);1485blk->heap_region_do(current);1486}1487}14881489class ShenandoahParallelHeapRegionTask : public AbstractGangTask {1490private:1491ShenandoahHeap* const _heap;1492ShenandoahHeapRegionClosure* const _blk;14931494shenandoah_padding(0);1495volatile size_t _index;1496shenandoah_padding(1);14971498public:1499ShenandoahParallelHeapRegionTask(ShenandoahHeapRegionClosure* blk) :1500AbstractGangTask("Shenandoah Parallel Region Operation"),1501_heap(ShenandoahHeap::heap()), _blk(blk), _index(0) {}15021503void work(uint worker_id) {1504ShenandoahParallelWorkerSession worker_session(worker_id);1505size_t stride = ShenandoahParallelRegionStride;15061507size_t max = _heap->num_regions();1508while (Atomic::load(&_index) < max) {1509size_t cur = Atomic::fetch_and_add(&_index, stride, memory_order_relaxed);1510size_t start = cur;1511size_t end = MIN2(cur + stride, max);1512if (start >= max) break;15131514for (size_t i = cur; i < end; i++) {1515ShenandoahHeapRegion* current = _heap->get_region(i);1516_blk->heap_region_do(current);1517}1518}1519}1520};15211522void ShenandoahHeap::parallel_heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {1523assert(blk->is_thread_safe(), "Only thread-safe closures here");1524if (num_regions() > ShenandoahParallelRegionStride) {1525ShenandoahParallelHeapRegionTask task(blk);1526workers()->run_task(&task);1527} else {1528heap_region_iterate(blk);1529}1530}15311532class ShenandoahInitMarkUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {1533private:1534ShenandoahMarkingContext* const _ctx;1535public:1536ShenandoahInitMarkUpdateRegionStateClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}15371538void heap_region_do(ShenandoahHeapRegion* r) {1539assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->index());1540if (r->is_active()) {1541// Check if region needs updating its TAMS. We have updated it already during concurrent1542// reset, so it is very likely we don't need to do another write here.1543if (_ctx->top_at_mark_start(r) != r->top()) {1544_ctx->capture_top_at_mark_start(r);1545}1546} else {1547assert(_ctx->top_at_mark_start(r) == r->top(),1548"Region " SIZE_FORMAT " should already have correct TAMS", r->index());1549}1550}15511552bool is_thread_safe() { return true; }1553};15541555class ShenandoahRendezvousClosure : public HandshakeClosure {1556public:1557inline ShenandoahRendezvousClosure() : HandshakeClosure("ShenandoahRendezvous") {}1558inline void do_thread(Thread* thread) {}1559};15601561void ShenandoahHeap::rendezvous_threads() {1562ShenandoahRendezvousClosure cl;1563Handshake::execute(&cl);1564}15651566void ShenandoahHeap::recycle_trash() {1567free_set()->recycle_trash();1568}15691570class ShenandoahResetUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {1571private:1572ShenandoahMarkingContext* const _ctx;1573public:1574ShenandoahResetUpdateRegionStateClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}15751576void heap_region_do(ShenandoahHeapRegion* r) {1577if (r->is_active()) {1578// Reset live data and set TAMS optimistically. We would recheck these under the pause1579// anyway to capture any updates that happened since now.1580r->clear_live_data();1581_ctx->capture_top_at_mark_start(r);1582}1583}15841585bool is_thread_safe() { return true; }1586};15871588void ShenandoahHeap::prepare_gc() {1589reset_mark_bitmap();15901591ShenandoahResetUpdateRegionStateClosure cl;1592parallel_heap_region_iterate(&cl);1593}15941595class ShenandoahFinalMarkUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {1596private:1597ShenandoahMarkingContext* const _ctx;1598ShenandoahHeapLock* const _lock;15991600public:1601ShenandoahFinalMarkUpdateRegionStateClosure() :1602_ctx(ShenandoahHeap::heap()->complete_marking_context()), _lock(ShenandoahHeap::heap()->lock()) {}16031604void heap_region_do(ShenandoahHeapRegion* r) {1605if (r->is_active()) {1606// All allocations past TAMS are implicitly live, adjust the region data.1607// Bitmaps/TAMS are swapped at this point, so we need to poll complete bitmap.1608HeapWord *tams = _ctx->top_at_mark_start(r);1609HeapWord *top = r->top();1610if (top > tams) {1611r->increase_live_data_alloc_words(pointer_delta(top, tams));1612}16131614// We are about to select the collection set, make sure it knows about1615// current pinning status. Also, this allows trashing more regions that1616// now have their pinning status dropped.1617if (r->is_pinned()) {1618if (r->pin_count() == 0) {1619ShenandoahHeapLocker locker(_lock);1620r->make_unpinned();1621}1622} else {1623if (r->pin_count() > 0) {1624ShenandoahHeapLocker locker(_lock);1625r->make_pinned();1626}1627}16281629// Remember limit for updating refs. It's guaranteed that we get no1630// from-space-refs written from here on.1631r->set_update_watermark_at_safepoint(r->top());1632} else {1633assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->index());1634assert(_ctx->top_at_mark_start(r) == r->top(),1635"Region " SIZE_FORMAT " should have correct TAMS", r->index());1636}1637}16381639bool is_thread_safe() { return true; }1640};16411642void ShenandoahHeap::prepare_regions_and_collection_set(bool concurrent) {1643assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");1644{1645ShenandoahGCPhase phase(concurrent ? ShenandoahPhaseTimings::final_update_region_states :1646ShenandoahPhaseTimings::degen_gc_final_update_region_states);1647ShenandoahFinalMarkUpdateRegionStateClosure cl;1648parallel_heap_region_iterate(&cl);16491650assert_pinned_region_status();1651}16521653{1654ShenandoahGCPhase phase(concurrent ? ShenandoahPhaseTimings::choose_cset :1655ShenandoahPhaseTimings::degen_gc_choose_cset);1656ShenandoahHeapLocker locker(lock());1657_collection_set->clear();1658heuristics()->choose_collection_set(_collection_set);1659}16601661{1662ShenandoahGCPhase phase(concurrent ? ShenandoahPhaseTimings::final_rebuild_freeset :1663ShenandoahPhaseTimings::degen_gc_final_rebuild_freeset);1664ShenandoahHeapLocker locker(lock());1665_free_set->rebuild();1666}1667}16681669void ShenandoahHeap::do_class_unloading() {1670_unloader.unload();1671}16721673void ShenandoahHeap::stw_weak_refs(bool full_gc) {1674// Weak refs processing1675ShenandoahPhaseTimings::Phase phase = full_gc ? ShenandoahPhaseTimings::full_gc_weakrefs1676: ShenandoahPhaseTimings::degen_gc_weakrefs;1677ShenandoahTimingsTracker t(phase);1678ShenandoahGCWorkerPhase worker_phase(phase);1679ref_processor()->process_references(phase, workers(), false /* concurrent */);1680}16811682void ShenandoahHeap::prepare_update_heap_references(bool concurrent) {1683assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");16841685// Evacuation is over, no GCLABs are needed anymore. GCLABs are under URWM, so we need to1686// make them parsable for update code to work correctly. Plus, we can compute new sizes1687// for future GCLABs here.1688if (UseTLAB) {1689ShenandoahGCPhase phase(concurrent ?1690ShenandoahPhaseTimings::init_update_refs_manage_gclabs :1691ShenandoahPhaseTimings::degen_gc_init_update_refs_manage_gclabs);1692gclabs_retire(ResizeTLAB);1693}16941695_update_refs_iterator.reset();1696}16971698void ShenandoahHeap::set_gc_state_all_threads(char state) {1699for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {1700ShenandoahThreadLocalData::set_gc_state(t, state);1701}1702}17031704void ShenandoahHeap::set_gc_state_mask(uint mask, bool value) {1705assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should really be Shenandoah safepoint");1706_gc_state.set_cond(mask, value);1707set_gc_state_all_threads(_gc_state.raw_value());1708}17091710void ShenandoahHeap::set_concurrent_mark_in_progress(bool in_progress) {1711assert(!has_forwarded_objects(), "Not expected before/after mark phase");1712set_gc_state_mask(MARKING, in_progress);1713ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);1714}17151716void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {1717assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint");1718set_gc_state_mask(EVACUATION, in_progress);1719}17201721void ShenandoahHeap::set_concurrent_strong_root_in_progress(bool in_progress) {1722if (in_progress) {1723_concurrent_strong_root_in_progress.set();1724} else {1725_concurrent_strong_root_in_progress.unset();1726}1727}17281729void ShenandoahHeap::set_concurrent_weak_root_in_progress(bool cond) {1730set_gc_state_mask(WEAK_ROOTS, cond);1731}17321733GCTracer* ShenandoahHeap::tracer() {1734return shenandoah_policy()->tracer();1735}17361737size_t ShenandoahHeap::tlab_used(Thread* thread) const {1738return _free_set->used();1739}17401741bool ShenandoahHeap::try_cancel_gc() {1742while (true) {1743jbyte prev = _cancelled_gc.cmpxchg(CANCELLED, CANCELLABLE);1744if (prev == CANCELLABLE) return true;1745else if (prev == CANCELLED) return false;1746assert(ShenandoahSuspendibleWorkers, "should not get here when not using suspendible workers");1747assert(prev == NOT_CANCELLED, "must be NOT_CANCELLED");1748Thread* thread = Thread::current();1749if (thread->is_Java_thread()) {1750// We need to provide a safepoint here, otherwise we might1751// spin forever if a SP is pending.1752ThreadBlockInVM sp(thread->as_Java_thread());1753SpinPause();1754}1755}1756}17571758void ShenandoahHeap::cancel_gc(GCCause::Cause cause) {1759if (try_cancel_gc()) {1760FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause));1761log_info(gc)("%s", msg.buffer());1762Events::log(Thread::current(), "%s", msg.buffer());1763}1764}17651766uint ShenandoahHeap::max_workers() {1767return _max_workers;1768}17691770void ShenandoahHeap::stop() {1771// The shutdown sequence should be able to terminate when GC is running.17721773// Step 0. Notify policy to disable event recording.1774_shenandoah_policy->record_shutdown();17751776// Step 1. Notify control thread that we are in shutdown.1777// Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown.1778// Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below.1779control_thread()->prepare_for_graceful_shutdown();17801781// Step 2. Notify GC workers that we are cancelling GC.1782cancel_gc(GCCause::_shenandoah_stop_vm);17831784// Step 3. Wait until GC worker exits normally.1785control_thread()->stop();1786}17871788void ShenandoahHeap::stw_unload_classes(bool full_gc) {1789if (!unload_classes()) return;1790// Unload classes and purge SystemDictionary.1791{1792ShenandoahPhaseTimings::Phase phase = full_gc ?1793ShenandoahPhaseTimings::full_gc_purge_class_unload :1794ShenandoahPhaseTimings::degen_gc_purge_class_unload;1795ShenandoahGCPhase gc_phase(phase);1796ShenandoahGCWorkerPhase worker_phase(phase);1797bool purged_class = SystemDictionary::do_unloading(gc_timer());17981799ShenandoahIsAliveSelector is_alive;1800uint num_workers = _workers->active_workers();1801ShenandoahClassUnloadingTask unlink_task(phase, is_alive.is_alive_closure(), num_workers, purged_class);1802_workers->run_task(&unlink_task);1803}18041805{1806ShenandoahGCPhase phase(full_gc ?1807ShenandoahPhaseTimings::full_gc_purge_cldg :1808ShenandoahPhaseTimings::degen_gc_purge_cldg);1809ClassLoaderDataGraph::purge(/*at_safepoint*/true);1810}1811// Resize and verify metaspace1812MetaspaceGC::compute_new_size();1813DEBUG_ONLY(MetaspaceUtils::verify();)1814}18151816// Weak roots are either pre-evacuated (final mark) or updated (final updaterefs),1817// so they should not have forwarded oops.1818// However, we do need to "null" dead oops in the roots, if can not be done1819// in concurrent cycles.1820void ShenandoahHeap::stw_process_weak_roots(bool full_gc) {1821uint num_workers = _workers->active_workers();1822ShenandoahPhaseTimings::Phase timing_phase = full_gc ?1823ShenandoahPhaseTimings::full_gc_purge_weak_par :1824ShenandoahPhaseTimings::degen_gc_purge_weak_par;1825ShenandoahGCPhase phase(timing_phase);1826ShenandoahGCWorkerPhase worker_phase(timing_phase);1827// Cleanup weak roots1828if (has_forwarded_objects()) {1829ShenandoahForwardedIsAliveClosure is_alive;1830ShenandoahUpdateRefsClosure keep_alive;1831ShenandoahParallelWeakRootsCleaningTask<ShenandoahForwardedIsAliveClosure, ShenandoahUpdateRefsClosure>1832cleaning_task(timing_phase, &is_alive, &keep_alive, num_workers);1833_workers->run_task(&cleaning_task);1834} else {1835ShenandoahIsAliveClosure is_alive;1836#ifdef ASSERT1837ShenandoahAssertNotForwardedClosure verify_cl;1838ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, ShenandoahAssertNotForwardedClosure>1839cleaning_task(timing_phase, &is_alive, &verify_cl, num_workers);1840#else1841ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, DoNothingClosure>1842cleaning_task(timing_phase, &is_alive, &do_nothing_cl, num_workers);1843#endif1844_workers->run_task(&cleaning_task);1845}1846}18471848void ShenandoahHeap::parallel_cleaning(bool full_gc) {1849assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");1850assert(is_stw_gc_in_progress(), "Only for Degenerated and Full GC");1851ShenandoahGCPhase phase(full_gc ?1852ShenandoahPhaseTimings::full_gc_purge :1853ShenandoahPhaseTimings::degen_gc_purge);1854stw_weak_refs(full_gc);1855stw_process_weak_roots(full_gc);1856stw_unload_classes(full_gc);1857}18581859void ShenandoahHeap::set_has_forwarded_objects(bool cond) {1860set_gc_state_mask(HAS_FORWARDED, cond);1861}18621863void ShenandoahHeap::set_unload_classes(bool uc) {1864_unload_classes.set_cond(uc);1865}18661867bool ShenandoahHeap::unload_classes() const {1868return _unload_classes.is_set();1869}18701871address ShenandoahHeap::in_cset_fast_test_addr() {1872ShenandoahHeap* heap = ShenandoahHeap::heap();1873assert(heap->collection_set() != NULL, "Sanity");1874return (address) heap->collection_set()->biased_map_address();1875}18761877address ShenandoahHeap::cancelled_gc_addr() {1878return (address) ShenandoahHeap::heap()->_cancelled_gc.addr_of();1879}18801881address ShenandoahHeap::gc_state_addr() {1882return (address) ShenandoahHeap::heap()->_gc_state.addr_of();1883}18841885size_t ShenandoahHeap::bytes_allocated_since_gc_start() {1886return Atomic::load(&_bytes_allocated_since_gc_start);1887}18881889void ShenandoahHeap::reset_bytes_allocated_since_gc_start() {1890Atomic::store(&_bytes_allocated_since_gc_start, (size_t)0);1891}18921893void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) {1894_degenerated_gc_in_progress.set_cond(in_progress);1895}18961897void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {1898_full_gc_in_progress.set_cond(in_progress);1899}19001901void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) {1902assert (is_full_gc_in_progress(), "should be");1903_full_gc_move_in_progress.set_cond(in_progress);1904}19051906void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {1907set_gc_state_mask(UPDATEREFS, in_progress);1908}19091910void ShenandoahHeap::register_nmethod(nmethod* nm) {1911ShenandoahCodeRoots::register_nmethod(nm);1912}19131914void ShenandoahHeap::unregister_nmethod(nmethod* nm) {1915ShenandoahCodeRoots::unregister_nmethod(nm);1916}19171918void ShenandoahHeap::flush_nmethod(nmethod* nm) {1919ShenandoahCodeRoots::flush_nmethod(nm);1920}19211922oop ShenandoahHeap::pin_object(JavaThread* thr, oop o) {1923heap_region_containing(o)->record_pin();1924return o;1925}19261927void ShenandoahHeap::unpin_object(JavaThread* thr, oop o) {1928heap_region_containing(o)->record_unpin();1929}19301931void ShenandoahHeap::sync_pinned_region_status() {1932ShenandoahHeapLocker locker(lock());19331934for (size_t i = 0; i < num_regions(); i++) {1935ShenandoahHeapRegion *r = get_region(i);1936if (r->is_active()) {1937if (r->is_pinned()) {1938if (r->pin_count() == 0) {1939r->make_unpinned();1940}1941} else {1942if (r->pin_count() > 0) {1943r->make_pinned();1944}1945}1946}1947}19481949assert_pinned_region_status();1950}19511952#ifdef ASSERT1953void ShenandoahHeap::assert_pinned_region_status() {1954for (size_t i = 0; i < num_regions(); i++) {1955ShenandoahHeapRegion* r = get_region(i);1956assert((r->is_pinned() && r->pin_count() > 0) || (!r->is_pinned() && r->pin_count() == 0),1957"Region " SIZE_FORMAT " pinning status is inconsistent", i);1958}1959}1960#endif19611962ConcurrentGCTimer* ShenandoahHeap::gc_timer() const {1963return _gc_timer;1964}19651966void ShenandoahHeap::prepare_concurrent_roots() {1967assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");1968assert(!is_stw_gc_in_progress(), "Only concurrent GC");1969set_concurrent_strong_root_in_progress(!collection_set()->is_empty());1970set_concurrent_weak_root_in_progress(true);1971if (unload_classes()) {1972_unloader.prepare();1973}1974}19751976void ShenandoahHeap::finish_concurrent_roots() {1977assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");1978assert(!is_stw_gc_in_progress(), "Only concurrent GC");1979if (unload_classes()) {1980_unloader.finish();1981}1982}19831984#ifdef ASSERT1985void ShenandoahHeap::assert_gc_workers(uint nworkers) {1986assert(nworkers > 0 && nworkers <= max_workers(), "Sanity");19871988if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {1989if (UseDynamicNumberOfGCThreads) {1990assert(nworkers <= ParallelGCThreads, "Cannot use more than it has");1991} else {1992// Use ParallelGCThreads inside safepoints1993assert(nworkers == ParallelGCThreads, "Use ParallelGCThreads within safepoints");1994}1995} else {1996if (UseDynamicNumberOfGCThreads) {1997assert(nworkers <= ConcGCThreads, "Cannot use more than it has");1998} else {1999// Use ConcGCThreads outside safepoints2000assert(nworkers == ConcGCThreads, "Use ConcGCThreads outside safepoints");2001}2002}2003}2004#endif20052006ShenandoahVerifier* ShenandoahHeap::verifier() {2007guarantee(ShenandoahVerify, "Should be enabled");2008assert (_verifier != NULL, "sanity");2009return _verifier;2010}20112012template<bool CONCURRENT>2013class ShenandoahUpdateHeapRefsTask : public AbstractGangTask {2014private:2015ShenandoahHeap* _heap;2016ShenandoahRegionIterator* _regions;2017public:2018ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions) :2019AbstractGangTask("Shenandoah Update References"),2020_heap(ShenandoahHeap::heap()),2021_regions(regions) {2022}20232024void work(uint worker_id) {2025if (CONCURRENT) {2026ShenandoahConcurrentWorkerSession worker_session(worker_id);2027ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);2028do_work<ShenandoahConcUpdateRefsClosure>();2029} else {2030ShenandoahParallelWorkerSession worker_session(worker_id);2031do_work<ShenandoahSTWUpdateRefsClosure>();2032}2033}20342035private:2036template<class T>2037void do_work() {2038T cl;2039ShenandoahHeapRegion* r = _regions->next();2040ShenandoahMarkingContext* const ctx = _heap->complete_marking_context();2041while (r != NULL) {2042HeapWord* update_watermark = r->get_update_watermark();2043assert (update_watermark >= r->bottom(), "sanity");2044if (r->is_active() && !r->is_cset()) {2045_heap->marked_object_oop_iterate(r, &cl, update_watermark);2046}2047if (ShenandoahPacing) {2048_heap->pacer()->report_updaterefs(pointer_delta(update_watermark, r->bottom()));2049}2050if (_heap->check_cancelled_gc_and_yield(CONCURRENT)) {2051return;2052}2053r = _regions->next();2054}2055}2056};20572058void ShenandoahHeap::update_heap_references(bool concurrent) {2059assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");20602061if (concurrent) {2062ShenandoahUpdateHeapRefsTask<true> task(&_update_refs_iterator);2063workers()->run_task(&task);2064} else {2065ShenandoahUpdateHeapRefsTask<false> task(&_update_refs_iterator);2066workers()->run_task(&task);2067}2068}206920702071class ShenandoahFinalUpdateRefsUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {2072private:2073ShenandoahHeapLock* const _lock;20742075public:2076ShenandoahFinalUpdateRefsUpdateRegionStateClosure() : _lock(ShenandoahHeap::heap()->lock()) {}20772078void heap_region_do(ShenandoahHeapRegion* r) {2079// Drop unnecessary "pinned" state from regions that does not have CP marks2080// anymore, as this would allow trashing them.20812082if (r->is_active()) {2083if (r->is_pinned()) {2084if (r->pin_count() == 0) {2085ShenandoahHeapLocker locker(_lock);2086r->make_unpinned();2087}2088} else {2089if (r->pin_count() > 0) {2090ShenandoahHeapLocker locker(_lock);2091r->make_pinned();2092}2093}2094}2095}20962097bool is_thread_safe() { return true; }2098};20992100void ShenandoahHeap::update_heap_region_states(bool concurrent) {2101assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");2102assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");21032104{2105ShenandoahGCPhase phase(concurrent ?2106ShenandoahPhaseTimings::final_update_refs_update_region_states :2107ShenandoahPhaseTimings::degen_gc_final_update_refs_update_region_states);2108ShenandoahFinalUpdateRefsUpdateRegionStateClosure cl;2109parallel_heap_region_iterate(&cl);21102111assert_pinned_region_status();2112}21132114{2115ShenandoahGCPhase phase(concurrent ?2116ShenandoahPhaseTimings::final_update_refs_trash_cset :2117ShenandoahPhaseTimings::degen_gc_final_update_refs_trash_cset);2118trash_cset_regions();2119}2120}21212122void ShenandoahHeap::rebuild_free_set(bool concurrent) {2123{2124ShenandoahGCPhase phase(concurrent ?2125ShenandoahPhaseTimings::final_update_refs_rebuild_freeset :2126ShenandoahPhaseTimings::degen_gc_final_update_refs_rebuild_freeset);2127ShenandoahHeapLocker locker(lock());2128_free_set->rebuild();2129}2130}21312132void ShenandoahHeap::print_extended_on(outputStream *st) const {2133print_on(st);2134print_heap_regions_on(st);2135}21362137bool ShenandoahHeap::is_bitmap_slice_committed(ShenandoahHeapRegion* r, bool skip_self) {2138size_t slice = r->index() / _bitmap_regions_per_slice;21392140size_t regions_from = _bitmap_regions_per_slice * slice;2141size_t regions_to = MIN2(num_regions(), _bitmap_regions_per_slice * (slice + 1));2142for (size_t g = regions_from; g < regions_to; g++) {2143assert (g / _bitmap_regions_per_slice == slice, "same slice");2144if (skip_self && g == r->index()) continue;2145if (get_region(g)->is_committed()) {2146return true;2147}2148}2149return false;2150}21512152bool ShenandoahHeap::commit_bitmap_slice(ShenandoahHeapRegion* r) {2153shenandoah_assert_heaplocked();21542155// Bitmaps in special regions do not need commits2156if (_bitmap_region_special) {2157return true;2158}21592160if (is_bitmap_slice_committed(r, true)) {2161// Some other region from the group is already committed, meaning the bitmap2162// slice is already committed, we exit right away.2163return true;2164}21652166// Commit the bitmap slice:2167size_t slice = r->index() / _bitmap_regions_per_slice;2168size_t off = _bitmap_bytes_per_slice * slice;2169size_t len = _bitmap_bytes_per_slice;2170char* start = (char*) _bitmap_region.start() + off;21712172if (!os::commit_memory(start, len, false)) {2173return false;2174}21752176if (AlwaysPreTouch) {2177os::pretouch_memory(start, start + len, _pretouch_bitmap_page_size);2178}21792180return true;2181}21822183bool ShenandoahHeap::uncommit_bitmap_slice(ShenandoahHeapRegion *r) {2184shenandoah_assert_heaplocked();21852186// Bitmaps in special regions do not need uncommits2187if (_bitmap_region_special) {2188return true;2189}21902191if (is_bitmap_slice_committed(r, true)) {2192// Some other region from the group is still committed, meaning the bitmap2193// slice is should stay committed, exit right away.2194return true;2195}21962197// Uncommit the bitmap slice:2198size_t slice = r->index() / _bitmap_regions_per_slice;2199size_t off = _bitmap_bytes_per_slice * slice;2200size_t len = _bitmap_bytes_per_slice;2201if (!os::uncommit_memory((char*)_bitmap_region.start() + off, len)) {2202return false;2203}2204return true;2205}22062207void ShenandoahHeap::safepoint_synchronize_begin() {2208if (ShenandoahSuspendibleWorkers || UseStringDeduplication) {2209SuspendibleThreadSet::synchronize();2210}2211}22122213void ShenandoahHeap::safepoint_synchronize_end() {2214if (ShenandoahSuspendibleWorkers || UseStringDeduplication) {2215SuspendibleThreadSet::desynchronize();2216}2217}22182219void ShenandoahHeap::entry_uncommit(double shrink_before, size_t shrink_until) {2220static const char *msg = "Concurrent uncommit";2221ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_uncommit, true /* log_heap_usage */);2222EventMark em("%s", msg);22232224op_uncommit(shrink_before, shrink_until);2225}22262227void ShenandoahHeap::try_inject_alloc_failure() {2228if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) {2229_inject_alloc_failure.set();2230os::naked_short_sleep(1);2231if (cancelled_gc()) {2232log_info(gc)("Allocation failure was successfully injected");2233}2234}2235}22362237bool ShenandoahHeap::should_inject_alloc_failure() {2238return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset();2239}22402241void ShenandoahHeap::initialize_serviceability() {2242_memory_pool = new ShenandoahMemoryPool(this);2243_cycle_memory_manager.add_pool(_memory_pool);2244_stw_memory_manager.add_pool(_memory_pool);2245}22462247GrowableArray<GCMemoryManager*> ShenandoahHeap::memory_managers() {2248GrowableArray<GCMemoryManager*> memory_managers(2);2249memory_managers.append(&_cycle_memory_manager);2250memory_managers.append(&_stw_memory_manager);2251return memory_managers;2252}22532254GrowableArray<MemoryPool*> ShenandoahHeap::memory_pools() {2255GrowableArray<MemoryPool*> memory_pools(1);2256memory_pools.append(_memory_pool);2257return memory_pools;2258}22592260MemoryUsage ShenandoahHeap::memory_usage() {2261return _memory_pool->get_memory_usage();2262}22632264ShenandoahRegionIterator::ShenandoahRegionIterator() :2265_heap(ShenandoahHeap::heap()),2266_index(0) {}22672268ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) :2269_heap(heap),2270_index(0) {}22712272void ShenandoahRegionIterator::reset() {2273_index = 0;2274}22752276bool ShenandoahRegionIterator::has_next() const {2277return _index < _heap->num_regions();2278}22792280char ShenandoahHeap::gc_state() const {2281return _gc_state.raw_value();2282}22832284ShenandoahLiveData* ShenandoahHeap::get_liveness_cache(uint worker_id) {2285#ifdef ASSERT2286assert(_liveness_cache != NULL, "sanity");2287assert(worker_id < _max_workers, "sanity");2288for (uint i = 0; i < num_regions(); i++) {2289assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty");2290}2291#endif2292return _liveness_cache[worker_id];2293}22942295void ShenandoahHeap::flush_liveness_cache(uint worker_id) {2296assert(worker_id < _max_workers, "sanity");2297assert(_liveness_cache != NULL, "sanity");2298ShenandoahLiveData* ld = _liveness_cache[worker_id];2299for (uint i = 0; i < num_regions(); i++) {2300ShenandoahLiveData live = ld[i];2301if (live > 0) {2302ShenandoahHeapRegion* r = get_region(i);2303r->increase_live_data_gc_words(live);2304ld[i] = 0;2305}2306}2307}230823092310