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