1 /*
  2  * Copyright (c) 2001, 2022, 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/memoryUsage.hpp"
 39 #include "utilities/debug.hpp"
 40 #include "utilities/formatBuffer.hpp"
 41 #include "utilities/growableArray.hpp"
 42 
 43 // A "CollectedHeap" is an implementation of a java heap for HotSpot.  This
 44 // is an abstract class: there may be many different kinds of heaps.  This
 45 // class defines the functions that a heap must implement, and contains
 46 // infrastructure common to all heaps.
 47 
 48 class WorkerTask;
 49 class AdaptiveSizePolicy;
 50 class BarrierSet;
 51 class GCHeapLog;
 52 class GCHeapSummary;
 53 class GCTimer;
 54 class GCTracer;
 55 class GCMemoryManager;
 56 class MemoryPool;
 57 class MetaspaceSummary;
 58 class ReservedHeapSpace;
 59 class SoftRefPolicy;
 60 class Thread;
 61 class ThreadClosure;
 62 class VirtualSpaceSummary;
 63 class WorkerThreads;
 64 class nmethod;
 65 
 66 class ParallelObjectIteratorImpl : public CHeapObj<mtGC> {
 67 public:
 68   virtual ~ParallelObjectIteratorImpl() {}
 69   virtual void object_iterate(ObjectClosure* cl, uint worker_id) = 0;
 70 };
 71 
 72 // User facing parallel object iterator. This is a StackObj, which ensures that
 73 // the _impl is allocated and deleted in the scope of this object. This ensures
 74 // the life cycle of the implementation is as required by ThreadsListHandle,
 75 // which is sometimes used by the root iterators.
 76 class ParallelObjectIterator : public StackObj {
 77   ParallelObjectIteratorImpl* _impl;
 78 
 79 public:
 80   ParallelObjectIterator(uint thread_num);
 81   ~ParallelObjectIterator();
 82   void object_iterate(ObjectClosure* cl, uint worker_id);
 83 };
 84 
 85 //
 86 // CollectedHeap
 87 //   GenCollectedHeap
 88 //     SerialHeap
 89 //   G1CollectedHeap
 90 //   ParallelScavengeHeap
 91 //   ShenandoahHeap
 92 //   ZCollectedHeap
 93 //
 94 class CollectedHeap : public CHeapObj<mtGC> {
 95   friend class VMStructs;
 96   friend class JVMCIVMStructs;
 97   friend class IsGCActiveMark; // Block structured external access to _is_gc_active
 98   friend class MemAllocator;
 99   friend class ParallelObjectIterator;
100 
101  private:
102   GCHeapLog* _gc_heap_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_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   // 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);
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,
163                                  bool* gc_overhead_limit_was_exceeded) = 0;
164 
165   // Filler object utilities.
166   static inline size_t filler_array_hdr_size();
167   static inline size_t filler_array_min_size();
168 
169   static inline void zap_filler_array_with(HeapWord* start, size_t words, juint value);
170   DEBUG_ONLY(static void fill_args_check(HeapWord* start, size_t words);)
171   DEBUG_ONLY(static void zap_filler_array(HeapWord* start, size_t words, bool zap = true);)
172 
173   // Fill with a single array; caller must ensure filler_array_min_size() <=
174   // words <= filler_array_max_size().
175   static inline void fill_with_array(HeapWord* start, size_t words, bool zap = true);
176 
177   // Fill with a single object (either an int array or a java.lang.Object).
178   static inline void fill_with_object_impl(HeapWord* start, size_t words, bool zap = true);
179 
180   virtual void trace_heap(GCWhen::Type when, const GCTracer* tracer);
181 
182   // Verification functions
183   virtual void check_for_non_bad_heap_word_value(HeapWord* addr, size_t size)
184     PRODUCT_RETURN;
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 != NULL, "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  public:
211 
212   static inline size_t filler_array_max_size() {
213     return _filler_array_max_size;
214   }
215 
216   static inline size_t stack_chunk_max_size() {
217     return _stack_chunk_max_size;
218   }
219 
220   static inline Klass* filler_object_klass() {
221     return _filler_object_klass;
222   }
223 
224   static inline void set_filler_object_klass(Klass* k) {
225     _filler_object_klass = k;
226   }
227 
228   virtual Name kind() const = 0;
229 
230   virtual const char* name() const = 0;
231 
232   /**
233    * Returns JNI error code JNI_ENOMEM if memory could not be allocated,
234    * and JNI_OK on success.
235    */
236   virtual jint initialize() = 0;
237 
238   // In many heaps, there will be a need to perform some initialization activities
239   // after the Universe is fully formed, but before general heap allocation is allowed.
240   // This is the correct place to place such initialization methods.
241   virtual void post_initialize();
242 
243   // Stop any onging concurrent work and prepare for exit.
244   virtual void stop() {}
245 
246   // Stop and resume concurrent GC threads interfering with safepoint operations
247   virtual void safepoint_synchronize_begin() {}
248   virtual void safepoint_synchronize_end() {}
249 
250   void initialize_reserved_region(const ReservedHeapSpace& rs);
251 
252   virtual size_t capacity() const = 0;
253   virtual size_t used() const = 0;
254 
255   // Returns unused capacity.
256   virtual size_t unused() const;
257 
258   // Historic gc information
259   size_t free_at_last_gc() const { return _capacity_at_last_gc - _used_at_last_gc; }
260   size_t used_at_last_gc() const { return _used_at_last_gc; }
261   void update_capacity_and_used_at_gc();
262 
263   // Return "true" if the part of the heap that allocates Java
264   // objects has reached the maximal committed limit that it can
265   // reach, without a garbage collection.
266   virtual bool is_maximal_no_gc() const = 0;
267 
268   // Support for java.lang.Runtime.maxMemory():  return the maximum amount of
269   // memory that the vm could make available for storing 'normal' java objects.
270   // This is based on the reserved address space, but should not include space
271   // that the vm uses internally for bookkeeping or temporary storage
272   // (e.g., in the case of the young gen, one of the survivor
273   // spaces).
274   virtual size_t max_capacity() const = 0;
275 
276   // Returns "TRUE" iff "p" points into the committed areas of the heap.
277   // This method can be expensive so avoid using it in performance critical
278   // code.
279   virtual bool is_in(const void* p) const = 0;
280 
281   DEBUG_ONLY(bool is_in_or_null(const void* p) const { return p == NULL || is_in(p); })
282 
283   virtual uint32_t hash_oop(oop obj) const;
284 
285   void set_gc_cause(GCCause::Cause v);
286   GCCause::Cause gc_cause() { return _gc_cause; }
287 
288   oop obj_allocate(Klass* klass, size_t size, TRAPS);
289   virtual oop array_allocate(Klass* klass, size_t size, int length, bool do_zero, TRAPS);
290   oop class_allocate(Klass* klass, size_t size, TRAPS);
291 
292   // Utilities for turning raw memory into filler objects.
293   //
294   // min_fill_size() is the smallest region that can be filled.
295   // fill_with_objects() can fill arbitrary-sized regions of the heap using
296   // multiple objects.  fill_with_object() is for regions known to be smaller
297   // than the largest array of integers; it uses a single object to fill the
298   // region and has slightly less overhead.
299   static size_t min_fill_size() {
300     return size_t(align_object_size(oopDesc::header_size()));
301   }
302 
303   static void fill_with_objects(HeapWord* start, size_t words, bool zap = true);
304 
305   static void fill_with_object(HeapWord* start, size_t words, bool zap = true);
306   static void fill_with_object(MemRegion region, bool zap = true) {
307     fill_with_object(region.start(), region.word_size(), zap);
308   }
309   static void fill_with_object(HeapWord* start, HeapWord* end, bool zap = true) {
310     fill_with_object(start, pointer_delta(end, start), zap);
311   }
312 
313   virtual void fill_with_dummy_object(HeapWord* start, HeapWord* end, bool zap);
314   static constexpr size_t min_dummy_object_size() {
315     return oopDesc::header_size();
316   }
317 
318   static size_t lab_alignment_reserve() {
319     assert(_lab_alignment_reserve != ~(size_t)0, "uninitialized");
320     return _lab_alignment_reserve;
321   }
322 
323   // Some heaps may be in an unparseable state at certain times between
324   // collections. This may be necessary for efficient implementation of
325   // certain allocation-related activities. Calling this function before
326   // attempting to parse a heap ensures that the heap is in a parsable
327   // state (provided other concurrent activity does not introduce
328   // unparsability). It is normally expected, therefore, that this
329   // method is invoked with the world stopped.
330   // NOTE: if you override this method, make sure you call
331   // super::ensure_parsability so that the non-generational
332   // part of the work gets done. See implementation of
333   // CollectedHeap::ensure_parsability and, for instance,
334   // that of GenCollectedHeap::ensure_parsability().
335   // The argument "retire_tlabs" controls whether existing TLABs
336   // are merely filled or also retired, thus preventing further
337   // allocation from them and necessitating allocation of new TLABs.
338   virtual void ensure_parsability(bool retire_tlabs);
339 
340   // The amount of space available for thread-local allocation buffers.
341   virtual size_t tlab_capacity(Thread *thr) const = 0;
342 
343   // The amount of used space for thread-local allocation buffers for the given thread.
344   virtual size_t tlab_used(Thread *thr) const = 0;
345 
346   virtual size_t max_tlab_size() const;
347 
348   // An estimate of the maximum allocation that could be performed
349   // for thread-local allocation buffers without triggering any
350   // collection or expansion activity.
351   virtual size_t unsafe_max_tlab_alloc(Thread *thr) const {
352     guarantee(false, "thread-local allocation buffers not supported");
353     return 0;
354   }
355 
356   // If a GC uses a stack watermark barrier, the stack processing is lazy, concurrent,
357   // incremental and cooperative. In order for that to work well, mechanisms that stop
358   // another thread might want to ensure its roots are in a sane state.
359   virtual bool uses_stack_watermark_barrier() const { return false; }
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.  (I assume
389   // that it should answer "false" for the concurrent part of a concurrent
390   // collector -- dld).
391   bool is_gc_active() const { return _is_gc_active; }
392 
393   // Total number of GC collections (started)
394   unsigned int total_collections() const { return _total_collections; }
395   unsigned int total_full_collections() const { return _total_full_collections;}
396 
397   // Increment total number of GC collections (started)
398   void increment_total_collections(bool full = false) {
399     _total_collections++;
400     if (full) {
401       increment_total_full_collections();
402     }
403   }
404 
405   void increment_total_full_collections() { _total_full_collections++; }
406 
407   // Return the SoftRefPolicy for the heap;
408   virtual SoftRefPolicy* soft_ref_policy() = 0;
409 
410   virtual MemoryUsage memory_usage();
411   virtual GrowableArray<GCMemoryManager*> memory_managers() = 0;
412   virtual GrowableArray<MemoryPool*> memory_pools() = 0;
413 
414   // Iterate over all objects, calling "cl.do_object" on each.
415   virtual void object_iterate(ObjectClosure* cl) = 0;
416 
417  protected:
418   virtual ParallelObjectIteratorImpl* parallel_object_iterator(uint thread_num) {
419     return NULL;
420   }
421 
422  public:
423   // Keep alive an object that was loaded with AS_NO_KEEPALIVE.
424   virtual void keep_alive(oop obj) {}
425 
426   // Perform any cleanup actions necessary before allowing a verification.
427   virtual void prepare_for_verify() = 0;
428 
429   // Returns the longest time (in ms) that has elapsed since the last
430   // time that the whole heap has been examined by a garbage collection.
431   jlong millis_since_last_whole_heap_examined();
432   // GC should call this when the next whole heap analysis has completed to
433   // satisfy above requirement.
434   void record_whole_heap_examined_timestamp();
435 
436  private:
437   // Generate any dumps preceding or following a full gc
438   void full_gc_dump(GCTimer* timer, bool before);
439 
440   virtual void initialize_serviceability() = 0;
441 
442  public:
443   void pre_full_gc_dump(GCTimer* timer);
444   void post_full_gc_dump(GCTimer* timer);
445 
446   virtual VirtualSpaceSummary create_heap_space_summary();
447   GCHeapSummary create_heap_summary();
448 
449   MetaspaceSummary create_metaspace_summary();
450 
451   // Print heap information on the given outputStream.
452   virtual void print_on(outputStream* st) const = 0;
453   // The default behavior is to call print_on() on tty.
454   virtual void print() const;
455 
456   // Print more detailed heap information on the given
457   // outputStream. The default behavior is to call print_on(). It is
458   // up to each subclass to override it and add any additional output
459   // it needs.
460   virtual void print_extended_on(outputStream* st) const {
461     print_on(st);
462   }
463 
464   virtual void print_on_error(outputStream* st) const;
465 
466   // Used to print information about locations in the hs_err file.
467   virtual bool print_location(outputStream* st, void* addr) const = 0;
468 
469   // Iterator for all GC threads (other than VM thread)
470   virtual void gc_threads_do(ThreadClosure* tc) const = 0;
471 
472   // Print any relevant tracing info that flags imply.
473   // Default implementation does nothing.
474   virtual void print_tracing_info() const = 0;
475 
476   void print_heap_before_gc();
477   void print_heap_after_gc();
478 
479   // Registering and unregistering an nmethod (compiled code) with the heap.
480   virtual void register_nmethod(nmethod* nm) = 0;
481   virtual void unregister_nmethod(nmethod* nm) = 0;
482   virtual void verify_nmethod(nmethod* nm) = 0;
483 
484   void trace_heap_before_gc(const GCTracer* gc_tracer);
485   void trace_heap_after_gc(const GCTracer* gc_tracer);
486 
487   // Heap verification
488   virtual void verify(VerifyOption option) = 0;
489 
490   // Return true if concurrent gc control via WhiteBox is supported by
491   // this collector.  The default implementation returns false.
492   virtual bool supports_concurrent_gc_breakpoints() const;
493 
494   // Workers used in non-GC safepoints for parallel safepoint cleanup. If this
495   // method returns NULL, cleanup tasks are done serially in the VMThread. See
496   // `SafepointSynchronize::do_cleanup_tasks` for details.
497   // GCs using a GC worker thread pool inside GC safepoints may opt to share
498   // that pool with non-GC safepoints, avoiding creating extraneous threads.
499   // Such sharing is safe, because GC safepoints and non-GC safepoints never
500   // overlap. For example, `G1CollectedHeap::workers()` (for GC safepoints) and
501   // `G1CollectedHeap::safepoint_workers()` (for non-GC safepoints) return the
502   // same thread-pool.
503   virtual WorkerThreads* safepoint_workers() { return NULL; }
504 
505   // Support for object pinning. This is used by JNI Get*Critical()
506   // and Release*Critical() family of functions. If supported, the GC
507   // must guarantee that pinned objects never move.
508   virtual bool supports_object_pinning() const;
509   virtual oop pin_object(JavaThread* thread, oop obj);
510   virtual void unpin_object(JavaThread* thread, oop obj);
511 
512   // Is the given object inside a CDS archive area?
513   virtual bool is_archived_object(oop object) const;
514 
515   // Support for loading objects from CDS archive into the heap
516   // (usually as a snapshot of the old generation).
517   virtual bool can_load_archived_objects() const { return false; }
518   virtual HeapWord* allocate_loaded_archive_space(size_t size) { return NULL; }
519   virtual void complete_loaded_archive_space(MemRegion archive_space) { }
520 
521   virtual bool is_oop(oop object) const;
522   // Non product verification and debugging.
523 #ifndef PRODUCT
524   // Support for PromotionFailureALot.  Return true if it's time to cause a
525   // promotion failure.  The no-argument version uses
526   // this->_promotion_failure_alot_count as the counter.
527   bool promotion_should_fail(volatile size_t* count);
528   bool promotion_should_fail();
529 
530   // Reset the PromotionFailureALot counters.  Should be called at the end of a
531   // GC in which promotion failure occurred.
532   void reset_promotion_should_fail(volatile size_t* count);
533   void reset_promotion_should_fail();
534 #endif  // #ifndef PRODUCT
535 };
536 
537 // Class to set and reset the GC cause for a CollectedHeap.
538 
539 class GCCauseSetter : StackObj {
540   CollectedHeap* _heap;
541   GCCause::Cause _previous_cause;
542  public:
543   GCCauseSetter(CollectedHeap* heap, GCCause::Cause cause) {
544     _heap = heap;
545     _previous_cause = _heap->gc_cause();
546     _heap->set_gc_cause(cause);
547   }
548 
549   ~GCCauseSetter() {
550     _heap->set_gc_cause(_previous_cause);
551   }
552 };
553 
554 #endif // SHARE_GC_SHARED_COLLECTEDHEAP_HPP