src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp

Tue, 27 Nov 2012 07:57:57 -0800

author
mikael
date
Tue, 27 Nov 2012 07:57:57 -0800
changeset 4290
7c15faa95ce7
parent 4037
da91efe96a93
child 4576
f64ffbf81af5
permissions
-rw-r--r--

8003879: Duplicate definitions in vmStructs
Summary: Removed duplicate entries
Reviewed-by: dholmes, sspitsyn

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

mercurial