1 #ifdef USE_PRAGMA_IDENT_HDR
   2 #pragma ident "@(#)genCollectedHeap.hpp 1.106 07/07/22 22:36:34 JVM"
   3 #endif
   4 /*
   5  * Copyright 2000-2007 Sun Microsystems, Inc.  All Rights Reserved.
   6  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   7  *
   8  * This code is free software; you can redistribute it and/or modify it
   9  * under the terms of the GNU General Public License version 2 only, as
  10  * published by the Free Software Foundation.
  11  *
  12  * This code is distributed in the hope that it will be useful, but WITHOUT
  13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  * version 2 for more details (a copy is included in the LICENSE file that
  16  * accompanied this code).
  17  *
  18  * You should have received a copy of the GNU General Public License version
  19  * 2 along with this work; if not, write to the Free Software Foundation,
  20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  21  *
  22  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  23  * CA 95054 USA or visit www.sun.com if you need additional information or
  24  * have any questions.
  25  *  
  26  */
  27 
  28 class SubTasksDone;
  29 
  30 // A "GenCollectedHeap" is a SharedHeap that uses generational
  31 // collection.  It is represented with a sequence of Generation's.
  32 class GenCollectedHeap : public SharedHeap {
  33   friend class GenCollectorPolicy;
  34   friend class Generation;
  35   friend class DefNewGeneration;
  36   friend class TenuredGeneration;
  37   friend class ConcurrentMarkSweepGeneration;
  38   friend class CMSCollector;
  39   friend class GenMarkSweep;
  40   friend class VM_GenCollectForAllocation;
  41   friend class VM_GenCollectFull;
  42   friend class VM_GenCollectFullConcurrent;
  43   friend class VM_GC_HeapInspection;
  44   friend class VM_HeapDumper;
  45   friend class HeapInspection;
  46   friend class GCCauseSetter;
  47   friend class VMStructs;
  48 public:
  49   enum SomeConstants {
  50     max_gens = 10
  51   };
  52 
  53   friend class VM_PopulateDumpSharedSpace;
  54 
  55  protected:
  56   // Fields:
  57   static GenCollectedHeap* _gch;
  58 
  59  private:
  60   int _n_gens;
  61   Generation* _gens[max_gens];
  62   GenerationSpec** _gen_specs;
  63 
  64   // The generational collector policy.
  65   GenCollectorPolicy* _gen_policy;
  66 
  67   // If a generation would bail out of an incremental collection, 
  68   // it sets this flag.  If the flag is set, satisfy_failed_allocation 
  69   // will attempt allocating in all generations before doing a full GC.
  70   bool _incremental_collection_will_fail;
  71   bool _last_incremental_collection_failed;
  72 
  73   // In support of ExplicitGCInvokesConcurrent functionality 
  74   unsigned int _full_collections_completed;
  75 
  76   // Data structure for claiming the (potentially) parallel tasks in
  77   // (gen-specific) strong roots processing.
  78   SubTasksDone* _gen_process_strong_tasks;
  79 
  80   // In block contents verification, the number of header words to skip
  81   NOT_PRODUCT(static size_t _skip_header_HeapWords;)
  82 
  83   // GC is not allowed during the dump of the shared classes.  Keep track
  84   // of this in order to provide an reasonable error message when terminating.
  85   bool _preloading_shared_classes;
  86 
  87 protected:
  88   // Directs each generation up to and including "collectedGen" to recompute
  89   // its desired size.
  90   void compute_new_generation_sizes(int collectedGen);
  91 
  92   // Helper functions for allocation
  93   HeapWord* attempt_allocation(size_t size,
  94                                bool   is_tlab,
  95                                bool   first_only);
  96 
  97   // Helper function for two callbacks below.
  98   // Considers collection of the first max_level+1 generations.
  99   void do_collection(bool   full,
 100                      bool   clear_all_soft_refs,
 101                      size_t size,
 102                      bool   is_tlab,
 103                      int    max_level);
 104 
 105   // Callback from VM_GenCollectForAllocation operation.
 106   // This function does everything necessary/possible to satisfy an
 107   // allocation request that failed in the youngest generation that should
 108   // have handled it (including collection, expansion, etc.)
 109   HeapWord* satisfy_failed_allocation(size_t size, bool is_tlab);
 110 
 111   // Callback from VM_GenCollectFull operation.
 112   // Perform a full collection of the first max_level+1 generations.
 113   void do_full_collection(bool clear_all_soft_refs, int max_level);
 114 
 115   // Does the "cause" of GC indicate that
 116   // we absolutely __must__ clear soft refs?
 117   bool must_clear_all_soft_refs();
 118 
 119 public:
 120   GenCollectedHeap(GenCollectorPolicy *policy);
 121 
 122   GCStats* gc_stats(int level) const;
 123 
 124   // Returns JNI_OK on success
 125   virtual jint initialize();
 126   char* allocate(size_t alignment, PermanentGenerationSpec* perm_gen_spec,
 127                  size_t* _total_reserved, int* _n_covered_regions,
 128                  ReservedSpace* heap_rs);
 129   
 130   // Does operations required after initialization has been done.
 131   void post_initialize();
 132 
 133   // Initialize ("weak") refs processing support
 134   virtual void ref_processing_init();
 135 
 136   virtual CollectedHeap::Name kind() const {
 137     return CollectedHeap::GenCollectedHeap;
 138   }
 139 
 140   // The generational collector policy.
 141   GenCollectorPolicy* gen_policy() const { return _gen_policy; }
 142 
 143   // Adaptive size policy
 144   virtual AdaptiveSizePolicy* size_policy() { 
 145     return gen_policy()->size_policy();
 146   }
 147 
 148   size_t capacity() const;
 149   size_t used() const;
 150 
 151   // Save the "used_region" for generations level and lower,
 152   // and, if perm is true, for perm gen.
 153   void save_used_regions(int level, bool perm);
 154 
 155   size_t max_capacity() const;
 156 
 157   HeapWord* mem_allocate(size_t size,
 158                          bool   is_large_noref,
 159                          bool   is_tlab,
 160                          bool*  gc_overhead_limit_was_exceeded);
 161 
 162   // We may support a shared contiguous allocation area, if the youngest
 163   // generation does.
 164   bool supports_inline_contig_alloc() const;
 165   HeapWord** top_addr() const;
 166   HeapWord** end_addr() const;
 167 
 168   // Return an estimate of the maximum allocation that could be performed
 169   // without triggering any collection activity.  In a generational
 170   // collector, for example, this is probably the largest allocation that
 171   // could be supported in the youngest generation.  It is "unsafe" because
 172   // no locks are taken; the result should be treated as an approximation,
 173   // not a guarantee.
 174   size_t unsafe_max_alloc();
 175 
 176   // Does this heap support heap inspection? (+PrintClassHistogram)
 177   virtual bool supports_heap_inspection() const { return true; }
 178 
 179   // Perform a full collection of the heap; intended for use in implementing
 180   // "System.gc". This implies as full a collection as the CollectedHeap
 181   // supports. Caller does not hold the Heap_lock on entry.
 182   void collect(GCCause::Cause cause);
 183 
 184   // This interface assumes that it's being called by the
 185   // vm thread. It collects the heap assuming that the
 186   // heap lock is already held and that we are executing in
 187   // the context of the vm thread.
 188   void collect_as_vm_thread(GCCause::Cause cause);
 189 
 190   // The same as above but assume that the caller holds the Heap_lock.
 191   void collect_locked(GCCause::Cause cause);
 192 
 193   // Perform a full collection of the first max_level+1 generations.
 194   // Mostly used for testing purposes. Caller does not hold the Heap_lock on entry.
 195   void collect(GCCause::Cause cause, int max_level);
 196 
 197   // Returns "TRUE" iff "p" points into the allocated area of the heap.
 198   // The methods is_in(), is_in_closed_subset() and is_in_youngest() may
 199   // be expensive to compute in general, so, to prevent
 200   // their inadvertent use in product jvm's, we restrict their use to
 201   // assertion checking or verification only.
 202   bool is_in(const void* p) const;
 203 
 204   // override
 205   bool is_in_closed_subset(const void* p) const {
 206     if (UseConcMarkSweepGC) {
 207       return is_in_reserved(p);
 208     } else {
 209       return is_in(p);
 210     }
 211   }
 212 
 213   // Returns "TRUE" iff "p" points into the youngest generation.
 214   bool is_in_youngest(void* p);
 215 
 216   // Iteration functions.
 217   void oop_iterate(OopClosure* cl);
 218   void oop_iterate(MemRegion mr, OopClosure* cl);
 219   void object_iterate(ObjectClosure* cl);
 220   void object_iterate_since_last_GC(ObjectClosure* cl);
 221   Space* space_containing(const void* addr) const;
 222 
 223   // A CollectedHeap is divided into a dense sequence of "blocks"; that is,
 224   // each address in the (reserved) heap is a member of exactly
 225   // one block.  The defining characteristic of a block is that it is
 226   // possible to find its size, and thus to progress forward to the next
 227   // block.  (Blocks may be of different sizes.)  Thus, blocks may
 228   // represent Java objects, or they might be free blocks in a
 229   // free-list-based heap (or subheap), as long as the two kinds are 
 230   // distinguishable and the size of each is determinable.
 231 
 232   // Returns the address of the start of the "block" that contains the
 233   // address "addr".  We say "blocks" instead of "object" since some heaps
 234   // may not pack objects densely; a chunk may either be an object or a
 235   // non-object. 
 236   virtual HeapWord* block_start(const void* addr) const;
 237 
 238   // Requires "addr" to be the start of a chunk, and returns its size.
 239   // "addr + size" is required to be the start of a new chunk, or the end
 240   // of the active area of the heap. Assumes (and verifies in non-product
 241   // builds) that addr is in the allocated part of the heap and is
 242   // the start of a chunk.
 243   virtual size_t block_size(const HeapWord* addr) const;
 244 
 245   // Requires "addr" to be the start of a block, and returns "TRUE" iff
 246   // the block is an object. Assumes (and verifies in non-product
 247   // builds) that addr is in the allocated part of the heap and is
 248   // the start of a chunk.
 249   virtual bool block_is_obj(const HeapWord* addr) const;
 250 
 251   // Section on TLAB's.
 252   virtual bool supports_tlab_allocation() const;
 253   virtual size_t tlab_capacity(Thread* thr) const;
 254   virtual size_t unsafe_max_tlab_alloc(Thread* thr) const;
 255   virtual HeapWord* allocate_new_tlab(size_t size);
 256 
 257   // The "requestor" generation is performing some garbage collection 
 258   // action for which it would be useful to have scratch space.  The
 259   // requestor promises to allocate no more than "max_alloc_words" in any
 260   // older generation (via promotion say.)   Any blocks of space that can
 261   // be provided are returned as a list of ScratchBlocks, sorted by
 262   // decreasing size.
 263   ScratchBlock* gather_scratch(Generation* requestor, size_t max_alloc_words);
 264 
 265   size_t large_typearray_limit();
 266 
 267   // Ensure parsability: override
 268   virtual void ensure_parsability(bool retire_tlabs);
 269 
 270   // Time in ms since the longest time a collector ran in
 271   // in any generation.
 272   virtual jlong millis_since_last_gc();
 273 
 274   // Total number of full collections completed.
 275   unsigned int total_full_collections_completed() {
 276     assert(_full_collections_completed <= _total_full_collections,
 277            "Can't complete more collections than were started");
 278     return _full_collections_completed;
 279   }
 280 
 281   // Update above counter, as appropriate, at the end of a stop-world GC cycle
 282   unsigned int update_full_collections_completed();
 283   // Update above counter, as appropriate, at the end of a concurrent GC cycle
 284   unsigned int update_full_collections_completed(unsigned int count);
 285 
 286   // Update "time of last gc" for all constituent generations
 287   // to "now".
 288   void update_time_of_last_gc(jlong now) {
 289     for (int i = 0; i < _n_gens; i++) {
 290       _gens[i]->update_time_of_last_gc(now);
 291     }
 292     perm_gen()->update_time_of_last_gc(now);
 293   }
 294 
 295   // Update the gc statistics for each generation.
 296   // "level" is the level of the lastest collection
 297   void update_gc_stats(int current_level, bool full) {
 298     for (int i = 0; i < _n_gens; i++) {
 299       _gens[i]->update_gc_stats(current_level, full);
 300     }
 301     perm_gen()->update_gc_stats(current_level, full);
 302   }
 303 
 304   // Override.
 305   bool no_gc_in_progress() { return !is_gc_active(); }
 306 
 307   // Override.
 308   void prepare_for_verify();
 309 
 310   // Override.
 311   void verify(bool allow_dirty, bool silent);
 312 
 313   // Override.
 314   void print() const;
 315   void print_on(outputStream* st) const;
 316   virtual void print_gc_threads_on(outputStream* st) const;
 317   virtual void gc_threads_do(ThreadClosure* tc) const;
 318   virtual void print_tracing_info() const;
 319 
 320   // PrintGC, PrintGCDetails support
 321   void print_heap_change(size_t prev_used) const;
 322   void print_perm_heap_change(size_t perm_prev_used) const;
 323 
 324   // The functions below are helper functions that a subclass of
 325   // "CollectedHeap" can use in the implementation of its virtual
 326   // functions.
 327 
 328   class GenClosure : public StackObj {
 329    public:
 330     virtual void do_generation(Generation* gen) = 0;
 331   };
 332 
 333   // Apply "cl.do_generation" to all generations in the heap (not including
 334   // the permanent generation).  If "old_to_young" determines the order.
 335   void generation_iterate(GenClosure* cl, bool old_to_young);
 336 
 337   void space_iterate(SpaceClosure* cl);
 338 
 339   // Return "true" if all generations (but perm) have reached the
 340   // maximal committed limit that they can reach, without a garbage
 341   // collection.
 342   virtual bool is_maximal_no_gc() const;
 343   
 344   // Return the generation before "gen", or else NULL.
 345   Generation* prev_gen(Generation* gen) const {
 346     int l = gen->level();
 347     if (l == 0) return NULL;
 348     else return _gens[l-1];
 349   }
 350 
 351   // Return the generation after "gen", or else NULL.
 352   Generation* next_gen(Generation* gen) const {
 353     int l = gen->level() + 1;
 354     if (l == _n_gens) return NULL;
 355     else return _gens[l];
 356   }
 357 
 358   Generation* get_gen(int i) const {
 359     if (i >= 0 && i < _n_gens)
 360       return _gens[i];
 361     else
 362       return NULL;
 363   }
 364 
 365   int n_gens() const {
 366     assert(_n_gens == gen_policy()->number_of_generations(), "Sanity");
 367     return _n_gens;
 368   }
 369 
 370   // Convenience function to be used in situations where the heap type can be
 371   // asserted to be this type.
 372   static GenCollectedHeap* heap();
 373 
 374   void set_par_threads(int t);
 375   
 376 
 377   // Invoke the "do_oop" method of one of the closures "not_older_gens"
 378   // or "older_gens" on root locations for the generation at
 379   // "level".  (The "older_gens" closure is used for scanning references
 380   // from older generations; "not_older_gens" is used everywhere else.)
 381   // If "younger_gens_as_roots" is false, younger generations are
 382   // not scanned as roots; in this case, the caller must be arranging to
 383   // scan the younger generations itself.  (For example, a generation might
 384   // explicitly mark reachable objects in younger generations, to avoid
 385   // excess storage retention.)  If "collecting_perm_gen" is false, then
 386   // roots that may only contain references to permGen objects are not
 387   // scanned. The "so" argument determines which of the roots
 388   // the closure is applied to:
 389   // "SO_None" does none;
 390   // "SO_AllClasses" applies the closure to all entries in the SystemDictionary;
 391   // "SO_SystemClasses" to all the "system" classes and loaders;
 392   // "SO_Symbols_and_Strings" applies the closure to all entries in
 393   // SymbolsTable and StringTable.
 394   void gen_process_strong_roots(int level, bool younger_gens_as_roots,
 395                                 bool collecting_perm_gen,
 396                                 SharedHeap::ScanningOption so,
 397                                 OopsInGenClosure* older_gens,
 398                                 OopsInGenClosure* not_older_gens);
 399 
 400   // Apply "blk" to all the weak roots of the system.  These include
 401   // JNI weak roots, the code cache, system dictionary, symbol table,
 402   // string table, and referents of reachable weak refs. 
 403   void gen_process_weak_roots(OopClosure* root_closure,
 404                               OopClosure* non_root_closure);
 405 
 406   // Set the saved marks of generations, if that makes sense.
 407   // In particular, if any generation might iterate over the oops
 408   // in other generations, it should call this method.
 409   void save_marks();
 410 
 411   // Apply "cur->do_oop" or "older->do_oop" to all the oops in objects
 412   // allocated since the last call to save_marks in generations at or above
 413   // "level" (including the permanent generation.)  The "cur" closure is
 414   // applied to references in the generation at "level", and the "older"
 415   // closure to older (and permanent) generations.
 416 #define GCH_SINCE_SAVE_MARKS_ITERATE_DECL(OopClosureType, nv_suffix)    \
 417   void oop_since_save_marks_iterate(int level,                          \
 418                                     OopClosureType* cur,                \
 419                                     OopClosureType* older);
 420 
 421   ALL_SINCE_SAVE_MARKS_CLOSURES(GCH_SINCE_SAVE_MARKS_ITERATE_DECL)
 422 
 423 #undef GCH_SINCE_SAVE_MARKS_ITERATE_DECL
 424 
 425   // Returns "true" iff no allocations have occurred in any generation at
 426   // "level" or above (including the permanent generation) since the last
 427   // call to "save_marks".
 428   bool no_allocs_since_save_marks(int level);
 429 
 430   // If a generation bails out of an incremental collection, 
 431   // it sets this flag.
 432   bool incremental_collection_will_fail() {
 433     return _incremental_collection_will_fail;
 434   }
 435   void set_incremental_collection_will_fail() {
 436     _incremental_collection_will_fail = true;
 437   }
 438   void clear_incremental_collection_will_fail() {
 439     _incremental_collection_will_fail = false;
 440   }
 441 
 442   bool last_incremental_collection_failed() const {
 443     return _last_incremental_collection_failed;
 444   }
 445   void set_last_incremental_collection_failed() {
 446     _last_incremental_collection_failed = true;
 447   }
 448   void clear_last_incremental_collection_failed() {
 449     _last_incremental_collection_failed = false;
 450   }
 451 
 452   // Promotion of obj into gen failed.  Try to promote obj to higher non-perm
 453   // gens in ascending order; return the new location of obj if successful.
 454   // Otherwise, try expand-and-allocate for obj in each generation starting at
 455   // gen; return the new location of obj if successful.  Otherwise, return NULL.
 456   oop handle_failed_promotion(Generation* gen,
 457                               oop obj,
 458                               size_t obj_size,
 459                               oop* ref);
 460 
 461 private:
 462   // Accessor for memory state verification support
 463   NOT_PRODUCT(
 464     static size_t skip_header_HeapWords() { return _skip_header_HeapWords; }
 465   )
 466 
 467   // Override
 468   void check_for_non_bad_heap_word_value(HeapWord* addr,
 469     size_t size) PRODUCT_RETURN;
 470 
 471   // For use by mark-sweep.  As implemented, mark-sweep-compact is global
 472   // in an essential way: compaction is performed across generations, by
 473   // iterating over spaces.
 474   void prepare_for_compaction();
 475 
 476   // Perform a full collection of the first max_level+1 generations.
 477   // This is the low level interface used by the public versions of
 478   // collect() and collect_locked(). Caller holds the Heap_lock on entry.
 479   void collect_locked(GCCause::Cause cause, int max_level);
 480 
 481   // Returns success or failure.
 482   bool create_cms_collector();
 483 
 484   // In support of ExplicitGCInvokesConcurrent functionality
 485   bool should_do_concurrent_full_gc(GCCause::Cause cause);
 486   void collect_mostly_concurrent(GCCause::Cause cause);
 487 
 488 protected:
 489   virtual void gc_prologue(bool full);
 490   virtual void gc_epilogue(bool full);
 491   
 492 public:
 493   virtual void preload_and_dump(TRAPS) KERNEL_RETURN;
 494 };