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