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