1 #ifdef USE_PRAGMA_IDENT_HDR
   2 #pragma ident "@(#)collectedHeap.hpp    1.58 07/09/07 10:56:50 JVM"
   3 #endif
   4 /*
   5  * Copyright 2001-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 // A "CollectedHeap" is an implementation of a java heap for HotSpot.  This
  29 // is an abstract class: there may be many different kinds of heaps.  This
  30 // class defines the functions that a heap must implement, and contains
  31 // infrastructure common to all heaps.
  32 
  33 class BarrierSet;
  34 class ThreadClosure;
  35 class AdaptiveSizePolicy;
  36 class Thread;
  37 
  38 //
  39 // CollectedHeap
  40 //   SharedHeap
  41 //     GenCollectedHeap
  42 //     G1CollectedHeap
  43 //   ParallelScavengeHeap
  44 //
  45 class CollectedHeap : public CHeapObj {
  46   friend class VMStructs;
  47   friend class IsGCActiveMark; // Block structured external access to _is_gc_active
  48 
  49 #ifdef ASSERT
  50   static int       _fire_out_of_memory_count;
  51 #endif
  52 
  53  protected:
  54   MemRegion _reserved;
  55   BarrierSet* _barrier_set;
  56   bool _is_gc_active;
  57   unsigned int _total_collections;          // ... started
  58   unsigned int _total_full_collections;     // ... started
  59   size_t _max_heap_capacity;
  60   NOT_PRODUCT(volatile size_t _promotion_failure_alot_count;)
  61   NOT_PRODUCT(volatile size_t _promotion_failure_alot_gc_number;)
  62 
  63   // Reason for current garbage collection.  Should be set to
  64   // a value reflecting no collection between collections.
  65   GCCause::Cause _gc_cause;
  66   GCCause::Cause _gc_lastcause;
  67   PerfStringVariable* _perf_gc_cause;
  68   PerfStringVariable* _perf_gc_lastcause;
  69 
  70   // Constructor
  71   CollectedHeap();
  72 
  73   // Create a new tlab
  74   virtual HeapWord* allocate_new_tlab(size_t size);
  75 
  76   // Fix up tlabs to make the heap well-formed again,
  77   // optionally retiring the tlabs.
  78   virtual void fill_all_tlabs(bool retire);
  79 
  80   // Accumulate statistics on all tlabs.
  81   virtual void accumulate_statistics_all_tlabs();
  82 
  83   // Reinitialize tlabs before resuming mutators.
  84   virtual void resize_all_tlabs();
  85 
  86   debug_only(static void check_for_valid_allocation_state();)
  87 
  88  protected:
  89   // Allocate from the current thread's TLAB, with broken-out slow path.
  90   inline static HeapWord* allocate_from_tlab(Thread* thread, size_t size);
  91   static HeapWord* allocate_from_tlab_slow(Thread* thread, size_t size);
  92 
  93   // Allocate an uninitialized block of the given size, or returns NULL if
  94   // this is impossible.
  95   inline static HeapWord* common_mem_allocate_noinit(size_t size, bool is_noref, TRAPS);
  96 
  97   // Like allocate_init, but the block returned by a successful allocation
  98   // is guaranteed initialized to zeros.
  99   inline static HeapWord* common_mem_allocate_init(size_t size, bool is_noref, TRAPS);
 100 
 101   // Same as common_mem version, except memory is allocated in the permanent area
 102   // If there is no permanent area, revert to common_mem_allocate_noinit
 103   inline static HeapWord* common_permanent_mem_allocate_noinit(size_t size, TRAPS);
 104 
 105   // Same as common_mem version, except memory is allocated in the permanent area
 106   // If there is no permanent area, revert to common_mem_allocate_init
 107   inline static HeapWord* common_permanent_mem_allocate_init(size_t size, TRAPS);
 108 
 109   // Helper functions for (VM) allocation.
 110   inline static void post_allocation_setup_common(KlassHandle klass,
 111                                                   HeapWord* obj, size_t size); 
 112   inline static void post_allocation_setup_no_klass_install(KlassHandle klass,
 113                                                             HeapWord* objPtr,
 114                                                             size_t size);
 115 
 116   inline static void post_allocation_setup_obj(KlassHandle klass,
 117                                                HeapWord* obj, size_t size);
 118 
 119   inline static void post_allocation_setup_array(KlassHandle klass,
 120                                                  HeapWord* obj, size_t size,
 121                                                  int length);
 122 
 123   // Clears an allocated object.
 124   inline static void init_obj(HeapWord* obj, size_t size);
 125 
 126   // Verification functions
 127   virtual void check_for_bad_heap_word_value(HeapWord* addr, size_t size)
 128     PRODUCT_RETURN;
 129   virtual void check_for_non_bad_heap_word_value(HeapWord* addr, size_t size)
 130     PRODUCT_RETURN;
 131 
 132  public:
 133   enum Name {
 134     Abstract,
 135     SharedHeap,
 136     GenCollectedHeap,
 137     ParallelScavengeHeap,
 138     G1CollectedHeap
 139   };
 140 
 141   virtual CollectedHeap::Name kind() const { return CollectedHeap::Abstract; }
 142 
 143   /**
 144    * Returns JNI error code JNI_ENOMEM if memory could not be allocated, 
 145    * and JNI_OK on success.
 146    */
 147   virtual jint initialize() = 0;
 148 
 149   // In many heaps, there will be a need to perform some initialization activities
 150   // after the Universe is fully formed, but before general heap allocation is allowed.
 151   // This is the correct place to place such initialization methods.
 152   virtual void post_initialize() = 0;
 153 
 154   MemRegion reserved_region() const { return _reserved; }
 155 
 156   // Return the number of bytes currently reserved, committed, and used,
 157   // respectively, for holding objects.
 158   size_t reserved_obj_bytes() const { return _reserved.byte_size(); }
 159 
 160   // Future cleanup here. The following functions should specify bytes or
 161   // heapwords as part of their signature.
 162   virtual size_t capacity() const = 0;
 163   virtual size_t used() const = 0;
 164 
 165   // Return "true" if the part of the heap that allocates Java
 166   // objects has reached the maximal committed limit that it can
 167   // reach, without a garbage collection.
 168   virtual bool is_maximal_no_gc() const = 0;
 169   
 170   virtual size_t permanent_capacity() const = 0;
 171   virtual size_t permanent_used() const = 0;
 172 
 173   // Support for java.lang.Runtime.maxMemory():  return the maximum amount of
 174   // memory that the vm could make available for storing 'normal' java objects.
 175   // This is based on the reserved address space, but should not include space
 176   // that the vm uses internally for bookkeeping or temporary storage (e.g.,
 177   // perm gen space or, in the case of the young gen, one of the survivor
 178   // spaces).
 179   virtual size_t max_capacity() const = 0;
 180 
 181   // Returns "TRUE" if "p" points into the reserved area of the heap.
 182   bool is_in_reserved(const void* p) const {
 183     return _reserved.contains(p);
 184   }
 185 
 186   bool is_in_reserved_or_null(const void* p) const {
 187     return p == NULL || is_in_reserved(p);
 188   }
 189 
 190   // Returns "TRUE" if "p" points to the head of an allocated object in the
 191   // heap. Since this method can be expensive in general, we restrict its
 192   // use to assertion checking only.
 193   virtual bool is_in(const void* p) const = 0;
 194 
 195   bool is_in_or_null(const void* p) const {
 196     return p == NULL || is_in(p);
 197   }
 198 
 199   // Let's define some terms: a "closed" subset of a heap is one that
 200   // 
 201   // 1) contains all currently-allocated objects, and
 202   // 
 203   // 2) is closed under reference: no object in the closed subset
 204   //    references one outside the closed subset.
 205   //
 206   // Membership in a heap's closed subset is useful for assertions.
 207   // Clearly, the entire heap is a closed subset, so the default
 208   // implementation is to use "is_in_reserved".  But this may not be too
 209   // liberal to perform useful checking.  Also, the "is_in" predicate
 210   // defines a closed subset, but may be too expensive, since "is_in"
 211   // verifies that its argument points to an object head.  The
 212   // "closed_subset" method allows a heap to define an intermediate
 213   // predicate, allowing more precise checking than "is_in_reserved" at
 214   // lower cost than "is_in."
 215 
 216   // One important case is a heap composed of disjoint contiguous spaces,
 217   // such as the Garbage-First collector.  Such heaps have a convenient
 218   // closed subset consisting of the allocated portions of those
 219   // contiguous spaces.
 220 
 221   // Return "TRUE" iff the given pointer points into the heap's defined
 222   // closed subset (which defaults to the entire heap).
 223   virtual bool is_in_closed_subset(const void* p) const {
 224     return is_in_reserved(p);
 225   }
 226 
 227   bool is_in_closed_subset_or_null(const void* p) const {
 228     return p == NULL || is_in_closed_subset(p);
 229   }
 230 
 231   // Returns "TRUE" if "p" is allocated as "permanent" data.
 232   // If the heap does not use "permanent" data, returns the same
 233   // value is_in_reserved() would return.
 234   // NOTE: this actually returns true if "p" is in reserved space
 235   // for the space not that it is actually allocated (i.e. in committed
 236   // space). If you need the more conservative answer use is_permanent().
 237   virtual bool is_in_permanent(const void *p) const = 0;
 238 
 239   // Returns "TRUE" if "p" is in the committed area of  "permanent" data.
 240   // If the heap does not use "permanent" data, returns the same
 241   // value is_in() would return.
 242   virtual bool is_permanent(const void *p) const = 0;
 243 
 244   bool is_in_permanent_or_null(const void *p) const {
 245     return p == NULL || is_in_permanent(p);
 246   }
 247 
 248   // Returns "TRUE" if "p" is a method oop in the
 249   // current heap, with high probability. This predicate
 250   // is not stable, in general.
 251   bool is_valid_method(oop p) const;
 252 
 253   void set_gc_cause(GCCause::Cause v) {
 254      if (UsePerfData) {
 255        _gc_lastcause = _gc_cause;
 256        _perf_gc_lastcause->set_value(GCCause::to_string(_gc_lastcause));
 257        _perf_gc_cause->set_value(GCCause::to_string(v));
 258      }
 259     _gc_cause = v;
 260   }
 261   GCCause::Cause gc_cause() { return _gc_cause; }
 262 
 263   // Preload classes into the shared portion of the heap, and then dump
 264   // that data to a file so that it can be loaded directly by another
 265   // VM (then terminate).
 266   virtual void preload_and_dump(TRAPS) { ShouldNotReachHere(); }
 267 
 268   // General obj/array allocation facilities.
 269   inline static oop obj_allocate(KlassHandle klass, int size, TRAPS);
 270   inline static oop array_allocate(KlassHandle klass, int size, int length, TRAPS);
 271   inline static oop large_typearray_allocate(KlassHandle klass, int size, int length, TRAPS);
 272 
 273   // Special obj/array allocation facilities.
 274   // Some heaps may want to manage "permanent" data uniquely. These default
 275   // to the general routines if the heap does not support such handling.
 276   inline static oop permanent_obj_allocate(KlassHandle klass, int size, TRAPS);
 277   // permanent_obj_allocate_no_klass_install() does not do the installation of 
 278   // the klass pointer in the newly created object (as permanent_obj_allocate() 
 279   // above does).  This allows for a delay in the installation of the klass
 280   // pointer that is needed during the create of klassKlass's.  The
 281   // method post_allocation_install_obj_klass() is used to install the
 282   // klass pointer.
 283   inline static oop permanent_obj_allocate_no_klass_install(KlassHandle klass,
 284                                                             int size, 
 285                                                             TRAPS);
 286   inline static void post_allocation_install_obj_klass(KlassHandle klass, 
 287                                                        oop obj,
 288                                                        int size);
 289   inline static oop permanent_array_allocate(KlassHandle klass, int size, int length, TRAPS);
 290 
 291   // Raw memory allocation facilities
 292   // The obj and array allocate methods are covers for these methods.
 293   // The permanent allocation method should default to mem_allocate if
 294   // permanent memory isn't supported.
 295   virtual HeapWord* mem_allocate(size_t size, 
 296                                  bool is_noref, 
 297                                  bool is_tlab, 
 298                                  bool* gc_overhead_limit_was_exceeded) = 0;
 299   virtual HeapWord* permanent_mem_allocate(size_t size) = 0;
 300 
 301   // The boundary between a "large" and "small" array of primitives, in words.
 302   virtual size_t large_typearray_limit() = 0;
 303 
 304   // Some heaps may offer a contiguous region for shared non-blocking
 305   // allocation, via inlined code (by exporting the address of the top and
 306   // end fields defining the extent of the contiguous allocation region.)
 307 
 308   // This function returns "true" iff the heap supports this kind of
 309   // allocation.  (Default is "no".)
 310   virtual bool supports_inline_contig_alloc() const {
 311     return false;
 312   }
 313   // These functions return the addresses of the fields that define the
 314   // boundaries of the contiguous allocation area.  (These fields should be
 315   // physically near to one another.)
 316   virtual HeapWord** top_addr() const {
 317     guarantee(false, "inline contiguous allocation not supported");
 318     return NULL;
 319   }
 320   virtual HeapWord** end_addr() const {
 321     guarantee(false, "inline contiguous allocation not supported");
 322     return NULL;
 323   }
 324 
 325   // Some heaps may be in an unparseable state at certain times between
 326   // collections. This may be necessary for efficient implementation of
 327   // certain allocation-related activities. Calling this function before
 328   // attempting to parse a heap ensures that the heap is in a parsable
 329   // state (provided other concurrent activity does not introduce
 330   // unparsability). It is normally expected, therefore, that this
 331   // method is invoked with the world stopped.
 332   // NOTE: if you override this method, make sure you call
 333   // super::ensure_parsability so that the non-generational
 334   // part of the work gets done. See implementation of
 335   // CollectedHeap::ensure_parsability and, for instance,
 336   // that of GenCollectedHeap::ensure_parsability().
 337   // The argument "retire_tlabs" controls whether existing TLABs
 338   // are merely filled or also retired, thus preventing further
 339   // allocation from them and necessitating allocation of new TLABs.
 340   virtual void ensure_parsability(bool retire_tlabs);
 341 
 342   // Return an estimate of the maximum allocation that could be performed
 343   // without triggering any collection or expansion activity.  In a
 344   // generational collector, for example, this is probably the largest
 345   // allocation that could be supported (without expansion) in the youngest
 346   // generation.  It is "unsafe" because no locks are taken; the result
 347   // should be treated as an approximation, not a guarantee, for use in
 348   // heuristic resizing decisions.
 349   virtual size_t unsafe_max_alloc() = 0;
 350 
 351   // Section on thread-local allocation buffers (TLABs)
 352   // If the heap supports thread-local allocation buffers, it should override
 353   // the following methods:
 354   // Returns "true" iff the heap supports thread-local allocation buffers.
 355   // The default is "no".  
 356   virtual bool supports_tlab_allocation() const {
 357     return false;
 358   }
 359   // The amount of space available for thread-local allocation buffers.
 360   virtual size_t tlab_capacity(Thread *thr) const {
 361     guarantee(false, "thread-local allocation buffers not supported");
 362     return 0;
 363   }
 364   // An estimate of the maximum allocation that could be performed
 365   // for thread-local allocation buffers without triggering any
 366   // collection or expansion activity.
 367   virtual size_t unsafe_max_tlab_alloc(Thread *thr) const {
 368     guarantee(false, "thread-local allocation buffers not supported");
 369     return 0;
 370   }
 371   // Can a compiler initialize a new object without store barriers?
 372   // This permission only extends from the creation of a new object
 373   // via a TLAB up to the first subsequent safepoint.
 374   virtual bool can_elide_tlab_store_barriers() const {
 375     guarantee(kind() < CollectedHeap::G1CollectedHeap, "else change or refactor this");
 376     return true;
 377   }
 378   // If a compiler is eliding store barriers for TLAB-allocated objects,
 379   // there is probably a corresponding slow path which can produce
 380   // an object allocated anywhere.  The compiler's runtime support
 381   // promises to call this function on such a slow-path-allocated
 382   // object before performing initializations that have elided
 383   // store barriers.  Returns new_obj, or maybe a safer copy thereof.
 384   virtual oop new_store_barrier(oop new_obj);
 385 
 386   // Can a compiler elide a store barrier when it writes
 387   // a permanent oop into the heap?  Applies when the compiler
 388   // is storing x to the heap, where x->is_perm() is true.
 389   virtual bool can_elide_permanent_oop_store_barriers() const;
 390   
 391   // Does this heap support heap inspection (+PrintClassHistogram?)
 392   virtual bool supports_heap_inspection() const {
 393     return false;   // Until RFE 5023697 is implemented
 394   }
 395 
 396   // Perform a collection of the heap; intended for use in implementing
 397   // "System.gc".  This probably implies as full a collection as the
 398   // "CollectedHeap" supports.
 399   virtual void collect(GCCause::Cause cause) = 0;
 400 
 401   // This interface assumes that it's being called by the
 402   // vm thread. It collects the heap assuming that the
 403   // heap lock is already held and that we are executing in
 404   // the context of the vm thread.
 405   virtual void collect_as_vm_thread(GCCause::Cause cause) = 0;
 406 
 407   // Returns the barrier set for this heap
 408   BarrierSet* barrier_set() { return _barrier_set; }
 409 
 410   // Returns "true" iff there is a stop-world GC in progress.  (I assume
 411   // that it should answer "false" for the concurrent part of a concurrent
 412   // collector -- dld).
 413   bool is_gc_active() const { return _is_gc_active; }
 414 
 415   // Total number of GC collections (started)
 416   unsigned int total_collections() const { return _total_collections; }
 417   unsigned int total_full_collections() const { return _total_full_collections;}
 418 
 419   // Increment total number of GC collections (started)
 420   // Should be protected but used by PSMarkSweep - cleanup for 1.4.2
 421   void increment_total_collections(bool full = false) {
 422     _total_collections++;
 423     if (full) {
 424       increment_total_full_collections();
 425     }
 426   }
 427 
 428   void increment_total_full_collections() { _total_full_collections++; }
 429 
 430   // Return the AdaptiveSizePolicy for the heap.
 431   virtual AdaptiveSizePolicy* size_policy() = 0;
 432 
 433   // Iterate over all the ref-containing fields of all objects, calling
 434   // "cl.do_oop" on each. This includes objects in permanent memory.
 435   virtual void oop_iterate(OopClosure* cl) = 0;
 436 
 437   // Iterate over all objects, calling "cl.do_object" on each.
 438   // This includes objects in permanent memory.
 439   virtual void object_iterate(ObjectClosure* cl) = 0;
 440 
 441   // Behaves the same as oop_iterate, except only traverses
 442   // interior pointers contained in permanent memory. If there
 443   // is no permanent memory, does nothing.
 444   virtual void permanent_oop_iterate(OopClosure* cl) = 0;
 445 
 446   // Behaves the same as object_iterate, except only traverses
 447   // object contained in permanent memory. If there is no
 448   // permanent memory, does nothing.
 449   virtual void permanent_object_iterate(ObjectClosure* cl) = 0;
 450 
 451   // NOTE! There is no requirement that a collector implement these
 452   // functions.
 453   //
 454   // A CollectedHeap is divided into a dense sequence of "blocks"; that is,
 455   // each address in the (reserved) heap is a member of exactly
 456   // one block.  The defining characteristic of a block is that it is
 457   // possible to find its size, and thus to progress forward to the next
 458   // block.  (Blocks may be of different sizes.)  Thus, blocks may
 459   // represent Java objects, or they might be free blocks in a
 460   // free-list-based heap (or subheap), as long as the two kinds are 
 461   // distinguishable and the size of each is determinable.
 462 
 463   // Returns the address of the start of the "block" that contains the
 464   // address "addr".  We say "blocks" instead of "object" since some heaps
 465   // may not pack objects densely; a chunk may either be an object or a
 466   // non-object. 
 467   virtual HeapWord* block_start(const void* addr) const = 0;
 468 
 469   // Requires "addr" to be the start of a chunk, and returns its size.
 470   // "addr + size" is required to be the start of a new chunk, or the end
 471   // of the active area of the heap.
 472   virtual size_t block_size(const HeapWord* addr) const = 0;
 473 
 474   // Requires "addr" to be the start of a block, and returns "TRUE" iff
 475   // the block is an object.
 476   virtual bool block_is_obj(const HeapWord* addr) const = 0;
 477 
 478   // Returns the longest time (in ms) that has elapsed since the last
 479   // time that any part of the heap was examined by a garbage collection.
 480   virtual jlong millis_since_last_gc() = 0;
 481 
 482   // Perform any cleanup actions necessary before allowing a verification.
 483   virtual void prepare_for_verify() = 0;
 484 
 485   virtual void print() const = 0;
 486   virtual void print_on(outputStream* st) const = 0;
 487   
 488   // Print all GC threads (other than the VM thread)
 489   // used by this heap.
 490   virtual void print_gc_threads_on(outputStream* st) const = 0;
 491   void print_gc_threads() { print_gc_threads_on(tty); }
 492   // Iterator for all GC threads (other than VM thread)
 493   virtual void gc_threads_do(ThreadClosure* tc) const = 0;
 494 
 495   // Print any relevant tracing info that flags imply.
 496   // Default implementation does nothing.
 497   virtual void print_tracing_info() const = 0;
 498 
 499   // Heap verification
 500   virtual void verify(bool allow_dirty, bool silent) = 0;
 501 
 502   // Non product verification and debugging.
 503 #ifndef PRODUCT
 504   // Support for PromotionFailureALot.  Return true if it's time to cause a
 505   // promotion failure.  The no-argument version uses
 506   // this->_promotion_failure_alot_count as the counter.
 507   inline bool promotion_should_fail(volatile size_t* count);
 508   inline bool promotion_should_fail();
 509 
 510   // Reset the PromotionFailureALot counters.  Should be called at the end of a
 511   // GC in which promotion failure ocurred.
 512   inline void reset_promotion_should_fail(volatile size_t* count);
 513   inline void reset_promotion_should_fail();
 514 #endif  // #ifndef PRODUCT
 515 
 516 #ifdef ASSERT
 517   static int fired_fake_oom() {
 518     return (CIFireOOMAt > 1 && _fire_out_of_memory_count >= CIFireOOMAt);
 519   }
 520 #endif
 521 };
 522 
 523 // Class to set and reset the GC cause for a CollectedHeap.
 524 
 525 class GCCauseSetter : StackObj {
 526   CollectedHeap* _heap;
 527   GCCause::Cause _previous_cause;
 528  public:
 529   GCCauseSetter(CollectedHeap* heap, GCCause::Cause cause) {
 530     assert(SafepointSynchronize::is_at_safepoint(),
 531            "This method manipulates heap state without locking");
 532     _heap = heap;
 533     _previous_cause = _heap->gc_cause();
 534     _heap->set_gc_cause(cause);
 535   }
 536 
 537   ~GCCauseSetter() {
 538     assert(SafepointSynchronize::is_at_safepoint(),
 539           "This method manipulates heap state without locking");
 540     _heap->set_gc_cause(_previous_cause);
 541   }
 542 };