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

Thu, 13 Feb 2014 17:44:39 +0100

author
stefank
date
Thu, 13 Feb 2014 17:44:39 +0100
changeset 6971
7426d8d76305
parent 6968
9fec19bb0659
child 6978
30c99d8e0f02
permissions
-rw-r--r--

8034761: Remove the do_code_roots parameter from process_strong_roots
Reviewed-by: tschatzl, mgerdin, jmasa

     1 /*
     2  * Copyright (c) 2001, 2014, 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 #include "precompiled.hpp"
    26 #include "classfile/classLoaderData.hpp"
    27 #include "classfile/symbolTable.hpp"
    28 #include "classfile/systemDictionary.hpp"
    29 #include "code/codeCache.hpp"
    30 #include "gc_implementation/concurrentMarkSweep/cmsAdaptiveSizePolicy.hpp"
    31 #include "gc_implementation/concurrentMarkSweep/cmsCollectorPolicy.hpp"
    32 #include "gc_implementation/concurrentMarkSweep/cmsGCAdaptivePolicyCounters.hpp"
    33 #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
    34 #include "gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp"
    35 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.inline.hpp"
    36 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
    37 #include "gc_implementation/concurrentMarkSweep/vmCMSOperations.hpp"
    38 #include "gc_implementation/parNew/parNewGeneration.hpp"
    39 #include "gc_implementation/shared/collectorCounters.hpp"
    40 #include "gc_implementation/shared/gcTimer.hpp"
    41 #include "gc_implementation/shared/gcTrace.hpp"
    42 #include "gc_implementation/shared/gcTraceTime.hpp"
    43 #include "gc_implementation/shared/isGCActiveMark.hpp"
    44 #include "gc_interface/collectedHeap.inline.hpp"
    45 #include "memory/allocation.hpp"
    46 #include "memory/cardTableRS.hpp"
    47 #include "memory/collectorPolicy.hpp"
    48 #include "memory/gcLocker.inline.hpp"
    49 #include "memory/genCollectedHeap.hpp"
    50 #include "memory/genMarkSweep.hpp"
    51 #include "memory/genOopClosures.inline.hpp"
    52 #include "memory/iterator.hpp"
    53 #include "memory/padded.hpp"
    54 #include "memory/referencePolicy.hpp"
    55 #include "memory/resourceArea.hpp"
    56 #include "memory/tenuredGeneration.hpp"
    57 #include "oops/oop.inline.hpp"
    58 #include "prims/jvmtiExport.hpp"
    59 #include "runtime/globals_extension.hpp"
    60 #include "runtime/handles.inline.hpp"
    61 #include "runtime/java.hpp"
    62 #include "runtime/orderAccess.inline.hpp"
    63 #include "runtime/vmThread.hpp"
    64 #include "services/memoryService.hpp"
    65 #include "services/runtimeService.hpp"
    67 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
    69 // statics
    70 CMSCollector* ConcurrentMarkSweepGeneration::_collector = NULL;
    71 bool CMSCollector::_full_gc_requested = false;
    72 GCCause::Cause CMSCollector::_full_gc_cause = GCCause::_no_gc;
    74 //////////////////////////////////////////////////////////////////
    75 // In support of CMS/VM thread synchronization
    76 //////////////////////////////////////////////////////////////////
    77 // We split use of the CGC_lock into 2 "levels".
    78 // The low-level locking is of the usual CGC_lock monitor. We introduce
    79 // a higher level "token" (hereafter "CMS token") built on top of the
    80 // low level monitor (hereafter "CGC lock").
    81 // The token-passing protocol gives priority to the VM thread. The
    82 // CMS-lock doesn't provide any fairness guarantees, but clients
    83 // should ensure that it is only held for very short, bounded
    84 // durations.
    85 //
    86 // When either of the CMS thread or the VM thread is involved in
    87 // collection operations during which it does not want the other
    88 // thread to interfere, it obtains the CMS token.
    89 //
    90 // If either thread tries to get the token while the other has
    91 // it, that thread waits. However, if the VM thread and CMS thread
    92 // both want the token, then the VM thread gets priority while the
    93 // CMS thread waits. This ensures, for instance, that the "concurrent"
    94 // phases of the CMS thread's work do not block out the VM thread
    95 // for long periods of time as the CMS thread continues to hog
    96 // the token. (See bug 4616232).
    97 //
    98 // The baton-passing functions are, however, controlled by the
    99 // flags _foregroundGCShouldWait and _foregroundGCIsActive,
   100 // and here the low-level CMS lock, not the high level token,
   101 // ensures mutual exclusion.
   102 //
   103 // Two important conditions that we have to satisfy:
   104 // 1. if a thread does a low-level wait on the CMS lock, then it
   105 //    relinquishes the CMS token if it were holding that token
   106 //    when it acquired the low-level CMS lock.
   107 // 2. any low-level notifications on the low-level lock
   108 //    should only be sent when a thread has relinquished the token.
   109 //
   110 // In the absence of either property, we'd have potential deadlock.
   111 //
   112 // We protect each of the CMS (concurrent and sequential) phases
   113 // with the CMS _token_, not the CMS _lock_.
   114 //
   115 // The only code protected by CMS lock is the token acquisition code
   116 // itself, see ConcurrentMarkSweepThread::[de]synchronize(), and the
   117 // baton-passing code.
   118 //
   119 // Unfortunately, i couldn't come up with a good abstraction to factor and
   120 // hide the naked CGC_lock manipulation in the baton-passing code
   121 // further below. That's something we should try to do. Also, the proof
   122 // of correctness of this 2-level locking scheme is far from obvious,
   123 // and potentially quite slippery. We have an uneasy supsicion, for instance,
   124 // that there may be a theoretical possibility of delay/starvation in the
   125 // low-level lock/wait/notify scheme used for the baton-passing because of
   126 // potential intereference with the priority scheme embodied in the
   127 // CMS-token-passing protocol. See related comments at a CGC_lock->wait()
   128 // invocation further below and marked with "XXX 20011219YSR".
   129 // Indeed, as we note elsewhere, this may become yet more slippery
   130 // in the presence of multiple CMS and/or multiple VM threads. XXX
   132 class CMSTokenSync: public StackObj {
   133  private:
   134   bool _is_cms_thread;
   135  public:
   136   CMSTokenSync(bool is_cms_thread):
   137     _is_cms_thread(is_cms_thread) {
   138     assert(is_cms_thread == Thread::current()->is_ConcurrentGC_thread(),
   139            "Incorrect argument to constructor");
   140     ConcurrentMarkSweepThread::synchronize(_is_cms_thread);
   141   }
   143   ~CMSTokenSync() {
   144     assert(_is_cms_thread ?
   145              ConcurrentMarkSweepThread::cms_thread_has_cms_token() :
   146              ConcurrentMarkSweepThread::vm_thread_has_cms_token(),
   147           "Incorrect state");
   148     ConcurrentMarkSweepThread::desynchronize(_is_cms_thread);
   149   }
   150 };
   152 // Convenience class that does a CMSTokenSync, and then acquires
   153 // upto three locks.
   154 class CMSTokenSyncWithLocks: public CMSTokenSync {
   155  private:
   156   // Note: locks are acquired in textual declaration order
   157   // and released in the opposite order
   158   MutexLockerEx _locker1, _locker2, _locker3;
   159  public:
   160   CMSTokenSyncWithLocks(bool is_cms_thread, Mutex* mutex1,
   161                         Mutex* mutex2 = NULL, Mutex* mutex3 = NULL):
   162     CMSTokenSync(is_cms_thread),
   163     _locker1(mutex1, Mutex::_no_safepoint_check_flag),
   164     _locker2(mutex2, Mutex::_no_safepoint_check_flag),
   165     _locker3(mutex3, Mutex::_no_safepoint_check_flag)
   166   { }
   167 };
   170 // Wrapper class to temporarily disable icms during a foreground cms collection.
   171 class ICMSDisabler: public StackObj {
   172  public:
   173   // The ctor disables icms and wakes up the thread so it notices the change;
   174   // the dtor re-enables icms.  Note that the CMSCollector methods will check
   175   // CMSIncrementalMode.
   176   ICMSDisabler()  { CMSCollector::disable_icms(); CMSCollector::start_icms(); }
   177   ~ICMSDisabler() { CMSCollector::enable_icms(); }
   178 };
   180 //////////////////////////////////////////////////////////////////
   181 //  Concurrent Mark-Sweep Generation /////////////////////////////
   182 //////////////////////////////////////////////////////////////////
   184 NOT_PRODUCT(CompactibleFreeListSpace* debug_cms_space;)
   186 // This struct contains per-thread things necessary to support parallel
   187 // young-gen collection.
   188 class CMSParGCThreadState: public CHeapObj<mtGC> {
   189  public:
   190   CFLS_LAB lab;
   191   PromotionInfo promo;
   193   // Constructor.
   194   CMSParGCThreadState(CompactibleFreeListSpace* cfls) : lab(cfls) {
   195     promo.setSpace(cfls);
   196   }
   197 };
   199 ConcurrentMarkSweepGeneration::ConcurrentMarkSweepGeneration(
   200      ReservedSpace rs, size_t initial_byte_size, int level,
   201      CardTableRS* ct, bool use_adaptive_freelists,
   202      FreeBlockDictionary<FreeChunk>::DictionaryChoice dictionaryChoice) :
   203   CardGeneration(rs, initial_byte_size, level, ct),
   204   _dilatation_factor(((double)MinChunkSize)/((double)(CollectedHeap::min_fill_size()))),
   205   _debug_collection_type(Concurrent_collection_type),
   206   _did_compact(false)
   207 {
   208   HeapWord* bottom = (HeapWord*) _virtual_space.low();
   209   HeapWord* end    = (HeapWord*) _virtual_space.high();
   211   _direct_allocated_words = 0;
   212   NOT_PRODUCT(
   213     _numObjectsPromoted = 0;
   214     _numWordsPromoted = 0;
   215     _numObjectsAllocated = 0;
   216     _numWordsAllocated = 0;
   217   )
   219   _cmsSpace = new CompactibleFreeListSpace(_bts, MemRegion(bottom, end),
   220                                            use_adaptive_freelists,
   221                                            dictionaryChoice);
   222   NOT_PRODUCT(debug_cms_space = _cmsSpace;)
   223   if (_cmsSpace == NULL) {
   224     vm_exit_during_initialization(
   225       "CompactibleFreeListSpace allocation failure");
   226   }
   227   _cmsSpace->_gen = this;
   229   _gc_stats = new CMSGCStats();
   231   // Verify the assumption that FreeChunk::_prev and OopDesc::_klass
   232   // offsets match. The ability to tell free chunks from objects
   233   // depends on this property.
   234   debug_only(
   235     FreeChunk* junk = NULL;
   236     assert(UseCompressedClassPointers ||
   237            junk->prev_addr() == (void*)(oop(junk)->klass_addr()),
   238            "Offset of FreeChunk::_prev within FreeChunk must match"
   239            "  that of OopDesc::_klass within OopDesc");
   240   )
   241   if (CollectedHeap::use_parallel_gc_threads()) {
   242     typedef CMSParGCThreadState* CMSParGCThreadStatePtr;
   243     _par_gc_thread_states =
   244       NEW_C_HEAP_ARRAY(CMSParGCThreadStatePtr, ParallelGCThreads, mtGC);
   245     if (_par_gc_thread_states == NULL) {
   246       vm_exit_during_initialization("Could not allocate par gc structs");
   247     }
   248     for (uint i = 0; i < ParallelGCThreads; i++) {
   249       _par_gc_thread_states[i] = new CMSParGCThreadState(cmsSpace());
   250       if (_par_gc_thread_states[i] == NULL) {
   251         vm_exit_during_initialization("Could not allocate par gc structs");
   252       }
   253     }
   254   } else {
   255     _par_gc_thread_states = NULL;
   256   }
   257   _incremental_collection_failed = false;
   258   // The "dilatation_factor" is the expansion that can occur on
   259   // account of the fact that the minimum object size in the CMS
   260   // generation may be larger than that in, say, a contiguous young
   261   //  generation.
   262   // Ideally, in the calculation below, we'd compute the dilatation
   263   // factor as: MinChunkSize/(promoting_gen's min object size)
   264   // Since we do not have such a general query interface for the
   265   // promoting generation, we'll instead just use the mimimum
   266   // object size (which today is a header's worth of space);
   267   // note that all arithmetic is in units of HeapWords.
   268   assert(MinChunkSize >= CollectedHeap::min_fill_size(), "just checking");
   269   assert(_dilatation_factor >= 1.0, "from previous assert");
   270 }
   273 // The field "_initiating_occupancy" represents the occupancy percentage
   274 // at which we trigger a new collection cycle.  Unless explicitly specified
   275 // via CMSInitiatingOccupancyFraction (argument "io" below), it
   276 // is calculated by:
   277 //
   278 //   Let "f" be MinHeapFreeRatio in
   279 //
   280 //    _intiating_occupancy = 100-f +
   281 //                           f * (CMSTriggerRatio/100)
   282 //   where CMSTriggerRatio is the argument "tr" below.
   283 //
   284 // That is, if we assume the heap is at its desired maximum occupancy at the
   285 // end of a collection, we let CMSTriggerRatio of the (purported) free
   286 // space be allocated before initiating a new collection cycle.
   287 //
   288 void ConcurrentMarkSweepGeneration::init_initiating_occupancy(intx io, uintx tr) {
   289   assert(io <= 100 && tr <= 100, "Check the arguments");
   290   if (io >= 0) {
   291     _initiating_occupancy = (double)io / 100.0;
   292   } else {
   293     _initiating_occupancy = ((100 - MinHeapFreeRatio) +
   294                              (double)(tr * MinHeapFreeRatio) / 100.0)
   295                             / 100.0;
   296   }
   297 }
   299 void ConcurrentMarkSweepGeneration::ref_processor_init() {
   300   assert(collector() != NULL, "no collector");
   301   collector()->ref_processor_init();
   302 }
   304 void CMSCollector::ref_processor_init() {
   305   if (_ref_processor == NULL) {
   306     // Allocate and initialize a reference processor
   307     _ref_processor =
   308       new ReferenceProcessor(_span,                               // span
   309                              (ParallelGCThreads > 1) && ParallelRefProcEnabled, // mt processing
   310                              (int) ParallelGCThreads,             // mt processing degree
   311                              _cmsGen->refs_discovery_is_mt(),     // mt discovery
   312                              (int) MAX2(ConcGCThreads, ParallelGCThreads), // mt discovery degree
   313                              _cmsGen->refs_discovery_is_atomic(), // discovery is not atomic
   314                              &_is_alive_closure);                 // closure for liveness info
   315     // Initialize the _ref_processor field of CMSGen
   316     _cmsGen->set_ref_processor(_ref_processor);
   318   }
   319 }
   321 CMSAdaptiveSizePolicy* CMSCollector::size_policy() {
   322   GenCollectedHeap* gch = GenCollectedHeap::heap();
   323   assert(gch->kind() == CollectedHeap::GenCollectedHeap,
   324     "Wrong type of heap");
   325   CMSAdaptiveSizePolicy* sp = (CMSAdaptiveSizePolicy*)
   326     gch->gen_policy()->size_policy();
   327   assert(sp->is_gc_cms_adaptive_size_policy(),
   328     "Wrong type of size policy");
   329   return sp;
   330 }
   332 CMSGCAdaptivePolicyCounters* CMSCollector::gc_adaptive_policy_counters() {
   333   CMSGCAdaptivePolicyCounters* results =
   334     (CMSGCAdaptivePolicyCounters*) collector_policy()->counters();
   335   assert(
   336     results->kind() == GCPolicyCounters::CMSGCAdaptivePolicyCountersKind,
   337     "Wrong gc policy counter kind");
   338   return results;
   339 }
   342 void ConcurrentMarkSweepGeneration::initialize_performance_counters() {
   344   const char* gen_name = "old";
   346   // Generation Counters - generation 1, 1 subspace
   347   _gen_counters = new GenerationCounters(gen_name, 1, 1, &_virtual_space);
   349   _space_counters = new GSpaceCounters(gen_name, 0,
   350                                        _virtual_space.reserved_size(),
   351                                        this, _gen_counters);
   352 }
   354 CMSStats::CMSStats(ConcurrentMarkSweepGeneration* cms_gen, unsigned int alpha):
   355   _cms_gen(cms_gen)
   356 {
   357   assert(alpha <= 100, "bad value");
   358   _saved_alpha = alpha;
   360   // Initialize the alphas to the bootstrap value of 100.
   361   _gc0_alpha = _cms_alpha = 100;
   363   _cms_begin_time.update();
   364   _cms_end_time.update();
   366   _gc0_duration = 0.0;
   367   _gc0_period = 0.0;
   368   _gc0_promoted = 0;
   370   _cms_duration = 0.0;
   371   _cms_period = 0.0;
   372   _cms_allocated = 0;
   374   _cms_used_at_gc0_begin = 0;
   375   _cms_used_at_gc0_end = 0;
   376   _allow_duty_cycle_reduction = false;
   377   _valid_bits = 0;
   378   _icms_duty_cycle = CMSIncrementalDutyCycle;
   379 }
   381 double CMSStats::cms_free_adjustment_factor(size_t free) const {
   382   // TBD: CR 6909490
   383   return 1.0;
   384 }
   386 void CMSStats::adjust_cms_free_adjustment_factor(bool fail, size_t free) {
   387 }
   389 // If promotion failure handling is on use
   390 // the padded average size of the promotion for each
   391 // young generation collection.
   392 double CMSStats::time_until_cms_gen_full() const {
   393   size_t cms_free = _cms_gen->cmsSpace()->free();
   394   GenCollectedHeap* gch = GenCollectedHeap::heap();
   395   size_t expected_promotion = MIN2(gch->get_gen(0)->capacity(),
   396                                    (size_t) _cms_gen->gc_stats()->avg_promoted()->padded_average());
   397   if (cms_free > expected_promotion) {
   398     // Start a cms collection if there isn't enough space to promote
   399     // for the next minor collection.  Use the padded average as
   400     // a safety factor.
   401     cms_free -= expected_promotion;
   403     // Adjust by the safety factor.
   404     double cms_free_dbl = (double)cms_free;
   405     double cms_adjustment = (100.0 - CMSIncrementalSafetyFactor)/100.0;
   406     // Apply a further correction factor which tries to adjust
   407     // for recent occurance of concurrent mode failures.
   408     cms_adjustment = cms_adjustment * cms_free_adjustment_factor(cms_free);
   409     cms_free_dbl = cms_free_dbl * cms_adjustment;
   411     if (PrintGCDetails && Verbose) {
   412       gclog_or_tty->print_cr("CMSStats::time_until_cms_gen_full: cms_free "
   413         SIZE_FORMAT " expected_promotion " SIZE_FORMAT,
   414         cms_free, expected_promotion);
   415       gclog_or_tty->print_cr("  cms_free_dbl %f cms_consumption_rate %f",
   416         cms_free_dbl, cms_consumption_rate() + 1.0);
   417     }
   418     // Add 1 in case the consumption rate goes to zero.
   419     return cms_free_dbl / (cms_consumption_rate() + 1.0);
   420   }
   421   return 0.0;
   422 }
   424 // Compare the duration of the cms collection to the
   425 // time remaining before the cms generation is empty.
   426 // Note that the time from the start of the cms collection
   427 // to the start of the cms sweep (less than the total
   428 // duration of the cms collection) can be used.  This
   429 // has been tried and some applications experienced
   430 // promotion failures early in execution.  This was
   431 // possibly because the averages were not accurate
   432 // enough at the beginning.
   433 double CMSStats::time_until_cms_start() const {
   434   // We add "gc0_period" to the "work" calculation
   435   // below because this query is done (mostly) at the
   436   // end of a scavenge, so we need to conservatively
   437   // account for that much possible delay
   438   // in the query so as to avoid concurrent mode failures
   439   // due to starting the collection just a wee bit too
   440   // late.
   441   double work = cms_duration() + gc0_period();
   442   double deadline = time_until_cms_gen_full();
   443   // If a concurrent mode failure occurred recently, we want to be
   444   // more conservative and halve our expected time_until_cms_gen_full()
   445   if (work > deadline) {
   446     if (Verbose && PrintGCDetails) {
   447       gclog_or_tty->print(
   448         " CMSCollector: collect because of anticipated promotion "
   449         "before full %3.7f + %3.7f > %3.7f ", cms_duration(),
   450         gc0_period(), time_until_cms_gen_full());
   451     }
   452     return 0.0;
   453   }
   454   return work - deadline;
   455 }
   457 // Return a duty cycle based on old_duty_cycle and new_duty_cycle, limiting the
   458 // amount of change to prevent wild oscillation.
   459 unsigned int CMSStats::icms_damped_duty_cycle(unsigned int old_duty_cycle,
   460                                               unsigned int new_duty_cycle) {
   461   assert(old_duty_cycle <= 100, "bad input value");
   462   assert(new_duty_cycle <= 100, "bad input value");
   464   // Note:  use subtraction with caution since it may underflow (values are
   465   // unsigned).  Addition is safe since we're in the range 0-100.
   466   unsigned int damped_duty_cycle = new_duty_cycle;
   467   if (new_duty_cycle < old_duty_cycle) {
   468     const unsigned int largest_delta = MAX2(old_duty_cycle / 4, 5U);
   469     if (new_duty_cycle + largest_delta < old_duty_cycle) {
   470       damped_duty_cycle = old_duty_cycle - largest_delta;
   471     }
   472   } else if (new_duty_cycle > old_duty_cycle) {
   473     const unsigned int largest_delta = MAX2(old_duty_cycle / 4, 15U);
   474     if (new_duty_cycle > old_duty_cycle + largest_delta) {
   475       damped_duty_cycle = MIN2(old_duty_cycle + largest_delta, 100U);
   476     }
   477   }
   478   assert(damped_duty_cycle <= 100, "invalid duty cycle computed");
   480   if (CMSTraceIncrementalPacing) {
   481     gclog_or_tty->print(" [icms_damped_duty_cycle(%d,%d) = %d] ",
   482                            old_duty_cycle, new_duty_cycle, damped_duty_cycle);
   483   }
   484   return damped_duty_cycle;
   485 }
   487 unsigned int CMSStats::icms_update_duty_cycle_impl() {
   488   assert(CMSIncrementalPacing && valid(),
   489          "should be handled in icms_update_duty_cycle()");
   491   double cms_time_so_far = cms_timer().seconds();
   492   double scaled_duration = cms_duration_per_mb() * _cms_used_at_gc0_end / M;
   493   double scaled_duration_remaining = fabsd(scaled_duration - cms_time_so_far);
   495   // Avoid division by 0.
   496   double time_until_full = MAX2(time_until_cms_gen_full(), 0.01);
   497   double duty_cycle_dbl = 100.0 * scaled_duration_remaining / time_until_full;
   499   unsigned int new_duty_cycle = MIN2((unsigned int)duty_cycle_dbl, 100U);
   500   if (new_duty_cycle > _icms_duty_cycle) {
   501     // Avoid very small duty cycles (1 or 2); 0 is allowed.
   502     if (new_duty_cycle > 2) {
   503       _icms_duty_cycle = icms_damped_duty_cycle(_icms_duty_cycle,
   504                                                 new_duty_cycle);
   505     }
   506   } else if (_allow_duty_cycle_reduction) {
   507     // The duty cycle is reduced only once per cms cycle (see record_cms_end()).
   508     new_duty_cycle = icms_damped_duty_cycle(_icms_duty_cycle, new_duty_cycle);
   509     // Respect the minimum duty cycle.
   510     unsigned int min_duty_cycle = (unsigned int)CMSIncrementalDutyCycleMin;
   511     _icms_duty_cycle = MAX2(new_duty_cycle, min_duty_cycle);
   512   }
   514   if (PrintGCDetails || CMSTraceIncrementalPacing) {
   515     gclog_or_tty->print(" icms_dc=%d ", _icms_duty_cycle);
   516   }
   518   _allow_duty_cycle_reduction = false;
   519   return _icms_duty_cycle;
   520 }
   522 #ifndef PRODUCT
   523 void CMSStats::print_on(outputStream *st) const {
   524   st->print(" gc0_alpha=%d,cms_alpha=%d", _gc0_alpha, _cms_alpha);
   525   st->print(",gc0_dur=%g,gc0_per=%g,gc0_promo=" SIZE_FORMAT,
   526                gc0_duration(), gc0_period(), gc0_promoted());
   527   st->print(",cms_dur=%g,cms_dur_per_mb=%g,cms_per=%g,cms_alloc=" SIZE_FORMAT,
   528             cms_duration(), cms_duration_per_mb(),
   529             cms_period(), cms_allocated());
   530   st->print(",cms_since_beg=%g,cms_since_end=%g",
   531             cms_time_since_begin(), cms_time_since_end());
   532   st->print(",cms_used_beg=" SIZE_FORMAT ",cms_used_end=" SIZE_FORMAT,
   533             _cms_used_at_gc0_begin, _cms_used_at_gc0_end);
   534   if (CMSIncrementalMode) {
   535     st->print(",dc=%d", icms_duty_cycle());
   536   }
   538   if (valid()) {
   539     st->print(",promo_rate=%g,cms_alloc_rate=%g",
   540               promotion_rate(), cms_allocation_rate());
   541     st->print(",cms_consumption_rate=%g,time_until_full=%g",
   542               cms_consumption_rate(), time_until_cms_gen_full());
   543   }
   544   st->print(" ");
   545 }
   546 #endif // #ifndef PRODUCT
   548 CMSCollector::CollectorState CMSCollector::_collectorState =
   549                              CMSCollector::Idling;
   550 bool CMSCollector::_foregroundGCIsActive = false;
   551 bool CMSCollector::_foregroundGCShouldWait = false;
   553 CMSCollector::CMSCollector(ConcurrentMarkSweepGeneration* cmsGen,
   554                            CardTableRS*                   ct,
   555                            ConcurrentMarkSweepPolicy*     cp):
   556   _cmsGen(cmsGen),
   557   _ct(ct),
   558   _ref_processor(NULL),    // will be set later
   559   _conc_workers(NULL),     // may be set later
   560   _abort_preclean(false),
   561   _start_sampling(false),
   562   _between_prologue_and_epilogue(false),
   563   _markBitMap(0, Mutex::leaf + 1, "CMS_markBitMap_lock"),
   564   _modUnionTable((CardTableModRefBS::card_shift - LogHeapWordSize),
   565                  -1 /* lock-free */, "No_lock" /* dummy */),
   566   _modUnionClosure(&_modUnionTable),
   567   _modUnionClosurePar(&_modUnionTable),
   568   // Adjust my span to cover old (cms) gen
   569   _span(cmsGen->reserved()),
   570   // Construct the is_alive_closure with _span & markBitMap
   571   _is_alive_closure(_span, &_markBitMap),
   572   _restart_addr(NULL),
   573   _overflow_list(NULL),
   574   _stats(cmsGen),
   575   _eden_chunk_lock(new Mutex(Mutex::leaf + 1, "CMS_eden_chunk_lock", true)),
   576   _eden_chunk_array(NULL),     // may be set in ctor body
   577   _eden_chunk_capacity(0),     // -- ditto --
   578   _eden_chunk_index(0),        // -- ditto --
   579   _survivor_plab_array(NULL),  // -- ditto --
   580   _survivor_chunk_array(NULL), // -- ditto --
   581   _survivor_chunk_capacity(0), // -- ditto --
   582   _survivor_chunk_index(0),    // -- ditto --
   583   _ser_pmc_preclean_ovflw(0),
   584   _ser_kac_preclean_ovflw(0),
   585   _ser_pmc_remark_ovflw(0),
   586   _par_pmc_remark_ovflw(0),
   587   _ser_kac_ovflw(0),
   588   _par_kac_ovflw(0),
   589 #ifndef PRODUCT
   590   _num_par_pushes(0),
   591 #endif
   592   _collection_count_start(0),
   593   _verifying(false),
   594   _icms_start_limit(NULL),
   595   _icms_stop_limit(NULL),
   596   _verification_mark_bm(0, Mutex::leaf + 1, "CMS_verification_mark_bm_lock"),
   597   _completed_initialization(false),
   598   _collector_policy(cp),
   599   _should_unload_classes(CMSClassUnloadingEnabled),
   600   _concurrent_cycles_since_last_unload(0),
   601   _roots_scanning_options(SharedHeap::SO_None),
   602   _inter_sweep_estimate(CMS_SweepWeight, CMS_SweepPadding),
   603   _intra_sweep_estimate(CMS_SweepWeight, CMS_SweepPadding),
   604   _gc_tracer_cm(new (ResourceObj::C_HEAP, mtGC) CMSTracer()),
   605   _gc_timer_cm(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
   606   _cms_start_registered(false)
   607 {
   608   if (ExplicitGCInvokesConcurrentAndUnloadsClasses) {
   609     ExplicitGCInvokesConcurrent = true;
   610   }
   611   // Now expand the span and allocate the collection support structures
   612   // (MUT, marking bit map etc.) to cover both generations subject to
   613   // collection.
   615   // For use by dirty card to oop closures.
   616   _cmsGen->cmsSpace()->set_collector(this);
   618   // Allocate MUT and marking bit map
   619   {
   620     MutexLockerEx x(_markBitMap.lock(), Mutex::_no_safepoint_check_flag);
   621     if (!_markBitMap.allocate(_span)) {
   622       warning("Failed to allocate CMS Bit Map");
   623       return;
   624     }
   625     assert(_markBitMap.covers(_span), "_markBitMap inconsistency?");
   626   }
   627   {
   628     _modUnionTable.allocate(_span);
   629     assert(_modUnionTable.covers(_span), "_modUnionTable inconsistency?");
   630   }
   632   if (!_markStack.allocate(MarkStackSize)) {
   633     warning("Failed to allocate CMS Marking Stack");
   634     return;
   635   }
   637   // Support for multi-threaded concurrent phases
   638   if (CMSConcurrentMTEnabled) {
   639     if (FLAG_IS_DEFAULT(ConcGCThreads)) {
   640       // just for now
   641       FLAG_SET_DEFAULT(ConcGCThreads, (ParallelGCThreads + 3)/4);
   642     }
   643     if (ConcGCThreads > 1) {
   644       _conc_workers = new YieldingFlexibleWorkGang("Parallel CMS Threads",
   645                                  ConcGCThreads, true);
   646       if (_conc_workers == NULL) {
   647         warning("GC/CMS: _conc_workers allocation failure: "
   648               "forcing -CMSConcurrentMTEnabled");
   649         CMSConcurrentMTEnabled = false;
   650       } else {
   651         _conc_workers->initialize_workers();
   652       }
   653     } else {
   654       CMSConcurrentMTEnabled = false;
   655     }
   656   }
   657   if (!CMSConcurrentMTEnabled) {
   658     ConcGCThreads = 0;
   659   } else {
   660     // Turn off CMSCleanOnEnter optimization temporarily for
   661     // the MT case where it's not fixed yet; see 6178663.
   662     CMSCleanOnEnter = false;
   663   }
   664   assert((_conc_workers != NULL) == (ConcGCThreads > 1),
   665          "Inconsistency");
   667   // Parallel task queues; these are shared for the
   668   // concurrent and stop-world phases of CMS, but
   669   // are not shared with parallel scavenge (ParNew).
   670   {
   671     uint i;
   672     uint num_queues = (uint) MAX2(ParallelGCThreads, ConcGCThreads);
   674     if ((CMSParallelRemarkEnabled || CMSConcurrentMTEnabled
   675          || ParallelRefProcEnabled)
   676         && num_queues > 0) {
   677       _task_queues = new OopTaskQueueSet(num_queues);
   678       if (_task_queues == NULL) {
   679         warning("task_queues allocation failure.");
   680         return;
   681       }
   682       _hash_seed = NEW_C_HEAP_ARRAY(int, num_queues, mtGC);
   683       if (_hash_seed == NULL) {
   684         warning("_hash_seed array allocation failure");
   685         return;
   686       }
   688       typedef Padded<OopTaskQueue> PaddedOopTaskQueue;
   689       for (i = 0; i < num_queues; i++) {
   690         PaddedOopTaskQueue *q = new PaddedOopTaskQueue();
   691         if (q == NULL) {
   692           warning("work_queue allocation failure.");
   693           return;
   694         }
   695         _task_queues->register_queue(i, q);
   696       }
   697       for (i = 0; i < num_queues; i++) {
   698         _task_queues->queue(i)->initialize();
   699         _hash_seed[i] = 17;  // copied from ParNew
   700       }
   701     }
   702   }
   704   _cmsGen ->init_initiating_occupancy(CMSInitiatingOccupancyFraction, CMSTriggerRatio);
   706   // Clip CMSBootstrapOccupancy between 0 and 100.
   707   _bootstrap_occupancy = ((double)CMSBootstrapOccupancy)/(double)100;
   709   _full_gcs_since_conc_gc = 0;
   711   // Now tell CMS generations the identity of their collector
   712   ConcurrentMarkSweepGeneration::set_collector(this);
   714   // Create & start a CMS thread for this CMS collector
   715   _cmsThread = ConcurrentMarkSweepThread::start(this);
   716   assert(cmsThread() != NULL, "CMS Thread should have been created");
   717   assert(cmsThread()->collector() == this,
   718          "CMS Thread should refer to this gen");
   719   assert(CGC_lock != NULL, "Where's the CGC_lock?");
   721   // Support for parallelizing young gen rescan
   722   GenCollectedHeap* gch = GenCollectedHeap::heap();
   723   _young_gen = gch->prev_gen(_cmsGen);
   724   if (gch->supports_inline_contig_alloc()) {
   725     _top_addr = gch->top_addr();
   726     _end_addr = gch->end_addr();
   727     assert(_young_gen != NULL, "no _young_gen");
   728     _eden_chunk_index = 0;
   729     _eden_chunk_capacity = (_young_gen->max_capacity()+CMSSamplingGrain)/CMSSamplingGrain;
   730     _eden_chunk_array = NEW_C_HEAP_ARRAY(HeapWord*, _eden_chunk_capacity, mtGC);
   731     if (_eden_chunk_array == NULL) {
   732       _eden_chunk_capacity = 0;
   733       warning("GC/CMS: _eden_chunk_array allocation failure");
   734     }
   735   }
   736   assert(_eden_chunk_array != NULL || _eden_chunk_capacity == 0, "Error");
   738   // Support for parallelizing survivor space rescan
   739   if ((CMSParallelRemarkEnabled && CMSParallelSurvivorRemarkEnabled) || CMSParallelInitialMarkEnabled) {
   740     const size_t max_plab_samples =
   741       ((DefNewGeneration*)_young_gen)->max_survivor_size()/MinTLABSize;
   743     _survivor_plab_array  = NEW_C_HEAP_ARRAY(ChunkArray, ParallelGCThreads, mtGC);
   744     _survivor_chunk_array = NEW_C_HEAP_ARRAY(HeapWord*, 2*max_plab_samples, mtGC);
   745     _cursor               = NEW_C_HEAP_ARRAY(size_t, ParallelGCThreads, mtGC);
   746     if (_survivor_plab_array == NULL || _survivor_chunk_array == NULL
   747         || _cursor == NULL) {
   748       warning("Failed to allocate survivor plab/chunk array");
   749       if (_survivor_plab_array  != NULL) {
   750         FREE_C_HEAP_ARRAY(ChunkArray, _survivor_plab_array, mtGC);
   751         _survivor_plab_array = NULL;
   752       }
   753       if (_survivor_chunk_array != NULL) {
   754         FREE_C_HEAP_ARRAY(HeapWord*, _survivor_chunk_array, mtGC);
   755         _survivor_chunk_array = NULL;
   756       }
   757       if (_cursor != NULL) {
   758         FREE_C_HEAP_ARRAY(size_t, _cursor, mtGC);
   759         _cursor = NULL;
   760       }
   761     } else {
   762       _survivor_chunk_capacity = 2*max_plab_samples;
   763       for (uint i = 0; i < ParallelGCThreads; i++) {
   764         HeapWord** vec = NEW_C_HEAP_ARRAY(HeapWord*, max_plab_samples, mtGC);
   765         if (vec == NULL) {
   766           warning("Failed to allocate survivor plab array");
   767           for (int j = i; j > 0; j--) {
   768             FREE_C_HEAP_ARRAY(HeapWord*, _survivor_plab_array[j-1].array(), mtGC);
   769           }
   770           FREE_C_HEAP_ARRAY(ChunkArray, _survivor_plab_array, mtGC);
   771           FREE_C_HEAP_ARRAY(HeapWord*, _survivor_chunk_array, mtGC);
   772           _survivor_plab_array = NULL;
   773           _survivor_chunk_array = NULL;
   774           _survivor_chunk_capacity = 0;
   775           break;
   776         } else {
   777           ChunkArray* cur =
   778             ::new (&_survivor_plab_array[i]) ChunkArray(vec,
   779                                                         max_plab_samples);
   780           assert(cur->end() == 0, "Should be 0");
   781           assert(cur->array() == vec, "Should be vec");
   782           assert(cur->capacity() == max_plab_samples, "Error");
   783         }
   784       }
   785     }
   786   }
   787   assert(   (   _survivor_plab_array  != NULL
   788              && _survivor_chunk_array != NULL)
   789          || (   _survivor_chunk_capacity == 0
   790              && _survivor_chunk_index == 0),
   791          "Error");
   793   NOT_PRODUCT(_overflow_counter = CMSMarkStackOverflowInterval;)
   794   _gc_counters = new CollectorCounters("CMS", 1);
   795   _completed_initialization = true;
   796   _inter_sweep_timer.start();  // start of time
   797 }
   799 const char* ConcurrentMarkSweepGeneration::name() const {
   800   return "concurrent mark-sweep generation";
   801 }
   802 void ConcurrentMarkSweepGeneration::update_counters() {
   803   if (UsePerfData) {
   804     _space_counters->update_all();
   805     _gen_counters->update_all();
   806   }
   807 }
   809 // this is an optimized version of update_counters(). it takes the
   810 // used value as a parameter rather than computing it.
   811 //
   812 void ConcurrentMarkSweepGeneration::update_counters(size_t used) {
   813   if (UsePerfData) {
   814     _space_counters->update_used(used);
   815     _space_counters->update_capacity();
   816     _gen_counters->update_all();
   817   }
   818 }
   820 void ConcurrentMarkSweepGeneration::print() const {
   821   Generation::print();
   822   cmsSpace()->print();
   823 }
   825 #ifndef PRODUCT
   826 void ConcurrentMarkSweepGeneration::print_statistics() {
   827   cmsSpace()->printFLCensus(0);
   828 }
   829 #endif
   831 void ConcurrentMarkSweepGeneration::printOccupancy(const char *s) {
   832   GenCollectedHeap* gch = GenCollectedHeap::heap();
   833   if (PrintGCDetails) {
   834     if (Verbose) {
   835       gclog_or_tty->print("[%d %s-%s: "SIZE_FORMAT"("SIZE_FORMAT")]",
   836         level(), short_name(), s, used(), capacity());
   837     } else {
   838       gclog_or_tty->print("[%d %s-%s: "SIZE_FORMAT"K("SIZE_FORMAT"K)]",
   839         level(), short_name(), s, used() / K, capacity() / K);
   840     }
   841   }
   842   if (Verbose) {
   843     gclog_or_tty->print(" "SIZE_FORMAT"("SIZE_FORMAT")",
   844               gch->used(), gch->capacity());
   845   } else {
   846     gclog_or_tty->print(" "SIZE_FORMAT"K("SIZE_FORMAT"K)",
   847               gch->used() / K, gch->capacity() / K);
   848   }
   849 }
   851 size_t
   852 ConcurrentMarkSweepGeneration::contiguous_available() const {
   853   // dld proposes an improvement in precision here. If the committed
   854   // part of the space ends in a free block we should add that to
   855   // uncommitted size in the calculation below. Will make this
   856   // change later, staying with the approximation below for the
   857   // time being. -- ysr.
   858   return MAX2(_virtual_space.uncommitted_size(), unsafe_max_alloc_nogc());
   859 }
   861 size_t
   862 ConcurrentMarkSweepGeneration::unsafe_max_alloc_nogc() const {
   863   return _cmsSpace->max_alloc_in_words() * HeapWordSize;
   864 }
   866 size_t ConcurrentMarkSweepGeneration::max_available() const {
   867   return free() + _virtual_space.uncommitted_size();
   868 }
   870 bool ConcurrentMarkSweepGeneration::promotion_attempt_is_safe(size_t max_promotion_in_bytes) const {
   871   size_t available = max_available();
   872   size_t av_promo  = (size_t)gc_stats()->avg_promoted()->padded_average();
   873   bool   res = (available >= av_promo) || (available >= max_promotion_in_bytes);
   874   if (Verbose && PrintGCDetails) {
   875     gclog_or_tty->print_cr(
   876       "CMS: promo attempt is%s safe: available("SIZE_FORMAT") %s av_promo("SIZE_FORMAT"),"
   877       "max_promo("SIZE_FORMAT")",
   878       res? "":" not", available, res? ">=":"<",
   879       av_promo, max_promotion_in_bytes);
   880   }
   881   return res;
   882 }
   884 // At a promotion failure dump information on block layout in heap
   885 // (cms old generation).
   886 void ConcurrentMarkSweepGeneration::promotion_failure_occurred() {
   887   if (CMSDumpAtPromotionFailure) {
   888     cmsSpace()->dump_at_safepoint_with_locks(collector(), gclog_or_tty);
   889   }
   890 }
   892 CompactibleSpace*
   893 ConcurrentMarkSweepGeneration::first_compaction_space() const {
   894   return _cmsSpace;
   895 }
   897 void ConcurrentMarkSweepGeneration::reset_after_compaction() {
   898   // Clear the promotion information.  These pointers can be adjusted
   899   // along with all the other pointers into the heap but
   900   // compaction is expected to be a rare event with
   901   // a heap using cms so don't do it without seeing the need.
   902   if (CollectedHeap::use_parallel_gc_threads()) {
   903     for (uint i = 0; i < ParallelGCThreads; i++) {
   904       _par_gc_thread_states[i]->promo.reset();
   905     }
   906   }
   907 }
   909 void ConcurrentMarkSweepGeneration::space_iterate(SpaceClosure* blk, bool usedOnly) {
   910   blk->do_space(_cmsSpace);
   911 }
   913 void ConcurrentMarkSweepGeneration::compute_new_size() {
   914   assert_locked_or_safepoint(Heap_lock);
   916   // If incremental collection failed, we just want to expand
   917   // to the limit.
   918   if (incremental_collection_failed()) {
   919     clear_incremental_collection_failed();
   920     grow_to_reserved();
   921     return;
   922   }
   924   // The heap has been compacted but not reset yet.
   925   // Any metric such as free() or used() will be incorrect.
   927   CardGeneration::compute_new_size();
   929   // Reset again after a possible resizing
   930   if (did_compact()) {
   931     cmsSpace()->reset_after_compaction();
   932   }
   933 }
   935 void ConcurrentMarkSweepGeneration::compute_new_size_free_list() {
   936   assert_locked_or_safepoint(Heap_lock);
   938   // If incremental collection failed, we just want to expand
   939   // to the limit.
   940   if (incremental_collection_failed()) {
   941     clear_incremental_collection_failed();
   942     grow_to_reserved();
   943     return;
   944   }
   946   double free_percentage = ((double) free()) / capacity();
   947   double desired_free_percentage = (double) MinHeapFreeRatio / 100;
   948   double maximum_free_percentage = (double) MaxHeapFreeRatio / 100;
   950   // compute expansion delta needed for reaching desired free percentage
   951   if (free_percentage < desired_free_percentage) {
   952     size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage));
   953     assert(desired_capacity >= capacity(), "invalid expansion size");
   954     size_t expand_bytes = MAX2(desired_capacity - capacity(), MinHeapDeltaBytes);
   955     if (PrintGCDetails && Verbose) {
   956       size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage));
   957       gclog_or_tty->print_cr("\nFrom compute_new_size: ");
   958       gclog_or_tty->print_cr("  Free fraction %f", free_percentage);
   959       gclog_or_tty->print_cr("  Desired free fraction %f",
   960         desired_free_percentage);
   961       gclog_or_tty->print_cr("  Maximum free fraction %f",
   962         maximum_free_percentage);
   963       gclog_or_tty->print_cr("  Capactiy "SIZE_FORMAT, capacity()/1000);
   964       gclog_or_tty->print_cr("  Desired capacity "SIZE_FORMAT,
   965         desired_capacity/1000);
   966       int prev_level = level() - 1;
   967       if (prev_level >= 0) {
   968         size_t prev_size = 0;
   969         GenCollectedHeap* gch = GenCollectedHeap::heap();
   970         Generation* prev_gen = gch->_gens[prev_level];
   971         prev_size = prev_gen->capacity();
   972           gclog_or_tty->print_cr("  Younger gen size "SIZE_FORMAT,
   973                                  prev_size/1000);
   974       }
   975       gclog_or_tty->print_cr("  unsafe_max_alloc_nogc "SIZE_FORMAT,
   976         unsafe_max_alloc_nogc()/1000);
   977       gclog_or_tty->print_cr("  contiguous available "SIZE_FORMAT,
   978         contiguous_available()/1000);
   979       gclog_or_tty->print_cr("  Expand by "SIZE_FORMAT" (bytes)",
   980         expand_bytes);
   981     }
   982     // safe if expansion fails
   983     expand(expand_bytes, 0, CMSExpansionCause::_satisfy_free_ratio);
   984     if (PrintGCDetails && Verbose) {
   985       gclog_or_tty->print_cr("  Expanded free fraction %f",
   986         ((double) free()) / capacity());
   987     }
   988   } else {
   989     size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage));
   990     assert(desired_capacity <= capacity(), "invalid expansion size");
   991     size_t shrink_bytes = capacity() - desired_capacity;
   992     // Don't shrink unless the delta is greater than the minimum shrink we want
   993     if (shrink_bytes >= MinHeapDeltaBytes) {
   994       shrink_free_list_by(shrink_bytes);
   995     }
   996   }
   997 }
   999 Mutex* ConcurrentMarkSweepGeneration::freelistLock() const {
  1000   return cmsSpace()->freelistLock();
  1003 HeapWord* ConcurrentMarkSweepGeneration::allocate(size_t size,
  1004                                                   bool   tlab) {
  1005   CMSSynchronousYieldRequest yr;
  1006   MutexLockerEx x(freelistLock(),
  1007                   Mutex::_no_safepoint_check_flag);
  1008   return have_lock_and_allocate(size, tlab);
  1011 HeapWord* ConcurrentMarkSweepGeneration::have_lock_and_allocate(size_t size,
  1012                                                   bool   tlab /* ignored */) {
  1013   assert_lock_strong(freelistLock());
  1014   size_t adjustedSize = CompactibleFreeListSpace::adjustObjectSize(size);
  1015   HeapWord* res = cmsSpace()->allocate(adjustedSize);
  1016   // Allocate the object live (grey) if the background collector has
  1017   // started marking. This is necessary because the marker may
  1018   // have passed this address and consequently this object will
  1019   // not otherwise be greyed and would be incorrectly swept up.
  1020   // Note that if this object contains references, the writing
  1021   // of those references will dirty the card containing this object
  1022   // allowing the object to be blackened (and its references scanned)
  1023   // either during a preclean phase or at the final checkpoint.
  1024   if (res != NULL) {
  1025     // We may block here with an uninitialized object with
  1026     // its mark-bit or P-bits not yet set. Such objects need
  1027     // to be safely navigable by block_start().
  1028     assert(oop(res)->klass_or_null() == NULL, "Object should be uninitialized here.");
  1029     assert(!((FreeChunk*)res)->is_free(), "Error, block will look free but show wrong size");
  1030     collector()->direct_allocated(res, adjustedSize);
  1031     _direct_allocated_words += adjustedSize;
  1032     // allocation counters
  1033     NOT_PRODUCT(
  1034       _numObjectsAllocated++;
  1035       _numWordsAllocated += (int)adjustedSize;
  1038   return res;
  1041 // In the case of direct allocation by mutators in a generation that
  1042 // is being concurrently collected, the object must be allocated
  1043 // live (grey) if the background collector has started marking.
  1044 // This is necessary because the marker may
  1045 // have passed this address and consequently this object will
  1046 // not otherwise be greyed and would be incorrectly swept up.
  1047 // Note that if this object contains references, the writing
  1048 // of those references will dirty the card containing this object
  1049 // allowing the object to be blackened (and its references scanned)
  1050 // either during a preclean phase or at the final checkpoint.
  1051 void CMSCollector::direct_allocated(HeapWord* start, size_t size) {
  1052   assert(_markBitMap.covers(start, size), "Out of bounds");
  1053   if (_collectorState >= Marking) {
  1054     MutexLockerEx y(_markBitMap.lock(),
  1055                     Mutex::_no_safepoint_check_flag);
  1056     // [see comments preceding SweepClosure::do_blk() below for details]
  1057     //
  1058     // Can the P-bits be deleted now?  JJJ
  1059     //
  1060     // 1. need to mark the object as live so it isn't collected
  1061     // 2. need to mark the 2nd bit to indicate the object may be uninitialized
  1062     // 3. need to mark the end of the object so marking, precleaning or sweeping
  1063     //    can skip over uninitialized or unparsable objects. An allocated
  1064     //    object is considered uninitialized for our purposes as long as
  1065     //    its klass word is NULL.  All old gen objects are parsable
  1066     //    as soon as they are initialized.)
  1067     _markBitMap.mark(start);          // object is live
  1068     _markBitMap.mark(start + 1);      // object is potentially uninitialized?
  1069     _markBitMap.mark(start + size - 1);
  1070                                       // mark end of object
  1072   // check that oop looks uninitialized
  1073   assert(oop(start)->klass_or_null() == NULL, "_klass should be NULL");
  1076 void CMSCollector::promoted(bool par, HeapWord* start,
  1077                             bool is_obj_array, size_t obj_size) {
  1078   assert(_markBitMap.covers(start), "Out of bounds");
  1079   // See comment in direct_allocated() about when objects should
  1080   // be allocated live.
  1081   if (_collectorState >= Marking) {
  1082     // we already hold the marking bit map lock, taken in
  1083     // the prologue
  1084     if (par) {
  1085       _markBitMap.par_mark(start);
  1086     } else {
  1087       _markBitMap.mark(start);
  1089     // We don't need to mark the object as uninitialized (as
  1090     // in direct_allocated above) because this is being done with the
  1091     // world stopped and the object will be initialized by the
  1092     // time the marking, precleaning or sweeping get to look at it.
  1093     // But see the code for copying objects into the CMS generation,
  1094     // where we need to ensure that concurrent readers of the
  1095     // block offset table are able to safely navigate a block that
  1096     // is in flux from being free to being allocated (and in
  1097     // transition while being copied into) and subsequently
  1098     // becoming a bona-fide object when the copy/promotion is complete.
  1099     assert(SafepointSynchronize::is_at_safepoint(),
  1100            "expect promotion only at safepoints");
  1102     if (_collectorState < Sweeping) {
  1103       // Mark the appropriate cards in the modUnionTable, so that
  1104       // this object gets scanned before the sweep. If this is
  1105       // not done, CMS generation references in the object might
  1106       // not get marked.
  1107       // For the case of arrays, which are otherwise precisely
  1108       // marked, we need to dirty the entire array, not just its head.
  1109       if (is_obj_array) {
  1110         // The [par_]mark_range() method expects mr.end() below to
  1111         // be aligned to the granularity of a bit's representation
  1112         // in the heap. In the case of the MUT below, that's a
  1113         // card size.
  1114         MemRegion mr(start,
  1115                      (HeapWord*)round_to((intptr_t)(start + obj_size),
  1116                         CardTableModRefBS::card_size /* bytes */));
  1117         if (par) {
  1118           _modUnionTable.par_mark_range(mr);
  1119         } else {
  1120           _modUnionTable.mark_range(mr);
  1122       } else {  // not an obj array; we can just mark the head
  1123         if (par) {
  1124           _modUnionTable.par_mark(start);
  1125         } else {
  1126           _modUnionTable.mark(start);
  1133 static inline size_t percent_of_space(Space* space, HeapWord* addr)
  1135   size_t delta = pointer_delta(addr, space->bottom());
  1136   return (size_t)(delta * 100.0 / (space->capacity() / HeapWordSize));
  1139 void CMSCollector::icms_update_allocation_limits()
  1141   Generation* gen0 = GenCollectedHeap::heap()->get_gen(0);
  1142   EdenSpace* eden = gen0->as_DefNewGeneration()->eden();
  1144   const unsigned int duty_cycle = stats().icms_update_duty_cycle();
  1145   if (CMSTraceIncrementalPacing) {
  1146     stats().print();
  1149   assert(duty_cycle <= 100, "invalid duty cycle");
  1150   if (duty_cycle != 0) {
  1151     // The duty_cycle is a percentage between 0 and 100; convert to words and
  1152     // then compute the offset from the endpoints of the space.
  1153     size_t free_words = eden->free() / HeapWordSize;
  1154     double free_words_dbl = (double)free_words;
  1155     size_t duty_cycle_words = (size_t)(free_words_dbl * duty_cycle / 100.0);
  1156     size_t offset_words = (free_words - duty_cycle_words) / 2;
  1158     _icms_start_limit = eden->top() + offset_words;
  1159     _icms_stop_limit = eden->end() - offset_words;
  1161     // The limits may be adjusted (shifted to the right) by
  1162     // CMSIncrementalOffset, to allow the application more mutator time after a
  1163     // young gen gc (when all mutators were stopped) and before CMS starts and
  1164     // takes away one or more cpus.
  1165     if (CMSIncrementalOffset != 0) {
  1166       double adjustment_dbl = free_words_dbl * CMSIncrementalOffset / 100.0;
  1167       size_t adjustment = (size_t)adjustment_dbl;
  1168       HeapWord* tmp_stop = _icms_stop_limit + adjustment;
  1169       if (tmp_stop > _icms_stop_limit && tmp_stop < eden->end()) {
  1170         _icms_start_limit += adjustment;
  1171         _icms_stop_limit = tmp_stop;
  1175   if (duty_cycle == 0 || (_icms_start_limit == _icms_stop_limit)) {
  1176     _icms_start_limit = _icms_stop_limit = eden->end();
  1179   // Install the new start limit.
  1180   eden->set_soft_end(_icms_start_limit);
  1182   if (CMSTraceIncrementalMode) {
  1183     gclog_or_tty->print(" icms alloc limits:  "
  1184                            PTR_FORMAT "," PTR_FORMAT
  1185                            " (" SIZE_FORMAT "%%," SIZE_FORMAT "%%) ",
  1186                            p2i(_icms_start_limit), p2i(_icms_stop_limit),
  1187                            percent_of_space(eden, _icms_start_limit),
  1188                            percent_of_space(eden, _icms_stop_limit));
  1189     if (Verbose) {
  1190       gclog_or_tty->print("eden:  ");
  1191       eden->print_on(gclog_or_tty);
  1196 // Any changes here should try to maintain the invariant
  1197 // that if this method is called with _icms_start_limit
  1198 // and _icms_stop_limit both NULL, then it should return NULL
  1199 // and not notify the icms thread.
  1200 HeapWord*
  1201 CMSCollector::allocation_limit_reached(Space* space, HeapWord* top,
  1202                                        size_t word_size)
  1204   // A start_limit equal to end() means the duty cycle is 0, so treat that as a
  1205   // nop.
  1206   if (CMSIncrementalMode && _icms_start_limit != space->end()) {
  1207     if (top <= _icms_start_limit) {
  1208       if (CMSTraceIncrementalMode) {
  1209         space->print_on(gclog_or_tty);
  1210         gclog_or_tty->stamp();
  1211         gclog_or_tty->print_cr(" start limit top=" PTR_FORMAT
  1212                                ", new limit=" PTR_FORMAT
  1213                                " (" SIZE_FORMAT "%%)",
  1214                                p2i(top), p2i(_icms_stop_limit),
  1215                                percent_of_space(space, _icms_stop_limit));
  1217       ConcurrentMarkSweepThread::start_icms();
  1218       assert(top < _icms_stop_limit, "Tautology");
  1219       if (word_size < pointer_delta(_icms_stop_limit, top)) {
  1220         return _icms_stop_limit;
  1223       // The allocation will cross both the _start and _stop limits, so do the
  1224       // stop notification also and return end().
  1225       if (CMSTraceIncrementalMode) {
  1226         space->print_on(gclog_or_tty);
  1227         gclog_or_tty->stamp();
  1228         gclog_or_tty->print_cr(" +stop limit top=" PTR_FORMAT
  1229                                ", new limit=" PTR_FORMAT
  1230                                " (" SIZE_FORMAT "%%)",
  1231                                p2i(top), p2i(space->end()),
  1232                                percent_of_space(space, space->end()));
  1234       ConcurrentMarkSweepThread::stop_icms();
  1235       return space->end();
  1238     if (top <= _icms_stop_limit) {
  1239       if (CMSTraceIncrementalMode) {
  1240         space->print_on(gclog_or_tty);
  1241         gclog_or_tty->stamp();
  1242         gclog_or_tty->print_cr(" stop limit top=" PTR_FORMAT
  1243                                ", new limit=" PTR_FORMAT
  1244                                " (" SIZE_FORMAT "%%)",
  1245                                top, space->end(),
  1246                                percent_of_space(space, space->end()));
  1248       ConcurrentMarkSweepThread::stop_icms();
  1249       return space->end();
  1252     if (CMSTraceIncrementalMode) {
  1253       space->print_on(gclog_or_tty);
  1254       gclog_or_tty->stamp();
  1255       gclog_or_tty->print_cr(" end limit top=" PTR_FORMAT
  1256                              ", new limit=" PTR_FORMAT,
  1257                              top, NULL);
  1261   return NULL;
  1264 oop ConcurrentMarkSweepGeneration::promote(oop obj, size_t obj_size) {
  1265   assert(obj_size == (size_t)obj->size(), "bad obj_size passed in");
  1266   // allocate, copy and if necessary update promoinfo --
  1267   // delegate to underlying space.
  1268   assert_lock_strong(freelistLock());
  1270 #ifndef PRODUCT
  1271   if (Universe::heap()->promotion_should_fail()) {
  1272     return NULL;
  1274 #endif  // #ifndef PRODUCT
  1276   oop res = _cmsSpace->promote(obj, obj_size);
  1277   if (res == NULL) {
  1278     // expand and retry
  1279     size_t s = _cmsSpace->expansionSpaceRequired(obj_size);  // HeapWords
  1280     expand(s*HeapWordSize, MinHeapDeltaBytes,
  1281       CMSExpansionCause::_satisfy_promotion);
  1282     // Since there's currently no next generation, we don't try to promote
  1283     // into a more senior generation.
  1284     assert(next_gen() == NULL, "assumption, based upon which no attempt "
  1285                                "is made to pass on a possibly failing "
  1286                                "promotion to next generation");
  1287     res = _cmsSpace->promote(obj, obj_size);
  1289   if (res != NULL) {
  1290     // See comment in allocate() about when objects should
  1291     // be allocated live.
  1292     assert(obj->is_oop(), "Will dereference klass pointer below");
  1293     collector()->promoted(false,           // Not parallel
  1294                           (HeapWord*)res, obj->is_objArray(), obj_size);
  1295     // promotion counters
  1296     NOT_PRODUCT(
  1297       _numObjectsPromoted++;
  1298       _numWordsPromoted +=
  1299         (int)(CompactibleFreeListSpace::adjustObjectSize(obj->size()));
  1302   return res;
  1306 HeapWord*
  1307 ConcurrentMarkSweepGeneration::allocation_limit_reached(Space* space,
  1308                                              HeapWord* top,
  1309                                              size_t word_sz)
  1311   return collector()->allocation_limit_reached(space, top, word_sz);
  1314 // IMPORTANT: Notes on object size recognition in CMS.
  1315 // ---------------------------------------------------
  1316 // A block of storage in the CMS generation is always in
  1317 // one of three states. A free block (FREE), an allocated
  1318 // object (OBJECT) whose size() method reports the correct size,
  1319 // and an intermediate state (TRANSIENT) in which its size cannot
  1320 // be accurately determined.
  1321 // STATE IDENTIFICATION:   (32 bit and 64 bit w/o COOPS)
  1322 // -----------------------------------------------------
  1323 // FREE:      klass_word & 1 == 1; mark_word holds block size
  1324 //
  1325 // OBJECT:    klass_word installed; klass_word != 0 && klass_word & 1 == 0;
  1326 //            obj->size() computes correct size
  1327 //
  1328 // TRANSIENT: klass_word == 0; size is indeterminate until we become an OBJECT
  1329 //
  1330 // STATE IDENTIFICATION: (64 bit+COOPS)
  1331 // ------------------------------------
  1332 // FREE:      mark_word & CMS_FREE_BIT == 1; mark_word & ~CMS_FREE_BIT gives block_size
  1333 //
  1334 // OBJECT:    klass_word installed; klass_word != 0;
  1335 //            obj->size() computes correct size
  1336 //
  1337 // TRANSIENT: klass_word == 0; size is indeterminate until we become an OBJECT
  1338 //
  1339 //
  1340 // STATE TRANSITION DIAGRAM
  1341 //
  1342 //        mut / parnew                     mut  /  parnew
  1343 // FREE --------------------> TRANSIENT ---------------------> OBJECT --|
  1344 //  ^                                                                   |
  1345 //  |------------------------ DEAD <------------------------------------|
  1346 //         sweep                            mut
  1347 //
  1348 // While a block is in TRANSIENT state its size cannot be determined
  1349 // so readers will either need to come back later or stall until
  1350 // the size can be determined. Note that for the case of direct
  1351 // allocation, P-bits, when available, may be used to determine the
  1352 // size of an object that may not yet have been initialized.
  1354 // Things to support parallel young-gen collection.
  1355 oop
  1356 ConcurrentMarkSweepGeneration::par_promote(int thread_num,
  1357                                            oop old, markOop m,
  1358                                            size_t word_sz) {
  1359 #ifndef PRODUCT
  1360   if (Universe::heap()->promotion_should_fail()) {
  1361     return NULL;
  1363 #endif  // #ifndef PRODUCT
  1365   CMSParGCThreadState* ps = _par_gc_thread_states[thread_num];
  1366   PromotionInfo* promoInfo = &ps->promo;
  1367   // if we are tracking promotions, then first ensure space for
  1368   // promotion (including spooling space for saving header if necessary).
  1369   // then allocate and copy, then track promoted info if needed.
  1370   // When tracking (see PromotionInfo::track()), the mark word may
  1371   // be displaced and in this case restoration of the mark word
  1372   // occurs in the (oop_since_save_marks_)iterate phase.
  1373   if (promoInfo->tracking() && !promoInfo->ensure_spooling_space()) {
  1374     // Out of space for allocating spooling buffers;
  1375     // try expanding and allocating spooling buffers.
  1376     if (!expand_and_ensure_spooling_space(promoInfo)) {
  1377       return NULL;
  1380   assert(promoInfo->has_spooling_space(), "Control point invariant");
  1381   const size_t alloc_sz = CompactibleFreeListSpace::adjustObjectSize(word_sz);
  1382   HeapWord* obj_ptr = ps->lab.alloc(alloc_sz);
  1383   if (obj_ptr == NULL) {
  1384      obj_ptr = expand_and_par_lab_allocate(ps, alloc_sz);
  1385      if (obj_ptr == NULL) {
  1386        return NULL;
  1389   oop obj = oop(obj_ptr);
  1390   OrderAccess::storestore();
  1391   assert(obj->klass_or_null() == NULL, "Object should be uninitialized here.");
  1392   assert(!((FreeChunk*)obj_ptr)->is_free(), "Error, block will look free but show wrong size");
  1393   // IMPORTANT: See note on object initialization for CMS above.
  1394   // Otherwise, copy the object.  Here we must be careful to insert the
  1395   // klass pointer last, since this marks the block as an allocated object.
  1396   // Except with compressed oops it's the mark word.
  1397   HeapWord* old_ptr = (HeapWord*)old;
  1398   // Restore the mark word copied above.
  1399   obj->set_mark(m);
  1400   assert(obj->klass_or_null() == NULL, "Object should be uninitialized here.");
  1401   assert(!((FreeChunk*)obj_ptr)->is_free(), "Error, block will look free but show wrong size");
  1402   OrderAccess::storestore();
  1404   if (UseCompressedClassPointers) {
  1405     // Copy gap missed by (aligned) header size calculation below
  1406     obj->set_klass_gap(old->klass_gap());
  1408   if (word_sz > (size_t)oopDesc::header_size()) {
  1409     Copy::aligned_disjoint_words(old_ptr + oopDesc::header_size(),
  1410                                  obj_ptr + oopDesc::header_size(),
  1411                                  word_sz - oopDesc::header_size());
  1414   // Now we can track the promoted object, if necessary.  We take care
  1415   // to delay the transition from uninitialized to full object
  1416   // (i.e., insertion of klass pointer) until after, so that it
  1417   // atomically becomes a promoted object.
  1418   if (promoInfo->tracking()) {
  1419     promoInfo->track((PromotedObject*)obj, old->klass());
  1421   assert(obj->klass_or_null() == NULL, "Object should be uninitialized here.");
  1422   assert(!((FreeChunk*)obj_ptr)->is_free(), "Error, block will look free but show wrong size");
  1423   assert(old->is_oop(), "Will use and dereference old klass ptr below");
  1425   // Finally, install the klass pointer (this should be volatile).
  1426   OrderAccess::storestore();
  1427   obj->set_klass(old->klass());
  1428   // We should now be able to calculate the right size for this object
  1429   assert(obj->is_oop() && obj->size() == (int)word_sz, "Error, incorrect size computed for promoted object");
  1431   collector()->promoted(true,          // parallel
  1432                         obj_ptr, old->is_objArray(), word_sz);
  1434   NOT_PRODUCT(
  1435     Atomic::inc_ptr(&_numObjectsPromoted);
  1436     Atomic::add_ptr(alloc_sz, &_numWordsPromoted);
  1439   return obj;
  1442 void
  1443 ConcurrentMarkSweepGeneration::
  1444 par_promote_alloc_undo(int thread_num,
  1445                        HeapWord* obj, size_t word_sz) {
  1446   // CMS does not support promotion undo.
  1447   ShouldNotReachHere();
  1450 void
  1451 ConcurrentMarkSweepGeneration::
  1452 par_promote_alloc_done(int thread_num) {
  1453   CMSParGCThreadState* ps = _par_gc_thread_states[thread_num];
  1454   ps->lab.retire(thread_num);
  1457 void
  1458 ConcurrentMarkSweepGeneration::
  1459 par_oop_since_save_marks_iterate_done(int thread_num) {
  1460   CMSParGCThreadState* ps = _par_gc_thread_states[thread_num];
  1461   ParScanWithoutBarrierClosure* dummy_cl = NULL;
  1462   ps->promo.promoted_oops_iterate_nv(dummy_cl);
  1465 bool ConcurrentMarkSweepGeneration::should_collect(bool   full,
  1466                                                    size_t size,
  1467                                                    bool   tlab)
  1469   // We allow a STW collection only if a full
  1470   // collection was requested.
  1471   return full || should_allocate(size, tlab); // FIX ME !!!
  1472   // This and promotion failure handling are connected at the
  1473   // hip and should be fixed by untying them.
  1476 bool CMSCollector::shouldConcurrentCollect() {
  1477   if (_full_gc_requested) {
  1478     if (Verbose && PrintGCDetails) {
  1479       gclog_or_tty->print_cr("CMSCollector: collect because of explicit "
  1480                              " gc request (or gc_locker)");
  1482     return true;
  1485   // For debugging purposes, change the type of collection.
  1486   // If the rotation is not on the concurrent collection
  1487   // type, don't start a concurrent collection.
  1488   NOT_PRODUCT(
  1489     if (RotateCMSCollectionTypes &&
  1490         (_cmsGen->debug_collection_type() !=
  1491           ConcurrentMarkSweepGeneration::Concurrent_collection_type)) {
  1492       assert(_cmsGen->debug_collection_type() !=
  1493         ConcurrentMarkSweepGeneration::Unknown_collection_type,
  1494         "Bad cms collection type");
  1495       return false;
  1499   FreelistLocker x(this);
  1500   // ------------------------------------------------------------------
  1501   // Print out lots of information which affects the initiation of
  1502   // a collection.
  1503   if (PrintCMSInitiationStatistics && stats().valid()) {
  1504     gclog_or_tty->print("CMSCollector shouldConcurrentCollect: ");
  1505     gclog_or_tty->stamp();
  1506     gclog_or_tty->cr();
  1507     stats().print_on(gclog_or_tty);
  1508     gclog_or_tty->print_cr("time_until_cms_gen_full %3.7f",
  1509       stats().time_until_cms_gen_full());
  1510     gclog_or_tty->print_cr("free="SIZE_FORMAT, _cmsGen->free());
  1511     gclog_or_tty->print_cr("contiguous_available="SIZE_FORMAT,
  1512                            _cmsGen->contiguous_available());
  1513     gclog_or_tty->print_cr("promotion_rate=%g", stats().promotion_rate());
  1514     gclog_or_tty->print_cr("cms_allocation_rate=%g", stats().cms_allocation_rate());
  1515     gclog_or_tty->print_cr("occupancy=%3.7f", _cmsGen->occupancy());
  1516     gclog_or_tty->print_cr("initiatingOccupancy=%3.7f", _cmsGen->initiating_occupancy());
  1517     gclog_or_tty->print_cr("metadata initialized %d",
  1518       MetaspaceGC::should_concurrent_collect());
  1520   // ------------------------------------------------------------------
  1522   // If the estimated time to complete a cms collection (cms_duration())
  1523   // is less than the estimated time remaining until the cms generation
  1524   // is full, start a collection.
  1525   if (!UseCMSInitiatingOccupancyOnly) {
  1526     if (stats().valid()) {
  1527       if (stats().time_until_cms_start() == 0.0) {
  1528         return true;
  1530     } else {
  1531       // We want to conservatively collect somewhat early in order
  1532       // to try and "bootstrap" our CMS/promotion statistics;
  1533       // this branch will not fire after the first successful CMS
  1534       // collection because the stats should then be valid.
  1535       if (_cmsGen->occupancy() >= _bootstrap_occupancy) {
  1536         if (Verbose && PrintGCDetails) {
  1537           gclog_or_tty->print_cr(
  1538             " CMSCollector: collect for bootstrapping statistics:"
  1539             " occupancy = %f, boot occupancy = %f", _cmsGen->occupancy(),
  1540             _bootstrap_occupancy);
  1542         return true;
  1547   // Otherwise, we start a collection cycle if
  1548   // old gen want a collection cycle started. Each may use
  1549   // an appropriate criterion for making this decision.
  1550   // XXX We need to make sure that the gen expansion
  1551   // criterion dovetails well with this. XXX NEED TO FIX THIS
  1552   if (_cmsGen->should_concurrent_collect()) {
  1553     if (Verbose && PrintGCDetails) {
  1554       gclog_or_tty->print_cr("CMS old gen initiated");
  1556     return true;
  1559   // We start a collection if we believe an incremental collection may fail;
  1560   // this is not likely to be productive in practice because it's probably too
  1561   // late anyway.
  1562   GenCollectedHeap* gch = GenCollectedHeap::heap();
  1563   assert(gch->collector_policy()->is_two_generation_policy(),
  1564          "You may want to check the correctness of the following");
  1565   if (gch->incremental_collection_will_fail(true /* consult_young */)) {
  1566     if (Verbose && PrintGCDetails) {
  1567       gclog_or_tty->print("CMSCollector: collect because incremental collection will fail ");
  1569     return true;
  1572   if (MetaspaceGC::should_concurrent_collect()) {
  1573       if (Verbose && PrintGCDetails) {
  1574       gclog_or_tty->print("CMSCollector: collect for metadata allocation ");
  1576       return true;
  1579   return false;
  1582 void CMSCollector::set_did_compact(bool v) { _cmsGen->set_did_compact(v); }
  1584 // Clear _expansion_cause fields of constituent generations
  1585 void CMSCollector::clear_expansion_cause() {
  1586   _cmsGen->clear_expansion_cause();
  1589 // We should be conservative in starting a collection cycle.  To
  1590 // start too eagerly runs the risk of collecting too often in the
  1591 // extreme.  To collect too rarely falls back on full collections,
  1592 // which works, even if not optimum in terms of concurrent work.
  1593 // As a work around for too eagerly collecting, use the flag
  1594 // UseCMSInitiatingOccupancyOnly.  This also has the advantage of
  1595 // giving the user an easily understandable way of controlling the
  1596 // collections.
  1597 // We want to start a new collection cycle if any of the following
  1598 // conditions hold:
  1599 // . our current occupancy exceeds the configured initiating occupancy
  1600 //   for this generation, or
  1601 // . we recently needed to expand this space and have not, since that
  1602 //   expansion, done a collection of this generation, or
  1603 // . the underlying space believes that it may be a good idea to initiate
  1604 //   a concurrent collection (this may be based on criteria such as the
  1605 //   following: the space uses linear allocation and linear allocation is
  1606 //   going to fail, or there is believed to be excessive fragmentation in
  1607 //   the generation, etc... or ...
  1608 // [.(currently done by CMSCollector::shouldConcurrentCollect() only for
  1609 //   the case of the old generation; see CR 6543076):
  1610 //   we may be approaching a point at which allocation requests may fail because
  1611 //   we will be out of sufficient free space given allocation rate estimates.]
  1612 bool ConcurrentMarkSweepGeneration::should_concurrent_collect() const {
  1614   assert_lock_strong(freelistLock());
  1615   if (occupancy() > initiating_occupancy()) {
  1616     if (PrintGCDetails && Verbose) {
  1617       gclog_or_tty->print(" %s: collect because of occupancy %f / %f  ",
  1618         short_name(), occupancy(), initiating_occupancy());
  1620     return true;
  1622   if (UseCMSInitiatingOccupancyOnly) {
  1623     return false;
  1625   if (expansion_cause() == CMSExpansionCause::_satisfy_allocation) {
  1626     if (PrintGCDetails && Verbose) {
  1627       gclog_or_tty->print(" %s: collect because expanded for allocation ",
  1628         short_name());
  1630     return true;
  1632   if (_cmsSpace->should_concurrent_collect()) {
  1633     if (PrintGCDetails && Verbose) {
  1634       gclog_or_tty->print(" %s: collect because cmsSpace says so ",
  1635         short_name());
  1637     return true;
  1639   return false;
  1642 void ConcurrentMarkSweepGeneration::collect(bool   full,
  1643                                             bool   clear_all_soft_refs,
  1644                                             size_t size,
  1645                                             bool   tlab)
  1647   collector()->collect(full, clear_all_soft_refs, size, tlab);
  1650 void CMSCollector::collect(bool   full,
  1651                            bool   clear_all_soft_refs,
  1652                            size_t size,
  1653                            bool   tlab)
  1655   if (!UseCMSCollectionPassing && _collectorState > Idling) {
  1656     // For debugging purposes skip the collection if the state
  1657     // is not currently idle
  1658     if (TraceCMSState) {
  1659       gclog_or_tty->print_cr("Thread " INTPTR_FORMAT " skipped full:%d CMS state %d",
  1660         Thread::current(), full, _collectorState);
  1662     return;
  1665   // The following "if" branch is present for defensive reasons.
  1666   // In the current uses of this interface, it can be replaced with:
  1667   // assert(!GC_locker.is_active(), "Can't be called otherwise");
  1668   // But I am not placing that assert here to allow future
  1669   // generality in invoking this interface.
  1670   if (GC_locker::is_active()) {
  1671     // A consistency test for GC_locker
  1672     assert(GC_locker::needs_gc(), "Should have been set already");
  1673     // Skip this foreground collection, instead
  1674     // expanding the heap if necessary.
  1675     // Need the free list locks for the call to free() in compute_new_size()
  1676     compute_new_size();
  1677     return;
  1679   acquire_control_and_collect(full, clear_all_soft_refs);
  1680   _full_gcs_since_conc_gc++;
  1683 void CMSCollector::request_full_gc(unsigned int full_gc_count, GCCause::Cause cause) {
  1684   GenCollectedHeap* gch = GenCollectedHeap::heap();
  1685   unsigned int gc_count = gch->total_full_collections();
  1686   if (gc_count == full_gc_count) {
  1687     MutexLockerEx y(CGC_lock, Mutex::_no_safepoint_check_flag);
  1688     _full_gc_requested = true;
  1689     _full_gc_cause = cause;
  1690     CGC_lock->notify();   // nudge CMS thread
  1691   } else {
  1692     assert(gc_count > full_gc_count, "Error: causal loop");
  1696 bool CMSCollector::is_external_interruption() {
  1697   GCCause::Cause cause = GenCollectedHeap::heap()->gc_cause();
  1698   return GCCause::is_user_requested_gc(cause) ||
  1699          GCCause::is_serviceability_requested_gc(cause);
  1702 void CMSCollector::report_concurrent_mode_interruption() {
  1703   if (is_external_interruption()) {
  1704     if (PrintGCDetails) {
  1705       gclog_or_tty->print(" (concurrent mode interrupted)");
  1707   } else {
  1708     if (PrintGCDetails) {
  1709       gclog_or_tty->print(" (concurrent mode failure)");
  1711     _gc_tracer_cm->report_concurrent_mode_failure();
  1716 // The foreground and background collectors need to coordinate in order
  1717 // to make sure that they do not mutually interfere with CMS collections.
  1718 // When a background collection is active,
  1719 // the foreground collector may need to take over (preempt) and
  1720 // synchronously complete an ongoing collection. Depending on the
  1721 // frequency of the background collections and the heap usage
  1722 // of the application, this preemption can be seldom or frequent.
  1723 // There are only certain
  1724 // points in the background collection that the "collection-baton"
  1725 // can be passed to the foreground collector.
  1726 //
  1727 // The foreground collector will wait for the baton before
  1728 // starting any part of the collection.  The foreground collector
  1729 // will only wait at one location.
  1730 //
  1731 // The background collector will yield the baton before starting a new
  1732 // phase of the collection (e.g., before initial marking, marking from roots,
  1733 // precleaning, final re-mark, sweep etc.)  This is normally done at the head
  1734 // of the loop which switches the phases. The background collector does some
  1735 // of the phases (initial mark, final re-mark) with the world stopped.
  1736 // Because of locking involved in stopping the world,
  1737 // the foreground collector should not block waiting for the background
  1738 // collector when it is doing a stop-the-world phase.  The background
  1739 // collector will yield the baton at an additional point just before
  1740 // it enters a stop-the-world phase.  Once the world is stopped, the
  1741 // background collector checks the phase of the collection.  If the
  1742 // phase has not changed, it proceeds with the collection.  If the
  1743 // phase has changed, it skips that phase of the collection.  See
  1744 // the comments on the use of the Heap_lock in collect_in_background().
  1745 //
  1746 // Variable used in baton passing.
  1747 //   _foregroundGCIsActive - Set to true by the foreground collector when
  1748 //      it wants the baton.  The foreground clears it when it has finished
  1749 //      the collection.
  1750 //   _foregroundGCShouldWait - Set to true by the background collector
  1751 //        when it is running.  The foreground collector waits while
  1752 //      _foregroundGCShouldWait is true.
  1753 //  CGC_lock - monitor used to protect access to the above variables
  1754 //      and to notify the foreground and background collectors.
  1755 //  _collectorState - current state of the CMS collection.
  1756 //
  1757 // The foreground collector
  1758 //   acquires the CGC_lock
  1759 //   sets _foregroundGCIsActive
  1760 //   waits on the CGC_lock for _foregroundGCShouldWait to be false
  1761 //     various locks acquired in preparation for the collection
  1762 //     are released so as not to block the background collector
  1763 //     that is in the midst of a collection
  1764 //   proceeds with the collection
  1765 //   clears _foregroundGCIsActive
  1766 //   returns
  1767 //
  1768 // The background collector in a loop iterating on the phases of the
  1769 //      collection
  1770 //   acquires the CGC_lock
  1771 //   sets _foregroundGCShouldWait
  1772 //   if _foregroundGCIsActive is set
  1773 //     clears _foregroundGCShouldWait, notifies _CGC_lock
  1774 //     waits on _CGC_lock for _foregroundGCIsActive to become false
  1775 //     and exits the loop.
  1776 //   otherwise
  1777 //     proceed with that phase of the collection
  1778 //     if the phase is a stop-the-world phase,
  1779 //       yield the baton once more just before enqueueing
  1780 //       the stop-world CMS operation (executed by the VM thread).
  1781 //   returns after all phases of the collection are done
  1782 //
  1784 void CMSCollector::acquire_control_and_collect(bool full,
  1785         bool clear_all_soft_refs) {
  1786   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
  1787   assert(!Thread::current()->is_ConcurrentGC_thread(),
  1788          "shouldn't try to acquire control from self!");
  1790   // Start the protocol for acquiring control of the
  1791   // collection from the background collector (aka CMS thread).
  1792   assert(ConcurrentMarkSweepThread::vm_thread_has_cms_token(),
  1793          "VM thread should have CMS token");
  1794   // Remember the possibly interrupted state of an ongoing
  1795   // concurrent collection
  1796   CollectorState first_state = _collectorState;
  1798   // Signal to a possibly ongoing concurrent collection that
  1799   // we want to do a foreground collection.
  1800   _foregroundGCIsActive = true;
  1802   // Disable incremental mode during a foreground collection.
  1803   ICMSDisabler icms_disabler;
  1805   // release locks and wait for a notify from the background collector
  1806   // releasing the locks in only necessary for phases which
  1807   // do yields to improve the granularity of the collection.
  1808   assert_lock_strong(bitMapLock());
  1809   // We need to lock the Free list lock for the space that we are
  1810   // currently collecting.
  1811   assert(haveFreelistLocks(), "Must be holding free list locks");
  1812   bitMapLock()->unlock();
  1813   releaseFreelistLocks();
  1815     MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
  1816     if (_foregroundGCShouldWait) {
  1817       // We are going to be waiting for action for the CMS thread;
  1818       // it had better not be gone (for instance at shutdown)!
  1819       assert(ConcurrentMarkSweepThread::cmst() != NULL,
  1820              "CMS thread must be running");
  1821       // Wait here until the background collector gives us the go-ahead
  1822       ConcurrentMarkSweepThread::clear_CMS_flag(
  1823         ConcurrentMarkSweepThread::CMS_vm_has_token);  // release token
  1824       // Get a possibly blocked CMS thread going:
  1825       //   Note that we set _foregroundGCIsActive true above,
  1826       //   without protection of the CGC_lock.
  1827       CGC_lock->notify();
  1828       assert(!ConcurrentMarkSweepThread::vm_thread_wants_cms_token(),
  1829              "Possible deadlock");
  1830       while (_foregroundGCShouldWait) {
  1831         // wait for notification
  1832         CGC_lock->wait(Mutex::_no_safepoint_check_flag);
  1833         // Possibility of delay/starvation here, since CMS token does
  1834         // not know to give priority to VM thread? Actually, i think
  1835         // there wouldn't be any delay/starvation, but the proof of
  1836         // that "fact" (?) appears non-trivial. XXX 20011219YSR
  1838       ConcurrentMarkSweepThread::set_CMS_flag(
  1839         ConcurrentMarkSweepThread::CMS_vm_has_token);
  1842   // The CMS_token is already held.  Get back the other locks.
  1843   assert(ConcurrentMarkSweepThread::vm_thread_has_cms_token(),
  1844          "VM thread should have CMS token");
  1845   getFreelistLocks();
  1846   bitMapLock()->lock_without_safepoint_check();
  1847   if (TraceCMSState) {
  1848     gclog_or_tty->print_cr("CMS foreground collector has asked for control "
  1849       INTPTR_FORMAT " with first state %d", Thread::current(), first_state);
  1850     gclog_or_tty->print_cr("    gets control with state %d", _collectorState);
  1853   // Check if we need to do a compaction, or if not, whether
  1854   // we need to start the mark-sweep from scratch.
  1855   bool should_compact    = false;
  1856   bool should_start_over = false;
  1857   decide_foreground_collection_type(clear_all_soft_refs,
  1858     &should_compact, &should_start_over);
  1860 NOT_PRODUCT(
  1861   if (RotateCMSCollectionTypes) {
  1862     if (_cmsGen->debug_collection_type() ==
  1863         ConcurrentMarkSweepGeneration::MSC_foreground_collection_type) {
  1864       should_compact = true;
  1865     } else if (_cmsGen->debug_collection_type() ==
  1866                ConcurrentMarkSweepGeneration::MS_foreground_collection_type) {
  1867       should_compact = false;
  1872   if (first_state > Idling) {
  1873     report_concurrent_mode_interruption();
  1876   set_did_compact(should_compact);
  1877   if (should_compact) {
  1878     // If the collection is being acquired from the background
  1879     // collector, there may be references on the discovered
  1880     // references lists that have NULL referents (being those
  1881     // that were concurrently cleared by a mutator) or
  1882     // that are no longer active (having been enqueued concurrently
  1883     // by the mutator).
  1884     // Scrub the list of those references because Mark-Sweep-Compact
  1885     // code assumes referents are not NULL and that all discovered
  1886     // Reference objects are active.
  1887     ref_processor()->clean_up_discovered_references();
  1889     if (first_state > Idling) {
  1890       save_heap_summary();
  1893     do_compaction_work(clear_all_soft_refs);
  1895     // Has the GC time limit been exceeded?
  1896     DefNewGeneration* young_gen = _young_gen->as_DefNewGeneration();
  1897     size_t max_eden_size = young_gen->max_capacity() -
  1898                            young_gen->to()->capacity() -
  1899                            young_gen->from()->capacity();
  1900     GenCollectedHeap* gch = GenCollectedHeap::heap();
  1901     GCCause::Cause gc_cause = gch->gc_cause();
  1902     size_policy()->check_gc_overhead_limit(_young_gen->used(),
  1903                                            young_gen->eden()->used(),
  1904                                            _cmsGen->max_capacity(),
  1905                                            max_eden_size,
  1906                                            full,
  1907                                            gc_cause,
  1908                                            gch->collector_policy());
  1909   } else {
  1910     do_mark_sweep_work(clear_all_soft_refs, first_state,
  1911       should_start_over);
  1913   // Reset the expansion cause, now that we just completed
  1914   // a collection cycle.
  1915   clear_expansion_cause();
  1916   _foregroundGCIsActive = false;
  1917   return;
  1920 // Resize the tenured generation
  1921 // after obtaining the free list locks for the
  1922 // two generations.
  1923 void CMSCollector::compute_new_size() {
  1924   assert_locked_or_safepoint(Heap_lock);
  1925   FreelistLocker z(this);
  1926   MetaspaceGC::compute_new_size();
  1927   _cmsGen->compute_new_size_free_list();
  1930 // A work method used by foreground collection to determine
  1931 // what type of collection (compacting or not, continuing or fresh)
  1932 // it should do.
  1933 // NOTE: the intent is to make UseCMSCompactAtFullCollection
  1934 // and CMSCompactWhenClearAllSoftRefs the default in the future
  1935 // and do away with the flags after a suitable period.
  1936 void CMSCollector::decide_foreground_collection_type(
  1937   bool clear_all_soft_refs, bool* should_compact,
  1938   bool* should_start_over) {
  1939   // Normally, we'll compact only if the UseCMSCompactAtFullCollection
  1940   // flag is set, and we have either requested a System.gc() or
  1941   // the number of full gc's since the last concurrent cycle
  1942   // has exceeded the threshold set by CMSFullGCsBeforeCompaction,
  1943   // or if an incremental collection has failed
  1944   GenCollectedHeap* gch = GenCollectedHeap::heap();
  1945   assert(gch->collector_policy()->is_two_generation_policy(),
  1946          "You may want to check the correctness of the following");
  1947   // Inform cms gen if this was due to partial collection failing.
  1948   // The CMS gen may use this fact to determine its expansion policy.
  1949   if (gch->incremental_collection_will_fail(false /* don't consult_young */)) {
  1950     assert(!_cmsGen->incremental_collection_failed(),
  1951            "Should have been noticed, reacted to and cleared");
  1952     _cmsGen->set_incremental_collection_failed();
  1954   *should_compact =
  1955     UseCMSCompactAtFullCollection &&
  1956     ((_full_gcs_since_conc_gc >= CMSFullGCsBeforeCompaction) ||
  1957      GCCause::is_user_requested_gc(gch->gc_cause()) ||
  1958      gch->incremental_collection_will_fail(true /* consult_young */));
  1959   *should_start_over = false;
  1960   if (clear_all_soft_refs && !*should_compact) {
  1961     // We are about to do a last ditch collection attempt
  1962     // so it would normally make sense to do a compaction
  1963     // to reclaim as much space as possible.
  1964     if (CMSCompactWhenClearAllSoftRefs) {
  1965       // Default: The rationale is that in this case either
  1966       // we are past the final marking phase, in which case
  1967       // we'd have to start over, or so little has been done
  1968       // that there's little point in saving that work. Compaction
  1969       // appears to be the sensible choice in either case.
  1970       *should_compact = true;
  1971     } else {
  1972       // We have been asked to clear all soft refs, but not to
  1973       // compact. Make sure that we aren't past the final checkpoint
  1974       // phase, for that is where we process soft refs. If we are already
  1975       // past that phase, we'll need to redo the refs discovery phase and
  1976       // if necessary clear soft refs that weren't previously
  1977       // cleared. We do so by remembering the phase in which
  1978       // we came in, and if we are past the refs processing
  1979       // phase, we'll choose to just redo the mark-sweep
  1980       // collection from scratch.
  1981       if (_collectorState > FinalMarking) {
  1982         // We are past the refs processing phase;
  1983         // start over and do a fresh synchronous CMS cycle
  1984         _collectorState = Resetting; // skip to reset to start new cycle
  1985         reset(false /* == !asynch */);
  1986         *should_start_over = true;
  1987       } // else we can continue a possibly ongoing current cycle
  1992 // A work method used by the foreground collector to do
  1993 // a mark-sweep-compact.
  1994 void CMSCollector::do_compaction_work(bool clear_all_soft_refs) {
  1995   GenCollectedHeap* gch = GenCollectedHeap::heap();
  1997   STWGCTimer* gc_timer = GenMarkSweep::gc_timer();
  1998   gc_timer->register_gc_start();
  2000   SerialOldTracer* gc_tracer = GenMarkSweep::gc_tracer();
  2001   gc_tracer->report_gc_start(gch->gc_cause(), gc_timer->gc_start());
  2003   GCTraceTime t("CMS:MSC ", PrintGCDetails && Verbose, true, NULL, gc_tracer->gc_id());
  2004   if (PrintGC && Verbose && !(GCCause::is_user_requested_gc(gch->gc_cause()))) {
  2005     gclog_or_tty->print_cr("Compact ConcurrentMarkSweepGeneration after %d "
  2006       "collections passed to foreground collector", _full_gcs_since_conc_gc);
  2009   // Sample collection interval time and reset for collection pause.
  2010   if (UseAdaptiveSizePolicy) {
  2011     size_policy()->msc_collection_begin();
  2014   // Temporarily widen the span of the weak reference processing to
  2015   // the entire heap.
  2016   MemRegion new_span(GenCollectedHeap::heap()->reserved_region());
  2017   ReferenceProcessorSpanMutator rp_mut_span(ref_processor(), new_span);
  2018   // Temporarily, clear the "is_alive_non_header" field of the
  2019   // reference processor.
  2020   ReferenceProcessorIsAliveMutator rp_mut_closure(ref_processor(), NULL);
  2021   // Temporarily make reference _processing_ single threaded (non-MT).
  2022   ReferenceProcessorMTProcMutator rp_mut_mt_processing(ref_processor(), false);
  2023   // Temporarily make refs discovery atomic
  2024   ReferenceProcessorAtomicMutator rp_mut_atomic(ref_processor(), true);
  2025   // Temporarily make reference _discovery_ single threaded (non-MT)
  2026   ReferenceProcessorMTDiscoveryMutator rp_mut_discovery(ref_processor(), false);
  2028   ref_processor()->set_enqueuing_is_done(false);
  2029   ref_processor()->enable_discovery(false /*verify_disabled*/, false /*check_no_refs*/);
  2030   ref_processor()->setup_policy(clear_all_soft_refs);
  2031   // If an asynchronous collection finishes, the _modUnionTable is
  2032   // all clear.  If we are assuming the collection from an asynchronous
  2033   // collection, clear the _modUnionTable.
  2034   assert(_collectorState != Idling || _modUnionTable.isAllClear(),
  2035     "_modUnionTable should be clear if the baton was not passed");
  2036   _modUnionTable.clear_all();
  2037   assert(_collectorState != Idling || _ct->klass_rem_set()->mod_union_is_clear(),
  2038     "mod union for klasses should be clear if the baton was passed");
  2039   _ct->klass_rem_set()->clear_mod_union();
  2041   // We must adjust the allocation statistics being maintained
  2042   // in the free list space. We do so by reading and clearing
  2043   // the sweep timer and updating the block flux rate estimates below.
  2044   assert(!_intra_sweep_timer.is_active(), "_intra_sweep_timer should be inactive");
  2045   if (_inter_sweep_timer.is_active()) {
  2046     _inter_sweep_timer.stop();
  2047     // Note that we do not use this sample to update the _inter_sweep_estimate.
  2048     _cmsGen->cmsSpace()->beginSweepFLCensus((float)(_inter_sweep_timer.seconds()),
  2049                                             _inter_sweep_estimate.padded_average(),
  2050                                             _intra_sweep_estimate.padded_average());
  2053   GenMarkSweep::invoke_at_safepoint(_cmsGen->level(),
  2054     ref_processor(), clear_all_soft_refs);
  2055   #ifdef ASSERT
  2056     CompactibleFreeListSpace* cms_space = _cmsGen->cmsSpace();
  2057     size_t free_size = cms_space->free();
  2058     assert(free_size ==
  2059            pointer_delta(cms_space->end(), cms_space->compaction_top())
  2060            * HeapWordSize,
  2061       "All the free space should be compacted into one chunk at top");
  2062     assert(cms_space->dictionary()->total_chunk_size(
  2063                                       debug_only(cms_space->freelistLock())) == 0 ||
  2064            cms_space->totalSizeInIndexedFreeLists() == 0,
  2065       "All the free space should be in a single chunk");
  2066     size_t num = cms_space->totalCount();
  2067     assert((free_size == 0 && num == 0) ||
  2068            (free_size > 0  && (num == 1 || num == 2)),
  2069          "There should be at most 2 free chunks after compaction");
  2070   #endif // ASSERT
  2071   _collectorState = Resetting;
  2072   assert(_restart_addr == NULL,
  2073          "Should have been NULL'd before baton was passed");
  2074   reset(false /* == !asynch */);
  2075   _cmsGen->reset_after_compaction();
  2076   _concurrent_cycles_since_last_unload = 0;
  2078   // Clear any data recorded in the PLAB chunk arrays.
  2079   if (_survivor_plab_array != NULL) {
  2080     reset_survivor_plab_arrays();
  2083   // Adjust the per-size allocation stats for the next epoch.
  2084   _cmsGen->cmsSpace()->endSweepFLCensus(sweep_count() /* fake */);
  2085   // Restart the "inter sweep timer" for the next epoch.
  2086   _inter_sweep_timer.reset();
  2087   _inter_sweep_timer.start();
  2089   // Sample collection pause time and reset for collection interval.
  2090   if (UseAdaptiveSizePolicy) {
  2091     size_policy()->msc_collection_end(gch->gc_cause());
  2094   gc_timer->register_gc_end();
  2096   gc_tracer->report_gc_end(gc_timer->gc_end(), gc_timer->time_partitions());
  2098   // For a mark-sweep-compact, compute_new_size() will be called
  2099   // in the heap's do_collection() method.
  2102 // A work method used by the foreground collector to do
  2103 // a mark-sweep, after taking over from a possibly on-going
  2104 // concurrent mark-sweep collection.
  2105 void CMSCollector::do_mark_sweep_work(bool clear_all_soft_refs,
  2106   CollectorState first_state, bool should_start_over) {
  2107   if (PrintGC && Verbose) {
  2108     gclog_or_tty->print_cr("Pass concurrent collection to foreground "
  2109       "collector with count %d",
  2110       _full_gcs_since_conc_gc);
  2112   switch (_collectorState) {
  2113     case Idling:
  2114       if (first_state == Idling || should_start_over) {
  2115         // The background GC was not active, or should
  2116         // restarted from scratch;  start the cycle.
  2117         _collectorState = InitialMarking;
  2119       // If first_state was not Idling, then a background GC
  2120       // was in progress and has now finished.  No need to do it
  2121       // again.  Leave the state as Idling.
  2122       break;
  2123     case Precleaning:
  2124       // In the foreground case don't do the precleaning since
  2125       // it is not done concurrently and there is extra work
  2126       // required.
  2127       _collectorState = FinalMarking;
  2129   collect_in_foreground(clear_all_soft_refs, GenCollectedHeap::heap()->gc_cause());
  2131   // For a mark-sweep, compute_new_size() will be called
  2132   // in the heap's do_collection() method.
  2136 void CMSCollector::print_eden_and_survivor_chunk_arrays() {
  2137   DefNewGeneration* dng = _young_gen->as_DefNewGeneration();
  2138   EdenSpace* eden_space = dng->eden();
  2139   ContiguousSpace* from_space = dng->from();
  2140   ContiguousSpace* to_space   = dng->to();
  2141   // Eden
  2142   if (_eden_chunk_array != NULL) {
  2143     gclog_or_tty->print_cr("eden " PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "(" SIZE_FORMAT ")",
  2144                            eden_space->bottom(), eden_space->top(),
  2145                            eden_space->end(), eden_space->capacity());
  2146     gclog_or_tty->print_cr("_eden_chunk_index=" SIZE_FORMAT ", "
  2147                            "_eden_chunk_capacity=" SIZE_FORMAT,
  2148                            _eden_chunk_index, _eden_chunk_capacity);
  2149     for (size_t i = 0; i < _eden_chunk_index; i++) {
  2150       gclog_or_tty->print_cr("_eden_chunk_array[" SIZE_FORMAT "]=" PTR_FORMAT,
  2151                              i, _eden_chunk_array[i]);
  2154   // Survivor
  2155   if (_survivor_chunk_array != NULL) {
  2156     gclog_or_tty->print_cr("survivor " PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "(" SIZE_FORMAT ")",
  2157                            from_space->bottom(), from_space->top(),
  2158                            from_space->end(), from_space->capacity());
  2159     gclog_or_tty->print_cr("_survivor_chunk_index=" SIZE_FORMAT ", "
  2160                            "_survivor_chunk_capacity=" SIZE_FORMAT,
  2161                            _survivor_chunk_index, _survivor_chunk_capacity);
  2162     for (size_t i = 0; i < _survivor_chunk_index; i++) {
  2163       gclog_or_tty->print_cr("_survivor_chunk_array[" SIZE_FORMAT "]=" PTR_FORMAT,
  2164                              i, _survivor_chunk_array[i]);
  2169 void CMSCollector::getFreelistLocks() const {
  2170   // Get locks for all free lists in all generations that this
  2171   // collector is responsible for
  2172   _cmsGen->freelistLock()->lock_without_safepoint_check();
  2175 void CMSCollector::releaseFreelistLocks() const {
  2176   // Release locks for all free lists in all generations that this
  2177   // collector is responsible for
  2178   _cmsGen->freelistLock()->unlock();
  2181 bool CMSCollector::haveFreelistLocks() const {
  2182   // Check locks for all free lists in all generations that this
  2183   // collector is responsible for
  2184   assert_lock_strong(_cmsGen->freelistLock());
  2185   PRODUCT_ONLY(ShouldNotReachHere());
  2186   return true;
  2189 // A utility class that is used by the CMS collector to
  2190 // temporarily "release" the foreground collector from its
  2191 // usual obligation to wait for the background collector to
  2192 // complete an ongoing phase before proceeding.
  2193 class ReleaseForegroundGC: public StackObj {
  2194  private:
  2195   CMSCollector* _c;
  2196  public:
  2197   ReleaseForegroundGC(CMSCollector* c) : _c(c) {
  2198     assert(_c->_foregroundGCShouldWait, "Else should not need to call");
  2199     MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
  2200     // allow a potentially blocked foreground collector to proceed
  2201     _c->_foregroundGCShouldWait = false;
  2202     if (_c->_foregroundGCIsActive) {
  2203       CGC_lock->notify();
  2205     assert(!ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  2206            "Possible deadlock");
  2209   ~ReleaseForegroundGC() {
  2210     assert(!_c->_foregroundGCShouldWait, "Usage protocol violation?");
  2211     MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
  2212     _c->_foregroundGCShouldWait = true;
  2214 };
  2216 // There are separate collect_in_background and collect_in_foreground because of
  2217 // the different locking requirements of the background collector and the
  2218 // foreground collector.  There was originally an attempt to share
  2219 // one "collect" method between the background collector and the foreground
  2220 // collector but the if-then-else required made it cleaner to have
  2221 // separate methods.
  2222 void CMSCollector::collect_in_background(bool clear_all_soft_refs, GCCause::Cause cause) {
  2223   assert(Thread::current()->is_ConcurrentGC_thread(),
  2224     "A CMS asynchronous collection is only allowed on a CMS thread.");
  2226   GenCollectedHeap* gch = GenCollectedHeap::heap();
  2228     bool safepoint_check = Mutex::_no_safepoint_check_flag;
  2229     MutexLockerEx hl(Heap_lock, safepoint_check);
  2230     FreelistLocker fll(this);
  2231     MutexLockerEx x(CGC_lock, safepoint_check);
  2232     if (_foregroundGCIsActive || !UseAsyncConcMarkSweepGC) {
  2233       // The foreground collector is active or we're
  2234       // not using asynchronous collections.  Skip this
  2235       // background collection.
  2236       assert(!_foregroundGCShouldWait, "Should be clear");
  2237       return;
  2238     } else {
  2239       assert(_collectorState == Idling, "Should be idling before start.");
  2240       _collectorState = InitialMarking;
  2241       register_gc_start(cause);
  2242       // Reset the expansion cause, now that we are about to begin
  2243       // a new cycle.
  2244       clear_expansion_cause();
  2246       // Clear the MetaspaceGC flag since a concurrent collection
  2247       // is starting but also clear it after the collection.
  2248       MetaspaceGC::set_should_concurrent_collect(false);
  2250     // Decide if we want to enable class unloading as part of the
  2251     // ensuing concurrent GC cycle.
  2252     update_should_unload_classes();
  2253     _full_gc_requested = false;           // acks all outstanding full gc requests
  2254     _full_gc_cause = GCCause::_no_gc;
  2255     // Signal that we are about to start a collection
  2256     gch->increment_total_full_collections();  // ... starting a collection cycle
  2257     _collection_count_start = gch->total_full_collections();
  2260   // Used for PrintGC
  2261   size_t prev_used;
  2262   if (PrintGC && Verbose) {
  2263     prev_used = _cmsGen->used(); // XXXPERM
  2266   // The change of the collection state is normally done at this level;
  2267   // the exceptions are phases that are executed while the world is
  2268   // stopped.  For those phases the change of state is done while the
  2269   // world is stopped.  For baton passing purposes this allows the
  2270   // background collector to finish the phase and change state atomically.
  2271   // The foreground collector cannot wait on a phase that is done
  2272   // while the world is stopped because the foreground collector already
  2273   // has the world stopped and would deadlock.
  2274   while (_collectorState != Idling) {
  2275     if (TraceCMSState) {
  2276       gclog_or_tty->print_cr("Thread " INTPTR_FORMAT " in CMS state %d",
  2277         Thread::current(), _collectorState);
  2279     // The foreground collector
  2280     //   holds the Heap_lock throughout its collection.
  2281     //   holds the CMS token (but not the lock)
  2282     //     except while it is waiting for the background collector to yield.
  2283     //
  2284     // The foreground collector should be blocked (not for long)
  2285     //   if the background collector is about to start a phase
  2286     //   executed with world stopped.  If the background
  2287     //   collector has already started such a phase, the
  2288     //   foreground collector is blocked waiting for the
  2289     //   Heap_lock.  The stop-world phases (InitialMarking and FinalMarking)
  2290     //   are executed in the VM thread.
  2291     //
  2292     // The locking order is
  2293     //   PendingListLock (PLL)  -- if applicable (FinalMarking)
  2294     //   Heap_lock  (both this & PLL locked in VM_CMS_Operation::prologue())
  2295     //   CMS token  (claimed in
  2296     //                stop_world_and_do() -->
  2297     //                  safepoint_synchronize() -->
  2298     //                    CMSThread::synchronize())
  2301       // Check if the FG collector wants us to yield.
  2302       CMSTokenSync x(true); // is cms thread
  2303       if (waitForForegroundGC()) {
  2304         // We yielded to a foreground GC, nothing more to be
  2305         // done this round.
  2306         assert(_foregroundGCShouldWait == false, "We set it to false in "
  2307                "waitForForegroundGC()");
  2308         if (TraceCMSState) {
  2309           gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT
  2310             " exiting collection CMS state %d",
  2311             Thread::current(), _collectorState);
  2313         return;
  2314       } else {
  2315         // The background collector can run but check to see if the
  2316         // foreground collector has done a collection while the
  2317         // background collector was waiting to get the CGC_lock
  2318         // above.  If yes, break so that _foregroundGCShouldWait
  2319         // is cleared before returning.
  2320         if (_collectorState == Idling) {
  2321           break;
  2326     assert(_foregroundGCShouldWait, "Foreground collector, if active, "
  2327       "should be waiting");
  2329     switch (_collectorState) {
  2330       case InitialMarking:
  2332           ReleaseForegroundGC x(this);
  2333           stats().record_cms_begin();
  2334           VM_CMS_Initial_Mark initial_mark_op(this);
  2335           VMThread::execute(&initial_mark_op);
  2337         // The collector state may be any legal state at this point
  2338         // since the background collector may have yielded to the
  2339         // foreground collector.
  2340         break;
  2341       case Marking:
  2342         // initial marking in checkpointRootsInitialWork has been completed
  2343         if (markFromRoots(true)) { // we were successful
  2344           assert(_collectorState == Precleaning, "Collector state should "
  2345             "have changed");
  2346         } else {
  2347           assert(_foregroundGCIsActive, "Internal state inconsistency");
  2349         break;
  2350       case Precleaning:
  2351         if (UseAdaptiveSizePolicy) {
  2352           size_policy()->concurrent_precleaning_begin();
  2354         // marking from roots in markFromRoots has been completed
  2355         preclean();
  2356         if (UseAdaptiveSizePolicy) {
  2357           size_policy()->concurrent_precleaning_end();
  2359         assert(_collectorState == AbortablePreclean ||
  2360                _collectorState == FinalMarking,
  2361                "Collector state should have changed");
  2362         break;
  2363       case AbortablePreclean:
  2364         if (UseAdaptiveSizePolicy) {
  2365         size_policy()->concurrent_phases_resume();
  2367         abortable_preclean();
  2368         if (UseAdaptiveSizePolicy) {
  2369           size_policy()->concurrent_precleaning_end();
  2371         assert(_collectorState == FinalMarking, "Collector state should "
  2372           "have changed");
  2373         break;
  2374       case FinalMarking:
  2376           ReleaseForegroundGC x(this);
  2378           VM_CMS_Final_Remark final_remark_op(this);
  2379           VMThread::execute(&final_remark_op);
  2381         assert(_foregroundGCShouldWait, "block post-condition");
  2382         break;
  2383       case Sweeping:
  2384         if (UseAdaptiveSizePolicy) {
  2385           size_policy()->concurrent_sweeping_begin();
  2387         // final marking in checkpointRootsFinal has been completed
  2388         sweep(true);
  2389         assert(_collectorState == Resizing, "Collector state change "
  2390           "to Resizing must be done under the free_list_lock");
  2391         _full_gcs_since_conc_gc = 0;
  2393         // Stop the timers for adaptive size policy for the concurrent phases
  2394         if (UseAdaptiveSizePolicy) {
  2395           size_policy()->concurrent_sweeping_end();
  2396           size_policy()->concurrent_phases_end(gch->gc_cause(),
  2397                                              gch->prev_gen(_cmsGen)->capacity(),
  2398                                              _cmsGen->free());
  2401       case Resizing: {
  2402         // Sweeping has been completed...
  2403         // At this point the background collection has completed.
  2404         // Don't move the call to compute_new_size() down
  2405         // into code that might be executed if the background
  2406         // collection was preempted.
  2408           ReleaseForegroundGC x(this);   // unblock FG collection
  2409           MutexLockerEx       y(Heap_lock, Mutex::_no_safepoint_check_flag);
  2410           CMSTokenSync        z(true);   // not strictly needed.
  2411           if (_collectorState == Resizing) {
  2412             compute_new_size();
  2413             save_heap_summary();
  2414             _collectorState = Resetting;
  2415           } else {
  2416             assert(_collectorState == Idling, "The state should only change"
  2417                    " because the foreground collector has finished the collection");
  2420         break;
  2422       case Resetting:
  2423         // CMS heap resizing has been completed
  2424         reset(true);
  2425         assert(_collectorState == Idling, "Collector state should "
  2426           "have changed");
  2428         MetaspaceGC::set_should_concurrent_collect(false);
  2430         stats().record_cms_end();
  2431         // Don't move the concurrent_phases_end() and compute_new_size()
  2432         // calls to here because a preempted background collection
  2433         // has it's state set to "Resetting".
  2434         break;
  2435       case Idling:
  2436       default:
  2437         ShouldNotReachHere();
  2438         break;
  2440     if (TraceCMSState) {
  2441       gclog_or_tty->print_cr("  Thread " INTPTR_FORMAT " done - next CMS state %d",
  2442         Thread::current(), _collectorState);
  2444     assert(_foregroundGCShouldWait, "block post-condition");
  2447   // Should this be in gc_epilogue?
  2448   collector_policy()->counters()->update_counters();
  2451     // Clear _foregroundGCShouldWait and, in the event that the
  2452     // foreground collector is waiting, notify it, before
  2453     // returning.
  2454     MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
  2455     _foregroundGCShouldWait = false;
  2456     if (_foregroundGCIsActive) {
  2457       CGC_lock->notify();
  2459     assert(!ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  2460            "Possible deadlock");
  2462   if (TraceCMSState) {
  2463     gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT
  2464       " exiting collection CMS state %d",
  2465       Thread::current(), _collectorState);
  2467   if (PrintGC && Verbose) {
  2468     _cmsGen->print_heap_change(prev_used);
  2472 void CMSCollector::register_foreground_gc_start(GCCause::Cause cause) {
  2473   if (!_cms_start_registered) {
  2474     register_gc_start(cause);
  2478 void CMSCollector::register_gc_start(GCCause::Cause cause) {
  2479   _cms_start_registered = true;
  2480   _gc_timer_cm->register_gc_start();
  2481   _gc_tracer_cm->report_gc_start(cause, _gc_timer_cm->gc_start());
  2484 void CMSCollector::register_gc_end() {
  2485   if (_cms_start_registered) {
  2486     report_heap_summary(GCWhen::AfterGC);
  2488     _gc_timer_cm->register_gc_end();
  2489     _gc_tracer_cm->report_gc_end(_gc_timer_cm->gc_end(), _gc_timer_cm->time_partitions());
  2490     _cms_start_registered = false;
  2494 void CMSCollector::save_heap_summary() {
  2495   GenCollectedHeap* gch = GenCollectedHeap::heap();
  2496   _last_heap_summary = gch->create_heap_summary();
  2497   _last_metaspace_summary = gch->create_metaspace_summary();
  2500 void CMSCollector::report_heap_summary(GCWhen::Type when) {
  2501   _gc_tracer_cm->report_gc_heap_summary(when, _last_heap_summary);
  2502   _gc_tracer_cm->report_metaspace_summary(when, _last_metaspace_summary);
  2505 void CMSCollector::collect_in_foreground(bool clear_all_soft_refs, GCCause::Cause cause) {
  2506   assert(_foregroundGCIsActive && !_foregroundGCShouldWait,
  2507          "Foreground collector should be waiting, not executing");
  2508   assert(Thread::current()->is_VM_thread(), "A foreground collection"
  2509     "may only be done by the VM Thread with the world stopped");
  2510   assert(ConcurrentMarkSweepThread::vm_thread_has_cms_token(),
  2511          "VM thread should have CMS token");
  2513   // The gc id is created in register_foreground_gc_start if this collection is synchronous
  2514   const GCId gc_id = _collectorState == InitialMarking ? GCId::peek() : _gc_tracer_cm->gc_id();
  2515   NOT_PRODUCT(GCTraceTime t("CMS:MS (foreground) ", PrintGCDetails && Verbose,
  2516     true, NULL, gc_id);)
  2517   if (UseAdaptiveSizePolicy) {
  2518     size_policy()->ms_collection_begin();
  2520   COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact);
  2522   HandleMark hm;  // Discard invalid handles created during verification
  2524   if (VerifyBeforeGC &&
  2525       GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2526     Universe::verify();
  2529   // Snapshot the soft reference policy to be used in this collection cycle.
  2530   ref_processor()->setup_policy(clear_all_soft_refs);
  2532   // Decide if class unloading should be done
  2533   update_should_unload_classes();
  2535   bool init_mark_was_synchronous = false; // until proven otherwise
  2536   while (_collectorState != Idling) {
  2537     if (TraceCMSState) {
  2538       gclog_or_tty->print_cr("Thread " INTPTR_FORMAT " in CMS state %d",
  2539         Thread::current(), _collectorState);
  2541     switch (_collectorState) {
  2542       case InitialMarking:
  2543         register_foreground_gc_start(cause);
  2544         init_mark_was_synchronous = true;  // fact to be exploited in re-mark
  2545         checkpointRootsInitial(false);
  2546         assert(_collectorState == Marking, "Collector state should have changed"
  2547           " within checkpointRootsInitial()");
  2548         break;
  2549       case Marking:
  2550         // initial marking in checkpointRootsInitialWork has been completed
  2551         if (VerifyDuringGC &&
  2552             GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2553           Universe::verify("Verify before initial mark: ");
  2556           bool res = markFromRoots(false);
  2557           assert(res && _collectorState == FinalMarking, "Collector state should "
  2558             "have changed");
  2559           break;
  2561       case FinalMarking:
  2562         if (VerifyDuringGC &&
  2563             GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2564           Universe::verify("Verify before re-mark: ");
  2566         checkpointRootsFinal(false, clear_all_soft_refs,
  2567                              init_mark_was_synchronous);
  2568         assert(_collectorState == Sweeping, "Collector state should not "
  2569           "have changed within checkpointRootsFinal()");
  2570         break;
  2571       case Sweeping:
  2572         // final marking in checkpointRootsFinal has been completed
  2573         if (VerifyDuringGC &&
  2574             GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2575           Universe::verify("Verify before sweep: ");
  2577         sweep(false);
  2578         assert(_collectorState == Resizing, "Incorrect state");
  2579         break;
  2580       case Resizing: {
  2581         // Sweeping has been completed; the actual resize in this case
  2582         // is done separately; nothing to be done in this state.
  2583         _collectorState = Resetting;
  2584         break;
  2586       case Resetting:
  2587         // The heap has been resized.
  2588         if (VerifyDuringGC &&
  2589             GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2590           Universe::verify("Verify before reset: ");
  2592         save_heap_summary();
  2593         reset(false);
  2594         assert(_collectorState == Idling, "Collector state should "
  2595           "have changed");
  2596         break;
  2597       case Precleaning:
  2598       case AbortablePreclean:
  2599         // Elide the preclean phase
  2600         _collectorState = FinalMarking;
  2601         break;
  2602       default:
  2603         ShouldNotReachHere();
  2605     if (TraceCMSState) {
  2606       gclog_or_tty->print_cr("  Thread " INTPTR_FORMAT " done - next CMS state %d",
  2607         Thread::current(), _collectorState);
  2611   if (UseAdaptiveSizePolicy) {
  2612     GenCollectedHeap* gch = GenCollectedHeap::heap();
  2613     size_policy()->ms_collection_end(gch->gc_cause());
  2616   if (VerifyAfterGC &&
  2617       GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2618     Universe::verify();
  2620   if (TraceCMSState) {
  2621     gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT
  2622       " exiting collection CMS state %d",
  2623       Thread::current(), _collectorState);
  2627 bool CMSCollector::waitForForegroundGC() {
  2628   bool res = false;
  2629   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  2630          "CMS thread should have CMS token");
  2631   // Block the foreground collector until the
  2632   // background collectors decides whether to
  2633   // yield.
  2634   MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
  2635   _foregroundGCShouldWait = true;
  2636   if (_foregroundGCIsActive) {
  2637     // The background collector yields to the
  2638     // foreground collector and returns a value
  2639     // indicating that it has yielded.  The foreground
  2640     // collector can proceed.
  2641     res = true;
  2642     _foregroundGCShouldWait = false;
  2643     ConcurrentMarkSweepThread::clear_CMS_flag(
  2644       ConcurrentMarkSweepThread::CMS_cms_has_token);
  2645     ConcurrentMarkSweepThread::set_CMS_flag(
  2646       ConcurrentMarkSweepThread::CMS_cms_wants_token);
  2647     // Get a possibly blocked foreground thread going
  2648     CGC_lock->notify();
  2649     if (TraceCMSState) {
  2650       gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT " waiting at CMS state %d",
  2651         Thread::current(), _collectorState);
  2653     while (_foregroundGCIsActive) {
  2654       CGC_lock->wait(Mutex::_no_safepoint_check_flag);
  2656     ConcurrentMarkSweepThread::set_CMS_flag(
  2657       ConcurrentMarkSweepThread::CMS_cms_has_token);
  2658     ConcurrentMarkSweepThread::clear_CMS_flag(
  2659       ConcurrentMarkSweepThread::CMS_cms_wants_token);
  2661   if (TraceCMSState) {
  2662     gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT " continuing at CMS state %d",
  2663       Thread::current(), _collectorState);
  2665   return res;
  2668 // Because of the need to lock the free lists and other structures in
  2669 // the collector, common to all the generations that the collector is
  2670 // collecting, we need the gc_prologues of individual CMS generations
  2671 // delegate to their collector. It may have been simpler had the
  2672 // current infrastructure allowed one to call a prologue on a
  2673 // collector. In the absence of that we have the generation's
  2674 // prologue delegate to the collector, which delegates back
  2675 // some "local" work to a worker method in the individual generations
  2676 // that it's responsible for collecting, while itself doing any
  2677 // work common to all generations it's responsible for. A similar
  2678 // comment applies to the  gc_epilogue()'s.
  2679 // The role of the varaible _between_prologue_and_epilogue is to
  2680 // enforce the invocation protocol.
  2681 void CMSCollector::gc_prologue(bool full) {
  2682   // Call gc_prologue_work() for the CMSGen
  2683   // we are responsible for.
  2685   // The following locking discipline assumes that we are only called
  2686   // when the world is stopped.
  2687   assert(SafepointSynchronize::is_at_safepoint(), "world is stopped assumption");
  2689   // The CMSCollector prologue must call the gc_prologues for the
  2690   // "generations" that it's responsible
  2691   // for.
  2693   assert(   Thread::current()->is_VM_thread()
  2694          || (   CMSScavengeBeforeRemark
  2695              && Thread::current()->is_ConcurrentGC_thread()),
  2696          "Incorrect thread type for prologue execution");
  2698   if (_between_prologue_and_epilogue) {
  2699     // We have already been invoked; this is a gc_prologue delegation
  2700     // from yet another CMS generation that we are responsible for, just
  2701     // ignore it since all relevant work has already been done.
  2702     return;
  2705   // set a bit saying prologue has been called; cleared in epilogue
  2706   _between_prologue_and_epilogue = true;
  2707   // Claim locks for common data structures, then call gc_prologue_work()
  2708   // for each CMSGen.
  2710   getFreelistLocks();   // gets free list locks on constituent spaces
  2711   bitMapLock()->lock_without_safepoint_check();
  2713   // Should call gc_prologue_work() for all cms gens we are responsible for
  2714   bool duringMarking =    _collectorState >= Marking
  2715                          && _collectorState < Sweeping;
  2717   // The young collections clear the modified oops state, which tells if
  2718   // there are any modified oops in the class. The remark phase also needs
  2719   // that information. Tell the young collection to save the union of all
  2720   // modified klasses.
  2721   if (duringMarking) {
  2722     _ct->klass_rem_set()->set_accumulate_modified_oops(true);
  2725   bool registerClosure = duringMarking;
  2727   ModUnionClosure* muc = CollectedHeap::use_parallel_gc_threads() ?
  2728                                                &_modUnionClosurePar
  2729                                                : &_modUnionClosure;
  2730   _cmsGen->gc_prologue_work(full, registerClosure, muc);
  2732   if (!full) {
  2733     stats().record_gc0_begin();
  2737 void ConcurrentMarkSweepGeneration::gc_prologue(bool full) {
  2739   _capacity_at_prologue = capacity();
  2740   _used_at_prologue = used();
  2742   // Delegate to CMScollector which knows how to coordinate between
  2743   // this and any other CMS generations that it is responsible for
  2744   // collecting.
  2745   collector()->gc_prologue(full);
  2748 // This is a "private" interface for use by this generation's CMSCollector.
  2749 // Not to be called directly by any other entity (for instance,
  2750 // GenCollectedHeap, which calls the "public" gc_prologue method above).
  2751 void ConcurrentMarkSweepGeneration::gc_prologue_work(bool full,
  2752   bool registerClosure, ModUnionClosure* modUnionClosure) {
  2753   assert(!incremental_collection_failed(), "Shouldn't be set yet");
  2754   assert(cmsSpace()->preconsumptionDirtyCardClosure() == NULL,
  2755     "Should be NULL");
  2756   if (registerClosure) {
  2757     cmsSpace()->setPreconsumptionDirtyCardClosure(modUnionClosure);
  2759   cmsSpace()->gc_prologue();
  2760   // Clear stat counters
  2761   NOT_PRODUCT(
  2762     assert(_numObjectsPromoted == 0, "check");
  2763     assert(_numWordsPromoted   == 0, "check");
  2764     if (Verbose && PrintGC) {
  2765       gclog_or_tty->print("Allocated "SIZE_FORMAT" objects, "
  2766                           SIZE_FORMAT" bytes concurrently",
  2767       _numObjectsAllocated, _numWordsAllocated*sizeof(HeapWord));
  2769     _numObjectsAllocated = 0;
  2770     _numWordsAllocated   = 0;
  2774 void CMSCollector::gc_epilogue(bool full) {
  2775   // The following locking discipline assumes that we are only called
  2776   // when the world is stopped.
  2777   assert(SafepointSynchronize::is_at_safepoint(),
  2778          "world is stopped assumption");
  2780   // Currently the CMS epilogue (see CompactibleFreeListSpace) merely checks
  2781   // if linear allocation blocks need to be appropriately marked to allow the
  2782   // the blocks to be parsable. We also check here whether we need to nudge the
  2783   // CMS collector thread to start a new cycle (if it's not already active).
  2784   assert(   Thread::current()->is_VM_thread()
  2785          || (   CMSScavengeBeforeRemark
  2786              && Thread::current()->is_ConcurrentGC_thread()),
  2787          "Incorrect thread type for epilogue execution");
  2789   if (!_between_prologue_and_epilogue) {
  2790     // We have already been invoked; this is a gc_epilogue delegation
  2791     // from yet another CMS generation that we are responsible for, just
  2792     // ignore it since all relevant work has already been done.
  2793     return;
  2795   assert(haveFreelistLocks(), "must have freelist locks");
  2796   assert_lock_strong(bitMapLock());
  2798   _ct->klass_rem_set()->set_accumulate_modified_oops(false);
  2800   _cmsGen->gc_epilogue_work(full);
  2802   if (_collectorState == AbortablePreclean || _collectorState == Precleaning) {
  2803     // in case sampling was not already enabled, enable it
  2804     _start_sampling = true;
  2806   // reset _eden_chunk_array so sampling starts afresh
  2807   _eden_chunk_index = 0;
  2809   size_t cms_used   = _cmsGen->cmsSpace()->used();
  2811   // update performance counters - this uses a special version of
  2812   // update_counters() that allows the utilization to be passed as a
  2813   // parameter, avoiding multiple calls to used().
  2814   //
  2815   _cmsGen->update_counters(cms_used);
  2817   if (CMSIncrementalMode) {
  2818     icms_update_allocation_limits();
  2821   bitMapLock()->unlock();
  2822   releaseFreelistLocks();
  2824   if (!CleanChunkPoolAsync) {
  2825     Chunk::clean_chunk_pool();
  2828   set_did_compact(false);
  2829   _between_prologue_and_epilogue = false;  // ready for next cycle
  2832 void ConcurrentMarkSweepGeneration::gc_epilogue(bool full) {
  2833   collector()->gc_epilogue(full);
  2835   // Also reset promotion tracking in par gc thread states.
  2836   if (CollectedHeap::use_parallel_gc_threads()) {
  2837     for (uint i = 0; i < ParallelGCThreads; i++) {
  2838       _par_gc_thread_states[i]->promo.stopTrackingPromotions(i);
  2843 void ConcurrentMarkSweepGeneration::gc_epilogue_work(bool full) {
  2844   assert(!incremental_collection_failed(), "Should have been cleared");
  2845   cmsSpace()->setPreconsumptionDirtyCardClosure(NULL);
  2846   cmsSpace()->gc_epilogue();
  2847     // Print stat counters
  2848   NOT_PRODUCT(
  2849     assert(_numObjectsAllocated == 0, "check");
  2850     assert(_numWordsAllocated == 0, "check");
  2851     if (Verbose && PrintGC) {
  2852       gclog_or_tty->print("Promoted "SIZE_FORMAT" objects, "
  2853                           SIZE_FORMAT" bytes",
  2854                  _numObjectsPromoted, _numWordsPromoted*sizeof(HeapWord));
  2856     _numObjectsPromoted = 0;
  2857     _numWordsPromoted   = 0;
  2860   if (PrintGC && Verbose) {
  2861     // Call down the chain in contiguous_available needs the freelistLock
  2862     // so print this out before releasing the freeListLock.
  2863     gclog_or_tty->print(" Contiguous available "SIZE_FORMAT" bytes ",
  2864                         contiguous_available());
  2868 #ifndef PRODUCT
  2869 bool CMSCollector::have_cms_token() {
  2870   Thread* thr = Thread::current();
  2871   if (thr->is_VM_thread()) {
  2872     return ConcurrentMarkSweepThread::vm_thread_has_cms_token();
  2873   } else if (thr->is_ConcurrentGC_thread()) {
  2874     return ConcurrentMarkSweepThread::cms_thread_has_cms_token();
  2875   } else if (thr->is_GC_task_thread()) {
  2876     return ConcurrentMarkSweepThread::vm_thread_has_cms_token() &&
  2877            ParGCRareEvent_lock->owned_by_self();
  2879   return false;
  2881 #endif
  2883 // Check reachability of the given heap address in CMS generation,
  2884 // treating all other generations as roots.
  2885 bool CMSCollector::is_cms_reachable(HeapWord* addr) {
  2886   // We could "guarantee" below, rather than assert, but i'll
  2887   // leave these as "asserts" so that an adventurous debugger
  2888   // could try this in the product build provided some subset of
  2889   // the conditions were met, provided they were intersted in the
  2890   // results and knew that the computation below wouldn't interfere
  2891   // with other concurrent computations mutating the structures
  2892   // being read or written.
  2893   assert(SafepointSynchronize::is_at_safepoint(),
  2894          "Else mutations in object graph will make answer suspect");
  2895   assert(have_cms_token(), "Should hold cms token");
  2896   assert(haveFreelistLocks(), "must hold free list locks");
  2897   assert_lock_strong(bitMapLock());
  2899   // Clear the marking bit map array before starting, but, just
  2900   // for kicks, first report if the given address is already marked
  2901   gclog_or_tty->print_cr("Start: Address 0x%x is%s marked", addr,
  2902                 _markBitMap.isMarked(addr) ? "" : " not");
  2904   if (verify_after_remark()) {
  2905     MutexLockerEx x(verification_mark_bm()->lock(), Mutex::_no_safepoint_check_flag);
  2906     bool result = verification_mark_bm()->isMarked(addr);
  2907     gclog_or_tty->print_cr("TransitiveMark: Address 0x%x %s marked", addr,
  2908                            result ? "IS" : "is NOT");
  2909     return result;
  2910   } else {
  2911     gclog_or_tty->print_cr("Could not compute result");
  2912     return false;
  2917 void
  2918 CMSCollector::print_on_error(outputStream* st) {
  2919   CMSCollector* collector = ConcurrentMarkSweepGeneration::_collector;
  2920   if (collector != NULL) {
  2921     CMSBitMap* bitmap = &collector->_markBitMap;
  2922     st->print_cr("Marking Bits: (CMSBitMap*) " PTR_FORMAT, bitmap);
  2923     bitmap->print_on_error(st, " Bits: ");
  2925     st->cr();
  2927     CMSBitMap* mut_bitmap = &collector->_modUnionTable;
  2928     st->print_cr("Mod Union Table: (CMSBitMap*) " PTR_FORMAT, mut_bitmap);
  2929     mut_bitmap->print_on_error(st, " Bits: ");
  2933 ////////////////////////////////////////////////////////
  2934 // CMS Verification Support
  2935 ////////////////////////////////////////////////////////
  2936 // Following the remark phase, the following invariant
  2937 // should hold -- each object in the CMS heap which is
  2938 // marked in markBitMap() should be marked in the verification_mark_bm().
  2940 class VerifyMarkedClosure: public BitMapClosure {
  2941   CMSBitMap* _marks;
  2942   bool       _failed;
  2944  public:
  2945   VerifyMarkedClosure(CMSBitMap* bm): _marks(bm), _failed(false) {}
  2947   bool do_bit(size_t offset) {
  2948     HeapWord* addr = _marks->offsetToHeapWord(offset);
  2949     if (!_marks->isMarked(addr)) {
  2950       oop(addr)->print_on(gclog_or_tty);
  2951       gclog_or_tty->print_cr(" ("INTPTR_FORMAT" should have been marked)", addr);
  2952       _failed = true;
  2954     return true;
  2957   bool failed() { return _failed; }
  2958 };
  2960 bool CMSCollector::verify_after_remark(bool silent) {
  2961   if (!silent) gclog_or_tty->print(" [Verifying CMS Marking... ");
  2962   MutexLockerEx ml(verification_mark_bm()->lock(), Mutex::_no_safepoint_check_flag);
  2963   static bool init = false;
  2965   assert(SafepointSynchronize::is_at_safepoint(),
  2966          "Else mutations in object graph will make answer suspect");
  2967   assert(have_cms_token(),
  2968          "Else there may be mutual interference in use of "
  2969          " verification data structures");
  2970   assert(_collectorState > Marking && _collectorState <= Sweeping,
  2971          "Else marking info checked here may be obsolete");
  2972   assert(haveFreelistLocks(), "must hold free list locks");
  2973   assert_lock_strong(bitMapLock());
  2976   // Allocate marking bit map if not already allocated
  2977   if (!init) { // first time
  2978     if (!verification_mark_bm()->allocate(_span)) {
  2979       return false;
  2981     init = true;
  2984   assert(verification_mark_stack()->isEmpty(), "Should be empty");
  2986   // Turn off refs discovery -- so we will be tracing through refs.
  2987   // This is as intended, because by this time
  2988   // GC must already have cleared any refs that need to be cleared,
  2989   // and traced those that need to be marked; moreover,
  2990   // the marking done here is not going to intefere in any
  2991   // way with the marking information used by GC.
  2992   NoRefDiscovery no_discovery(ref_processor());
  2994   COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;)
  2996   // Clear any marks from a previous round
  2997   verification_mark_bm()->clear_all();
  2998   assert(verification_mark_stack()->isEmpty(), "markStack should be empty");
  2999   verify_work_stacks_empty();
  3001   GenCollectedHeap* gch = GenCollectedHeap::heap();
  3002   gch->ensure_parsability(false);  // fill TLABs, but no need to retire them
  3003   // Update the saved marks which may affect the root scans.
  3004   gch->save_marks();
  3006   if (CMSRemarkVerifyVariant == 1) {
  3007     // In this first variant of verification, we complete
  3008     // all marking, then check if the new marks-verctor is
  3009     // a subset of the CMS marks-vector.
  3010     verify_after_remark_work_1();
  3011   } else if (CMSRemarkVerifyVariant == 2) {
  3012     // In this second variant of verification, we flag an error
  3013     // (i.e. an object reachable in the new marks-vector not reachable
  3014     // in the CMS marks-vector) immediately, also indicating the
  3015     // identify of an object (A) that references the unmarked object (B) --
  3016     // presumably, a mutation to A failed to be picked up by preclean/remark?
  3017     verify_after_remark_work_2();
  3018   } else {
  3019     warning("Unrecognized value %d for CMSRemarkVerifyVariant",
  3020             CMSRemarkVerifyVariant);
  3022   if (!silent) gclog_or_tty->print(" done] ");
  3023   return true;
  3026 void CMSCollector::verify_after_remark_work_1() {
  3027   ResourceMark rm;
  3028   HandleMark  hm;
  3029   GenCollectedHeap* gch = GenCollectedHeap::heap();
  3031   // Get a clear set of claim bits for the strong roots processing to work with.
  3032   ClassLoaderDataGraph::clear_claimed_marks();
  3034   // Mark from roots one level into CMS
  3035   MarkRefsIntoClosure notOlder(_span, verification_mark_bm());
  3036   gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
  3038   gch->gen_process_strong_roots(_cmsGen->level(),
  3039                                 true,   // younger gens are roots
  3040                                 true,   // activate StrongRootsScope
  3041                                 SharedHeap::ScanningOption(roots_scanning_options()),
  3042                                 &notOlder,
  3043                                 NULL,
  3044                                 NULL); // SSS: Provide correct closure
  3046   // Now mark from the roots
  3047   MarkFromRootsClosure markFromRootsClosure(this, _span,
  3048     verification_mark_bm(), verification_mark_stack(),
  3049     false /* don't yield */, true /* verifying */);
  3050   assert(_restart_addr == NULL, "Expected pre-condition");
  3051   verification_mark_bm()->iterate(&markFromRootsClosure);
  3052   while (_restart_addr != NULL) {
  3053     // Deal with stack overflow: by restarting at the indicated
  3054     // address.
  3055     HeapWord* ra = _restart_addr;
  3056     markFromRootsClosure.reset(ra);
  3057     _restart_addr = NULL;
  3058     verification_mark_bm()->iterate(&markFromRootsClosure, ra, _span.end());
  3060   assert(verification_mark_stack()->isEmpty(), "Should have been drained");
  3061   verify_work_stacks_empty();
  3063   // Marking completed -- now verify that each bit marked in
  3064   // verification_mark_bm() is also marked in markBitMap(); flag all
  3065   // errors by printing corresponding objects.
  3066   VerifyMarkedClosure vcl(markBitMap());
  3067   verification_mark_bm()->iterate(&vcl);
  3068   if (vcl.failed()) {
  3069     gclog_or_tty->print("Verification failed");
  3070     Universe::heap()->print_on(gclog_or_tty);
  3071     fatal("CMS: failed marking verification after remark");
  3075 class VerifyKlassOopsKlassClosure : public KlassClosure {
  3076   class VerifyKlassOopsClosure : public OopClosure {
  3077     CMSBitMap* _bitmap;
  3078    public:
  3079     VerifyKlassOopsClosure(CMSBitMap* bitmap) : _bitmap(bitmap) { }
  3080     void do_oop(oop* p)       { guarantee(*p == NULL || _bitmap->isMarked((HeapWord*) *p), "Should be marked"); }
  3081     void do_oop(narrowOop* p) { ShouldNotReachHere(); }
  3082   } _oop_closure;
  3083  public:
  3084   VerifyKlassOopsKlassClosure(CMSBitMap* bitmap) : _oop_closure(bitmap) {}
  3085   void do_klass(Klass* k) {
  3086     k->oops_do(&_oop_closure);
  3088 };
  3090 void CMSCollector::verify_after_remark_work_2() {
  3091   ResourceMark rm;
  3092   HandleMark  hm;
  3093   GenCollectedHeap* gch = GenCollectedHeap::heap();
  3095   // Get a clear set of claim bits for the strong roots processing to work with.
  3096   ClassLoaderDataGraph::clear_claimed_marks();
  3098   // Mark from roots one level into CMS
  3099   MarkRefsIntoVerifyClosure notOlder(_span, verification_mark_bm(),
  3100                                      markBitMap());
  3101   CMKlassClosure klass_closure(&notOlder);
  3103   gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
  3104   gch->gen_process_strong_roots(_cmsGen->level(),
  3105                                 true,   // younger gens are roots
  3106                                 true,   // activate StrongRootsScope
  3107                                 SharedHeap::ScanningOption(roots_scanning_options()),
  3108                                 &notOlder,
  3109                                 NULL,
  3110                                 &klass_closure);
  3112   // Now mark from the roots
  3113   MarkFromRootsVerifyClosure markFromRootsClosure(this, _span,
  3114     verification_mark_bm(), markBitMap(), verification_mark_stack());
  3115   assert(_restart_addr == NULL, "Expected pre-condition");
  3116   verification_mark_bm()->iterate(&markFromRootsClosure);
  3117   while (_restart_addr != NULL) {
  3118     // Deal with stack overflow: by restarting at the indicated
  3119     // address.
  3120     HeapWord* ra = _restart_addr;
  3121     markFromRootsClosure.reset(ra);
  3122     _restart_addr = NULL;
  3123     verification_mark_bm()->iterate(&markFromRootsClosure, ra, _span.end());
  3125   assert(verification_mark_stack()->isEmpty(), "Should have been drained");
  3126   verify_work_stacks_empty();
  3128   VerifyKlassOopsKlassClosure verify_klass_oops(verification_mark_bm());
  3129   ClassLoaderDataGraph::classes_do(&verify_klass_oops);
  3131   // Marking completed -- now verify that each bit marked in
  3132   // verification_mark_bm() is also marked in markBitMap(); flag all
  3133   // errors by printing corresponding objects.
  3134   VerifyMarkedClosure vcl(markBitMap());
  3135   verification_mark_bm()->iterate(&vcl);
  3136   assert(!vcl.failed(), "Else verification above should not have succeeded");
  3139 void ConcurrentMarkSweepGeneration::save_marks() {
  3140   // delegate to CMS space
  3141   cmsSpace()->save_marks();
  3142   for (uint i = 0; i < ParallelGCThreads; i++) {
  3143     _par_gc_thread_states[i]->promo.startTrackingPromotions();
  3147 bool ConcurrentMarkSweepGeneration::no_allocs_since_save_marks() {
  3148   return cmsSpace()->no_allocs_since_save_marks();
  3151 #define CMS_SINCE_SAVE_MARKS_DEFN(OopClosureType, nv_suffix)    \
  3153 void ConcurrentMarkSweepGeneration::                            \
  3154 oop_since_save_marks_iterate##nv_suffix(OopClosureType* cl) {   \
  3155   cl->set_generation(this);                                     \
  3156   cmsSpace()->oop_since_save_marks_iterate##nv_suffix(cl);      \
  3157   cl->reset_generation();                                       \
  3158   save_marks();                                                 \
  3161 ALL_SINCE_SAVE_MARKS_CLOSURES(CMS_SINCE_SAVE_MARKS_DEFN)
  3163 void
  3164 ConcurrentMarkSweepGeneration::younger_refs_iterate(OopsInGenClosure* cl) {
  3165   cl->set_generation(this);
  3166   younger_refs_in_space_iterate(_cmsSpace, cl);
  3167   cl->reset_generation();
  3170 void
  3171 ConcurrentMarkSweepGeneration::oop_iterate(MemRegion mr, ExtendedOopClosure* cl) {
  3172   if (freelistLock()->owned_by_self()) {
  3173     Generation::oop_iterate(mr, cl);
  3174   } else {
  3175     MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
  3176     Generation::oop_iterate(mr, cl);
  3180 void
  3181 ConcurrentMarkSweepGeneration::oop_iterate(ExtendedOopClosure* cl) {
  3182   if (freelistLock()->owned_by_self()) {
  3183     Generation::oop_iterate(cl);
  3184   } else {
  3185     MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
  3186     Generation::oop_iterate(cl);
  3190 void
  3191 ConcurrentMarkSweepGeneration::object_iterate(ObjectClosure* cl) {
  3192   if (freelistLock()->owned_by_self()) {
  3193     Generation::object_iterate(cl);
  3194   } else {
  3195     MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
  3196     Generation::object_iterate(cl);
  3200 void
  3201 ConcurrentMarkSweepGeneration::safe_object_iterate(ObjectClosure* cl) {
  3202   if (freelistLock()->owned_by_self()) {
  3203     Generation::safe_object_iterate(cl);
  3204   } else {
  3205     MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
  3206     Generation::safe_object_iterate(cl);
  3210 void
  3211 ConcurrentMarkSweepGeneration::post_compact() {
  3214 void
  3215 ConcurrentMarkSweepGeneration::prepare_for_verify() {
  3216   // Fix the linear allocation blocks to look like free blocks.
  3218   // Locks are normally acquired/released in gc_prologue/gc_epilogue, but those
  3219   // are not called when the heap is verified during universe initialization and
  3220   // at vm shutdown.
  3221   if (freelistLock()->owned_by_self()) {
  3222     cmsSpace()->prepare_for_verify();
  3223   } else {
  3224     MutexLockerEx fll(freelistLock(), Mutex::_no_safepoint_check_flag);
  3225     cmsSpace()->prepare_for_verify();
  3229 void
  3230 ConcurrentMarkSweepGeneration::verify() {
  3231   // Locks are normally acquired/released in gc_prologue/gc_epilogue, but those
  3232   // are not called when the heap is verified during universe initialization and
  3233   // at vm shutdown.
  3234   if (freelistLock()->owned_by_self()) {
  3235     cmsSpace()->verify();
  3236   } else {
  3237     MutexLockerEx fll(freelistLock(), Mutex::_no_safepoint_check_flag);
  3238     cmsSpace()->verify();
  3242 void CMSCollector::verify() {
  3243   _cmsGen->verify();
  3246 #ifndef PRODUCT
  3247 bool CMSCollector::overflow_list_is_empty() const {
  3248   assert(_num_par_pushes >= 0, "Inconsistency");
  3249   if (_overflow_list == NULL) {
  3250     assert(_num_par_pushes == 0, "Inconsistency");
  3252   return _overflow_list == NULL;
  3255 // The methods verify_work_stacks_empty() and verify_overflow_empty()
  3256 // merely consolidate assertion checks that appear to occur together frequently.
  3257 void CMSCollector::verify_work_stacks_empty() const {
  3258   assert(_markStack.isEmpty(), "Marking stack should be empty");
  3259   assert(overflow_list_is_empty(), "Overflow list should be empty");
  3262 void CMSCollector::verify_overflow_empty() const {
  3263   assert(overflow_list_is_empty(), "Overflow list should be empty");
  3264   assert(no_preserved_marks(), "No preserved marks");
  3266 #endif // PRODUCT
  3268 // Decide if we want to enable class unloading as part of the
  3269 // ensuing concurrent GC cycle. We will collect and
  3270 // unload classes if it's the case that:
  3271 // (1) an explicit gc request has been made and the flag
  3272 //     ExplicitGCInvokesConcurrentAndUnloadsClasses is set, OR
  3273 // (2) (a) class unloading is enabled at the command line, and
  3274 //     (b) old gen is getting really full
  3275 // NOTE: Provided there is no change in the state of the heap between
  3276 // calls to this method, it should have idempotent results. Moreover,
  3277 // its results should be monotonically increasing (i.e. going from 0 to 1,
  3278 // but not 1 to 0) between successive calls between which the heap was
  3279 // not collected. For the implementation below, it must thus rely on
  3280 // the property that concurrent_cycles_since_last_unload()
  3281 // will not decrease unless a collection cycle happened and that
  3282 // _cmsGen->is_too_full() are
  3283 // themselves also monotonic in that sense. See check_monotonicity()
  3284 // below.
  3285 void CMSCollector::update_should_unload_classes() {
  3286   _should_unload_classes = false;
  3287   // Condition 1 above
  3288   if (_full_gc_requested && ExplicitGCInvokesConcurrentAndUnloadsClasses) {
  3289     _should_unload_classes = true;
  3290   } else if (CMSClassUnloadingEnabled) { // Condition 2.a above
  3291     // Disjuncts 2.b.(i,ii,iii) above
  3292     _should_unload_classes = (concurrent_cycles_since_last_unload() >=
  3293                               CMSClassUnloadingMaxInterval)
  3294                            || _cmsGen->is_too_full();
  3298 bool ConcurrentMarkSweepGeneration::is_too_full() const {
  3299   bool res = should_concurrent_collect();
  3300   res = res && (occupancy() > (double)CMSIsTooFullPercentage/100.0);
  3301   return res;
  3304 void CMSCollector::setup_cms_unloading_and_verification_state() {
  3305   const  bool should_verify =   VerifyBeforeGC || VerifyAfterGC || VerifyDuringGC
  3306                              || VerifyBeforeExit;
  3307   const  int  rso           =   SharedHeap::SO_Strings | SharedHeap::SO_AllCodeCache;
  3309   // We set the proper root for this CMS cycle here.
  3310   if (should_unload_classes()) {   // Should unload classes this cycle
  3311     remove_root_scanning_option(SharedHeap::SO_AllClasses);
  3312     add_root_scanning_option(SharedHeap::SO_SystemClasses);
  3313     remove_root_scanning_option(rso);  // Shrink the root set appropriately
  3314     set_verifying(should_verify);    // Set verification state for this cycle
  3315     return;                            // Nothing else needs to be done at this time
  3318   // Not unloading classes this cycle
  3319   assert(!should_unload_classes(), "Inconsitency!");
  3320   remove_root_scanning_option(SharedHeap::SO_SystemClasses);
  3321   add_root_scanning_option(SharedHeap::SO_AllClasses);
  3323   if ((!verifying() || unloaded_classes_last_cycle()) && should_verify) {
  3324     // Include symbols, strings and code cache elements to prevent their resurrection.
  3325     add_root_scanning_option(rso);
  3326     set_verifying(true);
  3327   } else if (verifying() && !should_verify) {
  3328     // We were verifying, but some verification flags got disabled.
  3329     set_verifying(false);
  3330     // Exclude symbols, strings and code cache elements from root scanning to
  3331     // reduce IM and RM pauses.
  3332     remove_root_scanning_option(rso);
  3337 #ifndef PRODUCT
  3338 HeapWord* CMSCollector::block_start(const void* p) const {
  3339   const HeapWord* addr = (HeapWord*)p;
  3340   if (_span.contains(p)) {
  3341     if (_cmsGen->cmsSpace()->is_in_reserved(addr)) {
  3342       return _cmsGen->cmsSpace()->block_start(p);
  3345   return NULL;
  3347 #endif
  3349 HeapWord*
  3350 ConcurrentMarkSweepGeneration::expand_and_allocate(size_t word_size,
  3351                                                    bool   tlab,
  3352                                                    bool   parallel) {
  3353   CMSSynchronousYieldRequest yr;
  3354   assert(!tlab, "Can't deal with TLAB allocation");
  3355   MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
  3356   expand(word_size*HeapWordSize, MinHeapDeltaBytes,
  3357     CMSExpansionCause::_satisfy_allocation);
  3358   if (GCExpandToAllocateDelayMillis > 0) {
  3359     os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
  3361   return have_lock_and_allocate(word_size, tlab);
  3364 // YSR: All of this generation expansion/shrinking stuff is an exact copy of
  3365 // OneContigSpaceCardGeneration, which makes me wonder if we should move this
  3366 // to CardGeneration and share it...
  3367 bool ConcurrentMarkSweepGeneration::expand(size_t bytes, size_t expand_bytes) {
  3368   return CardGeneration::expand(bytes, expand_bytes);
  3371 void ConcurrentMarkSweepGeneration::expand(size_t bytes, size_t expand_bytes,
  3372   CMSExpansionCause::Cause cause)
  3375   bool success = expand(bytes, expand_bytes);
  3377   // remember why we expanded; this information is used
  3378   // by shouldConcurrentCollect() when making decisions on whether to start
  3379   // a new CMS cycle.
  3380   if (success) {
  3381     set_expansion_cause(cause);
  3382     if (PrintGCDetails && Verbose) {
  3383       gclog_or_tty->print_cr("Expanded CMS gen for %s",
  3384         CMSExpansionCause::to_string(cause));
  3389 HeapWord* ConcurrentMarkSweepGeneration::expand_and_par_lab_allocate(CMSParGCThreadState* ps, size_t word_sz) {
  3390   HeapWord* res = NULL;
  3391   MutexLocker x(ParGCRareEvent_lock);
  3392   while (true) {
  3393     // Expansion by some other thread might make alloc OK now:
  3394     res = ps->lab.alloc(word_sz);
  3395     if (res != NULL) return res;
  3396     // If there's not enough expansion space available, give up.
  3397     if (_virtual_space.uncommitted_size() < (word_sz * HeapWordSize)) {
  3398       return NULL;
  3400     // Otherwise, we try expansion.
  3401     expand(word_sz*HeapWordSize, MinHeapDeltaBytes,
  3402       CMSExpansionCause::_allocate_par_lab);
  3403     // Now go around the loop and try alloc again;
  3404     // A competing par_promote might beat us to the expansion space,
  3405     // so we may go around the loop again if promotion fails agaion.
  3406     if (GCExpandToAllocateDelayMillis > 0) {
  3407       os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
  3413 bool ConcurrentMarkSweepGeneration::expand_and_ensure_spooling_space(
  3414   PromotionInfo* promo) {
  3415   MutexLocker x(ParGCRareEvent_lock);
  3416   size_t refill_size_bytes = promo->refillSize() * HeapWordSize;
  3417   while (true) {
  3418     // Expansion by some other thread might make alloc OK now:
  3419     if (promo->ensure_spooling_space()) {
  3420       assert(promo->has_spooling_space(),
  3421              "Post-condition of successful ensure_spooling_space()");
  3422       return true;
  3424     // If there's not enough expansion space available, give up.
  3425     if (_virtual_space.uncommitted_size() < refill_size_bytes) {
  3426       return false;
  3428     // Otherwise, we try expansion.
  3429     expand(refill_size_bytes, MinHeapDeltaBytes,
  3430       CMSExpansionCause::_allocate_par_spooling_space);
  3431     // Now go around the loop and try alloc again;
  3432     // A competing allocation might beat us to the expansion space,
  3433     // so we may go around the loop again if allocation fails again.
  3434     if (GCExpandToAllocateDelayMillis > 0) {
  3435       os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
  3441 void ConcurrentMarkSweepGeneration::shrink_by(size_t bytes) {
  3442   assert_locked_or_safepoint(ExpandHeap_lock);
  3443   // Shrink committed space
  3444   _virtual_space.shrink_by(bytes);
  3445   // Shrink space; this also shrinks the space's BOT
  3446   _cmsSpace->set_end((HeapWord*) _virtual_space.high());
  3447   size_t new_word_size = heap_word_size(_cmsSpace->capacity());
  3448   // Shrink the shared block offset array
  3449   _bts->resize(new_word_size);
  3450   MemRegion mr(_cmsSpace->bottom(), new_word_size);
  3451   // Shrink the card table
  3452   Universe::heap()->barrier_set()->resize_covered_region(mr);
  3454   if (Verbose && PrintGC) {
  3455     size_t new_mem_size = _virtual_space.committed_size();
  3456     size_t old_mem_size = new_mem_size + bytes;
  3457     gclog_or_tty->print_cr("Shrinking %s from " SIZE_FORMAT "K to " SIZE_FORMAT "K",
  3458                   name(), old_mem_size/K, new_mem_size/K);
  3462 void ConcurrentMarkSweepGeneration::shrink(size_t bytes) {
  3463   assert_locked_or_safepoint(Heap_lock);
  3464   size_t size = ReservedSpace::page_align_size_down(bytes);
  3465   // Only shrink if a compaction was done so that all the free space
  3466   // in the generation is in a contiguous block at the end.
  3467   if (size > 0 && did_compact()) {
  3468     shrink_by(size);
  3472 bool ConcurrentMarkSweepGeneration::grow_by(size_t bytes) {
  3473   assert_locked_or_safepoint(Heap_lock);
  3474   bool result = _virtual_space.expand_by(bytes);
  3475   if (result) {
  3476     size_t new_word_size =
  3477       heap_word_size(_virtual_space.committed_size());
  3478     MemRegion mr(_cmsSpace->bottom(), new_word_size);
  3479     _bts->resize(new_word_size);  // resize the block offset shared array
  3480     Universe::heap()->barrier_set()->resize_covered_region(mr);
  3481     // Hmmmm... why doesn't CFLS::set_end verify locking?
  3482     // This is quite ugly; FIX ME XXX
  3483     _cmsSpace->assert_locked(freelistLock());
  3484     _cmsSpace->set_end((HeapWord*)_virtual_space.high());
  3486     // update the space and generation capacity counters
  3487     if (UsePerfData) {
  3488       _space_counters->update_capacity();
  3489       _gen_counters->update_all();
  3492     if (Verbose && PrintGC) {
  3493       size_t new_mem_size = _virtual_space.committed_size();
  3494       size_t old_mem_size = new_mem_size - bytes;
  3495       gclog_or_tty->print_cr("Expanding %s from " SIZE_FORMAT "K by " SIZE_FORMAT "K to " SIZE_FORMAT "K",
  3496                     name(), old_mem_size/K, bytes/K, new_mem_size/K);
  3499   return result;
  3502 bool ConcurrentMarkSweepGeneration::grow_to_reserved() {
  3503   assert_locked_or_safepoint(Heap_lock);
  3504   bool success = true;
  3505   const size_t remaining_bytes = _virtual_space.uncommitted_size();
  3506   if (remaining_bytes > 0) {
  3507     success = grow_by(remaining_bytes);
  3508     DEBUG_ONLY(if (!success) warning("grow to reserved failed");)
  3510   return success;
  3513 void ConcurrentMarkSweepGeneration::shrink_free_list_by(size_t bytes) {
  3514   assert_locked_or_safepoint(Heap_lock);
  3515   assert_lock_strong(freelistLock());
  3516   if (PrintGCDetails && Verbose) {
  3517     warning("Shrinking of CMS not yet implemented");
  3519   return;
  3523 // Simple ctor/dtor wrapper for accounting & timer chores around concurrent
  3524 // phases.
  3525 class CMSPhaseAccounting: public StackObj {
  3526  public:
  3527   CMSPhaseAccounting(CMSCollector *collector,
  3528                      const char *phase,
  3529                      const GCId gc_id,
  3530                      bool print_cr = true);
  3531   ~CMSPhaseAccounting();
  3533  private:
  3534   CMSCollector *_collector;
  3535   const char *_phase;
  3536   elapsedTimer _wallclock;
  3537   bool _print_cr;
  3538   const GCId _gc_id;
  3540  public:
  3541   // Not MT-safe; so do not pass around these StackObj's
  3542   // where they may be accessed by other threads.
  3543   jlong wallclock_millis() {
  3544     assert(_wallclock.is_active(), "Wall clock should not stop");
  3545     _wallclock.stop();  // to record time
  3546     jlong ret = _wallclock.milliseconds();
  3547     _wallclock.start(); // restart
  3548     return ret;
  3550 };
  3552 CMSPhaseAccounting::CMSPhaseAccounting(CMSCollector *collector,
  3553                                        const char *phase,
  3554                                        const GCId gc_id,
  3555                                        bool print_cr) :
  3556   _collector(collector), _phase(phase), _print_cr(print_cr), _gc_id(gc_id) {
  3558   if (PrintCMSStatistics != 0) {
  3559     _collector->resetYields();
  3561   if (PrintGCDetails) {
  3562     gclog_or_tty->gclog_stamp(_gc_id);
  3563     gclog_or_tty->print_cr("[%s-concurrent-%s-start]",
  3564       _collector->cmsGen()->short_name(), _phase);
  3566   _collector->resetTimer();
  3567   _wallclock.start();
  3568   _collector->startTimer();
  3571 CMSPhaseAccounting::~CMSPhaseAccounting() {
  3572   assert(_wallclock.is_active(), "Wall clock should not have stopped");
  3573   _collector->stopTimer();
  3574   _wallclock.stop();
  3575   if (PrintGCDetails) {
  3576     gclog_or_tty->gclog_stamp(_gc_id);
  3577     gclog_or_tty->print("[%s-concurrent-%s: %3.3f/%3.3f secs]",
  3578                  _collector->cmsGen()->short_name(),
  3579                  _phase, _collector->timerValue(), _wallclock.seconds());
  3580     if (_print_cr) {
  3581       gclog_or_tty->cr();
  3583     if (PrintCMSStatistics != 0) {
  3584       gclog_or_tty->print_cr(" (CMS-concurrent-%s yielded %d times)", _phase,
  3585                     _collector->yields());
  3590 // CMS work
  3592 // The common parts of CMSParInitialMarkTask and CMSParRemarkTask.
  3593 class CMSParMarkTask : public AbstractGangTask {
  3594  protected:
  3595   CMSCollector*     _collector;
  3596   int               _n_workers;
  3597   CMSParMarkTask(const char* name, CMSCollector* collector, int n_workers) :
  3598       AbstractGangTask(name),
  3599       _collector(collector),
  3600       _n_workers(n_workers) {}
  3601   // Work method in support of parallel rescan ... of young gen spaces
  3602   void do_young_space_rescan(uint worker_id, OopsInGenClosure* cl,
  3603                              ContiguousSpace* space,
  3604                              HeapWord** chunk_array, size_t chunk_top);
  3605   void work_on_young_gen_roots(uint worker_id, OopsInGenClosure* cl);
  3606 };
  3608 // Parallel initial mark task
  3609 class CMSParInitialMarkTask: public CMSParMarkTask {
  3610  public:
  3611   CMSParInitialMarkTask(CMSCollector* collector, int n_workers) :
  3612       CMSParMarkTask("Scan roots and young gen for initial mark in parallel",
  3613                      collector, n_workers) {}
  3614   void work(uint worker_id);
  3615 };
  3617 // Checkpoint the roots into this generation from outside
  3618 // this generation. [Note this initial checkpoint need only
  3619 // be approximate -- we'll do a catch up phase subsequently.]
  3620 void CMSCollector::checkpointRootsInitial(bool asynch) {
  3621   assert(_collectorState == InitialMarking, "Wrong collector state");
  3622   check_correct_thread_executing();
  3623   TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause());
  3625   save_heap_summary();
  3626   report_heap_summary(GCWhen::BeforeGC);
  3628   ReferenceProcessor* rp = ref_processor();
  3629   SpecializationStats::clear();
  3630   assert(_restart_addr == NULL, "Control point invariant");
  3631   if (asynch) {
  3632     // acquire locks for subsequent manipulations
  3633     MutexLockerEx x(bitMapLock(),
  3634                     Mutex::_no_safepoint_check_flag);
  3635     checkpointRootsInitialWork(asynch);
  3636     // enable ("weak") refs discovery
  3637     rp->enable_discovery(true /*verify_disabled*/, true /*check_no_refs*/);
  3638     _collectorState = Marking;
  3639   } else {
  3640     // (Weak) Refs discovery: this is controlled from genCollectedHeap::do_collection
  3641     // which recognizes if we are a CMS generation, and doesn't try to turn on
  3642     // discovery; verify that they aren't meddling.
  3643     assert(!rp->discovery_is_atomic(),
  3644            "incorrect setting of discovery predicate");
  3645     assert(!rp->discovery_enabled(), "genCollectedHeap shouldn't control "
  3646            "ref discovery for this generation kind");
  3647     // already have locks
  3648     checkpointRootsInitialWork(asynch);
  3649     // now enable ("weak") refs discovery
  3650     rp->enable_discovery(true /*verify_disabled*/, false /*verify_no_refs*/);
  3651     _collectorState = Marking;
  3653   SpecializationStats::print();
  3656 void CMSCollector::checkpointRootsInitialWork(bool asynch) {
  3657   assert(SafepointSynchronize::is_at_safepoint(), "world should be stopped");
  3658   assert(_collectorState == InitialMarking, "just checking");
  3660   // If there has not been a GC[n-1] since last GC[n] cycle completed,
  3661   // precede our marking with a collection of all
  3662   // younger generations to keep floating garbage to a minimum.
  3663   // XXX: we won't do this for now -- it's an optimization to be done later.
  3665   // already have locks
  3666   assert_lock_strong(bitMapLock());
  3667   assert(_markBitMap.isAllClear(), "was reset at end of previous cycle");
  3669   // Setup the verification and class unloading state for this
  3670   // CMS collection cycle.
  3671   setup_cms_unloading_and_verification_state();
  3673   NOT_PRODUCT(GCTraceTime t("\ncheckpointRootsInitialWork",
  3674     PrintGCDetails && Verbose, true, _gc_timer_cm, _gc_tracer_cm->gc_id());)
  3675   if (UseAdaptiveSizePolicy) {
  3676     size_policy()->checkpoint_roots_initial_begin();
  3679   // Reset all the PLAB chunk arrays if necessary.
  3680   if (_survivor_plab_array != NULL && !CMSPLABRecordAlways) {
  3681     reset_survivor_plab_arrays();
  3684   ResourceMark rm;
  3685   HandleMark  hm;
  3687   MarkRefsIntoClosure notOlder(_span, &_markBitMap);
  3688   GenCollectedHeap* gch = GenCollectedHeap::heap();
  3690   verify_work_stacks_empty();
  3691   verify_overflow_empty();
  3693   gch->ensure_parsability(false);  // fill TLABs, but no need to retire them
  3694   // Update the saved marks which may affect the root scans.
  3695   gch->save_marks();
  3697   // weak reference processing has not started yet.
  3698   ref_processor()->set_enqueuing_is_done(false);
  3700   // Need to remember all newly created CLDs,
  3701   // so that we can guarantee that the remark finds them.
  3702   ClassLoaderDataGraph::remember_new_clds(true);
  3704   // Whenever a CLD is found, it will be claimed before proceeding to mark
  3705   // the klasses. The claimed marks need to be cleared before marking starts.
  3706   ClassLoaderDataGraph::clear_claimed_marks();
  3708   if (CMSPrintEdenSurvivorChunks) {
  3709     print_eden_and_survivor_chunk_arrays();
  3713     COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;)
  3714     if (CMSParallelInitialMarkEnabled && CollectedHeap::use_parallel_gc_threads()) {
  3715       // The parallel version.
  3716       FlexibleWorkGang* workers = gch->workers();
  3717       assert(workers != NULL, "Need parallel worker threads.");
  3718       int n_workers = workers->active_workers();
  3719       CMSParInitialMarkTask tsk(this, n_workers);
  3720       gch->set_par_threads(n_workers);
  3721       initialize_sequential_subtasks_for_young_gen_rescan(n_workers);
  3722       if (n_workers > 1) {
  3723         GenCollectedHeap::StrongRootsScope srs(gch);
  3724         workers->run_task(&tsk);
  3725       } else {
  3726         GenCollectedHeap::StrongRootsScope srs(gch);
  3727         tsk.work(0);
  3729       gch->set_par_threads(0);
  3730     } else {
  3731       // The serial version.
  3732       CMKlassClosure klass_closure(&notOlder);
  3733       gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
  3734       gch->gen_process_strong_roots(_cmsGen->level(),
  3735                                     true,   // younger gens are roots
  3736                                     true,   // activate StrongRootsScope
  3737                                     SharedHeap::ScanningOption(roots_scanning_options()),
  3738                                     &notOlder,
  3739                                     NULL,
  3740                                     &klass_closure);
  3744   // Clear mod-union table; it will be dirtied in the prologue of
  3745   // CMS generation per each younger generation collection.
  3747   assert(_modUnionTable.isAllClear(),
  3748        "Was cleared in most recent final checkpoint phase"
  3749        " or no bits are set in the gc_prologue before the start of the next "
  3750        "subsequent marking phase.");
  3752   assert(_ct->klass_rem_set()->mod_union_is_clear(), "Must be");
  3754   // Save the end of the used_region of the constituent generations
  3755   // to be used to limit the extent of sweep in each generation.
  3756   save_sweep_limits();
  3757   if (UseAdaptiveSizePolicy) {
  3758     size_policy()->checkpoint_roots_initial_end(gch->gc_cause());
  3760   verify_overflow_empty();
  3763 bool CMSCollector::markFromRoots(bool asynch) {
  3764   // we might be tempted to assert that:
  3765   // assert(asynch == !SafepointSynchronize::is_at_safepoint(),
  3766   //        "inconsistent argument?");
  3767   // However that wouldn't be right, because it's possible that
  3768   // a safepoint is indeed in progress as a younger generation
  3769   // stop-the-world GC happens even as we mark in this generation.
  3770   assert(_collectorState == Marking, "inconsistent state?");
  3771   check_correct_thread_executing();
  3772   verify_overflow_empty();
  3774   bool res;
  3775   if (asynch) {
  3777     // Start the timers for adaptive size policy for the concurrent phases
  3778     // Do it here so that the foreground MS can use the concurrent
  3779     // timer since a foreground MS might has the sweep done concurrently
  3780     // or STW.
  3781     if (UseAdaptiveSizePolicy) {
  3782       size_policy()->concurrent_marking_begin();
  3785     // Weak ref discovery note: We may be discovering weak
  3786     // refs in this generation concurrent (but interleaved) with
  3787     // weak ref discovery by a younger generation collector.
  3789     CMSTokenSyncWithLocks ts(true, bitMapLock());
  3790     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  3791     CMSPhaseAccounting pa(this, "mark", _gc_tracer_cm->gc_id(), !PrintGCDetails);
  3792     res = markFromRootsWork(asynch);
  3793     if (res) {
  3794       _collectorState = Precleaning;
  3795     } else { // We failed and a foreground collection wants to take over
  3796       assert(_foregroundGCIsActive, "internal state inconsistency");
  3797       assert(_restart_addr == NULL,  "foreground will restart from scratch");
  3798       if (PrintGCDetails) {
  3799         gclog_or_tty->print_cr("bailing out to foreground collection");
  3802     if (UseAdaptiveSizePolicy) {
  3803       size_policy()->concurrent_marking_end();
  3805   } else {
  3806     assert(SafepointSynchronize::is_at_safepoint(),
  3807            "inconsistent with asynch == false");
  3808     if (UseAdaptiveSizePolicy) {
  3809       size_policy()->ms_collection_marking_begin();
  3811     // already have locks
  3812     res = markFromRootsWork(asynch);
  3813     _collectorState = FinalMarking;
  3814     if (UseAdaptiveSizePolicy) {
  3815       GenCollectedHeap* gch = GenCollectedHeap::heap();
  3816       size_policy()->ms_collection_marking_end(gch->gc_cause());
  3819   verify_overflow_empty();
  3820   return res;
  3823 bool CMSCollector::markFromRootsWork(bool asynch) {
  3824   // iterate over marked bits in bit map, doing a full scan and mark
  3825   // from these roots using the following algorithm:
  3826   // . if oop is to the right of the current scan pointer,
  3827   //   mark corresponding bit (we'll process it later)
  3828   // . else (oop is to left of current scan pointer)
  3829   //   push oop on marking stack
  3830   // . drain the marking stack
  3832   // Note that when we do a marking step we need to hold the
  3833   // bit map lock -- recall that direct allocation (by mutators)
  3834   // and promotion (by younger generation collectors) is also
  3835   // marking the bit map. [the so-called allocate live policy.]
  3836   // Because the implementation of bit map marking is not
  3837   // robust wrt simultaneous marking of bits in the same word,
  3838   // we need to make sure that there is no such interference
  3839   // between concurrent such updates.
  3841   // already have locks
  3842   assert_lock_strong(bitMapLock());
  3844   verify_work_stacks_empty();
  3845   verify_overflow_empty();
  3846   bool result = false;
  3847   if (CMSConcurrentMTEnabled && ConcGCThreads > 0) {
  3848     result = do_marking_mt(asynch);
  3849   } else {
  3850     result = do_marking_st(asynch);
  3852   return result;
  3855 // Forward decl
  3856 class CMSConcMarkingTask;
  3858 class CMSConcMarkingTerminator: public ParallelTaskTerminator {
  3859   CMSCollector*       _collector;
  3860   CMSConcMarkingTask* _task;
  3861  public:
  3862   virtual void yield();
  3864   // "n_threads" is the number of threads to be terminated.
  3865   // "queue_set" is a set of work queues of other threads.
  3866   // "collector" is the CMS collector associated with this task terminator.
  3867   // "yield" indicates whether we need the gang as a whole to yield.
  3868   CMSConcMarkingTerminator(int n_threads, TaskQueueSetSuper* queue_set, CMSCollector* collector) :
  3869     ParallelTaskTerminator(n_threads, queue_set),
  3870     _collector(collector) { }
  3872   void set_task(CMSConcMarkingTask* task) {
  3873     _task = task;
  3875 };
  3877 class CMSConcMarkingTerminatorTerminator: public TerminatorTerminator {
  3878   CMSConcMarkingTask* _task;
  3879  public:
  3880   bool should_exit_termination();
  3881   void set_task(CMSConcMarkingTask* task) {
  3882     _task = task;
  3884 };
  3886 // MT Concurrent Marking Task
  3887 class CMSConcMarkingTask: public YieldingFlexibleGangTask {
  3888   CMSCollector* _collector;
  3889   int           _n_workers;                  // requested/desired # workers
  3890   bool          _asynch;
  3891   bool          _result;
  3892   CompactibleFreeListSpace*  _cms_space;
  3893   char          _pad_front[64];   // padding to ...
  3894   HeapWord*     _global_finger;   // ... avoid sharing cache line
  3895   char          _pad_back[64];
  3896   HeapWord*     _restart_addr;
  3898   //  Exposed here for yielding support
  3899   Mutex* const _bit_map_lock;
  3901   // The per thread work queues, available here for stealing
  3902   OopTaskQueueSet*  _task_queues;
  3904   // Termination (and yielding) support
  3905   CMSConcMarkingTerminator _term;
  3906   CMSConcMarkingTerminatorTerminator _term_term;
  3908  public:
  3909   CMSConcMarkingTask(CMSCollector* collector,
  3910                  CompactibleFreeListSpace* cms_space,
  3911                  bool asynch,
  3912                  YieldingFlexibleWorkGang* workers,
  3913                  OopTaskQueueSet* task_queues):
  3914     YieldingFlexibleGangTask("Concurrent marking done multi-threaded"),
  3915     _collector(collector),
  3916     _cms_space(cms_space),
  3917     _asynch(asynch), _n_workers(0), _result(true),
  3918     _task_queues(task_queues),
  3919     _term(_n_workers, task_queues, _collector),
  3920     _bit_map_lock(collector->bitMapLock())
  3922     _requested_size = _n_workers;
  3923     _term.set_task(this);
  3924     _term_term.set_task(this);
  3925     _restart_addr = _global_finger = _cms_space->bottom();
  3929   OopTaskQueueSet* task_queues()  { return _task_queues; }
  3931   OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); }
  3933   HeapWord** global_finger_addr() { return &_global_finger; }
  3935   CMSConcMarkingTerminator* terminator() { return &_term; }
  3937   virtual void set_for_termination(int active_workers) {
  3938     terminator()->reset_for_reuse(active_workers);
  3941   void work(uint worker_id);
  3942   bool should_yield() {
  3943     return    ConcurrentMarkSweepThread::should_yield()
  3944            && !_collector->foregroundGCIsActive()
  3945            && _asynch;
  3948   virtual void coordinator_yield();  // stuff done by coordinator
  3949   bool result() { return _result; }
  3951   void reset(HeapWord* ra) {
  3952     assert(_global_finger >= _cms_space->end(),  "Postcondition of ::work(i)");
  3953     _restart_addr = _global_finger = ra;
  3954     _term.reset_for_reuse();
  3957   static bool get_work_from_overflow_stack(CMSMarkStack* ovflw_stk,
  3958                                            OopTaskQueue* work_q);
  3960  private:
  3961   void do_scan_and_mark(int i, CompactibleFreeListSpace* sp);
  3962   void do_work_steal(int i);
  3963   void bump_global_finger(HeapWord* f);
  3964 };
  3966 bool CMSConcMarkingTerminatorTerminator::should_exit_termination() {
  3967   assert(_task != NULL, "Error");
  3968   return _task->yielding();
  3969   // Note that we do not need the disjunct || _task->should_yield() above
  3970   // because we want terminating threads to yield only if the task
  3971   // is already in the midst of yielding, which happens only after at least one
  3972   // thread has yielded.
  3975 void CMSConcMarkingTerminator::yield() {
  3976   if (_task->should_yield()) {
  3977     _task->yield();
  3978   } else {
  3979     ParallelTaskTerminator::yield();
  3983 ////////////////////////////////////////////////////////////////
  3984 // Concurrent Marking Algorithm Sketch
  3985 ////////////////////////////////////////////////////////////////
  3986 // Until all tasks exhausted (both spaces):
  3987 // -- claim next available chunk
  3988 // -- bump global finger via CAS
  3989 // -- find first object that starts in this chunk
  3990 //    and start scanning bitmap from that position
  3991 // -- scan marked objects for oops
  3992 // -- CAS-mark target, and if successful:
  3993 //    . if target oop is above global finger (volatile read)
  3994 //      nothing to do
  3995 //    . if target oop is in chunk and above local finger
  3996 //        then nothing to do
  3997 //    . else push on work-queue
  3998 // -- Deal with possible overflow issues:
  3999 //    . local work-queue overflow causes stuff to be pushed on
  4000 //      global (common) overflow queue
  4001 //    . always first empty local work queue
  4002 //    . then get a batch of oops from global work queue if any
  4003 //    . then do work stealing
  4004 // -- When all tasks claimed (both spaces)
  4005 //    and local work queue empty,
  4006 //    then in a loop do:
  4007 //    . check global overflow stack; steal a batch of oops and trace
  4008 //    . try to steal from other threads oif GOS is empty
  4009 //    . if neither is available, offer termination
  4010 // -- Terminate and return result
  4011 //
  4012 void CMSConcMarkingTask::work(uint worker_id) {
  4013   elapsedTimer _timer;
  4014   ResourceMark rm;
  4015   HandleMark hm;
  4017   DEBUG_ONLY(_collector->verify_overflow_empty();)
  4019   // Before we begin work, our work queue should be empty
  4020   assert(work_queue(worker_id)->size() == 0, "Expected to be empty");
  4021   // Scan the bitmap covering _cms_space, tracing through grey objects.
  4022   _timer.start();
  4023   do_scan_and_mark(worker_id, _cms_space);
  4024   _timer.stop();
  4025   if (PrintCMSStatistics != 0) {
  4026     gclog_or_tty->print_cr("Finished cms space scanning in %dth thread: %3.3f sec",
  4027       worker_id, _timer.seconds());
  4028       // XXX: need xxx/xxx type of notation, two timers
  4031   // ... do work stealing
  4032   _timer.reset();
  4033   _timer.start();
  4034   do_work_steal(worker_id);
  4035   _timer.stop();
  4036   if (PrintCMSStatistics != 0) {
  4037     gclog_or_tty->print_cr("Finished work stealing in %dth thread: %3.3f sec",
  4038       worker_id, _timer.seconds());
  4039       // XXX: need xxx/xxx type of notation, two timers
  4041   assert(_collector->_markStack.isEmpty(), "Should have been emptied");
  4042   assert(work_queue(worker_id)->size() == 0, "Should have been emptied");
  4043   // Note that under the current task protocol, the
  4044   // following assertion is true even of the spaces
  4045   // expanded since the completion of the concurrent
  4046   // marking. XXX This will likely change under a strict
  4047   // ABORT semantics.
  4048   // After perm removal the comparison was changed to
  4049   // greater than or equal to from strictly greater than.
  4050   // Before perm removal the highest address sweep would
  4051   // have been at the end of perm gen but now is at the
  4052   // end of the tenured gen.
  4053   assert(_global_finger >=  _cms_space->end(),
  4054          "All tasks have been completed");
  4055   DEBUG_ONLY(_collector->verify_overflow_empty();)
  4058 void CMSConcMarkingTask::bump_global_finger(HeapWord* f) {
  4059   HeapWord* read = _global_finger;
  4060   HeapWord* cur  = read;
  4061   while (f > read) {
  4062     cur = read;
  4063     read = (HeapWord*) Atomic::cmpxchg_ptr(f, &_global_finger, cur);
  4064     if (cur == read) {
  4065       // our cas succeeded
  4066       assert(_global_finger >= f, "protocol consistency");
  4067       break;
  4072 // This is really inefficient, and should be redone by
  4073 // using (not yet available) block-read and -write interfaces to the
  4074 // stack and the work_queue. XXX FIX ME !!!
  4075 bool CMSConcMarkingTask::get_work_from_overflow_stack(CMSMarkStack* ovflw_stk,
  4076                                                       OopTaskQueue* work_q) {
  4077   // Fast lock-free check
  4078   if (ovflw_stk->length() == 0) {
  4079     return false;
  4081   assert(work_q->size() == 0, "Shouldn't steal");
  4082   MutexLockerEx ml(ovflw_stk->par_lock(),
  4083                    Mutex::_no_safepoint_check_flag);
  4084   // Grab up to 1/4 the size of the work queue
  4085   size_t num = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
  4086                     (size_t)ParGCDesiredObjsFromOverflowList);
  4087   num = MIN2(num, ovflw_stk->length());
  4088   for (int i = (int) num; i > 0; i--) {
  4089     oop cur = ovflw_stk->pop();
  4090     assert(cur != NULL, "Counted wrong?");
  4091     work_q->push(cur);
  4093   return num > 0;
  4096 void CMSConcMarkingTask::do_scan_and_mark(int i, CompactibleFreeListSpace* sp) {
  4097   SequentialSubTasksDone* pst = sp->conc_par_seq_tasks();
  4098   int n_tasks = pst->n_tasks();
  4099   // We allow that there may be no tasks to do here because
  4100   // we are restarting after a stack overflow.
  4101   assert(pst->valid() || n_tasks == 0, "Uninitialized use?");
  4102   uint nth_task = 0;
  4104   HeapWord* aligned_start = sp->bottom();
  4105   if (sp->used_region().contains(_restart_addr)) {
  4106     // Align down to a card boundary for the start of 0th task
  4107     // for this space.
  4108     aligned_start =
  4109       (HeapWord*)align_size_down((uintptr_t)_restart_addr,
  4110                                  CardTableModRefBS::card_size);
  4113   size_t chunk_size = sp->marking_task_size();
  4114   while (!pst->is_task_claimed(/* reference */ nth_task)) {
  4115     // Having claimed the nth task in this space,
  4116     // compute the chunk that it corresponds to:
  4117     MemRegion span = MemRegion(aligned_start + nth_task*chunk_size,
  4118                                aligned_start + (nth_task+1)*chunk_size);
  4119     // Try and bump the global finger via a CAS;
  4120     // note that we need to do the global finger bump
  4121     // _before_ taking the intersection below, because
  4122     // the task corresponding to that region will be
  4123     // deemed done even if the used_region() expands
  4124     // because of allocation -- as it almost certainly will
  4125     // during start-up while the threads yield in the
  4126     // closure below.
  4127     HeapWord* finger = span.end();
  4128     bump_global_finger(finger);   // atomically
  4129     // There are null tasks here corresponding to chunks
  4130     // beyond the "top" address of the space.
  4131     span = span.intersection(sp->used_region());
  4132     if (!span.is_empty()) {  // Non-null task
  4133       HeapWord* prev_obj;
  4134       assert(!span.contains(_restart_addr) || nth_task == 0,
  4135              "Inconsistency");
  4136       if (nth_task == 0) {
  4137         // For the 0th task, we'll not need to compute a block_start.
  4138         if (span.contains(_restart_addr)) {
  4139           // In the case of a restart because of stack overflow,
  4140           // we might additionally skip a chunk prefix.
  4141           prev_obj = _restart_addr;
  4142         } else {
  4143           prev_obj = span.start();
  4145       } else {
  4146         // We want to skip the first object because
  4147         // the protocol is to scan any object in its entirety
  4148         // that _starts_ in this span; a fortiori, any
  4149         // object starting in an earlier span is scanned
  4150         // as part of an earlier claimed task.
  4151         // Below we use the "careful" version of block_start
  4152         // so we do not try to navigate uninitialized objects.
  4153         prev_obj = sp->block_start_careful(span.start());
  4154         // Below we use a variant of block_size that uses the
  4155         // Printezis bits to avoid waiting for allocated
  4156         // objects to become initialized/parsable.
  4157         while (prev_obj < span.start()) {
  4158           size_t sz = sp->block_size_no_stall(prev_obj, _collector);
  4159           if (sz > 0) {
  4160             prev_obj += sz;
  4161           } else {
  4162             // In this case we may end up doing a bit of redundant
  4163             // scanning, but that appears unavoidable, short of
  4164             // locking the free list locks; see bug 6324141.
  4165             break;
  4169       if (prev_obj < span.end()) {
  4170         MemRegion my_span = MemRegion(prev_obj, span.end());
  4171         // Do the marking work within a non-empty span --
  4172         // the last argument to the constructor indicates whether the
  4173         // iteration should be incremental with periodic yields.
  4174         Par_MarkFromRootsClosure cl(this, _collector, my_span,
  4175                                     &_collector->_markBitMap,
  4176                                     work_queue(i),
  4177                                     &_collector->_markStack,
  4178                                     _asynch);
  4179         _collector->_markBitMap.iterate(&cl, my_span.start(), my_span.end());
  4180       } // else nothing to do for this task
  4181     }   // else nothing to do for this task
  4183   // We'd be tempted to assert here that since there are no
  4184   // more tasks left to claim in this space, the global_finger
  4185   // must exceed space->top() and a fortiori space->end(). However,
  4186   // that would not quite be correct because the bumping of
  4187   // global_finger occurs strictly after the claiming of a task,
  4188   // so by the time we reach here the global finger may not yet
  4189   // have been bumped up by the thread that claimed the last
  4190   // task.
  4191   pst->all_tasks_completed();
  4194 class Par_ConcMarkingClosure: public CMSOopClosure {
  4195  private:
  4196   CMSCollector* _collector;
  4197   CMSConcMarkingTask* _task;
  4198   MemRegion     _span;
  4199   CMSBitMap*    _bit_map;
  4200   CMSMarkStack* _overflow_stack;
  4201   OopTaskQueue* _work_queue;
  4202  protected:
  4203   DO_OOP_WORK_DEFN
  4204  public:
  4205   Par_ConcMarkingClosure(CMSCollector* collector, CMSConcMarkingTask* task, OopTaskQueue* work_queue,
  4206                          CMSBitMap* bit_map, CMSMarkStack* overflow_stack):
  4207     CMSOopClosure(collector->ref_processor()),
  4208     _collector(collector),
  4209     _task(task),
  4210     _span(collector->_span),
  4211     _work_queue(work_queue),
  4212     _bit_map(bit_map),
  4213     _overflow_stack(overflow_stack)
  4214   { }
  4215   virtual void do_oop(oop* p);
  4216   virtual void do_oop(narrowOop* p);
  4218   void trim_queue(size_t max);
  4219   void handle_stack_overflow(HeapWord* lost);
  4220   void do_yield_check() {
  4221     if (_task->should_yield()) {
  4222       _task->yield();
  4225 };
  4227 // Grey object scanning during work stealing phase --
  4228 // the salient assumption here is that any references
  4229 // that are in these stolen objects being scanned must
  4230 // already have been initialized (else they would not have
  4231 // been published), so we do not need to check for
  4232 // uninitialized objects before pushing here.
  4233 void Par_ConcMarkingClosure::do_oop(oop obj) {
  4234   assert(obj->is_oop_or_null(true), "expected an oop or NULL");
  4235   HeapWord* addr = (HeapWord*)obj;
  4236   // Check if oop points into the CMS generation
  4237   // and is not marked
  4238   if (_span.contains(addr) && !_bit_map->isMarked(addr)) {
  4239     // a white object ...
  4240     // If we manage to "claim" the object, by being the
  4241     // first thread to mark it, then we push it on our
  4242     // marking stack
  4243     if (_bit_map->par_mark(addr)) {     // ... now grey
  4244       // push on work queue (grey set)
  4245       bool simulate_overflow = false;
  4246       NOT_PRODUCT(
  4247         if (CMSMarkStackOverflowALot &&
  4248             _collector->simulate_overflow()) {
  4249           // simulate a stack overflow
  4250           simulate_overflow = true;
  4253       if (simulate_overflow ||
  4254           !(_work_queue->push(obj) || _overflow_stack->par_push(obj))) {
  4255         // stack overflow
  4256         if (PrintCMSStatistics != 0) {
  4257           gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
  4258                                  SIZE_FORMAT, _overflow_stack->capacity());
  4260         // We cannot assert that the overflow stack is full because
  4261         // it may have been emptied since.
  4262         assert(simulate_overflow ||
  4263                _work_queue->size() == _work_queue->max_elems(),
  4264               "Else push should have succeeded");
  4265         handle_stack_overflow(addr);
  4267     } // Else, some other thread got there first
  4268     do_yield_check();
  4272 void Par_ConcMarkingClosure::do_oop(oop* p)       { Par_ConcMarkingClosure::do_oop_work(p); }
  4273 void Par_ConcMarkingClosure::do_oop(narrowOop* p) { Par_ConcMarkingClosure::do_oop_work(p); }
  4275 void Par_ConcMarkingClosure::trim_queue(size_t max) {
  4276   while (_work_queue->size() > max) {
  4277     oop new_oop;
  4278     if (_work_queue->pop_local(new_oop)) {
  4279       assert(new_oop->is_oop(), "Should be an oop");
  4280       assert(_bit_map->isMarked((HeapWord*)new_oop), "Grey object");
  4281       assert(_span.contains((HeapWord*)new_oop), "Not in span");
  4282       new_oop->oop_iterate(this);  // do_oop() above
  4283       do_yield_check();
  4288 // Upon stack overflow, we discard (part of) the stack,
  4289 // remembering the least address amongst those discarded
  4290 // in CMSCollector's _restart_address.
  4291 void Par_ConcMarkingClosure::handle_stack_overflow(HeapWord* lost) {
  4292   // We need to do this under a mutex to prevent other
  4293   // workers from interfering with the work done below.
  4294   MutexLockerEx ml(_overflow_stack->par_lock(),
  4295                    Mutex::_no_safepoint_check_flag);
  4296   // Remember the least grey address discarded
  4297   HeapWord* ra = (HeapWord*)_overflow_stack->least_value(lost);
  4298   _collector->lower_restart_addr(ra);
  4299   _overflow_stack->reset();  // discard stack contents
  4300   _overflow_stack->expand(); // expand the stack if possible
  4304 void CMSConcMarkingTask::do_work_steal(int i) {
  4305   OopTaskQueue* work_q = work_queue(i);
  4306   oop obj_to_scan;
  4307   CMSBitMap* bm = &(_collector->_markBitMap);
  4308   CMSMarkStack* ovflw = &(_collector->_markStack);
  4309   int* seed = _collector->hash_seed(i);
  4310   Par_ConcMarkingClosure cl(_collector, this, work_q, bm, ovflw);
  4311   while (true) {
  4312     cl.trim_queue(0);
  4313     assert(work_q->size() == 0, "Should have been emptied above");
  4314     if (get_work_from_overflow_stack(ovflw, work_q)) {
  4315       // Can't assert below because the work obtained from the
  4316       // overflow stack may already have been stolen from us.
  4317       // assert(work_q->size() > 0, "Work from overflow stack");
  4318       continue;
  4319     } else if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) {
  4320       assert(obj_to_scan->is_oop(), "Should be an oop");
  4321       assert(bm->isMarked((HeapWord*)obj_to_scan), "Grey object");
  4322       obj_to_scan->oop_iterate(&cl);
  4323     } else if (terminator()->offer_termination(&_term_term)) {
  4324       assert(work_q->size() == 0, "Impossible!");
  4325       break;
  4326     } else if (yielding() || should_yield()) {
  4327       yield();
  4332 // This is run by the CMS (coordinator) thread.
  4333 void CMSConcMarkingTask::coordinator_yield() {
  4334   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  4335          "CMS thread should hold CMS token");
  4336   // First give up the locks, then yield, then re-lock
  4337   // We should probably use a constructor/destructor idiom to
  4338   // do this unlock/lock or modify the MutexUnlocker class to
  4339   // serve our purpose. XXX
  4340   assert_lock_strong(_bit_map_lock);
  4341   _bit_map_lock->unlock();
  4342   ConcurrentMarkSweepThread::desynchronize(true);
  4343   ConcurrentMarkSweepThread::acknowledge_yield_request();
  4344   _collector->stopTimer();
  4345   if (PrintCMSStatistics != 0) {
  4346     _collector->incrementYields();
  4348   _collector->icms_wait();
  4350   // It is possible for whichever thread initiated the yield request
  4351   // not to get a chance to wake up and take the bitmap lock between
  4352   // this thread releasing it and reacquiring it. So, while the
  4353   // should_yield() flag is on, let's sleep for a bit to give the
  4354   // other thread a chance to wake up. The limit imposed on the number
  4355   // of iterations is defensive, to avoid any unforseen circumstances
  4356   // putting us into an infinite loop. Since it's always been this
  4357   // (coordinator_yield()) method that was observed to cause the
  4358   // problem, we are using a parameter (CMSCoordinatorYieldSleepCount)
  4359   // which is by default non-zero. For the other seven methods that
  4360   // also perform the yield operation, as are using a different
  4361   // parameter (CMSYieldSleepCount) which is by default zero. This way we
  4362   // can enable the sleeping for those methods too, if necessary.
  4363   // See 6442774.
  4364   //
  4365   // We really need to reconsider the synchronization between the GC
  4366   // thread and the yield-requesting threads in the future and we
  4367   // should really use wait/notify, which is the recommended
  4368   // way of doing this type of interaction. Additionally, we should
  4369   // consolidate the eight methods that do the yield operation and they
  4370   // are almost identical into one for better maintenability and
  4371   // readability. See 6445193.
  4372   //
  4373   // Tony 2006.06.29
  4374   for (unsigned i = 0; i < CMSCoordinatorYieldSleepCount &&
  4375                    ConcurrentMarkSweepThread::should_yield() &&
  4376                    !CMSCollector::foregroundGCIsActive(); ++i) {
  4377     os::sleep(Thread::current(), 1, false);
  4378     ConcurrentMarkSweepThread::acknowledge_yield_request();
  4381   ConcurrentMarkSweepThread::synchronize(true);
  4382   _bit_map_lock->lock_without_safepoint_check();
  4383   _collector->startTimer();
  4386 bool CMSCollector::do_marking_mt(bool asynch) {
  4387   assert(ConcGCThreads > 0 && conc_workers() != NULL, "precondition");
  4388   int num_workers = AdaptiveSizePolicy::calc_active_conc_workers(
  4389                                        conc_workers()->total_workers(),
  4390                                        conc_workers()->active_workers(),
  4391                                        Threads::number_of_non_daemon_threads());
  4392   conc_workers()->set_active_workers(num_workers);
  4394   CompactibleFreeListSpace* cms_space  = _cmsGen->cmsSpace();
  4396   CMSConcMarkingTask tsk(this,
  4397                          cms_space,
  4398                          asynch,
  4399                          conc_workers(),
  4400                          task_queues());
  4402   // Since the actual number of workers we get may be different
  4403   // from the number we requested above, do we need to do anything different
  4404   // below? In particular, may be we need to subclass the SequantialSubTasksDone
  4405   // class?? XXX
  4406   cms_space ->initialize_sequential_subtasks_for_marking(num_workers);
  4408   // Refs discovery is already non-atomic.
  4409   assert(!ref_processor()->discovery_is_atomic(), "Should be non-atomic");
  4410   assert(ref_processor()->discovery_is_mt(), "Discovery should be MT");
  4411   conc_workers()->start_task(&tsk);
  4412   while (tsk.yielded()) {
  4413     tsk.coordinator_yield();
  4414     conc_workers()->continue_task(&tsk);
  4416   // If the task was aborted, _restart_addr will be non-NULL
  4417   assert(tsk.completed() || _restart_addr != NULL, "Inconsistency");
  4418   while (_restart_addr != NULL) {
  4419     // XXX For now we do not make use of ABORTED state and have not
  4420     // yet implemented the right abort semantics (even in the original
  4421     // single-threaded CMS case). That needs some more investigation
  4422     // and is deferred for now; see CR# TBF. 07252005YSR. XXX
  4423     assert(!CMSAbortSemantics || tsk.aborted(), "Inconsistency");
  4424     // If _restart_addr is non-NULL, a marking stack overflow
  4425     // occurred; we need to do a fresh marking iteration from the
  4426     // indicated restart address.
  4427     if (_foregroundGCIsActive && asynch) {
  4428       // We may be running into repeated stack overflows, having
  4429       // reached the limit of the stack size, while making very
  4430       // slow forward progress. It may be best to bail out and
  4431       // let the foreground collector do its job.
  4432       // Clear _restart_addr, so that foreground GC
  4433       // works from scratch. This avoids the headache of
  4434       // a "rescan" which would otherwise be needed because
  4435       // of the dirty mod union table & card table.
  4436       _restart_addr = NULL;
  4437       return false;
  4439     // Adjust the task to restart from _restart_addr
  4440     tsk.reset(_restart_addr);
  4441     cms_space ->initialize_sequential_subtasks_for_marking(num_workers,
  4442                   _restart_addr);
  4443     _restart_addr = NULL;
  4444     // Get the workers going again
  4445     conc_workers()->start_task(&tsk);
  4446     while (tsk.yielded()) {
  4447       tsk.coordinator_yield();
  4448       conc_workers()->continue_task(&tsk);
  4451   assert(tsk.completed(), "Inconsistency");
  4452   assert(tsk.result() == true, "Inconsistency");
  4453   return true;
  4456 bool CMSCollector::do_marking_st(bool asynch) {
  4457   ResourceMark rm;
  4458   HandleMark   hm;
  4460   // Temporarily make refs discovery single threaded (non-MT)
  4461   ReferenceProcessorMTDiscoveryMutator rp_mut_discovery(ref_processor(), false);
  4462   MarkFromRootsClosure markFromRootsClosure(this, _span, &_markBitMap,
  4463     &_markStack, CMSYield && asynch);
  4464   // the last argument to iterate indicates whether the iteration
  4465   // should be incremental with periodic yields.
  4466   _markBitMap.iterate(&markFromRootsClosure);
  4467   // If _restart_addr is non-NULL, a marking stack overflow
  4468   // occurred; we need to do a fresh iteration from the
  4469   // indicated restart address.
  4470   while (_restart_addr != NULL) {
  4471     if (_foregroundGCIsActive && asynch) {
  4472       // We may be running into repeated stack overflows, having
  4473       // reached the limit of the stack size, while making very
  4474       // slow forward progress. It may be best to bail out and
  4475       // let the foreground collector do its job.
  4476       // Clear _restart_addr, so that foreground GC
  4477       // works from scratch. This avoids the headache of
  4478       // a "rescan" which would otherwise be needed because
  4479       // of the dirty mod union table & card table.
  4480       _restart_addr = NULL;
  4481       return false;  // indicating failure to complete marking
  4483     // Deal with stack overflow:
  4484     // we restart marking from _restart_addr
  4485     HeapWord* ra = _restart_addr;
  4486     markFromRootsClosure.reset(ra);
  4487     _restart_addr = NULL;
  4488     _markBitMap.iterate(&markFromRootsClosure, ra, _span.end());
  4490   return true;
  4493 void CMSCollector::preclean() {
  4494   check_correct_thread_executing();
  4495   assert(Thread::current()->is_ConcurrentGC_thread(), "Wrong thread");
  4496   verify_work_stacks_empty();
  4497   verify_overflow_empty();
  4498   _abort_preclean = false;
  4499   if (CMSPrecleaningEnabled) {
  4500     if (!CMSEdenChunksRecordAlways) {
  4501       _eden_chunk_index = 0;
  4503     size_t used = get_eden_used();
  4504     size_t capacity = get_eden_capacity();
  4505     // Don't start sampling unless we will get sufficiently
  4506     // many samples.
  4507     if (used < (capacity/(CMSScheduleRemarkSamplingRatio * 100)
  4508                 * CMSScheduleRemarkEdenPenetration)) {
  4509       _start_sampling = true;
  4510     } else {
  4511       _start_sampling = false;
  4513     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  4514     CMSPhaseAccounting pa(this, "preclean", _gc_tracer_cm->gc_id(), !PrintGCDetails);
  4515     preclean_work(CMSPrecleanRefLists1, CMSPrecleanSurvivors1);
  4517   CMSTokenSync x(true); // is cms thread
  4518   if (CMSPrecleaningEnabled) {
  4519     sample_eden();
  4520     _collectorState = AbortablePreclean;
  4521   } else {
  4522     _collectorState = FinalMarking;
  4524   verify_work_stacks_empty();
  4525   verify_overflow_empty();
  4528 // Try and schedule the remark such that young gen
  4529 // occupancy is CMSScheduleRemarkEdenPenetration %.
  4530 void CMSCollector::abortable_preclean() {
  4531   check_correct_thread_executing();
  4532   assert(CMSPrecleaningEnabled,  "Inconsistent control state");
  4533   assert(_collectorState == AbortablePreclean, "Inconsistent control state");
  4535   // If Eden's current occupancy is below this threshold,
  4536   // immediately schedule the remark; else preclean
  4537   // past the next scavenge in an effort to
  4538   // schedule the pause as described avove. By choosing
  4539   // CMSScheduleRemarkEdenSizeThreshold >= max eden size
  4540   // we will never do an actual abortable preclean cycle.
  4541   if (get_eden_used() > CMSScheduleRemarkEdenSizeThreshold) {
  4542     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  4543     CMSPhaseAccounting pa(this, "abortable-preclean", _gc_tracer_cm->gc_id(), !PrintGCDetails);
  4544     // We need more smarts in the abortable preclean
  4545     // loop below to deal with cases where allocation
  4546     // in young gen is very very slow, and our precleaning
  4547     // is running a losing race against a horde of
  4548     // mutators intent on flooding us with CMS updates
  4549     // (dirty cards).
  4550     // One, admittedly dumb, strategy is to give up
  4551     // after a certain number of abortable precleaning loops
  4552     // or after a certain maximum time. We want to make
  4553     // this smarter in the next iteration.
  4554     // XXX FIX ME!!! YSR
  4555     size_t loops = 0, workdone = 0, cumworkdone = 0, waited = 0;
  4556     while (!(should_abort_preclean() ||
  4557              ConcurrentMarkSweepThread::should_terminate())) {
  4558       workdone = preclean_work(CMSPrecleanRefLists2, CMSPrecleanSurvivors2);
  4559       cumworkdone += workdone;
  4560       loops++;
  4561       // Voluntarily terminate abortable preclean phase if we have
  4562       // been at it for too long.
  4563       if ((CMSMaxAbortablePrecleanLoops != 0) &&
  4564           loops >= CMSMaxAbortablePrecleanLoops) {
  4565         if (PrintGCDetails) {
  4566           gclog_or_tty->print(" CMS: abort preclean due to loops ");
  4568         break;
  4570       if (pa.wallclock_millis() > CMSMaxAbortablePrecleanTime) {
  4571         if (PrintGCDetails) {
  4572           gclog_or_tty->print(" CMS: abort preclean due to time ");
  4574         break;
  4576       // If we are doing little work each iteration, we should
  4577       // take a short break.
  4578       if (workdone < CMSAbortablePrecleanMinWorkPerIteration) {
  4579         // Sleep for some time, waiting for work to accumulate
  4580         stopTimer();
  4581         cmsThread()->wait_on_cms_lock(CMSAbortablePrecleanWaitMillis);
  4582         startTimer();
  4583         waited++;
  4586     if (PrintCMSStatistics > 0) {
  4587       gclog_or_tty->print(" [%d iterations, %d waits, %d cards)] ",
  4588                           loops, waited, cumworkdone);
  4591   CMSTokenSync x(true); // is cms thread
  4592   if (_collectorState != Idling) {
  4593     assert(_collectorState == AbortablePreclean,
  4594            "Spontaneous state transition?");
  4595     _collectorState = FinalMarking;
  4596   } // Else, a foreground collection completed this CMS cycle.
  4597   return;
  4600 // Respond to an Eden sampling opportunity
  4601 void CMSCollector::sample_eden() {
  4602   // Make sure a young gc cannot sneak in between our
  4603   // reading and recording of a sample.
  4604   assert(Thread::current()->is_ConcurrentGC_thread(),
  4605          "Only the cms thread may collect Eden samples");
  4606   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  4607          "Should collect samples while holding CMS token");
  4608   if (!_start_sampling) {
  4609     return;
  4611   // When CMSEdenChunksRecordAlways is true, the eden chunk array
  4612   // is populated by the young generation.
  4613   if (_eden_chunk_array != NULL && !CMSEdenChunksRecordAlways) {
  4614     if (_eden_chunk_index < _eden_chunk_capacity) {
  4615       _eden_chunk_array[_eden_chunk_index] = *_top_addr;   // take sample
  4616       assert(_eden_chunk_array[_eden_chunk_index] <= *_end_addr,
  4617              "Unexpected state of Eden");
  4618       // We'd like to check that what we just sampled is an oop-start address;
  4619       // however, we cannot do that here since the object may not yet have been
  4620       // initialized. So we'll instead do the check when we _use_ this sample
  4621       // later.
  4622       if (_eden_chunk_index == 0 ||
  4623           (pointer_delta(_eden_chunk_array[_eden_chunk_index],
  4624                          _eden_chunk_array[_eden_chunk_index-1])
  4625            >= CMSSamplingGrain)) {
  4626         _eden_chunk_index++;  // commit sample
  4630   if ((_collectorState == AbortablePreclean) && !_abort_preclean) {
  4631     size_t used = get_eden_used();
  4632     size_t capacity = get_eden_capacity();
  4633     assert(used <= capacity, "Unexpected state of Eden");
  4634     if (used >  (capacity/100 * CMSScheduleRemarkEdenPenetration)) {
  4635       _abort_preclean = true;
  4641 size_t CMSCollector::preclean_work(bool clean_refs, bool clean_survivor) {
  4642   assert(_collectorState == Precleaning ||
  4643          _collectorState == AbortablePreclean, "incorrect state");
  4644   ResourceMark rm;
  4645   HandleMark   hm;
  4647   // Precleaning is currently not MT but the reference processor
  4648   // may be set for MT.  Disable it temporarily here.
  4649   ReferenceProcessor* rp = ref_processor();
  4650   ReferenceProcessorMTDiscoveryMutator rp_mut_discovery(rp, false);
  4652   // Do one pass of scrubbing the discovered reference lists
  4653   // to remove any reference objects with strongly-reachable
  4654   // referents.
  4655   if (clean_refs) {
  4656     CMSPrecleanRefsYieldClosure yield_cl(this);
  4657     assert(rp->span().equals(_span), "Spans should be equal");
  4658     CMSKeepAliveClosure keep_alive(this, _span, &_markBitMap,
  4659                                    &_markStack, true /* preclean */);
  4660     CMSDrainMarkingStackClosure complete_trace(this,
  4661                                    _span, &_markBitMap, &_markStack,
  4662                                    &keep_alive, true /* preclean */);
  4664     // We don't want this step to interfere with a young
  4665     // collection because we don't want to take CPU
  4666     // or memory bandwidth away from the young GC threads
  4667     // (which may be as many as there are CPUs).
  4668     // Note that we don't need to protect ourselves from
  4669     // interference with mutators because they can't
  4670     // manipulate the discovered reference lists nor affect
  4671     // the computed reachability of the referents, the
  4672     // only properties manipulated by the precleaning
  4673     // of these reference lists.
  4674     stopTimer();
  4675     CMSTokenSyncWithLocks x(true /* is cms thread */,
  4676                             bitMapLock());
  4677     startTimer();
  4678     sample_eden();
  4680     // The following will yield to allow foreground
  4681     // collection to proceed promptly. XXX YSR:
  4682     // The code in this method may need further
  4683     // tweaking for better performance and some restructuring
  4684     // for cleaner interfaces.
  4685     GCTimer *gc_timer = NULL; // Currently not tracing concurrent phases
  4686     rp->preclean_discovered_references(
  4687           rp->is_alive_non_header(), &keep_alive, &complete_trace, &yield_cl,
  4688           gc_timer, _gc_tracer_cm->gc_id());
  4691   if (clean_survivor) {  // preclean the active survivor space(s)
  4692     assert(_young_gen->kind() == Generation::DefNew ||
  4693            _young_gen->kind() == Generation::ParNew ||
  4694            _young_gen->kind() == Generation::ASParNew,
  4695          "incorrect type for cast");
  4696     DefNewGeneration* dng = (DefNewGeneration*)_young_gen;
  4697     PushAndMarkClosure pam_cl(this, _span, ref_processor(),
  4698                              &_markBitMap, &_modUnionTable,
  4699                              &_markStack, true /* precleaning phase */);
  4700     stopTimer();
  4701     CMSTokenSyncWithLocks ts(true /* is cms thread */,
  4702                              bitMapLock());
  4703     startTimer();
  4704     unsigned int before_count =
  4705       GenCollectedHeap::heap()->total_collections();
  4706     SurvivorSpacePrecleanClosure
  4707       sss_cl(this, _span, &_markBitMap, &_markStack,
  4708              &pam_cl, before_count, CMSYield);
  4709     dng->from()->object_iterate_careful(&sss_cl);
  4710     dng->to()->object_iterate_careful(&sss_cl);
  4712   MarkRefsIntoAndScanClosure
  4713     mrias_cl(_span, ref_processor(), &_markBitMap, &_modUnionTable,
  4714              &_markStack, this, CMSYield,
  4715              true /* precleaning phase */);
  4716   // CAUTION: The following closure has persistent state that may need to
  4717   // be reset upon a decrease in the sequence of addresses it
  4718   // processes.
  4719   ScanMarkedObjectsAgainCarefullyClosure
  4720     smoac_cl(this, _span,
  4721       &_markBitMap, &_markStack, &mrias_cl, CMSYield);
  4723   // Preclean dirty cards in ModUnionTable and CardTable using
  4724   // appropriate convergence criterion;
  4725   // repeat CMSPrecleanIter times unless we find that
  4726   // we are losing.
  4727   assert(CMSPrecleanIter < 10, "CMSPrecleanIter is too large");
  4728   assert(CMSPrecleanNumerator < CMSPrecleanDenominator,
  4729          "Bad convergence multiplier");
  4730   assert(CMSPrecleanThreshold >= 100,
  4731          "Unreasonably low CMSPrecleanThreshold");
  4733   size_t numIter, cumNumCards, lastNumCards, curNumCards;
  4734   for (numIter = 0, cumNumCards = lastNumCards = curNumCards = 0;
  4735        numIter < CMSPrecleanIter;
  4736        numIter++, lastNumCards = curNumCards, cumNumCards += curNumCards) {
  4737     curNumCards  = preclean_mod_union_table(_cmsGen, &smoac_cl);
  4738     if (Verbose && PrintGCDetails) {
  4739       gclog_or_tty->print(" (modUnionTable: %d cards)", curNumCards);
  4741     // Either there are very few dirty cards, so re-mark
  4742     // pause will be small anyway, or our pre-cleaning isn't
  4743     // that much faster than the rate at which cards are being
  4744     // dirtied, so we might as well stop and re-mark since
  4745     // precleaning won't improve our re-mark time by much.
  4746     if (curNumCards <= CMSPrecleanThreshold ||
  4747         (numIter > 0 &&
  4748          (curNumCards * CMSPrecleanDenominator >
  4749          lastNumCards * CMSPrecleanNumerator))) {
  4750       numIter++;
  4751       cumNumCards += curNumCards;
  4752       break;
  4756   preclean_klasses(&mrias_cl, _cmsGen->freelistLock());
  4758   curNumCards = preclean_card_table(_cmsGen, &smoac_cl);
  4759   cumNumCards += curNumCards;
  4760   if (PrintGCDetails && PrintCMSStatistics != 0) {
  4761     gclog_or_tty->print_cr(" (cardTable: %d cards, re-scanned %d cards, %d iterations)",
  4762                   curNumCards, cumNumCards, numIter);
  4764   return cumNumCards;   // as a measure of useful work done
  4767 // PRECLEANING NOTES:
  4768 // Precleaning involves:
  4769 // . reading the bits of the modUnionTable and clearing the set bits.
  4770 // . For the cards corresponding to the set bits, we scan the
  4771 //   objects on those cards. This means we need the free_list_lock
  4772 //   so that we can safely iterate over the CMS space when scanning
  4773 //   for oops.
  4774 // . When we scan the objects, we'll be both reading and setting
  4775 //   marks in the marking bit map, so we'll need the marking bit map.
  4776 // . For protecting _collector_state transitions, we take the CGC_lock.
  4777 //   Note that any races in the reading of of card table entries by the
  4778 //   CMS thread on the one hand and the clearing of those entries by the
  4779 //   VM thread or the setting of those entries by the mutator threads on the
  4780 //   other are quite benign. However, for efficiency it makes sense to keep
  4781 //   the VM thread from racing with the CMS thread while the latter is
  4782 //   dirty card info to the modUnionTable. We therefore also use the
  4783 //   CGC_lock to protect the reading of the card table and the mod union
  4784 //   table by the CM thread.
  4785 // . We run concurrently with mutator updates, so scanning
  4786 //   needs to be done carefully  -- we should not try to scan
  4787 //   potentially uninitialized objects.
  4788 //
  4789 // Locking strategy: While holding the CGC_lock, we scan over and
  4790 // reset a maximal dirty range of the mod union / card tables, then lock
  4791 // the free_list_lock and bitmap lock to do a full marking, then
  4792 // release these locks; and repeat the cycle. This allows for a
  4793 // certain amount of fairness in the sharing of these locks between
  4794 // the CMS collector on the one hand, and the VM thread and the
  4795 // mutators on the other.
  4797 // NOTE: preclean_mod_union_table() and preclean_card_table()
  4798 // further below are largely identical; if you need to modify
  4799 // one of these methods, please check the other method too.
  4801 size_t CMSCollector::preclean_mod_union_table(
  4802   ConcurrentMarkSweepGeneration* gen,
  4803   ScanMarkedObjectsAgainCarefullyClosure* cl) {
  4804   verify_work_stacks_empty();
  4805   verify_overflow_empty();
  4807   // strategy: starting with the first card, accumulate contiguous
  4808   // ranges of dirty cards; clear these cards, then scan the region
  4809   // covered by these cards.
  4811   // Since all of the MUT is committed ahead, we can just use
  4812   // that, in case the generations expand while we are precleaning.
  4813   // It might also be fine to just use the committed part of the
  4814   // generation, but we might potentially miss cards when the
  4815   // generation is rapidly expanding while we are in the midst
  4816   // of precleaning.
  4817   HeapWord* startAddr = gen->reserved().start();
  4818   HeapWord* endAddr   = gen->reserved().end();
  4820   cl->setFreelistLock(gen->freelistLock());   // needed for yielding
  4822   size_t numDirtyCards, cumNumDirtyCards;
  4823   HeapWord *nextAddr, *lastAddr;
  4824   for (cumNumDirtyCards = numDirtyCards = 0,
  4825        nextAddr = lastAddr = startAddr;
  4826        nextAddr < endAddr;
  4827        nextAddr = lastAddr, cumNumDirtyCards += numDirtyCards) {
  4829     ResourceMark rm;
  4830     HandleMark   hm;
  4832     MemRegion dirtyRegion;
  4834       stopTimer();
  4835       // Potential yield point
  4836       CMSTokenSync ts(true);
  4837       startTimer();
  4838       sample_eden();
  4839       // Get dirty region starting at nextOffset (inclusive),
  4840       // simultaneously clearing it.
  4841       dirtyRegion =
  4842         _modUnionTable.getAndClearMarkedRegion(nextAddr, endAddr);
  4843       assert(dirtyRegion.start() >= nextAddr,
  4844              "returned region inconsistent?");
  4846     // Remember where the next search should begin.
  4847     // The returned region (if non-empty) is a right open interval,
  4848     // so lastOffset is obtained from the right end of that
  4849     // interval.
  4850     lastAddr = dirtyRegion.end();
  4851     // Should do something more transparent and less hacky XXX
  4852     numDirtyCards =
  4853       _modUnionTable.heapWordDiffToOffsetDiff(dirtyRegion.word_size());
  4855     // We'll scan the cards in the dirty region (with periodic
  4856     // yields for foreground GC as needed).
  4857     if (!dirtyRegion.is_empty()) {
  4858       assert(numDirtyCards > 0, "consistency check");
  4859       HeapWord* stop_point = NULL;
  4860       stopTimer();
  4861       // Potential yield point
  4862       CMSTokenSyncWithLocks ts(true, gen->freelistLock(),
  4863                                bitMapLock());
  4864       startTimer();
  4866         verify_work_stacks_empty();
  4867         verify_overflow_empty();
  4868         sample_eden();
  4869         stop_point =
  4870           gen->cmsSpace()->object_iterate_careful_m(dirtyRegion, cl);
  4872       if (stop_point != NULL) {
  4873         // The careful iteration stopped early either because it found an
  4874         // uninitialized object, or because we were in the midst of an
  4875         // "abortable preclean", which should now be aborted. Redirty
  4876         // the bits corresponding to the partially-scanned or unscanned
  4877         // cards. We'll either restart at the next block boundary or
  4878         // abort the preclean.
  4879         assert((_collectorState == AbortablePreclean && should_abort_preclean()),
  4880                "Should only be AbortablePreclean.");
  4881         _modUnionTable.mark_range(MemRegion(stop_point, dirtyRegion.end()));
  4882         if (should_abort_preclean()) {
  4883           break; // out of preclean loop
  4884         } else {
  4885           // Compute the next address at which preclean should pick up;
  4886           // might need bitMapLock in order to read P-bits.
  4887           lastAddr = next_card_start_after_block(stop_point);
  4890     } else {
  4891       assert(lastAddr == endAddr, "consistency check");
  4892       assert(numDirtyCards == 0, "consistency check");
  4893       break;
  4896   verify_work_stacks_empty();
  4897   verify_overflow_empty();
  4898   return cumNumDirtyCards;
  4901 // NOTE: preclean_mod_union_table() above and preclean_card_table()
  4902 // below are largely identical; if you need to modify
  4903 // one of these methods, please check the other method too.
  4905 size_t CMSCollector::preclean_card_table(ConcurrentMarkSweepGeneration* gen,
  4906   ScanMarkedObjectsAgainCarefullyClosure* cl) {
  4907   // strategy: it's similar to precleamModUnionTable above, in that
  4908   // we accumulate contiguous ranges of dirty cards, mark these cards
  4909   // precleaned, then scan the region covered by these cards.
  4910   HeapWord* endAddr   = (HeapWord*)(gen->_virtual_space.high());
  4911   HeapWord* startAddr = (HeapWord*)(gen->_virtual_space.low());
  4913   cl->setFreelistLock(gen->freelistLock());   // needed for yielding
  4915   size_t numDirtyCards, cumNumDirtyCards;
  4916   HeapWord *lastAddr, *nextAddr;
  4918   for (cumNumDirtyCards = numDirtyCards = 0,
  4919        nextAddr = lastAddr = startAddr;
  4920        nextAddr < endAddr;
  4921        nextAddr = lastAddr, cumNumDirtyCards += numDirtyCards) {
  4923     ResourceMark rm;
  4924     HandleMark   hm;
  4926     MemRegion dirtyRegion;
  4928       // See comments in "Precleaning notes" above on why we
  4929       // do this locking. XXX Could the locking overheads be
  4930       // too high when dirty cards are sparse? [I don't think so.]
  4931       stopTimer();
  4932       CMSTokenSync x(true); // is cms thread
  4933       startTimer();
  4934       sample_eden();
  4935       // Get and clear dirty region from card table
  4936       dirtyRegion = _ct->ct_bs()->dirty_card_range_after_reset(
  4937                                     MemRegion(nextAddr, endAddr),
  4938                                     true,
  4939                                     CardTableModRefBS::precleaned_card_val());
  4941       assert(dirtyRegion.start() >= nextAddr,
  4942              "returned region inconsistent?");
  4944     lastAddr = dirtyRegion.end();
  4945     numDirtyCards =
  4946       dirtyRegion.word_size()/CardTableModRefBS::card_size_in_words;
  4948     if (!dirtyRegion.is_empty()) {
  4949       stopTimer();
  4950       CMSTokenSyncWithLocks ts(true, gen->freelistLock(), bitMapLock());
  4951       startTimer();
  4952       sample_eden();
  4953       verify_work_stacks_empty();
  4954       verify_overflow_empty();
  4955       HeapWord* stop_point =
  4956         gen->cmsSpace()->object_iterate_careful_m(dirtyRegion, cl);
  4957       if (stop_point != NULL) {
  4958         assert((_collectorState == AbortablePreclean && should_abort_preclean()),
  4959                "Should only be AbortablePreclean.");
  4960         _ct->ct_bs()->invalidate(MemRegion(stop_point, dirtyRegion.end()));
  4961         if (should_abort_preclean()) {
  4962           break; // out of preclean loop
  4963         } else {
  4964           // Compute the next address at which preclean should pick up.
  4965           lastAddr = next_card_start_after_block(stop_point);
  4968     } else {
  4969       break;
  4972   verify_work_stacks_empty();
  4973   verify_overflow_empty();
  4974   return cumNumDirtyCards;
  4977 class PrecleanKlassClosure : public KlassClosure {
  4978   CMKlassClosure _cm_klass_closure;
  4979  public:
  4980   PrecleanKlassClosure(OopClosure* oop_closure) : _cm_klass_closure(oop_closure) {}
  4981   void do_klass(Klass* k) {
  4982     if (k->has_accumulated_modified_oops()) {
  4983       k->clear_accumulated_modified_oops();
  4985       _cm_klass_closure.do_klass(k);
  4988 };
  4990 // The freelist lock is needed to prevent asserts, is it really needed?
  4991 void CMSCollector::preclean_klasses(MarkRefsIntoAndScanClosure* cl, Mutex* freelistLock) {
  4993   cl->set_freelistLock(freelistLock);
  4995   CMSTokenSyncWithLocks ts(true, freelistLock, bitMapLock());
  4997   // SSS: Add equivalent to ScanMarkedObjectsAgainCarefullyClosure::do_yield_check and should_abort_preclean?
  4998   // SSS: We should probably check if precleaning should be aborted, at suitable intervals?
  4999   PrecleanKlassClosure preclean_klass_closure(cl);
  5000   ClassLoaderDataGraph::classes_do(&preclean_klass_closure);
  5002   verify_work_stacks_empty();
  5003   verify_overflow_empty();
  5006 void CMSCollector::checkpointRootsFinal(bool asynch,
  5007   bool clear_all_soft_refs, bool init_mark_was_synchronous) {
  5008   assert(_collectorState == FinalMarking, "incorrect state transition?");
  5009   check_correct_thread_executing();
  5010   // world is stopped at this checkpoint
  5011   assert(SafepointSynchronize::is_at_safepoint(),
  5012          "world should be stopped");
  5013   TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause());
  5015   verify_work_stacks_empty();
  5016   verify_overflow_empty();
  5018   SpecializationStats::clear();
  5019   if (PrintGCDetails) {
  5020     gclog_or_tty->print("[YG occupancy: "SIZE_FORMAT" K ("SIZE_FORMAT" K)]",
  5021                         _young_gen->used() / K,
  5022                         _young_gen->capacity() / K);
  5024   if (asynch) {
  5025     if (CMSScavengeBeforeRemark) {
  5026       GenCollectedHeap* gch = GenCollectedHeap::heap();
  5027       // Temporarily set flag to false, GCH->do_collection will
  5028       // expect it to be false and set to true
  5029       FlagSetting fl(gch->_is_gc_active, false);
  5030       NOT_PRODUCT(GCTraceTime t("Scavenge-Before-Remark",
  5031         PrintGCDetails && Verbose, true, _gc_timer_cm, _gc_tracer_cm->gc_id());)
  5032       int level = _cmsGen->level() - 1;
  5033       if (level >= 0) {
  5034         gch->do_collection(true,        // full (i.e. force, see below)
  5035                            false,       // !clear_all_soft_refs
  5036                            0,           // size
  5037                            false,       // is_tlab
  5038                            level        // max_level
  5039                           );
  5042     FreelistLocker x(this);
  5043     MutexLockerEx y(bitMapLock(),
  5044                     Mutex::_no_safepoint_check_flag);
  5045     assert(!init_mark_was_synchronous, "but that's impossible!");
  5046     checkpointRootsFinalWork(asynch, clear_all_soft_refs, false);
  5047   } else {
  5048     // already have all the locks
  5049     checkpointRootsFinalWork(asynch, clear_all_soft_refs,
  5050                              init_mark_was_synchronous);
  5052   verify_work_stacks_empty();
  5053   verify_overflow_empty();
  5054   SpecializationStats::print();
  5057 void CMSCollector::checkpointRootsFinalWork(bool asynch,
  5058   bool clear_all_soft_refs, bool init_mark_was_synchronous) {
  5060   NOT_PRODUCT(GCTraceTime tr("checkpointRootsFinalWork", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());)
  5062   assert(haveFreelistLocks(), "must have free list locks");
  5063   assert_lock_strong(bitMapLock());
  5065   if (UseAdaptiveSizePolicy) {
  5066     size_policy()->checkpoint_roots_final_begin();
  5069   ResourceMark rm;
  5070   HandleMark   hm;
  5072   GenCollectedHeap* gch = GenCollectedHeap::heap();
  5074   if (should_unload_classes()) {
  5075     CodeCache::gc_prologue();
  5077   assert(haveFreelistLocks(), "must have free list locks");
  5078   assert_lock_strong(bitMapLock());
  5080   if (!init_mark_was_synchronous) {
  5081     // We might assume that we need not fill TLAB's when
  5082     // CMSScavengeBeforeRemark is set, because we may have just done
  5083     // a scavenge which would have filled all TLAB's -- and besides
  5084     // Eden would be empty. This however may not always be the case --
  5085     // for instance although we asked for a scavenge, it may not have
  5086     // happened because of a JNI critical section. We probably need
  5087     // a policy for deciding whether we can in that case wait until
  5088     // the critical section releases and then do the remark following
  5089     // the scavenge, and skip it here. In the absence of that policy,
  5090     // or of an indication of whether the scavenge did indeed occur,
  5091     // we cannot rely on TLAB's having been filled and must do
  5092     // so here just in case a scavenge did not happen.
  5093     gch->ensure_parsability(false);  // fill TLAB's, but no need to retire them
  5094     // Update the saved marks which may affect the root scans.
  5095     gch->save_marks();
  5097     if (CMSPrintEdenSurvivorChunks) {
  5098       print_eden_and_survivor_chunk_arrays();
  5102       COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;)
  5104       // Note on the role of the mod union table:
  5105       // Since the marker in "markFromRoots" marks concurrently with
  5106       // mutators, it is possible for some reachable objects not to have been
  5107       // scanned. For instance, an only reference to an object A was
  5108       // placed in object B after the marker scanned B. Unless B is rescanned,
  5109       // A would be collected. Such updates to references in marked objects
  5110       // are detected via the mod union table which is the set of all cards
  5111       // dirtied since the first checkpoint in this GC cycle and prior to
  5112       // the most recent young generation GC, minus those cleaned up by the
  5113       // concurrent precleaning.
  5114       if (CMSParallelRemarkEnabled && CollectedHeap::use_parallel_gc_threads()) {
  5115         GCTraceTime t("Rescan (parallel) ", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
  5116         do_remark_parallel();
  5117       } else {
  5118         GCTraceTime t("Rescan (non-parallel) ", PrintGCDetails, false,
  5119                     _gc_timer_cm, _gc_tracer_cm->gc_id());
  5120         do_remark_non_parallel();
  5123   } else {
  5124     assert(!asynch, "Can't have init_mark_was_synchronous in asynch mode");
  5125     // The initial mark was stop-world, so there's no rescanning to
  5126     // do; go straight on to the next step below.
  5128   verify_work_stacks_empty();
  5129   verify_overflow_empty();
  5132     NOT_PRODUCT(GCTraceTime ts("refProcessingWork", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());)
  5133     refProcessingWork(asynch, clear_all_soft_refs);
  5135   verify_work_stacks_empty();
  5136   verify_overflow_empty();
  5138   if (should_unload_classes()) {
  5139     CodeCache::gc_epilogue();
  5141   JvmtiExport::gc_epilogue();
  5143   // If we encountered any (marking stack / work queue) overflow
  5144   // events during the current CMS cycle, take appropriate
  5145   // remedial measures, where possible, so as to try and avoid
  5146   // recurrence of that condition.
  5147   assert(_markStack.isEmpty(), "No grey objects");
  5148   size_t ser_ovflw = _ser_pmc_remark_ovflw + _ser_pmc_preclean_ovflw +
  5149                      _ser_kac_ovflw        + _ser_kac_preclean_ovflw;
  5150   if (ser_ovflw > 0) {
  5151     if (PrintCMSStatistics != 0) {
  5152       gclog_or_tty->print_cr("Marking stack overflow (benign) "
  5153         "(pmc_pc="SIZE_FORMAT", pmc_rm="SIZE_FORMAT", kac="SIZE_FORMAT
  5154         ", kac_preclean="SIZE_FORMAT")",
  5155         _ser_pmc_preclean_ovflw, _ser_pmc_remark_ovflw,
  5156         _ser_kac_ovflw, _ser_kac_preclean_ovflw);
  5158     _markStack.expand();
  5159     _ser_pmc_remark_ovflw = 0;
  5160     _ser_pmc_preclean_ovflw = 0;
  5161     _ser_kac_preclean_ovflw = 0;
  5162     _ser_kac_ovflw = 0;
  5164   if (_par_pmc_remark_ovflw > 0 || _par_kac_ovflw > 0) {
  5165     if (PrintCMSStatistics != 0) {
  5166       gclog_or_tty->print_cr("Work queue overflow (benign) "
  5167         "(pmc_rm="SIZE_FORMAT", kac="SIZE_FORMAT")",
  5168         _par_pmc_remark_ovflw, _par_kac_ovflw);
  5170     _par_pmc_remark_ovflw = 0;
  5171     _par_kac_ovflw = 0;
  5173   if (PrintCMSStatistics != 0) {
  5174      if (_markStack._hit_limit > 0) {
  5175        gclog_or_tty->print_cr(" (benign) Hit max stack size limit ("SIZE_FORMAT")",
  5176                               _markStack._hit_limit);
  5178      if (_markStack._failed_double > 0) {
  5179        gclog_or_tty->print_cr(" (benign) Failed stack doubling ("SIZE_FORMAT"),"
  5180                               " current capacity "SIZE_FORMAT,
  5181                               _markStack._failed_double,
  5182                               _markStack.capacity());
  5185   _markStack._hit_limit = 0;
  5186   _markStack._failed_double = 0;
  5188   if ((VerifyAfterGC || VerifyDuringGC) &&
  5189       GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  5190     verify_after_remark();
  5193   _gc_tracer_cm->report_object_count_after_gc(&_is_alive_closure);
  5195   // Change under the freelistLocks.
  5196   _collectorState = Sweeping;
  5197   // Call isAllClear() under bitMapLock
  5198   assert(_modUnionTable.isAllClear(),
  5199       "Should be clear by end of the final marking");
  5200   assert(_ct->klass_rem_set()->mod_union_is_clear(),
  5201       "Should be clear by end of the final marking");
  5202   if (UseAdaptiveSizePolicy) {
  5203     size_policy()->checkpoint_roots_final_end(gch->gc_cause());
  5207 void CMSParInitialMarkTask::work(uint worker_id) {
  5208   elapsedTimer _timer;
  5209   ResourceMark rm;
  5210   HandleMark   hm;
  5212   // ---------- scan from roots --------------
  5213   _timer.start();
  5214   GenCollectedHeap* gch = GenCollectedHeap::heap();
  5215   Par_MarkRefsIntoClosure par_mri_cl(_collector->_span, &(_collector->_markBitMap));
  5216   CMKlassClosure klass_closure(&par_mri_cl);
  5218   // ---------- young gen roots --------------
  5220     work_on_young_gen_roots(worker_id, &par_mri_cl);
  5221     _timer.stop();
  5222     if (PrintCMSStatistics != 0) {
  5223       gclog_or_tty->print_cr(
  5224         "Finished young gen initial mark scan work in %dth thread: %3.3f sec",
  5225         worker_id, _timer.seconds());
  5229   // ---------- remaining roots --------------
  5230   _timer.reset();
  5231   _timer.start();
  5232   gch->gen_process_strong_roots(_collector->_cmsGen->level(),
  5233                                 false,     // yg was scanned above
  5234                                 false,     // this is parallel code
  5235                                 SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()),
  5236                                 &par_mri_cl,
  5237                                 NULL,
  5238                                 &klass_closure);
  5239   assert(_collector->should_unload_classes()
  5240          || (_collector->CMSCollector::roots_scanning_options() & SharedHeap::SO_AllCodeCache),
  5241          "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops");
  5242   _timer.stop();
  5243   if (PrintCMSStatistics != 0) {
  5244     gclog_or_tty->print_cr(
  5245       "Finished remaining root initial mark scan work in %dth thread: %3.3f sec",
  5246       worker_id, _timer.seconds());
  5250 // Parallel remark task
  5251 class CMSParRemarkTask: public CMSParMarkTask {
  5252   CompactibleFreeListSpace* _cms_space;
  5254   // The per-thread work queues, available here for stealing.
  5255   OopTaskQueueSet*       _task_queues;
  5256   ParallelTaskTerminator _term;
  5258  public:
  5259   // A value of 0 passed to n_workers will cause the number of
  5260   // workers to be taken from the active workers in the work gang.
  5261   CMSParRemarkTask(CMSCollector* collector,
  5262                    CompactibleFreeListSpace* cms_space,
  5263                    int n_workers, FlexibleWorkGang* workers,
  5264                    OopTaskQueueSet* task_queues):
  5265     CMSParMarkTask("Rescan roots and grey objects in parallel",
  5266                    collector, n_workers),
  5267     _cms_space(cms_space),
  5268     _task_queues(task_queues),
  5269     _term(n_workers, task_queues) { }
  5271   OopTaskQueueSet* task_queues() { return _task_queues; }
  5273   OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); }
  5275   ParallelTaskTerminator* terminator() { return &_term; }
  5276   int n_workers() { return _n_workers; }
  5278   void work(uint worker_id);
  5280  private:
  5281   // ... of  dirty cards in old space
  5282   void do_dirty_card_rescan_tasks(CompactibleFreeListSpace* sp, int i,
  5283                                   Par_MarkRefsIntoAndScanClosure* cl);
  5285   // ... work stealing for the above
  5286   void do_work_steal(int i, Par_MarkRefsIntoAndScanClosure* cl, int* seed);
  5287 };
  5289 class RemarkKlassClosure : public KlassClosure {
  5290   CMKlassClosure _cm_klass_closure;
  5291  public:
  5292   RemarkKlassClosure(OopClosure* oop_closure) : _cm_klass_closure(oop_closure) {}
  5293   void do_klass(Klass* k) {
  5294     // Check if we have modified any oops in the Klass during the concurrent marking.
  5295     if (k->has_accumulated_modified_oops()) {
  5296       k->clear_accumulated_modified_oops();
  5298       // We could have transfered the current modified marks to the accumulated marks,
  5299       // like we do with the Card Table to Mod Union Table. But it's not really necessary.
  5300     } else if (k->has_modified_oops()) {
  5301       // Don't clear anything, this info is needed by the next young collection.
  5302     } else {
  5303       // No modified oops in the Klass.
  5304       return;
  5307     // The klass has modified fields, need to scan the klass.
  5308     _cm_klass_closure.do_klass(k);
  5310 };
  5312 void CMSParMarkTask::work_on_young_gen_roots(uint worker_id, OopsInGenClosure* cl) {
  5313   DefNewGeneration* dng = _collector->_young_gen->as_DefNewGeneration();
  5314   EdenSpace* eden_space = dng->eden();
  5315   ContiguousSpace* from_space = dng->from();
  5316   ContiguousSpace* to_space   = dng->to();
  5318   HeapWord** eca = _collector->_eden_chunk_array;
  5319   size_t     ect = _collector->_eden_chunk_index;
  5320   HeapWord** sca = _collector->_survivor_chunk_array;
  5321   size_t     sct = _collector->_survivor_chunk_index;
  5323   assert(ect <= _collector->_eden_chunk_capacity, "out of bounds");
  5324   assert(sct <= _collector->_survivor_chunk_capacity, "out of bounds");
  5326   do_young_space_rescan(worker_id, cl, to_space, NULL, 0);
  5327   do_young_space_rescan(worker_id, cl, from_space, sca, sct);
  5328   do_young_space_rescan(worker_id, cl, eden_space, eca, ect);
  5331 // work_queue(i) is passed to the closure
  5332 // Par_MarkRefsIntoAndScanClosure.  The "i" parameter
  5333 // also is passed to do_dirty_card_rescan_tasks() and to
  5334 // do_work_steal() to select the i-th task_queue.
  5336 void CMSParRemarkTask::work(uint worker_id) {
  5337   elapsedTimer _timer;
  5338   ResourceMark rm;
  5339   HandleMark   hm;
  5341   // ---------- rescan from roots --------------
  5342   _timer.start();
  5343   GenCollectedHeap* gch = GenCollectedHeap::heap();
  5344   Par_MarkRefsIntoAndScanClosure par_mrias_cl(_collector,
  5345     _collector->_span, _collector->ref_processor(),
  5346     &(_collector->_markBitMap),
  5347     work_queue(worker_id));
  5349   // Rescan young gen roots first since these are likely
  5350   // coarsely partitioned and may, on that account, constitute
  5351   // the critical path; thus, it's best to start off that
  5352   // work first.
  5353   // ---------- young gen roots --------------
  5355     work_on_young_gen_roots(worker_id, &par_mrias_cl);
  5356     _timer.stop();
  5357     if (PrintCMSStatistics != 0) {
  5358       gclog_or_tty->print_cr(
  5359         "Finished young gen rescan work in %dth thread: %3.3f sec",
  5360         worker_id, _timer.seconds());
  5364   // ---------- remaining roots --------------
  5365   _timer.reset();
  5366   _timer.start();
  5367   gch->gen_process_strong_roots(_collector->_cmsGen->level(),
  5368                                 false,     // yg was scanned above
  5369                                 false,     // this is parallel code
  5370                                 SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()),
  5371                                 &par_mrias_cl,
  5372                                 NULL,
  5373                                 NULL);     // The dirty klasses will be handled below
  5374   assert(_collector->should_unload_classes()
  5375          || (_collector->CMSCollector::roots_scanning_options() & SharedHeap::SO_AllCodeCache),
  5376          "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops");
  5377   _timer.stop();
  5378   if (PrintCMSStatistics != 0) {
  5379     gclog_or_tty->print_cr(
  5380       "Finished remaining root rescan work in %dth thread: %3.3f sec",
  5381       worker_id, _timer.seconds());
  5384   // ---------- unhandled CLD scanning ----------
  5385   if (worker_id == 0) { // Single threaded at the moment.
  5386     _timer.reset();
  5387     _timer.start();
  5389     // Scan all new class loader data objects and new dependencies that were
  5390     // introduced during concurrent marking.
  5391     ResourceMark rm;
  5392     GrowableArray<ClassLoaderData*>* array = ClassLoaderDataGraph::new_clds();
  5393     for (int i = 0; i < array->length(); i++) {
  5394       par_mrias_cl.do_class_loader_data(array->at(i));
  5397     // We don't need to keep track of new CLDs anymore.
  5398     ClassLoaderDataGraph::remember_new_clds(false);
  5400     _timer.stop();
  5401     if (PrintCMSStatistics != 0) {
  5402       gclog_or_tty->print_cr(
  5403           "Finished unhandled CLD scanning work in %dth thread: %3.3f sec",
  5404           worker_id, _timer.seconds());
  5408   // ---------- dirty klass scanning ----------
  5409   if (worker_id == 0) { // Single threaded at the moment.
  5410     _timer.reset();
  5411     _timer.start();
  5413     // Scan all classes that was dirtied during the concurrent marking phase.
  5414     RemarkKlassClosure remark_klass_closure(&par_mrias_cl);
  5415     ClassLoaderDataGraph::classes_do(&remark_klass_closure);
  5417     _timer.stop();
  5418     if (PrintCMSStatistics != 0) {
  5419       gclog_or_tty->print_cr(
  5420           "Finished dirty klass scanning work in %dth thread: %3.3f sec",
  5421           worker_id, _timer.seconds());
  5425   // We might have added oops to ClassLoaderData::_handles during the
  5426   // concurrent marking phase. These oops point to newly allocated objects
  5427   // that are guaranteed to be kept alive. Either by the direct allocation
  5428   // code, or when the young collector processes the strong roots. Hence,
  5429   // we don't have to revisit the _handles block during the remark phase.
  5431   // ---------- rescan dirty cards ------------
  5432   _timer.reset();
  5433   _timer.start();
  5435   // Do the rescan tasks for each of the two spaces
  5436   // (cms_space) in turn.
  5437   // "worker_id" is passed to select the task_queue for "worker_id"
  5438   do_dirty_card_rescan_tasks(_cms_space, worker_id, &par_mrias_cl);
  5439   _timer.stop();
  5440   if (PrintCMSStatistics != 0) {
  5441     gclog_or_tty->print_cr(
  5442       "Finished dirty card rescan work in %dth thread: %3.3f sec",
  5443       worker_id, _timer.seconds());
  5446   // ---------- steal work from other threads ...
  5447   // ---------- ... and drain overflow list.
  5448   _timer.reset();
  5449   _timer.start();
  5450   do_work_steal(worker_id, &par_mrias_cl, _collector->hash_seed(worker_id));
  5451   _timer.stop();
  5452   if (PrintCMSStatistics != 0) {
  5453     gclog_or_tty->print_cr(
  5454       "Finished work stealing in %dth thread: %3.3f sec",
  5455       worker_id, _timer.seconds());
  5459 // Note that parameter "i" is not used.
  5460 void
  5461 CMSParMarkTask::do_young_space_rescan(uint worker_id,
  5462   OopsInGenClosure* cl, ContiguousSpace* space,
  5463   HeapWord** chunk_array, size_t chunk_top) {
  5464   // Until all tasks completed:
  5465   // . claim an unclaimed task
  5466   // . compute region boundaries corresponding to task claimed
  5467   //   using chunk_array
  5468   // . par_oop_iterate(cl) over that region
  5470   ResourceMark rm;
  5471   HandleMark   hm;
  5473   SequentialSubTasksDone* pst = space->par_seq_tasks();
  5475   uint nth_task = 0;
  5476   uint n_tasks  = pst->n_tasks();
  5478   if (n_tasks > 0) {
  5479     assert(pst->valid(), "Uninitialized use?");
  5480     HeapWord *start, *end;
  5481     while (!pst->is_task_claimed(/* reference */ nth_task)) {
  5482       // We claimed task # nth_task; compute its boundaries.
  5483       if (chunk_top == 0) {  // no samples were taken
  5484         assert(nth_task == 0 && n_tasks == 1, "Can have only 1 EdenSpace task");
  5485         start = space->bottom();
  5486         end   = space->top();
  5487       } else if (nth_task == 0) {
  5488         start = space->bottom();
  5489         end   = chunk_array[nth_task];
  5490       } else if (nth_task < (uint)chunk_top) {
  5491         assert(nth_task >= 1, "Control point invariant");
  5492         start = chunk_array[nth_task - 1];
  5493         end   = chunk_array[nth_task];
  5494       } else {
  5495         assert(nth_task == (uint)chunk_top, "Control point invariant");
  5496         start = chunk_array[chunk_top - 1];
  5497         end   = space->top();
  5499       MemRegion mr(start, end);
  5500       // Verify that mr is in space
  5501       assert(mr.is_empty() || space->used_region().contains(mr),
  5502              "Should be in space");
  5503       // Verify that "start" is an object boundary
  5504       assert(mr.is_empty() || oop(mr.start())->is_oop(),
  5505              "Should be an oop");
  5506       space->par_oop_iterate(mr, cl);
  5508     pst->all_tasks_completed();
  5512 void
  5513 CMSParRemarkTask::do_dirty_card_rescan_tasks(
  5514   CompactibleFreeListSpace* sp, int i,
  5515   Par_MarkRefsIntoAndScanClosure* cl) {
  5516   // Until all tasks completed:
  5517   // . claim an unclaimed task
  5518   // . compute region boundaries corresponding to task claimed
  5519   // . transfer dirty bits ct->mut for that region
  5520   // . apply rescanclosure to dirty mut bits for that region
  5522   ResourceMark rm;
  5523   HandleMark   hm;
  5525   OopTaskQueue* work_q = work_queue(i);
  5526   ModUnionClosure modUnionClosure(&(_collector->_modUnionTable));
  5527   // CAUTION! CAUTION! CAUTION! CAUTION! CAUTION! CAUTION! CAUTION!
  5528   // CAUTION: This closure has state that persists across calls to
  5529   // the work method dirty_range_iterate_clear() in that it has
  5530   // imbedded in it a (subtype of) UpwardsObjectClosure. The
  5531   // use of that state in the imbedded UpwardsObjectClosure instance
  5532   // assumes that the cards are always iterated (even if in parallel
  5533   // by several threads) in monotonically increasing order per each
  5534   // thread. This is true of the implementation below which picks
  5535   // card ranges (chunks) in monotonically increasing order globally
  5536   // and, a-fortiori, in monotonically increasing order per thread
  5537   // (the latter order being a subsequence of the former).
  5538   // If the work code below is ever reorganized into a more chaotic
  5539   // work-partitioning form than the current "sequential tasks"
  5540   // paradigm, the use of that persistent state will have to be
  5541   // revisited and modified appropriately. See also related
  5542   // bug 4756801 work on which should examine this code to make
  5543   // sure that the changes there do not run counter to the
  5544   // assumptions made here and necessary for correctness and
  5545   // efficiency. Note also that this code might yield inefficient
  5546   // behaviour in the case of very large objects that span one or
  5547   // more work chunks. Such objects would potentially be scanned
  5548   // several times redundantly. Work on 4756801 should try and
  5549   // address that performance anomaly if at all possible. XXX
  5550   MemRegion  full_span  = _collector->_span;
  5551   CMSBitMap* bm    = &(_collector->_markBitMap);     // shared
  5552   MarkFromDirtyCardsClosure
  5553     greyRescanClosure(_collector, full_span, // entire span of interest
  5554                       sp, bm, work_q, cl);
  5556   SequentialSubTasksDone* pst = sp->conc_par_seq_tasks();
  5557   assert(pst->valid(), "Uninitialized use?");
  5558   uint nth_task = 0;
  5559   const int alignment = CardTableModRefBS::card_size * BitsPerWord;
  5560   MemRegion span = sp->used_region();
  5561   HeapWord* start_addr = span.start();
  5562   HeapWord* end_addr = (HeapWord*)round_to((intptr_t)span.end(),
  5563                                            alignment);
  5564   const size_t chunk_size = sp->rescan_task_size(); // in HeapWord units
  5565   assert((HeapWord*)round_to((intptr_t)start_addr, alignment) ==
  5566          start_addr, "Check alignment");
  5567   assert((size_t)round_to((intptr_t)chunk_size, alignment) ==
  5568          chunk_size, "Check alignment");
  5570   while (!pst->is_task_claimed(/* reference */ nth_task)) {
  5571     // Having claimed the nth_task, compute corresponding mem-region,
  5572     // which is a-fortiori aligned correctly (i.e. at a MUT bopundary).
  5573     // The alignment restriction ensures that we do not need any
  5574     // synchronization with other gang-workers while setting or
  5575     // clearing bits in thus chunk of the MUT.
  5576     MemRegion this_span = MemRegion(start_addr + nth_task*chunk_size,
  5577                                     start_addr + (nth_task+1)*chunk_size);
  5578     // The last chunk's end might be way beyond end of the
  5579     // used region. In that case pull back appropriately.
  5580     if (this_span.end() > end_addr) {
  5581       this_span.set_end(end_addr);
  5582       assert(!this_span.is_empty(), "Program logic (calculation of n_tasks)");
  5584     // Iterate over the dirty cards covering this chunk, marking them
  5585     // precleaned, and setting the corresponding bits in the mod union
  5586     // table. Since we have been careful to partition at Card and MUT-word
  5587     // boundaries no synchronization is needed between parallel threads.
  5588     _collector->_ct->ct_bs()->dirty_card_iterate(this_span,
  5589                                                  &modUnionClosure);
  5591     // Having transferred these marks into the modUnionTable,
  5592     // rescan the marked objects on the dirty cards in the modUnionTable.
  5593     // Even if this is at a synchronous collection, the initial marking
  5594     // may have been done during an asynchronous collection so there
  5595     // may be dirty bits in the mod-union table.
  5596     _collector->_modUnionTable.dirty_range_iterate_clear(
  5597                   this_span, &greyRescanClosure);
  5598     _collector->_modUnionTable.verifyNoOneBitsInRange(
  5599                                  this_span.start(),
  5600                                  this_span.end());
  5602   pst->all_tasks_completed();  // declare that i am done
  5605 // . see if we can share work_queues with ParNew? XXX
  5606 void
  5607 CMSParRemarkTask::do_work_steal(int i, Par_MarkRefsIntoAndScanClosure* cl,
  5608                                 int* seed) {
  5609   OopTaskQueue* work_q = work_queue(i);
  5610   NOT_PRODUCT(int num_steals = 0;)
  5611   oop obj_to_scan;
  5612   CMSBitMap* bm = &(_collector->_markBitMap);
  5614   while (true) {
  5615     // Completely finish any left over work from (an) earlier round(s)
  5616     cl->trim_queue(0);
  5617     size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
  5618                                          (size_t)ParGCDesiredObjsFromOverflowList);
  5619     // Now check if there's any work in the overflow list
  5620     // Passing ParallelGCThreads as the third parameter, no_of_gc_threads,
  5621     // only affects the number of attempts made to get work from the
  5622     // overflow list and does not affect the number of workers.  Just
  5623     // pass ParallelGCThreads so this behavior is unchanged.
  5624     if (_collector->par_take_from_overflow_list(num_from_overflow_list,
  5625                                                 work_q,
  5626                                                 ParallelGCThreads)) {
  5627       // found something in global overflow list;
  5628       // not yet ready to go stealing work from others.
  5629       // We'd like to assert(work_q->size() != 0, ...)
  5630       // because we just took work from the overflow list,
  5631       // but of course we can't since all of that could have
  5632       // been already stolen from us.
  5633       // "He giveth and He taketh away."
  5634       continue;
  5636     // Verify that we have no work before we resort to stealing
  5637     assert(work_q->size() == 0, "Have work, shouldn't steal");
  5638     // Try to steal from other queues that have work
  5639     if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) {
  5640       NOT_PRODUCT(num_steals++;)
  5641       assert(obj_to_scan->is_oop(), "Oops, not an oop!");
  5642       assert(bm->isMarked((HeapWord*)obj_to_scan), "Stole an unmarked oop?");
  5643       // Do scanning work
  5644       obj_to_scan->oop_iterate(cl);
  5645       // Loop around, finish this work, and try to steal some more
  5646     } else if (terminator()->offer_termination()) {
  5647         break;  // nirvana from the infinite cycle
  5650   NOT_PRODUCT(
  5651     if (PrintCMSStatistics != 0) {
  5652       gclog_or_tty->print("\n\t(%d: stole %d oops)", i, num_steals);
  5655   assert(work_q->size() == 0 && _collector->overflow_list_is_empty(),
  5656          "Else our work is not yet done");
  5659 // Record object boundaries in _eden_chunk_array by sampling the eden
  5660 // top in the slow-path eden object allocation code path and record
  5661 // the boundaries, if CMSEdenChunksRecordAlways is true. If
  5662 // CMSEdenChunksRecordAlways is false, we use the other asynchronous
  5663 // sampling in sample_eden() that activates during the part of the
  5664 // preclean phase.
  5665 void CMSCollector::sample_eden_chunk() {
  5666   if (CMSEdenChunksRecordAlways && _eden_chunk_array != NULL) {
  5667     if (_eden_chunk_lock->try_lock()) {
  5668       // Record a sample. This is the critical section. The contents
  5669       // of the _eden_chunk_array have to be non-decreasing in the
  5670       // address order.
  5671       _eden_chunk_array[_eden_chunk_index] = *_top_addr;
  5672       assert(_eden_chunk_array[_eden_chunk_index] <= *_end_addr,
  5673              "Unexpected state of Eden");
  5674       if (_eden_chunk_index == 0 ||
  5675           ((_eden_chunk_array[_eden_chunk_index] > _eden_chunk_array[_eden_chunk_index-1]) &&
  5676            (pointer_delta(_eden_chunk_array[_eden_chunk_index],
  5677                           _eden_chunk_array[_eden_chunk_index-1]) >= CMSSamplingGrain))) {
  5678         _eden_chunk_index++;  // commit sample
  5680       _eden_chunk_lock->unlock();
  5685 // Return a thread-local PLAB recording array, as appropriate.
  5686 void* CMSCollector::get_data_recorder(int thr_num) {
  5687   if (_survivor_plab_array != NULL &&
  5688       (CMSPLABRecordAlways ||
  5689        (_collectorState > Marking && _collectorState < FinalMarking))) {
  5690     assert(thr_num < (int)ParallelGCThreads, "thr_num is out of bounds");
  5691     ChunkArray* ca = &_survivor_plab_array[thr_num];
  5692     ca->reset();   // clear it so that fresh data is recorded
  5693     return (void*) ca;
  5694   } else {
  5695     return NULL;
  5699 // Reset all the thread-local PLAB recording arrays
  5700 void CMSCollector::reset_survivor_plab_arrays() {
  5701   for (uint i = 0; i < ParallelGCThreads; i++) {
  5702     _survivor_plab_array[i].reset();
  5706 // Merge the per-thread plab arrays into the global survivor chunk
  5707 // array which will provide the partitioning of the survivor space
  5708 // for CMS initial scan and rescan.
  5709 void CMSCollector::merge_survivor_plab_arrays(ContiguousSpace* surv,
  5710                                               int no_of_gc_threads) {
  5711   assert(_survivor_plab_array  != NULL, "Error");
  5712   assert(_survivor_chunk_array != NULL, "Error");
  5713   assert(_collectorState == FinalMarking ||
  5714          (CMSParallelInitialMarkEnabled && _collectorState == InitialMarking), "Error");
  5715   for (int j = 0; j < no_of_gc_threads; j++) {
  5716     _cursor[j] = 0;
  5718   HeapWord* top = surv->top();
  5719   size_t i;
  5720   for (i = 0; i < _survivor_chunk_capacity; i++) {  // all sca entries
  5721     HeapWord* min_val = top;          // Higher than any PLAB address
  5722     uint      min_tid = 0;            // position of min_val this round
  5723     for (int j = 0; j < no_of_gc_threads; j++) {
  5724       ChunkArray* cur_sca = &_survivor_plab_array[j];
  5725       if (_cursor[j] == cur_sca->end()) {
  5726         continue;
  5728       assert(_cursor[j] < cur_sca->end(), "ctl pt invariant");
  5729       HeapWord* cur_val = cur_sca->nth(_cursor[j]);
  5730       assert(surv->used_region().contains(cur_val), "Out of bounds value");
  5731       if (cur_val < min_val) {
  5732         min_tid = j;
  5733         min_val = cur_val;
  5734       } else {
  5735         assert(cur_val < top, "All recorded addresses should be less");
  5738     // At this point min_val and min_tid are respectively
  5739     // the least address in _survivor_plab_array[j]->nth(_cursor[j])
  5740     // and the thread (j) that witnesses that address.
  5741     // We record this address in the _survivor_chunk_array[i]
  5742     // and increment _cursor[min_tid] prior to the next round i.
  5743     if (min_val == top) {
  5744       break;
  5746     _survivor_chunk_array[i] = min_val;
  5747     _cursor[min_tid]++;
  5749   // We are all done; record the size of the _survivor_chunk_array
  5750   _survivor_chunk_index = i; // exclusive: [0, i)
  5751   if (PrintCMSStatistics > 0) {
  5752     gclog_or_tty->print(" (Survivor:" SIZE_FORMAT "chunks) ", i);
  5754   // Verify that we used up all the recorded entries
  5755   #ifdef ASSERT
  5756     size_t total = 0;
  5757     for (int j = 0; j < no_of_gc_threads; j++) {
  5758       assert(_cursor[j] == _survivor_plab_array[j].end(), "Ctl pt invariant");
  5759       total += _cursor[j];
  5761     assert(total == _survivor_chunk_index, "Ctl Pt Invariant");
  5762     // Check that the merged array is in sorted order
  5763     if (total > 0) {
  5764       for (size_t i = 0; i < total - 1; i++) {
  5765         if (PrintCMSStatistics > 0) {
  5766           gclog_or_tty->print(" (chunk" SIZE_FORMAT ":" INTPTR_FORMAT ") ",
  5767                               i, _survivor_chunk_array[i]);
  5769         assert(_survivor_chunk_array[i] < _survivor_chunk_array[i+1],
  5770                "Not sorted");
  5773   #endif // ASSERT
  5776 // Set up the space's par_seq_tasks structure for work claiming
  5777 // for parallel initial scan and rescan of young gen.
  5778 // See ParRescanTask where this is currently used.
  5779 void
  5780 CMSCollector::
  5781 initialize_sequential_subtasks_for_young_gen_rescan(int n_threads) {
  5782   assert(n_threads > 0, "Unexpected n_threads argument");
  5783   DefNewGeneration* dng = (DefNewGeneration*)_young_gen;
  5785   // Eden space
  5786   if (!dng->eden()->is_empty()) {
  5787     SequentialSubTasksDone* pst = dng->eden()->par_seq_tasks();
  5788     assert(!pst->valid(), "Clobbering existing data?");
  5789     // Each valid entry in [0, _eden_chunk_index) represents a task.
  5790     size_t n_tasks = _eden_chunk_index + 1;
  5791     assert(n_tasks == 1 || _eden_chunk_array != NULL, "Error");
  5792     // Sets the condition for completion of the subtask (how many threads
  5793     // need to finish in order to be done).
  5794     pst->set_n_threads(n_threads);
  5795     pst->set_n_tasks((int)n_tasks);
  5798   // Merge the survivor plab arrays into _survivor_chunk_array
  5799   if (_survivor_plab_array != NULL) {
  5800     merge_survivor_plab_arrays(dng->from(), n_threads);
  5801   } else {
  5802     assert(_survivor_chunk_index == 0, "Error");
  5805   // To space
  5807     SequentialSubTasksDone* pst = dng->to()->par_seq_tasks();
  5808     assert(!pst->valid(), "Clobbering existing data?");
  5809     // Sets the condition for completion of the subtask (how many threads
  5810     // need to finish in order to be done).
  5811     pst->set_n_threads(n_threads);
  5812     pst->set_n_tasks(1);
  5813     assert(pst->valid(), "Error");
  5816   // From space
  5818     SequentialSubTasksDone* pst = dng->from()->par_seq_tasks();
  5819     assert(!pst->valid(), "Clobbering existing data?");
  5820     size_t n_tasks = _survivor_chunk_index + 1;
  5821     assert(n_tasks == 1 || _survivor_chunk_array != NULL, "Error");
  5822     // Sets the condition for completion of the subtask (how many threads
  5823     // need to finish in order to be done).
  5824     pst->set_n_threads(n_threads);
  5825     pst->set_n_tasks((int)n_tasks);
  5826     assert(pst->valid(), "Error");
  5830 // Parallel version of remark
  5831 void CMSCollector::do_remark_parallel() {
  5832   GenCollectedHeap* gch = GenCollectedHeap::heap();
  5833   FlexibleWorkGang* workers = gch->workers();
  5834   assert(workers != NULL, "Need parallel worker threads.");
  5835   // Choose to use the number of GC workers most recently set
  5836   // into "active_workers".  If active_workers is not set, set it
  5837   // to ParallelGCThreads.
  5838   int n_workers = workers->active_workers();
  5839   if (n_workers == 0) {
  5840     assert(n_workers > 0, "Should have been set during scavenge");
  5841     n_workers = ParallelGCThreads;
  5842     workers->set_active_workers(n_workers);
  5844   CompactibleFreeListSpace* cms_space  = _cmsGen->cmsSpace();
  5846   CMSParRemarkTask tsk(this,
  5847     cms_space,
  5848     n_workers, workers, task_queues());
  5850   // Set up for parallel process_strong_roots work.
  5851   gch->set_par_threads(n_workers);
  5852   // We won't be iterating over the cards in the card table updating
  5853   // the younger_gen cards, so we shouldn't call the following else
  5854   // the verification code as well as subsequent younger_refs_iterate
  5855   // code would get confused. XXX
  5856   // gch->rem_set()->prepare_for_younger_refs_iterate(true); // parallel
  5858   // The young gen rescan work will not be done as part of
  5859   // process_strong_roots (which currently doesn't knw how to
  5860   // parallelize such a scan), but rather will be broken up into
  5861   // a set of parallel tasks (via the sampling that the [abortable]
  5862   // preclean phase did of EdenSpace, plus the [two] tasks of
  5863   // scanning the [two] survivor spaces. Further fine-grain
  5864   // parallelization of the scanning of the survivor spaces
  5865   // themselves, and of precleaning of the younger gen itself
  5866   // is deferred to the future.
  5867   initialize_sequential_subtasks_for_young_gen_rescan(n_workers);
  5869   // The dirty card rescan work is broken up into a "sequence"
  5870   // of parallel tasks (per constituent space) that are dynamically
  5871   // claimed by the parallel threads.
  5872   cms_space->initialize_sequential_subtasks_for_rescan(n_workers);
  5874   // It turns out that even when we're using 1 thread, doing the work in a
  5875   // separate thread causes wide variance in run times.  We can't help this
  5876   // in the multi-threaded case, but we special-case n=1 here to get
  5877   // repeatable measurements of the 1-thread overhead of the parallel code.
  5878   if (n_workers > 1) {
  5879     // Make refs discovery MT-safe, if it isn't already: it may not
  5880     // necessarily be so, since it's possible that we are doing
  5881     // ST marking.
  5882     ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), true);
  5883     GenCollectedHeap::StrongRootsScope srs(gch);
  5884     workers->run_task(&tsk);
  5885   } else {
  5886     ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), false);
  5887     GenCollectedHeap::StrongRootsScope srs(gch);
  5888     tsk.work(0);
  5891   gch->set_par_threads(0);  // 0 ==> non-parallel.
  5892   // restore, single-threaded for now, any preserved marks
  5893   // as a result of work_q overflow
  5894   restore_preserved_marks_if_any();
  5897 // Non-parallel version of remark
  5898 void CMSCollector::do_remark_non_parallel() {
  5899   ResourceMark rm;
  5900   HandleMark   hm;
  5901   GenCollectedHeap* gch = GenCollectedHeap::heap();
  5902   ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), false);
  5904   MarkRefsIntoAndScanClosure
  5905     mrias_cl(_span, ref_processor(), &_markBitMap, NULL /* not precleaning */,
  5906              &_markStack, this,
  5907              false /* should_yield */, false /* not precleaning */);
  5908   MarkFromDirtyCardsClosure
  5909     markFromDirtyCardsClosure(this, _span,
  5910                               NULL,  // space is set further below
  5911                               &_markBitMap, &_markStack, &mrias_cl);
  5913     GCTraceTime t("grey object rescan", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
  5914     // Iterate over the dirty cards, setting the corresponding bits in the
  5915     // mod union table.
  5917       ModUnionClosure modUnionClosure(&_modUnionTable);
  5918       _ct->ct_bs()->dirty_card_iterate(
  5919                       _cmsGen->used_region(),
  5920                       &modUnionClosure);
  5922     // Having transferred these marks into the modUnionTable, we just need
  5923     // to rescan the marked objects on the dirty cards in the modUnionTable.
  5924     // The initial marking may have been done during an asynchronous
  5925     // collection so there may be dirty bits in the mod-union table.
  5926     const int alignment =
  5927       CardTableModRefBS::card_size * BitsPerWord;
  5929       // ... First handle dirty cards in CMS gen
  5930       markFromDirtyCardsClosure.set_space(_cmsGen->cmsSpace());
  5931       MemRegion ur = _cmsGen->used_region();
  5932       HeapWord* lb = ur.start();
  5933       HeapWord* ub = (HeapWord*)round_to((intptr_t)ur.end(), alignment);
  5934       MemRegion cms_span(lb, ub);
  5935       _modUnionTable.dirty_range_iterate_clear(cms_span,
  5936                                                &markFromDirtyCardsClosure);
  5937       verify_work_stacks_empty();
  5938       if (PrintCMSStatistics != 0) {
  5939         gclog_or_tty->print(" (re-scanned "SIZE_FORMAT" dirty cards in cms gen) ",
  5940           markFromDirtyCardsClosure.num_dirty_cards());
  5944   if (VerifyDuringGC &&
  5945       GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  5946     HandleMark hm;  // Discard invalid handles created during verification
  5947     Universe::verify();
  5950     GCTraceTime t("root rescan", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
  5952     verify_work_stacks_empty();
  5954     gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
  5955     GenCollectedHeap::StrongRootsScope srs(gch);
  5956     gch->gen_process_strong_roots(_cmsGen->level(),
  5957                                   true,  // younger gens as roots
  5958                                   false, // use the local StrongRootsScope
  5959                                   SharedHeap::ScanningOption(roots_scanning_options()),
  5960                                   &mrias_cl,
  5961                                   NULL,
  5962                                   NULL);  // The dirty klasses will be handled below
  5964     assert(should_unload_classes()
  5965            || (roots_scanning_options() & SharedHeap::SO_AllCodeCache),
  5966            "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops");
  5970     GCTraceTime t("visit unhandled CLDs", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
  5972     verify_work_stacks_empty();
  5974     // Scan all class loader data objects that might have been introduced
  5975     // during concurrent marking.
  5976     ResourceMark rm;
  5977     GrowableArray<ClassLoaderData*>* array = ClassLoaderDataGraph::new_clds();
  5978     for (int i = 0; i < array->length(); i++) {
  5979       mrias_cl.do_class_loader_data(array->at(i));
  5982     // We don't need to keep track of new CLDs anymore.
  5983     ClassLoaderDataGraph::remember_new_clds(false);
  5985     verify_work_stacks_empty();
  5989     GCTraceTime t("dirty klass scan", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
  5991     verify_work_stacks_empty();
  5993     RemarkKlassClosure remark_klass_closure(&mrias_cl);
  5994     ClassLoaderDataGraph::classes_do(&remark_klass_closure);
  5996     verify_work_stacks_empty();
  5999   // We might have added oops to ClassLoaderData::_handles during the
  6000   // concurrent marking phase. These oops point to newly allocated objects
  6001   // that are guaranteed to be kept alive. Either by the direct allocation
  6002   // code, or when the young collector processes the strong roots. Hence,
  6003   // we don't have to revisit the _handles block during the remark phase.
  6005   verify_work_stacks_empty();
  6006   // Restore evacuated mark words, if any, used for overflow list links
  6007   if (!CMSOverflowEarlyRestoration) {
  6008     restore_preserved_marks_if_any();
  6010   verify_overflow_empty();
  6013 ////////////////////////////////////////////////////////
  6014 // Parallel Reference Processing Task Proxy Class
  6015 ////////////////////////////////////////////////////////
  6016 class CMSRefProcTaskProxy: public AbstractGangTaskWOopQueues {
  6017   typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
  6018   CMSCollector*          _collector;
  6019   CMSBitMap*             _mark_bit_map;
  6020   const MemRegion        _span;
  6021   ProcessTask&           _task;
  6023 public:
  6024   CMSRefProcTaskProxy(ProcessTask&     task,
  6025                       CMSCollector*    collector,
  6026                       const MemRegion& span,
  6027                       CMSBitMap*       mark_bit_map,
  6028                       AbstractWorkGang* workers,
  6029                       OopTaskQueueSet* task_queues):
  6030     // XXX Should superclass AGTWOQ also know about AWG since it knows
  6031     // about the task_queues used by the AWG? Then it could initialize
  6032     // the terminator() object. See 6984287. The set_for_termination()
  6033     // below is a temporary band-aid for the regression in 6984287.
  6034     AbstractGangTaskWOopQueues("Process referents by policy in parallel",
  6035       task_queues),
  6036     _task(task),
  6037     _collector(collector), _span(span), _mark_bit_map(mark_bit_map)
  6039     assert(_collector->_span.equals(_span) && !_span.is_empty(),
  6040            "Inconsistency in _span");
  6041     set_for_termination(workers->active_workers());
  6044   OopTaskQueueSet* task_queues() { return queues(); }
  6046   OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); }
  6048   void do_work_steal(int i,
  6049                      CMSParDrainMarkingStackClosure* drain,
  6050                      CMSParKeepAliveClosure* keep_alive,
  6051                      int* seed);
  6053   virtual void work(uint worker_id);
  6054 };
  6056 void CMSRefProcTaskProxy::work(uint worker_id) {
  6057   assert(_collector->_span.equals(_span), "Inconsistency in _span");
  6058   CMSParKeepAliveClosure par_keep_alive(_collector, _span,
  6059                                         _mark_bit_map,
  6060                                         work_queue(worker_id));
  6061   CMSParDrainMarkingStackClosure par_drain_stack(_collector, _span,
  6062                                                  _mark_bit_map,
  6063                                                  work_queue(worker_id));
  6064   CMSIsAliveClosure is_alive_closure(_span, _mark_bit_map);
  6065   _task.work(worker_id, is_alive_closure, par_keep_alive, par_drain_stack);
  6066   if (_task.marks_oops_alive()) {
  6067     do_work_steal(worker_id, &par_drain_stack, &par_keep_alive,
  6068                   _collector->hash_seed(worker_id));
  6070   assert(work_queue(worker_id)->size() == 0, "work_queue should be empty");
  6071   assert(_collector->_overflow_list == NULL, "non-empty _overflow_list");
  6074 class CMSRefEnqueueTaskProxy: public AbstractGangTask {
  6075   typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
  6076   EnqueueTask& _task;
  6078 public:
  6079   CMSRefEnqueueTaskProxy(EnqueueTask& task)
  6080     : AbstractGangTask("Enqueue reference objects in parallel"),
  6081       _task(task)
  6082   { }
  6084   virtual void work(uint worker_id)
  6086     _task.work(worker_id);
  6088 };
  6090 CMSParKeepAliveClosure::CMSParKeepAliveClosure(CMSCollector* collector,
  6091   MemRegion span, CMSBitMap* bit_map, OopTaskQueue* work_queue):
  6092    _span(span),
  6093    _bit_map(bit_map),
  6094    _work_queue(work_queue),
  6095    _mark_and_push(collector, span, bit_map, work_queue),
  6096    _low_water_mark(MIN2((uint)(work_queue->max_elems()/4),
  6097                         (uint)(CMSWorkQueueDrainThreshold * ParallelGCThreads)))
  6098 { }
  6100 // . see if we can share work_queues with ParNew? XXX
  6101 void CMSRefProcTaskProxy::do_work_steal(int i,
  6102   CMSParDrainMarkingStackClosure* drain,
  6103   CMSParKeepAliveClosure* keep_alive,
  6104   int* seed) {
  6105   OopTaskQueue* work_q = work_queue(i);
  6106   NOT_PRODUCT(int num_steals = 0;)
  6107   oop obj_to_scan;
  6109   while (true) {
  6110     // Completely finish any left over work from (an) earlier round(s)
  6111     drain->trim_queue(0);
  6112     size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
  6113                                          (size_t)ParGCDesiredObjsFromOverflowList);
  6114     // Now check if there's any work in the overflow list
  6115     // Passing ParallelGCThreads as the third parameter, no_of_gc_threads,
  6116     // only affects the number of attempts made to get work from the
  6117     // overflow list and does not affect the number of workers.  Just
  6118     // pass ParallelGCThreads so this behavior is unchanged.
  6119     if (_collector->par_take_from_overflow_list(num_from_overflow_list,
  6120                                                 work_q,
  6121                                                 ParallelGCThreads)) {
  6122       // Found something in global overflow list;
  6123       // not yet ready to go stealing work from others.
  6124       // We'd like to assert(work_q->size() != 0, ...)
  6125       // because we just took work from the overflow list,
  6126       // but of course we can't, since all of that might have
  6127       // been already stolen from us.
  6128       continue;
  6130     // Verify that we have no work before we resort to stealing
  6131     assert(work_q->size() == 0, "Have work, shouldn't steal");
  6132     // Try to steal from other queues that have work
  6133     if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) {
  6134       NOT_PRODUCT(num_steals++;)
  6135       assert(obj_to_scan->is_oop(), "Oops, not an oop!");
  6136       assert(_mark_bit_map->isMarked((HeapWord*)obj_to_scan), "Stole an unmarked oop?");
  6137       // Do scanning work
  6138       obj_to_scan->oop_iterate(keep_alive);
  6139       // Loop around, finish this work, and try to steal some more
  6140     } else if (terminator()->offer_termination()) {
  6141       break;  // nirvana from the infinite cycle
  6144   NOT_PRODUCT(
  6145     if (PrintCMSStatistics != 0) {
  6146       gclog_or_tty->print("\n\t(%d: stole %d oops)", i, num_steals);
  6151 void CMSRefProcTaskExecutor::execute(ProcessTask& task)
  6153   GenCollectedHeap* gch = GenCollectedHeap::heap();
  6154   FlexibleWorkGang* workers = gch->workers();
  6155   assert(workers != NULL, "Need parallel worker threads.");
  6156   CMSRefProcTaskProxy rp_task(task, &_collector,
  6157                               _collector.ref_processor()->span(),
  6158                               _collector.markBitMap(),
  6159                               workers, _collector.task_queues());
  6160   workers->run_task(&rp_task);
  6163 void CMSRefProcTaskExecutor::execute(EnqueueTask& task)
  6166   GenCollectedHeap* gch = GenCollectedHeap::heap();
  6167   FlexibleWorkGang* workers = gch->workers();
  6168   assert(workers != NULL, "Need parallel worker threads.");
  6169   CMSRefEnqueueTaskProxy enq_task(task);
  6170   workers->run_task(&enq_task);
  6173 void CMSCollector::refProcessingWork(bool asynch, bool clear_all_soft_refs) {
  6175   ResourceMark rm;
  6176   HandleMark   hm;
  6178   ReferenceProcessor* rp = ref_processor();
  6179   assert(rp->span().equals(_span), "Spans should be equal");
  6180   assert(!rp->enqueuing_is_done(), "Enqueuing should not be complete");
  6181   // Process weak references.
  6182   rp->setup_policy(clear_all_soft_refs);
  6183   verify_work_stacks_empty();
  6185   CMSKeepAliveClosure cmsKeepAliveClosure(this, _span, &_markBitMap,
  6186                                           &_markStack, false /* !preclean */);
  6187   CMSDrainMarkingStackClosure cmsDrainMarkingStackClosure(this,
  6188                                 _span, &_markBitMap, &_markStack,
  6189                                 &cmsKeepAliveClosure, false /* !preclean */);
  6191     GCTraceTime t("weak refs processing", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
  6193     ReferenceProcessorStats stats;
  6194     if (rp->processing_is_mt()) {
  6195       // Set the degree of MT here.  If the discovery is done MT, there
  6196       // may have been a different number of threads doing the discovery
  6197       // and a different number of discovered lists may have Ref objects.
  6198       // That is OK as long as the Reference lists are balanced (see
  6199       // balance_all_queues() and balance_queues()).
  6200       GenCollectedHeap* gch = GenCollectedHeap::heap();
  6201       int active_workers = ParallelGCThreads;
  6202       FlexibleWorkGang* workers = gch->workers();
  6203       if (workers != NULL) {
  6204         active_workers = workers->active_workers();
  6205         // The expectation is that active_workers will have already
  6206         // been set to a reasonable value.  If it has not been set,
  6207         // investigate.
  6208         assert(active_workers > 0, "Should have been set during scavenge");
  6210       rp->set_active_mt_degree(active_workers);
  6211       CMSRefProcTaskExecutor task_executor(*this);
  6212       stats = rp->process_discovered_references(&_is_alive_closure,
  6213                                         &cmsKeepAliveClosure,
  6214                                         &cmsDrainMarkingStackClosure,
  6215                                         &task_executor,
  6216                                         _gc_timer_cm,
  6217                                         _gc_tracer_cm->gc_id());
  6218     } else {
  6219       stats = rp->process_discovered_references(&_is_alive_closure,
  6220                                         &cmsKeepAliveClosure,
  6221                                         &cmsDrainMarkingStackClosure,
  6222                                         NULL,
  6223                                         _gc_timer_cm,
  6224                                         _gc_tracer_cm->gc_id());
  6226     _gc_tracer_cm->report_gc_reference_stats(stats);
  6230   // This is the point where the entire marking should have completed.
  6231   verify_work_stacks_empty();
  6233   if (should_unload_classes()) {
  6235       GCTraceTime t("class unloading", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
  6237       // Unload classes and purge the SystemDictionary.
  6238       bool purged_class = SystemDictionary::do_unloading(&_is_alive_closure);
  6240       // Unload nmethods.
  6241       CodeCache::do_unloading(&_is_alive_closure, purged_class);
  6243       // Prune dead klasses from subklass/sibling/implementor lists.
  6244       Klass::clean_weak_klass_links(&_is_alive_closure);
  6248       GCTraceTime t("scrub symbol table", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
  6249       // Clean up unreferenced symbols in symbol table.
  6250       SymbolTable::unlink();
  6254   // CMS doesn't use the StringTable as hard roots when class unloading is turned off.
  6255   // Need to check if we really scanned the StringTable.
  6256   if ((roots_scanning_options() & SharedHeap::SO_Strings) == 0) {
  6257     GCTraceTime t("scrub string table", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id());
  6258     // Delete entries for dead interned strings.
  6259     StringTable::unlink(&_is_alive_closure);
  6262   // Restore any preserved marks as a result of mark stack or
  6263   // work queue overflow
  6264   restore_preserved_marks_if_any();  // done single-threaded for now
  6266   rp->set_enqueuing_is_done(true);
  6267   if (rp->processing_is_mt()) {
  6268     rp->balance_all_queues();
  6269     CMSRefProcTaskExecutor task_executor(*this);
  6270     rp->enqueue_discovered_references(&task_executor);
  6271   } else {
  6272     rp->enqueue_discovered_references(NULL);
  6274   rp->verify_no_references_recorded();
  6275   assert(!rp->discovery_enabled(), "should have been disabled");
  6278 #ifndef PRODUCT
  6279 void CMSCollector::check_correct_thread_executing() {
  6280   Thread* t = Thread::current();
  6281   // Only the VM thread or the CMS thread should be here.
  6282   assert(t->is_ConcurrentGC_thread() || t->is_VM_thread(),
  6283          "Unexpected thread type");
  6284   // If this is the vm thread, the foreground process
  6285   // should not be waiting.  Note that _foregroundGCIsActive is
  6286   // true while the foreground collector is waiting.
  6287   if (_foregroundGCShouldWait) {
  6288     // We cannot be the VM thread
  6289     assert(t->is_ConcurrentGC_thread(),
  6290            "Should be CMS thread");
  6291   } else {
  6292     // We can be the CMS thread only if we are in a stop-world
  6293     // phase of CMS collection.
  6294     if (t->is_ConcurrentGC_thread()) {
  6295       assert(_collectorState == InitialMarking ||
  6296              _collectorState == FinalMarking,
  6297              "Should be a stop-world phase");
  6298       // The CMS thread should be holding the CMS_token.
  6299       assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  6300              "Potential interference with concurrently "
  6301              "executing VM thread");
  6305 #endif
  6307 void CMSCollector::sweep(bool asynch) {
  6308   assert(_collectorState == Sweeping, "just checking");
  6309   check_correct_thread_executing();
  6310   verify_work_stacks_empty();
  6311   verify_overflow_empty();
  6312   increment_sweep_count();
  6313   TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause());
  6315   _inter_sweep_timer.stop();
  6316   _inter_sweep_estimate.sample(_inter_sweep_timer.seconds());
  6317   size_policy()->avg_cms_free_at_sweep()->sample(_cmsGen->free());
  6319   assert(!_intra_sweep_timer.is_active(), "Should not be active");
  6320   _intra_sweep_timer.reset();
  6321   _intra_sweep_timer.start();
  6322   if (asynch) {
  6323     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  6324     CMSPhaseAccounting pa(this, "sweep", _gc_tracer_cm->gc_id(), !PrintGCDetails);
  6325     // First sweep the old gen
  6327       CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock(),
  6328                                bitMapLock());
  6329       sweepWork(_cmsGen, asynch);
  6332     // Update Universe::_heap_*_at_gc figures.
  6333     // We need all the free list locks to make the abstract state
  6334     // transition from Sweeping to Resetting. See detailed note
  6335     // further below.
  6337       CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock());
  6338       // Update heap occupancy information which is used as
  6339       // input to soft ref clearing policy at the next gc.
  6340       Universe::update_heap_info_at_gc();
  6341       _collectorState = Resizing;
  6343   } else {
  6344     // already have needed locks
  6345     sweepWork(_cmsGen,  asynch);
  6346     // Update heap occupancy information which is used as
  6347     // input to soft ref clearing policy at the next gc.
  6348     Universe::update_heap_info_at_gc();
  6349     _collectorState = Resizing;
  6351   verify_work_stacks_empty();
  6352   verify_overflow_empty();
  6354   if (should_unload_classes()) {
  6355     // Delay purge to the beginning of the next safepoint.  Metaspace::contains
  6356     // requires that the virtual spaces are stable and not deleted.
  6357     ClassLoaderDataGraph::set_should_purge(true);
  6360   _intra_sweep_timer.stop();
  6361   _intra_sweep_estimate.sample(_intra_sweep_timer.seconds());
  6363   _inter_sweep_timer.reset();
  6364   _inter_sweep_timer.start();
  6366   // We need to use a monotonically non-deccreasing time in ms
  6367   // or we will see time-warp warnings and os::javaTimeMillis()
  6368   // does not guarantee monotonicity.
  6369   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
  6370   update_time_of_last_gc(now);
  6372   // NOTE on abstract state transitions:
  6373   // Mutators allocate-live and/or mark the mod-union table dirty
  6374   // based on the state of the collection.  The former is done in
  6375   // the interval [Marking, Sweeping] and the latter in the interval
  6376   // [Marking, Sweeping).  Thus the transitions into the Marking state
  6377   // and out of the Sweeping state must be synchronously visible
  6378   // globally to the mutators.
  6379   // The transition into the Marking state happens with the world
  6380   // stopped so the mutators will globally see it.  Sweeping is
  6381   // done asynchronously by the background collector so the transition
  6382   // from the Sweeping state to the Resizing state must be done
  6383   // under the freelistLock (as is the check for whether to
  6384   // allocate-live and whether to dirty the mod-union table).
  6385   assert(_collectorState == Resizing, "Change of collector state to"
  6386     " Resizing must be done under the freelistLocks (plural)");
  6388   // Now that sweeping has been completed, we clear
  6389   // the incremental_collection_failed flag,
  6390   // thus inviting a younger gen collection to promote into
  6391   // this generation. If such a promotion may still fail,
  6392   // the flag will be set again when a young collection is
  6393   // attempted.
  6394   GenCollectedHeap* gch = GenCollectedHeap::heap();
  6395   gch->clear_incremental_collection_failed();  // Worth retrying as fresh space may have been freed up
  6396   gch->update_full_collections_completed(_collection_count_start);
  6399 // FIX ME!!! Looks like this belongs in CFLSpace, with
  6400 // CMSGen merely delegating to it.
  6401 void ConcurrentMarkSweepGeneration::setNearLargestChunk() {
  6402   double nearLargestPercent = FLSLargestBlockCoalesceProximity;
  6403   HeapWord*  minAddr        = _cmsSpace->bottom();
  6404   HeapWord*  largestAddr    =
  6405     (HeapWord*) _cmsSpace->dictionary()->find_largest_dict();
  6406   if (largestAddr == NULL) {
  6407     // The dictionary appears to be empty.  In this case
  6408     // try to coalesce at the end of the heap.
  6409     largestAddr = _cmsSpace->end();
  6411   size_t largestOffset     = pointer_delta(largestAddr, minAddr);
  6412   size_t nearLargestOffset =
  6413     (size_t)((double)largestOffset * nearLargestPercent) - MinChunkSize;
  6414   if (PrintFLSStatistics != 0) {
  6415     gclog_or_tty->print_cr(
  6416       "CMS: Large Block: " PTR_FORMAT ";"
  6417       " Proximity: " PTR_FORMAT " -> " PTR_FORMAT,
  6418       largestAddr,
  6419       _cmsSpace->nearLargestChunk(), minAddr + nearLargestOffset);
  6421   _cmsSpace->set_nearLargestChunk(minAddr + nearLargestOffset);
  6424 bool ConcurrentMarkSweepGeneration::isNearLargestChunk(HeapWord* addr) {
  6425   return addr >= _cmsSpace->nearLargestChunk();
  6428 FreeChunk* ConcurrentMarkSweepGeneration::find_chunk_at_end() {
  6429   return _cmsSpace->find_chunk_at_end();
  6432 void ConcurrentMarkSweepGeneration::update_gc_stats(int current_level,
  6433                                                     bool full) {
  6434   // The next lower level has been collected.  Gather any statistics
  6435   // that are of interest at this point.
  6436   if (!full && (current_level + 1) == level()) {
  6437     // Gather statistics on the young generation collection.
  6438     collector()->stats().record_gc0_end(used());
  6442 CMSAdaptiveSizePolicy* ConcurrentMarkSweepGeneration::size_policy() {
  6443   GenCollectedHeap* gch = GenCollectedHeap::heap();
  6444   assert(gch->kind() == CollectedHeap::GenCollectedHeap,
  6445     "Wrong type of heap");
  6446   CMSAdaptiveSizePolicy* sp = (CMSAdaptiveSizePolicy*)
  6447     gch->gen_policy()->size_policy();
  6448   assert(sp->is_gc_cms_adaptive_size_policy(),
  6449     "Wrong type of size policy");
  6450   return sp;
  6453 void ConcurrentMarkSweepGeneration::rotate_debug_collection_type() {
  6454   if (PrintGCDetails && Verbose) {
  6455     gclog_or_tty->print("Rotate from %d ", _debug_collection_type);
  6457   _debug_collection_type = (CollectionTypes) (_debug_collection_type + 1);
  6458   _debug_collection_type =
  6459     (CollectionTypes) (_debug_collection_type % Unknown_collection_type);
  6460   if (PrintGCDetails && Verbose) {
  6461     gclog_or_tty->print_cr("to %d ", _debug_collection_type);
  6465 void CMSCollector::sweepWork(ConcurrentMarkSweepGeneration* gen,
  6466   bool asynch) {
  6467   // We iterate over the space(s) underlying this generation,
  6468   // checking the mark bit map to see if the bits corresponding
  6469   // to specific blocks are marked or not. Blocks that are
  6470   // marked are live and are not swept up. All remaining blocks
  6471   // are swept up, with coalescing on-the-fly as we sweep up
  6472   // contiguous free and/or garbage blocks:
  6473   // We need to ensure that the sweeper synchronizes with allocators
  6474   // and stop-the-world collectors. In particular, the following
  6475   // locks are used:
  6476   // . CMS token: if this is held, a stop the world collection cannot occur
  6477   // . freelistLock: if this is held no allocation can occur from this
  6478   //                 generation by another thread
  6479   // . bitMapLock: if this is held, no other thread can access or update
  6480   //
  6482   // Note that we need to hold the freelistLock if we use
  6483   // block iterate below; else the iterator might go awry if
  6484   // a mutator (or promotion) causes block contents to change
  6485   // (for instance if the allocator divvies up a block).
  6486   // If we hold the free list lock, for all practical purposes
  6487   // young generation GC's can't occur (they'll usually need to
  6488   // promote), so we might as well prevent all young generation
  6489   // GC's while we do a sweeping step. For the same reason, we might
  6490   // as well take the bit map lock for the entire duration
  6492   // check that we hold the requisite locks
  6493   assert(have_cms_token(), "Should hold cms token");
  6494   assert(   (asynch && ConcurrentMarkSweepThread::cms_thread_has_cms_token())
  6495          || (!asynch && ConcurrentMarkSweepThread::vm_thread_has_cms_token()),
  6496         "Should possess CMS token to sweep");
  6497   assert_lock_strong(gen->freelistLock());
  6498   assert_lock_strong(bitMapLock());
  6500   assert(!_inter_sweep_timer.is_active(), "Was switched off in an outer context");
  6501   assert(_intra_sweep_timer.is_active(),  "Was switched on  in an outer context");
  6502   gen->cmsSpace()->beginSweepFLCensus((float)(_inter_sweep_timer.seconds()),
  6503                                       _inter_sweep_estimate.padded_average(),
  6504                                       _intra_sweep_estimate.padded_average());
  6505   gen->setNearLargestChunk();
  6508     SweepClosure sweepClosure(this, gen, &_markBitMap,
  6509                             CMSYield && asynch);
  6510     gen->cmsSpace()->blk_iterate_careful(&sweepClosure);
  6511     // We need to free-up/coalesce garbage/blocks from a
  6512     // co-terminal free run. This is done in the SweepClosure
  6513     // destructor; so, do not remove this scope, else the
  6514     // end-of-sweep-census below will be off by a little bit.
  6516   gen->cmsSpace()->sweep_completed();
  6517   gen->cmsSpace()->endSweepFLCensus(sweep_count());
  6518   if (should_unload_classes()) {                // unloaded classes this cycle,
  6519     _concurrent_cycles_since_last_unload = 0;   // ... reset count
  6520   } else {                                      // did not unload classes,
  6521     _concurrent_cycles_since_last_unload++;     // ... increment count
  6525 // Reset CMS data structures (for now just the marking bit map)
  6526 // preparatory for the next cycle.
  6527 void CMSCollector::reset(bool asynch) {
  6528   GenCollectedHeap* gch = GenCollectedHeap::heap();
  6529   CMSAdaptiveSizePolicy* sp = size_policy();
  6530   AdaptiveSizePolicyOutput(sp, gch->total_collections());
  6531   if (asynch) {
  6532     CMSTokenSyncWithLocks ts(true, bitMapLock());
  6534     // If the state is not "Resetting", the foreground  thread
  6535     // has done a collection and the resetting.
  6536     if (_collectorState != Resetting) {
  6537       assert(_collectorState == Idling, "The state should only change"
  6538         " because the foreground collector has finished the collection");
  6539       return;
  6542     // Clear the mark bitmap (no grey objects to start with)
  6543     // for the next cycle.
  6544     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  6545     CMSPhaseAccounting cmspa(this, "reset", _gc_tracer_cm->gc_id(), !PrintGCDetails);
  6547     HeapWord* curAddr = _markBitMap.startWord();
  6548     while (curAddr < _markBitMap.endWord()) {
  6549       size_t remaining  = pointer_delta(_markBitMap.endWord(), curAddr);
  6550       MemRegion chunk(curAddr, MIN2(CMSBitMapYieldQuantum, remaining));
  6551       _markBitMap.clear_large_range(chunk);
  6552       if (ConcurrentMarkSweepThread::should_yield() &&
  6553           !foregroundGCIsActive() &&
  6554           CMSYield) {
  6555         assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  6556                "CMS thread should hold CMS token");
  6557         assert_lock_strong(bitMapLock());
  6558         bitMapLock()->unlock();
  6559         ConcurrentMarkSweepThread::desynchronize(true);
  6560         ConcurrentMarkSweepThread::acknowledge_yield_request();
  6561         stopTimer();
  6562         if (PrintCMSStatistics != 0) {
  6563           incrementYields();
  6565         icms_wait();
  6567         // See the comment in coordinator_yield()
  6568         for (unsigned i = 0; i < CMSYieldSleepCount &&
  6569                          ConcurrentMarkSweepThread::should_yield() &&
  6570                          !CMSCollector::foregroundGCIsActive(); ++i) {
  6571           os::sleep(Thread::current(), 1, false);
  6572           ConcurrentMarkSweepThread::acknowledge_yield_request();
  6575         ConcurrentMarkSweepThread::synchronize(true);
  6576         bitMapLock()->lock_without_safepoint_check();
  6577         startTimer();
  6579       curAddr = chunk.end();
  6581     // A successful mostly concurrent collection has been done.
  6582     // Because only the full (i.e., concurrent mode failure) collections
  6583     // are being measured for gc overhead limits, clean the "near" flag
  6584     // and count.
  6585     sp->reset_gc_overhead_limit_count();
  6586     _collectorState = Idling;
  6587   } else {
  6588     // already have the lock
  6589     assert(_collectorState == Resetting, "just checking");
  6590     assert_lock_strong(bitMapLock());
  6591     _markBitMap.clear_all();
  6592     _collectorState = Idling;
  6595   // Stop incremental mode after a cycle completes, so that any future cycles
  6596   // are triggered by allocation.
  6597   stop_icms();
  6599   NOT_PRODUCT(
  6600     if (RotateCMSCollectionTypes) {
  6601       _cmsGen->rotate_debug_collection_type();
  6605   register_gc_end();
  6608 void CMSCollector::do_CMS_operation(CMS_op_type op, GCCause::Cause gc_cause) {
  6609   gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
  6610   TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  6611   GCTraceTime t(GCCauseString("GC", gc_cause), PrintGC, !PrintGCDetails, NULL, _gc_tracer_cm->gc_id());
  6612   TraceCollectorStats tcs(counters());
  6614   switch (op) {
  6615     case CMS_op_checkpointRootsInitial: {
  6616       SvcGCMarker sgcm(SvcGCMarker::OTHER);
  6617       checkpointRootsInitial(true);       // asynch
  6618       if (PrintGC) {
  6619         _cmsGen->printOccupancy("initial-mark");
  6621       break;
  6623     case CMS_op_checkpointRootsFinal: {
  6624       SvcGCMarker sgcm(SvcGCMarker::OTHER);
  6625       checkpointRootsFinal(true,    // asynch
  6626                            false,   // !clear_all_soft_refs
  6627                            false);  // !init_mark_was_synchronous
  6628       if (PrintGC) {
  6629         _cmsGen->printOccupancy("remark");
  6631       break;
  6633     default:
  6634       fatal("No such CMS_op");
  6638 #ifndef PRODUCT
  6639 size_t const CMSCollector::skip_header_HeapWords() {
  6640   return FreeChunk::header_size();
  6643 // Try and collect here conditions that should hold when
  6644 // CMS thread is exiting. The idea is that the foreground GC
  6645 // thread should not be blocked if it wants to terminate
  6646 // the CMS thread and yet continue to run the VM for a while
  6647 // after that.
  6648 void CMSCollector::verify_ok_to_terminate() const {
  6649   assert(Thread::current()->is_ConcurrentGC_thread(),
  6650          "should be called by CMS thread");
  6651   assert(!_foregroundGCShouldWait, "should be false");
  6652   // We could check here that all the various low-level locks
  6653   // are not held by the CMS thread, but that is overkill; see
  6654   // also CMSThread::verify_ok_to_terminate() where the CGC_lock
  6655   // is checked.
  6657 #endif
  6659 size_t CMSCollector::block_size_using_printezis_bits(HeapWord* addr) const {
  6660    assert(_markBitMap.isMarked(addr) && _markBitMap.isMarked(addr + 1),
  6661           "missing Printezis mark?");
  6662   HeapWord* nextOneAddr = _markBitMap.getNextMarkedWordAddress(addr + 2);
  6663   size_t size = pointer_delta(nextOneAddr + 1, addr);
  6664   assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
  6665          "alignment problem");
  6666   assert(size >= 3, "Necessary for Printezis marks to work");
  6667   return size;
  6670 // A variant of the above (block_size_using_printezis_bits()) except
  6671 // that we return 0 if the P-bits are not yet set.
  6672 size_t CMSCollector::block_size_if_printezis_bits(HeapWord* addr) const {
  6673   if (_markBitMap.isMarked(addr + 1)) {
  6674     assert(_markBitMap.isMarked(addr), "P-bit can be set only for marked objects");
  6675     HeapWord* nextOneAddr = _markBitMap.getNextMarkedWordAddress(addr + 2);
  6676     size_t size = pointer_delta(nextOneAddr + 1, addr);
  6677     assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
  6678            "alignment problem");
  6679     assert(size >= 3, "Necessary for Printezis marks to work");
  6680     return size;
  6682   return 0;
  6685 HeapWord* CMSCollector::next_card_start_after_block(HeapWord* addr) const {
  6686   size_t sz = 0;
  6687   oop p = (oop)addr;
  6688   if (p->klass_or_null() != NULL) {
  6689     sz = CompactibleFreeListSpace::adjustObjectSize(p->size());
  6690   } else {
  6691     sz = block_size_using_printezis_bits(addr);
  6693   assert(sz > 0, "size must be nonzero");
  6694   HeapWord* next_block = addr + sz;
  6695   HeapWord* next_card  = (HeapWord*)round_to((uintptr_t)next_block,
  6696                                              CardTableModRefBS::card_size);
  6697   assert(round_down((uintptr_t)addr,      CardTableModRefBS::card_size) <
  6698          round_down((uintptr_t)next_card, CardTableModRefBS::card_size),
  6699          "must be different cards");
  6700   return next_card;
  6704 // CMS Bit Map Wrapper /////////////////////////////////////////
  6706 // Construct a CMS bit map infrastructure, but don't create the
  6707 // bit vector itself. That is done by a separate call CMSBitMap::allocate()
  6708 // further below.
  6709 CMSBitMap::CMSBitMap(int shifter, int mutex_rank, const char* mutex_name):
  6710   _bm(),
  6711   _shifter(shifter),
  6712   _lock(mutex_rank >= 0 ? new Mutex(mutex_rank, mutex_name, true) : NULL)
  6714   _bmStartWord = 0;
  6715   _bmWordSize  = 0;
  6718 bool CMSBitMap::allocate(MemRegion mr) {
  6719   _bmStartWord = mr.start();
  6720   _bmWordSize  = mr.word_size();
  6721   ReservedSpace brs(ReservedSpace::allocation_align_size_up(
  6722                      (_bmWordSize >> (_shifter + LogBitsPerByte)) + 1));
  6723   if (!brs.is_reserved()) {
  6724     warning("CMS bit map allocation failure");
  6725     return false;
  6727   // For now we'll just commit all of the bit map up fromt.
  6728   // Later on we'll try to be more parsimonious with swap.
  6729   if (!_virtual_space.initialize(brs, brs.size())) {
  6730     warning("CMS bit map backing store failure");
  6731     return false;
  6733   assert(_virtual_space.committed_size() == brs.size(),
  6734          "didn't reserve backing store for all of CMS bit map?");
  6735   _bm.set_map((BitMap::bm_word_t*)_virtual_space.low());
  6736   assert(_virtual_space.committed_size() << (_shifter + LogBitsPerByte) >=
  6737          _bmWordSize, "inconsistency in bit map sizing");
  6738   _bm.set_size(_bmWordSize >> _shifter);
  6740   // bm.clear(); // can we rely on getting zero'd memory? verify below
  6741   assert(isAllClear(),
  6742          "Expected zero'd memory from ReservedSpace constructor");
  6743   assert(_bm.size() == heapWordDiffToOffsetDiff(sizeInWords()),
  6744          "consistency check");
  6745   return true;
  6748 void CMSBitMap::dirty_range_iterate_clear(MemRegion mr, MemRegionClosure* cl) {
  6749   HeapWord *next_addr, *end_addr, *last_addr;
  6750   assert_locked();
  6751   assert(covers(mr), "out-of-range error");
  6752   // XXX assert that start and end are appropriately aligned
  6753   for (next_addr = mr.start(), end_addr = mr.end();
  6754        next_addr < end_addr; next_addr = last_addr) {
  6755     MemRegion dirty_region = getAndClearMarkedRegion(next_addr, end_addr);
  6756     last_addr = dirty_region.end();
  6757     if (!dirty_region.is_empty()) {
  6758       cl->do_MemRegion(dirty_region);
  6759     } else {
  6760       assert(last_addr == end_addr, "program logic");
  6761       return;
  6766 void CMSBitMap::print_on_error(outputStream* st, const char* prefix) const {
  6767   _bm.print_on_error(st, prefix);
  6770 #ifndef PRODUCT
  6771 void CMSBitMap::assert_locked() const {
  6772   CMSLockVerifier::assert_locked(lock());
  6775 bool CMSBitMap::covers(MemRegion mr) const {
  6776   // assert(_bm.map() == _virtual_space.low(), "map inconsistency");
  6777   assert((size_t)_bm.size() == (_bmWordSize >> _shifter),
  6778          "size inconsistency");
  6779   return (mr.start() >= _bmStartWord) &&
  6780          (mr.end()   <= endWord());
  6783 bool CMSBitMap::covers(HeapWord* start, size_t size) const {
  6784     return (start >= _bmStartWord && (start + size) <= endWord());
  6787 void CMSBitMap::verifyNoOneBitsInRange(HeapWord* left, HeapWord* right) {
  6788   // verify that there are no 1 bits in the interval [left, right)
  6789   FalseBitMapClosure falseBitMapClosure;
  6790   iterate(&falseBitMapClosure, left, right);
  6793 void CMSBitMap::region_invariant(MemRegion mr)
  6795   assert_locked();
  6796   // mr = mr.intersection(MemRegion(_bmStartWord, _bmWordSize));
  6797   assert(!mr.is_empty(), "unexpected empty region");
  6798   assert(covers(mr), "mr should be covered by bit map");
  6799   // convert address range into offset range
  6800   size_t start_ofs = heapWordToOffset(mr.start());
  6801   // Make sure that end() is appropriately aligned
  6802   assert(mr.end() == (HeapWord*)round_to((intptr_t)mr.end(),
  6803                         (1 << (_shifter+LogHeapWordSize))),
  6804          "Misaligned mr.end()");
  6805   size_t end_ofs   = heapWordToOffset(mr.end());
  6806   assert(end_ofs > start_ofs, "Should mark at least one bit");
  6809 #endif
  6811 bool CMSMarkStack::allocate(size_t size) {
  6812   // allocate a stack of the requisite depth
  6813   ReservedSpace rs(ReservedSpace::allocation_align_size_up(
  6814                    size * sizeof(oop)));
  6815   if (!rs.is_reserved()) {
  6816     warning("CMSMarkStack allocation failure");
  6817     return false;
  6819   if (!_virtual_space.initialize(rs, rs.size())) {
  6820     warning("CMSMarkStack backing store failure");
  6821     return false;
  6823   assert(_virtual_space.committed_size() == rs.size(),
  6824          "didn't reserve backing store for all of CMS stack?");
  6825   _base = (oop*)(_virtual_space.low());
  6826   _index = 0;
  6827   _capacity = size;
  6828   NOT_PRODUCT(_max_depth = 0);
  6829   return true;
  6832 // XXX FIX ME !!! In the MT case we come in here holding a
  6833 // leaf lock. For printing we need to take a further lock
  6834 // which has lower rank. We need to recallibrate the two
  6835 // lock-ranks involved in order to be able to rpint the
  6836 // messages below. (Or defer the printing to the caller.
  6837 // For now we take the expedient path of just disabling the
  6838 // messages for the problematic case.)
  6839 void CMSMarkStack::expand() {
  6840   assert(_capacity <= MarkStackSizeMax, "stack bigger than permitted");
  6841   if (_capacity == MarkStackSizeMax) {
  6842     if (_hit_limit++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) {
  6843       // We print a warning message only once per CMS cycle.
  6844       gclog_or_tty->print_cr(" (benign) Hit CMSMarkStack max size limit");
  6846     return;
  6848   // Double capacity if possible
  6849   size_t new_capacity = MIN2(_capacity*2, MarkStackSizeMax);
  6850   // Do not give up existing stack until we have managed to
  6851   // get the double capacity that we desired.
  6852   ReservedSpace rs(ReservedSpace::allocation_align_size_up(
  6853                    new_capacity * sizeof(oop)));
  6854   if (rs.is_reserved()) {
  6855     // Release the backing store associated with old stack
  6856     _virtual_space.release();
  6857     // Reinitialize virtual space for new stack
  6858     if (!_virtual_space.initialize(rs, rs.size())) {
  6859       fatal("Not enough swap for expanded marking stack");
  6861     _base = (oop*)(_virtual_space.low());
  6862     _index = 0;
  6863     _capacity = new_capacity;
  6864   } else if (_failed_double++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) {
  6865     // Failed to double capacity, continue;
  6866     // we print a detail message only once per CMS cycle.
  6867     gclog_or_tty->print(" (benign) Failed to expand marking stack from "SIZE_FORMAT"K to "
  6868             SIZE_FORMAT"K",
  6869             _capacity / K, new_capacity / K);
  6874 // Closures
  6875 // XXX: there seems to be a lot of code  duplication here;
  6876 // should refactor and consolidate common code.
  6878 // This closure is used to mark refs into the CMS generation in
  6879 // the CMS bit map. Called at the first checkpoint. This closure
  6880 // assumes that we do not need to re-mark dirty cards; if the CMS
  6881 // generation on which this is used is not an oldest
  6882 // generation then this will lose younger_gen cards!
  6884 MarkRefsIntoClosure::MarkRefsIntoClosure(
  6885   MemRegion span, CMSBitMap* bitMap):
  6886     _span(span),
  6887     _bitMap(bitMap)
  6889     assert(_ref_processor == NULL, "deliberately left NULL");
  6890     assert(_bitMap->covers(_span), "_bitMap/_span mismatch");
  6893 void MarkRefsIntoClosure::do_oop(oop obj) {
  6894   // if p points into _span, then mark corresponding bit in _markBitMap
  6895   assert(obj->is_oop(), "expected an oop");
  6896   HeapWord* addr = (HeapWord*)obj;
  6897   if (_span.contains(addr)) {
  6898     // this should be made more efficient
  6899     _bitMap->mark(addr);
  6903 void MarkRefsIntoClosure::do_oop(oop* p)       { MarkRefsIntoClosure::do_oop_work(p); }
  6904 void MarkRefsIntoClosure::do_oop(narrowOop* p) { MarkRefsIntoClosure::do_oop_work(p); }
  6906 Par_MarkRefsIntoClosure::Par_MarkRefsIntoClosure(
  6907   MemRegion span, CMSBitMap* bitMap):
  6908     _span(span),
  6909     _bitMap(bitMap)
  6911     assert(_ref_processor == NULL, "deliberately left NULL");
  6912     assert(_bitMap->covers(_span), "_bitMap/_span mismatch");
  6915 void Par_MarkRefsIntoClosure::do_oop(oop obj) {
  6916   // if p points into _span, then mark corresponding bit in _markBitMap
  6917   assert(obj->is_oop(), "expected an oop");
  6918   HeapWord* addr = (HeapWord*)obj;
  6919   if (_span.contains(addr)) {
  6920     // this should be made more efficient
  6921     _bitMap->par_mark(addr);
  6925 void Par_MarkRefsIntoClosure::do_oop(oop* p)       { Par_MarkRefsIntoClosure::do_oop_work(p); }
  6926 void Par_MarkRefsIntoClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoClosure::do_oop_work(p); }
  6928 // A variant of the above, used for CMS marking verification.
  6929 MarkRefsIntoVerifyClosure::MarkRefsIntoVerifyClosure(
  6930   MemRegion span, CMSBitMap* verification_bm, CMSBitMap* cms_bm):
  6931     _span(span),
  6932     _verification_bm(verification_bm),
  6933     _cms_bm(cms_bm)
  6935     assert(_ref_processor == NULL, "deliberately left NULL");
  6936     assert(_verification_bm->covers(_span), "_verification_bm/_span mismatch");
  6939 void MarkRefsIntoVerifyClosure::do_oop(oop obj) {
  6940   // if p points into _span, then mark corresponding bit in _markBitMap
  6941   assert(obj->is_oop(), "expected an oop");
  6942   HeapWord* addr = (HeapWord*)obj;
  6943   if (_span.contains(addr)) {
  6944     _verification_bm->mark(addr);
  6945     if (!_cms_bm->isMarked(addr)) {
  6946       oop(addr)->print();
  6947       gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)", addr);
  6948       fatal("... aborting");
  6953 void MarkRefsIntoVerifyClosure::do_oop(oop* p)       { MarkRefsIntoVerifyClosure::do_oop_work(p); }
  6954 void MarkRefsIntoVerifyClosure::do_oop(narrowOop* p) { MarkRefsIntoVerifyClosure::do_oop_work(p); }
  6956 //////////////////////////////////////////////////
  6957 // MarkRefsIntoAndScanClosure
  6958 //////////////////////////////////////////////////
  6960 MarkRefsIntoAndScanClosure::MarkRefsIntoAndScanClosure(MemRegion span,
  6961                                                        ReferenceProcessor* rp,
  6962                                                        CMSBitMap* bit_map,
  6963                                                        CMSBitMap* mod_union_table,
  6964                                                        CMSMarkStack*  mark_stack,
  6965                                                        CMSCollector* collector,
  6966                                                        bool should_yield,
  6967                                                        bool concurrent_precleaning):
  6968   _collector(collector),
  6969   _span(span),
  6970   _bit_map(bit_map),
  6971   _mark_stack(mark_stack),
  6972   _pushAndMarkClosure(collector, span, rp, bit_map, mod_union_table,
  6973                       mark_stack, concurrent_precleaning),
  6974   _yield(should_yield),
  6975   _concurrent_precleaning(concurrent_precleaning),
  6976   _freelistLock(NULL)
  6978   _ref_processor = rp;
  6979   assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL");
  6982 // This closure is used to mark refs into the CMS generation at the
  6983 // second (final) checkpoint, and to scan and transitively follow
  6984 // the unmarked oops. It is also used during the concurrent precleaning
  6985 // phase while scanning objects on dirty cards in the CMS generation.
  6986 // The marks are made in the marking bit map and the marking stack is
  6987 // used for keeping the (newly) grey objects during the scan.
  6988 // The parallel version (Par_...) appears further below.
  6989 void MarkRefsIntoAndScanClosure::do_oop(oop obj) {
  6990   if (obj != NULL) {
  6991     assert(obj->is_oop(), "expected an oop");
  6992     HeapWord* addr = (HeapWord*)obj;
  6993     assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)");
  6994     assert(_collector->overflow_list_is_empty(),
  6995            "overflow list should be empty");
  6996     if (_span.contains(addr) &&
  6997         !_bit_map->isMarked(addr)) {
  6998       // mark bit map (object is now grey)
  6999       _bit_map->mark(addr);
  7000       // push on marking stack (stack should be empty), and drain the
  7001       // stack by applying this closure to the oops in the oops popped
  7002       // from the stack (i.e. blacken the grey objects)
  7003       bool res = _mark_stack->push(obj);
  7004       assert(res, "Should have space to push on empty stack");
  7005       do {
  7006         oop new_oop = _mark_stack->pop();
  7007         assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop");
  7008         assert(_bit_map->isMarked((HeapWord*)new_oop),
  7009                "only grey objects on this stack");
  7010         // iterate over the oops in this oop, marking and pushing
  7011         // the ones in CMS heap (i.e. in _span).
  7012         new_oop->oop_iterate(&_pushAndMarkClosure);
  7013         // check if it's time to yield
  7014         do_yield_check();
  7015       } while (!_mark_stack->isEmpty() ||
  7016                (!_concurrent_precleaning && take_from_overflow_list()));
  7017         // if marking stack is empty, and we are not doing this
  7018         // during precleaning, then check the overflow list
  7020     assert(_mark_stack->isEmpty(), "post-condition (eager drainage)");
  7021     assert(_collector->overflow_list_is_empty(),
  7022            "overflow list was drained above");
  7023     // We could restore evacuated mark words, if any, used for
  7024     // overflow list links here because the overflow list is
  7025     // provably empty here. That would reduce the maximum
  7026     // size requirements for preserved_{oop,mark}_stack.
  7027     // But we'll just postpone it until we are all done
  7028     // so we can just stream through.
  7029     if (!_concurrent_precleaning && CMSOverflowEarlyRestoration) {
  7030       _collector->restore_preserved_marks_if_any();
  7031       assert(_collector->no_preserved_marks(), "No preserved marks");
  7033     assert(!CMSOverflowEarlyRestoration || _collector->no_preserved_marks(),
  7034            "All preserved marks should have been restored above");
  7038 void MarkRefsIntoAndScanClosure::do_oop(oop* p)       { MarkRefsIntoAndScanClosure::do_oop_work(p); }
  7039 void MarkRefsIntoAndScanClosure::do_oop(narrowOop* p) { MarkRefsIntoAndScanClosure::do_oop_work(p); }
  7041 void MarkRefsIntoAndScanClosure::do_yield_work() {
  7042   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  7043          "CMS thread should hold CMS token");
  7044   assert_lock_strong(_freelistLock);
  7045   assert_lock_strong(_bit_map->lock());
  7046   // relinquish the free_list_lock and bitMaplock()
  7047   _bit_map->lock()->unlock();
  7048   _freelistLock->unlock();
  7049   ConcurrentMarkSweepThread::desynchronize(true);
  7050   ConcurrentMarkSweepThread::acknowledge_yield_request();
  7051   _collector->stopTimer();
  7052   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  7053   if (PrintCMSStatistics != 0) {
  7054     _collector->incrementYields();
  7056   _collector->icms_wait();
  7058   // See the comment in coordinator_yield()
  7059   for (unsigned i = 0;
  7060        i < CMSYieldSleepCount &&
  7061        ConcurrentMarkSweepThread::should_yield() &&
  7062        !CMSCollector::foregroundGCIsActive();
  7063        ++i) {
  7064     os::sleep(Thread::current(), 1, false);
  7065     ConcurrentMarkSweepThread::acknowledge_yield_request();
  7068   ConcurrentMarkSweepThread::synchronize(true);
  7069   _freelistLock->lock_without_safepoint_check();
  7070   _bit_map->lock()->lock_without_safepoint_check();
  7071   _collector->startTimer();
  7074 ///////////////////////////////////////////////////////////
  7075 // Par_MarkRefsIntoAndScanClosure: a parallel version of
  7076 //                                 MarkRefsIntoAndScanClosure
  7077 ///////////////////////////////////////////////////////////
  7078 Par_MarkRefsIntoAndScanClosure::Par_MarkRefsIntoAndScanClosure(
  7079   CMSCollector* collector, MemRegion span, ReferenceProcessor* rp,
  7080   CMSBitMap* bit_map, OopTaskQueue* work_queue):
  7081   _span(span),
  7082   _bit_map(bit_map),
  7083   _work_queue(work_queue),
  7084   _low_water_mark(MIN2((uint)(work_queue->max_elems()/4),
  7085                        (uint)(CMSWorkQueueDrainThreshold * ParallelGCThreads))),
  7086   _par_pushAndMarkClosure(collector, span, rp, bit_map, work_queue)
  7088   _ref_processor = rp;
  7089   assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL");
  7092 // This closure is used to mark refs into the CMS generation at the
  7093 // second (final) checkpoint, and to scan and transitively follow
  7094 // the unmarked oops. The marks are made in the marking bit map and
  7095 // the work_queue is used for keeping the (newly) grey objects during
  7096 // the scan phase whence they are also available for stealing by parallel
  7097 // threads. Since the marking bit map is shared, updates are
  7098 // synchronized (via CAS).
  7099 void Par_MarkRefsIntoAndScanClosure::do_oop(oop obj) {
  7100   if (obj != NULL) {
  7101     // Ignore mark word because this could be an already marked oop
  7102     // that may be chained at the end of the overflow list.
  7103     assert(obj->is_oop(true), "expected an oop");
  7104     HeapWord* addr = (HeapWord*)obj;
  7105     if (_span.contains(addr) &&
  7106         !_bit_map->isMarked(addr)) {
  7107       // mark bit map (object will become grey):
  7108       // It is possible for several threads to be
  7109       // trying to "claim" this object concurrently;
  7110       // the unique thread that succeeds in marking the
  7111       // object first will do the subsequent push on
  7112       // to the work queue (or overflow list).
  7113       if (_bit_map->par_mark(addr)) {
  7114         // push on work_queue (which may not be empty), and trim the
  7115         // queue to an appropriate length by applying this closure to
  7116         // the oops in the oops popped from the stack (i.e. blacken the
  7117         // grey objects)
  7118         bool res = _work_queue->push(obj);
  7119         assert(res, "Low water mark should be less than capacity?");
  7120         trim_queue(_low_water_mark);
  7121       } // Else, another thread claimed the object
  7126 void Par_MarkRefsIntoAndScanClosure::do_oop(oop* p)       { Par_MarkRefsIntoAndScanClosure::do_oop_work(p); }
  7127 void Par_MarkRefsIntoAndScanClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoAndScanClosure::do_oop_work(p); }
  7129 // This closure is used to rescan the marked objects on the dirty cards
  7130 // in the mod union table and the card table proper.
  7131 size_t ScanMarkedObjectsAgainCarefullyClosure::do_object_careful_m(
  7132   oop p, MemRegion mr) {
  7134   size_t size = 0;
  7135   HeapWord* addr = (HeapWord*)p;
  7136   DEBUG_ONLY(_collector->verify_work_stacks_empty();)
  7137   assert(_span.contains(addr), "we are scanning the CMS generation");
  7138   // check if it's time to yield
  7139   if (do_yield_check()) {
  7140     // We yielded for some foreground stop-world work,
  7141     // and we have been asked to abort this ongoing preclean cycle.
  7142     return 0;
  7144   if (_bitMap->isMarked(addr)) {
  7145     // it's marked; is it potentially uninitialized?
  7146     if (p->klass_or_null() != NULL) {
  7147         // an initialized object; ignore mark word in verification below
  7148         // since we are running concurrent with mutators
  7149         assert(p->is_oop(true), "should be an oop");
  7150         if (p->is_objArray()) {
  7151           // objArrays are precisely marked; restrict scanning
  7152           // to dirty cards only.
  7153           size = CompactibleFreeListSpace::adjustObjectSize(
  7154                    p->oop_iterate(_scanningClosure, mr));
  7155         } else {
  7156           // A non-array may have been imprecisely marked; we need
  7157           // to scan object in its entirety.
  7158           size = CompactibleFreeListSpace::adjustObjectSize(
  7159                    p->oop_iterate(_scanningClosure));
  7161         #ifdef ASSERT
  7162           size_t direct_size =
  7163             CompactibleFreeListSpace::adjustObjectSize(p->size());
  7164           assert(size == direct_size, "Inconsistency in size");
  7165           assert(size >= 3, "Necessary for Printezis marks to work");
  7166           if (!_bitMap->isMarked(addr+1)) {
  7167             _bitMap->verifyNoOneBitsInRange(addr+2, addr+size);
  7168           } else {
  7169             _bitMap->verifyNoOneBitsInRange(addr+2, addr+size-1);
  7170             assert(_bitMap->isMarked(addr+size-1),
  7171                    "inconsistent Printezis mark");
  7173         #endif // ASSERT
  7174     } else {
  7175       // an unitialized object
  7176       assert(_bitMap->isMarked(addr+1), "missing Printezis mark?");
  7177       HeapWord* nextOneAddr = _bitMap->getNextMarkedWordAddress(addr + 2);
  7178       size = pointer_delta(nextOneAddr + 1, addr);
  7179       assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
  7180              "alignment problem");
  7181       // Note that pre-cleaning needn't redirty the card. OopDesc::set_klass()
  7182       // will dirty the card when the klass pointer is installed in the
  7183       // object (signalling the completion of initialization).
  7185   } else {
  7186     // Either a not yet marked object or an uninitialized object
  7187     if (p->klass_or_null() == NULL) {
  7188       // An uninitialized object, skip to the next card, since
  7189       // we may not be able to read its P-bits yet.
  7190       assert(size == 0, "Initial value");
  7191     } else {
  7192       // An object not (yet) reached by marking: we merely need to
  7193       // compute its size so as to go look at the next block.
  7194       assert(p->is_oop(true), "should be an oop");
  7195       size = CompactibleFreeListSpace::adjustObjectSize(p->size());
  7198   DEBUG_ONLY(_collector->verify_work_stacks_empty();)
  7199   return size;
  7202 void ScanMarkedObjectsAgainCarefullyClosure::do_yield_work() {
  7203   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  7204          "CMS thread should hold CMS token");
  7205   assert_lock_strong(_freelistLock);
  7206   assert_lock_strong(_bitMap->lock());
  7207   // relinquish the free_list_lock and bitMaplock()
  7208   _bitMap->lock()->unlock();
  7209   _freelistLock->unlock();
  7210   ConcurrentMarkSweepThread::desynchronize(true);
  7211   ConcurrentMarkSweepThread::acknowledge_yield_request();
  7212   _collector->stopTimer();
  7213   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  7214   if (PrintCMSStatistics != 0) {
  7215     _collector->incrementYields();
  7217   _collector->icms_wait();
  7219   // See the comment in coordinator_yield()
  7220   for (unsigned i = 0; i < CMSYieldSleepCount &&
  7221                    ConcurrentMarkSweepThread::should_yield() &&
  7222                    !CMSCollector::foregroundGCIsActive(); ++i) {
  7223     os::sleep(Thread::current(), 1, false);
  7224     ConcurrentMarkSweepThread::acknowledge_yield_request();
  7227   ConcurrentMarkSweepThread::synchronize(true);
  7228   _freelistLock->lock_without_safepoint_check();
  7229   _bitMap->lock()->lock_without_safepoint_check();
  7230   _collector->startTimer();
  7234 //////////////////////////////////////////////////////////////////
  7235 // SurvivorSpacePrecleanClosure
  7236 //////////////////////////////////////////////////////////////////
  7237 // This (single-threaded) closure is used to preclean the oops in
  7238 // the survivor spaces.
  7239 size_t SurvivorSpacePrecleanClosure::do_object_careful(oop p) {
  7241   HeapWord* addr = (HeapWord*)p;
  7242   DEBUG_ONLY(_collector->verify_work_stacks_empty();)
  7243   assert(!_span.contains(addr), "we are scanning the survivor spaces");
  7244   assert(p->klass_or_null() != NULL, "object should be initializd");
  7245   // an initialized object; ignore mark word in verification below
  7246   // since we are running concurrent with mutators
  7247   assert(p->is_oop(true), "should be an oop");
  7248   // Note that we do not yield while we iterate over
  7249   // the interior oops of p, pushing the relevant ones
  7250   // on our marking stack.
  7251   size_t size = p->oop_iterate(_scanning_closure);
  7252   do_yield_check();
  7253   // Observe that below, we do not abandon the preclean
  7254   // phase as soon as we should; rather we empty the
  7255   // marking stack before returning. This is to satisfy
  7256   // some existing assertions. In general, it may be a
  7257   // good idea to abort immediately and complete the marking
  7258   // from the grey objects at a later time.
  7259   while (!_mark_stack->isEmpty()) {
  7260     oop new_oop = _mark_stack->pop();
  7261     assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop");
  7262     assert(_bit_map->isMarked((HeapWord*)new_oop),
  7263            "only grey objects on this stack");
  7264     // iterate over the oops in this oop, marking and pushing
  7265     // the ones in CMS heap (i.e. in _span).
  7266     new_oop->oop_iterate(_scanning_closure);
  7267     // check if it's time to yield
  7268     do_yield_check();
  7270   unsigned int after_count =
  7271     GenCollectedHeap::heap()->total_collections();
  7272   bool abort = (_before_count != after_count) ||
  7273                _collector->should_abort_preclean();
  7274   return abort ? 0 : size;
  7277 void SurvivorSpacePrecleanClosure::do_yield_work() {
  7278   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  7279          "CMS thread should hold CMS token");
  7280   assert_lock_strong(_bit_map->lock());
  7281   // Relinquish the bit map lock
  7282   _bit_map->lock()->unlock();
  7283   ConcurrentMarkSweepThread::desynchronize(true);
  7284   ConcurrentMarkSweepThread::acknowledge_yield_request();
  7285   _collector->stopTimer();
  7286   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  7287   if (PrintCMSStatistics != 0) {
  7288     _collector->incrementYields();
  7290   _collector->icms_wait();
  7292   // See the comment in coordinator_yield()
  7293   for (unsigned i = 0; i < CMSYieldSleepCount &&
  7294                        ConcurrentMarkSweepThread::should_yield() &&
  7295                        !CMSCollector::foregroundGCIsActive(); ++i) {
  7296     os::sleep(Thread::current(), 1, false);
  7297     ConcurrentMarkSweepThread::acknowledge_yield_request();
  7300   ConcurrentMarkSweepThread::synchronize(true);
  7301   _bit_map->lock()->lock_without_safepoint_check();
  7302   _collector->startTimer();
  7305 // This closure is used to rescan the marked objects on the dirty cards
  7306 // in the mod union table and the card table proper. In the parallel
  7307 // case, although the bitMap is shared, we do a single read so the
  7308 // isMarked() query is "safe".
  7309 bool ScanMarkedObjectsAgainClosure::do_object_bm(oop p, MemRegion mr) {
  7310   // Ignore mark word because we are running concurrent with mutators
  7311   assert(p->is_oop_or_null(true), "expected an oop or null");
  7312   HeapWord* addr = (HeapWord*)p;
  7313   assert(_span.contains(addr), "we are scanning the CMS generation");
  7314   bool is_obj_array = false;
  7315   #ifdef ASSERT
  7316     if (!_parallel) {
  7317       assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)");
  7318       assert(_collector->overflow_list_is_empty(),
  7319              "overflow list should be empty");
  7322   #endif // ASSERT
  7323   if (_bit_map->isMarked(addr)) {
  7324     // Obj arrays are precisely marked, non-arrays are not;
  7325     // so we scan objArrays precisely and non-arrays in their
  7326     // entirety.
  7327     if (p->is_objArray()) {
  7328       is_obj_array = true;
  7329       if (_parallel) {
  7330         p->oop_iterate(_par_scan_closure, mr);
  7331       } else {
  7332         p->oop_iterate(_scan_closure, mr);
  7334     } else {
  7335       if (_parallel) {
  7336         p->oop_iterate(_par_scan_closure);
  7337       } else {
  7338         p->oop_iterate(_scan_closure);
  7342   #ifdef ASSERT
  7343     if (!_parallel) {
  7344       assert(_mark_stack->isEmpty(), "post-condition (eager drainage)");
  7345       assert(_collector->overflow_list_is_empty(),
  7346              "overflow list should be empty");
  7349   #endif // ASSERT
  7350   return is_obj_array;
  7353 MarkFromRootsClosure::MarkFromRootsClosure(CMSCollector* collector,
  7354                         MemRegion span,
  7355                         CMSBitMap* bitMap, CMSMarkStack*  markStack,
  7356                         bool should_yield, bool verifying):
  7357   _collector(collector),
  7358   _span(span),
  7359   _bitMap(bitMap),
  7360   _mut(&collector->_modUnionTable),
  7361   _markStack(markStack),
  7362   _yield(should_yield),
  7363   _skipBits(0)
  7365   assert(_markStack->isEmpty(), "stack should be empty");
  7366   _finger = _bitMap->startWord();
  7367   _threshold = _finger;
  7368   assert(_collector->_restart_addr == NULL, "Sanity check");
  7369   assert(_span.contains(_finger), "Out of bounds _finger?");
  7370   DEBUG_ONLY(_verifying = verifying;)
  7373 void MarkFromRootsClosure::reset(HeapWord* addr) {
  7374   assert(_markStack->isEmpty(), "would cause duplicates on stack");
  7375   assert(_span.contains(addr), "Out of bounds _finger?");
  7376   _finger = addr;
  7377   _threshold = (HeapWord*)round_to(
  7378                  (intptr_t)_finger, CardTableModRefBS::card_size);
  7381 // Should revisit to see if this should be restructured for
  7382 // greater efficiency.
  7383 bool MarkFromRootsClosure::do_bit(size_t offset) {
  7384   if (_skipBits > 0) {
  7385     _skipBits--;
  7386     return true;
  7388   // convert offset into a HeapWord*
  7389   HeapWord* addr = _bitMap->startWord() + offset;
  7390   assert(_bitMap->endWord() && addr < _bitMap->endWord(),
  7391          "address out of range");
  7392   assert(_bitMap->isMarked(addr), "tautology");
  7393   if (_bitMap->isMarked(addr+1)) {
  7394     // this is an allocated but not yet initialized object
  7395     assert(_skipBits == 0, "tautology");
  7396     _skipBits = 2;  // skip next two marked bits ("Printezis-marks")
  7397     oop p = oop(addr);
  7398     if (p->klass_or_null() == NULL) {
  7399       DEBUG_ONLY(if (!_verifying) {)
  7400         // We re-dirty the cards on which this object lies and increase
  7401         // the _threshold so that we'll come back to scan this object
  7402         // during the preclean or remark phase. (CMSCleanOnEnter)
  7403         if (CMSCleanOnEnter) {
  7404           size_t sz = _collector->block_size_using_printezis_bits(addr);
  7405           HeapWord* end_card_addr   = (HeapWord*)round_to(
  7406                                          (intptr_t)(addr+sz), CardTableModRefBS::card_size);
  7407           MemRegion redirty_range = MemRegion(addr, end_card_addr);
  7408           assert(!redirty_range.is_empty(), "Arithmetical tautology");
  7409           // Bump _threshold to end_card_addr; note that
  7410           // _threshold cannot possibly exceed end_card_addr, anyhow.
  7411           // This prevents future clearing of the card as the scan proceeds
  7412           // to the right.
  7413           assert(_threshold <= end_card_addr,
  7414                  "Because we are just scanning into this object");
  7415           if (_threshold < end_card_addr) {
  7416             _threshold = end_card_addr;
  7418           if (p->klass_or_null() != NULL) {
  7419             // Redirty the range of cards...
  7420             _mut->mark_range(redirty_range);
  7421           } // ...else the setting of klass will dirty the card anyway.
  7423       DEBUG_ONLY(})
  7424       return true;
  7427   scanOopsInOop(addr);
  7428   return true;
  7431 // We take a break if we've been at this for a while,
  7432 // so as to avoid monopolizing the locks involved.
  7433 void MarkFromRootsClosure::do_yield_work() {
  7434   // First give up the locks, then yield, then re-lock
  7435   // We should probably use a constructor/destructor idiom to
  7436   // do this unlock/lock or modify the MutexUnlocker class to
  7437   // serve our purpose. XXX
  7438   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  7439          "CMS thread should hold CMS token");
  7440   assert_lock_strong(_bitMap->lock());
  7441   _bitMap->lock()->unlock();
  7442   ConcurrentMarkSweepThread::desynchronize(true);
  7443   ConcurrentMarkSweepThread::acknowledge_yield_request();
  7444   _collector->stopTimer();
  7445   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  7446   if (PrintCMSStatistics != 0) {
  7447     _collector->incrementYields();
  7449   _collector->icms_wait();
  7451   // See the comment in coordinator_yield()
  7452   for (unsigned i = 0; i < CMSYieldSleepCount &&
  7453                        ConcurrentMarkSweepThread::should_yield() &&
  7454                        !CMSCollector::foregroundGCIsActive(); ++i) {
  7455     os::sleep(Thread::current(), 1, false);
  7456     ConcurrentMarkSweepThread::acknowledge_yield_request();
  7459   ConcurrentMarkSweepThread::synchronize(true);
  7460   _bitMap->lock()->lock_without_safepoint_check();
  7461   _collector->startTimer();
  7464 void MarkFromRootsClosure::scanOopsInOop(HeapWord* ptr) {
  7465   assert(_bitMap->isMarked(ptr), "expected bit to be set");
  7466   assert(_markStack->isEmpty(),
  7467          "should drain stack to limit stack usage");
  7468   // convert ptr to an oop preparatory to scanning
  7469   oop obj = oop(ptr);
  7470   // Ignore mark word in verification below, since we
  7471   // may be running concurrent with mutators.
  7472   assert(obj->is_oop(true), "should be an oop");
  7473   assert(_finger <= ptr, "_finger runneth ahead");
  7474   // advance the finger to right end of this object
  7475   _finger = ptr + obj->size();
  7476   assert(_finger > ptr, "we just incremented it above");
  7477   // On large heaps, it may take us some time to get through
  7478   // the marking phase (especially if running iCMS). During
  7479   // this time it's possible that a lot of mutations have
  7480   // accumulated in the card table and the mod union table --
  7481   // these mutation records are redundant until we have
  7482   // actually traced into the corresponding card.
  7483   // Here, we check whether advancing the finger would make
  7484   // us cross into a new card, and if so clear corresponding
  7485   // cards in the MUT (preclean them in the card-table in the
  7486   // future).
  7488   DEBUG_ONLY(if (!_verifying) {)
  7489     // The clean-on-enter optimization is disabled by default,
  7490     // until we fix 6178663.
  7491     if (CMSCleanOnEnter && (_finger > _threshold)) {
  7492       // [_threshold, _finger) represents the interval
  7493       // of cards to be cleared  in MUT (or precleaned in card table).
  7494       // The set of cards to be cleared is all those that overlap
  7495       // with the interval [_threshold, _finger); note that
  7496       // _threshold is always kept card-aligned but _finger isn't
  7497       // always card-aligned.
  7498       HeapWord* old_threshold = _threshold;
  7499       assert(old_threshold == (HeapWord*)round_to(
  7500               (intptr_t)old_threshold, CardTableModRefBS::card_size),
  7501              "_threshold should always be card-aligned");
  7502       _threshold = (HeapWord*)round_to(
  7503                      (intptr_t)_finger, CardTableModRefBS::card_size);
  7504       MemRegion mr(old_threshold, _threshold);
  7505       assert(!mr.is_empty(), "Control point invariant");
  7506       assert(_span.contains(mr), "Should clear within span");
  7507       _mut->clear_range(mr);
  7509   DEBUG_ONLY(})
  7510   // Note: the finger doesn't advance while we drain
  7511   // the stack below.
  7512   PushOrMarkClosure pushOrMarkClosure(_collector,
  7513                                       _span, _bitMap, _markStack,
  7514                                       _finger, this);
  7515   bool res = _markStack->push(obj);
  7516   assert(res, "Empty non-zero size stack should have space for single push");
  7517   while (!_markStack->isEmpty()) {
  7518     oop new_oop = _markStack->pop();
  7519     // Skip verifying header mark word below because we are
  7520     // running concurrent with mutators.
  7521     assert(new_oop->is_oop(true), "Oops! expected to pop an oop");
  7522     // now scan this oop's oops
  7523     new_oop->oop_iterate(&pushOrMarkClosure);
  7524     do_yield_check();
  7526   assert(_markStack->isEmpty(), "tautology, emphasizing post-condition");
  7529 Par_MarkFromRootsClosure::Par_MarkFromRootsClosure(CMSConcMarkingTask* task,
  7530                        CMSCollector* collector, MemRegion span,
  7531                        CMSBitMap* bit_map,
  7532                        OopTaskQueue* work_queue,
  7533                        CMSMarkStack*  overflow_stack,
  7534                        bool should_yield):
  7535   _collector(collector),
  7536   _whole_span(collector->_span),
  7537   _span(span),
  7538   _bit_map(bit_map),
  7539   _mut(&collector->_modUnionTable),
  7540   _work_queue(work_queue),
  7541   _overflow_stack(overflow_stack),
  7542   _yield(should_yield),
  7543   _skip_bits(0),
  7544   _task(task)
  7546   assert(_work_queue->size() == 0, "work_queue should be empty");
  7547   _finger = span.start();
  7548   _threshold = _finger;     // XXX Defer clear-on-enter optimization for now
  7549   assert(_span.contains(_finger), "Out of bounds _finger?");
  7552 // Should revisit to see if this should be restructured for
  7553 // greater efficiency.
  7554 bool Par_MarkFromRootsClosure::do_bit(size_t offset) {
  7555   if (_skip_bits > 0) {
  7556     _skip_bits--;
  7557     return true;
  7559   // convert offset into a HeapWord*
  7560   HeapWord* addr = _bit_map->startWord() + offset;
  7561   assert(_bit_map->endWord() && addr < _bit_map->endWord(),
  7562          "address out of range");
  7563   assert(_bit_map->isMarked(addr), "tautology");
  7564   if (_bit_map->isMarked(addr+1)) {
  7565     // this is an allocated object that might not yet be initialized
  7566     assert(_skip_bits == 0, "tautology");
  7567     _skip_bits = 2;  // skip next two marked bits ("Printezis-marks")
  7568     oop p = oop(addr);
  7569     if (p->klass_or_null() == NULL) {
  7570       // in the case of Clean-on-Enter optimization, redirty card
  7571       // and avoid clearing card by increasing  the threshold.
  7572       return true;
  7575   scan_oops_in_oop(addr);
  7576   return true;
  7579 void Par_MarkFromRootsClosure::scan_oops_in_oop(HeapWord* ptr) {
  7580   assert(_bit_map->isMarked(ptr), "expected bit to be set");
  7581   // Should we assert that our work queue is empty or
  7582   // below some drain limit?
  7583   assert(_work_queue->size() == 0,
  7584          "should drain stack to limit stack usage");
  7585   // convert ptr to an oop preparatory to scanning
  7586   oop obj = oop(ptr);
  7587   // Ignore mark word in verification below, since we
  7588   // may be running concurrent with mutators.
  7589   assert(obj->is_oop(true), "should be an oop");
  7590   assert(_finger <= ptr, "_finger runneth ahead");
  7591   // advance the finger to right end of this object
  7592   _finger = ptr + obj->size();
  7593   assert(_finger > ptr, "we just incremented it above");
  7594   // On large heaps, it may take us some time to get through
  7595   // the marking phase (especially if running iCMS). During
  7596   // this time it's possible that a lot of mutations have
  7597   // accumulated in the card table and the mod union table --
  7598   // these mutation records are redundant until we have
  7599   // actually traced into the corresponding card.
  7600   // Here, we check whether advancing the finger would make
  7601   // us cross into a new card, and if so clear corresponding
  7602   // cards in the MUT (preclean them in the card-table in the
  7603   // future).
  7605   // The clean-on-enter optimization is disabled by default,
  7606   // until we fix 6178663.
  7607   if (CMSCleanOnEnter && (_finger > _threshold)) {
  7608     // [_threshold, _finger) represents the interval
  7609     // of cards to be cleared  in MUT (or precleaned in card table).
  7610     // The set of cards to be cleared is all those that overlap
  7611     // with the interval [_threshold, _finger); note that
  7612     // _threshold is always kept card-aligned but _finger isn't
  7613     // always card-aligned.
  7614     HeapWord* old_threshold = _threshold;
  7615     assert(old_threshold == (HeapWord*)round_to(
  7616             (intptr_t)old_threshold, CardTableModRefBS::card_size),
  7617            "_threshold should always be card-aligned");
  7618     _threshold = (HeapWord*)round_to(
  7619                    (intptr_t)_finger, CardTableModRefBS::card_size);
  7620     MemRegion mr(old_threshold, _threshold);
  7621     assert(!mr.is_empty(), "Control point invariant");
  7622     assert(_span.contains(mr), "Should clear within span"); // _whole_span ??
  7623     _mut->clear_range(mr);
  7626   // Note: the local finger doesn't advance while we drain
  7627   // the stack below, but the global finger sure can and will.
  7628   HeapWord** gfa = _task->global_finger_addr();
  7629   Par_PushOrMarkClosure pushOrMarkClosure(_collector,
  7630                                       _span, _bit_map,
  7631                                       _work_queue,
  7632                                       _overflow_stack,
  7633                                       _finger,
  7634                                       gfa, this);
  7635   bool res = _work_queue->push(obj);   // overflow could occur here
  7636   assert(res, "Will hold once we use workqueues");
  7637   while (true) {
  7638     oop new_oop;
  7639     if (!_work_queue->pop_local(new_oop)) {
  7640       // We emptied our work_queue; check if there's stuff that can
  7641       // be gotten from the overflow stack.
  7642       if (CMSConcMarkingTask::get_work_from_overflow_stack(
  7643             _overflow_stack, _work_queue)) {
  7644         do_yield_check();
  7645         continue;
  7646       } else {  // done
  7647         break;
  7650     // Skip verifying header mark word below because we are
  7651     // running concurrent with mutators.
  7652     assert(new_oop->is_oop(true), "Oops! expected to pop an oop");
  7653     // now scan this oop's oops
  7654     new_oop->oop_iterate(&pushOrMarkClosure);
  7655     do_yield_check();
  7657   assert(_work_queue->size() == 0, "tautology, emphasizing post-condition");
  7660 // Yield in response to a request from VM Thread or
  7661 // from mutators.
  7662 void Par_MarkFromRootsClosure::do_yield_work() {
  7663   assert(_task != NULL, "sanity");
  7664   _task->yield();
  7667 // A variant of the above used for verifying CMS marking work.
  7668 MarkFromRootsVerifyClosure::MarkFromRootsVerifyClosure(CMSCollector* collector,
  7669                         MemRegion span,
  7670                         CMSBitMap* verification_bm, CMSBitMap* cms_bm,
  7671                         CMSMarkStack*  mark_stack):
  7672   _collector(collector),
  7673   _span(span),
  7674   _verification_bm(verification_bm),
  7675   _cms_bm(cms_bm),
  7676   _mark_stack(mark_stack),
  7677   _pam_verify_closure(collector, span, verification_bm, cms_bm,
  7678                       mark_stack)
  7680   assert(_mark_stack->isEmpty(), "stack should be empty");
  7681   _finger = _verification_bm->startWord();
  7682   assert(_collector->_restart_addr == NULL, "Sanity check");
  7683   assert(_span.contains(_finger), "Out of bounds _finger?");
  7686 void MarkFromRootsVerifyClosure::reset(HeapWord* addr) {
  7687   assert(_mark_stack->isEmpty(), "would cause duplicates on stack");
  7688   assert(_span.contains(addr), "Out of bounds _finger?");
  7689   _finger = addr;
  7692 // Should revisit to see if this should be restructured for
  7693 // greater efficiency.
  7694 bool MarkFromRootsVerifyClosure::do_bit(size_t offset) {
  7695   // convert offset into a HeapWord*
  7696   HeapWord* addr = _verification_bm->startWord() + offset;
  7697   assert(_verification_bm->endWord() && addr < _verification_bm->endWord(),
  7698          "address out of range");
  7699   assert(_verification_bm->isMarked(addr), "tautology");
  7700   assert(_cms_bm->isMarked(addr), "tautology");
  7702   assert(_mark_stack->isEmpty(),
  7703          "should drain stack to limit stack usage");
  7704   // convert addr to an oop preparatory to scanning
  7705   oop obj = oop(addr);
  7706   assert(obj->is_oop(), "should be an oop");
  7707   assert(_finger <= addr, "_finger runneth ahead");
  7708   // advance the finger to right end of this object
  7709   _finger = addr + obj->size();
  7710   assert(_finger > addr, "we just incremented it above");
  7711   // Note: the finger doesn't advance while we drain
  7712   // the stack below.
  7713   bool res = _mark_stack->push(obj);
  7714   assert(res, "Empty non-zero size stack should have space for single push");
  7715   while (!_mark_stack->isEmpty()) {
  7716     oop new_oop = _mark_stack->pop();
  7717     assert(new_oop->is_oop(), "Oops! expected to pop an oop");
  7718     // now scan this oop's oops
  7719     new_oop->oop_iterate(&_pam_verify_closure);
  7721   assert(_mark_stack->isEmpty(), "tautology, emphasizing post-condition");
  7722   return true;
  7725 PushAndMarkVerifyClosure::PushAndMarkVerifyClosure(
  7726   CMSCollector* collector, MemRegion span,
  7727   CMSBitMap* verification_bm, CMSBitMap* cms_bm,
  7728   CMSMarkStack*  mark_stack):
  7729   CMSOopClosure(collector->ref_processor()),
  7730   _collector(collector),
  7731   _span(span),
  7732   _verification_bm(verification_bm),
  7733   _cms_bm(cms_bm),
  7734   _mark_stack(mark_stack)
  7735 { }
  7737 void PushAndMarkVerifyClosure::do_oop(oop* p)       { PushAndMarkVerifyClosure::do_oop_work(p); }
  7738 void PushAndMarkVerifyClosure::do_oop(narrowOop* p) { PushAndMarkVerifyClosure::do_oop_work(p); }
  7740 // Upon stack overflow, we discard (part of) the stack,
  7741 // remembering the least address amongst those discarded
  7742 // in CMSCollector's _restart_address.
  7743 void PushAndMarkVerifyClosure::handle_stack_overflow(HeapWord* lost) {
  7744   // Remember the least grey address discarded
  7745   HeapWord* ra = (HeapWord*)_mark_stack->least_value(lost);
  7746   _collector->lower_restart_addr(ra);
  7747   _mark_stack->reset();  // discard stack contents
  7748   _mark_stack->expand(); // expand the stack if possible
  7751 void PushAndMarkVerifyClosure::do_oop(oop obj) {
  7752   assert(obj->is_oop_or_null(), "expected an oop or NULL");
  7753   HeapWord* addr = (HeapWord*)obj;
  7754   if (_span.contains(addr) && !_verification_bm->isMarked(addr)) {
  7755     // Oop lies in _span and isn't yet grey or black
  7756     _verification_bm->mark(addr);            // now grey
  7757     if (!_cms_bm->isMarked(addr)) {
  7758       oop(addr)->print();
  7759       gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)",
  7760                              addr);
  7761       fatal("... aborting");
  7764     if (!_mark_stack->push(obj)) { // stack overflow
  7765       if (PrintCMSStatistics != 0) {
  7766         gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
  7767                                SIZE_FORMAT, _mark_stack->capacity());
  7769       assert(_mark_stack->isFull(), "Else push should have succeeded");
  7770       handle_stack_overflow(addr);
  7772     // anything including and to the right of _finger
  7773     // will be scanned as we iterate over the remainder of the
  7774     // bit map
  7778 PushOrMarkClosure::PushOrMarkClosure(CMSCollector* collector,
  7779                      MemRegion span,
  7780                      CMSBitMap* bitMap, CMSMarkStack*  markStack,
  7781                      HeapWord* finger, MarkFromRootsClosure* parent) :
  7782   CMSOopClosure(collector->ref_processor()),
  7783   _collector(collector),
  7784   _span(span),
  7785   _bitMap(bitMap),
  7786   _markStack(markStack),
  7787   _finger(finger),
  7788   _parent(parent)
  7789 { }
  7791 Par_PushOrMarkClosure::Par_PushOrMarkClosure(CMSCollector* collector,
  7792                      MemRegion span,
  7793                      CMSBitMap* bit_map,
  7794                      OopTaskQueue* work_queue,
  7795                      CMSMarkStack*  overflow_stack,
  7796                      HeapWord* finger,
  7797                      HeapWord** global_finger_addr,
  7798                      Par_MarkFromRootsClosure* parent) :
  7799   CMSOopClosure(collector->ref_processor()),
  7800   _collector(collector),
  7801   _whole_span(collector->_span),
  7802   _span(span),
  7803   _bit_map(bit_map),
  7804   _work_queue(work_queue),
  7805   _overflow_stack(overflow_stack),
  7806   _finger(finger),
  7807   _global_finger_addr(global_finger_addr),
  7808   _parent(parent)
  7809 { }
  7811 // Assumes thread-safe access by callers, who are
  7812 // responsible for mutual exclusion.
  7813 void CMSCollector::lower_restart_addr(HeapWord* low) {
  7814   assert(_span.contains(low), "Out of bounds addr");
  7815   if (_restart_addr == NULL) {
  7816     _restart_addr = low;
  7817   } else {
  7818     _restart_addr = MIN2(_restart_addr, low);
  7822 // Upon stack overflow, we discard (part of) the stack,
  7823 // remembering the least address amongst those discarded
  7824 // in CMSCollector's _restart_address.
  7825 void PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) {
  7826   // Remember the least grey address discarded
  7827   HeapWord* ra = (HeapWord*)_markStack->least_value(lost);
  7828   _collector->lower_restart_addr(ra);
  7829   _markStack->reset();  // discard stack contents
  7830   _markStack->expand(); // expand the stack if possible
  7833 // Upon stack overflow, we discard (part of) the stack,
  7834 // remembering the least address amongst those discarded
  7835 // in CMSCollector's _restart_address.
  7836 void Par_PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) {
  7837   // We need to do this under a mutex to prevent other
  7838   // workers from interfering with the work done below.
  7839   MutexLockerEx ml(_overflow_stack->par_lock(),
  7840                    Mutex::_no_safepoint_check_flag);
  7841   // Remember the least grey address discarded
  7842   HeapWord* ra = (HeapWord*)_overflow_stack->least_value(lost);
  7843   _collector->lower_restart_addr(ra);
  7844   _overflow_stack->reset();  // discard stack contents
  7845   _overflow_stack->expand(); // expand the stack if possible
  7848 void CMKlassClosure::do_klass(Klass* k) {
  7849   assert(_oop_closure != NULL, "Not initialized?");
  7850   k->oops_do(_oop_closure);
  7853 void PushOrMarkClosure::do_oop(oop obj) {
  7854   // Ignore mark word because we are running concurrent with mutators.
  7855   assert(obj->is_oop_or_null(true), "expected an oop or NULL");
  7856   HeapWord* addr = (HeapWord*)obj;
  7857   if (_span.contains(addr) && !_bitMap->isMarked(addr)) {
  7858     // Oop lies in _span and isn't yet grey or black
  7859     _bitMap->mark(addr);            // now grey
  7860     if (addr < _finger) {
  7861       // the bit map iteration has already either passed, or
  7862       // sampled, this bit in the bit map; we'll need to
  7863       // use the marking stack to scan this oop's oops.
  7864       bool simulate_overflow = false;
  7865       NOT_PRODUCT(
  7866         if (CMSMarkStackOverflowALot &&
  7867             _collector->simulate_overflow()) {
  7868           // simulate a stack overflow
  7869           simulate_overflow = true;
  7872       if (simulate_overflow || !_markStack->push(obj)) { // stack overflow
  7873         if (PrintCMSStatistics != 0) {
  7874           gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
  7875                                  SIZE_FORMAT, _markStack->capacity());
  7877         assert(simulate_overflow || _markStack->isFull(), "Else push should have succeeded");
  7878         handle_stack_overflow(addr);
  7881     // anything including and to the right of _finger
  7882     // will be scanned as we iterate over the remainder of the
  7883     // bit map
  7884     do_yield_check();
  7888 void PushOrMarkClosure::do_oop(oop* p)       { PushOrMarkClosure::do_oop_work(p); }
  7889 void PushOrMarkClosure::do_oop(narrowOop* p) { PushOrMarkClosure::do_oop_work(p); }
  7891 void Par_PushOrMarkClosure::do_oop(oop obj) {
  7892   // Ignore mark word because we are running concurrent with mutators.
  7893   assert(obj->is_oop_or_null(true), "expected an oop or NULL");
  7894   HeapWord* addr = (HeapWord*)obj;
  7895   if (_whole_span.contains(addr) && !_bit_map->isMarked(addr)) {
  7896     // Oop lies in _span and isn't yet grey or black
  7897     // We read the global_finger (volatile read) strictly after marking oop
  7898     bool res = _bit_map->par_mark(addr);    // now grey
  7899     volatile HeapWord** gfa = (volatile HeapWord**)_global_finger_addr;
  7900     // Should we push this marked oop on our stack?
  7901     // -- if someone else marked it, nothing to do
  7902     // -- if target oop is above global finger nothing to do
  7903     // -- if target oop is in chunk and above local finger
  7904     //      then nothing to do
  7905     // -- else push on work queue
  7906     if (   !res       // someone else marked it, they will deal with it
  7907         || (addr >= *gfa)  // will be scanned in a later task
  7908         || (_span.contains(addr) && addr >= _finger)) { // later in this chunk
  7909       return;
  7911     // the bit map iteration has already either passed, or
  7912     // sampled, this bit in the bit map; we'll need to
  7913     // use the marking stack to scan this oop's oops.
  7914     bool simulate_overflow = false;
  7915     NOT_PRODUCT(
  7916       if (CMSMarkStackOverflowALot &&
  7917           _collector->simulate_overflow()) {
  7918         // simulate a stack overflow
  7919         simulate_overflow = true;
  7922     if (simulate_overflow ||
  7923         !(_work_queue->push(obj) || _overflow_stack->par_push(obj))) {
  7924       // stack overflow
  7925       if (PrintCMSStatistics != 0) {
  7926         gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
  7927                                SIZE_FORMAT, _overflow_stack->capacity());
  7929       // We cannot assert that the overflow stack is full because
  7930       // it may have been emptied since.
  7931       assert(simulate_overflow ||
  7932              _work_queue->size() == _work_queue->max_elems(),
  7933             "Else push should have succeeded");
  7934       handle_stack_overflow(addr);
  7936     do_yield_check();
  7940 void Par_PushOrMarkClosure::do_oop(oop* p)       { Par_PushOrMarkClosure::do_oop_work(p); }
  7941 void Par_PushOrMarkClosure::do_oop(narrowOop* p) { Par_PushOrMarkClosure::do_oop_work(p); }
  7943 PushAndMarkClosure::PushAndMarkClosure(CMSCollector* collector,
  7944                                        MemRegion span,
  7945                                        ReferenceProcessor* rp,
  7946                                        CMSBitMap* bit_map,
  7947                                        CMSBitMap* mod_union_table,
  7948                                        CMSMarkStack*  mark_stack,
  7949                                        bool           concurrent_precleaning):
  7950   CMSOopClosure(rp),
  7951   _collector(collector),
  7952   _span(span),
  7953   _bit_map(bit_map),
  7954   _mod_union_table(mod_union_table),
  7955   _mark_stack(mark_stack),
  7956   _concurrent_precleaning(concurrent_precleaning)
  7958   assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL");
  7961 // Grey object rescan during pre-cleaning and second checkpoint phases --
  7962 // the non-parallel version (the parallel version appears further below.)
  7963 void PushAndMarkClosure::do_oop(oop obj) {
  7964   // Ignore mark word verification. If during concurrent precleaning,
  7965   // the object monitor may be locked. If during the checkpoint
  7966   // phases, the object may already have been reached by a  different
  7967   // path and may be at the end of the global overflow list (so
  7968   // the mark word may be NULL).
  7969   assert(obj->is_oop_or_null(true /* ignore mark word */),
  7970          "expected an oop or NULL");
  7971   HeapWord* addr = (HeapWord*)obj;
  7972   // Check if oop points into the CMS generation
  7973   // and is not marked
  7974   if (_span.contains(addr) && !_bit_map->isMarked(addr)) {
  7975     // a white object ...
  7976     _bit_map->mark(addr);         // ... now grey
  7977     // push on the marking stack (grey set)
  7978     bool simulate_overflow = false;
  7979     NOT_PRODUCT(
  7980       if (CMSMarkStackOverflowALot &&
  7981           _collector->simulate_overflow()) {
  7982         // simulate a stack overflow
  7983         simulate_overflow = true;
  7986     if (simulate_overflow || !_mark_stack->push(obj)) {
  7987       if (_concurrent_precleaning) {
  7988          // During precleaning we can just dirty the appropriate card(s)
  7989          // in the mod union table, thus ensuring that the object remains
  7990          // in the grey set  and continue. In the case of object arrays
  7991          // we need to dirty all of the cards that the object spans,
  7992          // since the rescan of object arrays will be limited to the
  7993          // dirty cards.
  7994          // Note that no one can be intefering with us in this action
  7995          // of dirtying the mod union table, so no locking or atomics
  7996          // are required.
  7997          if (obj->is_objArray()) {
  7998            size_t sz = obj->size();
  7999            HeapWord* end_card_addr = (HeapWord*)round_to(
  8000                                         (intptr_t)(addr+sz), CardTableModRefBS::card_size);
  8001            MemRegion redirty_range = MemRegion(addr, end_card_addr);
  8002            assert(!redirty_range.is_empty(), "Arithmetical tautology");
  8003            _mod_union_table->mark_range(redirty_range);
  8004          } else {
  8005            _mod_union_table->mark(addr);
  8007          _collector->_ser_pmc_preclean_ovflw++;
  8008       } else {
  8009          // During the remark phase, we need to remember this oop
  8010          // in the overflow list.
  8011          _collector->push_on_overflow_list(obj);
  8012          _collector->_ser_pmc_remark_ovflw++;
  8018 Par_PushAndMarkClosure::Par_PushAndMarkClosure(CMSCollector* collector,
  8019                                                MemRegion span,
  8020                                                ReferenceProcessor* rp,
  8021                                                CMSBitMap* bit_map,
  8022                                                OopTaskQueue* work_queue):
  8023   CMSOopClosure(rp),
  8024   _collector(collector),
  8025   _span(span),
  8026   _bit_map(bit_map),
  8027   _work_queue(work_queue)
  8029   assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL");
  8032 void PushAndMarkClosure::do_oop(oop* p)       { PushAndMarkClosure::do_oop_work(p); }
  8033 void PushAndMarkClosure::do_oop(narrowOop* p) { PushAndMarkClosure::do_oop_work(p); }
  8035 // Grey object rescan during second checkpoint phase --
  8036 // the parallel version.
  8037 void Par_PushAndMarkClosure::do_oop(oop obj) {
  8038   // In the assert below, we ignore the mark word because
  8039   // this oop may point to an already visited object that is
  8040   // on the overflow stack (in which case the mark word has
  8041   // been hijacked for chaining into the overflow stack --
  8042   // if this is the last object in the overflow stack then
  8043   // its mark word will be NULL). Because this object may
  8044   // have been subsequently popped off the global overflow
  8045   // stack, and the mark word possibly restored to the prototypical
  8046   // value, by the time we get to examined this failing assert in
  8047   // the debugger, is_oop_or_null(false) may subsequently start
  8048   // to hold.
  8049   assert(obj->is_oop_or_null(true),
  8050          "expected an oop or NULL");
  8051   HeapWord* addr = (HeapWord*)obj;
  8052   // Check if oop points into the CMS generation
  8053   // and is not marked
  8054   if (_span.contains(addr) && !_bit_map->isMarked(addr)) {
  8055     // a white object ...
  8056     // If we manage to "claim" the object, by being the
  8057     // first thread to mark it, then we push it on our
  8058     // marking stack
  8059     if (_bit_map->par_mark(addr)) {     // ... now grey
  8060       // push on work queue (grey set)
  8061       bool simulate_overflow = false;
  8062       NOT_PRODUCT(
  8063         if (CMSMarkStackOverflowALot &&
  8064             _collector->par_simulate_overflow()) {
  8065           // simulate a stack overflow
  8066           simulate_overflow = true;
  8069       if (simulate_overflow || !_work_queue->push(obj)) {
  8070         _collector->par_push_on_overflow_list(obj);
  8071         _collector->_par_pmc_remark_ovflw++; //  imprecise OK: no need to CAS
  8073     } // Else, some other thread got there first
  8077 void Par_PushAndMarkClosure::do_oop(oop* p)       { Par_PushAndMarkClosure::do_oop_work(p); }
  8078 void Par_PushAndMarkClosure::do_oop(narrowOop* p) { Par_PushAndMarkClosure::do_oop_work(p); }
  8080 void CMSPrecleanRefsYieldClosure::do_yield_work() {
  8081   Mutex* bml = _collector->bitMapLock();
  8082   assert_lock_strong(bml);
  8083   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  8084          "CMS thread should hold CMS token");
  8086   bml->unlock();
  8087   ConcurrentMarkSweepThread::desynchronize(true);
  8089   ConcurrentMarkSweepThread::acknowledge_yield_request();
  8091   _collector->stopTimer();
  8092   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  8093   if (PrintCMSStatistics != 0) {
  8094     _collector->incrementYields();
  8096   _collector->icms_wait();
  8098   // See the comment in coordinator_yield()
  8099   for (unsigned i = 0; i < CMSYieldSleepCount &&
  8100                        ConcurrentMarkSweepThread::should_yield() &&
  8101                        !CMSCollector::foregroundGCIsActive(); ++i) {
  8102     os::sleep(Thread::current(), 1, false);
  8103     ConcurrentMarkSweepThread::acknowledge_yield_request();
  8106   ConcurrentMarkSweepThread::synchronize(true);
  8107   bml->lock();
  8109   _collector->startTimer();
  8112 bool CMSPrecleanRefsYieldClosure::should_return() {
  8113   if (ConcurrentMarkSweepThread::should_yield()) {
  8114     do_yield_work();
  8116   return _collector->foregroundGCIsActive();
  8119 void MarkFromDirtyCardsClosure::do_MemRegion(MemRegion mr) {
  8120   assert(((size_t)mr.start())%CardTableModRefBS::card_size_in_words == 0,
  8121          "mr should be aligned to start at a card boundary");
  8122   // We'd like to assert:
  8123   // assert(mr.word_size()%CardTableModRefBS::card_size_in_words == 0,
  8124   //        "mr should be a range of cards");
  8125   // However, that would be too strong in one case -- the last
  8126   // partition ends at _unallocated_block which, in general, can be
  8127   // an arbitrary boundary, not necessarily card aligned.
  8128   if (PrintCMSStatistics != 0) {
  8129     _num_dirty_cards +=
  8130          mr.word_size()/CardTableModRefBS::card_size_in_words;
  8132   _space->object_iterate_mem(mr, &_scan_cl);
  8135 SweepClosure::SweepClosure(CMSCollector* collector,
  8136                            ConcurrentMarkSweepGeneration* g,
  8137                            CMSBitMap* bitMap, bool should_yield) :
  8138   _collector(collector),
  8139   _g(g),
  8140   _sp(g->cmsSpace()),
  8141   _limit(_sp->sweep_limit()),
  8142   _freelistLock(_sp->freelistLock()),
  8143   _bitMap(bitMap),
  8144   _yield(should_yield),
  8145   _inFreeRange(false),           // No free range at beginning of sweep
  8146   _freeRangeInFreeLists(false),  // No free range at beginning of sweep
  8147   _lastFreeRangeCoalesced(false),
  8148   _freeFinger(g->used_region().start())
  8150   NOT_PRODUCT(
  8151     _numObjectsFreed = 0;
  8152     _numWordsFreed   = 0;
  8153     _numObjectsLive = 0;
  8154     _numWordsLive = 0;
  8155     _numObjectsAlreadyFree = 0;
  8156     _numWordsAlreadyFree = 0;
  8157     _last_fc = NULL;
  8159     _sp->initializeIndexedFreeListArrayReturnedBytes();
  8160     _sp->dictionary()->initialize_dict_returned_bytes();
  8162   assert(_limit >= _sp->bottom() && _limit <= _sp->end(),
  8163          "sweep _limit out of bounds");
  8164   if (CMSTraceSweeper) {
  8165     gclog_or_tty->print_cr("\n====================\nStarting new sweep with limit " PTR_FORMAT,
  8166                         _limit);
  8170 void SweepClosure::print_on(outputStream* st) const {
  8171   tty->print_cr("_sp = [" PTR_FORMAT "," PTR_FORMAT ")",
  8172                 _sp->bottom(), _sp->end());
  8173   tty->print_cr("_limit = " PTR_FORMAT, _limit);
  8174   tty->print_cr("_freeFinger = " PTR_FORMAT, _freeFinger);
  8175   NOT_PRODUCT(tty->print_cr("_last_fc = " PTR_FORMAT, _last_fc);)
  8176   tty->print_cr("_inFreeRange = %d, _freeRangeInFreeLists = %d, _lastFreeRangeCoalesced = %d",
  8177                 _inFreeRange, _freeRangeInFreeLists, _lastFreeRangeCoalesced);
  8180 #ifndef PRODUCT
  8181 // Assertion checking only:  no useful work in product mode --
  8182 // however, if any of the flags below become product flags,
  8183 // you may need to review this code to see if it needs to be
  8184 // enabled in product mode.
  8185 SweepClosure::~SweepClosure() {
  8186   assert_lock_strong(_freelistLock);
  8187   assert(_limit >= _sp->bottom() && _limit <= _sp->end(),
  8188          "sweep _limit out of bounds");
  8189   if (inFreeRange()) {
  8190     warning("inFreeRange() should have been reset; dumping state of SweepClosure");
  8191     print();
  8192     ShouldNotReachHere();
  8194   if (Verbose && PrintGC) {
  8195     gclog_or_tty->print("Collected "SIZE_FORMAT" objects, " SIZE_FORMAT " bytes",
  8196                         _numObjectsFreed, _numWordsFreed*sizeof(HeapWord));
  8197     gclog_or_tty->print_cr("\nLive "SIZE_FORMAT" objects,  "
  8198                            SIZE_FORMAT" bytes  "
  8199       "Already free "SIZE_FORMAT" objects, "SIZE_FORMAT" bytes",
  8200       _numObjectsLive, _numWordsLive*sizeof(HeapWord),
  8201       _numObjectsAlreadyFree, _numWordsAlreadyFree*sizeof(HeapWord));
  8202     size_t totalBytes = (_numWordsFreed + _numWordsLive + _numWordsAlreadyFree)
  8203                         * sizeof(HeapWord);
  8204     gclog_or_tty->print_cr("Total sweep: "SIZE_FORMAT" bytes", totalBytes);
  8206     if (PrintCMSStatistics && CMSVerifyReturnedBytes) {
  8207       size_t indexListReturnedBytes = _sp->sumIndexedFreeListArrayReturnedBytes();
  8208       size_t dict_returned_bytes = _sp->dictionary()->sum_dict_returned_bytes();
  8209       size_t returned_bytes = indexListReturnedBytes + dict_returned_bytes;
  8210       gclog_or_tty->print("Returned "SIZE_FORMAT" bytes", returned_bytes);
  8211       gclog_or_tty->print("   Indexed List Returned "SIZE_FORMAT" bytes",
  8212         indexListReturnedBytes);
  8213       gclog_or_tty->print_cr("        Dictionary Returned "SIZE_FORMAT" bytes",
  8214         dict_returned_bytes);
  8217   if (CMSTraceSweeper) {
  8218     gclog_or_tty->print_cr("end of sweep with _limit = " PTR_FORMAT "\n================",
  8219                            _limit);
  8222 #endif  // PRODUCT
  8224 void SweepClosure::initialize_free_range(HeapWord* freeFinger,
  8225     bool freeRangeInFreeLists) {
  8226   if (CMSTraceSweeper) {
  8227     gclog_or_tty->print("---- Start free range at 0x%x with free block (%d)\n",
  8228                freeFinger, freeRangeInFreeLists);
  8230   assert(!inFreeRange(), "Trampling existing free range");
  8231   set_inFreeRange(true);
  8232   set_lastFreeRangeCoalesced(false);
  8234   set_freeFinger(freeFinger);
  8235   set_freeRangeInFreeLists(freeRangeInFreeLists);
  8236   if (CMSTestInFreeList) {
  8237     if (freeRangeInFreeLists) {
  8238       FreeChunk* fc = (FreeChunk*) freeFinger;
  8239       assert(fc->is_free(), "A chunk on the free list should be free.");
  8240       assert(fc->size() > 0, "Free range should have a size");
  8241       assert(_sp->verify_chunk_in_free_list(fc), "Chunk is not in free lists");
  8246 // Note that the sweeper runs concurrently with mutators. Thus,
  8247 // it is possible for direct allocation in this generation to happen
  8248 // in the middle of the sweep. Note that the sweeper also coalesces
  8249 // contiguous free blocks. Thus, unless the sweeper and the allocator
  8250 // synchronize appropriately freshly allocated blocks may get swept up.
  8251 // This is accomplished by the sweeper locking the free lists while
  8252 // it is sweeping. Thus blocks that are determined to be free are
  8253 // indeed free. There is however one additional complication:
  8254 // blocks that have been allocated since the final checkpoint and
  8255 // mark, will not have been marked and so would be treated as
  8256 // unreachable and swept up. To prevent this, the allocator marks
  8257 // the bit map when allocating during the sweep phase. This leads,
  8258 // however, to a further complication -- objects may have been allocated
  8259 // but not yet initialized -- in the sense that the header isn't yet
  8260 // installed. The sweeper can not then determine the size of the block
  8261 // in order to skip over it. To deal with this case, we use a technique
  8262 // (due to Printezis) to encode such uninitialized block sizes in the
  8263 // bit map. Since the bit map uses a bit per every HeapWord, but the
  8264 // CMS generation has a minimum object size of 3 HeapWords, it follows
  8265 // that "normal marks" won't be adjacent in the bit map (there will
  8266 // always be at least two 0 bits between successive 1 bits). We make use
  8267 // of these "unused" bits to represent uninitialized blocks -- the bit
  8268 // corresponding to the start of the uninitialized object and the next
  8269 // bit are both set. Finally, a 1 bit marks the end of the object that
  8270 // started with the two consecutive 1 bits to indicate its potentially
  8271 // uninitialized state.
  8273 size_t SweepClosure::do_blk_careful(HeapWord* addr) {
  8274   FreeChunk* fc = (FreeChunk*)addr;
  8275   size_t res;
  8277   // Check if we are done sweeping. Below we check "addr >= _limit" rather
  8278   // than "addr == _limit" because although _limit was a block boundary when
  8279   // we started the sweep, it may no longer be one because heap expansion
  8280   // may have caused us to coalesce the block ending at the address _limit
  8281   // with a newly expanded chunk (this happens when _limit was set to the
  8282   // previous _end of the space), so we may have stepped past _limit:
  8283   // see the following Zeno-like trail of CRs 6977970, 7008136, 7042740.
  8284   if (addr >= _limit) { // we have swept up to or past the limit: finish up
  8285     assert(_limit >= _sp->bottom() && _limit <= _sp->end(),
  8286            "sweep _limit out of bounds");
  8287     assert(addr < _sp->end(), "addr out of bounds");
  8288     // Flush any free range we might be holding as a single
  8289     // coalesced chunk to the appropriate free list.
  8290     if (inFreeRange()) {
  8291       assert(freeFinger() >= _sp->bottom() && freeFinger() < _limit,
  8292              err_msg("freeFinger() " PTR_FORMAT" is out-of-bounds", freeFinger()));
  8293       flush_cur_free_chunk(freeFinger(),
  8294                            pointer_delta(addr, freeFinger()));
  8295       if (CMSTraceSweeper) {
  8296         gclog_or_tty->print("Sweep: last chunk: ");
  8297         gclog_or_tty->print("put_free_blk 0x%x ("SIZE_FORMAT") "
  8298                    "[coalesced:"SIZE_FORMAT"]\n",
  8299                    freeFinger(), pointer_delta(addr, freeFinger()),
  8300                    lastFreeRangeCoalesced());
  8304     // help the iterator loop finish
  8305     return pointer_delta(_sp->end(), addr);
  8308   assert(addr < _limit, "sweep invariant");
  8309   // check if we should yield
  8310   do_yield_check(addr);
  8311   if (fc->is_free()) {
  8312     // Chunk that is already free
  8313     res = fc->size();
  8314     do_already_free_chunk(fc);
  8315     debug_only(_sp->verifyFreeLists());
  8316     // If we flush the chunk at hand in lookahead_and_flush()
  8317     // and it's coalesced with a preceding chunk, then the
  8318     // process of "mangling" the payload of the coalesced block
  8319     // will cause erasure of the size information from the
  8320     // (erstwhile) header of all the coalesced blocks but the
  8321     // first, so the first disjunct in the assert will not hold
  8322     // in that specific case (in which case the second disjunct
  8323     // will hold).
  8324     assert(res == fc->size() || ((HeapWord*)fc) + res >= _limit,
  8325            "Otherwise the size info doesn't change at this step");
  8326     NOT_PRODUCT(
  8327       _numObjectsAlreadyFree++;
  8328       _numWordsAlreadyFree += res;
  8330     NOT_PRODUCT(_last_fc = fc;)
  8331   } else if (!_bitMap->isMarked(addr)) {
  8332     // Chunk is fresh garbage
  8333     res = do_garbage_chunk(fc);
  8334     debug_only(_sp->verifyFreeLists());
  8335     NOT_PRODUCT(
  8336       _numObjectsFreed++;
  8337       _numWordsFreed += res;
  8339   } else {
  8340     // Chunk that is alive.
  8341     res = do_live_chunk(fc);
  8342     debug_only(_sp->verifyFreeLists());
  8343     NOT_PRODUCT(
  8344         _numObjectsLive++;
  8345         _numWordsLive += res;
  8348   return res;
  8351 // For the smart allocation, record following
  8352 //  split deaths - a free chunk is removed from its free list because
  8353 //      it is being split into two or more chunks.
  8354 //  split birth - a free chunk is being added to its free list because
  8355 //      a larger free chunk has been split and resulted in this free chunk.
  8356 //  coal death - a free chunk is being removed from its free list because
  8357 //      it is being coalesced into a large free chunk.
  8358 //  coal birth - a free chunk is being added to its free list because
  8359 //      it was created when two or more free chunks where coalesced into
  8360 //      this free chunk.
  8361 //
  8362 // These statistics are used to determine the desired number of free
  8363 // chunks of a given size.  The desired number is chosen to be relative
  8364 // to the end of a CMS sweep.  The desired number at the end of a sweep
  8365 // is the
  8366 //      count-at-end-of-previous-sweep (an amount that was enough)
  8367 //              - count-at-beginning-of-current-sweep  (the excess)
  8368 //              + split-births  (gains in this size during interval)
  8369 //              - split-deaths  (demands on this size during interval)
  8370 // where the interval is from the end of one sweep to the end of the
  8371 // next.
  8372 //
  8373 // When sweeping the sweeper maintains an accumulated chunk which is
  8374 // the chunk that is made up of chunks that have been coalesced.  That
  8375 // will be termed the left-hand chunk.  A new chunk of garbage that
  8376 // is being considered for coalescing will be referred to as the
  8377 // right-hand chunk.
  8378 //
  8379 // When making a decision on whether to coalesce a right-hand chunk with
  8380 // the current left-hand chunk, the current count vs. the desired count
  8381 // of the left-hand chunk is considered.  Also if the right-hand chunk
  8382 // is near the large chunk at the end of the heap (see
  8383 // ConcurrentMarkSweepGeneration::isNearLargestChunk()), then the
  8384 // left-hand chunk is coalesced.
  8385 //
  8386 // When making a decision about whether to split a chunk, the desired count
  8387 // vs. the current count of the candidate to be split is also considered.
  8388 // If the candidate is underpopulated (currently fewer chunks than desired)
  8389 // a chunk of an overpopulated (currently more chunks than desired) size may
  8390 // be chosen.  The "hint" associated with a free list, if non-null, points
  8391 // to a free list which may be overpopulated.
  8392 //
  8394 void SweepClosure::do_already_free_chunk(FreeChunk* fc) {
  8395   const size_t size = fc->size();
  8396   // Chunks that cannot be coalesced are not in the
  8397   // free lists.
  8398   if (CMSTestInFreeList && !fc->cantCoalesce()) {
  8399     assert(_sp->verify_chunk_in_free_list(fc),
  8400       "free chunk should be in free lists");
  8402   // a chunk that is already free, should not have been
  8403   // marked in the bit map
  8404   HeapWord* const addr = (HeapWord*) fc;
  8405   assert(!_bitMap->isMarked(addr), "free chunk should be unmarked");
  8406   // Verify that the bit map has no bits marked between
  8407   // addr and purported end of this block.
  8408   _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size);
  8410   // Some chunks cannot be coalesced under any circumstances.
  8411   // See the definition of cantCoalesce().
  8412   if (!fc->cantCoalesce()) {
  8413     // This chunk can potentially be coalesced.
  8414     if (_sp->adaptive_freelists()) {
  8415       // All the work is done in
  8416       do_post_free_or_garbage_chunk(fc, size);
  8417     } else {  // Not adaptive free lists
  8418       // this is a free chunk that can potentially be coalesced by the sweeper;
  8419       if (!inFreeRange()) {
  8420         // if the next chunk is a free block that can't be coalesced
  8421         // it doesn't make sense to remove this chunk from the free lists
  8422         FreeChunk* nextChunk = (FreeChunk*)(addr + size);
  8423         assert((HeapWord*)nextChunk <= _sp->end(), "Chunk size out of bounds?");
  8424         if ((HeapWord*)nextChunk < _sp->end() &&     // There is another free chunk to the right ...
  8425             nextChunk->is_free()               &&     // ... which is free...
  8426             nextChunk->cantCoalesce()) {             // ... but can't be coalesced
  8427           // nothing to do
  8428         } else {
  8429           // Potentially the start of a new free range:
  8430           // Don't eagerly remove it from the free lists.
  8431           // No need to remove it if it will just be put
  8432           // back again.  (Also from a pragmatic point of view
  8433           // if it is a free block in a region that is beyond
  8434           // any allocated blocks, an assertion will fail)
  8435           // Remember the start of a free run.
  8436           initialize_free_range(addr, true);
  8437           // end - can coalesce with next chunk
  8439       } else {
  8440         // the midst of a free range, we are coalescing
  8441         print_free_block_coalesced(fc);
  8442         if (CMSTraceSweeper) {
  8443           gclog_or_tty->print("  -- pick up free block 0x%x (%d)\n", fc, size);
  8445         // remove it from the free lists
  8446         _sp->removeFreeChunkFromFreeLists(fc);
  8447         set_lastFreeRangeCoalesced(true);
  8448         // If the chunk is being coalesced and the current free range is
  8449         // in the free lists, remove the current free range so that it
  8450         // will be returned to the free lists in its entirety - all
  8451         // the coalesced pieces included.
  8452         if (freeRangeInFreeLists()) {
  8453           FreeChunk* ffc = (FreeChunk*) freeFinger();
  8454           assert(ffc->size() == pointer_delta(addr, freeFinger()),
  8455             "Size of free range is inconsistent with chunk size.");
  8456           if (CMSTestInFreeList) {
  8457             assert(_sp->verify_chunk_in_free_list(ffc),
  8458               "free range is not in free lists");
  8460           _sp->removeFreeChunkFromFreeLists(ffc);
  8461           set_freeRangeInFreeLists(false);
  8465     // Note that if the chunk is not coalescable (the else arm
  8466     // below), we unconditionally flush, without needing to do
  8467     // a "lookahead," as we do below.
  8468     if (inFreeRange()) lookahead_and_flush(fc, size);
  8469   } else {
  8470     // Code path common to both original and adaptive free lists.
  8472     // cant coalesce with previous block; this should be treated
  8473     // as the end of a free run if any
  8474     if (inFreeRange()) {
  8475       // we kicked some butt; time to pick up the garbage
  8476       assert(freeFinger() < addr, "freeFinger points too high");
  8477       flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger()));
  8479     // else, nothing to do, just continue
  8483 size_t SweepClosure::do_garbage_chunk(FreeChunk* fc) {
  8484   // This is a chunk of garbage.  It is not in any free list.
  8485   // Add it to a free list or let it possibly be coalesced into
  8486   // a larger chunk.
  8487   HeapWord* const addr = (HeapWord*) fc;
  8488   const size_t size = CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size());
  8490   if (_sp->adaptive_freelists()) {
  8491     // Verify that the bit map has no bits marked between
  8492     // addr and purported end of just dead object.
  8493     _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size);
  8495     do_post_free_or_garbage_chunk(fc, size);
  8496   } else {
  8497     if (!inFreeRange()) {
  8498       // start of a new free range
  8499       assert(size > 0, "A free range should have a size");
  8500       initialize_free_range(addr, false);
  8501     } else {
  8502       // this will be swept up when we hit the end of the
  8503       // free range
  8504       if (CMSTraceSweeper) {
  8505         gclog_or_tty->print("  -- pick up garbage 0x%x (%d) \n", fc, size);
  8507       // If the chunk is being coalesced and the current free range is
  8508       // in the free lists, remove the current free range so that it
  8509       // will be returned to the free lists in its entirety - all
  8510       // the coalesced pieces included.
  8511       if (freeRangeInFreeLists()) {
  8512         FreeChunk* ffc = (FreeChunk*)freeFinger();
  8513         assert(ffc->size() == pointer_delta(addr, freeFinger()),
  8514           "Size of free range is inconsistent with chunk size.");
  8515         if (CMSTestInFreeList) {
  8516           assert(_sp->verify_chunk_in_free_list(ffc),
  8517             "free range is not in free lists");
  8519         _sp->removeFreeChunkFromFreeLists(ffc);
  8520         set_freeRangeInFreeLists(false);
  8522       set_lastFreeRangeCoalesced(true);
  8524     // this will be swept up when we hit the end of the free range
  8526     // Verify that the bit map has no bits marked between
  8527     // addr and purported end of just dead object.
  8528     _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size);
  8530   assert(_limit >= addr + size,
  8531          "A freshly garbage chunk can't possibly straddle over _limit");
  8532   if (inFreeRange()) lookahead_and_flush(fc, size);
  8533   return size;
  8536 size_t SweepClosure::do_live_chunk(FreeChunk* fc) {
  8537   HeapWord* addr = (HeapWord*) fc;
  8538   // The sweeper has just found a live object. Return any accumulated
  8539   // left hand chunk to the free lists.
  8540   if (inFreeRange()) {
  8541     assert(freeFinger() < addr, "freeFinger points too high");
  8542     flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger()));
  8545   // This object is live: we'd normally expect this to be
  8546   // an oop, and like to assert the following:
  8547   // assert(oop(addr)->is_oop(), "live block should be an oop");
  8548   // However, as we commented above, this may be an object whose
  8549   // header hasn't yet been initialized.
  8550   size_t size;
  8551   assert(_bitMap->isMarked(addr), "Tautology for this control point");
  8552   if (_bitMap->isMarked(addr + 1)) {
  8553     // Determine the size from the bit map, rather than trying to
  8554     // compute it from the object header.
  8555     HeapWord* nextOneAddr = _bitMap->getNextMarkedWordAddress(addr + 2);
  8556     size = pointer_delta(nextOneAddr + 1, addr);
  8557     assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
  8558            "alignment problem");
  8560 #ifdef ASSERT
  8561       if (oop(addr)->klass_or_null() != NULL) {
  8562         // Ignore mark word because we are running concurrent with mutators
  8563         assert(oop(addr)->is_oop(true), "live block should be an oop");
  8564         assert(size ==
  8565                CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size()),
  8566                "P-mark and computed size do not agree");
  8568 #endif
  8570   } else {
  8571     // This should be an initialized object that's alive.
  8572     assert(oop(addr)->klass_or_null() != NULL,
  8573            "Should be an initialized object");
  8574     // Ignore mark word because we are running concurrent with mutators
  8575     assert(oop(addr)->is_oop(true), "live block should be an oop");
  8576     // Verify that the bit map has no bits marked between
  8577     // addr and purported end of this block.
  8578     size = CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size());
  8579     assert(size >= 3, "Necessary for Printezis marks to work");
  8580     assert(!_bitMap->isMarked(addr+1), "Tautology for this control point");
  8581     DEBUG_ONLY(_bitMap->verifyNoOneBitsInRange(addr+2, addr+size);)
  8583   return size;
  8586 void SweepClosure::do_post_free_or_garbage_chunk(FreeChunk* fc,
  8587                                                  size_t chunkSize) {
  8588   // do_post_free_or_garbage_chunk() should only be called in the case
  8589   // of the adaptive free list allocator.
  8590   const bool fcInFreeLists = fc->is_free();
  8591   assert(_sp->adaptive_freelists(), "Should only be used in this case.");
  8592   assert((HeapWord*)fc <= _limit, "sweep invariant");
  8593   if (CMSTestInFreeList && fcInFreeLists) {
  8594     assert(_sp->verify_chunk_in_free_list(fc), "free chunk is not in free lists");
  8597   if (CMSTraceSweeper) {
  8598     gclog_or_tty->print_cr("  -- pick up another chunk at 0x%x (%d)", fc, chunkSize);
  8601   HeapWord* const fc_addr = (HeapWord*) fc;
  8603   bool coalesce;
  8604   const size_t left  = pointer_delta(fc_addr, freeFinger());
  8605   const size_t right = chunkSize;
  8606   switch (FLSCoalescePolicy) {
  8607     // numeric value forms a coalition aggressiveness metric
  8608     case 0:  { // never coalesce
  8609       coalesce = false;
  8610       break;
  8612     case 1: { // coalesce if left & right chunks on overpopulated lists
  8613       coalesce = _sp->coalOverPopulated(left) &&
  8614                  _sp->coalOverPopulated(right);
  8615       break;
  8617     case 2: { // coalesce if left chunk on overpopulated list (default)
  8618       coalesce = _sp->coalOverPopulated(left);
  8619       break;
  8621     case 3: { // coalesce if left OR right chunk on overpopulated list
  8622       coalesce = _sp->coalOverPopulated(left) ||
  8623                  _sp->coalOverPopulated(right);
  8624       break;
  8626     case 4: { // always coalesce
  8627       coalesce = true;
  8628       break;
  8630     default:
  8631      ShouldNotReachHere();
  8634   // Should the current free range be coalesced?
  8635   // If the chunk is in a free range and either we decided to coalesce above
  8636   // or the chunk is near the large block at the end of the heap
  8637   // (isNearLargestChunk() returns true), then coalesce this chunk.
  8638   const bool doCoalesce = inFreeRange()
  8639                           && (coalesce || _g->isNearLargestChunk(fc_addr));
  8640   if (doCoalesce) {
  8641     // Coalesce the current free range on the left with the new
  8642     // chunk on the right.  If either is on a free list,
  8643     // it must be removed from the list and stashed in the closure.
  8644     if (freeRangeInFreeLists()) {
  8645       FreeChunk* const ffc = (FreeChunk*)freeFinger();
  8646       assert(ffc->size() == pointer_delta(fc_addr, freeFinger()),
  8647         "Size of free range is inconsistent with chunk size.");
  8648       if (CMSTestInFreeList) {
  8649         assert(_sp->verify_chunk_in_free_list(ffc),
  8650           "Chunk is not in free lists");
  8652       _sp->coalDeath(ffc->size());
  8653       _sp->removeFreeChunkFromFreeLists(ffc);
  8654       set_freeRangeInFreeLists(false);
  8656     if (fcInFreeLists) {
  8657       _sp->coalDeath(chunkSize);
  8658       assert(fc->size() == chunkSize,
  8659         "The chunk has the wrong size or is not in the free lists");
  8660       _sp->removeFreeChunkFromFreeLists(fc);
  8662     set_lastFreeRangeCoalesced(true);
  8663     print_free_block_coalesced(fc);
  8664   } else {  // not in a free range and/or should not coalesce
  8665     // Return the current free range and start a new one.
  8666     if (inFreeRange()) {
  8667       // In a free range but cannot coalesce with the right hand chunk.
  8668       // Put the current free range into the free lists.
  8669       flush_cur_free_chunk(freeFinger(),
  8670                            pointer_delta(fc_addr, freeFinger()));
  8672     // Set up for new free range.  Pass along whether the right hand
  8673     // chunk is in the free lists.
  8674     initialize_free_range((HeapWord*)fc, fcInFreeLists);
  8678 // Lookahead flush:
  8679 // If we are tracking a free range, and this is the last chunk that
  8680 // we'll look at because its end crosses past _limit, we'll preemptively
  8681 // flush it along with any free range we may be holding on to. Note that
  8682 // this can be the case only for an already free or freshly garbage
  8683 // chunk. If this block is an object, it can never straddle
  8684 // over _limit. The "straddling" occurs when _limit is set at
  8685 // the previous end of the space when this cycle started, and
  8686 // a subsequent heap expansion caused the previously co-terminal
  8687 // free block to be coalesced with the newly expanded portion,
  8688 // thus rendering _limit a non-block-boundary making it dangerous
  8689 // for the sweeper to step over and examine.
  8690 void SweepClosure::lookahead_and_flush(FreeChunk* fc, size_t chunk_size) {
  8691   assert(inFreeRange(), "Should only be called if currently in a free range.");
  8692   HeapWord* const eob = ((HeapWord*)fc) + chunk_size;
  8693   assert(_sp->used_region().contains(eob - 1),
  8694          err_msg("eob = " PTR_FORMAT " eob-1 = " PTR_FORMAT " _limit = " PTR_FORMAT
  8695                  " out of bounds wrt _sp = [" PTR_FORMAT "," PTR_FORMAT ")"
  8696                  " when examining fc = " PTR_FORMAT "(" SIZE_FORMAT ")",
  8697                  eob, eob-1, _limit, _sp->bottom(), _sp->end(), fc, chunk_size));
  8698   if (eob >= _limit) {
  8699     assert(eob == _limit || fc->is_free(), "Only a free chunk should allow us to cross over the limit");
  8700     if (CMSTraceSweeper) {
  8701       gclog_or_tty->print_cr("_limit " PTR_FORMAT " reached or crossed by block "
  8702                              "[" PTR_FORMAT "," PTR_FORMAT ") in space "
  8703                              "[" PTR_FORMAT "," PTR_FORMAT ")",
  8704                              _limit, fc, eob, _sp->bottom(), _sp->end());
  8706     // Return the storage we are tracking back into the free lists.
  8707     if (CMSTraceSweeper) {
  8708       gclog_or_tty->print_cr("Flushing ... ");
  8710     assert(freeFinger() < eob, "Error");
  8711     flush_cur_free_chunk( freeFinger(), pointer_delta(eob, freeFinger()));
  8715 void SweepClosure::flush_cur_free_chunk(HeapWord* chunk, size_t size) {
  8716   assert(inFreeRange(), "Should only be called if currently in a free range.");
  8717   assert(size > 0,
  8718     "A zero sized chunk cannot be added to the free lists.");
  8719   if (!freeRangeInFreeLists()) {
  8720     if (CMSTestInFreeList) {
  8721       FreeChunk* fc = (FreeChunk*) chunk;
  8722       fc->set_size(size);
  8723       assert(!_sp->verify_chunk_in_free_list(fc),
  8724         "chunk should not be in free lists yet");
  8726     if (CMSTraceSweeper) {
  8727       gclog_or_tty->print_cr(" -- add free block 0x%x (%d) to free lists",
  8728                     chunk, size);
  8730     // A new free range is going to be starting.  The current
  8731     // free range has not been added to the free lists yet or
  8732     // was removed so add it back.
  8733     // If the current free range was coalesced, then the death
  8734     // of the free range was recorded.  Record a birth now.
  8735     if (lastFreeRangeCoalesced()) {
  8736       _sp->coalBirth(size);
  8738     _sp->addChunkAndRepairOffsetTable(chunk, size,
  8739             lastFreeRangeCoalesced());
  8740   } else if (CMSTraceSweeper) {
  8741     gclog_or_tty->print_cr("Already in free list: nothing to flush");
  8743   set_inFreeRange(false);
  8744   set_freeRangeInFreeLists(false);
  8747 // We take a break if we've been at this for a while,
  8748 // so as to avoid monopolizing the locks involved.
  8749 void SweepClosure::do_yield_work(HeapWord* addr) {
  8750   // Return current free chunk being used for coalescing (if any)
  8751   // to the appropriate freelist.  After yielding, the next
  8752   // free block encountered will start a coalescing range of
  8753   // free blocks.  If the next free block is adjacent to the
  8754   // chunk just flushed, they will need to wait for the next
  8755   // sweep to be coalesced.
  8756   if (inFreeRange()) {
  8757     flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger()));
  8760   // First give up the locks, then yield, then re-lock.
  8761   // We should probably use a constructor/destructor idiom to
  8762   // do this unlock/lock or modify the MutexUnlocker class to
  8763   // serve our purpose. XXX
  8764   assert_lock_strong(_bitMap->lock());
  8765   assert_lock_strong(_freelistLock);
  8766   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  8767          "CMS thread should hold CMS token");
  8768   _bitMap->lock()->unlock();
  8769   _freelistLock->unlock();
  8770   ConcurrentMarkSweepThread::desynchronize(true);
  8771   ConcurrentMarkSweepThread::acknowledge_yield_request();
  8772   _collector->stopTimer();
  8773   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  8774   if (PrintCMSStatistics != 0) {
  8775     _collector->incrementYields();
  8777   _collector->icms_wait();
  8779   // See the comment in coordinator_yield()
  8780   for (unsigned i = 0; i < CMSYieldSleepCount &&
  8781                        ConcurrentMarkSweepThread::should_yield() &&
  8782                        !CMSCollector::foregroundGCIsActive(); ++i) {
  8783     os::sleep(Thread::current(), 1, false);
  8784     ConcurrentMarkSweepThread::acknowledge_yield_request();
  8787   ConcurrentMarkSweepThread::synchronize(true);
  8788   _freelistLock->lock();
  8789   _bitMap->lock()->lock_without_safepoint_check();
  8790   _collector->startTimer();
  8793 #ifndef PRODUCT
  8794 // This is actually very useful in a product build if it can
  8795 // be called from the debugger.  Compile it into the product
  8796 // as needed.
  8797 bool debug_verify_chunk_in_free_list(FreeChunk* fc) {
  8798   return debug_cms_space->verify_chunk_in_free_list(fc);
  8800 #endif
  8802 void SweepClosure::print_free_block_coalesced(FreeChunk* fc) const {
  8803   if (CMSTraceSweeper) {
  8804     gclog_or_tty->print_cr("Sweep:coal_free_blk " PTR_FORMAT " (" SIZE_FORMAT ")",
  8805                            fc, fc->size());
  8809 // CMSIsAliveClosure
  8810 bool CMSIsAliveClosure::do_object_b(oop obj) {
  8811   HeapWord* addr = (HeapWord*)obj;
  8812   return addr != NULL &&
  8813          (!_span.contains(addr) || _bit_map->isMarked(addr));
  8817 CMSKeepAliveClosure::CMSKeepAliveClosure( CMSCollector* collector,
  8818                       MemRegion span,
  8819                       CMSBitMap* bit_map, CMSMarkStack* mark_stack,
  8820                       bool cpc):
  8821   _collector(collector),
  8822   _span(span),
  8823   _bit_map(bit_map),
  8824   _mark_stack(mark_stack),
  8825   _concurrent_precleaning(cpc) {
  8826   assert(!_span.is_empty(), "Empty span could spell trouble");
  8830 // CMSKeepAliveClosure: the serial version
  8831 void CMSKeepAliveClosure::do_oop(oop obj) {
  8832   HeapWord* addr = (HeapWord*)obj;
  8833   if (_span.contains(addr) &&
  8834       !_bit_map->isMarked(addr)) {
  8835     _bit_map->mark(addr);
  8836     bool simulate_overflow = false;
  8837     NOT_PRODUCT(
  8838       if (CMSMarkStackOverflowALot &&
  8839           _collector->simulate_overflow()) {
  8840         // simulate a stack overflow
  8841         simulate_overflow = true;
  8844     if (simulate_overflow || !_mark_stack->push(obj)) {
  8845       if (_concurrent_precleaning) {
  8846         // We dirty the overflown object and let the remark
  8847         // phase deal with it.
  8848         assert(_collector->overflow_list_is_empty(), "Error");
  8849         // In the case of object arrays, we need to dirty all of
  8850         // the cards that the object spans. No locking or atomics
  8851         // are needed since no one else can be mutating the mod union
  8852         // table.
  8853         if (obj->is_objArray()) {
  8854           size_t sz = obj->size();
  8855           HeapWord* end_card_addr =
  8856             (HeapWord*)round_to((intptr_t)(addr+sz), CardTableModRefBS::card_size);
  8857           MemRegion redirty_range = MemRegion(addr, end_card_addr);
  8858           assert(!redirty_range.is_empty(), "Arithmetical tautology");
  8859           _collector->_modUnionTable.mark_range(redirty_range);
  8860         } else {
  8861           _collector->_modUnionTable.mark(addr);
  8863         _collector->_ser_kac_preclean_ovflw++;
  8864       } else {
  8865         _collector->push_on_overflow_list(obj);
  8866         _collector->_ser_kac_ovflw++;
  8872 void CMSKeepAliveClosure::do_oop(oop* p)       { CMSKeepAliveClosure::do_oop_work(p); }
  8873 void CMSKeepAliveClosure::do_oop(narrowOop* p) { CMSKeepAliveClosure::do_oop_work(p); }
  8875 // CMSParKeepAliveClosure: a parallel version of the above.
  8876 // The work queues are private to each closure (thread),
  8877 // but (may be) available for stealing by other threads.
  8878 void CMSParKeepAliveClosure::do_oop(oop obj) {
  8879   HeapWord* addr = (HeapWord*)obj;
  8880   if (_span.contains(addr) &&
  8881       !_bit_map->isMarked(addr)) {
  8882     // In general, during recursive tracing, several threads
  8883     // may be concurrently getting here; the first one to
  8884     // "tag" it, claims it.
  8885     if (_bit_map->par_mark(addr)) {
  8886       bool res = _work_queue->push(obj);
  8887       assert(res, "Low water mark should be much less than capacity");
  8888       // Do a recursive trim in the hope that this will keep
  8889       // stack usage lower, but leave some oops for potential stealers
  8890       trim_queue(_low_water_mark);
  8891     } // Else, another thread got there first
  8895 void CMSParKeepAliveClosure::do_oop(oop* p)       { CMSParKeepAliveClosure::do_oop_work(p); }
  8896 void CMSParKeepAliveClosure::do_oop(narrowOop* p) { CMSParKeepAliveClosure::do_oop_work(p); }
  8898 void CMSParKeepAliveClosure::trim_queue(uint max) {
  8899   while (_work_queue->size() > max) {
  8900     oop new_oop;
  8901     if (_work_queue->pop_local(new_oop)) {
  8902       assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop");
  8903       assert(_bit_map->isMarked((HeapWord*)new_oop),
  8904              "no white objects on this stack!");
  8905       assert(_span.contains((HeapWord*)new_oop), "Out of bounds oop");
  8906       // iterate over the oops in this oop, marking and pushing
  8907       // the ones in CMS heap (i.e. in _span).
  8908       new_oop->oop_iterate(&_mark_and_push);
  8913 CMSInnerParMarkAndPushClosure::CMSInnerParMarkAndPushClosure(
  8914                                 CMSCollector* collector,
  8915                                 MemRegion span, CMSBitMap* bit_map,
  8916                                 OopTaskQueue* work_queue):
  8917   _collector(collector),
  8918   _span(span),
  8919   _bit_map(bit_map),
  8920   _work_queue(work_queue) { }
  8922 void CMSInnerParMarkAndPushClosure::do_oop(oop obj) {
  8923   HeapWord* addr = (HeapWord*)obj;
  8924   if (_span.contains(addr) &&
  8925       !_bit_map->isMarked(addr)) {
  8926     if (_bit_map->par_mark(addr)) {
  8927       bool simulate_overflow = false;
  8928       NOT_PRODUCT(
  8929         if (CMSMarkStackOverflowALot &&
  8930             _collector->par_simulate_overflow()) {
  8931           // simulate a stack overflow
  8932           simulate_overflow = true;
  8935       if (simulate_overflow || !_work_queue->push(obj)) {
  8936         _collector->par_push_on_overflow_list(obj);
  8937         _collector->_par_kac_ovflw++;
  8939     } // Else another thread got there already
  8943 void CMSInnerParMarkAndPushClosure::do_oop(oop* p)       { CMSInnerParMarkAndPushClosure::do_oop_work(p); }
  8944 void CMSInnerParMarkAndPushClosure::do_oop(narrowOop* p) { CMSInnerParMarkAndPushClosure::do_oop_work(p); }
  8946 //////////////////////////////////////////////////////////////////
  8947 //  CMSExpansionCause                /////////////////////////////
  8948 //////////////////////////////////////////////////////////////////
  8949 const char* CMSExpansionCause::to_string(CMSExpansionCause::Cause cause) {
  8950   switch (cause) {
  8951     case _no_expansion:
  8952       return "No expansion";
  8953     case _satisfy_free_ratio:
  8954       return "Free ratio";
  8955     case _satisfy_promotion:
  8956       return "Satisfy promotion";
  8957     case _satisfy_allocation:
  8958       return "allocation";
  8959     case _allocate_par_lab:
  8960       return "Par LAB";
  8961     case _allocate_par_spooling_space:
  8962       return "Par Spooling Space";
  8963     case _adaptive_size_policy:
  8964       return "Ergonomics";
  8965     default:
  8966       return "unknown";
  8970 void CMSDrainMarkingStackClosure::do_void() {
  8971   // the max number to take from overflow list at a time
  8972   const size_t num = _mark_stack->capacity()/4;
  8973   assert(!_concurrent_precleaning || _collector->overflow_list_is_empty(),
  8974          "Overflow list should be NULL during concurrent phases");
  8975   while (!_mark_stack->isEmpty() ||
  8976          // if stack is empty, check the overflow list
  8977          _collector->take_from_overflow_list(num, _mark_stack)) {
  8978     oop obj = _mark_stack->pop();
  8979     HeapWord* addr = (HeapWord*)obj;
  8980     assert(_span.contains(addr), "Should be within span");
  8981     assert(_bit_map->isMarked(addr), "Should be marked");
  8982     assert(obj->is_oop(), "Should be an oop");
  8983     obj->oop_iterate(_keep_alive);
  8987 void CMSParDrainMarkingStackClosure::do_void() {
  8988   // drain queue
  8989   trim_queue(0);
  8992 // Trim our work_queue so its length is below max at return
  8993 void CMSParDrainMarkingStackClosure::trim_queue(uint max) {
  8994   while (_work_queue->size() > max) {
  8995     oop new_oop;
  8996     if (_work_queue->pop_local(new_oop)) {
  8997       assert(new_oop->is_oop(), "Expected an oop");
  8998       assert(_bit_map->isMarked((HeapWord*)new_oop),
  8999              "no white objects on this stack!");
  9000       assert(_span.contains((HeapWord*)new_oop), "Out of bounds oop");
  9001       // iterate over the oops in this oop, marking and pushing
  9002       // the ones in CMS heap (i.e. in _span).
  9003       new_oop->oop_iterate(&_mark_and_push);
  9008 ////////////////////////////////////////////////////////////////////
  9009 // Support for Marking Stack Overflow list handling and related code
  9010 ////////////////////////////////////////////////////////////////////
  9011 // Much of the following code is similar in shape and spirit to the
  9012 // code used in ParNewGC. We should try and share that code
  9013 // as much as possible in the future.
  9015 #ifndef PRODUCT
  9016 // Debugging support for CMSStackOverflowALot
  9018 // It's OK to call this multi-threaded;  the worst thing
  9019 // that can happen is that we'll get a bunch of closely
  9020 // spaced simulated oveflows, but that's OK, in fact
  9021 // probably good as it would exercise the overflow code
  9022 // under contention.
  9023 bool CMSCollector::simulate_overflow() {
  9024   if (_overflow_counter-- <= 0) { // just being defensive
  9025     _overflow_counter = CMSMarkStackOverflowInterval;
  9026     return true;
  9027   } else {
  9028     return false;
  9032 bool CMSCollector::par_simulate_overflow() {
  9033   return simulate_overflow();
  9035 #endif
  9037 // Single-threaded
  9038 bool CMSCollector::take_from_overflow_list(size_t num, CMSMarkStack* stack) {
  9039   assert(stack->isEmpty(), "Expected precondition");
  9040   assert(stack->capacity() > num, "Shouldn't bite more than can chew");
  9041   size_t i = num;
  9042   oop  cur = _overflow_list;
  9043   const markOop proto = markOopDesc::prototype();
  9044   NOT_PRODUCT(ssize_t n = 0;)
  9045   for (oop next; i > 0 && cur != NULL; cur = next, i--) {
  9046     next = oop(cur->mark());
  9047     cur->set_mark(proto);   // until proven otherwise
  9048     assert(cur->is_oop(), "Should be an oop");
  9049     bool res = stack->push(cur);
  9050     assert(res, "Bit off more than can chew?");
  9051     NOT_PRODUCT(n++;)
  9053   _overflow_list = cur;
  9054 #ifndef PRODUCT
  9055   assert(_num_par_pushes >= n, "Too many pops?");
  9056   _num_par_pushes -=n;
  9057 #endif
  9058   return !stack->isEmpty();
  9061 #define BUSY  (cast_to_oop<intptr_t>(0x1aff1aff))
  9062 // (MT-safe) Get a prefix of at most "num" from the list.
  9063 // The overflow list is chained through the mark word of
  9064 // each object in the list. We fetch the entire list,
  9065 // break off a prefix of the right size and return the
  9066 // remainder. If other threads try to take objects from
  9067 // the overflow list at that time, they will wait for
  9068 // some time to see if data becomes available. If (and
  9069 // only if) another thread places one or more object(s)
  9070 // on the global list before we have returned the suffix
  9071 // to the global list, we will walk down our local list
  9072 // to find its end and append the global list to
  9073 // our suffix before returning it. This suffix walk can
  9074 // prove to be expensive (quadratic in the amount of traffic)
  9075 // when there are many objects in the overflow list and
  9076 // there is much producer-consumer contention on the list.
  9077 // *NOTE*: The overflow list manipulation code here and
  9078 // in ParNewGeneration:: are very similar in shape,
  9079 // except that in the ParNew case we use the old (from/eden)
  9080 // copy of the object to thread the list via its klass word.
  9081 // Because of the common code, if you make any changes in
  9082 // the code below, please check the ParNew version to see if
  9083 // similar changes might be needed.
  9084 // CR 6797058 has been filed to consolidate the common code.
  9085 bool CMSCollector::par_take_from_overflow_list(size_t num,
  9086                                                OopTaskQueue* work_q,
  9087                                                int no_of_gc_threads) {
  9088   assert(work_q->size() == 0, "First empty local work queue");
  9089   assert(num < work_q->max_elems(), "Can't bite more than we can chew");
  9090   if (_overflow_list == NULL) {
  9091     return false;
  9093   // Grab the entire list; we'll put back a suffix
  9094   oop prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list));
  9095   Thread* tid = Thread::current();
  9096   // Before "no_of_gc_threads" was introduced CMSOverflowSpinCount was
  9097   // set to ParallelGCThreads.
  9098   size_t CMSOverflowSpinCount = (size_t) no_of_gc_threads; // was ParallelGCThreads;
  9099   size_t sleep_time_millis = MAX2((size_t)1, num/100);
  9100   // If the list is busy, we spin for a short while,
  9101   // sleeping between attempts to get the list.
  9102   for (size_t spin = 0; prefix == BUSY && spin < CMSOverflowSpinCount; spin++) {
  9103     os::sleep(tid, sleep_time_millis, false);
  9104     if (_overflow_list == NULL) {
  9105       // Nothing left to take
  9106       return false;
  9107     } else if (_overflow_list != BUSY) {
  9108       // Try and grab the prefix
  9109       prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list));
  9112   // If the list was found to be empty, or we spun long
  9113   // enough, we give up and return empty-handed. If we leave
  9114   // the list in the BUSY state below, it must be the case that
  9115   // some other thread holds the overflow list and will set it
  9116   // to a non-BUSY state in the future.
  9117   if (prefix == NULL || prefix == BUSY) {
  9118      // Nothing to take or waited long enough
  9119      if (prefix == NULL) {
  9120        // Write back the NULL in case we overwrote it with BUSY above
  9121        // and it is still the same value.
  9122        (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY);
  9124      return false;
  9126   assert(prefix != NULL && prefix != BUSY, "Error");
  9127   size_t i = num;
  9128   oop cur = prefix;
  9129   // Walk down the first "num" objects, unless we reach the end.
  9130   for (; i > 1 && cur->mark() != NULL; cur = oop(cur->mark()), i--);
  9131   if (cur->mark() == NULL) {
  9132     // We have "num" or fewer elements in the list, so there
  9133     // is nothing to return to the global list.
  9134     // Write back the NULL in lieu of the BUSY we wrote
  9135     // above, if it is still the same value.
  9136     if (_overflow_list == BUSY) {
  9137       (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY);
  9139   } else {
  9140     // Chop off the suffix and rerturn it to the global list.
  9141     assert(cur->mark() != BUSY, "Error");
  9142     oop suffix_head = cur->mark(); // suffix will be put back on global list
  9143     cur->set_mark(NULL);           // break off suffix
  9144     // It's possible that the list is still in the empty(busy) state
  9145     // we left it in a short while ago; in that case we may be
  9146     // able to place back the suffix without incurring the cost
  9147     // of a walk down the list.
  9148     oop observed_overflow_list = _overflow_list;
  9149     oop cur_overflow_list = observed_overflow_list;
  9150     bool attached = false;
  9151     while (observed_overflow_list == BUSY || observed_overflow_list == NULL) {
  9152       observed_overflow_list =
  9153         (oop) Atomic::cmpxchg_ptr(suffix_head, &_overflow_list, cur_overflow_list);
  9154       if (cur_overflow_list == observed_overflow_list) {
  9155         attached = true;
  9156         break;
  9157       } else cur_overflow_list = observed_overflow_list;
  9159     if (!attached) {
  9160       // Too bad, someone else sneaked in (at least) an element; we'll need
  9161       // to do a splice. Find tail of suffix so we can prepend suffix to global
  9162       // list.
  9163       for (cur = suffix_head; cur->mark() != NULL; cur = (oop)(cur->mark()));
  9164       oop suffix_tail = cur;
  9165       assert(suffix_tail != NULL && suffix_tail->mark() == NULL,
  9166              "Tautology");
  9167       observed_overflow_list = _overflow_list;
  9168       do {
  9169         cur_overflow_list = observed_overflow_list;
  9170         if (cur_overflow_list != BUSY) {
  9171           // Do the splice ...
  9172           suffix_tail->set_mark(markOop(cur_overflow_list));
  9173         } else { // cur_overflow_list == BUSY
  9174           suffix_tail->set_mark(NULL);
  9176         // ... and try to place spliced list back on overflow_list ...
  9177         observed_overflow_list =
  9178           (oop) Atomic::cmpxchg_ptr(suffix_head, &_overflow_list, cur_overflow_list);
  9179       } while (cur_overflow_list != observed_overflow_list);
  9180       // ... until we have succeeded in doing so.
  9184   // Push the prefix elements on work_q
  9185   assert(prefix != NULL, "control point invariant");
  9186   const markOop proto = markOopDesc::prototype();
  9187   oop next;
  9188   NOT_PRODUCT(ssize_t n = 0;)
  9189   for (cur = prefix; cur != NULL; cur = next) {
  9190     next = oop(cur->mark());
  9191     cur->set_mark(proto);   // until proven otherwise
  9192     assert(cur->is_oop(), "Should be an oop");
  9193     bool res = work_q->push(cur);
  9194     assert(res, "Bit off more than we can chew?");
  9195     NOT_PRODUCT(n++;)
  9197 #ifndef PRODUCT
  9198   assert(_num_par_pushes >= n, "Too many pops?");
  9199   Atomic::add_ptr(-(intptr_t)n, &_num_par_pushes);
  9200 #endif
  9201   return true;
  9204 // Single-threaded
  9205 void CMSCollector::push_on_overflow_list(oop p) {
  9206   NOT_PRODUCT(_num_par_pushes++;)
  9207   assert(p->is_oop(), "Not an oop");
  9208   preserve_mark_if_necessary(p);
  9209   p->set_mark((markOop)_overflow_list);
  9210   _overflow_list = p;
  9213 // Multi-threaded; use CAS to prepend to overflow list
  9214 void CMSCollector::par_push_on_overflow_list(oop p) {
  9215   NOT_PRODUCT(Atomic::inc_ptr(&_num_par_pushes);)
  9216   assert(p->is_oop(), "Not an oop");
  9217   par_preserve_mark_if_necessary(p);
  9218   oop observed_overflow_list = _overflow_list;
  9219   oop cur_overflow_list;
  9220   do {
  9221     cur_overflow_list = observed_overflow_list;
  9222     if (cur_overflow_list != BUSY) {
  9223       p->set_mark(markOop(cur_overflow_list));
  9224     } else {
  9225       p->set_mark(NULL);
  9227     observed_overflow_list =
  9228       (oop) Atomic::cmpxchg_ptr(p, &_overflow_list, cur_overflow_list);
  9229   } while (cur_overflow_list != observed_overflow_list);
  9231 #undef BUSY
  9233 // Single threaded
  9234 // General Note on GrowableArray: pushes may silently fail
  9235 // because we are (temporarily) out of C-heap for expanding
  9236 // the stack. The problem is quite ubiquitous and affects
  9237 // a lot of code in the JVM. The prudent thing for GrowableArray
  9238 // to do (for now) is to exit with an error. However, that may
  9239 // be too draconian in some cases because the caller may be
  9240 // able to recover without much harm. For such cases, we
  9241 // should probably introduce a "soft_push" method which returns
  9242 // an indication of success or failure with the assumption that
  9243 // the caller may be able to recover from a failure; code in
  9244 // the VM can then be changed, incrementally, to deal with such
  9245 // failures where possible, thus, incrementally hardening the VM
  9246 // in such low resource situations.
  9247 void CMSCollector::preserve_mark_work(oop p, markOop m) {
  9248   _preserved_oop_stack.push(p);
  9249   _preserved_mark_stack.push(m);
  9250   assert(m == p->mark(), "Mark word changed");
  9251   assert(_preserved_oop_stack.size() == _preserved_mark_stack.size(),
  9252          "bijection");
  9255 // Single threaded
  9256 void CMSCollector::preserve_mark_if_necessary(oop p) {
  9257   markOop m = p->mark();
  9258   if (m->must_be_preserved(p)) {
  9259     preserve_mark_work(p, m);
  9263 void CMSCollector::par_preserve_mark_if_necessary(oop p) {
  9264   markOop m = p->mark();
  9265   if (m->must_be_preserved(p)) {
  9266     MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
  9267     // Even though we read the mark word without holding
  9268     // the lock, we are assured that it will not change
  9269     // because we "own" this oop, so no other thread can
  9270     // be trying to push it on the overflow list; see
  9271     // the assertion in preserve_mark_work() that checks
  9272     // that m == p->mark().
  9273     preserve_mark_work(p, m);
  9277 // We should be able to do this multi-threaded,
  9278 // a chunk of stack being a task (this is
  9279 // correct because each oop only ever appears
  9280 // once in the overflow list. However, it's
  9281 // not very easy to completely overlap this with
  9282 // other operations, so will generally not be done
  9283 // until all work's been completed. Because we
  9284 // expect the preserved oop stack (set) to be small,
  9285 // it's probably fine to do this single-threaded.
  9286 // We can explore cleverer concurrent/overlapped/parallel
  9287 // processing of preserved marks if we feel the
  9288 // need for this in the future. Stack overflow should
  9289 // be so rare in practice and, when it happens, its
  9290 // effect on performance so great that this will
  9291 // likely just be in the noise anyway.
  9292 void CMSCollector::restore_preserved_marks_if_any() {
  9293   assert(SafepointSynchronize::is_at_safepoint(),
  9294          "world should be stopped");
  9295   assert(Thread::current()->is_ConcurrentGC_thread() ||
  9296          Thread::current()->is_VM_thread(),
  9297          "should be single-threaded");
  9298   assert(_preserved_oop_stack.size() == _preserved_mark_stack.size(),
  9299          "bijection");
  9301   while (!_preserved_oop_stack.is_empty()) {
  9302     oop p = _preserved_oop_stack.pop();
  9303     assert(p->is_oop(), "Should be an oop");
  9304     assert(_span.contains(p), "oop should be in _span");
  9305     assert(p->mark() == markOopDesc::prototype(),
  9306            "Set when taken from overflow list");
  9307     markOop m = _preserved_mark_stack.pop();
  9308     p->set_mark(m);
  9310   assert(_preserved_mark_stack.is_empty() && _preserved_oop_stack.is_empty(),
  9311          "stacks were cleared above");
  9314 #ifndef PRODUCT
  9315 bool CMSCollector::no_preserved_marks() const {
  9316   return _preserved_mark_stack.is_empty() && _preserved_oop_stack.is_empty();
  9318 #endif
  9320 CMSAdaptiveSizePolicy* ASConcurrentMarkSweepGeneration::cms_size_policy() const
  9322   GenCollectedHeap* gch = (GenCollectedHeap*) GenCollectedHeap::heap();
  9323   CMSAdaptiveSizePolicy* size_policy =
  9324     (CMSAdaptiveSizePolicy*) gch->gen_policy()->size_policy();
  9325   assert(size_policy->is_gc_cms_adaptive_size_policy(),
  9326     "Wrong type for size policy");
  9327   return size_policy;
  9330 void ASConcurrentMarkSweepGeneration::resize(size_t cur_promo_size,
  9331                                            size_t desired_promo_size) {
  9332   if (cur_promo_size < desired_promo_size) {
  9333     size_t expand_bytes = desired_promo_size - cur_promo_size;
  9334     if (PrintAdaptiveSizePolicy && Verbose) {
  9335       gclog_or_tty->print_cr(" ASConcurrentMarkSweepGeneration::resize "
  9336         "Expanding tenured generation by " SIZE_FORMAT " (bytes)",
  9337         expand_bytes);
  9339     expand(expand_bytes,
  9340            MinHeapDeltaBytes,
  9341            CMSExpansionCause::_adaptive_size_policy);
  9342   } else if (desired_promo_size < cur_promo_size) {
  9343     size_t shrink_bytes = cur_promo_size - desired_promo_size;
  9344     if (PrintAdaptiveSizePolicy && Verbose) {
  9345       gclog_or_tty->print_cr(" ASConcurrentMarkSweepGeneration::resize "
  9346         "Shrinking tenured generation by " SIZE_FORMAT " (bytes)",
  9347         shrink_bytes);
  9349     shrink(shrink_bytes);
  9353 CMSGCAdaptivePolicyCounters* ASConcurrentMarkSweepGeneration::gc_adaptive_policy_counters() {
  9354   GenCollectedHeap* gch = GenCollectedHeap::heap();
  9355   CMSGCAdaptivePolicyCounters* counters =
  9356     (CMSGCAdaptivePolicyCounters*) gch->collector_policy()->counters();
  9357   assert(counters->kind() == GCPolicyCounters::CMSGCAdaptivePolicyCountersKind,
  9358     "Wrong kind of counters");
  9359   return counters;
  9363 void ASConcurrentMarkSweepGeneration::update_counters() {
  9364   if (UsePerfData) {
  9365     _space_counters->update_all();
  9366     _gen_counters->update_all();
  9367     CMSGCAdaptivePolicyCounters* counters = gc_adaptive_policy_counters();
  9368     GenCollectedHeap* gch = GenCollectedHeap::heap();
  9369     CMSGCStats* gc_stats_l = (CMSGCStats*) gc_stats();
  9370     assert(gc_stats_l->kind() == GCStats::CMSGCStatsKind,
  9371       "Wrong gc statistics type");
  9372     counters->update_counters(gc_stats_l);
  9376 void ASConcurrentMarkSweepGeneration::update_counters(size_t used) {
  9377   if (UsePerfData) {
  9378     _space_counters->update_used(used);
  9379     _space_counters->update_capacity();
  9380     _gen_counters->update_all();
  9382     CMSGCAdaptivePolicyCounters* counters = gc_adaptive_policy_counters();
  9383     GenCollectedHeap* gch = GenCollectedHeap::heap();
  9384     CMSGCStats* gc_stats_l = (CMSGCStats*) gc_stats();
  9385     assert(gc_stats_l->kind() == GCStats::CMSGCStatsKind,
  9386       "Wrong gc statistics type");
  9387     counters->update_counters(gc_stats_l);
  9391 void ASConcurrentMarkSweepGeneration::shrink_by(size_t desired_bytes) {
  9392   assert_locked_or_safepoint(Heap_lock);
  9393   assert_lock_strong(freelistLock());
  9394   HeapWord* old_end = _cmsSpace->end();
  9395   HeapWord* unallocated_start = _cmsSpace->unallocated_block();
  9396   assert(old_end >= unallocated_start, "Miscalculation of unallocated_start");
  9397   FreeChunk* chunk_at_end = find_chunk_at_end();
  9398   if (chunk_at_end == NULL) {
  9399     // No room to shrink
  9400     if (PrintGCDetails && Verbose) {
  9401       gclog_or_tty->print_cr("No room to shrink: old_end  "
  9402         PTR_FORMAT "  unallocated_start  " PTR_FORMAT
  9403         " chunk_at_end  " PTR_FORMAT,
  9404         old_end, unallocated_start, chunk_at_end);
  9406     return;
  9407   } else {
  9409     // Find the chunk at the end of the space and determine
  9410     // how much it can be shrunk.
  9411     size_t shrinkable_size_in_bytes = chunk_at_end->size();
  9412     size_t aligned_shrinkable_size_in_bytes =
  9413       align_size_down(shrinkable_size_in_bytes, os::vm_page_size());
  9414     assert(unallocated_start <= (HeapWord*) chunk_at_end->end(),
  9415       "Inconsistent chunk at end of space");
  9416     size_t bytes = MIN2(desired_bytes, aligned_shrinkable_size_in_bytes);
  9417     size_t word_size_before = heap_word_size(_virtual_space.committed_size());
  9419     // Shrink the underlying space
  9420     _virtual_space.shrink_by(bytes);
  9421     if (PrintGCDetails && Verbose) {
  9422       gclog_or_tty->print_cr("ConcurrentMarkSweepGeneration::shrink_by:"
  9423         " desired_bytes " SIZE_FORMAT
  9424         " shrinkable_size_in_bytes " SIZE_FORMAT
  9425         " aligned_shrinkable_size_in_bytes " SIZE_FORMAT
  9426         "  bytes  " SIZE_FORMAT,
  9427         desired_bytes, shrinkable_size_in_bytes,
  9428         aligned_shrinkable_size_in_bytes, bytes);
  9429       gclog_or_tty->print_cr("          old_end  " SIZE_FORMAT
  9430         "  unallocated_start  " SIZE_FORMAT,
  9431         old_end, unallocated_start);
  9434     // If the space did shrink (shrinking is not guaranteed),
  9435     // shrink the chunk at the end by the appropriate amount.
  9436     if (((HeapWord*)_virtual_space.high()) < old_end) {
  9437       size_t new_word_size =
  9438         heap_word_size(_virtual_space.committed_size());
  9440       // Have to remove the chunk from the dictionary because it is changing
  9441       // size and might be someplace elsewhere in the dictionary.
  9443       // Get the chunk at end, shrink it, and put it
  9444       // back.
  9445       _cmsSpace->removeChunkFromDictionary(chunk_at_end);
  9446       size_t word_size_change = word_size_before - new_word_size;
  9447       size_t chunk_at_end_old_size = chunk_at_end->size();
  9448       assert(chunk_at_end_old_size >= word_size_change,
  9449         "Shrink is too large");
  9450       chunk_at_end->set_size(chunk_at_end_old_size -
  9451                           word_size_change);
  9452       _cmsSpace->freed((HeapWord*) chunk_at_end->end(),
  9453         word_size_change);
  9455       _cmsSpace->returnChunkToDictionary(chunk_at_end);
  9457       MemRegion mr(_cmsSpace->bottom(), new_word_size);
  9458       _bts->resize(new_word_size);  // resize the block offset shared array
  9459       Universe::heap()->barrier_set()->resize_covered_region(mr);
  9460       _cmsSpace->assert_locked();
  9461       _cmsSpace->set_end((HeapWord*)_virtual_space.high());
  9463       NOT_PRODUCT(_cmsSpace->dictionary()->verify());
  9465       // update the space and generation capacity counters
  9466       if (UsePerfData) {
  9467         _space_counters->update_capacity();
  9468         _gen_counters->update_all();
  9471       if (Verbose && PrintGCDetails) {
  9472         size_t new_mem_size = _virtual_space.committed_size();
  9473         size_t old_mem_size = new_mem_size + bytes;
  9474         gclog_or_tty->print_cr("Shrinking %s from " SIZE_FORMAT "K by " SIZE_FORMAT "K to " SIZE_FORMAT "K",
  9475                       name(), old_mem_size/K, bytes/K, new_mem_size/K);
  9479     assert(_cmsSpace->unallocated_block() <= _cmsSpace->end(),
  9480       "Inconsistency at end of space");
  9481     assert(chunk_at_end->end() == (uintptr_t*) _cmsSpace->end(),
  9482       "Shrinking is inconsistent");
  9483     return;
  9486 // Transfer some number of overflown objects to usual marking
  9487 // stack. Return true if some objects were transferred.
  9488 bool MarkRefsIntoAndScanClosure::take_from_overflow_list() {
  9489   size_t num = MIN2((size_t)(_mark_stack->capacity() - _mark_stack->length())/4,
  9490                     (size_t)ParGCDesiredObjsFromOverflowList);
  9492   bool res = _collector->take_from_overflow_list(num, _mark_stack);
  9493   assert(_collector->overflow_list_is_empty() || res,
  9494          "If list is not empty, we should have taken something");
  9495   assert(!res || !_mark_stack->isEmpty(),
  9496          "If we took something, it should now be on our stack");
  9497   return res;
  9500 size_t MarkDeadObjectsClosure::do_blk(HeapWord* addr) {
  9501   size_t res = _sp->block_size_no_stall(addr, _collector);
  9502   if (_sp->block_is_obj(addr)) {
  9503     if (_live_bit_map->isMarked(addr)) {
  9504       // It can't have been dead in a previous cycle
  9505       guarantee(!_dead_bit_map->isMarked(addr), "No resurrection!");
  9506     } else {
  9507       _dead_bit_map->mark(addr);      // mark the dead object
  9510   // Could be 0, if the block size could not be computed without stalling.
  9511   return res;
  9514 TraceCMSMemoryManagerStats::TraceCMSMemoryManagerStats(CMSCollector::CollectorState phase, GCCause::Cause cause): TraceMemoryManagerStats() {
  9516   switch (phase) {
  9517     case CMSCollector::InitialMarking:
  9518       initialize(true  /* fullGC */ ,
  9519                  cause /* cause of the GC */,
  9520                  true  /* recordGCBeginTime */,
  9521                  true  /* recordPreGCUsage */,
  9522                  false /* recordPeakUsage */,
  9523                  false /* recordPostGCusage */,
  9524                  true  /* recordAccumulatedGCTime */,
  9525                  false /* recordGCEndTime */,
  9526                  false /* countCollection */  );
  9527       break;
  9529     case CMSCollector::FinalMarking:
  9530       initialize(true  /* fullGC */ ,
  9531                  cause /* cause of the GC */,
  9532                  false /* recordGCBeginTime */,
  9533                  false /* recordPreGCUsage */,
  9534                  false /* recordPeakUsage */,
  9535                  false /* recordPostGCusage */,
  9536                  true  /* recordAccumulatedGCTime */,
  9537                  false /* recordGCEndTime */,
  9538                  false /* countCollection */  );
  9539       break;
  9541     case CMSCollector::Sweeping:
  9542       initialize(true  /* fullGC */ ,
  9543                  cause /* cause of the GC */,
  9544                  false /* recordGCBeginTime */,
  9545                  false /* recordPreGCUsage */,
  9546                  true  /* recordPeakUsage */,
  9547                  true  /* recordPostGCusage */,
  9548                  false /* recordAccumulatedGCTime */,
  9549                  true  /* recordGCEndTime */,
  9550                  true  /* countCollection */  );
  9551       break;
  9553     default:
  9554       ShouldNotReachHere();

mercurial