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