1 #ifdef USE_PRAGMA_IDENT_HDR
   2 #pragma ident "@(#)concurrentMarkSweepGeneration.hpp    1.163 08/09/25 13:47:54 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 // ConcurrentMarkSweepGeneration is in support of a concurrent
  29 // mark-sweep old generation in the Detlefs-Printezis--Boehm-Demers-Schenker
  30 // style. We assume, for now, that this generation is always the
  31 // seniormost generation (modulo the PermGeneration), and for simplicity
  32 // in the first implementation, that this generation is a single compactible
  33 // space. Neither of these restrictions appears essential, and will be
  34 // relaxed in the future when more time is available to implement the
  35 // greater generality (and there's a need for it).
  36 //
  37 // Concurrent mode failures are currently handled by
  38 // means of a sliding mark-compact.
  39 
  40 class CMSAdaptiveSizePolicy;
  41 class CMSConcMarkingTask;
  42 class CMSGCAdaptivePolicyCounters;
  43 class ConcurrentMarkSweepGeneration;
  44 class ConcurrentMarkSweepPolicy;
  45 class ConcurrentMarkSweepThread;
  46 class CompactibleFreeListSpace;
  47 class FreeChunk;
  48 class PromotionInfo;
  49 class ScanMarkedObjectsAgainCarefullyClosure;
  50 
  51 // A generic CMS bit map. It's the basis for both the CMS marking bit map
  52 // as well as for the mod union table (in each case only a subset of the
  53 // methods are used). This is essentially a wrapper around the BitMap class,
  54 // with one bit per (1<<_shifter) HeapWords. (i.e. for the marking bit map,
  55 // we have _shifter == 0. and for the mod union table we have
  56 // shifter == CardTableModRefBS::card_shift - LogHeapWordSize.)
  57 // XXX 64-bit issues in BitMap?
  58 class CMSBitMap VALUE_OBJ_CLASS_SPEC {
  59   friend class VMStructs;
  60 
  61   HeapWord* _bmStartWord;   // base address of range covered by map
  62   size_t    _bmWordSize;    // map size (in #HeapWords covered)
  63   const int _shifter;       // shifts to convert HeapWord to bit position
  64   VirtualSpace _virtual_space; // underlying the bit map
  65   BitMap    _bm;            // the bit map itself
  66  public:
  67   Mutex* const _lock;       // mutex protecting _bm;
  68 
  69  public:
  70   // constructor
  71   CMSBitMap(int shifter, int mutex_rank, const char* mutex_name);
  72 
  73   // allocates the actual storage for the map
  74   bool allocate(MemRegion mr);
  75   // field getter
  76   Mutex* lock() const { return _lock; }
  77   // locking verifier convenience function
  78   void assert_locked() const PRODUCT_RETURN;
  79 
  80   // inquiries
  81   HeapWord* startWord()   const { return _bmStartWord; }
  82   size_t    sizeInWords() const { return _bmWordSize;  }
  83   size_t    sizeInBits()  const { return _bm.size();   }
  84   // the following is one past the last word in space
  85   HeapWord* endWord()     const { return _bmStartWord + _bmWordSize; }
  86 
  87   // reading marks
  88   bool isMarked(HeapWord* addr) const;
  89   bool par_isMarked(HeapWord* addr) const; // do not lock checks
  90   bool isUnmarked(HeapWord* addr) const;
  91   bool isAllClear() const;
  92 
  93   // writing marks
  94   void mark(HeapWord* addr);
  95   // For marking by parallel GC threads;
  96   // returns true if we did, false if another thread did
  97   bool par_mark(HeapWord* addr);
  98 
  99   void mark_range(MemRegion mr);
 100   void par_mark_range(MemRegion mr);
 101   void mark_large_range(MemRegion mr);
 102   void par_mark_large_range(MemRegion mr);
 103   void par_clear(HeapWord* addr); // For unmarking by parallel GC threads.
 104   void clear_range(MemRegion mr);
 105   void par_clear_range(MemRegion mr);
 106   void clear_large_range(MemRegion mr);
 107   void par_clear_large_range(MemRegion mr);
 108   void clear_all();
 109   void clear_all_incrementally();  // Not yet implemented!!
 110 
 111   NOT_PRODUCT(
 112     // checks the memory region for validity
 113     void region_invariant(MemRegion mr);
 114   )
 115   
 116   // iteration
 117   void iterate(BitMapClosure* cl) {
 118     _bm.iterate(cl);
 119   }
 120   void iterate(BitMapClosure* cl, HeapWord* left, HeapWord* right);
 121   void dirty_range_iterate_clear(MemRegionClosure* cl);
 122   void dirty_range_iterate_clear(MemRegion mr, MemRegionClosure* cl);
 123  
 124   // auxiliary support for iteration
 125   HeapWord* getNextMarkedWordAddress(HeapWord* addr) const;
 126   HeapWord* getNextMarkedWordAddress(HeapWord* start_addr,
 127                                             HeapWord* end_addr) const;
 128   HeapWord* getNextUnmarkedWordAddress(HeapWord* addr) const;
 129   HeapWord* getNextUnmarkedWordAddress(HeapWord* start_addr,
 130                                               HeapWord* end_addr) const;
 131   MemRegion getAndClearMarkedRegion(HeapWord* addr);
 132   MemRegion getAndClearMarkedRegion(HeapWord* start_addr, 
 133                                            HeapWord* end_addr);
 134 
 135   // conversion utilities
 136   HeapWord* offsetToHeapWord(size_t offset) const;
 137   size_t    heapWordToOffset(HeapWord* addr) const;
 138   size_t    heapWordDiffToOffsetDiff(size_t diff) const;
 139   
 140   // debugging
 141   // is this address range covered by the bit-map?
 142   NOT_PRODUCT(
 143     bool covers(MemRegion mr) const;
 144     bool covers(HeapWord* start, size_t size = 0) const;
 145   )
 146   void verifyNoOneBitsInRange(HeapWord* left, HeapWord* right) PRODUCT_RETURN;
 147 };
 148 
 149 // Represents a marking stack used by the CMS collector.
 150 // Ideally this should be GrowableArray<> just like MSC's marking stack(s).
 151 class CMSMarkStack: public CHeapObj  {
 152   // 
 153   friend class CMSCollector;   // to get at expasion stats further below
 154   //
 155 
 156   VirtualSpace _virtual_space;  // space for the stack
 157   oop*   _base;      // bottom of stack
 158   size_t _index;     // one more than last occupied index
 159   size_t _capacity;  // max #elements
 160   Mutex  _par_lock;  // an advisory lock used in case of parallel access
 161   NOT_PRODUCT(size_t _max_depth;)  // max depth plumbed during run
 162 
 163  protected:
 164   size_t _hit_limit;      // we hit max stack size limit
 165   size_t _failed_double;  // we failed expansion before hitting limit
 166 
 167  public:
 168   CMSMarkStack():
 169     _par_lock(Mutex::event, "CMSMarkStack._par_lock", true),
 170     _hit_limit(0),
 171     _failed_double(0) {}
 172 
 173   bool allocate(size_t size);
 174 
 175   size_t capacity() const { return _capacity; }
 176 
 177   oop pop() {
 178     if (!isEmpty()) {
 179       return _base[--_index] ;
 180     }
 181     return NULL;
 182   }
 183 
 184   bool push(oop ptr) {
 185     if (isFull()) {
 186       return false;
 187     } else {
 188       _base[_index++] = ptr;
 189       NOT_PRODUCT(_max_depth = MAX2(_max_depth, _index));
 190       return true;
 191     }
 192   }
 193 
 194   bool isEmpty() const { return _index == 0; }
 195   bool isFull()  const {
 196     assert(_index <= _capacity, "buffer overflow");
 197     return _index == _capacity;
 198   }
 199 
 200   size_t length() { return _index; }
 201 
 202   // "Parallel versions" of some of the above
 203   oop par_pop() {
 204     // lock and pop
 205     MutexLockerEx x(&_par_lock, Mutex::_no_safepoint_check_flag);
 206     return pop();
 207   }
 208 
 209   bool par_push(oop ptr) {
 210     // lock and push
 211     MutexLockerEx x(&_par_lock, Mutex::_no_safepoint_check_flag);
 212     return push(ptr);
 213   }
 214 
 215   // Forcibly reset the stack, losing all of its contents.
 216   void reset() {
 217     _index = 0;
 218   }
 219 
 220   // Expand the stack, typically in response to an overflow condition
 221   void expand();
 222 
 223   // Compute the least valued stack element.
 224   oop least_value(HeapWord* low) {
 225      oop least = (oop)low;
 226      for (size_t i = 0; i < _index; i++) {
 227        least = MIN2(least, _base[i]);
 228      }
 229      return least;
 230   }
 231 
 232   // Exposed here to allow stack expansion in || case
 233   Mutex* par_lock() { return &_par_lock; }
 234 };
 235 
 236 class CardTableRS;
 237 class CMSParGCThreadState;
 238 
 239 class ModUnionClosure: public MemRegionClosure {
 240  protected:
 241   CMSBitMap* _t;
 242  public:
 243   ModUnionClosure(CMSBitMap* t): _t(t) { }
 244   void do_MemRegion(MemRegion mr);
 245 };
 246 
 247 class ModUnionClosurePar: public ModUnionClosure {
 248  public:
 249   ModUnionClosurePar(CMSBitMap* t): ModUnionClosure(t) { }
 250   void do_MemRegion(MemRegion mr);
 251 };
 252 
 253 // Survivor Chunk Array in support of parallelization of
 254 // Survivor Space rescan.
 255 class ChunkArray: public CHeapObj {
 256   size_t _index;
 257   size_t _capacity;
 258   HeapWord** _array;   // storage for array
 259 
 260  public:
 261   ChunkArray() : _index(0), _capacity(0), _array(NULL) {}
 262   ChunkArray(HeapWord** a, size_t c):
 263     _index(0), _capacity(c), _array(a) {}
 264 
 265   HeapWord** array() { return _array; }
 266   void set_array(HeapWord** a) { _array = a; }
 267 
 268   size_t capacity() { return _capacity; }
 269   void set_capacity(size_t c) { _capacity = c; }
 270 
 271   size_t end() {
 272     assert(_index < capacity(), "_index out of bounds");
 273     return _index;
 274   }  // exclusive
 275 
 276   HeapWord* nth(size_t n) {
 277     assert(n < end(), "Out of bounds access");
 278     return _array[n];
 279   }
 280   
 281   void reset() {
 282     _index = 0;
 283   }
 284 
 285   void record_sample(HeapWord* p, size_t sz) {
 286     // For now we do not do anything with the size
 287     if (_index < _capacity) {
 288       _array[_index++] = p;
 289     }
 290   }
 291 };
 292 
 293 // 
 294 // Timing, allocation and promotion statistics for gc scheduling and incremental
 295 // mode pacing.  Most statistics are exponential averages.
 296 // 
 297 class CMSStats VALUE_OBJ_CLASS_SPEC {
 298  private:
 299   ConcurrentMarkSweepGeneration* const _cms_gen;   // The cms (old) gen.
 300 
 301   // The following are exponential averages with factor alpha:
 302   //   avg = (100 - alpha) * avg + alpha * cur_sample
 303   // 
 304   //   The durations measure:  end_time[n] - start_time[n]
 305   //   The periods measure:    start_time[n] - start_time[n-1]
 306   //
 307   // The cms period and duration include only concurrent collections; time spent
 308   // in foreground cms collections due to System.gc() or because of a failure to
 309   // keep up are not included.
 310   //
 311   // There are 3 alphas to "bootstrap" the statistics.  The _saved_alpha is the
 312   // real value, but is used only after the first period.  A value of 100 is
 313   // used for the first sample so it gets the entire weight.
 314   unsigned int _saved_alpha; // 0-100
 315   unsigned int _gc0_alpha;
 316   unsigned int _cms_alpha;
 317 
 318   double _gc0_duration;
 319   double _gc0_period;
 320   size_t _gc0_promoted;         // bytes promoted per gc0
 321   double _cms_duration;
 322   double _cms_duration_pre_sweep; // time from initiation to start of sweep
 323   double _cms_duration_per_mb;
 324   double _cms_period;
 325   size_t _cms_allocated;        // bytes of direct allocation per gc0 period
 326 
 327   // Timers.
 328   elapsedTimer _cms_timer;
 329   TimeStamp    _gc0_begin_time;
 330   TimeStamp    _cms_begin_time;
 331   TimeStamp    _cms_end_time;
 332 
 333   // Snapshots of the amount used in the CMS generation.
 334   size_t _cms_used_at_gc0_begin;
 335   size_t _cms_used_at_gc0_end;
 336   size_t _cms_used_at_cms_begin;
 337 
 338   // Used to prevent the duty cycle from being reduced in the middle of a cms
 339   // cycle.
 340   bool _allow_duty_cycle_reduction;
 341 
 342   enum {
 343     _GC0_VALID = 0x1,
 344     _CMS_VALID = 0x2,
 345     _ALL_VALID = _GC0_VALID | _CMS_VALID
 346   };
 347 
 348   unsigned int _valid_bits;
 349 
 350   unsigned int _icms_duty_cycle;        // icms duty cycle (0-100).
 351 
 352  protected:
 353 
 354   // Return a duty cycle that avoids wild oscillations, by limiting the amount
 355   // of change between old_duty_cycle and new_duty_cycle (the latter is treated
 356   // as a recommended value).
 357   static unsigned int icms_damped_duty_cycle(unsigned int old_duty_cycle,
 358                                              unsigned int new_duty_cycle);
 359   unsigned int icms_update_duty_cycle_impl();
 360 
 361  public:
 362   CMSStats(ConcurrentMarkSweepGeneration* cms_gen,
 363            unsigned int alpha = CMSExpAvgFactor);
 364 
 365   // Whether or not the statistics contain valid data; higher level statistics
 366   // cannot be called until this returns true (they require at least one young
 367   // gen and one cms cycle to have completed).
 368   bool valid() const;
 369 
 370   // Record statistics.
 371   void record_gc0_begin();
 372   void record_gc0_end(size_t cms_gen_bytes_used);
 373   void record_cms_begin();
 374   void record_cms_end();
 375 
 376   // Allow management of the cms timer, which must be stopped/started around
 377   // yield points.
 378   elapsedTimer& cms_timer()     { return _cms_timer; }
 379   void start_cms_timer()        { _cms_timer.start(); }
 380   void stop_cms_timer()         { _cms_timer.stop(); }
 381 
 382   // Basic statistics; units are seconds or bytes.
 383   double gc0_period() const     { return _gc0_period; }
 384   double gc0_duration() const   { return _gc0_duration; }
 385   size_t gc0_promoted() const   { return _gc0_promoted; }
 386   double cms_period() const          { return _cms_period; }
 387   double cms_duration() const        { return _cms_duration; }
 388   double cms_duration_per_mb() const { return _cms_duration_per_mb; }
 389   size_t cms_allocated() const       { return _cms_allocated; }
 390 
 391   size_t cms_used_at_gc0_end() const { return _cms_used_at_gc0_end;}
 392 
 393   // Seconds since the last background cms cycle began or ended.
 394   double cms_time_since_begin() const;
 395   double cms_time_since_end() const;
 396 
 397   // Higher level statistics--caller must check that valid() returns true before
 398   // calling.
 399 
 400   // Returns bytes promoted per second of wall clock time.
 401   double promotion_rate() const;
 402 
 403   // Returns bytes directly allocated per second of wall clock time.
 404   double cms_allocation_rate() const;
 405 
 406   // Rate at which space in the cms generation is being consumed (sum of the
 407   // above two).
 408   double cms_consumption_rate() const;
 409 
 410   // Returns an estimate of the number of seconds until the cms generation will
 411   // fill up, assuming no collection work is done.
 412   double time_until_cms_gen_full() const;
 413 
 414   // Returns an estimate of the number of seconds remaining until
 415   // the cms generation collection should start.
 416   double time_until_cms_start() const;
 417 
 418   // End of higher level statistics.
 419 
 420   // Returns the cms incremental mode duty cycle, as a percentage (0-100).
 421   unsigned int icms_duty_cycle() const { return _icms_duty_cycle; }
 422 
 423   // Update the duty cycle and return the new value.
 424   unsigned int icms_update_duty_cycle();
 425 
 426   // Debugging.
 427   void print_on(outputStream* st) const PRODUCT_RETURN;
 428   void print() const { print_on(gclog_or_tty); }
 429 };
 430 
 431 // A closure related to weak references processing which
 432 // we embed in the CMSCollector, since we need to pass
 433 // it to the reference processor for secondary filtering
 434 // of references based on reachability of referent;
 435 // see role of _is_alive_non_header closure in the
 436 // ReferenceProcessor class.
 437 // For objects in the CMS generation, this closure checks
 438 // if the object is "live" (reachable). Used in weak
 439 // reference processing.
 440 class CMSIsAliveClosure: public BoolObjectClosure {
 441   const MemRegion  _span;
 442   const CMSBitMap* _bit_map;
 443 
 444   friend class CMSCollector;
 445  public:
 446   CMSIsAliveClosure(MemRegion span,
 447                     CMSBitMap* bit_map):
 448     _span(span),
 449     _bit_map(bit_map) {
 450       assert(!span.is_empty(), "Empty span could spell trouble");
 451     }
 452 
 453   void do_object(oop obj) {
 454     assert(false, "not to be invoked");
 455   }
 456   bool do_object_b(oop obj);
 457 };
 458 
 459 
 460 // Implements AbstractRefProcTaskExecutor for CMS.
 461 class CMSRefProcTaskExecutor: public AbstractRefProcTaskExecutor {
 462 public:
 463 
 464   CMSRefProcTaskExecutor(CMSCollector& collector)
 465     : _collector(collector)
 466   { }
 467   
 468   // Executes a task using worker threads.  
 469   virtual void execute(ProcessTask& task);
 470   virtual void execute(EnqueueTask& task);
 471 private:
 472   CMSCollector& _collector;
 473 };
 474 
 475 
 476 class CMSCollector: public CHeapObj {
 477   friend class VMStructs;
 478   friend class ConcurrentMarkSweepThread;
 479   friend class ConcurrentMarkSweepGeneration;
 480   friend class CompactibleFreeListSpace;
 481   friend class CMSParRemarkTask;
 482   friend class CMSConcMarkingTask;
 483   friend class CMSRefProcTaskProxy;
 484   friend class CMSRefProcTaskExecutor;
 485   friend class ScanMarkedObjectsAgainCarefullyClosure;  // for sampling eden
 486   friend class SurvivorSpacePrecleanClosure;            // --- ditto -------
 487   friend class PushOrMarkClosure;             // to access _restart_addr
 488   friend class Par_PushOrMarkClosure;             // to access _restart_addr
 489   friend class MarkFromRootsClosure;          //  -- ditto --
 490                                               // ... and for clearing cards
 491   friend class Par_MarkFromRootsClosure;      //  to access _restart_addr
 492                                               // ... and for clearing cards
 493   friend class Par_ConcMarkingClosure;        //  to access _restart_addr etc.
 494   friend class MarkFromRootsVerifyClosure;    // to access _restart_addr
 495   friend class PushAndMarkVerifyClosure;      //  -- ditto --
 496   friend class MarkRefsIntoAndScanClosure;    // to access _overflow_list
 497   friend class PushAndMarkClosure;            //  -- ditto --
 498   friend class Par_PushAndMarkClosure;        //  -- ditto --
 499   friend class CMSKeepAliveClosure;           //  -- ditto --
 500   friend class CMSDrainMarkingStackClosure;   //  -- ditto --
 501   friend class CMSInnerParMarkAndPushClosure; //  -- ditto --
 502   NOT_PRODUCT(friend class ScanMarkedObjectsAgainClosure;) //  assertion on _overflow_list
 503   friend class ReleaseForegroundGC;  // to access _foregroundGCShouldWait
 504   friend class VM_CMS_Operation;
 505   friend class VM_CMS_Initial_Mark;
 506   friend class VM_CMS_Final_Remark;
 507 
 508  private:
 509   jlong _time_of_last_gc;
 510   void update_time_of_last_gc(jlong now) {
 511     _time_of_last_gc = now;
 512   }
 513   
 514   OopTaskQueueSet* _task_queues;
 515 
 516   // Overflow list of grey objects, threaded through mark-word
 517   // Manipulated with CAS in the parallel/multi-threaded case.
 518   oop _overflow_list;
 519   // The following array-pair keeps track of mark words
 520   // displaced for accomodating overflow list above.
 521   // This code will likely be revisited under RFE#4922830.
 522   GrowableArray<oop>*     _preserved_oop_stack; 
 523   GrowableArray<markOop>* _preserved_mark_stack; 
 524 
 525   int*             _hash_seed;
 526 
 527   // In support of multi-threaded concurrent phases
 528   YieldingFlexibleWorkGang* _conc_workers;
 529 
 530   // Performance Counters
 531   CollectorCounters* _gc_counters;
 532 
 533   // Initialization Errors
 534   bool _completed_initialization;
 535 
 536   // In support of ExplicitGCInvokesConcurrent
 537   static   bool _full_gc_requested;
 538   unsigned int  _collection_count_start;
 539   // Should we unload classes this concurrent cycle?
 540   // Set in response to a concurrent full gc request.
 541   bool _unload_classes;
 542   bool _unloaded_classes_last_cycle;
 543   // Did we (allow) unload classes in the previous concurrent cycle?
 544   bool cms_unloaded_classes_last_cycle() const {
 545     return _unloaded_classes_last_cycle || CMSClassUnloadingEnabled;
 546   }
 547 
 548   // Verification support
 549   CMSBitMap     _verification_mark_bm;
 550   void verify_after_remark_work_1();
 551   void verify_after_remark_work_2();
 552 
 553   // true if any verification flag is on.
 554   bool _verifying;
 555   bool verifying() const { return _verifying; }
 556   void set_verifying(bool v) { _verifying = v; }
 557 
 558   // Collector policy
 559   ConcurrentMarkSweepPolicy* _collector_policy;
 560   ConcurrentMarkSweepPolicy* collector_policy() { return _collector_policy; }
 561 
 562   // Check whether the gc time limit has been 
 563   // exceeded and set the size policy flag
 564   // appropriately.
 565   void check_gc_time_limit();
 566   // XXX Move these to CMSStats ??? FIX ME !!!
 567   elapsedTimer _sweep_timer;
 568   AdaptivePaddedAverage _sweep_estimate;
 569 
 570  protected:
 571   ConcurrentMarkSweepGeneration* _cmsGen;  // old gen (CMS)
 572   ConcurrentMarkSweepGeneration* _permGen; // perm gen
 573   MemRegion                      _span;    // span covering above two
 574   CardTableRS*                   _ct;      // card table
 575 
 576   // CMS marking support structures
 577   CMSBitMap     _markBitMap;
 578   CMSBitMap     _modUnionTable;
 579   CMSMarkStack  _markStack;
 580   CMSMarkStack  _revisitStack;            // used to keep track of klassKlass objects
 581                                           // to revisit
 582   CMSBitMap     _perm_gen_verify_bit_map; // Mark bit map for perm gen verification support.
 583 
 584   HeapWord*     _restart_addr; // in support of marking stack overflow
 585   void          lower_restart_addr(HeapWord* low);
 586 
 587   // Counters in support of marking stack / work queue overflow handling:
 588   // a non-zero value indicates certain types of overflow events during
 589   // the current CMS cycle and could lead to stack resizing efforts at
 590   // an opportune future time.
 591   size_t        _ser_pmc_preclean_ovflw;
 592   size_t        _ser_pmc_remark_ovflw;
 593   size_t        _par_pmc_remark_ovflw;
 594   size_t        _ser_kac_ovflw;
 595   size_t        _par_kac_ovflw;
 596   NOT_PRODUCT(size_t _num_par_pushes;)
 597 
 598   // ("Weak") Reference processing support
 599   ReferenceProcessor*            _ref_processor;
 600   CMSIsAliveClosure              _is_alive_closure;
 601       // keep this textually after _markBitMap and _span; c'tor dependency
 602 
 603   ConcurrentMarkSweepThread*     _cmsThread;   // the thread doing the work
 604   ModUnionClosure    _modUnionClosure;
 605   ModUnionClosurePar _modUnionClosurePar;
 606 
 607   // CMS abstract state machine
 608   // initial_state: Idling
 609   // next_state(Idling)            = {Marking}
 610   // next_state(Marking)           = {Precleaning, Sweeping}
 611   // next_state(Precleaning)       = {AbortablePreclean, FinalMarking}
 612   // next_state(AbortablePreclean) = {FinalMarking}
 613   // next_state(FinalMarking)      = {Sweeping}
 614   // next_state(Sweeping)          = {Resizing}
 615   // next_state(Resizing)          = {Resetting}
 616   // next_state(Resetting)         = {Idling}
 617   // The numeric values below are chosen so that:
 618   // . _collectorState <= Idling ==  post-sweep && pre-mark
 619   // . _collectorState in (Idling, Sweeping) == {initial,final}marking ||
 620   //                                            precleaning || abortablePrecleanb
 621   enum CollectorState {
 622     Resizing            = 0,
 623     Resetting           = 1,
 624     Idling              = 2,
 625     InitialMarking      = 3,
 626     Marking             = 4,
 627     Precleaning         = 5,
 628     AbortablePreclean   = 6,
 629     FinalMarking        = 7,
 630     Sweeping            = 8 
 631   };
 632   static CollectorState _collectorState;
 633 
 634   // State related to prologue/epilogue invocation for my generations
 635   bool _between_prologue_and_epilogue;
 636 
 637   // Signalling/State related to coordination between fore- and backgroud GC
 638   // Note: When the baton has been passed from background GC to foreground GC,
 639   // _foregroundGCIsActive is true and _foregroundGCShouldWait is false.
 640   static bool _foregroundGCIsActive;    // true iff foreground collector is active or
 641                                  // wants to go active
 642   static bool _foregroundGCShouldWait;  // true iff background GC is active and has not
 643                                  // yet passed the baton to the foreground GC
 644 
 645   // Support for CMSScheduleRemark (abortable preclean)
 646   bool _abort_preclean;
 647   bool _start_sampling;
 648 
 649   int    _numYields;
 650   size_t _numDirtyCards;
 651   uint   _sweepCount;
 652   // number of full gc's since the last concurrent gc.
 653   uint   _full_gcs_since_conc_gc;
 654 
 655   // if occupancy exceeds this, start a new gc cycle
 656   double _initiatingOccupancy;
 657   // occupancy used for bootstrapping stats
 658   double _bootstrap_occupancy;
 659 
 660   // timer
 661   elapsedTimer _timer;
 662 
 663   // Timing, allocation and promotion statistics, used for scheduling.
 664   CMSStats      _stats;
 665 
 666   // Allocation limits installed in the young gen, used only in
 667   // CMSIncrementalMode.  When an allocation in the young gen would cross one of
 668   // these limits, the cms generation is notified and the cms thread is started
 669   // or stopped, respectively.
 670   HeapWord*     _icms_start_limit;
 671   HeapWord*     _icms_stop_limit;
 672 
 673   enum CMS_op_type {
 674     CMS_op_checkpointRootsInitial,
 675     CMS_op_checkpointRootsFinal
 676   };
 677 
 678   void do_CMS_operation(CMS_op_type op);
 679   bool stop_world_and_do(CMS_op_type op);
 680 
 681   OopTaskQueueSet* task_queues() { return _task_queues; }
 682   int*             hash_seed(int i) { return &_hash_seed[i]; }
 683   YieldingFlexibleWorkGang* conc_workers() { return _conc_workers; }
 684 
 685   // Support for parallelizing Eden rescan in CMS remark phase
 686   void sample_eden(); // ... sample Eden space top
 687 
 688  private:
 689   // Support for parallelizing young gen rescan in CMS remark phase
 690   Generation* _young_gen;  // the younger gen
 691   HeapWord** _top_addr;    // ... Top of Eden
 692   HeapWord** _end_addr;    // ... End of Eden
 693   HeapWord** _eden_chunk_array; // ... Eden partitioning array
 694   size_t     _eden_chunk_index; // ... top (exclusive) of array
 695   size_t     _eden_chunk_capacity;  // ... max entries in array
 696 
 697   // Support for parallelizing survivor space rescan 
 698   HeapWord** _survivor_chunk_array;
 699   size_t     _survivor_chunk_index;
 700   size_t     _survivor_chunk_capacity;
 701   size_t*    _cursor;
 702   ChunkArray* _survivor_plab_array;
 703 
 704   // Support for marking stack overflow handling
 705   bool take_from_overflow_list(size_t num, CMSMarkStack* to_stack);
 706   bool par_take_from_overflow_list(size_t num, OopTaskQueue* to_work_q);
 707   void push_on_overflow_list(oop p);
 708   void par_push_on_overflow_list(oop p);
 709   // the following is, obviously, not, in general, "MT-stable"
 710   bool overflow_list_is_empty() const;
 711   
 712   void preserve_mark_if_necessary(oop p);
 713   void par_preserve_mark_if_necessary(oop p);
 714   void preserve_mark_work(oop p, markOop m);
 715   void restore_preserved_marks_if_any();
 716   NOT_PRODUCT(bool no_preserved_marks() const;)
 717   // in support of testing overflow code
 718   NOT_PRODUCT(int _overflow_counter;)
 719   NOT_PRODUCT(bool simulate_overflow();)       // sequential
 720   NOT_PRODUCT(bool par_simulate_overflow();)   // MT version
 721 
 722   int _roots_scanning_options;
 723   int roots_scanning_options() const      { return _roots_scanning_options; }
 724   void add_root_scanning_option(int o)    { _roots_scanning_options |= o;   }
 725   void remove_root_scanning_option(int o) { _roots_scanning_options &= ~o;  }
 726 
 727   // CMS work methods
 728   void checkpointRootsInitialWork(bool asynch); // initial checkpoint work
 729 
 730   // a return value of false indicates failure due to stack overflow
 731   bool markFromRootsWork(bool asynch);  // concurrent marking work
 732 
 733  public:   // FIX ME!!! only for testing
 734   bool do_marking_st(bool asynch);      // single-threaded marking
 735   bool do_marking_mt(bool asynch);      // multi-threaded  marking
 736 
 737  private:
 738 
 739   // concurrent precleaning work
 740   size_t preclean_mod_union_table(ConcurrentMarkSweepGeneration* gen,
 741                                   ScanMarkedObjectsAgainCarefullyClosure* cl);
 742   size_t preclean_card_table(ConcurrentMarkSweepGeneration* gen,
 743                              ScanMarkedObjectsAgainCarefullyClosure* cl);
 744   // Does precleaning work, returning a quantity indicative of
 745   // the amount of "useful work" done.
 746   size_t preclean_work(bool clean_refs, bool clean_survivors);
 747   void abortable_preclean(); // Preclean while looking for possible abort
 748   void initialize_sequential_subtasks_for_young_gen_rescan(int i);
 749   // Helper function for above; merge-sorts the per-thread plab samples
 750   void merge_survivor_plab_arrays(ContiguousSpace* surv);
 751   // Resets (i.e. clears) the per-thread plab sample vectors
 752   void reset_survivor_plab_arrays();
 753 
 754   // final (second) checkpoint work
 755   void checkpointRootsFinalWork(bool asynch, bool clear_all_soft_refs,
 756                                 bool init_mark_was_synchronous);
 757   // work routine for parallel version of remark
 758   void do_remark_parallel();
 759   // work routine for non-parallel version of remark
 760   void do_remark_non_parallel();
 761   // reference processing work routine (during second checkpoint)
 762   void refProcessingWork(bool asynch, bool clear_all_soft_refs);
 763 
 764   // concurrent sweeping work
 765   void sweepWork(ConcurrentMarkSweepGeneration* gen, bool asynch);
 766 
 767   // (concurrent) resetting of support data structures
 768   void reset(bool asynch);
 769 
 770   // Clear _expansion_cause fields of constituent generations
 771   void clear_expansion_cause();
 772 
 773   // An auxilliary method used to record the ends of
 774   // used regions of each generation to limit the extent of sweep
 775   void save_sweep_limits();
 776 
 777   // Resize the generations included in the collector.
 778   void compute_new_size();
 779 
 780   // A work method used by foreground collection to determine
 781   // what type of collection (compacting or not, continuing or fresh)
 782   // it should do.
 783   void decide_foreground_collection_type(bool clear_all_soft_refs,
 784     bool* should_compact, bool* should_start_over);
 785 
 786   // A work method used by the foreground collector to do
 787   // a mark-sweep-compact.
 788   void do_compaction_work(bool clear_all_soft_refs);
 789 
 790   // A work method used by the foreground collector to do
 791   // a mark-sweep, after taking over from a possibly on-going
 792   // concurrent mark-sweep collection.
 793   void do_mark_sweep_work(bool clear_all_soft_refs,
 794     CollectorState first_state, bool should_start_over);
 795 
 796   // If the backgrould GC is active, acquire control from the background
 797   // GC and do the collection.
 798   void acquire_control_and_collect(bool   full, bool clear_all_soft_refs);
 799 
 800   // For synchronizing passing of control from background to foreground
 801   // GC.  waitForForegroundGC() is called by the background
 802   // collector.  It if had to wait for a foreground collection,
 803   // it returns true and the background collection should assume
 804   // that the collection was finished by the foreground
 805   // collector.
 806   bool waitForForegroundGC();
 807 
 808   // Incremental mode triggering:  recompute the icms duty cycle and set the
 809   // allocation limits in the young gen.
 810   void icms_update_allocation_limits();
 811 
 812   size_t block_size_using_printezis_bits(HeapWord* addr) const;
 813   size_t block_size_if_printezis_bits(HeapWord* addr) const;
 814   HeapWord* next_card_start_after_block(HeapWord* addr) const;
 815 
 816   void setup_cms_unloading_and_verification_state();
 817  public:
 818   CMSCollector(ConcurrentMarkSweepGeneration* cmsGen,
 819                ConcurrentMarkSweepGeneration* permGen,
 820                CardTableRS*                   ct,
 821                ConcurrentMarkSweepPolicy*     cp);
 822   ConcurrentMarkSweepThread* cmsThread() { return _cmsThread; }
 823 
 824   ReferenceProcessor* ref_processor() { return _ref_processor; }
 825   void ref_processor_init();
 826 
 827   Mutex* bitMapLock()        const { return _markBitMap.lock();    }
 828   static CollectorState abstract_state() { return _collectorState;  }
 829   double initiatingOccupancy() const { return _initiatingOccupancy; }
 830 
 831   bool should_abort_preclean() const; // Whether preclean should be aborted.
 832   size_t get_eden_used() const;
 833   size_t get_eden_capacity() const;
 834 
 835   ConcurrentMarkSweepGeneration* cmsGen() { return _cmsGen; }
 836 
 837   // locking checks
 838   NOT_PRODUCT(static bool have_cms_token();)
 839 
 840   // XXXPERM bool should_collect(bool full, size_t size, bool tlab);
 841   bool shouldConcurrentCollect();
 842 
 843   void collect(bool   full,
 844                bool   clear_all_soft_refs,
 845                size_t size,
 846                bool   tlab);
 847   void collect_in_background(bool clear_all_soft_refs);
 848   void collect_in_foreground(bool clear_all_soft_refs);
 849 
 850   // In support of ExplicitGCInvokesConcurrent
 851   static void request_full_gc(unsigned int full_gc_count);
 852   // Should we unload classes in a particular concurrent cycle?
 853   bool cms_should_unload_classes() const {
 854     assert(!_unload_classes ||  ExplicitGCInvokesConcurrentAndUnloadsClasses,
 855            "Inconsistency; see CR 6541037");
 856     return _unload_classes || CMSClassUnloadingEnabled;
 857   }
 858 
 859   void direct_allocated(HeapWord* start, size_t size);
 860 
 861   // Object is dead if not marked and current phase is sweeping.
 862   bool is_dead_obj(oop obj) const;
 863 
 864   // After a promotion (of "start"), do any necessary marking.
 865   // If "par", then it's being done by a parallel GC thread.
 866   // The last two args indicate if we need precise marking
 867   // and if so the size of the object so it can be dirtied
 868   // in its entirety.
 869   void promoted(bool par, HeapWord* start,
 870                 bool is_obj_array, size_t obj_size);
 871 
 872   HeapWord* allocation_limit_reached(Space* space, HeapWord* top,
 873                                      size_t word_size);
 874 
 875   void getFreelistLocks() const;
 876   void releaseFreelistLocks() const;
 877   bool haveFreelistLocks() const;
 878 
 879   // GC prologue and epilogue
 880   void gc_prologue(bool full);
 881   void gc_epilogue(bool full);
 882 
 883   jlong time_of_last_gc(jlong now) {
 884     if (_collectorState <= Idling) {
 885       // gc not in progress
 886       return _time_of_last_gc;
 887     } else {
 888       // collection in progress
 889       return now;
 890     }
 891   }
 892 
 893   // Support for parallel remark of survivor space
 894   void* get_data_recorder(int thr_num);
 895 
 896   CMSBitMap* markBitMap()  { return &_markBitMap; }
 897   void directAllocated(HeapWord* start, size_t size);
 898 
 899   // main CMS steps and related support
 900   void checkpointRootsInitial(bool asynch);
 901   bool markFromRoots(bool asynch);  // a return value of false indicates failure
 902                                     // due to stack overflow
 903   void preclean();
 904   void checkpointRootsFinal(bool asynch, bool clear_all_soft_refs,
 905                             bool init_mark_was_synchronous);
 906   void sweep(bool asynch);
 907 
 908   // Check that the currently executing thread is the expected
 909   // one (foreground collector or background collector).
 910   void check_correct_thread_executing()        PRODUCT_RETURN;
 911   // XXXPERM void print_statistics()           PRODUCT_RETURN;
 912 
 913   bool is_cms_reachable(HeapWord* addr);
 914 
 915   // Performance Counter Support
 916   CollectorCounters* counters()    { return _gc_counters; }
 917 
 918   // timer stuff
 919   void    startTimer() { assert(!_timer.is_active(), "Error"); _timer.start();   }
 920   void    stopTimer()  { assert( _timer.is_active(), "Error"); _timer.stop();    }
 921   void    resetTimer() { assert(!_timer.is_active(), "Error"); _timer.reset();   }
 922   double  timerValue() { assert(!_timer.is_active(), "Error"); return _timer.seconds(); }
 923 
 924   int  yields()          { return _numYields; }
 925   void resetYields()     { _numYields = 0;    }
 926   void incrementYields() { _numYields++;      }
 927   void resetNumDirtyCards()               { _numDirtyCards = 0; }
 928   void incrementNumDirtyCards(size_t num) { _numDirtyCards += num; }
 929   size_t  numDirtyCards()                 { return _numDirtyCards; }
 930 
 931   static bool foregroundGCShouldWait() { return _foregroundGCShouldWait; }
 932   static void set_foregroundGCShouldWait(bool v) { _foregroundGCShouldWait = v; }
 933   static bool foregroundGCIsActive() { return _foregroundGCIsActive; }
 934   static void set_foregroundGCIsActive(bool v) { _foregroundGCIsActive = v; }
 935   uint  sweepCount() const             { return _sweepCount; }
 936   void incrementSweepCount()           { _sweepCount++; }
 937 
 938   // Timers/stats for gc scheduling and incremental mode pacing.
 939   CMSStats& stats() { return _stats; }
 940 
 941   // Convenience methods that check whether CMSIncrementalMode is enabled and
 942   // forward to the corresponding methods in ConcurrentMarkSweepThread.
 943   static void start_icms();
 944   static void stop_icms();    // Called at the end of the cms cycle.
 945   static void disable_icms(); // Called before a foreground collection.
 946   static void enable_icms();  // Called after a foreground collection.
 947   void icms_wait();          // Called at yield points.
 948 
 949   // Adaptive size policy
 950   CMSAdaptiveSizePolicy* size_policy();
 951   CMSGCAdaptivePolicyCounters* gc_adaptive_policy_counters();
 952 
 953   // debugging
 954   void verify(bool);
 955   bool verify_after_remark();
 956   void verify_ok_to_terminate() const PRODUCT_RETURN;
 957   void verify_work_stacks_empty() const PRODUCT_RETURN;
 958   void verify_overflow_empty() const PRODUCT_RETURN;
 959 
 960   // convenience methods in support of debugging
 961   static const size_t skip_header_HeapWords() PRODUCT_RETURN0;
 962   HeapWord* block_start(const void* p) const PRODUCT_RETURN0;
 963 
 964   // accessors
 965   CMSMarkStack* verification_mark_stack() { return &_markStack; }
 966   CMSBitMap*    verification_mark_bm()    { return &_verification_mark_bm; }
 967 
 968   // Get the bit map with a perm gen "deadness" information.
 969   CMSBitMap* perm_gen_verify_bit_map()       { return &_perm_gen_verify_bit_map; }
 970 
 971   // Initialization errors
 972   bool completed_initialization() { return _completed_initialization; }
 973 };
 974 
 975 class CMSExpansionCause : public AllStatic  {
 976  public:
 977   enum Cause {
 978     _no_expansion,
 979     _satisfy_free_ratio,
 980     _satisfy_promotion,
 981     _satisfy_allocation,
 982     _allocate_par_lab,
 983     _allocate_par_spooling_space,
 984     _adaptive_size_policy
 985   };
 986   // Return a string describing the cause of the expansion.
 987   static const char* to_string(CMSExpansionCause::Cause cause);
 988 };
 989 
 990 class ConcurrentMarkSweepGeneration: public CardGeneration {
 991   friend class VMStructs;
 992   friend class ConcurrentMarkSweepThread;
 993   friend class ConcurrentMarkSweep;
 994   friend class CMSCollector;
 995  protected:
 996   static CMSCollector*       _collector; // the collector that collects us
 997   CompactibleFreeListSpace*  _cmsSpace;  // underlying space (only one for now)
 998 
 999   // Performance Counters
1000   GenerationCounters*      _gen_counters;
1001   GSpaceCounters*          _space_counters;
1002 
1003   // Words directly allocated, used by CMSStats.
1004   size_t _direct_allocated_words;
1005 
1006   // Non-product stat counters
1007   NOT_PRODUCT(
1008     int _numObjectsPromoted;
1009     int _numWordsPromoted;
1010     int _numObjectsAllocated;
1011     int _numWordsAllocated;
1012   )
1013 
1014   // Used for sizing decisions
1015   bool _incremental_collection_failed;
1016   bool incremental_collection_failed() {
1017     return _incremental_collection_failed;
1018   }
1019   void set_incremental_collection_failed() {
1020     _incremental_collection_failed = true;
1021   }
1022   void clear_incremental_collection_failed() {
1023     _incremental_collection_failed = false;
1024   }
1025 
1026  private:
1027   // For parallel young-gen GC support.
1028   CMSParGCThreadState** _par_gc_thread_states;
1029 
1030   // Reason generation was expanded
1031   CMSExpansionCause::Cause _expansion_cause;
1032 
1033   // accessors
1034   void set_expansion_cause(CMSExpansionCause::Cause v) { _expansion_cause = v;}
1035   CMSExpansionCause::Cause expansion_cause() { return _expansion_cause; }
1036 
1037   // In support of MinChunkSize being larger than min object size
1038   const double _dilatation_factor;
1039 
1040   enum CollectionTypes {
1041     Concurrent_collection_type          = 0,
1042     MS_foreground_collection_type       = 1,
1043     MSC_foreground_collection_type      = 2,
1044     Unknown_collection_type             = 3
1045   };
1046 
1047   CollectionTypes _debug_collection_type;
1048 
1049  protected:
1050   // Grow generation by specified size (returns false if unable to grow)
1051   bool grow_by(size_t bytes);
1052   // Grow generation to reserved size.
1053   bool grow_to_reserved();
1054   // Shrink generation by specified size (returns false if unable to shrink)
1055   virtual void shrink_by(size_t bytes);
1056 
1057   // Update statistics for GC
1058   virtual void update_gc_stats(int level, bool full);
1059 
1060   // Maximum available space in the generation (including uncommitted)
1061   // space.
1062   size_t max_available() const;
1063 
1064  public:
1065   ConcurrentMarkSweepGeneration(ReservedSpace rs, size_t initial_byte_size,
1066                                 int level, CardTableRS* ct,
1067                                 bool use_adaptive_freelists,
1068                                 FreeBlockDictionary::DictionaryChoice);
1069 
1070   // Accessors
1071   CMSCollector* collector() const { return _collector; }
1072   static void set_collector(CMSCollector* collector) {
1073     assert(_collector == NULL, "already set");
1074     _collector = collector;
1075   }
1076   CompactibleFreeListSpace*  cmsSpace() const { return _cmsSpace;  }
1077   
1078   Mutex* freelistLock() const;
1079 
1080   virtual Generation::Name kind() { return Generation::ConcurrentMarkSweep; }
1081 
1082   // Adaptive size policy
1083   CMSAdaptiveSizePolicy* size_policy();
1084 
1085   bool refs_discovery_is_atomic() const { return false; }
1086   bool refs_discovery_is_mt()     const {
1087     // Note: CMS does MT-discovery during the parallel-remark
1088     // phases. Use ReferenceProcessorMTMutator to make refs
1089     // discovery MT-safe during such phases or other parallel
1090     // discovery phases in the future. This may all go away
1091     // if/when we decide that refs discovery is sufficiently
1092     // rare that the cost of the CAS's involved is in the
1093     // noise. That's a measurement that should be done, and
1094     // the code simplified if that turns out to be the case.
1095     return false;
1096   }
1097 
1098   // Override
1099   virtual void ref_processor_init();
1100 
1101   void clear_expansion_cause() { _expansion_cause = CMSExpansionCause::_no_expansion; }
1102 
1103   // Space enquiries
1104   size_t capacity() const;
1105   size_t used() const;
1106   size_t free() const;
1107   double occupancy()      { return ((double)used())/((double)capacity()); }
1108   size_t contiguous_available() const;
1109   size_t unsafe_max_alloc_nogc() const;
1110 
1111   // over-rides
1112   MemRegion used_region() const;
1113   MemRegion used_region_at_save_marks() const;
1114 
1115   // Does a "full" (forced) collection invoked on this generation collect
1116   // all younger generations as well? Note that the second conjunct is a
1117   // hack to allow the collection of the younger gen first if the flag is
1118   // set. This is better than using th policy's should_collect_gen0_first()
1119   // since that causes us to do an extra unnecessary pair of restart-&-stop-world.
1120   virtual bool full_collects_younger_generations() const {
1121     return UseCMSCompactAtFullCollection && !CollectGen0First;
1122   }
1123 
1124   void space_iterate(SpaceClosure* blk, bool usedOnly = false);
1125 
1126   // Support for compaction
1127   CompactibleSpace* first_compaction_space() const;
1128   // Adjust quantites in the generation affected by
1129   // the compaction.
1130   void reset_after_compaction();
1131 
1132   // Allocation support
1133   HeapWord* allocate(size_t size, bool tlab);
1134   HeapWord* have_lock_and_allocate(size_t size, bool tlab);
1135   oop       promote(oop obj, size_t obj_size, oop* ref);
1136   HeapWord* par_allocate(size_t size, bool tlab) {
1137     return allocate(size, tlab);
1138   }
1139 
1140   // Incremental mode triggering.
1141   HeapWord* allocation_limit_reached(Space* space, HeapWord* top,
1142                                      size_t word_size);
1143 
1144   // Used by CMSStats to track direct allocation.  The value is sampled and
1145   // reset after each young gen collection.
1146   size_t direct_allocated_words() const { return _direct_allocated_words; }
1147   void reset_direct_allocated_words()   { _direct_allocated_words = 0; }
1148 
1149   // Overrides for parallel promotion.
1150   virtual oop par_promote(int thread_num,
1151                           oop obj, markOop m, size_t word_sz);
1152   // This one should not be called for CMS.
1153   virtual void par_promote_alloc_undo(int thread_num,
1154                                       HeapWord* obj, size_t word_sz);
1155   virtual void par_promote_alloc_done(int thread_num);
1156   virtual void par_oop_since_save_marks_iterate_done(int thread_num);
1157 
1158   virtual bool promotion_attempt_is_safe(size_t promotion_in_bytes,
1159     bool younger_handles_promotion_failure) const;
1160 
1161   bool should_collect(bool full, size_t size, bool tlab);
1162     // XXXPERM
1163   bool shouldConcurrentCollect(double initiatingOccupancy); // XXXPERM
1164   void collect(bool   full,
1165                bool   clear_all_soft_refs,
1166                size_t size,
1167                bool   tlab);
1168 
1169   HeapWord* expand_and_allocate(size_t word_size,
1170                                 bool tlab,
1171                                 bool parallel = false);
1172 
1173   // GC prologue and epilogue
1174   void gc_prologue(bool full);
1175   void gc_prologue_work(bool full, bool registerClosure,
1176                         ModUnionClosure* modUnionClosure);
1177   void gc_epilogue(bool full);
1178   void gc_epilogue_work(bool full);
1179 
1180   // Time since last GC of this generation
1181   jlong time_of_last_gc(jlong now) {
1182     return collector()->time_of_last_gc(now);
1183   }
1184   void update_time_of_last_gc(jlong now) {
1185     collector()-> update_time_of_last_gc(now);
1186   }
1187 
1188   // Allocation failure
1189   void expand(size_t bytes, size_t expand_bytes, 
1190     CMSExpansionCause::Cause cause);
1191   void shrink(size_t bytes);
1192   HeapWord* expand_and_par_lab_allocate(CMSParGCThreadState* ps, size_t word_sz);
1193   bool expand_and_ensure_spooling_space(PromotionInfo* promo);
1194 
1195   // Iteration support and related enquiries
1196   void save_marks();
1197   bool no_allocs_since_save_marks();
1198   void object_iterate_since_last_GC(ObjectClosure* cl);
1199   void younger_refs_iterate(OopsInGenClosure* cl);
1200 
1201   // Iteration support specific to CMS generations
1202   void save_sweep_limit();
1203 
1204   // More iteration support
1205   virtual void oop_iterate(MemRegion mr, OopClosure* cl);
1206   virtual void oop_iterate(OopClosure* cl);
1207   virtual void object_iterate(ObjectClosure* cl);
1208 
1209   // Need to declare the full complement of closures, whether we'll
1210   // override them or not, or get message from the compiler:
1211   //   oop_since_save_marks_iterate_nv hides virtual function...
1212   #define CMS_SINCE_SAVE_MARKS_DECL(OopClosureType, nv_suffix) \
1213     void oop_since_save_marks_iterate##nv_suffix(OopClosureType* cl);
1214   ALL_SINCE_SAVE_MARKS_CLOSURES(CMS_SINCE_SAVE_MARKS_DECL)
1215 
1216   // Smart allocation  XXX -- move to CFLSpace?
1217   void setNearLargestChunk();
1218   bool isNearLargestChunk(HeapWord* addr);
1219 
1220   // Get the chunk at the end of the space.  Delagates to
1221   // the space.
1222   FreeChunk* find_chunk_at_end(); 
1223 
1224   // Overriding of unused functionality (sharing not yet supported with CMS)
1225   void pre_adjust_pointers();
1226   void post_compact();
1227 
1228   // Debugging
1229   void prepare_for_verify();
1230   void verify(bool allow_dirty);
1231   void print_statistics()               PRODUCT_RETURN;
1232 
1233   // Performance Counters support
1234   virtual void update_counters();
1235   virtual void update_counters(size_t used);
1236   void initialize_performance_counters();
1237   CollectorCounters* counters()  { return collector()->counters(); }
1238 
1239   // Support for parallel remark of survivor space
1240   void* get_data_recorder(int thr_num) {
1241     //Delegate to collector
1242     return collector()->get_data_recorder(thr_num);
1243   }
1244 
1245   // Printing
1246   const char* name() const;
1247   virtual const char* short_name() const { return "CMS"; }
1248   void        print() const;
1249   void printOccupancy(const char* s);
1250   bool must_be_youngest() const { return false; }
1251   bool must_be_oldest()   const { return true; }
1252 
1253   void compute_new_size();
1254 
1255   CollectionTypes debug_collection_type() { return _debug_collection_type; }
1256   void rotate_debug_collection_type();
1257 };
1258 
1259 class ASConcurrentMarkSweepGeneration : public ConcurrentMarkSweepGeneration {
1260 
1261   // Return the size policy from the heap's collector
1262   // policy casted to CMSAdaptiveSizePolicy*.
1263   CMSAdaptiveSizePolicy* cms_size_policy() const;
1264 
1265   // Resize the generation based on the adaptive size
1266   // policy.
1267   void resize(size_t cur_promo, size_t desired_promo);
1268 
1269   // Return the GC counters from the collector policy
1270   CMSGCAdaptivePolicyCounters* gc_adaptive_policy_counters();
1271 
1272   virtual void shrink_by(size_t bytes);
1273 
1274  public:
1275   virtual void compute_new_size();
1276   ASConcurrentMarkSweepGeneration(ReservedSpace rs, size_t initial_byte_size,
1277                                   int level, CardTableRS* ct,
1278                                   bool use_adaptive_freelists,
1279                                   FreeBlockDictionary::DictionaryChoice 
1280                                     dictionaryChoice) :
1281     ConcurrentMarkSweepGeneration(rs, initial_byte_size, level, ct,
1282       use_adaptive_freelists, dictionaryChoice) {}
1283 
1284   virtual const char* short_name() const { return "ASCMS"; }
1285   virtual Generation::Name kind() { return Generation::ASConcurrentMarkSweep; }
1286 
1287   virtual void update_counters();
1288   virtual void update_counters(size_t used);
1289 };
1290 
1291 //
1292 // Closures of various sorts used by CMS to accomplish its work
1293 //
1294 
1295 // This closure is used to check that a certain set of oops is empty.
1296 class FalseClosure: public OopClosure {
1297  public:
1298   void do_oop(oop* p) {
1299     guarantee(false, "Should be an empty set");
1300   }
1301 };
1302 
1303 // This closure is used to do concurrent marking from the roots
1304 // following the first checkpoint. 
1305 class MarkFromRootsClosure: public BitMapClosure {
1306   CMSCollector*  _collector;
1307   MemRegion      _span;
1308   CMSBitMap*     _bitMap;
1309   CMSBitMap*     _mut;
1310   CMSMarkStack*  _markStack;
1311   CMSMarkStack*  _revisitStack;
1312   bool           _yield;
1313   int            _skipBits;
1314   HeapWord*      _finger;
1315   HeapWord*      _threshold;
1316   DEBUG_ONLY(bool _verifying;)
1317 
1318  public:
1319   MarkFromRootsClosure(CMSCollector* collector, MemRegion span,
1320                        CMSBitMap* bitMap,
1321                        CMSMarkStack*  markStack,
1322                        CMSMarkStack*  revisitStack,
1323                        bool should_yield, bool verifying = false);
1324   void do_bit(size_t offset);
1325   void reset(HeapWord* addr);
1326   inline void do_yield_check();
1327 
1328  private:
1329   void scanOopsInOop(HeapWord* ptr);
1330   void do_yield_work();
1331 };
1332 
1333 // This closure is used to do concurrent multi-threaded
1334 // marking from the roots following the first checkpoint. 
1335 // XXX This should really be a subclass of The serial version
1336 // above, but i have not had the time to refactor things cleanly.
1337 // That willbe done for Dolphin.
1338 class Par_MarkFromRootsClosure: public BitMapClosure {
1339   CMSCollector*  _collector;
1340   MemRegion      _whole_span;
1341   MemRegion      _span;
1342   CMSBitMap*     _bit_map;
1343   CMSBitMap*     _mut;
1344   OopTaskQueue*  _work_queue;
1345   CMSMarkStack*  _overflow_stack;
1346   CMSMarkStack*  _revisit_stack;
1347   bool           _yield;
1348   int            _skip_bits;
1349   HeapWord*      _finger;
1350   HeapWord*      _threshold;
1351   CMSConcMarkingTask* _task;
1352  public:
1353   Par_MarkFromRootsClosure(CMSConcMarkingTask* task, CMSCollector* collector,
1354                        MemRegion span,
1355                        CMSBitMap* bit_map,
1356                        OopTaskQueue* work_queue,
1357                        CMSMarkStack*  overflow_stack,
1358                        CMSMarkStack*  revisit_stack,
1359                        bool should_yield);
1360   void do_bit(size_t offset);
1361   inline void do_yield_check();
1362 
1363  private:
1364   void scan_oops_in_oop(HeapWord* ptr);
1365   void do_yield_work();
1366   bool get_work_from_overflow_stack();
1367 };
1368 
1369 // The following closures are used to do certain kinds of verification of
1370 // CMS marking.
1371 class PushAndMarkVerifyClosure: public OopClosure {
1372   CMSCollector*    _collector;
1373   MemRegion        _span;
1374   CMSBitMap*       _verification_bm;
1375   CMSBitMap*       _cms_bm;
1376   CMSMarkStack*    _mark_stack;
1377  public:
1378   PushAndMarkVerifyClosure(CMSCollector* cms_collector,
1379                            MemRegion span,
1380                            CMSBitMap* verification_bm,
1381                            CMSBitMap* cms_bm,
1382                            CMSMarkStack*  mark_stack);
1383   void do_oop(oop* p);
1384   // Deal with a stack overflow condition
1385   void handle_stack_overflow(HeapWord* lost);
1386 };
1387 
1388 class MarkFromRootsVerifyClosure: public BitMapClosure {
1389   CMSCollector*  _collector;
1390   MemRegion      _span;
1391   CMSBitMap*     _verification_bm;
1392   CMSBitMap*     _cms_bm;
1393   CMSMarkStack*  _mark_stack;
1394   HeapWord*      _finger;
1395   PushAndMarkVerifyClosure _pam_verify_closure;
1396  public:
1397   MarkFromRootsVerifyClosure(CMSCollector* collector, MemRegion span,
1398                              CMSBitMap* verification_bm,
1399                              CMSBitMap* cms_bm,
1400                              CMSMarkStack*  mark_stack);
1401   void do_bit(size_t offset);
1402   void reset(HeapWord* addr);
1403 };
1404 
1405 
1406 // This closure is used to check that a certain set of bits is
1407 // "empty" (i.e. the bit vector doesn't have any 1-bits).
1408 class FalseBitMapClosure: public BitMapClosure {
1409  public:
1410   void do_bit(size_t offset) {
1411     guarantee(false, "Should not have a 1 bit"); 
1412   }
1413 };
1414 
1415 // This closure is used during the second checkpointing phase
1416 // to rescan the marked objects on the dirty cards in the mod
1417 // union table and the card table proper. It's invoked via
1418 // MarkFromDirtyCardsClosure below. It uses either
1419 // [Par_]MarkRefsIntoAndScanClosure (Par_ in the parallel case)
1420 // declared in genOopClosures.hpp to accomplish some of its work.
1421 // In the parallel case the bitMap is shared, so access to
1422 // it needs to be suitably synchronized for updates by embedded
1423 // closures that update it; however, this closure itself only
1424 // reads the bit_map and because it is idempotent, is immune to
1425 // reading stale values.
1426 class ScanMarkedObjectsAgainClosure: public UpwardsObjectClosure {
1427   #ifdef ASSERT
1428     CMSCollector*          _collector;
1429     MemRegion              _span;
1430     union {
1431       CMSMarkStack*        _mark_stack;
1432       OopTaskQueue*        _work_queue;
1433     };
1434   #endif // ASSERT
1435   bool                       _parallel;
1436   CMSBitMap*                 _bit_map;
1437   union {
1438     MarkRefsIntoAndScanClosure*     _scan_closure;
1439     Par_MarkRefsIntoAndScanClosure* _par_scan_closure;
1440   };
1441 
1442  public:
1443   ScanMarkedObjectsAgainClosure(CMSCollector* collector,
1444                                 MemRegion span,
1445                                 ReferenceProcessor* rp,
1446                                 CMSBitMap* bit_map,
1447                                 CMSMarkStack*  mark_stack,
1448                                 CMSMarkStack*  revisit_stack,
1449                                 MarkRefsIntoAndScanClosure* cl):
1450     #ifdef ASSERT
1451       _collector(collector),
1452       _span(span),
1453       _mark_stack(mark_stack),
1454     #endif // ASSERT
1455     _parallel(false),
1456     _bit_map(bit_map),
1457     _scan_closure(cl) { }
1458 
1459   ScanMarkedObjectsAgainClosure(CMSCollector* collector,
1460                                 MemRegion span,
1461                                 ReferenceProcessor* rp,
1462                                 CMSBitMap* bit_map,
1463                                 OopTaskQueue* work_queue,
1464                                 CMSMarkStack* revisit_stack,
1465                                 Par_MarkRefsIntoAndScanClosure* cl):
1466     #ifdef ASSERT
1467       _collector(collector),
1468       _span(span),
1469       _work_queue(work_queue),
1470     #endif // ASSERT
1471     _parallel(true),
1472     _bit_map(bit_map),
1473     _par_scan_closure(cl) { }
1474                                 
1475   void do_object(oop obj) {
1476     guarantee(false, "Call do_object_b(oop, MemRegion) instead");
1477   }
1478   bool do_object_b(oop obj) {
1479     guarantee(false, "Call do_object_b(oop, MemRegion) form instead");
1480     return false;
1481   }
1482   bool do_object_bm(oop p, MemRegion mr);
1483 };
1484 
1485 // This closure is used during the second checkpointing phase
1486 // to rescan the marked objects on the dirty cards in the mod
1487 // union table and the card table proper. It invokes
1488 // ScanMarkedObjectsAgainClosure above to accomplish much of its work.
1489 // In the parallel case, the bit map is shared and requires
1490 // synchronized access.
1491 class MarkFromDirtyCardsClosure: public MemRegionClosure {
1492   CompactibleFreeListSpace*      _space;
1493   ScanMarkedObjectsAgainClosure  _scan_cl;
1494   size_t                         _num_dirty_cards;
1495 
1496  public:
1497   MarkFromDirtyCardsClosure(CMSCollector* collector,
1498                             MemRegion span,
1499                             CompactibleFreeListSpace* space,
1500                             CMSBitMap* bit_map,
1501                             CMSMarkStack* mark_stack,
1502                             CMSMarkStack* revisit_stack,
1503                             MarkRefsIntoAndScanClosure* cl):
1504     _space(space),
1505     _num_dirty_cards(0),
1506     _scan_cl(collector, span, collector->ref_processor(), bit_map,
1507                  mark_stack, revisit_stack, cl) { }
1508 
1509   MarkFromDirtyCardsClosure(CMSCollector* collector,
1510                             MemRegion span,
1511                             CompactibleFreeListSpace* space,
1512                             CMSBitMap* bit_map,
1513                             OopTaskQueue* work_queue,
1514                             CMSMarkStack* revisit_stack,
1515                             Par_MarkRefsIntoAndScanClosure* cl):
1516     _space(space),
1517     _num_dirty_cards(0),
1518     _scan_cl(collector, span, collector->ref_processor(), bit_map,
1519              work_queue, revisit_stack, cl) { }
1520 
1521   void do_MemRegion(MemRegion mr);
1522   void set_space(CompactibleFreeListSpace* space) { _space = space; }
1523   size_t num_dirty_cards() { return _num_dirty_cards; }
1524 };
1525 
1526 // This closure is used in the non-product build to check
1527 // that there are no MemRegions with a certain property.
1528 class FalseMemRegionClosure: public MemRegionClosure {
1529   void do_MemRegion(MemRegion mr) {
1530     guarantee(!mr.is_empty(), "Shouldn't be empty");
1531     guarantee(false, "Should never be here");
1532   }
1533 };
1534 
1535 // This closure is used during the precleaning phase
1536 // to "carefully" rescan marked objects on dirty cards.
1537 // It uses MarkRefsIntoAndScanClosure declared in genOopClosures.hpp
1538 // to accomplish some of its work.
1539 class ScanMarkedObjectsAgainCarefullyClosure: public ObjectClosureCareful {
1540   CMSCollector*                  _collector;
1541   MemRegion                      _span;
1542   bool                           _yield;
1543   Mutex*                         _freelistLock;
1544   CMSBitMap*                     _bitMap;
1545   CMSMarkStack*                  _markStack;
1546   MarkRefsIntoAndScanClosure*    _scanningClosure;
1547 
1548  public:
1549   ScanMarkedObjectsAgainCarefullyClosure(CMSCollector* collector,
1550                                          MemRegion     span,
1551                                          CMSBitMap* bitMap,
1552                                          CMSMarkStack*  markStack,
1553                                          CMSMarkStack*  revisitStack,
1554                                          MarkRefsIntoAndScanClosure* cl,
1555                                          bool should_yield):
1556     _collector(collector),
1557     _span(span),
1558     _yield(should_yield),
1559     _bitMap(bitMap),
1560     _markStack(markStack),
1561     _scanningClosure(cl) {
1562   }
1563   
1564   void do_object(oop p) {
1565     guarantee(false, "call do_object_careful instead");
1566   }
1567 
1568   size_t      do_object_careful(oop p) {
1569     guarantee(false, "Unexpected caller");
1570     return 0;
1571   }
1572 
1573   size_t      do_object_careful_m(oop p, MemRegion mr);
1574 
1575   void setFreelistLock(Mutex* m) {
1576     _freelistLock = m;
1577     _scanningClosure->set_freelistLock(m);
1578   }
1579 
1580  private:
1581   inline bool do_yield_check();
1582 
1583   void do_yield_work();
1584 };
1585 
1586 class SurvivorSpacePrecleanClosure: public ObjectClosureCareful {
1587   CMSCollector*                  _collector;
1588   MemRegion                      _span;
1589   bool                           _yield;
1590   CMSBitMap*                     _bit_map;
1591   CMSMarkStack*                  _mark_stack;
1592   PushAndMarkClosure*            _scanning_closure;
1593   unsigned int                   _before_count;
1594 
1595  public:
1596   SurvivorSpacePrecleanClosure(CMSCollector* collector,
1597                                MemRegion     span,
1598                                CMSBitMap*    bit_map,
1599                                CMSMarkStack* mark_stack,
1600                                PushAndMarkClosure* cl,
1601                                unsigned int  before_count,
1602                                bool          should_yield):
1603     _collector(collector),
1604     _span(span),
1605     _yield(should_yield),
1606     _bit_map(bit_map),
1607     _mark_stack(mark_stack),
1608     _scanning_closure(cl),
1609     _before_count(before_count)
1610   { }
1611 
1612   void do_object(oop p) {
1613     guarantee(false, "call do_object_careful instead");
1614   }
1615 
1616   size_t      do_object_careful(oop p);
1617 
1618   size_t      do_object_careful_m(oop p, MemRegion mr) {
1619     guarantee(false, "Unexpected caller");
1620     return 0;
1621   }
1622 
1623  private:
1624   inline void do_yield_check();
1625   void do_yield_work();
1626 };
1627 
1628 // This closure is used to accomplish the sweeping work
1629 // after the second checkpoint but before the concurrent reset
1630 // phase.
1631 // 
1632 // Terminology
1633 //   left hand chunk (LHC) - block of one or more chunks currently being
1634 //     coalesced.  The LHC is available for coalescing with a new chunk.
1635 //   right hand chunk (RHC) - block that is currently being swept that is
1636 //     free or garbage that can be coalesced with the LHC.
1637 // _inFreeRange is true if there is currently a LHC
1638 // _lastFreeRangeCoalesced is true if the LHC consists of more than one chunk.
1639 // _freeRangeInFreeLists is true if the LHC is in the free lists.
1640 // _freeFinger is the address of the current LHC
1641 class SweepClosure: public BlkClosureCareful {
1642   CMSCollector*                  _collector;  // collector doing the work
1643   ConcurrentMarkSweepGeneration* _g;    // Generation being swept
1644   CompactibleFreeListSpace*      _sp;   // Space being swept
1645   HeapWord*                      _limit;
1646   Mutex*                         _freelistLock; // Free list lock (in space)
1647   CMSBitMap*                     _bitMap;       // Marking bit map (in 
1648                                                 // generation)
1649   bool                           _inFreeRange;  // Indicates if we are in the
1650                                                 // midst of a free run
1651   bool                           _freeRangeInFreeLists; 
1652                                         // Often, we have just found
1653                                         // a free chunk and started
1654                                         // a new free range; we do not
1655                                         // eagerly remove this chunk from
1656                                         // the free lists unless there is
1657                                         // a possibility of coalescing.
1658                                         // When true, this flag indicates
1659                                         // that the _freeFinger below
1660                                         // points to a potentially free chunk
1661                                         // that may still be in the free lists
1662   bool                           _lastFreeRangeCoalesced;
1663                                         // free range contains chunks
1664                                         // coalesced
1665   bool                           _yield;        
1666                                         // Whether sweeping should be 
1667                                         // done with yields. For instance 
1668                                         // when done by the foreground 
1669                                         // collector we shouldn't yield.
1670   HeapWord*                      _freeFinger;   // When _inFreeRange is set, the
1671                                                 // pointer to the "left hand 
1672                                                 // chunk"
1673   size_t                         _freeRangeSize; 
1674                                         // When _inFreeRange is set, this 
1675                                         // indicates the accumulated size 
1676                                         // of the "left hand chunk"
1677   NOT_PRODUCT(
1678     size_t                       _numObjectsFreed;
1679     size_t                       _numWordsFreed;
1680     size_t                       _numObjectsLive;
1681     size_t                       _numWordsLive;
1682     size_t                       _numObjectsAlreadyFree;
1683     size_t                       _numWordsAlreadyFree;
1684     FreeChunk*                   _last_fc;
1685   )
1686  private:
1687   // Code that is common to a free chunk or garbage when
1688   // encountered during sweeping.
1689   void doPostIsFreeOrGarbageChunk(FreeChunk *fc, 
1690                                   size_t chunkSize);
1691   // Process a free chunk during sweeping.
1692   void doAlreadyFreeChunk(FreeChunk *fc);
1693   // Process a garbage chunk during sweeping.
1694   size_t doGarbageChunk(FreeChunk *fc);
1695   // Process a live chunk during sweeping.
1696   size_t doLiveChunk(FreeChunk* fc);
1697 
1698   // Accessors.
1699   HeapWord* freeFinger() const          { return _freeFinger; }
1700   void set_freeFinger(HeapWord* v)      { _freeFinger = v; }
1701   size_t freeRangeSize() const          { return _freeRangeSize; }
1702   void set_freeRangeSize(size_t v)      { _freeRangeSize = v; }
1703   bool inFreeRange()    const           { return _inFreeRange; }
1704   void set_inFreeRange(bool v)          { _inFreeRange = v; }
1705   bool lastFreeRangeCoalesced() const    { return _lastFreeRangeCoalesced; }
1706   void set_lastFreeRangeCoalesced(bool v) { _lastFreeRangeCoalesced = v; }
1707   bool freeRangeInFreeLists() const     { return _freeRangeInFreeLists; }
1708   void set_freeRangeInFreeLists(bool v) { _freeRangeInFreeLists = v; }
1709 
1710   // Initialize a free range.
1711   void initialize_free_range(HeapWord* freeFinger, bool freeRangeInFreeLists);
1712   // Return this chunk to the free lists.
1713   void flushCurFreeChunk(HeapWord* chunk, size_t size);
1714 
1715   // Check if we should yield and do so when necessary.
1716   inline void do_yield_check(HeapWord* addr);
1717 
1718   // Yield
1719   void do_yield_work(HeapWord* addr);
1720 
1721   // Debugging/Printing
1722   void record_free_block_coalesced(FreeChunk* fc) const PRODUCT_RETURN;
1723 
1724  public:
1725   SweepClosure(CMSCollector* collector, ConcurrentMarkSweepGeneration* g,
1726                CMSBitMap* bitMap, bool should_yield);
1727   ~SweepClosure();
1728 
1729   size_t       do_blk_careful(HeapWord* addr);
1730 };
1731 
1732 // Closures related to weak references processing
1733 
1734 // During CMS' weak reference processing, this is a
1735 // work-routine/closure used to complete transitive
1736 // marking of objects as live after a certain point
1737 // in which an initial set has been completely accumulated.
1738 class CMSDrainMarkingStackClosure: public VoidClosure {
1739   CMSCollector*        _collector;
1740   MemRegion            _span;
1741   CMSMarkStack*        _mark_stack;
1742   CMSBitMap*           _bit_map;
1743   CMSKeepAliveClosure* _keep_alive;
1744  public:
1745   CMSDrainMarkingStackClosure(CMSCollector* collector, MemRegion span,
1746                       CMSBitMap* bit_map, CMSMarkStack* mark_stack,
1747                       CMSKeepAliveClosure* keep_alive):
1748     _collector(collector),
1749     _span(span),
1750     _bit_map(bit_map),
1751     _mark_stack(mark_stack),
1752     _keep_alive(keep_alive) { }
1753 
1754   void do_void();
1755 };
1756 
1757 // A parallel version of CMSDrainMarkingStackClosure above.
1758 class CMSParDrainMarkingStackClosure: public VoidClosure {
1759   CMSCollector*           _collector;
1760   MemRegion               _span;
1761   OopTaskQueue*           _work_queue;
1762   CMSBitMap*              _bit_map;
1763   CMSInnerParMarkAndPushClosure _mark_and_push;
1764 
1765  public:
1766   CMSParDrainMarkingStackClosure(CMSCollector* collector,
1767                                  MemRegion span, CMSBitMap* bit_map,
1768                                  OopTaskQueue* work_queue):
1769     _collector(collector),
1770     _span(span),
1771     _bit_map(bit_map),
1772     _work_queue(work_queue),
1773     _mark_and_push(collector, span, bit_map, work_queue) { }
1774 
1775  public:
1776   void trim_queue(uint max);
1777   void do_void();
1778 };
1779 
1780 // Allow yielding or short-circuiting of reference list
1781 // prelceaning work.
1782 class CMSPrecleanRefsYieldClosure: public YieldClosure {
1783   CMSCollector* _collector;
1784   void do_yield_work();
1785  public:
1786   CMSPrecleanRefsYieldClosure(CMSCollector* collector):
1787     _collector(collector) {}
1788   virtual bool should_return();
1789 };
1790 
1791 
1792 // Convenience class that locks free list locks for given CMS collector
1793 class FreelistLocker: public StackObj {
1794  private:
1795   CMSCollector* _collector;
1796  public:
1797   FreelistLocker(CMSCollector* collector):
1798     _collector(collector) {
1799     _collector->getFreelistLocks();
1800   }
1801 
1802   ~FreelistLocker() {
1803     _collector->releaseFreelistLocks();
1804   }
1805 };
1806 
1807 // Mark all dead objects in a given space.
1808 class MarkDeadObjectsClosure: public BlkClosure {
1809   const CMSCollector*             _collector;
1810   const CompactibleFreeListSpace* _sp;
1811   CMSBitMap*                      _live_bit_map;
1812   CMSBitMap*                      _dead_bit_map;
1813 public:
1814   MarkDeadObjectsClosure(const CMSCollector* collector,
1815                          const CompactibleFreeListSpace* sp, 
1816                          CMSBitMap *live_bit_map,
1817                          CMSBitMap *dead_bit_map) :
1818     _collector(collector),
1819     _sp(sp),
1820     _live_bit_map(live_bit_map),
1821     _dead_bit_map(dead_bit_map) {}
1822   size_t do_blk(HeapWord* addr);
1823 };