Path: blob/master/src/hotspot/share/gc/shared/collectedHeap.hpp
40957 views
/*1* Copyright (c) 2001, 2021, Oracle and/or its affiliates. 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#ifndef SHARE_GC_SHARED_COLLECTEDHEAP_HPP25#define SHARE_GC_SHARED_COLLECTEDHEAP_HPP2627#include "gc/shared/gcCause.hpp"28#include "gc/shared/gcWhen.hpp"29#include "gc/shared/verifyOption.hpp"30#include "memory/allocation.hpp"31#include "memory/metaspace.hpp"32#include "memory/universe.hpp"33#include "runtime/handles.hpp"34#include "runtime/perfDataTypes.hpp"35#include "runtime/safepoint.hpp"36#include "services/memoryUsage.hpp"37#include "utilities/debug.hpp"38#include "utilities/formatBuffer.hpp"39#include "utilities/growableArray.hpp"4041// A "CollectedHeap" is an implementation of a java heap for HotSpot. This42// is an abstract class: there may be many different kinds of heaps. This43// class defines the functions that a heap must implement, and contains44// infrastructure common to all heaps.4546class AbstractGangTask;47class AdaptiveSizePolicy;48class BarrierSet;49class GCHeapLog;50class GCHeapSummary;51class GCTimer;52class GCTracer;53class GCMemoryManager;54class MemoryPool;55class MetaspaceSummary;56class ReservedHeapSpace;57class SoftRefPolicy;58class Thread;59class ThreadClosure;60class VirtualSpaceSummary;61class WorkGang;62class nmethod;6364class ParallelObjectIterator : public CHeapObj<mtGC> {65public:66virtual void object_iterate(ObjectClosure* cl, uint worker_id) = 0;67virtual ~ParallelObjectIterator() {}68};6970//71// CollectedHeap72// GenCollectedHeap73// SerialHeap74// G1CollectedHeap75// ParallelScavengeHeap76// ShenandoahHeap77// ZCollectedHeap78//79class CollectedHeap : public CHeapObj<mtInternal> {80friend class VMStructs;81friend class JVMCIVMStructs;82friend class IsGCActiveMark; // Block structured external access to _is_gc_active83friend class MemAllocator;8485private:86GCHeapLog* _gc_heap_log;8788// Historic gc information89size_t _capacity_at_last_gc;90size_t _used_at_last_gc;9192protected:93// Not used by all GCs94MemRegion _reserved;9596bool _is_gc_active;9798// Used for filler objects (static, but initialized in ctor).99static size_t _filler_array_max_size;100101// Last time the whole heap has been examined in support of RMI102// MaxObjectInspectionAge.103// This timestamp must be monotonically non-decreasing to avoid104// time-warp warnings.105jlong _last_whole_heap_examined_time_ns;106107unsigned int _total_collections; // ... started108unsigned int _total_full_collections; // ... started109NOT_PRODUCT(volatile size_t _promotion_failure_alot_count;)110NOT_PRODUCT(volatile size_t _promotion_failure_alot_gc_number;)111112// Reason for current garbage collection. Should be set to113// a value reflecting no collection between collections.114GCCause::Cause _gc_cause;115GCCause::Cause _gc_lastcause;116PerfStringVariable* _perf_gc_cause;117PerfStringVariable* _perf_gc_lastcause;118119// Constructor120CollectedHeap();121122// Create a new tlab. All TLAB allocations must go through this.123// To allow more flexible TLAB allocations min_size specifies124// the minimum size needed, while requested_size is the requested125// size based on ergonomics. The actually allocated size will be126// returned in actual_size.127virtual HeapWord* allocate_new_tlab(size_t min_size,128size_t requested_size,129size_t* actual_size);130131// Reinitialize tlabs before resuming mutators.132virtual void resize_all_tlabs();133134// Raw memory allocation facilities135// The obj and array allocate methods are covers for these methods.136// mem_allocate() should never be137// called to allocate TLABs, only individual objects.138virtual HeapWord* mem_allocate(size_t size,139bool* gc_overhead_limit_was_exceeded) = 0;140141// Filler object utilities.142static inline size_t filler_array_hdr_size();143static inline size_t filler_array_min_size();144145DEBUG_ONLY(static void fill_args_check(HeapWord* start, size_t words);)146DEBUG_ONLY(static void zap_filler_array(HeapWord* start, size_t words, bool zap = true);)147148// Fill with a single array; caller must ensure filler_array_min_size() <=149// words <= filler_array_max_size().150static inline void fill_with_array(HeapWord* start, size_t words, bool zap = true);151152// Fill with a single object (either an int array or a java.lang.Object).153static inline void fill_with_object_impl(HeapWord* start, size_t words, bool zap = true);154155virtual void trace_heap(GCWhen::Type when, const GCTracer* tracer);156157// Verification functions158virtual void check_for_non_bad_heap_word_value(HeapWord* addr, size_t size)159PRODUCT_RETURN;160debug_only(static void check_for_valid_allocation_state();)161162public:163enum Name {164None,165Serial,166Parallel,167G1,168Epsilon,169Z,170Shenandoah171};172173protected:174// Get a pointer to the derived heap object. Used to implement175// derived class heap() functions rather than being called directly.176template<typename T>177static T* named_heap(Name kind) {178CollectedHeap* heap = Universe::heap();179assert(heap != NULL, "Uninitialized heap");180assert(kind == heap->kind(), "Heap kind %u should be %u",181static_cast<uint>(heap->kind()), static_cast<uint>(kind));182return static_cast<T*>(heap);183}184185public:186187static inline size_t filler_array_max_size() {188return _filler_array_max_size;189}190191virtual Name kind() const = 0;192193virtual const char* name() const = 0;194195/**196* Returns JNI error code JNI_ENOMEM if memory could not be allocated,197* and JNI_OK on success.198*/199virtual jint initialize() = 0;200201// In many heaps, there will be a need to perform some initialization activities202// after the Universe is fully formed, but before general heap allocation is allowed.203// This is the correct place to place such initialization methods.204virtual void post_initialize();205206// Stop any onging concurrent work and prepare for exit.207virtual void stop() {}208209// Stop and resume concurrent GC threads interfering with safepoint operations210virtual void safepoint_synchronize_begin() {}211virtual void safepoint_synchronize_end() {}212213void initialize_reserved_region(const ReservedHeapSpace& rs);214215virtual size_t capacity() const = 0;216virtual size_t used() const = 0;217218// Returns unused capacity.219virtual size_t unused() const;220221// Historic gc information222size_t free_at_last_gc() const { return _capacity_at_last_gc - _used_at_last_gc; }223size_t used_at_last_gc() const { return _used_at_last_gc; }224void update_capacity_and_used_at_gc();225226// Return "true" if the part of the heap that allocates Java227// objects has reached the maximal committed limit that it can228// reach, without a garbage collection.229virtual bool is_maximal_no_gc() const = 0;230231// Support for java.lang.Runtime.maxMemory(): return the maximum amount of232// memory that the vm could make available for storing 'normal' java objects.233// This is based on the reserved address space, but should not include space234// that the vm uses internally for bookkeeping or temporary storage235// (e.g., in the case of the young gen, one of the survivor236// spaces).237virtual size_t max_capacity() const = 0;238239// Returns "TRUE" iff "p" points into the committed areas of the heap.240// This method can be expensive so avoid using it in performance critical241// code.242virtual bool is_in(const void* p) const = 0;243244DEBUG_ONLY(bool is_in_or_null(const void* p) const { return p == NULL || is_in(p); })245246virtual uint32_t hash_oop(oop obj) const;247248void set_gc_cause(GCCause::Cause v);249GCCause::Cause gc_cause() { return _gc_cause; }250251oop obj_allocate(Klass* klass, int size, TRAPS);252virtual oop array_allocate(Klass* klass, int size, int length, bool do_zero, TRAPS);253oop class_allocate(Klass* klass, int size, TRAPS);254255// Utilities for turning raw memory into filler objects.256//257// min_fill_size() is the smallest region that can be filled.258// fill_with_objects() can fill arbitrary-sized regions of the heap using259// multiple objects. fill_with_object() is for regions known to be smaller260// than the largest array of integers; it uses a single object to fill the261// region and has slightly less overhead.262static size_t min_fill_size() {263return size_t(align_object_size(oopDesc::header_size()));264}265266static void fill_with_objects(HeapWord* start, size_t words, bool zap = true);267268static void fill_with_object(HeapWord* start, size_t words, bool zap = true);269static void fill_with_object(MemRegion region, bool zap = true) {270fill_with_object(region.start(), region.word_size(), zap);271}272static void fill_with_object(HeapWord* start, HeapWord* end, bool zap = true) {273fill_with_object(start, pointer_delta(end, start), zap);274}275276virtual void fill_with_dummy_object(HeapWord* start, HeapWord* end, bool zap);277virtual size_t min_dummy_object_size() const;278size_t tlab_alloc_reserve() const;279280// Some heaps may offer a contiguous region for shared non-blocking281// allocation, via inlined code (by exporting the address of the top and282// end fields defining the extent of the contiguous allocation region.)283284// This function returns "true" iff the heap supports this kind of285// allocation. (Default is "no".)286virtual bool supports_inline_contig_alloc() const {287return false;288}289// These functions return the addresses of the fields that define the290// boundaries of the contiguous allocation area. (These fields should be291// physically near to one another.)292virtual HeapWord* volatile* top_addr() const {293guarantee(false, "inline contiguous allocation not supported");294return NULL;295}296virtual HeapWord** end_addr() const {297guarantee(false, "inline contiguous allocation not supported");298return NULL;299}300301// Some heaps may be in an unparseable state at certain times between302// collections. This may be necessary for efficient implementation of303// certain allocation-related activities. Calling this function before304// attempting to parse a heap ensures that the heap is in a parsable305// state (provided other concurrent activity does not introduce306// unparsability). It is normally expected, therefore, that this307// method is invoked with the world stopped.308// NOTE: if you override this method, make sure you call309// super::ensure_parsability so that the non-generational310// part of the work gets done. See implementation of311// CollectedHeap::ensure_parsability and, for instance,312// that of GenCollectedHeap::ensure_parsability().313// The argument "retire_tlabs" controls whether existing TLABs314// are merely filled or also retired, thus preventing further315// allocation from them and necessitating allocation of new TLABs.316virtual void ensure_parsability(bool retire_tlabs);317318// The amount of space available for thread-local allocation buffers.319virtual size_t tlab_capacity(Thread *thr) const = 0;320321// The amount of used space for thread-local allocation buffers for the given thread.322virtual size_t tlab_used(Thread *thr) const = 0;323324virtual size_t max_tlab_size() const;325326// An estimate of the maximum allocation that could be performed327// for thread-local allocation buffers without triggering any328// collection or expansion activity.329virtual size_t unsafe_max_tlab_alloc(Thread *thr) const {330guarantee(false, "thread-local allocation buffers not supported");331return 0;332}333334// If a GC uses a stack watermark barrier, the stack processing is lazy, concurrent,335// incremental and cooperative. In order for that to work well, mechanisms that stop336// another thread might want to ensure its roots are in a sane state.337virtual bool uses_stack_watermark_barrier() const { return false; }338339// Perform a collection of the heap; intended for use in implementing340// "System.gc". This probably implies as full a collection as the341// "CollectedHeap" supports.342virtual void collect(GCCause::Cause cause) = 0;343344// Perform a full collection345virtual void do_full_collection(bool clear_all_soft_refs) = 0;346347// This interface assumes that it's being called by the348// vm thread. It collects the heap assuming that the349// heap lock is already held and that we are executing in350// the context of the vm thread.351virtual void collect_as_vm_thread(GCCause::Cause cause);352353virtual MetaWord* satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,354size_t size,355Metaspace::MetadataType mdtype);356357// Returns "true" iff there is a stop-world GC in progress. (I assume358// that it should answer "false" for the concurrent part of a concurrent359// collector -- dld).360bool is_gc_active() const { return _is_gc_active; }361362// Total number of GC collections (started)363unsigned int total_collections() const { return _total_collections; }364unsigned int total_full_collections() const { return _total_full_collections;}365366// Increment total number of GC collections (started)367void increment_total_collections(bool full = false) {368_total_collections++;369if (full) {370increment_total_full_collections();371}372}373374void increment_total_full_collections() { _total_full_collections++; }375376// Return the SoftRefPolicy for the heap;377virtual SoftRefPolicy* soft_ref_policy() = 0;378379virtual MemoryUsage memory_usage();380virtual GrowableArray<GCMemoryManager*> memory_managers() = 0;381virtual GrowableArray<MemoryPool*> memory_pools() = 0;382383// Iterate over all objects, calling "cl.do_object" on each.384virtual void object_iterate(ObjectClosure* cl) = 0;385386virtual ParallelObjectIterator* parallel_object_iterator(uint thread_num) {387return NULL;388}389390// Keep alive an object that was loaded with AS_NO_KEEPALIVE.391virtual void keep_alive(oop obj) {}392393// Perform any cleanup actions necessary before allowing a verification.394virtual void prepare_for_verify() = 0;395396// Returns the longest time (in ms) that has elapsed since the last397// time that the whole heap has been examined by a garbage collection.398jlong millis_since_last_whole_heap_examined();399// GC should call this when the next whole heap analysis has completed to400// satisfy above requirement.401void record_whole_heap_examined_timestamp();402403private:404// Generate any dumps preceding or following a full gc405void full_gc_dump(GCTimer* timer, bool before);406407virtual void initialize_serviceability() = 0;408409public:410void pre_full_gc_dump(GCTimer* timer);411void post_full_gc_dump(GCTimer* timer);412413virtual VirtualSpaceSummary create_heap_space_summary();414GCHeapSummary create_heap_summary();415416MetaspaceSummary create_metaspace_summary();417418// Print heap information on the given outputStream.419virtual void print_on(outputStream* st) const = 0;420// The default behavior is to call print_on() on tty.421virtual void print() const;422423// Print more detailed heap information on the given424// outputStream. The default behavior is to call print_on(). It is425// up to each subclass to override it and add any additional output426// it needs.427virtual void print_extended_on(outputStream* st) const {428print_on(st);429}430431virtual void print_on_error(outputStream* st) const;432433// Used to print information about locations in the hs_err file.434virtual bool print_location(outputStream* st, void* addr) const = 0;435436// Iterator for all GC threads (other than VM thread)437virtual void gc_threads_do(ThreadClosure* tc) const = 0;438439// Print any relevant tracing info that flags imply.440// Default implementation does nothing.441virtual void print_tracing_info() const = 0;442443void print_heap_before_gc();444void print_heap_after_gc();445446// Registering and unregistering an nmethod (compiled code) with the heap.447virtual void register_nmethod(nmethod* nm) = 0;448virtual void unregister_nmethod(nmethod* nm) = 0;449// Callback for when nmethod is about to be deleted.450virtual void flush_nmethod(nmethod* nm) = 0;451virtual void verify_nmethod(nmethod* nm) = 0;452453void trace_heap_before_gc(const GCTracer* gc_tracer);454void trace_heap_after_gc(const GCTracer* gc_tracer);455456// Heap verification457virtual void verify(VerifyOption option) = 0;458459// Return true if concurrent gc control via WhiteBox is supported by460// this collector. The default implementation returns false.461virtual bool supports_concurrent_gc_breakpoints() const;462463// Provides a thread pool to SafepointSynchronize to use464// for parallel safepoint cleanup.465// GCs that use a GC worker thread pool may want to share466// it for use during safepoint cleanup. This is only possible467// if the GC can pause and resume concurrent work (e.g. G1468// concurrent marking) for an intermittent non-GC safepoint.469// If this method returns NULL, SafepointSynchronize will470// perform cleanup tasks serially in the VMThread.471virtual WorkGang* safepoint_workers() { return NULL; }472473// Support for object pinning. This is used by JNI Get*Critical()474// and Release*Critical() family of functions. If supported, the GC475// must guarantee that pinned objects never move.476virtual bool supports_object_pinning() const;477virtual oop pin_object(JavaThread* thread, oop obj);478virtual void unpin_object(JavaThread* thread, oop obj);479480// Is the given object inside a CDS archive area?481virtual bool is_archived_object(oop object) const;482483virtual bool is_oop(oop object) const;484// Non product verification and debugging.485#ifndef PRODUCT486// Support for PromotionFailureALot. Return true if it's time to cause a487// promotion failure. The no-argument version uses488// this->_promotion_failure_alot_count as the counter.489bool promotion_should_fail(volatile size_t* count);490bool promotion_should_fail();491492// Reset the PromotionFailureALot counters. Should be called at the end of a493// GC in which promotion failure occurred.494void reset_promotion_should_fail(volatile size_t* count);495void reset_promotion_should_fail();496#endif // #ifndef PRODUCT497};498499// Class to set and reset the GC cause for a CollectedHeap.500501class GCCauseSetter : StackObj {502CollectedHeap* _heap;503GCCause::Cause _previous_cause;504public:505GCCauseSetter(CollectedHeap* heap, GCCause::Cause cause) {506_heap = heap;507_previous_cause = _heap->gc_cause();508_heap->set_gc_cause(cause);509}510511~GCCauseSetter() {512_heap->set_gc_cause(_previous_cause);513}514};515516#endif // SHARE_GC_SHARED_COLLECTEDHEAP_HPP517518519