Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/gc_interface/collectedHeap.hpp
32285 views
/*1* Copyright (c) 2001, 2014, 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_VM_GC_INTERFACE_COLLECTEDHEAP_HPP25#define SHARE_VM_GC_INTERFACE_COLLECTEDHEAP_HPP2627#include "gc_interface/gcCause.hpp"28#include "gc_implementation/shared/gcWhen.hpp"29#include "memory/allocation.hpp"30#include "memory/barrierSet.hpp"31#include "runtime/handles.hpp"32#include "runtime/perfData.hpp"33#include "runtime/safepoint.hpp"34#include "utilities/events.hpp"3536// A "CollectedHeap" is an implementation of a java heap for HotSpot. This37// is an abstract class: there may be many different kinds of heaps. This38// class defines the functions that a heap must implement, and contains39// infrastructure common to all heaps.4041class AdaptiveSizePolicy;42class BarrierSet;43class CollectorPolicy;44class GCHeapSummary;45class GCTimer;46class GCTracer;47class MetaspaceSummary;48class Thread;49class ThreadClosure;50class VirtualSpaceSummary;51class nmethod;5253class GCMessage : public FormatBuffer<1024> {54public:55bool is_before;5657public:58GCMessage() {}59};6061class GCHeapLog : public EventLogBase<GCMessage> {62private:63void log_heap(bool before);6465public:66GCHeapLog() : EventLogBase<GCMessage>("GC Heap History") {}6768void log_heap_before() {69log_heap(true);70}71void log_heap_after() {72log_heap(false);73}74};7576//77// CollectedHeap78// SharedHeap79// GenCollectedHeap80// G1CollectedHeap81// ParallelScavengeHeap82// ShenandoahHeap83//84class CollectedHeap : public CHeapObj<mtInternal> {85friend class VMStructs;86friend class IsGCActiveMark; // Block structured external access to _is_gc_active8788#ifdef ASSERT89static int _fire_out_of_memory_count;90#endif9192// Used for filler objects (static, but initialized in ctor).93static size_t _filler_array_max_size;9495GCHeapLog* _gc_heap_log;9697// Used in support of ReduceInitialCardMarks; only consulted if COMPILER2 is being used98bool _defer_initial_card_mark;99100protected:101MemRegion _reserved;102BarrierSet* _barrier_set;103bool _is_gc_active;104uint _n_par_threads;105106unsigned int _total_collections; // ... started107unsigned int _total_full_collections; // ... started108NOT_PRODUCT(volatile size_t _promotion_failure_alot_count;)109NOT_PRODUCT(volatile size_t _promotion_failure_alot_gc_number;)110111// Reason for current garbage collection. Should be set to112// a value reflecting no collection between collections.113GCCause::Cause _gc_cause;114GCCause::Cause _gc_lastcause;115PerfStringVariable* _perf_gc_cause;116PerfStringVariable* _perf_gc_lastcause;117118// Constructor119CollectedHeap();120121// Do common initializations that must follow instance construction,122// for example, those needing virtual calls.123// This code could perhaps be moved into initialize() but would124// be slightly more awkward because we want the latter to be a125// pure virtual.126void pre_initialize();127128// Create a new tlab. All TLAB allocations must go through this.129virtual HeapWord* allocate_new_tlab(size_t size);130131// Accumulate statistics on all tlabs.132virtual void accumulate_statistics_all_tlabs();133134// Reinitialize tlabs before resuming mutators.135virtual void resize_all_tlabs();136137// Allocate from the current thread's TLAB, with broken-out slow path.138inline static HeapWord* allocate_from_tlab(KlassHandle klass, Thread* thread, size_t size);139static HeapWord* allocate_from_tlab_slow(KlassHandle klass, Thread* thread, size_t size);140141// Allocate an uninitialized block of the given size, or returns NULL if142// this is impossible.143inline static HeapWord* common_mem_allocate_noinit(KlassHandle klass, size_t size, TRAPS);144145// Like allocate_init, but the block returned by a successful allocation146// is guaranteed initialized to zeros.147inline static HeapWord* common_mem_allocate_init(KlassHandle klass, size_t size, TRAPS);148149// Helper functions for (VM) allocation.150inline static void post_allocation_setup_common(KlassHandle klass, HeapWord* obj);151inline static void post_allocation_setup_no_klass_install(KlassHandle klass,152HeapWord* objPtr);153154inline static void post_allocation_setup_obj(KlassHandle klass, HeapWord* obj, int size);155156inline static void post_allocation_setup_array(KlassHandle klass,157HeapWord* obj, int length);158159// Clears an allocated object.160inline static void init_obj(HeapWord* obj, size_t size);161162// Filler object utilities.163static inline size_t filler_array_hdr_size();164static inline size_t filler_array_min_size();165166DEBUG_ONLY(static void fill_args_check(HeapWord* start, size_t words);)167DEBUG_ONLY(static void zap_filler_array(HeapWord* start, size_t words, bool zap = true);)168169// Fill with a single array; caller must ensure filler_array_min_size() <=170// words <= filler_array_max_size().171static inline void fill_with_array(HeapWord* start, size_t words, bool zap = true);172173// Fill with a single object (either an int array or a java.lang.Object).174static inline void fill_with_object_impl(HeapWord* start, size_t words, bool zap = true);175176virtual void trace_heap(GCWhen::Type when, GCTracer* tracer);177178// Verification functions179virtual void check_for_bad_heap_word_value(HeapWord* addr, size_t size)180PRODUCT_RETURN;181virtual void check_for_non_bad_heap_word_value(HeapWord* addr, size_t size)182PRODUCT_RETURN;183debug_only(static void check_for_valid_allocation_state();)184185public:186enum Name {187Abstract,188SharedHeap,189GenCollectedHeap,190ParallelScavengeHeap,191G1CollectedHeap,192ShenandoahHeap193};194195static inline size_t filler_array_max_size() {196return _filler_array_max_size;197}198199virtual CollectedHeap::Name kind() const { return CollectedHeap::Abstract; }200201/**202* Returns JNI error code JNI_ENOMEM if memory could not be allocated,203* and JNI_OK on success.204*/205virtual jint initialize() = 0;206207// In many heaps, there will be a need to perform some initialization activities208// after the Universe is fully formed, but before general heap allocation is allowed.209// This is the correct place to place such initialization methods.210virtual void post_initialize() = 0;211212// Stop any onging concurrent work and prepare for exit.213virtual void stop() {}214215MemRegion reserved_region() const { return _reserved; }216address base() const { return (address)reserved_region().start(); }217218virtual size_t capacity() const = 0;219virtual size_t used() const = 0;220221// Return "true" if the part of the heap that allocates Java222// objects has reached the maximal committed limit that it can223// reach, without a garbage collection.224virtual bool is_maximal_no_gc() const = 0;225226// Support for java.lang.Runtime.maxMemory(): return the maximum amount of227// memory that the vm could make available for storing 'normal' java objects.228// This is based on the reserved address space, but should not include space229// that the vm uses internally for bookkeeping or temporary storage230// (e.g., in the case of the young gen, one of the survivor231// spaces).232virtual size_t max_capacity() const = 0;233234// Returns "TRUE" if "p" points into the reserved area of the heap.235bool is_in_reserved(const void* p) const {236return _reserved.contains(p);237}238239bool is_in_reserved_or_null(const void* p) const {240return p == NULL || is_in_reserved(p);241}242243// Returns "TRUE" iff "p" points into the committed areas of the heap.244// Since this method can be expensive in general, we restrict its245// use to assertion checking only.246virtual bool is_in(const void* p) const = 0;247248bool is_in_or_null(const void* p) const {249return p == NULL || is_in(p);250}251252bool is_in_place(Metadata** p) {253return !Universe::heap()->is_in(p);254}255bool is_in_place(oop* p) { return Universe::heap()->is_in(p); }256bool is_in_place(narrowOop* p) {257oop o = oopDesc::load_decode_heap_oop_not_null(p);258return Universe::heap()->is_in((const void*)o);259}260261// Let's define some terms: a "closed" subset of a heap is one that262//263// 1) contains all currently-allocated objects, and264//265// 2) is closed under reference: no object in the closed subset266// references one outside the closed subset.267//268// Membership in a heap's closed subset is useful for assertions.269// Clearly, the entire heap is a closed subset, so the default270// implementation is to use "is_in_reserved". But this may not be too271// liberal to perform useful checking. Also, the "is_in" predicate272// defines a closed subset, but may be too expensive, since "is_in"273// verifies that its argument points to an object head. The274// "closed_subset" method allows a heap to define an intermediate275// predicate, allowing more precise checking than "is_in_reserved" at276// lower cost than "is_in."277278// One important case is a heap composed of disjoint contiguous spaces,279// such as the Garbage-First collector. Such heaps have a convenient280// closed subset consisting of the allocated portions of those281// contiguous spaces.282283// Return "TRUE" iff the given pointer points into the heap's defined284// closed subset (which defaults to the entire heap).285virtual bool is_in_closed_subset(const void* p) const {286return is_in_reserved(p);287}288289bool is_in_closed_subset_or_null(const void* p) const {290return p == NULL || is_in_closed_subset(p);291}292293#ifdef ASSERT294// Returns true if "p" is in the part of the295// heap being collected.296virtual bool is_in_partial_collection(const void *p) = 0;297#endif298299// An object is scavengable if its location may move during a scavenge.300// (A scavenge is a GC which is not a full GC.)301virtual bool is_scavengable(const void *p) = 0;302303void set_gc_cause(GCCause::Cause v) {304if (UsePerfData) {305_gc_lastcause = _gc_cause;306_perf_gc_lastcause->set_value(GCCause::to_string(_gc_lastcause));307_perf_gc_cause->set_value(GCCause::to_string(v));308}309_gc_cause = v;310}311GCCause::Cause gc_cause() { return _gc_cause; }312313// Number of threads currently working on GC tasks.314uint n_par_threads() { return _n_par_threads; }315316// May be overridden to set additional parallelism.317virtual void set_par_threads(uint t) { _n_par_threads = t; };318319// General obj/array allocation facilities.320inline static oop obj_allocate(KlassHandle klass, int size, TRAPS);321inline static oop array_allocate(KlassHandle klass, int size, int length, TRAPS);322inline static oop array_allocate_nozero(KlassHandle klass, int size, int length, TRAPS);323324// Raw memory allocation facilities325// The obj and array allocate methods are covers for these methods.326// mem_allocate() should never be327// called to allocate TLABs, only individual objects.328virtual HeapWord* mem_allocate(size_t size,329bool* gc_overhead_limit_was_exceeded) = 0;330331// Utilities for turning raw memory into filler objects.332//333// min_fill_size() is the smallest region that can be filled.334// fill_with_objects() can fill arbitrary-sized regions of the heap using335// multiple objects. fill_with_object() is for regions known to be smaller336// than the largest array of integers; it uses a single object to fill the337// region and has slightly less overhead.338static size_t min_fill_size() {339return size_t(align_object_size(oopDesc::header_size()));340}341342static void fill_with_objects(HeapWord* start, size_t words, bool zap = true);343344static void fill_with_object(HeapWord* start, size_t words, bool zap = true);345static void fill_with_object(MemRegion region, bool zap = true) {346fill_with_object(region.start(), region.word_size(), zap);347}348static void fill_with_object(HeapWord* start, HeapWord* end, bool zap = true) {349fill_with_object(start, pointer_delta(end, start), zap);350}351352// Return the address "addr" aligned by "alignment_in_bytes" if such353// an address is below "end". Return NULL otherwise.354inline static HeapWord* align_allocation_or_fail(HeapWord* addr,355HeapWord* end,356unsigned short alignment_in_bytes);357358// Some heaps may offer a contiguous region for shared non-blocking359// allocation, via inlined code (by exporting the address of the top and360// end fields defining the extent of the contiguous allocation region.)361362// This function returns "true" iff the heap supports this kind of363// allocation. (Default is "no".)364virtual bool supports_inline_contig_alloc() const {365return false;366}367// These functions return the addresses of the fields that define the368// boundaries of the contiguous allocation area. (These fields should be369// physically near to one another.)370virtual HeapWord** top_addr() const {371guarantee(false, "inline contiguous allocation not supported");372return NULL;373}374virtual HeapWord** end_addr() const {375guarantee(false, "inline contiguous allocation not supported");376return NULL;377}378379// Some heaps may be in an unparseable state at certain times between380// collections. This may be necessary for efficient implementation of381// certain allocation-related activities. Calling this function before382// attempting to parse a heap ensures that the heap is in a parsable383// state (provided other concurrent activity does not introduce384// unparsability). It is normally expected, therefore, that this385// method is invoked with the world stopped.386// NOTE: if you override this method, make sure you call387// super::ensure_parsability so that the non-generational388// part of the work gets done. See implementation of389// CollectedHeap::ensure_parsability and, for instance,390// that of GenCollectedHeap::ensure_parsability().391// The argument "retire_tlabs" controls whether existing TLABs392// are merely filled or also retired, thus preventing further393// allocation from them and necessitating allocation of new TLABs.394virtual void ensure_parsability(bool retire_tlabs);395396// Section on thread-local allocation buffers (TLABs)397// If the heap supports thread-local allocation buffers, it should override398// the following methods:399// Returns "true" iff the heap supports thread-local allocation buffers.400// The default is "no".401virtual bool supports_tlab_allocation() const = 0;402403// The amount of space available for thread-local allocation buffers.404virtual size_t tlab_capacity(Thread *thr) const = 0;405406// The amount of used space for thread-local allocation buffers for the given thread.407virtual size_t tlab_used(Thread *thr) const = 0;408409virtual size_t max_tlab_size() const;410411// An estimate of the maximum allocation that could be performed412// for thread-local allocation buffers without triggering any413// collection or expansion activity.414virtual size_t unsafe_max_tlab_alloc(Thread *thr) const {415guarantee(false, "thread-local allocation buffers not supported");416return 0;417}418419// Can a compiler initialize a new object without store barriers?420// This permission only extends from the creation of a new object421// via a TLAB up to the first subsequent safepoint. If such permission422// is granted for this heap type, the compiler promises to call423// defer_store_barrier() below on any slow path allocation of424// a new object for which such initializing store barriers will425// have been elided.426virtual bool can_elide_tlab_store_barriers() const = 0;427428// If a compiler is eliding store barriers for TLAB-allocated objects,429// there is probably a corresponding slow path which can produce430// an object allocated anywhere. The compiler's runtime support431// promises to call this function on such a slow-path-allocated432// object before performing initializations that have elided433// store barriers. Returns new_obj, or maybe a safer copy thereof.434virtual oop new_store_pre_barrier(JavaThread* thread, oop new_obj);435436// Answers whether an initializing store to a new object currently437// allocated at the given address doesn't need a store438// barrier. Returns "true" if it doesn't need an initializing439// store barrier; answers "false" if it does.440virtual bool can_elide_initializing_store_barrier(oop new_obj) = 0;441442// If a compiler is eliding store barriers for TLAB-allocated objects,443// we will be informed of a slow-path allocation by a call444// to new_store_pre_barrier() above. Such a call precedes the445// initialization of the object itself, and no post-store-barriers will446// be issued. Some heap types require that the barrier strictly follows447// the initializing stores. (This is currently implemented by deferring the448// barrier until the next slow-path allocation or gc-related safepoint.)449// This interface answers whether a particular heap type needs the card450// mark to be thus strictly sequenced after the stores.451virtual bool card_mark_must_follow_store() const = 0;452453// If the CollectedHeap was asked to defer a store barrier above,454// this informs it to flush such a deferred store barrier to the455// remembered set.456virtual void flush_deferred_store_barrier(JavaThread* thread);457458// Does this heap support heap inspection (+PrintClassHistogram?)459virtual bool supports_heap_inspection() const = 0;460461// Perform a collection of the heap; intended for use in implementing462// "System.gc". This probably implies as full a collection as the463// "CollectedHeap" supports.464virtual void collect(GCCause::Cause cause) = 0;465466// Perform a full collection467virtual void do_full_collection(bool clear_all_soft_refs) = 0;468469// This interface assumes that it's being called by the470// vm thread. It collects the heap assuming that the471// heap lock is already held and that we are executing in472// the context of the vm thread.473virtual void collect_as_vm_thread(GCCause::Cause cause);474475// Returns the barrier set for this heap476BarrierSet* barrier_set() { return _barrier_set; }477478// Returns "true" iff there is a stop-world GC in progress. (I assume479// that it should answer "false" for the concurrent part of a concurrent480// collector -- dld).481bool is_gc_active() const { return _is_gc_active; }482483// Total number of GC collections (started)484unsigned int total_collections() const { return _total_collections; }485unsigned int total_full_collections() const { return _total_full_collections;}486487// Increment total number of GC collections (started)488// Should be protected but used by PSMarkSweep - cleanup for 1.4.2489void increment_total_collections(bool full = false) {490_total_collections++;491if (full) {492increment_total_full_collections();493}494}495496void increment_total_full_collections() { _total_full_collections++; }497498// Return the AdaptiveSizePolicy for the heap.499virtual AdaptiveSizePolicy* size_policy() = 0;500501// Return the CollectorPolicy for the heap502virtual CollectorPolicy* collector_policy() const = 0;503504void oop_iterate_no_header(OopClosure* cl);505506// Iterate over all the ref-containing fields of all objects, calling507// "cl.do_oop" on each.508virtual void oop_iterate(ExtendedOopClosure* cl) = 0;509510// Iterate over all objects, calling "cl.do_object" on each.511virtual void object_iterate(ObjectClosure* cl) = 0;512513// Similar to object_iterate() except iterates only514// over live objects.515virtual void safe_object_iterate(ObjectClosure* cl) = 0;516517// NOTE! There is no requirement that a collector implement these518// functions.519//520// A CollectedHeap is divided into a dense sequence of "blocks"; that is,521// each address in the (reserved) heap is a member of exactly522// one block. The defining characteristic of a block is that it is523// possible to find its size, and thus to progress forward to the next524// block. (Blocks may be of different sizes.) Thus, blocks may525// represent Java objects, or they might be free blocks in a526// free-list-based heap (or subheap), as long as the two kinds are527// distinguishable and the size of each is determinable.528529// Returns the address of the start of the "block" that contains the530// address "addr". We say "blocks" instead of "object" since some heaps531// may not pack objects densely; a chunk may either be an object or a532// non-object.533virtual HeapWord* block_start(const void* addr) const = 0;534535// Requires "addr" to be the start of a chunk, and returns its size.536// "addr + size" is required to be the start of a new chunk, or the end537// of the active area of the heap.538virtual size_t block_size(const HeapWord* addr) const = 0;539540// Requires "addr" to be the start of a block, and returns "TRUE" iff541// the block is an object.542virtual bool block_is_obj(const HeapWord* addr) const = 0;543544// Returns the longest time (in ms) that has elapsed since the last545// time that any part of the heap was examined by a garbage collection.546virtual jlong millis_since_last_gc() = 0;547548// Perform any cleanup actions necessary before allowing a verification.549virtual void prepare_for_verify() = 0;550551// Generate any dumps preceding or following a full gc552void pre_full_gc_dump(GCTimer* timer);553void post_full_gc_dump(GCTimer* timer);554555VirtualSpaceSummary create_heap_space_summary();556GCHeapSummary create_heap_summary();557558MetaspaceSummary create_metaspace_summary();559560// Print heap information on the given outputStream.561virtual void print_on(outputStream* st) const = 0;562// The default behavior is to call print_on() on tty.563virtual void print() const {564print_on(tty);565}566// Print more detailed heap information on the given567// outputStream. The default behavior is to call print_on(). It is568// up to each subclass to override it and add any additional output569// it needs.570virtual void print_extended_on(outputStream* st) const {571print_on(st);572}573574virtual void print_on_error(outputStream* st) const {575st->print_cr("Heap:");576print_extended_on(st);577st->cr();578579_barrier_set->print_on(st);580}581582// Print all GC threads (other than the VM thread)583// used by this heap.584virtual void print_gc_threads_on(outputStream* st) const = 0;585// The default behavior is to call print_gc_threads_on() on tty.586void print_gc_threads() {587print_gc_threads_on(tty);588}589// Iterator for all GC threads (other than VM thread)590virtual void gc_threads_do(ThreadClosure* tc) const = 0;591592// Print any relevant tracing info that flags imply.593// Default implementation does nothing.594virtual void print_tracing_info() const = 0;595596void print_heap_before_gc();597void print_heap_after_gc();598599// Registering and unregistering an nmethod (compiled code) with the heap.600// Override with specific mechanism for each specialized heap type.601virtual void register_nmethod(nmethod* nm);602virtual void unregister_nmethod(nmethod* nm);603604void trace_heap_before_gc(GCTracer* gc_tracer);605void trace_heap_after_gc(GCTracer* gc_tracer);606607// Heap verification608virtual void verify(bool silent, VerifyOption option) = 0;609610// Shut down all GC workers and other GC related threads.611virtual void shutdown();612613// Accumulate additional statistics from GCLABs.614virtual void accumulate_statistics_all_gclabs();615616// Support for object pinning. This is used by JNI Get*Critical()617// and Release*Critical() family of functions. If supported, the GC618// must guarantee that pinned objects never move.619virtual bool supports_object_pinning() const;620virtual oop pin_object(JavaThread* thread, oop obj);621virtual void unpin_object(JavaThread* thread, oop obj);622623// Non product verification and debugging.624#ifndef PRODUCT625// Support for PromotionFailureALot. Return true if it's time to cause a626// promotion failure. The no-argument version uses627// this->_promotion_failure_alot_count as the counter.628inline bool promotion_should_fail(volatile size_t* count);629inline bool promotion_should_fail();630631// Reset the PromotionFailureALot counters. Should be called at the end of a632// GC in which promotion failure occurred.633inline void reset_promotion_should_fail(volatile size_t* count);634inline void reset_promotion_should_fail();635#endif // #ifndef PRODUCT636637#ifdef ASSERT638static int fired_fake_oom() {639return (CIFireOOMAt > 1 && _fire_out_of_memory_count >= CIFireOOMAt);640}641#endif642643public:644// This is a convenience method that is used in cases where645// the actual number of GC worker threads is not pertinent but646// only whether there more than 0. Use of this method helps647// reduce the occurrence of ParallelGCThreads to uses where the648// actual number may be germane.649static bool use_parallel_gc_threads() { return ParallelGCThreads > 0; }650651// Copy the current allocation context statistics for the specified contexts.652// For each context in contexts, set the corresponding entries in the totals653// and accuracy arrays to the current values held by the statistics. Each654// array should be of length len.655// Returns true if there are more stats available.656virtual bool copy_allocation_context_stats(const jint* contexts,657jlong* totals,658jbyte* accuracy,659jint len) {660return false;661}662663/////////////// Unit tests ///////////////664665NOT_PRODUCT(static void test_is_in();)666};667668// Class to set and reset the GC cause for a CollectedHeap.669670class GCCauseSetter : StackObj {671CollectedHeap* _heap;672GCCause::Cause _previous_cause;673public:674GCCauseSetter(CollectedHeap* heap, GCCause::Cause cause) {675assert(SafepointSynchronize::is_at_safepoint(),676"This method manipulates heap state without locking");677_heap = heap;678_previous_cause = _heap->gc_cause();679_heap->set_gc_cause(cause);680}681682~GCCauseSetter() {683assert(SafepointSynchronize::is_at_safepoint(),684"This method manipulates heap state without locking");685_heap->set_gc_cause(_previous_cause);686}687};688689#endif // SHARE_VM_GC_INTERFACE_COLLECTEDHEAP_HPP690691692