1 /*
  2  * Copyright (c) 2001, 2026, Oracle and/or its affiliates. All rights reserved.
  3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4  *
  5  * This code is free software; you can redistribute it and/or modify it
  6  * under the terms of the GNU General Public License version 2 only, as
  7  * published by the Free Software Foundation.
  8  *
  9  * This code is distributed in the hope that it will be useful, but WITHOUT
 10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 12  * version 2 for more details (a copy is included in the LICENSE file that
 13  * accompanied this code).
 14  *
 15  * You should have received a copy of the GNU General Public License version
 16  * 2 along with this work; if not, write to the Free Software Foundation,
 17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 18  *
 19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 20  * or visit www.oracle.com if you need additional information or have any
 21  * questions.
 22  *
 23  */
 24 
 25 #ifndef SHARE_GC_SHARED_COLLECTEDHEAP_HPP
 26 #define SHARE_GC_SHARED_COLLECTEDHEAP_HPP
 27 
 28 #include "gc/shared/gcCause.hpp"
 29 #include "gc/shared/gcWhen.hpp"
 30 #include "gc/shared/verifyOption.hpp"
 31 #include "memory/allocation.hpp"
 32 #include "memory/metaspace.hpp"
 33 #include "memory/universe.hpp"
 34 #include "oops/stackChunkOop.hpp"
 35 #include "runtime/handles.hpp"
 36 #include "runtime/perfDataTypes.hpp"
 37 #include "runtime/safepoint.hpp"
 38 #include "services/cpuTimeUsage.hpp"
 39 #include "services/memoryUsage.hpp"
 40 #include "utilities/debug.hpp"
 41 #include "utilities/formatBuffer.hpp"
 42 #include "utilities/growableArray.hpp"
 43 
 44 // A "CollectedHeap" is an implementation of a java heap for HotSpot.  This
 45 // is an abstract class: there may be many different kinds of heaps.  This
 46 // class defines the functions that a heap must implement, and contains
 47 // infrastructure common to all heaps.
 48 
 49 class GCHeapLog;
 50 class GCHeapSummary;
 51 class GCMemoryManager;
 52 class GCMetaspaceLog;
 53 class GCTimer;
 54 class GCTracer;
 55 class MemoryPool;
 56 class MetaspaceSummary;
 57 class ReservedHeapSpace;
 58 class Thread;
 59 class ThreadClosure;
 60 class VirtualSpaceSummary;
 61 class WorkerThreads;
 62 class nmethod;
 63 
 64 class ParallelObjectIteratorImpl : public CHeapObj<mtGC> {
 65 public:
 66   virtual ~ParallelObjectIteratorImpl() {}
 67   virtual void object_iterate(ObjectClosure* cl, uint worker_id) = 0;
 68 };
 69 
 70 // User facing parallel object iterator. This is a StackObj, which ensures that
 71 // the _impl is allocated and deleted in the scope of this object. This ensures
 72 // the life cycle of the implementation is as required by ThreadsListHandle,
 73 // which is sometimes used by the root iterators.
 74 class ParallelObjectIterator : public StackObj {
 75   ParallelObjectIteratorImpl* _impl;
 76 
 77 public:
 78   ParallelObjectIterator(uint thread_num);
 79   ~ParallelObjectIterator();
 80   void object_iterate(ObjectClosure* cl, uint worker_id);
 81 };
 82 
 83 //
 84 // CollectedHeap
 85 //   SerialHeap
 86 //   G1CollectedHeap
 87 //   ParallelScavengeHeap
 88 //   ShenandoahHeap
 89 //   ZCollectedHeap
 90 //
 91 class CollectedHeap : public CHeapObj<mtGC> {
 92   friend class CPUTimeUsage::GC;
 93   friend class VMStructs;
 94   friend class JVMCIVMStructs;
 95   friend class IsSTWGCActiveMark; // Block structured external access to _is_stw_gc_active
 96   friend class MemAllocator;
 97 
 98  private:
 99   static bool _is_shutting_down;
100 
101   GCHeapLog*      _heap_log;
102   GCMetaspaceLog* _metaspace_log;
103 
104   // Historic gc information
105   size_t _capacity_at_last_gc;
106   size_t _used_at_last_gc;
107 
108   // First, set it to java_lang_Object.
109   // Then, set it to FillerObject after the FillerObject_klass loading is complete.
110   static Klass* _filler_object_klass;
111 
112  protected:
113   // Not used by all GCs
114   MemRegion _reserved;
115 
116   bool _is_stw_gc_active;
117 
118   // (Minimum) Alignment reserve for TLABs and PLABs.
119   static size_t _lab_alignment_reserve;
120   // Used for filler objects (static, but initialized in ctor).
121   static size_t _filler_array_max_size;
122 
123   static size_t _stack_chunk_max_size; // 0 for no limit
124 
125   // Last time the whole heap has been examined in support of RMI
126   // MaxObjectInspectionAge.
127   // This timestamp must be monotonically non-decreasing to avoid
128   // time-warp warnings.
129   jlong _last_whole_heap_examined_time_ns;
130 
131   unsigned int _total_collections;          // ... started
132   unsigned int _total_full_collections;     // ... started
133   NOT_PRODUCT(volatile size_t _promotion_failure_alot_count;)
134   NOT_PRODUCT(volatile size_t _promotion_failure_alot_gc_number;)
135 
136   jlong _vmthread_cpu_time;
137 
138   // Reason for current garbage collection.  Should be set to
139   // a value reflecting no collection between collections.
140   GCCause::Cause _gc_cause;
141   GCCause::Cause _gc_lastcause;
142   PerfStringVariable* _perf_gc_cause;
143   PerfStringVariable* _perf_gc_lastcause;
144 
145   // Constructor
146   CollectedHeap();
147 
148   // Create a new tlab. All TLAB allocations must go through this.
149   // To allow more flexible TLAB allocations min_size specifies
150   // the minimum size needed, while requested_size is the requested
151   // size based on ergonomics. The actually allocated size will be
152   // returned in actual_size.
153   virtual HeapWord* allocate_new_tlab(size_t min_size,
154                                       size_t requested_size,
155                                       size_t* actual_size) = 0;
156 
157   // Reinitialize tlabs before resuming mutators.
158   virtual void resize_all_tlabs();
159 
160   // Raw memory allocation facilities
161   // The obj and array allocate methods are covers for these methods.
162   // mem_allocate() should never be
163   // called to allocate TLABs, only individual objects.
164   virtual HeapWord* mem_allocate(size_t size) = 0;
165 
166   // Filler object utilities.
167   static inline size_t filler_array_hdr_size();
168 
169   static size_t filler_array_min_size();
170 
171 protected:
172   static inline void zap_filler_array_with(HeapWord* start, size_t words, juint value);
173   DEBUG_ONLY(static void zap_filler_array(HeapWord* start, size_t words, bool zap = true);)
174 
175   // Fill with a single array; caller must ensure filler_array_min_size() <=
176   // words <= filler_array_max_size().
177   static inline void fill_with_array(HeapWord* start, size_t words, bool zap = true);
178 
179   // Fill with a single object (either an int array or a java.lang.Object).
180   static inline void fill_with_object_impl(HeapWord* start, size_t words, bool zap = true);
181 
182   virtual void trace_heap(GCWhen::Type when, const GCTracer* tracer);
183 
184   // Verification functions
185   DEBUG_ONLY(static void check_for_valid_allocation_state();)
186 
187  public:
188   enum Name {
189     None,
190     Serial,
191     Parallel,
192     G1,
193     Epsilon,
194     Z,
195     Shenandoah
196   };
197 
198  protected:
199   // Get a pointer to the derived heap object.  Used to implement
200   // derived class heap() functions rather than being called directly.
201   template<typename T>
202   static T* named_heap(Name kind) {
203     CollectedHeap* heap = Universe::heap();
204     assert(heap != nullptr, "Uninitialized heap");
205     assert(kind == heap->kind(), "Heap kind %u should be %u",
206            static_cast<uint>(heap->kind()), static_cast<uint>(kind));
207     return static_cast<T*>(heap);
208   }
209 
210   // Print any relevant tracing info that flags imply.
211   // Default implementation does nothing.
212   virtual void print_tracing_info() const = 0;
213 
214  public:
215   // Stop any onging concurrent work and prepare for exit.
216   virtual void stop() = 0;
217 
218   static inline size_t filler_array_max_size() {
219     return _filler_array_max_size;
220   }
221 
222   static inline size_t stack_chunk_max_size() {
223     return _stack_chunk_max_size;
224   }
225 
226   static inline Klass* filler_object_klass() {
227     return _filler_object_klass;
228   }
229 
230   static inline void set_filler_object_klass(Klass* k) {
231     _filler_object_klass = k;
232   }
233 
234   virtual Name kind() const = 0;
235 
236   virtual const char* name() const = 0;
237 
238   /**
239    * Returns JNI error code JNI_ENOMEM if memory could not be allocated,
240    * and JNI_OK on success.
241    */
242   virtual jint initialize() = 0;
243 
244   // Initialize serviceability support. This should prepare the implementation
245   // for accepting serviceability-related calls, like memory_managers(), memory_pools().
246   virtual void initialize_serviceability() = 0;
247 
248   // In many heaps, there will be a need to perform some initialization activities
249   // after the Universe is fully formed, but before general heap allocation is allowed.
250   // This is the correct place to place such initialization methods.
251   virtual void post_initialize();
252 
253   static bool is_shutting_down();
254 
255   void initiate_shutdown();
256 
257   // Stop and resume concurrent GC threads interfering with safepoint operations
258   virtual void safepoint_synchronize_begin() {}
259   virtual void safepoint_synchronize_end() {}
260 
261   void add_vmthread_cpu_time(jlong time);
262 
263   void initialize_reserved_region(const ReservedHeapSpace& rs);
264 
265   virtual size_t capacity() const = 0;
266   virtual size_t used() const = 0;
267 
268   // Returns unused capacity.
269   virtual size_t unused() const;
270 
271   // Historic gc information
272   size_t free_at_last_gc() const { return _capacity_at_last_gc - _used_at_last_gc; }
273   size_t used_at_last_gc() const { return _used_at_last_gc; }
274   void update_capacity_and_used_at_gc();
275 
276   // Support for java.lang.Runtime.maxMemory():  return the maximum amount of
277   // memory that the vm could make available for storing 'normal' java objects.
278   // This is based on the reserved address space, but should not include space
279   // that the vm uses internally for bookkeeping or temporary storage
280   // (e.g., in the case of the young gen, one of the survivor
281   // spaces).
282   virtual size_t max_capacity() const = 0;
283 
284   // Returns "TRUE" iff "p" points into the committed areas of the heap.
285   // This method can be expensive so avoid using it in performance critical
286   // code.
287   virtual bool is_in(const void* p) const = 0;
288 
289   DEBUG_ONLY(bool is_in_or_null(const void* p) const { return p == nullptr || is_in(p); })
290 
291   void set_gc_cause(GCCause::Cause v);
292   GCCause::Cause gc_cause() const { return _gc_cause; }
293 
294   oop obj_allocate(Klass* klass, size_t size, TRAPS);
295   virtual oop array_allocate(Klass* klass, size_t size, int length, bool do_zero, TRAPS);
296   oop class_allocate(Klass* klass, size_t size, size_t base_size, TRAPS);
297 
298   // Utilities for turning raw memory into filler objects.
299   //
300   // min_fill_size() is the smallest region that can be filled.
301   // fill_with_objects() can fill arbitrary-sized regions of the heap using
302   // multiple objects.  fill_with_object() is for regions known to be smaller
303   // than the largest array of integers; it uses a single object to fill the
304   // region and has slightly less overhead.
305   static size_t min_fill_size() {
306     return size_t(align_object_size(oopDesc::header_size()));
307   }
308 
309   static void fill_with_objects(HeapWord* start, size_t words, bool zap = true);
310 
311   static void fill_with_object(HeapWord* start, size_t words, bool zap = true);
312   static void fill_with_object(HeapWord* start, HeapWord* end, bool zap = true) {
313     fill_with_object(start, pointer_delta(end, start), zap);
314   }
315 
316   inline static bool is_filler_object(oop obj);
317 
318   virtual void fill_with_dummy_object(HeapWord* start, HeapWord* end, bool zap);
319   static size_t min_dummy_object_size() {
320     return oopDesc::header_size();
321   }
322 
323   static size_t lab_alignment_reserve() {
324     assert(_lab_alignment_reserve != SIZE_MAX, "uninitialized");
325     return _lab_alignment_reserve;
326   }
327 
328   // Some heaps may be in an unparseable state at certain times between
329   // collections. This may be necessary for efficient implementation of
330   // certain allocation-related activities. Calling this function before
331   // attempting to parse a heap ensures that the heap is in a parsable
332   // state (provided other concurrent activity does not introduce
333   // unparsability). It is normally expected, therefore, that this
334   // method is invoked with the world stopped.
335   // NOTE: if you override this method, make sure you call
336   // super::ensure_parsability so that the non-generational
337   // part of the work gets done. See implementation of
338   // CollectedHeap::ensure_parsability and, for instance,
339   // that of ParallelScavengeHeap::ensure_parsability().
340   // The argument "retire_tlabs" controls whether existing TLABs
341   // are merely filled or also retired, thus preventing further
342   // allocation from them and necessitating allocation of new TLABs.
343   virtual void ensure_parsability(bool retire_tlabs);
344 
345   // The amount of space available for thread-local allocation buffers.
346   virtual size_t tlab_capacity() const = 0;
347 
348   // The amount of space used for thread-local allocation buffers.
349   virtual size_t tlab_used() const = 0;
350 
351   virtual size_t max_tlab_size() const;
352 
353   // An estimate of the maximum allocation that could be performed
354   // for thread-local allocation buffers without triggering any
355   // collection or expansion activity.
356   virtual size_t unsafe_max_tlab_alloc() const = 0;
357 
358   // Perform a collection of the heap of a type depending on the given cause.
359   virtual void collect(GCCause::Cause cause) = 0;
360 
361   // Perform a full collection
362   virtual void do_full_collection(bool clear_all_soft_refs) = 0;
363 
364   // This interface assumes that it's being called by the
365   // vm thread. It collects the heap assuming that the
366   // heap lock is already held and that we are executing in
367   // the context of the vm thread.
368   virtual void collect_as_vm_thread(GCCause::Cause cause);
369 
370   virtual MetaWord* satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,
371                                                        size_t size,
372                                                        Metaspace::MetadataType mdtype);
373 
374   // Return true, if accesses to the object would require barriers.
375   // This is used by continuations to copy chunks of a thread stack into StackChunk object or out of a StackChunk
376   // object back into the thread stack. These chunks may contain references to objects. It is crucial that
377   // the GC does not attempt to traverse the object while we modify it, because its structure (oopmap) is changed
378   // when stack chunks are stored into it.
379   // StackChunk objects may be reused, the GC must not assume that a StackChunk object is always a freshly
380   // allocated object.
381   virtual bool requires_barriers(stackChunkOop obj) const = 0;
382 
383   // Returns "true" iff there is a stop-world GC in progress.
384   bool is_stw_gc_active() const { return _is_stw_gc_active; }
385 
386   // Total number of GC collections (started)
387   unsigned int total_collections() const { return _total_collections; }
388   unsigned int total_full_collections() const { return _total_full_collections;}
389 
390   // Increment total number of GC collections (started)
391   void increment_total_collections(bool full = false) {
392     _total_collections++;
393     if (full) {
394       _total_full_collections++;
395     }
396   }
397 
398   virtual MemoryUsage memory_usage();
399   virtual GrowableArray<GCMemoryManager*> memory_managers() = 0;
400   virtual GrowableArray<MemoryPool*> memory_pools() = 0;
401 
402   // Iterate over all objects, calling "cl.do_object" on each.
403   virtual void object_iterate(ObjectClosure* cl) = 0;
404 
405   virtual ParallelObjectIteratorImpl* parallel_object_iterator(uint thread_num) {
406     return nullptr;
407   }
408 
409   // Keep alive an object that was loaded with AS_NO_KEEPALIVE.
410   virtual void keep_alive(oop obj) {}
411 
412   // Perform any cleanup actions necessary before allowing a verification.
413   virtual void prepare_for_verify() = 0;
414 
415   // Returns the longest time (in ms) that has elapsed since the last
416   // time that the whole heap has been examined by a garbage collection.
417   jlong millis_since_last_whole_heap_examined();
418   // GC should call this when the next whole heap analysis has completed to
419   // satisfy above requirement.
420   void record_whole_heap_examined_timestamp();
421 
422  private:
423   // Generate any dumps preceding or following a full gc
424   void full_gc_dump(GCTimer* timer, bool before);
425 
426   void print_relative_to_gc(GCWhen::Type when) const;
427 
428  public:
429   void pre_full_gc_dump(GCTimer* timer);
430   void post_full_gc_dump(GCTimer* timer);
431 
432   virtual VirtualSpaceSummary create_heap_space_summary();
433   GCHeapSummary create_heap_summary();
434 
435   MetaspaceSummary create_metaspace_summary();
436 
437   // GCs are free to represent the bit representation for null differently in memory,
438   // which is typically not observable when using the Access API. However, if for
439   // some reason a context doesn't allow using the Access API, then this function
440   // explicitly checks if the given memory location contains a null value.
441   virtual bool contains_null(const oop* p) const;
442 
443   void print_invocation_on(outputStream* st, const char* type, GCWhen::Type when) const;
444 
445   // Print heap information.
446   virtual void print_heap_on(outputStream* st) const = 0;
447 
448   // Print additional information about the GC that is not included in print_heap_on().
449   virtual void print_gc_on(outputStream* st) const = 0;
450 
451   // The default behavior is to call print_heap_on() and print_gc_on() on tty.
452   virtual void print() const;
453 
454   // Used to print information about locations in the hs_err file.
455   virtual bool print_location(outputStream* st, void* addr) const = 0;
456 
457   // Iterator for all GC threads (other than VM thread)
458   virtual void gc_threads_do(ThreadClosure* tc) const = 0;
459 
460   void print_before_gc() const;
461   void print_after_gc() const;
462 
463   // Registering and unregistering an nmethod (compiled code) with the heap.
464   virtual void register_nmethod(nmethod* nm) = 0;
465   virtual void unregister_nmethod(nmethod* nm) = 0;
466   virtual void verify_nmethod(nmethod* nm) = 0;
467 
468   void trace_heap_before_gc(const GCTracer* gc_tracer);
469   void trace_heap_after_gc(const GCTracer* gc_tracer);
470 
471   // Heap verification
472   virtual void verify(VerifyOption option) = 0;
473 
474   // Return true if concurrent gc control via WhiteBox is supported by
475   // this collector.  The default implementation returns false.
476   virtual bool supports_concurrent_gc_breakpoints() const;
477 
478   // Workers used in non-GC safepoints for parallel safepoint cleanup. If this
479   // method returns null, cleanup tasks are done serially in the VMThread. See
480   // `SafepointSynchronize::do_cleanup_tasks` for details.
481   // GCs using a GC worker thread pool inside GC safepoints may opt to share
482   // that pool with non-GC safepoints, avoiding creating extraneous threads.
483   // Such sharing is safe, because GC safepoints and non-GC safepoints never
484   // overlap. For example, `G1CollectedHeap::workers()` (for GC safepoints) and
485   // `G1CollectedHeap::safepoint_workers()` (for non-GC safepoints) return the
486   // same thread-pool.
487   virtual WorkerThreads* safepoint_workers() { return nullptr; }
488 
489   // Support for object pinning. This is used by JNI Get*Critical()
490   // and Release*Critical() family of functions. The GC must guarantee
491   // that pinned objects never move and don't get reclaimed as garbage.
492   // These functions are potentially safepointing.
493   virtual void pin_object(JavaThread* thread, oop obj) = 0;
494   virtual void unpin_object(JavaThread* thread, oop obj) = 0;
495 
496   // Support for loading objects from CDS archive into the heap
497   // (usually as a snapshot of the old generation).
498   virtual bool can_load_archived_objects() const { return false; }
499   virtual HeapWord* allocate_loaded_archive_space(size_t size) { return nullptr; }
500   virtual void complete_loaded_archive_space(MemRegion archive_space) { }
501   virtual size_t bootstrap_max_memory() const;
502 
503   virtual bool is_oop(oop object) const;
504   // Non product verification and debugging.
505 #ifndef PRODUCT
506   // Support for PromotionFailureALot.  Return true if it's time to cause a
507   // promotion failure.  The no-argument version uses
508   // this->_promotion_failure_alot_count as the counter.
509   bool promotion_should_fail(volatile size_t* count);
510   bool promotion_should_fail();
511 
512   // Reset the PromotionFailureALot counters.  Should be called at the end of a
513   // GC in which promotion failure occurred.
514   void reset_promotion_should_fail(volatile size_t* count);
515   void reset_promotion_should_fail();
516 #endif  // #ifndef PRODUCT
517 };
518 
519 // Class to set and reset the GC cause for a CollectedHeap.
520 
521 class GCCauseSetter : StackObj {
522   CollectedHeap* _heap;
523   GCCause::Cause _previous_cause;
524  public:
525   GCCauseSetter(CollectedHeap* heap, GCCause::Cause cause) {
526     _heap = heap;
527     _previous_cause = _heap->gc_cause();
528     _heap->set_gc_cause(cause);
529   }
530 
531   ~GCCauseSetter() {
532     _heap->set_gc_cause(_previous_cause);
533   }
534 };
535 
536 #endif // SHARE_GC_SHARED_COLLECTEDHEAP_HPP