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 "runtime/handles.hpp"
 35 #include "runtime/perfDataTypes.hpp"
 36 #include "runtime/safepoint.hpp"
 37 #include "services/memoryUsage.hpp"
 38 #include "utilities/debug.hpp"
 39 #include "utilities/formatBuffer.hpp"
 40 #include "utilities/growableArray.hpp"
 41 
 42 // A "CollectedHeap" is an implementation of a java heap for HotSpot.  This
 43 // is an abstract class: there may be many different kinds of heaps.  This
 44 // class defines the functions that a heap must implement, and contains
 45 // infrastructure common to all heaps.
 46 
 47 class WorkerTask;
 48 class AdaptiveSizePolicy;
 49 class BarrierSet;
 50 class GCHeapLog;
 51 class GCHeapSummary;
 52 class GCTimer;
 53 class GCTracer;
 54 class GCMemoryManager;
 55 class MemoryPool;
 56 class MetaspaceSummary;
 57 class ReservedHeapSpace;
 58 class SoftRefPolicy;
 59 class Thread;
 60 class ThreadClosure;
 61 class VirtualSpaceSummary;
 62 class WorkerThreads;
 63 class nmethod;
 64 
 65 class ParallelObjectIteratorImpl : public CHeapObj<mtGC> {
 66 public:
 67   virtual ~ParallelObjectIteratorImpl() {}
 68   virtual void object_iterate(ObjectClosure* cl, uint worker_id) = 0;
 69 };
 70 
 71 // User facing parallel object iterator. This is a StackObj, which ensures that
 72 // the _impl is allocated and deleted in the scope of this object. This ensures
 73 // the life cycle of the implementation is as required by ThreadsListHandle,
 74 // which is sometimes used by the root iterators.
 75 class ParallelObjectIterator : public StackObj {
 76   ParallelObjectIteratorImpl* _impl;
 77 
 78 public:
 79   ParallelObjectIterator(uint thread_num);
 80   ~ParallelObjectIterator();
 81   void object_iterate(ObjectClosure* cl, uint worker_id);
 82 };
 83 
 84 //
 85 // CollectedHeap
 86 //   GenCollectedHeap
 87 //     SerialHeap
 88 //   G1CollectedHeap
 89 //   ParallelScavengeHeap
 90 //   ShenandoahHeap
 91 //   ZCollectedHeap
 92 //
 93 class CollectedHeap : public CHeapObj<mtGC> {
 94   friend class VMStructs;
 95   friend class JVMCIVMStructs;
 96   friend class IsGCActiveMark; // Block structured external access to _is_gc_active
 97   friend class MemAllocator;
 98   friend class ParallelObjectIterator;
 99 
100  private:
101   GCHeapLog* _gc_heap_log;
102 
103   // Historic gc information
104   size_t _capacity_at_last_gc;
105   size_t _used_at_last_gc;
106 
107  protected:
108   // Not used by all GCs
109   MemRegion _reserved;
110 
111   bool _is_gc_active;
112 
113   // Used for filler objects (static, but initialized in ctor).
114   static size_t _filler_array_max_size;
115 
116   // Last time the whole heap has been examined in support of RMI
117   // MaxObjectInspectionAge.
118   // This timestamp must be monotonically non-decreasing to avoid
119   // time-warp warnings.
120   jlong _last_whole_heap_examined_time_ns;
121 
122   unsigned int _total_collections;          // ... started
123   unsigned int _total_full_collections;     // ... started
124   NOT_PRODUCT(volatile size_t _promotion_failure_alot_count;)
125   NOT_PRODUCT(volatile size_t _promotion_failure_alot_gc_number;)
126 
127   // Reason for current garbage collection.  Should be set to
128   // a value reflecting no collection between collections.
129   GCCause::Cause _gc_cause;
130   GCCause::Cause _gc_lastcause;
131   PerfStringVariable* _perf_gc_cause;
132   PerfStringVariable* _perf_gc_lastcause;
133 
134   // Constructor
135   CollectedHeap();
136 
137   // Create a new tlab. All TLAB allocations must go through this.
138   // To allow more flexible TLAB allocations min_size specifies
139   // the minimum size needed, while requested_size is the requested
140   // size based on ergonomics. The actually allocated size will be
141   // returned in actual_size.
142   virtual HeapWord* allocate_new_tlab(size_t min_size,
143                                       size_t requested_size,
144                                       size_t* actual_size);
145 
146   // Reinitialize tlabs before resuming mutators.
147   virtual void resize_all_tlabs();
148 
149   // Raw memory allocation facilities
150   // The obj and array allocate methods are covers for these methods.
151   // mem_allocate() should never be
152   // called to allocate TLABs, only individual objects.
153   virtual HeapWord* mem_allocate(size_t size,
154                                  bool* gc_overhead_limit_was_exceeded) = 0;
155 
156   // Filler object utilities.
157   static inline size_t filler_array_hdr_size();
158   static inline size_t filler_array_min_size();
159 
160   static inline void zap_filler_array_with(HeapWord* start, size_t words, juint value);
161   DEBUG_ONLY(static void fill_args_check(HeapWord* start, size_t words);)
162   DEBUG_ONLY(static void zap_filler_array(HeapWord* start, size_t words, bool zap = true);)
163 
164   // Fill with a single array; caller must ensure filler_array_min_size() <=
165   // words <= filler_array_max_size().
166   static inline void fill_with_array(HeapWord* start, size_t words, bool zap = true);
167 
168   // Fill with a single object (either an int array or a java.lang.Object).
169   static inline void fill_with_object_impl(HeapWord* start, size_t words, bool zap = true);
170 
171   virtual void trace_heap(GCWhen::Type when, const GCTracer* tracer);
172 
173   // Verification functions
174   virtual void check_for_non_bad_heap_word_value(HeapWord* addr, size_t size)
175     PRODUCT_RETURN;
176   debug_only(static void check_for_valid_allocation_state();)
177 
178  public:
179   enum Name {
180     None,
181     Serial,
182     Parallel,
183     G1,
184     Epsilon,
185     Z,
186     Shenandoah
187   };
188 
189  protected:
190   // Get a pointer to the derived heap object.  Used to implement
191   // derived class heap() functions rather than being called directly.
192   template<typename T>
193   static T* named_heap(Name kind) {
194     CollectedHeap* heap = Universe::heap();
195     assert(heap != NULL, "Uninitialized heap");
196     assert(kind == heap->kind(), "Heap kind %u should be %u",
197            static_cast<uint>(heap->kind()), static_cast<uint>(kind));
198     return static_cast<T*>(heap);
199   }
200 
201  public:
202 
203   static inline size_t filler_array_max_size() {
204     return _filler_array_max_size;
205   }
206 
207   virtual Name kind() const = 0;
208 
209   virtual const char* name() const = 0;
210 
211   /**
212    * Returns JNI error code JNI_ENOMEM if memory could not be allocated,
213    * and JNI_OK on success.
214    */
215   virtual jint initialize() = 0;
216 
217   // In many heaps, there will be a need to perform some initialization activities
218   // after the Universe is fully formed, but before general heap allocation is allowed.
219   // This is the correct place to place such initialization methods.
220   virtual void post_initialize();
221 
222   // Stop any onging concurrent work and prepare for exit.
223   virtual void stop() {}
224 
225   // Stop and resume concurrent GC threads interfering with safepoint operations
226   virtual void safepoint_synchronize_begin() {}
227   virtual void safepoint_synchronize_end() {}
228 
229   void initialize_reserved_region(const ReservedHeapSpace& rs);
230 
231   virtual size_t capacity() const = 0;
232   virtual size_t used() const = 0;
233 
234   // Returns unused capacity.
235   virtual size_t unused() const;
236 
237   // Historic gc information
238   size_t free_at_last_gc() const { return _capacity_at_last_gc - _used_at_last_gc; }
239   size_t used_at_last_gc() const { return _used_at_last_gc; }
240   void update_capacity_and_used_at_gc();
241 
242   // Return "true" if the part of the heap that allocates Java
243   // objects has reached the maximal committed limit that it can
244   // reach, without a garbage collection.
245   virtual bool is_maximal_no_gc() const = 0;
246 
247   // Support for java.lang.Runtime.maxMemory():  return the maximum amount of
248   // memory that the vm could make available for storing 'normal' java objects.
249   // This is based on the reserved address space, but should not include space
250   // that the vm uses internally for bookkeeping or temporary storage
251   // (e.g., in the case of the young gen, one of the survivor
252   // spaces).
253   virtual size_t max_capacity() const = 0;
254 
255   // Returns "TRUE" iff "p" points into the committed areas of the heap.
256   // This method can be expensive so avoid using it in performance critical
257   // code.
258   virtual bool is_in(const void* p) const = 0;
259 
260   DEBUG_ONLY(bool is_in_or_null(const void* p) const { return p == NULL || is_in(p); })
261 
262   virtual uint32_t hash_oop(oop obj) const;
263 
264   void set_gc_cause(GCCause::Cause v);
265   GCCause::Cause gc_cause() { return _gc_cause; }
266 
267   oop obj_allocate(Klass* klass, size_t size, TRAPS);
268   oop obj_buffer_allocate(Klass* klass, size_t size, TRAPS); // doesn't clear memory
269   virtual oop array_allocate(Klass* klass, size_t size, int length, bool do_zero, TRAPS);
270   oop class_allocate(Klass* klass, size_t size, TRAPS);
271 
272   // Utilities for turning raw memory into filler objects.
273   //
274   // min_fill_size() is the smallest region that can be filled.
275   // fill_with_objects() can fill arbitrary-sized regions of the heap using
276   // multiple objects.  fill_with_object() is for regions known to be smaller
277   // than the largest array of integers; it uses a single object to fill the
278   // region and has slightly less overhead.
279   static size_t min_fill_size() {
280     return size_t(align_object_size(oopDesc::header_size()));
281   }
282 
283   static void fill_with_objects(HeapWord* start, size_t words, bool zap = true);
284 
285   static void fill_with_object(HeapWord* start, size_t words, bool zap = true);
286   static void fill_with_object(MemRegion region, bool zap = true) {
287     fill_with_object(region.start(), region.word_size(), zap);
288   }
289   static void fill_with_object(HeapWord* start, HeapWord* end, bool zap = true) {
290     fill_with_object(start, pointer_delta(end, start), zap);
291   }
292 
293   virtual void fill_with_dummy_object(HeapWord* start, HeapWord* end, bool zap);
294   static constexpr size_t min_dummy_object_size() {
295     return oopDesc::header_size();
296   }
297 
298   size_t tlab_alloc_reserve() const;
299 
300   // Some heaps may offer a contiguous region for shared non-blocking
301   // allocation, via inlined code (by exporting the address of the top and
302   // end fields defining the extent of the contiguous allocation region.)
303 
304   // This function returns "true" iff the heap supports this kind of
305   // allocation.  (Default is "no".)
306   virtual bool supports_inline_contig_alloc() const {
307     return false;
308   }
309   // These functions return the addresses of the fields that define the
310   // boundaries of the contiguous allocation area.  (These fields should be
311   // physically near to one another.)
312   virtual HeapWord* volatile* top_addr() const {
313     guarantee(false, "inline contiguous allocation not supported");
314     return NULL;
315   }
316   virtual HeapWord** end_addr() const {
317     guarantee(false, "inline contiguous allocation not supported");
318     return NULL;
319   }
320 
321   // Some heaps may be in an unparseable state at certain times between
322   // collections. This may be necessary for efficient implementation of
323   // certain allocation-related activities. Calling this function before
324   // attempting to parse a heap ensures that the heap is in a parsable
325   // state (provided other concurrent activity does not introduce
326   // unparsability). It is normally expected, therefore, that this
327   // method is invoked with the world stopped.
328   // NOTE: if you override this method, make sure you call
329   // super::ensure_parsability so that the non-generational
330   // part of the work gets done. See implementation of
331   // CollectedHeap::ensure_parsability and, for instance,
332   // that of GenCollectedHeap::ensure_parsability().
333   // The argument "retire_tlabs" controls whether existing TLABs
334   // are merely filled or also retired, thus preventing further
335   // allocation from them and necessitating allocation of new TLABs.
336   virtual void ensure_parsability(bool retire_tlabs);
337 
338   // The amount of space available for thread-local allocation buffers.
339   virtual size_t tlab_capacity(Thread *thr) const = 0;
340 
341   // The amount of used space for thread-local allocation buffers for the given thread.
342   virtual size_t tlab_used(Thread *thr) const = 0;
343 
344   virtual size_t max_tlab_size() const;
345 
346   // An estimate of the maximum allocation that could be performed
347   // for thread-local allocation buffers without triggering any
348   // collection or expansion activity.
349   virtual size_t unsafe_max_tlab_alloc(Thread *thr) const {
350     guarantee(false, "thread-local allocation buffers not supported");
351     return 0;
352   }
353 
354   // If a GC uses a stack watermark barrier, the stack processing is lazy, concurrent,
355   // incremental and cooperative. In order for that to work well, mechanisms that stop
356   // another thread might want to ensure its roots are in a sane state.
357   virtual bool uses_stack_watermark_barrier() const { return false; }
358 
359   // Perform a collection of the heap; intended for use in implementing
360   // "System.gc".  This probably implies as full a collection as the
361   // "CollectedHeap" supports.
362   virtual void collect(GCCause::Cause cause) = 0;
363 
364   // Perform a full collection
365   virtual void do_full_collection(bool clear_all_soft_refs) = 0;
366 
367   // This interface assumes that it's being called by the
368   // vm thread. It collects the heap assuming that the
369   // heap lock is already held and that we are executing in
370   // the context of the vm thread.
371   virtual void collect_as_vm_thread(GCCause::Cause cause);
372 
373   virtual MetaWord* satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,
374                                                        size_t size,
375                                                        Metaspace::MetadataType mdtype);
376 
377   // Returns "true" iff there is a stop-world GC in progress.  (I assume
378   // that it should answer "false" for the concurrent part of a concurrent
379   // collector -- dld).
380   bool is_gc_active() const { return _is_gc_active; }
381 
382   // Total number of GC collections (started)
383   unsigned int total_collections() const { return _total_collections; }
384   unsigned int total_full_collections() const { return _total_full_collections;}
385 
386   // Increment total number of GC collections (started)
387   void increment_total_collections(bool full = false) {
388     _total_collections++;
389     if (full) {
390       increment_total_full_collections();
391     }
392   }
393 
394   void increment_total_full_collections() { _total_full_collections++; }
395 
396   // Return the SoftRefPolicy for the heap;
397   virtual SoftRefPolicy* soft_ref_policy() = 0;
398 
399   virtual MemoryUsage memory_usage();
400   virtual GrowableArray<GCMemoryManager*> memory_managers() = 0;
401   virtual GrowableArray<MemoryPool*> memory_pools() = 0;
402 
403   // Iterate over all objects, calling "cl.do_object" on each.
404   virtual void object_iterate(ObjectClosure* cl) = 0;
405 
406  protected:
407   virtual ParallelObjectIteratorImpl* parallel_object_iterator(uint thread_num) {
408     return NULL;
409   }
410 
411  public:
412   // Keep alive an object that was loaded with AS_NO_KEEPALIVE.
413   virtual void keep_alive(oop obj) {}
414 
415   // Perform any cleanup actions necessary before allowing a verification.
416   virtual void prepare_for_verify() = 0;
417 
418   // Returns the longest time (in ms) that has elapsed since the last
419   // time that the whole heap has been examined by a garbage collection.
420   jlong millis_since_last_whole_heap_examined();
421   // GC should call this when the next whole heap analysis has completed to
422   // satisfy above requirement.
423   void record_whole_heap_examined_timestamp();
424 
425  private:
426   // Generate any dumps preceding or following a full gc
427   void full_gc_dump(GCTimer* timer, bool before);
428 
429   virtual void initialize_serviceability() = 0;
430 
431  public:
432   void pre_full_gc_dump(GCTimer* timer);
433   void post_full_gc_dump(GCTimer* timer);
434 
435   virtual VirtualSpaceSummary create_heap_space_summary();
436   GCHeapSummary create_heap_summary();
437 
438   MetaspaceSummary create_metaspace_summary();
439 
440   // Print heap information on the given outputStream.
441   virtual void print_on(outputStream* st) const = 0;
442   // The default behavior is to call print_on() on tty.
443   virtual void print() const;
444 
445   // Print more detailed heap information on the given
446   // outputStream. The default behavior is to call print_on(). It is
447   // up to each subclass to override it and add any additional output
448   // it needs.
449   virtual void print_extended_on(outputStream* st) const {
450     print_on(st);
451   }
452 
453   virtual void print_on_error(outputStream* st) const;
454 
455   // Used to print information about locations in the hs_err file.
456   virtual bool print_location(outputStream* st, void* addr) const = 0;
457 
458   // Iterator for all GC threads (other than VM thread)
459   virtual void gc_threads_do(ThreadClosure* tc) const = 0;
460 
461   // Print any relevant tracing info that flags imply.
462   // Default implementation does nothing.
463   virtual void print_tracing_info() const = 0;
464 
465   void print_heap_before_gc();
466   void print_heap_after_gc();
467 
468   // Registering and unregistering an nmethod (compiled code) with the heap.
469   virtual void register_nmethod(nmethod* nm) = 0;
470   virtual void unregister_nmethod(nmethod* nm) = 0;
471   // Callback for when nmethod is about to be deleted.
472   virtual void flush_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 NULL; }
495 
496   // Support for object pinning. This is used by JNI Get*Critical()
497   // and Release*Critical() family of functions. If supported, the GC
498   // must guarantee that pinned objects never move.
499   virtual bool supports_object_pinning() const;
500   virtual oop pin_object(JavaThread* thread, oop obj);
501   virtual void unpin_object(JavaThread* thread, oop obj);
502 
503   // Is the given object inside a CDS archive area?
504   virtual bool is_archived_object(oop object) const;
505 
506   // Support for loading objects from CDS archive into the heap
507   // (usually as a snapshot of the old generation).
508   virtual bool can_load_archived_objects() const { return false; }
509   virtual HeapWord* allocate_loaded_archive_space(size_t size) { return NULL; }
510   virtual void complete_loaded_archive_space(MemRegion archive_space) { }
511 
512   virtual bool is_oop(oop object) const;
513   // Non product verification and debugging.
514 #ifndef PRODUCT
515   // Support for PromotionFailureALot.  Return true if it's time to cause a
516   // promotion failure.  The no-argument version uses
517   // this->_promotion_failure_alot_count as the counter.
518   bool promotion_should_fail(volatile size_t* count);
519   bool promotion_should_fail();
520 
521   // Reset the PromotionFailureALot counters.  Should be called at the end of a
522   // GC in which promotion failure occurred.
523   void reset_promotion_should_fail(volatile size_t* count);
524   void reset_promotion_should_fail();
525 #endif  // #ifndef PRODUCT
526 };
527 
528 // Class to set and reset the GC cause for a CollectedHeap.
529 
530 class GCCauseSetter : StackObj {
531   CollectedHeap* _heap;
532   GCCause::Cause _previous_cause;
533  public:
534   GCCauseSetter(CollectedHeap* heap, GCCause::Cause cause) {
535     _heap = heap;
536     _previous_cause = _heap->gc_cause();
537     _heap->set_gc_cause(cause);
538   }
539 
540   ~GCCauseSetter() {
541     _heap->set_gc_cause(_previous_cause);
542   }
543 };
544 
545 #endif // SHARE_GC_SHARED_COLLECTEDHEAP_HPP