1 /*
   2  * Copyright (c) 1997, 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_GENERATION_HPP
  26 #define SHARE_GC_SHARED_GENERATION_HPP
  27 
  28 #include "gc/shared/collectorCounters.hpp"
  29 #include "gc/shared/referenceProcessor.hpp"
  30 #include "logging/log.hpp"
  31 #include "memory/allocation.hpp"
  32 #include "memory/memRegion.hpp"
  33 #include "memory/virtualspace.hpp"
  34 #include "runtime/mutex.hpp"
  35 #include "runtime/perfData.hpp"
  36 
  37 // A Generation models a heap area for similarly-aged objects.
  38 // It will contain one ore more spaces holding the actual objects.
  39 //
  40 // The Generation class hierarchy:
  41 //
  42 // Generation                      - abstract base class
  43 // - DefNewGeneration              - allocation area (copy collected)
  44 // - CardGeneration                 - abstract class adding offset array behavior
  45 //   - TenuredGeneration             - tenured (old object) space (markSweepCompact)
  46 //
  47 // The system configuration currently allowed is:
  48 //
  49 //   DefNewGeneration + TenuredGeneration
  50 //
  51 
  52 class DefNewGeneration;
  53 class GCMemoryManager;
  54 class GenerationSpec;
  55 class CompactibleSpace;
  56 class ContiguousSpace;
  57 class CompactPoint;
  58 class OopsInGenClosure;
  59 class OopClosure;
  60 class ScanClosure;
  61 class FastScanClosure;
  62 class GenCollectedHeap;
  63 class GCStats;
  64 
  65 // A "ScratchBlock" represents a block of memory in one generation usable by
  66 // another.  It represents "num_words" free words, starting at and including
  67 // the address of "this".
  68 struct ScratchBlock {
  69   ScratchBlock* next;
  70   size_t num_words;
  71   HeapWord scratch_space[1];  // Actually, of size "num_words-2" (assuming
  72                               // first two fields are word-sized.)
  73 };
  74 
  75 class Generation: public CHeapObj<mtGC> {
  76   friend class VMStructs;
  77  private:
  78   jlong _time_of_last_gc; // time when last gc on this generation happened (ms)
  79   MemRegion _prev_used_region; // for collectors that want to "remember" a value for
  80                                // used region at some specific point during collection.
  81 
  82   GCMemoryManager* _gc_manager;
  83 
  84  protected:
  85   // Minimum and maximum addresses for memory reserved (not necessarily
  86   // committed) for generation.
  87   // Used by card marking code. Must not overlap with address ranges of
  88   // other generations.
  89   MemRegion _reserved;
  90 
  91   // Memory area reserved for generation
  92   VirtualSpace _virtual_space;
  93 
  94   // ("Weak") Reference processing support
  95   SpanSubjectToDiscoveryClosure _span_based_discoverer;
  96   ReferenceProcessor* _ref_processor;
  97 
  98   // Performance Counters
  99   CollectorCounters* _gc_counters;
 100 
 101   // Statistics for garbage collection
 102   GCStats* _gc_stats;
 103 
 104   // Initialize the generation.
 105   Generation(ReservedSpace rs, size_t initial_byte_size);
 106 
 107   // Apply "cl->do_oop" to (the address of) (exactly) all the ref fields in
 108   // "sp" that point into younger generations.
 109   // The iteration is only over objects allocated at the start of the
 110   // iterations; objects allocated as a result of applying the closure are
 111   // not included.
 112   void younger_refs_in_space_iterate(Space* sp, OopsInGenClosure* cl, uint n_threads);
 113 
 114  public:
 115   // The set of possible generation kinds.
 116   enum Name {
 117     DefNew,
 118     MarkSweepCompact,
 119     Other
 120   };
 121 
 122   enum SomePublicConstants {
 123     // Generations are GenGrain-aligned and have size that are multiples of
 124     // GenGrain.
 125     // Note: on ARM we add 1 bit for card_table_base to be properly aligned
 126     // (we expect its low byte to be zero - see implementation of post_barrier)
 127     LogOfGenGrain = 16 ARM32_ONLY(+1),
 128     GenGrain = 1 << LogOfGenGrain
 129   };
 130 
 131   // allocate and initialize ("weak") refs processing support
 132   virtual void ref_processor_init();
 133   void set_ref_processor(ReferenceProcessor* rp) {
 134     assert(_ref_processor == NULL, "clobbering existing _ref_processor");
 135     _ref_processor = rp;
 136   }
 137 
 138   virtual Generation::Name kind() { return Generation::Other; }
 139 
 140   // This properly belongs in the collector, but for now this
 141   // will do.
 142   virtual bool refs_discovery_is_atomic() const { return true;  }
 143   virtual bool refs_discovery_is_mt()     const { return false; }
 144 
 145   // Space inquiries (results in bytes)
 146   size_t initial_size();
 147   virtual size_t capacity() const = 0;  // The maximum number of object bytes the
 148                                         // generation can currently hold.
 149   virtual size_t used() const = 0;      // The number of used bytes in the gen.
 150   virtual size_t free() const = 0;      // The number of free bytes in the gen.
 151 
 152   // Support for java.lang.Runtime.maxMemory(); see CollectedHeap.
 153   // Returns the total number of bytes  available in a generation
 154   // for the allocation of objects.
 155   virtual size_t max_capacity() const;
 156 
 157   // If this is a young generation, the maximum number of bytes that can be
 158   // allocated in this generation before a GC is triggered.
 159   virtual size_t capacity_before_gc() const { return 0; }
 160 
 161   // The largest number of contiguous free bytes in the generation,
 162   // including expansion  (Assumes called at a safepoint.)
 163   virtual size_t contiguous_available() const = 0;
 164   // The largest number of contiguous free bytes in this or any higher generation.
 165   virtual size_t max_contiguous_available() const;
 166 
 167   // Returns true if promotions of the specified amount are
 168   // likely to succeed without a promotion failure.
 169   // Promotion of the full amount is not guaranteed but
 170   // might be attempted in the worst case.
 171   virtual bool promotion_attempt_is_safe(size_t max_promotion_in_bytes) const;
 172 
 173   // For a non-young generation, this interface can be used to inform a
 174   // generation that a promotion attempt into that generation failed.
 175   // Typically used to enable diagnostic output for post-mortem analysis,
 176   // but other uses of the interface are not ruled out.
 177   virtual void promotion_failure_occurred() { /* does nothing */ }
 178 
 179   // Return an estimate of the maximum allocation that could be performed
 180   // in the generation without triggering any collection or expansion
 181   // activity.  It is "unsafe" because no locks are taken; the result
 182   // should be treated as an approximation, not a guarantee, for use in
 183   // heuristic resizing decisions.
 184   virtual size_t unsafe_max_alloc_nogc() const = 0;
 185 
 186   // Returns true if this generation cannot be expanded further
 187   // without a GC. Override as appropriate.
 188   virtual bool is_maximal_no_gc() const {
 189     return _virtual_space.uncommitted_size() == 0;
 190   }
 191 
 192   MemRegion reserved() const { return _reserved; }
 193 
 194   // Returns a region guaranteed to contain all the objects in the
 195   // generation.
 196   virtual MemRegion used_region() const { return _reserved; }
 197 
 198   MemRegion prev_used_region() const { return _prev_used_region; }
 199   virtual void  save_used_region()   { _prev_used_region = used_region(); }
 200 
 201   // Returns "TRUE" iff "p" points into the committed areas in the generation.
 202   // For some kinds of generations, this may be an expensive operation.
 203   // To avoid performance problems stemming from its inadvertent use in
 204   // product jvm's, we restrict its use to assertion checking or
 205   // verification only.
 206   virtual bool is_in(const void* p) const;
 207 
 208   /* Returns "TRUE" iff "p" points into the reserved area of the generation. */
 209   bool is_in_reserved(const void* p) const {
 210     return _reserved.contains(p);
 211   }
 212 
 213   // If some space in the generation contains the given "addr", return a
 214   // pointer to that space, else return "NULL".
 215   virtual Space* space_containing(const void* addr) const;
 216 
 217   // Iteration - do not use for time critical operations
 218   virtual void space_iterate(SpaceClosure* blk, bool usedOnly = false) = 0;
 219 
 220   // Returns the first space, if any, in the generation that can participate
 221   // in compaction, or else "NULL".
 222   virtual CompactibleSpace* first_compaction_space() const = 0;
 223 
 224   // Returns "true" iff this generation should be used to allocate an
 225   // object of the given size.  Young generations might
 226   // wish to exclude very large objects, for example, since, if allocated
 227   // often, they would greatly increase the frequency of young-gen
 228   // collection.
 229   virtual bool should_allocate(size_t word_size, bool is_tlab) {
 230     bool result = false;
 231     size_t overflow_limit = (size_t)1 << (BitsPerSize_t - LogHeapWordSize);
 232     if (!is_tlab || supports_tlab_allocation()) {
 233       result = (word_size > 0) && (word_size < overflow_limit);
 234     }
 235     return result;
 236   }
 237 
 238   // Allocate and returns a block of the requested size, or returns "NULL".
 239   // Assumes the caller has done any necessary locking.
 240   virtual HeapWord* allocate(size_t word_size, bool is_tlab) = 0;
 241 
 242   // Like "allocate", but performs any necessary locking internally.
 243   virtual HeapWord* par_allocate(size_t word_size, bool is_tlab) = 0;
 244 
 245   // Some generation may offer a region for shared, contiguous allocation,
 246   // via inlined code (by exporting the address of the top and end fields
 247   // defining the extent of the contiguous allocation region.)
 248 
 249   // This function returns "true" iff the heap supports this kind of
 250   // allocation.  (More precisely, this means the style of allocation that
 251   // increments *top_addr()" with a CAS.) (Default is "no".)
 252   // A generation that supports this allocation style must use lock-free
 253   // allocation for *all* allocation, since there are times when lock free
 254   // allocation will be concurrent with plain "allocate" calls.
 255   virtual bool supports_inline_contig_alloc() const { return false; }
 256 
 257   // These functions return the addresses of the fields that define the
 258   // boundaries of the contiguous allocation area.  (These fields should be
 259   // physically near to one another.)
 260   virtual HeapWord* volatile* top_addr() const { return NULL; }
 261   virtual HeapWord** end_addr() const { return NULL; }
 262 
 263   // Thread-local allocation buffers
 264   virtual bool supports_tlab_allocation() const { return false; }
 265   virtual size_t tlab_capacity() const {
 266     guarantee(false, "Generation doesn't support thread local allocation buffers");
 267     return 0;
 268   }
 269   virtual size_t tlab_used() const {
 270     guarantee(false, "Generation doesn't support thread local allocation buffers");
 271     return 0;
 272   }
 273   virtual size_t unsafe_max_tlab_alloc() const {
 274     guarantee(false, "Generation doesn't support thread local allocation buffers");
 275     return 0;
 276   }
 277 
 278   // "obj" is the address of an object in a younger generation.  Allocate space
 279   // for "obj" in the current (or some higher) generation, and copy "obj" into
 280   // the newly allocated space, if possible, returning the result (or NULL if
 281   // the allocation failed).
 282   //
 283   // The "obj_size" argument is just obj->size(), passed along so the caller can
 284   // avoid repeating the virtual call to retrieve it.
 285   virtual oop promote(oop obj, size_t obj_size);
 286 
 287   // Thread "thread_num" (0 <= i < ParalleGCThreads) wants to promote
 288   // object "obj", whose original mark word was "m", and whose size is
 289   // "word_sz".  If possible, allocate space for "obj", copy obj into it
 290   // (taking care to copy "m" into the mark word when done, since the mark
 291   // word of "obj" may have been overwritten with a forwarding pointer, and
 292   // also taking care to copy the klass pointer *last*.  Returns the new
 293   // object if successful, or else NULL.
 294   virtual oop par_promote(int thread_num, oop obj, markWord m, size_t word_sz);
 295 
 296   // Informs the current generation that all par_promote_alloc's in the
 297   // collection have been completed; any supporting data structures can be
 298   // reset.  Default is to do nothing.
 299   virtual void par_promote_alloc_done(int thread_num) {}
 300 
 301   // Informs the current generation that all oop_since_save_marks_iterates
 302   // performed by "thread_num" in the current collection, if any, have been
 303   // completed; any supporting data structures can be reset.  Default is to
 304   // do nothing.
 305   virtual void par_oop_since_save_marks_iterate_done(int thread_num) {}
 306 
 307   // Returns "true" iff collect() should subsequently be called on this
 308   // this generation. See comment below.
 309   // This is a generic implementation which can be overridden.
 310   //
 311   // Note: in the current (1.4) implementation, when genCollectedHeap's
 312   // incremental_collection_will_fail flag is set, all allocations are
 313   // slow path (the only fast-path place to allocate is DefNew, which
 314   // will be full if the flag is set).
 315   // Thus, older generations which collect younger generations should
 316   // test this flag and collect if it is set.
 317   virtual bool should_collect(bool   full,
 318                               size_t word_size,
 319                               bool   is_tlab) {
 320     return (full || should_allocate(word_size, is_tlab));
 321   }
 322 
 323   // Returns true if the collection is likely to be safely
 324   // completed. Even if this method returns true, a collection
 325   // may not be guaranteed to succeed, and the system should be
 326   // able to safely unwind and recover from that failure, albeit
 327   // at some additional cost.
 328   virtual bool collection_attempt_is_safe() {
 329     guarantee(false, "Are you sure you want to call this method?");
 330     return true;
 331   }
 332 
 333   // Perform a garbage collection.
 334   // If full is true attempt a full garbage collection of this generation.
 335   // Otherwise, attempting to (at least) free enough space to support an
 336   // allocation of the given "word_size".
 337   virtual void collect(bool   full,
 338                        bool   clear_all_soft_refs,
 339                        size_t word_size,
 340                        bool   is_tlab) = 0;
 341 
 342   // Perform a heap collection, attempting to create (at least) enough
 343   // space to support an allocation of the given "word_size".  If
 344   // successful, perform the allocation and return the resulting
 345   // "oop" (initializing the allocated block). If the allocation is
 346   // still unsuccessful, return "NULL".
 347   virtual HeapWord* expand_and_allocate(size_t word_size,
 348                                         bool is_tlab,
 349                                         bool parallel = false) = 0;
 350 
 351   // Some generations may require some cleanup or preparation actions before
 352   // allowing a collection.  The default is to do nothing.
 353   virtual void gc_prologue(bool full) {}
 354 
 355   // Some generations may require some cleanup actions after a collection.
 356   // The default is to do nothing.
 357   virtual void gc_epilogue(bool full) {}
 358 
 359   // Save the high water marks for the used space in a generation.
 360   virtual void record_spaces_top() {}
 361 
 362   // Some generations may need to be "fixed-up" after some allocation
 363   // activity to make them parsable again. The default is to do nothing.
 364   virtual void ensure_parsability() {}
 365 
 366   // Time (in ms) when we were last collected or now if a collection is
 367   // in progress.
 368   virtual jlong time_of_last_gc(jlong now) {
 369     // Both _time_of_last_gc and now are set using a time source
 370     // that guarantees monotonically non-decreasing values provided
 371     // the underlying platform provides such a source. So we still
 372     // have to guard against non-monotonicity.
 373     NOT_PRODUCT(
 374       if (now < _time_of_last_gc) {
 375         log_warning(gc)("time warp: " JLONG_FORMAT " to " JLONG_FORMAT, _time_of_last_gc, now);
 376       }
 377     )
 378     return _time_of_last_gc;
 379   }
 380 
 381   virtual void update_time_of_last_gc(jlong now)  {
 382     _time_of_last_gc = now;
 383   }
 384 
 385   // Generations may keep statistics about collection. This method
 386   // updates those statistics. current_generation is the generation
 387   // that was most recently collected. This allows the generation to
 388   // decide what statistics are valid to collect. For example, the
 389   // generation can decide to gather the amount of promoted data if
 390   // the collection of the young generation has completed.
 391   GCStats* gc_stats() const { return _gc_stats; }
 392   virtual void update_gc_stats(Generation* current_generation, bool full) {}
 393 
 394 #if INCLUDE_SERIALGC
 395   // Mark sweep support phase2
 396   virtual void prepare_for_compaction(CompactPoint* cp);
 397   // Mark sweep support phase3
 398   virtual void adjust_pointers();
 399   // Mark sweep support phase4
 400   virtual void compact();
 401   virtual void post_compact() { ShouldNotReachHere(); }
 402 #endif
 403 
 404   // Support for CMS's rescan. In this general form we return a pointer
 405   // to an abstract object that can be used, based on specific previously
 406   // decided protocols, to exchange information between generations,
 407   // information that may be useful for speeding up certain types of
 408   // garbage collectors. A NULL value indicates to the client that
 409   // no data recording is expected by the provider. The data-recorder is
 410   // expected to be GC worker thread-local, with the worker index
 411   // indicated by "thr_num".
 412   virtual void* get_data_recorder(int thr_num) { return NULL; }
 413   virtual void sample_eden_chunk() {}
 414 
 415   // Some generations may require some cleanup actions before allowing
 416   // a verification.
 417   virtual void prepare_for_verify() {}
 418 
 419   // Accessing "marks".
 420 
 421   // This function gives a generation a chance to note a point between
 422   // collections.  For example, a contiguous generation might note the
 423   // beginning allocation point post-collection, which might allow some later
 424   // operations to be optimized.
 425   virtual void save_marks() {}
 426 
 427   // This function allows generations to initialize any "saved marks".  That
 428   // is, should only be called when the generation is empty.
 429   virtual void reset_saved_marks() {}
 430 
 431   // This function is "true" iff any no allocations have occurred in the
 432   // generation since the last call to "save_marks".
 433   virtual bool no_allocs_since_save_marks() = 0;
 434 
 435   // The "requestor" generation is performing some garbage collection
 436   // action for which it would be useful to have scratch space.  If
 437   // the target is not the requestor, no gc actions will be required
 438   // of the target.  The requestor promises to allocate no more than
 439   // "max_alloc_words" in the target generation (via promotion say,
 440   // if the requestor is a young generation and the target is older).
 441   // If the target generation can provide any scratch space, it adds
 442   // it to "list", leaving "list" pointing to the head of the
 443   // augmented list.  The default is to offer no space.
 444   virtual void contribute_scratch(ScratchBlock*& list, Generation* requestor,
 445                                   size_t max_alloc_words) {}
 446 
 447   // Give each generation an opportunity to do clean up for any
 448   // contributed scratch.
 449   virtual void reset_scratch() {}
 450 
 451   // When an older generation has been collected, and perhaps resized,
 452   // this method will be invoked on all younger generations (from older to
 453   // younger), allowing them to resize themselves as appropriate.
 454   virtual void compute_new_size() = 0;
 455 
 456   // Printing
 457   virtual const char* name() const = 0;
 458   virtual const char* short_name() const = 0;
 459 
 460   // Reference Processing accessor
 461   ReferenceProcessor* const ref_processor() { return _ref_processor; }
 462 
 463   // Iteration.
 464 
 465   // Iterate over all the ref-containing fields of all objects in the
 466   // generation, calling "cl.do_oop" on each.
 467   virtual void oop_iterate(OopIterateClosure* cl);
 468 
 469   // Iterate over all objects in the generation, calling "cl.do_object" on
 470   // each.
 471   virtual void object_iterate(ObjectClosure* cl);
 472 
 473   // Apply "cl->do_oop" to (the address of) all and only all the ref fields
 474   // in the current generation that contain pointers to objects in younger
 475   // generations. Objects allocated since the last "save_marks" call are
 476   // excluded.
 477   virtual void younger_refs_iterate(OopsInGenClosure* cl, uint n_threads) = 0;
 478 
 479   // Inform a generation that it longer contains references to objects
 480   // in any younger generation.    [e.g. Because younger gens are empty,
 481   // clear the card table.]
 482   virtual void clear_remembered_set() { }
 483 
 484   // Inform a generation that some of its objects have moved.  [e.g. The
 485   // generation's spaces were compacted, invalidating the card table.]
 486   virtual void invalidate_remembered_set() { }
 487 
 488   // Block abstraction.
 489 
 490   // Returns the address of the start of the "block" that contains the
 491   // address "addr".  We say "blocks" instead of "object" since some heaps
 492   // may not pack objects densely; a chunk may either be an object or a
 493   // non-object.
 494   virtual HeapWord* block_start(const void* addr) const;
 495 
 496   // Requires "addr" to be the start of a chunk, and returns its size.
 497   // "addr + size" is required to be the start of a new chunk, or the end
 498   // of the active area of the heap.
 499   virtual size_t block_size(const HeapWord* addr) const ;
 500 
 501   // Requires "addr" to be the start of a block, and returns "TRUE" iff
 502   // the block is an object.
 503   virtual bool block_is_obj(const HeapWord* addr) const;
 504 
 505   void print_heap_change(size_t prev_used) const;
 506 
 507   virtual void print() const;
 508   virtual void print_on(outputStream* st) const;
 509 
 510   virtual void verify() = 0;
 511 
 512   struct StatRecord {
 513     int invocations;
 514     elapsedTimer accumulated_time;
 515     StatRecord() :
 516       invocations(0),
 517       accumulated_time(elapsedTimer()) {}
 518   };
 519 private:
 520   StatRecord _stat_record;
 521 public:
 522   StatRecord* stat_record() { return &_stat_record; }
 523 
 524   virtual void print_summary_info_on(outputStream* st);
 525 
 526   // Performance Counter support
 527   virtual void update_counters() = 0;
 528   virtual CollectorCounters* counters() { return _gc_counters; }
 529 
 530   GCMemoryManager* gc_manager() const {
 531     assert(_gc_manager != NULL, "not initialized yet");
 532     return _gc_manager;
 533   }
 534 
 535   void set_gc_manager(GCMemoryManager* gc_manager) {
 536     _gc_manager = gc_manager;
 537   }
 538 
 539 };
 540 
 541 #endif // SHARE_GC_SHARED_GENERATION_HPP