Path: blob/jdk8u272-b10-aarch32-20201026/hotspot/src/share/vm/gc_interface/collectedHeap.hpp
48773 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//83class CollectedHeap : public CHeapObj<mtInternal> {84friend class VMStructs;85friend class IsGCActiveMark; // Block structured external access to _is_gc_active8687#ifdef ASSERT88static int _fire_out_of_memory_count;89#endif9091// Used for filler objects (static, but initialized in ctor).92static size_t _filler_array_max_size;9394GCHeapLog* _gc_heap_log;9596// Used in support of ReduceInitialCardMarks; only consulted if COMPILER2 is being used97bool _defer_initial_card_mark;9899protected:100MemRegion _reserved;101BarrierSet* _barrier_set;102bool _is_gc_active;103uint _n_par_threads;104105unsigned int _total_collections; // ... started106unsigned int _total_full_collections; // ... started107NOT_PRODUCT(volatile size_t _promotion_failure_alot_count;)108NOT_PRODUCT(volatile size_t _promotion_failure_alot_gc_number;)109110// Reason for current garbage collection. Should be set to111// a value reflecting no collection between collections.112GCCause::Cause _gc_cause;113GCCause::Cause _gc_lastcause;114PerfStringVariable* _perf_gc_cause;115PerfStringVariable* _perf_gc_lastcause;116117// Constructor118CollectedHeap();119120// Do common initializations that must follow instance construction,121// for example, those needing virtual calls.122// This code could perhaps be moved into initialize() but would123// be slightly more awkward because we want the latter to be a124// pure virtual.125void pre_initialize();126127// Create a new tlab. All TLAB allocations must go through this.128virtual HeapWord* allocate_new_tlab(size_t size);129130// Accumulate statistics on all tlabs.131virtual void accumulate_statistics_all_tlabs();132133// Reinitialize tlabs before resuming mutators.134virtual void resize_all_tlabs();135136// Allocate from the current thread's TLAB, with broken-out slow path.137inline static HeapWord* allocate_from_tlab(KlassHandle klass, Thread* thread, size_t size);138static HeapWord* allocate_from_tlab_slow(KlassHandle klass, Thread* thread, size_t size);139140// Allocate an uninitialized block of the given size, or returns NULL if141// this is impossible.142inline static HeapWord* common_mem_allocate_noinit(KlassHandle klass, size_t size, TRAPS);143144// Like allocate_init, but the block returned by a successful allocation145// is guaranteed initialized to zeros.146inline static HeapWord* common_mem_allocate_init(KlassHandle klass, size_t size, TRAPS);147148// Helper functions for (VM) allocation.149inline static void post_allocation_setup_common(KlassHandle klass, HeapWord* obj);150inline static void post_allocation_setup_no_klass_install(KlassHandle klass,151HeapWord* objPtr);152153inline static void post_allocation_setup_obj(KlassHandle klass, HeapWord* obj, int size);154155inline static void post_allocation_setup_array(KlassHandle klass,156HeapWord* obj, int length);157158// Clears an allocated object.159inline static void init_obj(HeapWord* obj, size_t size);160161// Filler object utilities.162static inline size_t filler_array_hdr_size();163static inline size_t filler_array_min_size();164165DEBUG_ONLY(static void fill_args_check(HeapWord* start, size_t words);)166DEBUG_ONLY(static void zap_filler_array(HeapWord* start, size_t words, bool zap = true);)167168// Fill with a single array; caller must ensure filler_array_min_size() <=169// words <= filler_array_max_size().170static inline void fill_with_array(HeapWord* start, size_t words, bool zap = true);171172// Fill with a single object (either an int array or a java.lang.Object).173static inline void fill_with_object_impl(HeapWord* start, size_t words, bool zap = true);174175virtual void trace_heap(GCWhen::Type when, GCTracer* tracer);176177// Verification functions178virtual void check_for_bad_heap_word_value(HeapWord* addr, size_t size)179PRODUCT_RETURN;180virtual void check_for_non_bad_heap_word_value(HeapWord* addr, size_t size)181PRODUCT_RETURN;182debug_only(static void check_for_valid_allocation_state();)183184public:185enum Name {186Abstract,187SharedHeap,188GenCollectedHeap,189ParallelScavengeHeap,190G1CollectedHeap191};192193static inline size_t filler_array_max_size() {194return _filler_array_max_size;195}196197virtual CollectedHeap::Name kind() const { return CollectedHeap::Abstract; }198199/**200* Returns JNI error code JNI_ENOMEM if memory could not be allocated,201* and JNI_OK on success.202*/203virtual jint initialize() = 0;204205// In many heaps, there will be a need to perform some initialization activities206// after the Universe is fully formed, but before general heap allocation is allowed.207// This is the correct place to place such initialization methods.208virtual void post_initialize() = 0;209210// Stop any onging concurrent work and prepare for exit.211virtual void stop() {}212213MemRegion reserved_region() const { return _reserved; }214address base() const { return (address)reserved_region().start(); }215216virtual size_t capacity() const = 0;217virtual size_t used() const = 0;218219// Return "true" if the part of the heap that allocates Java220// objects has reached the maximal committed limit that it can221// reach, without a garbage collection.222virtual bool is_maximal_no_gc() const = 0;223224// Support for java.lang.Runtime.maxMemory(): return the maximum amount of225// memory that the vm could make available for storing 'normal' java objects.226// This is based on the reserved address space, but should not include space227// that the vm uses internally for bookkeeping or temporary storage228// (e.g., in the case of the young gen, one of the survivor229// spaces).230virtual size_t max_capacity() const = 0;231232// Returns "TRUE" if "p" points into the reserved area of the heap.233bool is_in_reserved(const void* p) const {234return _reserved.contains(p);235}236237bool is_in_reserved_or_null(const void* p) const {238return p == NULL || is_in_reserved(p);239}240241// Returns "TRUE" iff "p" points into the committed areas of the heap.242// Since this method can be expensive in general, we restrict its243// use to assertion checking only.244virtual bool is_in(const void* p) const = 0;245246bool is_in_or_null(const void* p) const {247return p == NULL || is_in(p);248}249250bool is_in_place(Metadata** p) {251return !Universe::heap()->is_in(p);252}253bool is_in_place(oop* p) { return Universe::heap()->is_in(p); }254bool is_in_place(narrowOop* p) {255oop o = oopDesc::load_decode_heap_oop_not_null(p);256return Universe::heap()->is_in((const void*)o);257}258259// Let's define some terms: a "closed" subset of a heap is one that260//261// 1) contains all currently-allocated objects, and262//263// 2) is closed under reference: no object in the closed subset264// references one outside the closed subset.265//266// Membership in a heap's closed subset is useful for assertions.267// Clearly, the entire heap is a closed subset, so the default268// implementation is to use "is_in_reserved". But this may not be too269// liberal to perform useful checking. Also, the "is_in" predicate270// defines a closed subset, but may be too expensive, since "is_in"271// verifies that its argument points to an object head. The272// "closed_subset" method allows a heap to define an intermediate273// predicate, allowing more precise checking than "is_in_reserved" at274// lower cost than "is_in."275276// One important case is a heap composed of disjoint contiguous spaces,277// such as the Garbage-First collector. Such heaps have a convenient278// closed subset consisting of the allocated portions of those279// contiguous spaces.280281// Return "TRUE" iff the given pointer points into the heap's defined282// closed subset (which defaults to the entire heap).283virtual bool is_in_closed_subset(const void* p) const {284return is_in_reserved(p);285}286287bool is_in_closed_subset_or_null(const void* p) const {288return p == NULL || is_in_closed_subset(p);289}290291#ifdef ASSERT292// Returns true if "p" is in the part of the293// heap being collected.294virtual bool is_in_partial_collection(const void *p) = 0;295#endif296297// An object is scavengable if its location may move during a scavenge.298// (A scavenge is a GC which is not a full GC.)299virtual bool is_scavengable(const void *p) = 0;300301void set_gc_cause(GCCause::Cause v) {302if (UsePerfData) {303_gc_lastcause = _gc_cause;304_perf_gc_lastcause->set_value(GCCause::to_string(_gc_lastcause));305_perf_gc_cause->set_value(GCCause::to_string(v));306}307_gc_cause = v;308}309GCCause::Cause gc_cause() { return _gc_cause; }310311// Number of threads currently working on GC tasks.312uint n_par_threads() { return _n_par_threads; }313314// May be overridden to set additional parallelism.315virtual void set_par_threads(uint t) { _n_par_threads = t; };316317// General obj/array allocation facilities.318inline static oop obj_allocate(KlassHandle klass, int size, TRAPS);319inline static oop array_allocate(KlassHandle klass, int size, int length, TRAPS);320inline static oop array_allocate_nozero(KlassHandle klass, int size, int length, TRAPS);321322// Raw memory allocation facilities323// The obj and array allocate methods are covers for these methods.324// mem_allocate() should never be325// called to allocate TLABs, only individual objects.326virtual HeapWord* mem_allocate(size_t size,327bool* gc_overhead_limit_was_exceeded) = 0;328329// Utilities for turning raw memory into filler objects.330//331// min_fill_size() is the smallest region that can be filled.332// fill_with_objects() can fill arbitrary-sized regions of the heap using333// multiple objects. fill_with_object() is for regions known to be smaller334// than the largest array of integers; it uses a single object to fill the335// region and has slightly less overhead.336static size_t min_fill_size() {337return size_t(align_object_size(oopDesc::header_size()));338}339340static void fill_with_objects(HeapWord* start, size_t words, bool zap = true);341342static void fill_with_object(HeapWord* start, size_t words, bool zap = true);343static void fill_with_object(MemRegion region, bool zap = true) {344fill_with_object(region.start(), region.word_size(), zap);345}346static void fill_with_object(HeapWord* start, HeapWord* end, bool zap = true) {347fill_with_object(start, pointer_delta(end, start), zap);348}349350// Return the address "addr" aligned by "alignment_in_bytes" if such351// an address is below "end". Return NULL otherwise.352inline static HeapWord* align_allocation_or_fail(HeapWord* addr,353HeapWord* end,354unsigned short alignment_in_bytes);355356// Some heaps may offer a contiguous region for shared non-blocking357// allocation, via inlined code (by exporting the address of the top and358// end fields defining the extent of the contiguous allocation region.)359360// This function returns "true" iff the heap supports this kind of361// allocation. (Default is "no".)362virtual bool supports_inline_contig_alloc() const {363return false;364}365// These functions return the addresses of the fields that define the366// boundaries of the contiguous allocation area. (These fields should be367// physically near to one another.)368virtual HeapWord** top_addr() const {369guarantee(false, "inline contiguous allocation not supported");370return NULL;371}372virtual HeapWord** end_addr() const {373guarantee(false, "inline contiguous allocation not supported");374return NULL;375}376377// Some heaps may be in an unparseable state at certain times between378// collections. This may be necessary for efficient implementation of379// certain allocation-related activities. Calling this function before380// attempting to parse a heap ensures that the heap is in a parsable381// state (provided other concurrent activity does not introduce382// unparsability). It is normally expected, therefore, that this383// method is invoked with the world stopped.384// NOTE: if you override this method, make sure you call385// super::ensure_parsability so that the non-generational386// part of the work gets done. See implementation of387// CollectedHeap::ensure_parsability and, for instance,388// that of GenCollectedHeap::ensure_parsability().389// The argument "retire_tlabs" controls whether existing TLABs390// are merely filled or also retired, thus preventing further391// allocation from them and necessitating allocation of new TLABs.392virtual void ensure_parsability(bool retire_tlabs);393394// Section on thread-local allocation buffers (TLABs)395// If the heap supports thread-local allocation buffers, it should override396// the following methods:397// Returns "true" iff the heap supports thread-local allocation buffers.398// The default is "no".399virtual bool supports_tlab_allocation() const = 0;400401// The amount of space available for thread-local allocation buffers.402virtual size_t tlab_capacity(Thread *thr) const = 0;403404// The amount of used space for thread-local allocation buffers for the given thread.405virtual size_t tlab_used(Thread *thr) const = 0;406407virtual size_t max_tlab_size() const;408409// An estimate of the maximum allocation that could be performed410// for thread-local allocation buffers without triggering any411// collection or expansion activity.412virtual size_t unsafe_max_tlab_alloc(Thread *thr) const {413guarantee(false, "thread-local allocation buffers not supported");414return 0;415}416417// Can a compiler initialize a new object without store barriers?418// This permission only extends from the creation of a new object419// via a TLAB up to the first subsequent safepoint. If such permission420// is granted for this heap type, the compiler promises to call421// defer_store_barrier() below on any slow path allocation of422// a new object for which such initializing store barriers will423// have been elided.424virtual bool can_elide_tlab_store_barriers() const = 0;425426// If a compiler is eliding store barriers for TLAB-allocated objects,427// there is probably a corresponding slow path which can produce428// an object allocated anywhere. The compiler's runtime support429// promises to call this function on such a slow-path-allocated430// object before performing initializations that have elided431// store barriers. Returns new_obj, or maybe a safer copy thereof.432virtual oop new_store_pre_barrier(JavaThread* thread, oop new_obj);433434// Answers whether an initializing store to a new object currently435// allocated at the given address doesn't need a store436// barrier. Returns "true" if it doesn't need an initializing437// store barrier; answers "false" if it does.438virtual bool can_elide_initializing_store_barrier(oop new_obj) = 0;439440// If a compiler is eliding store barriers for TLAB-allocated objects,441// we will be informed of a slow-path allocation by a call442// to new_store_pre_barrier() above. Such a call precedes the443// initialization of the object itself, and no post-store-barriers will444// be issued. Some heap types require that the barrier strictly follows445// the initializing stores. (This is currently implemented by deferring the446// barrier until the next slow-path allocation or gc-related safepoint.)447// This interface answers whether a particular heap type needs the card448// mark to be thus strictly sequenced after the stores.449virtual bool card_mark_must_follow_store() const = 0;450451// If the CollectedHeap was asked to defer a store barrier above,452// this informs it to flush such a deferred store barrier to the453// remembered set.454virtual void flush_deferred_store_barrier(JavaThread* thread);455456// Does this heap support heap inspection (+PrintClassHistogram?)457virtual bool supports_heap_inspection() const = 0;458459// Perform a collection of the heap; intended for use in implementing460// "System.gc". This probably implies as full a collection as the461// "CollectedHeap" supports.462virtual void collect(GCCause::Cause cause) = 0;463464// Perform a full collection465virtual void do_full_collection(bool clear_all_soft_refs) = 0;466467// This interface assumes that it's being called by the468// vm thread. It collects the heap assuming that the469// heap lock is already held and that we are executing in470// the context of the vm thread.471virtual void collect_as_vm_thread(GCCause::Cause cause);472473// Returns the barrier set for this heap474BarrierSet* barrier_set() { return _barrier_set; }475476// Returns "true" iff there is a stop-world GC in progress. (I assume477// that it should answer "false" for the concurrent part of a concurrent478// collector -- dld).479bool is_gc_active() const { return _is_gc_active; }480481// Total number of GC collections (started)482unsigned int total_collections() const { return _total_collections; }483unsigned int total_full_collections() const { return _total_full_collections;}484485// Increment total number of GC collections (started)486// Should be protected but used by PSMarkSweep - cleanup for 1.4.2487void increment_total_collections(bool full = false) {488_total_collections++;489if (full) {490increment_total_full_collections();491}492}493494void increment_total_full_collections() { _total_full_collections++; }495496// Return the AdaptiveSizePolicy for the heap.497virtual AdaptiveSizePolicy* size_policy() = 0;498499// Return the CollectorPolicy for the heap500virtual CollectorPolicy* collector_policy() const = 0;501502void oop_iterate_no_header(OopClosure* cl);503504// Iterate over all the ref-containing fields of all objects, calling505// "cl.do_oop" on each.506virtual void oop_iterate(ExtendedOopClosure* cl) = 0;507508// Iterate over all objects, calling "cl.do_object" on each.509virtual void object_iterate(ObjectClosure* cl) = 0;510511// Similar to object_iterate() except iterates only512// over live objects.513virtual void safe_object_iterate(ObjectClosure* cl) = 0;514515// NOTE! There is no requirement that a collector implement these516// functions.517//518// A CollectedHeap is divided into a dense sequence of "blocks"; that is,519// each address in the (reserved) heap is a member of exactly520// one block. The defining characteristic of a block is that it is521// possible to find its size, and thus to progress forward to the next522// block. (Blocks may be of different sizes.) Thus, blocks may523// represent Java objects, or they might be free blocks in a524// free-list-based heap (or subheap), as long as the two kinds are525// distinguishable and the size of each is determinable.526527// Returns the address of the start of the "block" that contains the528// address "addr". We say "blocks" instead of "object" since some heaps529// may not pack objects densely; a chunk may either be an object or a530// non-object.531virtual HeapWord* block_start(const void* addr) const = 0;532533// Requires "addr" to be the start of a chunk, and returns its size.534// "addr + size" is required to be the start of a new chunk, or the end535// of the active area of the heap.536virtual size_t block_size(const HeapWord* addr) const = 0;537538// Requires "addr" to be the start of a block, and returns "TRUE" iff539// the block is an object.540virtual bool block_is_obj(const HeapWord* addr) const = 0;541542// Returns the longest time (in ms) that has elapsed since the last543// time that any part of the heap was examined by a garbage collection.544virtual jlong millis_since_last_gc() = 0;545546// Perform any cleanup actions necessary before allowing a verification.547virtual void prepare_for_verify() = 0;548549// Generate any dumps preceding or following a full gc550void pre_full_gc_dump(GCTimer* timer);551void post_full_gc_dump(GCTimer* timer);552553VirtualSpaceSummary create_heap_space_summary();554GCHeapSummary create_heap_summary();555556MetaspaceSummary create_metaspace_summary();557558// Print heap information on the given outputStream.559virtual void print_on(outputStream* st) const = 0;560// The default behavior is to call print_on() on tty.561virtual void print() const {562print_on(tty);563}564// Print more detailed heap information on the given565// outputStream. The default behavior is to call print_on(). It is566// up to each subclass to override it and add any additional output567// it needs.568virtual void print_extended_on(outputStream* st) const {569print_on(st);570}571572virtual void print_on_error(outputStream* st) const {573st->print_cr("Heap:");574print_extended_on(st);575st->cr();576577_barrier_set->print_on(st);578}579580// Print all GC threads (other than the VM thread)581// used by this heap.582virtual void print_gc_threads_on(outputStream* st) const = 0;583// The default behavior is to call print_gc_threads_on() on tty.584void print_gc_threads() {585print_gc_threads_on(tty);586}587// Iterator for all GC threads (other than VM thread)588virtual void gc_threads_do(ThreadClosure* tc) const = 0;589590// Print any relevant tracing info that flags imply.591// Default implementation does nothing.592virtual void print_tracing_info() const = 0;593594void print_heap_before_gc();595void print_heap_after_gc();596597// Registering and unregistering an nmethod (compiled code) with the heap.598// Override with specific mechanism for each specialized heap type.599virtual void register_nmethod(nmethod* nm);600virtual void unregister_nmethod(nmethod* nm);601602void trace_heap_before_gc(GCTracer* gc_tracer);603void trace_heap_after_gc(GCTracer* gc_tracer);604605// Heap verification606virtual void verify(bool silent, VerifyOption option) = 0;607608// Non product verification and debugging.609#ifndef PRODUCT610// Support for PromotionFailureALot. Return true if it's time to cause a611// promotion failure. The no-argument version uses612// this->_promotion_failure_alot_count as the counter.613inline bool promotion_should_fail(volatile size_t* count);614inline bool promotion_should_fail();615616// Reset the PromotionFailureALot counters. Should be called at the end of a617// GC in which promotion failure occurred.618inline void reset_promotion_should_fail(volatile size_t* count);619inline void reset_promotion_should_fail();620#endif // #ifndef PRODUCT621622#ifdef ASSERT623static int fired_fake_oom() {624return (CIFireOOMAt > 1 && _fire_out_of_memory_count >= CIFireOOMAt);625}626#endif627628public:629// This is a convenience method that is used in cases where630// the actual number of GC worker threads is not pertinent but631// only whether there more than 0. Use of this method helps632// reduce the occurrence of ParallelGCThreads to uses where the633// actual number may be germane.634static bool use_parallel_gc_threads() { return ParallelGCThreads > 0; }635636// Copy the current allocation context statistics for the specified contexts.637// For each context in contexts, set the corresponding entries in the totals638// and accuracy arrays to the current values held by the statistics. Each639// array should be of length len.640// Returns true if there are more stats available.641virtual bool copy_allocation_context_stats(const jint* contexts,642jlong* totals,643jbyte* accuracy,644jint len) {645return false;646}647648/////////////// Unit tests ///////////////649650NOT_PRODUCT(static void test_is_in();)651};652653// Class to set and reset the GC cause for a CollectedHeap.654655class GCCauseSetter : StackObj {656CollectedHeap* _heap;657GCCause::Cause _previous_cause;658public:659GCCauseSetter(CollectedHeap* heap, GCCause::Cause cause) {660assert(SafepointSynchronize::is_at_safepoint(),661"This method manipulates heap state without locking");662_heap = heap;663_previous_cause = _heap->gc_cause();664_heap->set_gc_cause(cause);665}666667~GCCauseSetter() {668assert(SafepointSynchronize::is_at_safepoint(),669"This method manipulates heap state without locking");670_heap->set_gc_cause(_previous_cause);671}672};673674#endif // SHARE_VM_GC_INTERFACE_COLLECTEDHEAP_HPP675676677