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