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