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