1 /*
   2  * Copyright (c) 2000, 2018, 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_VM_GC_SHARED_GENCOLLECTEDHEAP_HPP
  26 #define SHARE_VM_GC_SHARED_GENCOLLECTEDHEAP_HPP
  27 
  28 #include "gc/shared/collectedHeap.hpp"
  29 #include "gc/shared/collectorPolicy.hpp"
  30 #include "gc/shared/generation.hpp"
  31 #include "gc/shared/softRefGenPolicy.hpp"
  32 
  33 class AdaptiveSizePolicy;
  34 class StrongRootsScope;
  35 class SubTasksDone;
  36 class WorkGang;
  37 
  38 // A "GenCollectedHeap" is a CollectedHeap that uses generational
  39 // collection.  It has two generations, young and old.
  40 class GenCollectedHeap : public CollectedHeap {
  41   friend class GenCollectorPolicy;
  42   friend class Generation;
  43   friend class DefNewGeneration;
  44   friend class TenuredGeneration;
  45   friend class ConcurrentMarkSweepGeneration;
  46   friend class CMSCollector;
  47   friend class GenMarkSweep;
  48   friend class VM_GenCollectForAllocation;
  49   friend class VM_GenCollectFull;
  50   friend class VM_GenCollectFullConcurrent;
  51   friend class VM_GC_HeapInspection;
  52   friend class VM_HeapDumper;
  53   friend class HeapInspection;
  54   friend class GCCauseSetter;
  55   friend class VMStructs;
  56 public:
  57   friend class VM_PopulateDumpSharedSpace;
  58 
  59   enum GenerationType {
  60     YoungGen,
  61     OldGen
  62   };
  63 
  64 private:
  65   Generation* _young_gen;
  66   Generation* _old_gen;
  67 
  68   // The singleton CardTable Remembered Set.
  69   CardTableRS* _rem_set;
  70 
  71   // The generational collector policy.
  72   GenCollectorPolicy* _gen_policy;
  73 
  74   SoftRefGenPolicy _soft_ref_gen_policy;
  75 
  76   // The sizing of the heap is controlled by a sizing policy.
  77   AdaptiveSizePolicy* _size_policy;
  78 
  79   // Indicates that the most recent previous incremental collection failed.
  80   // The flag is cleared when an action is taken that might clear the
  81   // condition that caused that incremental collection to fail.
  82   bool _incremental_collection_failed;
  83 
  84   // In support of ExplicitGCInvokesConcurrent functionality
  85   unsigned int _full_collections_completed;
  86 
  87   // Collects the given generation.
  88   void collect_generation(Generation* gen, bool full, size_t size, bool is_tlab,
  89                           bool run_verification, bool clear_soft_refs,
  90                           bool restore_marks_for_biased_locking);
  91 
  92   // Reserve aligned space for the heap as needed by the contained generations.
  93   char* allocate(size_t alignment, ReservedSpace* heap_rs);
  94 
  95   // Initialize ("weak") refs processing support
  96   void ref_processing_init();
  97 
  98 protected:
  99 
 100   // The set of potentially parallel tasks in root scanning.
 101   enum GCH_strong_roots_tasks {
 102     GCH_PS_Universe_oops_do,
 103     GCH_PS_JNIHandles_oops_do,
 104     GCH_PS_ObjectSynchronizer_oops_do,
 105     GCH_PS_FlatProfiler_oops_do,
 106     GCH_PS_Management_oops_do,
 107     GCH_PS_SystemDictionary_oops_do,
 108     GCH_PS_ClassLoaderDataGraph_oops_do,
 109     GCH_PS_jvmti_oops_do,
 110     GCH_PS_CodeCache_oops_do,
 111     GCH_PS_aot_oops_do,
 112     GCH_PS_younger_gens,
 113     // Leave this one last.
 114     GCH_PS_NumElements
 115   };
 116 
 117   // Data structure for claiming the (potentially) parallel tasks in
 118   // (gen-specific) roots processing.
 119   SubTasksDone* _process_strong_tasks;
 120 
 121   GCMemoryManager* _young_manager;
 122   GCMemoryManager* _old_manager;
 123 
 124   // Helper functions for allocation
 125   HeapWord* attempt_allocation(size_t size,
 126                                bool   is_tlab,
 127                                bool   first_only);
 128 
 129   // Helper function for two callbacks below.
 130   // Considers collection of the first max_level+1 generations.
 131   void do_collection(bool           full,
 132                      bool           clear_all_soft_refs,
 133                      size_t         size,
 134                      bool           is_tlab,
 135                      GenerationType max_generation);
 136 
 137   // Callback from VM_GenCollectForAllocation operation.
 138   // This function does everything necessary/possible to satisfy an
 139   // allocation request that failed in the youngest generation that should
 140   // have handled it (including collection, expansion, etc.)
 141   HeapWord* satisfy_failed_allocation(size_t size, bool is_tlab);
 142 
 143   // Callback from VM_GenCollectFull operation.
 144   // Perform a full collection of the first max_level+1 generations.
 145   virtual void do_full_collection(bool clear_all_soft_refs);
 146   void do_full_collection(bool clear_all_soft_refs, GenerationType max_generation);
 147 
 148   // Does the "cause" of GC indicate that
 149   // we absolutely __must__ clear soft refs?
 150   bool must_clear_all_soft_refs();
 151 
 152   GenCollectedHeap(GenCollectorPolicy *policy);
 153 
 154   virtual void check_gen_kinds() = 0;
 155 
 156 public:
 157 
 158   // Returns JNI_OK on success
 159   virtual jint initialize();
 160 
 161   void initialize_size_policy(size_t init_eden_size,
 162                               size_t init_promo_size,
 163                               size_t init_survivor_size);
 164 
 165   // Does operations required after initialization has been done.
 166   void post_initialize();
 167 
 168   Generation* young_gen() const { return _young_gen; }
 169   Generation* old_gen()   const { return _old_gen; }
 170 
 171   bool is_young_gen(const Generation* gen) const { return gen == _young_gen; }
 172   bool is_old_gen(const Generation* gen) const { return gen == _old_gen; }
 173 
 174   // The generational collector policy.
 175   GenCollectorPolicy* gen_policy() const { return _gen_policy; }
 176 
 177   virtual CollectorPolicy* collector_policy() const { return gen_policy(); }
 178 
 179   virtual SoftRefPolicy* soft_ref_policy() { return &_soft_ref_gen_policy; }
 180 
 181   // Adaptive size policy
 182   virtual AdaptiveSizePolicy* size_policy() {
 183     return _size_policy;
 184   }
 185 
 186   // Return the (conservative) maximum heap alignment
 187   static size_t conservative_max_heap_alignment() {
 188     return Generation::GenGrain;
 189   }
 190 
 191   size_t capacity() const;
 192   size_t used() const;
 193 
 194   // Save the "used_region" for both generations.
 195   void save_used_regions();
 196 
 197   size_t max_capacity() const;
 198 
 199   HeapWord* mem_allocate(size_t size, bool*  gc_overhead_limit_was_exceeded);
 200 
 201   // We may support a shared contiguous allocation area, if the youngest
 202   // generation does.
 203   bool supports_inline_contig_alloc() const;
 204   HeapWord* volatile* top_addr() const;
 205   HeapWord** end_addr() const;
 206 
 207   // Perform a full collection of the heap; intended for use in implementing
 208   // "System.gc". This implies as full a collection as the CollectedHeap
 209   // supports. Caller does not hold the Heap_lock on entry.
 210   virtual void collect(GCCause::Cause cause);
 211 
 212   // The same as above but assume that the caller holds the Heap_lock.
 213   void collect_locked(GCCause::Cause cause);
 214 
 215   // Perform a full collection of generations up to and including max_generation.
 216   // Mostly used for testing purposes. Caller does not hold the Heap_lock on entry.
 217   void collect(GCCause::Cause cause, GenerationType max_generation);
 218 
 219   // Returns "TRUE" iff "p" points into the committed areas of the heap.
 220   // The methods is_in(), is_in_closed_subset() and is_in_youngest() may
 221   // be expensive to compute in general, so, to prevent
 222   // their inadvertent use in product jvm's, we restrict their use to
 223   // assertion checking or verification only.
 224   bool is_in(const void* p) const;
 225 
 226   // Returns true if the reference is to an object in the reserved space
 227   // for the young generation.
 228   // Assumes the the young gen address range is less than that of the old gen.
 229   bool is_in_young(oop p);
 230 
 231 #ifdef ASSERT
 232   bool is_in_partial_collection(const void* p);
 233 #endif
 234 
 235   virtual bool is_scavengable(oop obj) {
 236     return is_in_young(obj);
 237   }
 238 
 239   // Optimized nmethod scanning support routines
 240   virtual void register_nmethod(nmethod* nm);
 241   virtual void verify_nmethod(nmethod* nmethod);
 242 
 243   // Iteration functions.
 244   void oop_iterate_no_header(OopClosure* cl);
 245   void oop_iterate(ExtendedOopClosure* cl);
 246   void object_iterate(ObjectClosure* cl);
 247   void safe_object_iterate(ObjectClosure* cl);
 248   Space* space_containing(const void* addr) const;
 249 
 250   // A CollectedHeap is divided into a dense sequence of "blocks"; that is,
 251   // each address in the (reserved) heap is a member of exactly
 252   // one block.  The defining characteristic of a block is that it is
 253   // possible to find its size, and thus to progress forward to the next
 254   // block.  (Blocks may be of different sizes.)  Thus, blocks may
 255   // represent Java objects, or they might be free blocks in a
 256   // free-list-based heap (or subheap), as long as the two kinds are
 257   // distinguishable and the size of each is determinable.
 258 
 259   // Returns the address of the start of the "block" that contains the
 260   // address "addr".  We say "blocks" instead of "object" since some heaps
 261   // may not pack objects densely; a chunk may either be an object or a
 262   // non-object.
 263   virtual HeapWord* block_start(const void* addr) const;
 264 
 265   // Requires "addr" to be the start of a chunk, and returns its size.
 266   // "addr + size" is required to be the start of a new chunk, or the end
 267   // of the active area of the heap. Assumes (and verifies in non-product
 268   // builds) that addr is in the allocated part of the heap and is
 269   // the start of a chunk.
 270   virtual size_t block_size(const HeapWord* addr) const;
 271 
 272   // Requires "addr" to be the start of a block, and returns "TRUE" iff
 273   // the block is an object. Assumes (and verifies in non-product
 274   // builds) that addr is in the allocated part of the heap and is
 275   // the start of a chunk.
 276   virtual bool block_is_obj(const HeapWord* addr) const;
 277 
 278   // Section on TLAB's.
 279   virtual bool supports_tlab_allocation() const;
 280   virtual size_t tlab_capacity(Thread* thr) const;
 281   virtual size_t tlab_used(Thread* thr) const;
 282   virtual size_t unsafe_max_tlab_alloc(Thread* thr) const;
 283   virtual HeapWord* allocate_new_tlab(size_t size);
 284 
 285   // The "requestor" generation is performing some garbage collection
 286   // action for which it would be useful to have scratch space.  The
 287   // requestor promises to allocate no more than "max_alloc_words" in any
 288   // older generation (via promotion say.)   Any blocks of space that can
 289   // be provided are returned as a list of ScratchBlocks, sorted by
 290   // decreasing size.
 291   ScratchBlock* gather_scratch(Generation* requestor, size_t max_alloc_words);
 292   // Allow each generation to reset any scratch space that it has
 293   // contributed as it needs.
 294   void release_scratch();
 295 
 296   // Ensure parsability: override
 297   virtual void ensure_parsability(bool retire_tlabs);
 298 
 299   // Time in ms since the longest time a collector ran in
 300   // in any generation.
 301   virtual jlong millis_since_last_gc();
 302 
 303   // Total number of full collections completed.
 304   unsigned int total_full_collections_completed() {
 305     assert(_full_collections_completed <= _total_full_collections,
 306            "Can't complete more collections than were started");
 307     return _full_collections_completed;
 308   }
 309 
 310   // Update above counter, as appropriate, at the end of a stop-world GC cycle
 311   unsigned int update_full_collections_completed();
 312   // Update above counter, as appropriate, at the end of a concurrent GC cycle
 313   unsigned int update_full_collections_completed(unsigned int count);
 314 
 315   // Update "time of last gc" for all generations to "now".
 316   void update_time_of_last_gc(jlong now) {
 317     _young_gen->update_time_of_last_gc(now);
 318     _old_gen->update_time_of_last_gc(now);
 319   }
 320 
 321   // Update the gc statistics for each generation.
 322   void update_gc_stats(Generation* current_generation, bool full) {
 323     _old_gen->update_gc_stats(current_generation, full);
 324   }
 325 
 326   bool no_gc_in_progress() { return !is_gc_active(); }
 327 
 328   // Override.
 329   void prepare_for_verify();
 330 
 331   // Override.
 332   void verify(VerifyOption option);
 333 
 334   // Override.
 335   virtual void print_on(outputStream* st) const;
 336   virtual void print_gc_threads_on(outputStream* st) const;
 337   virtual void gc_threads_do(ThreadClosure* tc) const;
 338   virtual void print_tracing_info() const;
 339 
 340   void print_heap_change(size_t young_prev_used, size_t old_prev_used) const;
 341 
 342   // The functions below are helper functions that a subclass of
 343   // "CollectedHeap" can use in the implementation of its virtual
 344   // functions.
 345 
 346   class GenClosure : public StackObj {
 347    public:
 348     virtual void do_generation(Generation* gen) = 0;
 349   };
 350 
 351   // Apply "cl.do_generation" to all generations in the heap
 352   // If "old_to_young" determines the order.
 353   void generation_iterate(GenClosure* cl, bool old_to_young);
 354 
 355   // Return "true" if all generations have reached the
 356   // maximal committed limit that they can reach, without a garbage
 357   // collection.
 358   virtual bool is_maximal_no_gc() const;
 359 
 360   // This function returns the CardTableRS object that allows us to scan
 361   // generations in a fully generational heap.
 362   CardTableRS* rem_set() { return _rem_set; }
 363 
 364   // Convenience function to be used in situations where the heap type can be
 365   // asserted to be this type.
 366   static GenCollectedHeap* heap();
 367 
 368   // The ScanningOption determines which of the roots
 369   // the closure is applied to:
 370   // "SO_None" does none;
 371   enum ScanningOption {
 372     SO_None                =  0x0,
 373     SO_AllCodeCache        =  0x8,
 374     SO_ScavengeCodeCache   = 0x10
 375   };
 376 
 377  protected:
 378   void process_roots(StrongRootsScope* scope,
 379                      ScanningOption so,
 380                      OopClosure* strong_roots,
 381                      OopClosure* weak_roots,
 382                      CLDClosure* strong_cld_closure,
 383                      CLDClosure* weak_cld_closure,
 384                      CodeBlobToOopClosure* code_roots);
 385 
 386   void process_string_table_roots(StrongRootsScope* scope,
 387                                   OopClosure* root_closure);
 388 
 389   // Accessor for memory state verification support
 390   NOT_PRODUCT(
 391     virtual size_t skip_header_HeapWords() { return 0; }
 392   )
 393 
 394   virtual void gc_prologue(bool full);
 395   virtual void gc_epilogue(bool full);
 396 
 397  public:
 398   void young_process_roots(StrongRootsScope* scope,
 399                            OopsInGenClosure* root_closure,
 400                            OopsInGenClosure* old_gen_closure,
 401                            CLDClosure* cld_closure);
 402 
 403   void full_process_roots(StrongRootsScope* scope,
 404                           bool is_adjust_phase,
 405                           ScanningOption so,
 406                           bool only_strong_roots,
 407                           OopsInGenClosure* root_closure,
 408                           CLDClosure* cld_closure);
 409 
 410   // Apply "root_closure" to all the weak roots of the system.
 411   // These include JNI weak roots, string table,
 412   // and referents of reachable weak refs.
 413   void gen_process_weak_roots(OopClosure* root_closure);
 414 
 415   // Set the saved marks of generations, if that makes sense.
 416   // In particular, if any generation might iterate over the oops
 417   // in other generations, it should call this method.
 418   void save_marks();
 419 
 420   // Apply "cur->do_oop" or "older->do_oop" to all the oops in objects
 421   // allocated since the last call to save_marks in generations at or above
 422   // "level".  The "cur" closure is
 423   // applied to references in the generation at "level", and the "older"
 424   // closure to older generations.
 425 #define GCH_SINCE_SAVE_MARKS_ITERATE_DECL(OopClosureType, nv_suffix)    \
 426   void oop_since_save_marks_iterate(GenerationType start_gen,           \
 427                                     OopClosureType* cur,                \
 428                                     OopClosureType* older);
 429 
 430   ALL_SINCE_SAVE_MARKS_CLOSURES(GCH_SINCE_SAVE_MARKS_ITERATE_DECL)
 431 
 432 #undef GCH_SINCE_SAVE_MARKS_ITERATE_DECL
 433 
 434   // Returns "true" iff no allocations have occurred since the last
 435   // call to "save_marks".
 436   bool no_allocs_since_save_marks();
 437 
 438   // Returns true if an incremental collection is likely to fail.
 439   // We optionally consult the young gen, if asked to do so;
 440   // otherwise we base our answer on whether the previous incremental
 441   // collection attempt failed with no corrective action as of yet.
 442   bool incremental_collection_will_fail(bool consult_young) {
 443     // The first disjunct remembers if an incremental collection failed, even
 444     // when we thought (second disjunct) that it would not.
 445     return incremental_collection_failed() ||
 446            (consult_young && !_young_gen->collection_attempt_is_safe());
 447   }
 448 
 449   // If a generation bails out of an incremental collection,
 450   // it sets this flag.
 451   bool incremental_collection_failed() const {
 452     return _incremental_collection_failed;
 453   }
 454   void set_incremental_collection_failed() {
 455     _incremental_collection_failed = true;
 456   }
 457   void clear_incremental_collection_failed() {
 458     _incremental_collection_failed = false;
 459   }
 460 
 461   // Promotion of obj into gen failed.  Try to promote obj to higher
 462   // gens in ascending order; return the new location of obj if successful.
 463   // Otherwise, try expand-and-allocate for obj in both the young and old
 464   // generation; return the new location of obj if successful.  Otherwise, return NULL.
 465   oop handle_failed_promotion(Generation* old_gen,
 466                               oop obj,
 467                               size_t obj_size);
 468 
 469 
 470 private:
 471   // Return true if an allocation should be attempted in the older generation
 472   // if it fails in the younger generation.  Return false, otherwise.
 473   bool should_try_older_generation_allocation(size_t word_size) const;
 474 
 475   // Try to allocate space by expanding the heap.
 476   HeapWord* expand_heap_and_allocate(size_t size, bool is_tlab);
 477 
 478   HeapWord* mem_allocate_work(size_t size,
 479                               bool is_tlab,
 480                               bool* gc_overhead_limit_was_exceeded);
 481 
 482   // Override
 483   void check_for_non_bad_heap_word_value(HeapWord* addr,
 484     size_t size) PRODUCT_RETURN;
 485 
 486   // For use by mark-sweep.  As implemented, mark-sweep-compact is global
 487   // in an essential way: compaction is performed across generations, by
 488   // iterating over spaces.
 489   void prepare_for_compaction();
 490 
 491   // Perform a full collection of the generations up to and including max_generation.
 492   // This is the low level interface used by the public versions of
 493   // collect() and collect_locked(). Caller holds the Heap_lock on entry.
 494   void collect_locked(GCCause::Cause cause, GenerationType max_generation);
 495 
 496   // Save the tops of the spaces in all generations
 497   void record_gen_tops_before_GC() PRODUCT_RETURN;
 498 };
 499 
 500 #endif // SHARE_VM_GC_SHARED_GENCOLLECTEDHEAP_HPP