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