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