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