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