1 /*
2 * Copyright (c) 2001, 2025, 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 GCHeapLog* _heap_log;
100 GCMetaspaceLog* _metaspace_log;
101
102 // Historic gc information
103 size_t _capacity_at_last_gc;
104 size_t _used_at_last_gc;
105
106 // First, set it to java_lang_Object.
107 // Then, set it to FillerObject after the FillerObject_klass loading is complete.
108 static Klass* _filler_object_klass;
109
110 protected:
111 // Not used by all GCs
112 MemRegion _reserved;
113
114 bool _is_stw_gc_active;
115
116 // (Minimum) Alignment reserve for TLABs and PLABs.
117 static size_t _lab_alignment_reserve;
118 // Used for filler objects (static, but initialized in ctor).
119 static size_t _filler_array_max_size;
120
121 static size_t _stack_chunk_max_size; // 0 for no limit
122
123 // Last time the whole heap has been examined in support of RMI
124 // MaxObjectInspectionAge.
125 // This timestamp must be monotonically non-decreasing to avoid
126 // time-warp warnings.
127 jlong _last_whole_heap_examined_time_ns;
128
129 unsigned int _total_collections; // ... started
130 unsigned int _total_full_collections; // ... started
131 NOT_PRODUCT(volatile size_t _promotion_failure_alot_count;)
132 NOT_PRODUCT(volatile size_t _promotion_failure_alot_gc_number;)
133
134 jlong _vmthread_cpu_time;
135
136 // Reason for current garbage collection. Should be set to
137 // a value reflecting no collection between collections.
138 GCCause::Cause _gc_cause;
139 GCCause::Cause _gc_lastcause;
140 PerfStringVariable* _perf_gc_cause;
141 PerfStringVariable* _perf_gc_lastcause;
142
143 // Constructor
144 CollectedHeap();
145
146 // Create a new tlab. All TLAB allocations must go through this.
147 // To allow more flexible TLAB allocations min_size specifies
148 // the minimum size needed, while requested_size is the requested
149 // size based on ergonomics. The actually allocated size will be
150 // returned in actual_size.
151 virtual HeapWord* allocate_new_tlab(size_t min_size,
152 size_t requested_size,
153 size_t* actual_size) = 0;
154
155 // Reinitialize tlabs before resuming mutators.
156 virtual void resize_all_tlabs();
157
158 // Raw memory allocation facilities
159 // The obj and array allocate methods are covers for these methods.
160 // mem_allocate() should never be
161 // called to allocate TLABs, only individual objects.
162 virtual HeapWord* mem_allocate(size_t size) = 0;
163
164 // Filler object utilities.
165 static inline size_t filler_array_hdr_size();
166
167 static size_t filler_array_min_size();
168
169 protected:
170 static inline void zap_filler_array_with(HeapWord* start, size_t words, juint value);
171 DEBUG_ONLY(static void fill_args_check(HeapWord* start, size_t words);)
172 DEBUG_ONLY(static void zap_filler_array(HeapWord* start, size_t words, bool zap = true);)
173
174 // Fill with a single array; caller must ensure filler_array_min_size() <=
175 // words <= filler_array_max_size().
176 static inline void fill_with_array(HeapWord* start, size_t words, bool zap = true);
177
178 // Fill with a single object (either an int array or a java.lang.Object).
179 static inline void fill_with_object_impl(HeapWord* start, size_t words, bool zap = true);
180
181 virtual void trace_heap(GCWhen::Type when, const GCTracer* tracer);
182
183 // Verification functions
184 DEBUG_ONLY(static void check_for_valid_allocation_state();)
185
186 public:
187 enum Name {
188 None,
189 Serial,
190 Parallel,
191 G1,
192 Epsilon,
193 Z,
194 Shenandoah
195 };
196
197 protected:
198 // Get a pointer to the derived heap object. Used to implement
199 // derived class heap() functions rather than being called directly.
200 template<typename T>
201 static T* named_heap(Name kind) {
202 CollectedHeap* heap = Universe::heap();
203 assert(heap != nullptr, "Uninitialized heap");
204 assert(kind == heap->kind(), "Heap kind %u should be %u",
205 static_cast<uint>(heap->kind()), static_cast<uint>(kind));
206 return static_cast<T*>(heap);
207 }
208
209 // Print any relevant tracing info that flags imply.
210 // Default implementation does nothing.
211 virtual void print_tracing_info() const = 0;
212
213 // Stop any onging concurrent work and prepare for exit.
214 virtual void stop() = 0;
215
216 public:
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 // In many heaps, there will be a need to perform some initialization activities
245 // after the Universe is fully formed, but before general heap allocation is allowed.
246 // This is the correct place to place such initialization methods.
247 virtual void post_initialize();
248
249 bool is_shutting_down() const;
250
251 // If the VM is shutting down, we may have skipped VM_CollectForAllocation.
252 // In this case, stall the allocation request briefly in the hope that
253 // the VM shutdown completes before the allocation request returns.
254 void stall_for_vm_shutdown();
255
256 void before_exit();
257
258 // Stop and resume concurrent GC threads interfering with safepoint operations
259 virtual void safepoint_synchronize_begin() {}
260 virtual void safepoint_synchronize_end() {}
261
262 void add_vmthread_cpu_time(jlong time);
263
264 void initialize_reserved_region(const ReservedHeapSpace& rs);
265
266 virtual size_t capacity() const = 0;
267 virtual size_t used() const = 0;
268
269 // Returns unused capacity.
270 virtual size_t unused() const;
271
272 // Historic gc information
273 size_t free_at_last_gc() const { return _capacity_at_last_gc - _used_at_last_gc; }
274 size_t used_at_last_gc() const { return _used_at_last_gc; }
275 void update_capacity_and_used_at_gc();
276
277 // Support for java.lang.Runtime.maxMemory(): return the maximum amount of
278 // memory that the vm could make available for storing 'normal' java objects.
279 // This is based on the reserved address space, but should not include space
280 // that the vm uses internally for bookkeeping or temporary storage
281 // (e.g., in the case of the young gen, one of the survivor
282 // spaces).
283 virtual size_t max_capacity() const = 0;
284
285 // Returns "TRUE" iff "p" points into the committed areas of the heap.
286 // This method can be expensive so avoid using it in performance critical
287 // code.
288 virtual bool is_in(const void* p) const = 0;
289
290 DEBUG_ONLY(bool is_in_or_null(const void* p) const { return p == nullptr || is_in(p); })
291
292 void set_gc_cause(GCCause::Cause v);
293 GCCause::Cause gc_cause() { return _gc_cause; }
294
295 oop obj_allocate(Klass* klass, size_t size, TRAPS);
296 oop obj_buffer_allocate(Klass* klass, size_t size, TRAPS); // doesn't clear memory
297 virtual oop array_allocate(Klass* klass, size_t size, int length, bool do_zero, TRAPS);
298 oop class_allocate(Klass* klass, size_t size, TRAPS);
299
300 // Utilities for turning raw memory into filler objects.
301 //
302 // min_fill_size() is the smallest region that can be filled.
303 // fill_with_objects() can fill arbitrary-sized regions of the heap using
304 // multiple objects. fill_with_object() is for regions known to be smaller
305 // than the largest array of integers; it uses a single object to fill the
306 // region and has slightly less overhead.
307 static size_t min_fill_size() {
308 return size_t(align_object_size(oopDesc::header_size()));
309 }
310
311 static void fill_with_objects(HeapWord* start, size_t words, bool zap = true);
312
313 static void fill_with_object(HeapWord* start, size_t words, bool zap = true);
314 static void fill_with_object(MemRegion region, bool zap = true) {
315 fill_with_object(region.start(), region.word_size(), zap);
316 }
317 static void fill_with_object(HeapWord* start, HeapWord* end, bool zap = true) {
318 fill_with_object(start, pointer_delta(end, start), zap);
319 }
320
321 virtual void fill_with_dummy_object(HeapWord* start, HeapWord* end, bool zap);
322 static size_t min_dummy_object_size() {
323 return oopDesc::header_size();
324 }
325
326 static size_t lab_alignment_reserve() {
327 assert(_lab_alignment_reserve != SIZE_MAX, "uninitialized");
328 return _lab_alignment_reserve;
329 }
330
331 // Some heaps may be in an unparseable state at certain times between
332 // collections. This may be necessary for efficient implementation of
333 // certain allocation-related activities. Calling this function before
334 // attempting to parse a heap ensures that the heap is in a parsable
335 // state (provided other concurrent activity does not introduce
336 // unparsability). It is normally expected, therefore, that this
337 // method is invoked with the world stopped.
338 // NOTE: if you override this method, make sure you call
339 // super::ensure_parsability so that the non-generational
340 // part of the work gets done. See implementation of
341 // CollectedHeap::ensure_parsability and, for instance,
342 // that of ParallelScavengeHeap::ensure_parsability().
343 // The argument "retire_tlabs" controls whether existing TLABs
344 // are merely filled or also retired, thus preventing further
345 // allocation from them and necessitating allocation of new TLABs.
346 virtual void ensure_parsability(bool retire_tlabs);
347
348 // The amount of space available for thread-local allocation buffers.
349 virtual size_t tlab_capacity(Thread *thr) const = 0;
350
351 // The amount of used space for thread-local allocation buffers for the given thread.
352 virtual size_t tlab_used(Thread *thr) const = 0;
353
354 virtual size_t max_tlab_size() const;
355
356 // An estimate of the maximum allocation that could be performed
357 // for thread-local allocation buffers without triggering any
358 // collection or expansion activity.
359 virtual size_t unsafe_max_tlab_alloc(Thread *thr) const = 0;
360
361 // Perform a collection of the heap; intended for use in implementing
362 // "System.gc". This probably implies as full a collection as the
363 // "CollectedHeap" supports.
364 virtual void collect(GCCause::Cause cause) = 0;
365
366 // Perform a full collection
367 virtual void do_full_collection(bool clear_all_soft_refs) = 0;
368
369 // This interface assumes that it's being called by the
370 // vm thread. It collects the heap assuming that the
371 // heap lock is already held and that we are executing in
372 // the context of the vm thread.
373 virtual void collect_as_vm_thread(GCCause::Cause cause);
374
375 virtual MetaWord* satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,
376 size_t size,
377 Metaspace::MetadataType mdtype);
378
379 // Return true, if accesses to the object would require barriers.
380 // This is used by continuations to copy chunks of a thread stack into StackChunk object or out of a StackChunk
381 // object back into the thread stack. These chunks may contain references to objects. It is crucial that
382 // the GC does not attempt to traverse the object while we modify it, because its structure (oopmap) is changed
383 // when stack chunks are stored into it.
384 // StackChunk objects may be reused, the GC must not assume that a StackChunk object is always a freshly
385 // allocated object.
386 virtual bool requires_barriers(stackChunkOop obj) const = 0;
387
388 // Returns "true" iff there is a stop-world GC in progress.
389 bool is_stw_gc_active() const { return _is_stw_gc_active; }
390
391 // Total number of GC collections (started)
392 unsigned int total_collections() const { return _total_collections; }
393 unsigned int total_full_collections() const { return _total_full_collections;}
394
395 // Increment total number of GC collections (started)
396 void increment_total_collections(bool full = false) {
397 _total_collections++;
398 if (full) {
399 _total_full_collections++;
400 }
401 }
402
403 virtual MemoryUsage memory_usage();
404 virtual GrowableArray<GCMemoryManager*> memory_managers() = 0;
405 virtual GrowableArray<MemoryPool*> memory_pools() = 0;
406
407 // Iterate over all objects, calling "cl.do_object" on each.
408 virtual void object_iterate(ObjectClosure* cl) = 0;
409
410 virtual ParallelObjectIteratorImpl* parallel_object_iterator(uint thread_num) {
411 return nullptr;
412 }
413
414 // Keep alive an object that was loaded with AS_NO_KEEPALIVE.
415 virtual void keep_alive(oop obj) {}
416
417 // Perform any cleanup actions necessary before allowing a verification.
418 virtual void prepare_for_verify() = 0;
419
420 // Returns the longest time (in ms) that has elapsed since the last
421 // time that the whole heap has been examined by a garbage collection.
422 jlong millis_since_last_whole_heap_examined();
423 // GC should call this when the next whole heap analysis has completed to
424 // satisfy above requirement.
425 void record_whole_heap_examined_timestamp();
426
427 private:
428 // Generate any dumps preceding or following a full gc
429 void full_gc_dump(GCTimer* timer, bool before);
430
431 virtual void initialize_serviceability() = 0;
432
433 void print_relative_to_gc(GCWhen::Type when) const;
434
435 public:
436 void pre_full_gc_dump(GCTimer* timer);
437 void post_full_gc_dump(GCTimer* timer);
438
439 virtual VirtualSpaceSummary create_heap_space_summary();
440 GCHeapSummary create_heap_summary();
441
442 MetaspaceSummary create_metaspace_summary();
443
444 // GCs are free to represent the bit representation for null differently in memory,
445 // which is typically not observable when using the Access API. However, if for
446 // some reason a context doesn't allow using the Access API, then this function
447 // explicitly checks if the given memory location contains a null value.
448 virtual bool contains_null(const oop* p) const;
449
450 void print_invocation_on(outputStream* st, const char* type, GCWhen::Type when) const;
451
452 // Print heap information.
453 virtual void print_heap_on(outputStream* st) const = 0;
454
455 // Print additional information about the GC that is not included in print_heap_on().
456 virtual void print_gc_on(outputStream* st) const = 0;
457
458 // The default behavior is to call print_heap_on() and print_gc_on() on tty.
459 virtual void print() const;
460
461 // Used to print information about locations in the hs_err file.
462 virtual bool print_location(outputStream* st, void* addr) const = 0;
463
464 // Iterator for all GC threads (other than VM thread)
465 virtual void gc_threads_do(ThreadClosure* tc) const = 0;
466
467 void print_before_gc() const;
468 void print_after_gc() const;
469
470 // Registering and unregistering an nmethod (compiled code) with the heap.
471 virtual void register_nmethod(nmethod* nm) = 0;
472 virtual void unregister_nmethod(nmethod* nm) = 0;
473 virtual void verify_nmethod(nmethod* nm) = 0;
474
475 void trace_heap_before_gc(const GCTracer* gc_tracer);
476 void trace_heap_after_gc(const GCTracer* gc_tracer);
477
478 // Heap verification
479 virtual void verify(VerifyOption option) = 0;
480
481 // Return true if concurrent gc control via WhiteBox is supported by
482 // this collector. The default implementation returns false.
483 virtual bool supports_concurrent_gc_breakpoints() const;
484
485 // Workers used in non-GC safepoints for parallel safepoint cleanup. If this
486 // method returns null, cleanup tasks are done serially in the VMThread. See
487 // `SafepointSynchronize::do_cleanup_tasks` for details.
488 // GCs using a GC worker thread pool inside GC safepoints may opt to share
489 // that pool with non-GC safepoints, avoiding creating extraneous threads.
490 // Such sharing is safe, because GC safepoints and non-GC safepoints never
491 // overlap. For example, `G1CollectedHeap::workers()` (for GC safepoints) and
492 // `G1CollectedHeap::safepoint_workers()` (for non-GC safepoints) return the
493 // same thread-pool.
494 virtual WorkerThreads* safepoint_workers() { return nullptr; }
495
496 // Support for object pinning. This is used by JNI Get*Critical()
497 // and Release*Critical() family of functions. The GC must guarantee
498 // that pinned objects never move and don't get reclaimed as garbage.
499 // These functions are potentially safepointing.
500 virtual void pin_object(JavaThread* thread, oop obj) = 0;
501 virtual void unpin_object(JavaThread* thread, oop obj) = 0;
502
503 // Support for loading objects from CDS archive into the heap
504 // (usually as a snapshot of the old generation).
505 virtual bool can_load_archived_objects() const { return false; }
506 virtual HeapWord* allocate_loaded_archive_space(size_t size) { return nullptr; }
507 virtual void complete_loaded_archive_space(MemRegion archive_space) { }
508
509 virtual bool is_oop(oop object) const;
510 // Non product verification and debugging.
511 #ifndef PRODUCT
512 // Support for PromotionFailureALot. Return true if it's time to cause a
513 // promotion failure. The no-argument version uses
514 // this->_promotion_failure_alot_count as the counter.
515 bool promotion_should_fail(volatile size_t* count);
516 bool promotion_should_fail();
517
518 // Reset the PromotionFailureALot counters. Should be called at the end of a
519 // GC in which promotion failure occurred.
520 void reset_promotion_should_fail(volatile size_t* count);
521 void reset_promotion_should_fail();
522 #endif // #ifndef PRODUCT
523 };
524
525 // Class to set and reset the GC cause for a CollectedHeap.
526
527 class GCCauseSetter : StackObj {
528 CollectedHeap* _heap;
529 GCCause::Cause _previous_cause;
530 public:
531 GCCauseSetter(CollectedHeap* heap, GCCause::Cause cause) {
532 _heap = heap;
533 _previous_cause = _heap->gc_cause();
534 _heap->set_gc_cause(cause);
535 }
536
537 ~GCCauseSetter() {
538 _heap->set_gc_cause(_previous_cause);
539 }
540 };
541
542 #endif // SHARE_GC_SHARED_COLLECTEDHEAP_HPP