1 /*
   2  * Copyright (c) 2001, 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_CMS_COMPACTIBLEFREELISTSPACE_HPP
  26 #define SHARE_VM_GC_CMS_COMPACTIBLEFREELISTSPACE_HPP
  27 
  28 #include "gc/cms/adaptiveFreeList.hpp"
  29 #include "gc/cms/promotionInfo.hpp"
  30 #include "gc/shared/blockOffsetTable.hpp"
  31 #include "gc/shared/space.hpp"
  32 #include "logging/log.hpp"
  33 #include "memory/binaryTreeDictionary.hpp"
  34 #include "memory/freeList.hpp"
  35 
  36 // Classes in support of keeping track of promotions into a non-Contiguous
  37 // space, in this case a CompactibleFreeListSpace.
  38 
  39 // Forward declarations
  40 class CMSCollector;
  41 class CompactibleFreeListSpace;
  42 class ConcurrentMarkSweepGeneration;
  43 class BlkClosure;
  44 class BlkClosureCareful;
  45 class FreeChunk;
  46 class UpwardsObjectClosure;
  47 class ObjectClosureCareful;
  48 class Klass;
  49 
  50 class LinearAllocBlock VALUE_OBJ_CLASS_SPEC {
  51  public:
  52   LinearAllocBlock() : _ptr(0), _word_size(0), _refillSize(0),
  53     _allocation_size_limit(0) {}
  54   void set(HeapWord* ptr, size_t word_size, size_t refill_size,
  55     size_t allocation_size_limit) {
  56     _ptr = ptr;
  57     _word_size = word_size;
  58     _refillSize = refill_size;
  59     _allocation_size_limit = allocation_size_limit;
  60   }
  61   HeapWord* _ptr;
  62   size_t    _word_size;
  63   size_t    _refillSize;
  64   size_t    _allocation_size_limit;  // Largest size that will be allocated
  65 
  66   void print_on(outputStream* st) const;
  67 };
  68 
  69 // Concrete subclass of CompactibleSpace that implements
  70 // a free list space, such as used in the concurrent mark sweep
  71 // generation.
  72 
  73 class CompactibleFreeListSpace: public CompactibleSpace {
  74   friend class VMStructs;
  75   friend class ConcurrentMarkSweepGeneration;
  76   friend class CMSCollector;
  77   // Local alloc buffer for promotion into this space.
  78   friend class CFLS_LAB;
  79   // Allow scan_and_* functions to call (private) overrides of the auxiliary functions on this class
  80   template <typename SpaceType>
  81   friend void CompactibleSpace::scan_and_adjust_pointers(SpaceType* space);
  82   template <typename SpaceType>
  83   friend void CompactibleSpace::scan_and_compact(SpaceType* space);
  84   template <typename SpaceType>
  85   friend void CompactibleSpace::scan_and_forward(SpaceType* space, CompactPoint* cp);
  86 
  87   // "Size" of chunks of work (executed during parallel remark phases
  88   // of CMS collection); this probably belongs in CMSCollector, although
  89   // it's cached here because it's used in
  90   // initialize_sequential_subtasks_for_rescan() which modifies
  91   // par_seq_tasks which also lives in Space. XXX
  92   const size_t _rescan_task_size;
  93   const size_t _marking_task_size;
  94 
  95   // Yet another sequential tasks done structure. This supports
  96   // CMS GC, where we have threads dynamically
  97   // claiming sub-tasks from a larger parallel task.
  98   SequentialSubTasksDone _conc_par_seq_tasks;
  99 
 100   BlockOffsetArrayNonContigSpace _bt;
 101 
 102   CMSCollector* _collector;
 103   ConcurrentMarkSweepGeneration* _old_gen;
 104 
 105   // Data structures for free blocks (used during allocation/sweeping)
 106 
 107   // Allocation is done linearly from two different blocks depending on
 108   // whether the request is small or large, in an effort to reduce
 109   // fragmentation. We assume that any locking for allocation is done
 110   // by the containing generation. Thus, none of the methods in this
 111   // space are re-entrant.
 112   enum SomeConstants {
 113     SmallForLinearAlloc = 16,        // size < this then use _sLAB
 114     SmallForDictionary  = 257,       // size < this then use _indexedFreeList
 115     IndexSetSize        = SmallForDictionary  // keep this odd-sized
 116   };
 117   static size_t IndexSetStart;
 118   static size_t IndexSetStride;
 119 
 120  private:
 121   enum FitStrategyOptions {
 122     FreeBlockStrategyNone = 0,
 123     FreeBlockBestFitFirst
 124   };
 125 
 126   PromotionInfo _promoInfo;
 127 
 128   // Helps to impose a global total order on freelistLock ranks;
 129   // assumes that CFLSpace's are allocated in global total order
 130   static int   _lockRank;
 131 
 132   // A lock protecting the free lists and free blocks;
 133   // mutable because of ubiquity of locking even for otherwise const methods
 134   mutable Mutex _freelistLock;
 135   // Locking verifier convenience function
 136   void assert_locked() const PRODUCT_RETURN;
 137   void assert_locked(const Mutex* lock) const PRODUCT_RETURN;
 138 
 139   // Linear allocation blocks
 140   LinearAllocBlock _smallLinearAllocBlock;
 141 
 142   AFLBinaryTreeDictionary* _dictionary;    // Pointer to dictionary for large size blocks
 143 
 144   // Indexed array for small size blocks
 145   AdaptiveFreeList<FreeChunk> _indexedFreeList[IndexSetSize];
 146 
 147   // Allocation strategy
 148   bool _fitStrategy;  // Use best fit strategy
 149 
 150   // This is an address close to the largest free chunk in the heap.
 151   // It is currently assumed to be at the end of the heap.  Free
 152   // chunks with addresses greater than nearLargestChunk are coalesced
 153   // in an effort to maintain a large chunk at the end of the heap.
 154   HeapWord*  _nearLargestChunk;
 155 
 156   // Used to keep track of limit of sweep for the space
 157   HeapWord* _sweep_limit;
 158 
 159   // Used to make the young collector update the mod union table
 160   MemRegionClosure* _preconsumptionDirtyCardClosure;
 161 
 162   // Support for compacting cms
 163   HeapWord* cross_threshold(HeapWord* start, HeapWord* end);
 164   HeapWord* forward(oop q, size_t size, CompactPoint* cp, HeapWord* compact_top);
 165 
 166   // Initialization helpers.
 167   void initializeIndexedFreeListArray();
 168 
 169   // Extra stuff to manage promotion parallelism.
 170 
 171   // A lock protecting the dictionary during par promotion allocation.
 172   mutable Mutex _parDictionaryAllocLock;
 173   Mutex* parDictionaryAllocLock() const { return &_parDictionaryAllocLock; }
 174 
 175   // Locks protecting the exact lists during par promotion allocation.
 176   Mutex* _indexedFreeListParLocks[IndexSetSize];
 177 
 178   // Attempt to obtain up to "n" blocks of the size "word_sz" (which is
 179   // required to be smaller than "IndexSetSize".)  If successful,
 180   // adds them to "fl", which is required to be an empty free list.
 181   // If the count of "fl" is negative, it's absolute value indicates a
 182   // number of free chunks that had been previously "borrowed" from global
 183   // list of size "word_sz", and must now be decremented.
 184   void par_get_chunk_of_blocks(size_t word_sz, size_t n, AdaptiveFreeList<FreeChunk>* fl);
 185 
 186   // Used by par_get_chunk_of_blocks() for the chunks from the
 187   // indexed_free_lists.
 188   bool par_get_chunk_of_blocks_IFL(size_t word_sz, size_t n, AdaptiveFreeList<FreeChunk>* fl);
 189 
 190   // Used by par_get_chunk_of_blocks_dictionary() to get a chunk
 191   // evenly splittable into "n" "word_sz" chunks.  Returns that
 192   // evenly splittable chunk.  May split a larger chunk to get the
 193   // evenly splittable chunk.
 194   FreeChunk* get_n_way_chunk_to_split(size_t word_sz, size_t n);
 195 
 196   // Used by par_get_chunk_of_blocks() for the chunks from the
 197   // dictionary.
 198   void par_get_chunk_of_blocks_dictionary(size_t word_sz, size_t n, AdaptiveFreeList<FreeChunk>* fl);
 199 
 200   // Allocation helper functions
 201   // Allocate using a strategy that takes from the indexed free lists
 202   // first.  This allocation strategy assumes a companion sweeping
 203   // strategy that attempts to keep the needed number of chunks in each
 204   // indexed free lists.
 205   HeapWord* allocate_adaptive_freelists(size_t size);
 206 
 207   // Gets a chunk from the linear allocation block (LinAB).  If there
 208   // is not enough space in the LinAB, refills it.
 209   HeapWord*  getChunkFromLinearAllocBlock(LinearAllocBlock* blk, size_t size);
 210   HeapWord*  getChunkFromSmallLinearAllocBlock(size_t size);
 211   // Get a chunk from the space remaining in the linear allocation block.  Do
 212   // not attempt to refill if the space is not available, return NULL.  Do the
 213   // repairs on the linear allocation block as appropriate.
 214   HeapWord*  getChunkFromLinearAllocBlockRemainder(LinearAllocBlock* blk, size_t size);
 215   inline HeapWord*  getChunkFromSmallLinearAllocBlockRemainder(size_t size);
 216 
 217   // Helper function for getChunkFromIndexedFreeList.
 218   // Replenish the indexed free list for this "size".  Do not take from an
 219   // underpopulated size.
 220   FreeChunk*  getChunkFromIndexedFreeListHelper(size_t size, bool replenish = true);
 221 
 222   // Get a chunk from the indexed free list.  If the indexed free list
 223   // does not have a free chunk, try to replenish the indexed free list
 224   // then get the free chunk from the replenished indexed free list.
 225   inline FreeChunk* getChunkFromIndexedFreeList(size_t size);
 226 
 227   // The returned chunk may be larger than requested (or null).
 228   FreeChunk* getChunkFromDictionary(size_t size);
 229   // The returned chunk is the exact size requested (or null).
 230   FreeChunk* getChunkFromDictionaryExact(size_t size);
 231 
 232   // Find a chunk in the indexed free list that is the best
 233   // fit for size "numWords".
 234   FreeChunk* bestFitSmall(size_t numWords);
 235   // For free list "fl" of chunks of size > numWords,
 236   // remove a chunk, split off a chunk of size numWords
 237   // and return it.  The split off remainder is returned to
 238   // the free lists.  The old name for getFromListGreater
 239   // was lookInListGreater.
 240   FreeChunk* getFromListGreater(AdaptiveFreeList<FreeChunk>* fl, size_t numWords);
 241   // Get a chunk in the indexed free list or dictionary,
 242   // by considering a larger chunk and splitting it.
 243   FreeChunk* getChunkFromGreater(size_t numWords);
 244   //  Verify that the given chunk is in the indexed free lists.
 245   bool verifyChunkInIndexedFreeLists(FreeChunk* fc) const;
 246   // Remove the specified chunk from the indexed free lists.
 247   void       removeChunkFromIndexedFreeList(FreeChunk* fc);
 248   // Remove the specified chunk from the dictionary.
 249   void       removeChunkFromDictionary(FreeChunk* fc);
 250   // Split a free chunk into a smaller free chunk of size "new_size".
 251   // Return the smaller free chunk and return the remainder to the
 252   // free lists.
 253   FreeChunk* splitChunkAndReturnRemainder(FreeChunk* chunk, size_t new_size);
 254   // Add a chunk to the free lists.
 255   void       addChunkToFreeLists(HeapWord* chunk, size_t size);
 256   // Add a chunk to the free lists, preferring to suffix it
 257   // to the last free chunk at end of space if possible, and
 258   // updating the block census stats as well as block offset table.
 259   // Take any locks as appropriate if we are multithreaded.
 260   void       addChunkToFreeListsAtEndRecordingStats(HeapWord* chunk, size_t size);
 261   // Add a free chunk to the indexed free lists.
 262   void       returnChunkToFreeList(FreeChunk* chunk);
 263   // Add a free chunk to the dictionary.
 264   void       returnChunkToDictionary(FreeChunk* chunk);
 265 
 266   // Functions for maintaining the linear allocation buffers (LinAB).
 267   // Repairing a linear allocation block refers to operations
 268   // performed on the remainder of a LinAB after an allocation
 269   // has been made from it.
 270   void       repairLinearAllocationBlocks();
 271   void       repairLinearAllocBlock(LinearAllocBlock* blk);
 272   void       refillLinearAllocBlock(LinearAllocBlock* blk);
 273   void       refillLinearAllocBlockIfNeeded(LinearAllocBlock* blk);
 274   void       refillLinearAllocBlocksIfNeeded();
 275 
 276   void       verify_objects_initialized() const;
 277 
 278   // Statistics reporting helper functions
 279   void       reportFreeListStatistics(const char* title) const;
 280   void       reportIndexedFreeListStatistics(outputStream* st) const;
 281   size_t     maxChunkSizeInIndexedFreeLists() const;
 282   size_t     numFreeBlocksInIndexedFreeLists() const;
 283   // Accessor
 284   HeapWord* unallocated_block() const {
 285     if (BlockOffsetArrayUseUnallocatedBlock) {
 286       HeapWord* ub = _bt.unallocated_block();
 287       assert(ub >= bottom() &&
 288              ub <= end(), "space invariant");
 289       return ub;
 290     } else {
 291       return end();
 292     }
 293   }
 294   void freed(HeapWord* start, size_t size) {
 295     _bt.freed(start, size);
 296   }
 297 
 298   // Auxiliary functions for scan_and_{forward,adjust_pointers,compact} support.
 299   // See comments for CompactibleSpace for more information.
 300   inline HeapWord* scan_limit() const {
 301     return end();
 302   }
 303 
 304   inline bool scanned_block_is_obj(const HeapWord* addr) const {
 305     return CompactibleFreeListSpace::block_is_obj(addr); // Avoid virtual call
 306   }
 307 
 308   inline size_t scanned_block_size(const HeapWord* addr) const {
 309     return CompactibleFreeListSpace::block_size(addr); // Avoid virtual call
 310   }
 311 
 312   inline size_t adjust_obj_size(size_t size) const {
 313     return adjustObjectSize(size);
 314   }
 315 
 316   inline size_t obj_size(const HeapWord* addr) const {
 317     return adjustObjectSize(oop(addr)->size());
 318   }
 319 
 320  protected:
 321   // Reset the indexed free list to its initial empty condition.
 322   void resetIndexedFreeListArray();
 323   // Reset to an initial state with a single free block described
 324   // by the MemRegion parameter.
 325   void reset(MemRegion mr);
 326   // Return the total number of words in the indexed free lists.
 327   size_t     totalSizeInIndexedFreeLists() const;
 328 
 329  public:
 330   // Constructor
 331   CompactibleFreeListSpace(BlockOffsetSharedArray* bs, MemRegion mr);
 332   // Accessors
 333   bool bestFitFirst() { return _fitStrategy == FreeBlockBestFitFirst; }
 334   FreeBlockDictionary<FreeChunk>* dictionary() const { return _dictionary; }
 335   HeapWord* nearLargestChunk() const { return _nearLargestChunk; }
 336   void set_nearLargestChunk(HeapWord* v) { _nearLargestChunk = v; }
 337 
 338   // Set CMS global values.
 339   static void set_cms_values();
 340 
 341   // Return the free chunk at the end of the space.  If no such
 342   // chunk exists, return NULL.
 343   FreeChunk* find_chunk_at_end();
 344 
 345   void set_collector(CMSCollector* collector) { _collector = collector; }
 346 
 347   // Support for parallelization of rescan and marking.
 348   const size_t rescan_task_size()  const { return _rescan_task_size;  }
 349   const size_t marking_task_size() const { return _marking_task_size; }
 350   SequentialSubTasksDone* conc_par_seq_tasks() {return &_conc_par_seq_tasks; }
 351   void initialize_sequential_subtasks_for_rescan(int n_threads);
 352   void initialize_sequential_subtasks_for_marking(int n_threads,
 353          HeapWord* low = NULL);
 354 
 355   virtual MemRegionClosure* preconsumptionDirtyCardClosure() const {
 356     return _preconsumptionDirtyCardClosure;
 357   }
 358 
 359   void setPreconsumptionDirtyCardClosure(MemRegionClosure* cl) {
 360     _preconsumptionDirtyCardClosure = cl;
 361   }
 362 
 363   // Space enquiries
 364   size_t used() const;
 365   size_t free() const;
 366   size_t max_alloc_in_words() const;
 367   // XXX: should have a less conservative used_region() than that of
 368   // Space; we could consider keeping track of highest allocated
 369   // address and correcting that at each sweep, as the sweeper
 370   // goes through the entire allocated part of the generation. We
 371   // could also use that information to keep the sweeper from
 372   // sweeping more than is necessary. The allocator and sweeper will
 373   // of course need to synchronize on this, since the sweeper will
 374   // try to bump down the address and the allocator will try to bump it up.
 375   // For now, however, we'll just use the default used_region()
 376   // which overestimates the region by returning the entire
 377   // committed region (this is safe, but inefficient).
 378 
 379   // Returns a subregion of the space containing all the objects in
 380   // the space.
 381   MemRegion used_region() const {
 382     return MemRegion(bottom(),
 383                      BlockOffsetArrayUseUnallocatedBlock ?
 384                      unallocated_block() : end());
 385   }
 386 
 387   virtual bool is_free_block(const HeapWord* p) const;
 388 
 389   // Resizing support
 390   void set_end(HeapWord* value);  // override
 391 
 392   // Never mangle CompactibleFreeListSpace
 393   void mangle_unused_area() {}
 394   void mangle_unused_area_complete() {}
 395 
 396   // Mutual exclusion support
 397   Mutex* freelistLock() const { return &_freelistLock; }
 398 
 399   // Iteration support
 400   void oop_iterate(ExtendedOopClosure* cl);
 401 
 402   void object_iterate(ObjectClosure* blk);
 403   // Apply the closure to each object in the space whose references
 404   // point to objects in the heap.  The usage of CompactibleFreeListSpace
 405   // by the ConcurrentMarkSweepGeneration for concurrent GC's allows
 406   // objects in the space with references to objects that are no longer
 407   // valid.  For example, an object may reference another object
 408   // that has already been sweep up (collected).  This method uses
 409   // obj_is_alive() to determine whether it is safe to iterate of
 410   // an object.
 411   void safe_object_iterate(ObjectClosure* blk);
 412 
 413   // Iterate over all objects that intersect with mr, calling "cl->do_object"
 414   // on each.  There is an exception to this: if this closure has already
 415   // been invoked on an object, it may skip such objects in some cases.  This is
 416   // Most likely to happen in an "upwards" (ascending address) iteration of
 417   // MemRegions.
 418   void object_iterate_mem(MemRegion mr, UpwardsObjectClosure* cl);
 419 
 420   // Requires that "mr" be entirely within the space.
 421   // Apply "cl->do_object" to all objects that intersect with "mr".
 422   // If the iteration encounters an unparseable portion of the region,
 423   // terminate the iteration and return the address of the start of the
 424   // subregion that isn't done.  Return of "NULL" indicates that the
 425   // iteration completed.
 426   HeapWord* object_iterate_careful_m(MemRegion mr,
 427                                      ObjectClosureCareful* cl);
 428 
 429   // Override: provides a DCTO_CL specific to this kind of space.
 430   DirtyCardToOopClosure* new_dcto_cl(ExtendedOopClosure* cl,
 431                                      CardTableModRefBS::PrecisionStyle precision,
 432                                      HeapWord* boundary,
 433                                      bool parallel);
 434 
 435   void blk_iterate(BlkClosure* cl);
 436   void blk_iterate_careful(BlkClosureCareful* cl);
 437   HeapWord* block_start_const(const void* p) const;
 438   HeapWord* block_start_careful(const void* p) const;
 439   size_t block_size(const HeapWord* p) const;
 440   size_t block_size_no_stall(HeapWord* p, const CMSCollector* c) const;
 441   bool block_is_obj(const HeapWord* p) const;
 442   bool obj_is_alive(const HeapWord* p) const;
 443   size_t block_size_nopar(const HeapWord* p) const;
 444   bool block_is_obj_nopar(const HeapWord* p) const;
 445 
 446   // Iteration support for promotion
 447   void save_marks();
 448   bool no_allocs_since_save_marks();
 449 
 450   // Iteration support for sweeping
 451   void save_sweep_limit() {
 452     _sweep_limit = BlockOffsetArrayUseUnallocatedBlock ?
 453                    unallocated_block() : end();
 454     log_develop_trace(gc, sweep)(">>>>> Saving sweep limit " PTR_FORMAT
 455                                  "  for space [" PTR_FORMAT "," PTR_FORMAT ") <<<<<<",
 456                                  p2i(_sweep_limit), p2i(bottom()), p2i(end()));
 457   }
 458   NOT_PRODUCT(
 459     void clear_sweep_limit() { _sweep_limit = NULL; }
 460   )
 461   HeapWord* sweep_limit() { return _sweep_limit; }
 462 
 463   // Apply "blk->do_oop" to the addresses of all reference fields in objects
 464   // promoted into this generation since the most recent save_marks() call.
 465   // Fields in objects allocated by applications of the closure
 466   // *are* included in the iteration. Thus, when the iteration completes
 467   // there should be no further such objects remaining.
 468   #define CFLS_OOP_SINCE_SAVE_MARKS_DECL(OopClosureType, nv_suffix)  \
 469     void oop_since_save_marks_iterate##nv_suffix(OopClosureType* blk);
 470   ALL_SINCE_SAVE_MARKS_CLOSURES(CFLS_OOP_SINCE_SAVE_MARKS_DECL)
 471   #undef CFLS_OOP_SINCE_SAVE_MARKS_DECL
 472 
 473   // Allocation support
 474   HeapWord* allocate(size_t size);
 475   HeapWord* par_allocate(size_t size);
 476 
 477   oop       promote(oop obj, size_t obj_size);
 478   void      gc_prologue();
 479   void      gc_epilogue();
 480 
 481   // This call is used by a containing CMS generation / collector
 482   // to inform the CFLS space that a sweep has been completed
 483   // and that the space can do any related house-keeping functions.
 484   void      sweep_completed();
 485 
 486   // For an object in this space, the mark-word's two
 487   // LSB's having the value [11] indicates that it has been
 488   // promoted since the most recent call to save_marks() on
 489   // this generation and has not subsequently been iterated
 490   // over (using oop_since_save_marks_iterate() above).
 491   // This property holds only for single-threaded collections,
 492   // and is typically used for Cheney scans; for MT scavenges,
 493   // the property holds for all objects promoted during that
 494   // scavenge for the duration of the scavenge and is used
 495   // by card-scanning to avoid scanning objects (being) promoted
 496   // during that scavenge.
 497   bool obj_allocated_since_save_marks(const oop obj) const {
 498     assert(is_in_reserved(obj), "Wrong space?");
 499     return ((PromotedObject*)obj)->hasPromotedMark();
 500   }
 501 
 502   // A worst-case estimate of the space required (in HeapWords) to expand the
 503   // heap when promoting an obj of size obj_size.
 504   size_t expansionSpaceRequired(size_t obj_size) const;
 505 
 506   FreeChunk* allocateScratch(size_t size);
 507 
 508   // Returns true if either the small or large linear allocation buffer is empty.
 509   bool       linearAllocationWouldFail() const;
 510 
 511   // Adjust the chunk for the minimum size.  This version is called in
 512   // most cases in CompactibleFreeListSpace methods.
 513   inline static size_t adjustObjectSize(size_t size) {
 514     return (size_t) align_object_size(MAX2(size, (size_t)MinChunkSize));
 515   }
 516   // This is a virtual version of adjustObjectSize() that is called
 517   // only occasionally when the compaction space changes and the type
 518   // of the new compaction space is is only known to be CompactibleSpace.
 519   size_t adjust_object_size_v(size_t size) const {
 520     return adjustObjectSize(size);
 521   }
 522   // Minimum size of a free block.
 523   virtual size_t minimum_free_block_size() const { return MinChunkSize; }
 524   void      removeFreeChunkFromFreeLists(FreeChunk* chunk);
 525   void      addChunkAndRepairOffsetTable(HeapWord* chunk, size_t size,
 526               bool coalesced);
 527 
 528   // Support for compaction.
 529   void prepare_for_compaction(CompactPoint* cp);
 530   void adjust_pointers();
 531   void compact();
 532   // Reset the space to reflect the fact that a compaction of the
 533   // space has been done.
 534   virtual void reset_after_compaction();
 535 
 536   // Debugging support.
 537   void print()                            const;
 538   void print_on(outputStream* st)         const;
 539   void prepare_for_verify();
 540   void verify()                           const;
 541   void verifyFreeLists()                  const PRODUCT_RETURN;
 542   void verifyIndexedFreeLists()           const;
 543   void verifyIndexedFreeList(size_t size) const;
 544   // Verify that the given chunk is in the free lists:
 545   // i.e. either the binary tree dictionary, the indexed free lists
 546   // or the linear allocation block.
 547   bool verify_chunk_in_free_list(FreeChunk* fc) const;
 548   // Verify that the given chunk is the linear allocation block.
 549   bool verify_chunk_is_linear_alloc_block(FreeChunk* fc) const;
 550   // Do some basic checks on the the free lists.
 551   void check_free_list_consistency()      const PRODUCT_RETURN;
 552 
 553   // Printing support
 554   void dump_at_safepoint_with_locks(CMSCollector* c, outputStream* st);
 555   void print_indexed_free_lists(outputStream* st) const;
 556   void print_dictionary_free_lists(outputStream* st) const;
 557   void print_promo_info_blocks(outputStream* st) const;
 558 
 559   NOT_PRODUCT (
 560     void initializeIndexedFreeListArrayReturnedBytes();
 561     size_t sumIndexedFreeListArrayReturnedBytes();
 562     // Return the total number of chunks in the indexed free lists.
 563     size_t totalCountInIndexedFreeLists() const;
 564     // Return the total number of chunks in the space.
 565     size_t totalCount();
 566   )
 567 
 568   // The census consists of counts of the quantities such as
 569   // the current count of the free chunks, number of chunks
 570   // created as a result of the split of a larger chunk or
 571   // coalescing of smaller chucks, etc.  The counts in the
 572   // census is used to make decisions on splitting and
 573   // coalescing of chunks during the sweep of garbage.
 574 
 575   // Print the statistics for the free lists.
 576   void printFLCensus(size_t sweep_count) const;
 577 
 578   // Statistics functions
 579   // Initialize census for lists before the sweep.
 580   void beginSweepFLCensus(float inter_sweep_current,
 581                           float inter_sweep_estimate,
 582                           float intra_sweep_estimate);
 583   // Set the surplus for each of the free lists.
 584   void setFLSurplus();
 585   // Set the hint for each of the free lists.
 586   void setFLHints();
 587   // Clear the census for each of the free lists.
 588   void clearFLCensus();
 589   // Perform functions for the census after the end of the sweep.
 590   void endSweepFLCensus(size_t sweep_count);
 591   // Return true if the count of free chunks is greater
 592   // than the desired number of free chunks.
 593   bool coalOverPopulated(size_t size);
 594 
 595 // Record (for each size):
 596 //
 597 //   split-births = #chunks added due to splits in (prev-sweep-end,
 598 //      this-sweep-start)
 599 //   split-deaths = #chunks removed for splits in (prev-sweep-end,
 600 //      this-sweep-start)
 601 //   num-curr     = #chunks at start of this sweep
 602 //   num-prev     = #chunks at end of previous sweep
 603 //
 604 // The above are quantities that are measured. Now define:
 605 //
 606 //   num-desired := num-prev + split-births - split-deaths - num-curr
 607 //
 608 // Roughly, num-prev + split-births is the supply,
 609 // split-deaths is demand due to other sizes
 610 // and num-curr is what we have left.
 611 //
 612 // Thus, num-desired is roughly speaking the "legitimate demand"
 613 // for blocks of this size and what we are striving to reach at the
 614 // end of the current sweep.
 615 //
 616 // For a given list, let num-len be its current population.
 617 // Define, for a free list of a given size:
 618 //
 619 //   coal-overpopulated := num-len >= num-desired * coal-surplus
 620 // (coal-surplus is set to 1.05, i.e. we allow a little slop when
 621 // coalescing -- we do not coalesce unless we think that the current
 622 // supply has exceeded the estimated demand by more than 5%).
 623 //
 624 // For the set of sizes in the binary tree, which is neither dense nor
 625 // closed, it may be the case that for a particular size we have never
 626 // had, or do not now have, or did not have at the previous sweep,
 627 // chunks of that size. We need to extend the definition of
 628 // coal-overpopulated to such sizes as well:
 629 //
 630 //   For a chunk in/not in the binary tree, extend coal-overpopulated
 631 //   defined above to include all sizes as follows:
 632 //
 633 //   . a size that is non-existent is coal-overpopulated
 634 //   . a size that has a num-desired <= 0 as defined above is
 635 //     coal-overpopulated.
 636 //
 637 // Also define, for a chunk heap-offset C and mountain heap-offset M:
 638 //
 639 //   close-to-mountain := C >= 0.99 * M
 640 //
 641 // Now, the coalescing strategy is:
 642 //
 643 //    Coalesce left-hand chunk with right-hand chunk if and
 644 //    only if:
 645 //
 646 //      EITHER
 647 //        . left-hand chunk is of a size that is coal-overpopulated
 648 //      OR
 649 //        . right-hand chunk is close-to-mountain
 650   void smallCoalBirth(size_t size);
 651   void smallCoalDeath(size_t size);
 652   void coalBirth(size_t size);
 653   void coalDeath(size_t size);
 654   void smallSplitBirth(size_t size);
 655   void smallSplitDeath(size_t size);
 656   void split_birth(size_t size);
 657   void splitDeath(size_t size);
 658   void split(size_t from, size_t to1);
 659 
 660   double flsFrag() const;
 661 };
 662 
 663 // A parallel-GC-thread-local allocation buffer for allocation into a
 664 // CompactibleFreeListSpace.
 665 class CFLS_LAB : public CHeapObj<mtGC> {
 666   // The space that this buffer allocates into.
 667   CompactibleFreeListSpace* _cfls;
 668 
 669   // Our local free lists.
 670   AdaptiveFreeList<FreeChunk> _indexedFreeList[CompactibleFreeListSpace::IndexSetSize];
 671 
 672   // Initialized from a command-line arg.
 673 
 674   // Allocation statistics in support of dynamic adjustment of
 675   // #blocks to claim per get_from_global_pool() call below.
 676   static AdaptiveWeightedAverage
 677                  _blocks_to_claim  [CompactibleFreeListSpace::IndexSetSize];
 678   static size_t _global_num_blocks [CompactibleFreeListSpace::IndexSetSize];
 679   static uint   _global_num_workers[CompactibleFreeListSpace::IndexSetSize];
 680   size_t        _num_blocks        [CompactibleFreeListSpace::IndexSetSize];
 681 
 682   // Internal work method
 683   void get_from_global_pool(size_t word_sz, AdaptiveFreeList<FreeChunk>* fl);
 684 
 685 public:
 686   static const int _default_dynamic_old_plab_size = 16;
 687   static const int _default_static_old_plab_size  = 50;
 688 
 689   CFLS_LAB(CompactibleFreeListSpace* cfls);
 690 
 691   // Allocate and return a block of the given size, or else return NULL.
 692   HeapWord* alloc(size_t word_sz);
 693 
 694   // Return any unused portions of the buffer to the global pool.
 695   void retire(int tid);
 696 
 697   // Dynamic OldPLABSize sizing
 698   static void compute_desired_plab_size();
 699   // When the settings are modified from default static initialization
 700   static void modify_initialization(size_t n, unsigned wt);
 701 };
 702 
 703 size_t PromotionInfo::refillSize() const {
 704   const size_t CMSSpoolBlockSize = 256;
 705   const size_t sz = heap_word_size(sizeof(SpoolBlock) + sizeof(markOop)
 706                                    * CMSSpoolBlockSize);
 707   return CompactibleFreeListSpace::adjustObjectSize(sz);
 708 }
 709 
 710 #endif // SHARE_VM_GC_CMS_COMPACTIBLEFREELISTSPACE_HPP