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

Thu, 22 May 2014 15:52:41 -0400

author
drchase
date
Thu, 22 May 2014 15:52:41 -0400
changeset 6680
78bbf4d43a14
parent 6678
7384f6a12fc1
child 6719
8e20ef014b08
permissions
-rw-r--r--

8037816: Fix for 8036122 breaks build with Xcode5/clang
8043029: Change 8037816 breaks HS build with older GCC versions which don't support diagnostic pragmas
8043164: Format warning in traceStream.hpp
Summary: Backport of main fix + two corrections, enables clang compilation, turns on format attributes, corrects/mutes warnings
Reviewed-by: kvn, coleenp, iveresov, twisti

     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/vmThread.hpp"
    63 #include "services/memoryService.hpp"
    64 #include "services/runtimeService.hpp"
    66 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
    68 // statics
    69 CMSCollector* ConcurrentMarkSweepGeneration::_collector = NULL;
    70 bool CMSCollector::_full_gc_requested = false;
    71 GCCause::Cause CMSCollector::_full_gc_cause = GCCause::_no_gc;
    73 //////////////////////////////////////////////////////////////////
    74 // In support of CMS/VM thread synchronization
    75 //////////////////////////////////////////////////////////////////
    76 // We split use of the CGC_lock into 2 "levels".
    77 // The low-level locking is of the usual CGC_lock monitor. We introduce
    78 // a higher level "token" (hereafter "CMS token") built on top of the
    79 // low level monitor (hereafter "CGC lock").
    80 // The token-passing protocol gives priority to the VM thread. The
    81 // CMS-lock doesn't provide any fairness guarantees, but clients
    82 // should ensure that it is only held for very short, bounded
    83 // durations.
    84 //
    85 // When either of the CMS thread or the VM thread is involved in
    86 // collection operations during which it does not want the other
    87 // thread to interfere, it obtains the CMS token.
    88 //
    89 // If either thread tries to get the token while the other has
    90 // it, that thread waits. However, if the VM thread and CMS thread
    91 // both want the token, then the VM thread gets priority while the
    92 // CMS thread waits. This ensures, for instance, that the "concurrent"
    93 // phases of the CMS thread's work do not block out the VM thread
    94 // for long periods of time as the CMS thread continues to hog
    95 // the token. (See bug 4616232).
    96 //
    97 // The baton-passing functions are, however, controlled by the
    98 // flags _foregroundGCShouldWait and _foregroundGCIsActive,
    99 // and here the low-level CMS lock, not the high level token,
   100 // ensures mutual exclusion.
   101 //
   102 // Two important conditions that we have to satisfy:
   103 // 1. if a thread does a low-level wait on the CMS lock, then it
   104 //    relinquishes the CMS token if it were holding that token
   105 //    when it acquired the low-level CMS lock.
   106 // 2. any low-level notifications on the low-level lock
   107 //    should only be sent when a thread has relinquished the token.
   108 //
   109 // In the absence of either property, we'd have potential deadlock.
   110 //
   111 // We protect each of the CMS (concurrent and sequential) phases
   112 // with the CMS _token_, not the CMS _lock_.
   113 //
   114 // The only code protected by CMS lock is the token acquisition code
   115 // itself, see ConcurrentMarkSweepThread::[de]synchronize(), and the
   116 // baton-passing code.
   117 //
   118 // Unfortunately, i couldn't come up with a good abstraction to factor and
   119 // hide the naked CGC_lock manipulation in the baton-passing code
   120 // further below. That's something we should try to do. Also, the proof
   121 // of correctness of this 2-level locking scheme is far from obvious,
   122 // and potentially quite slippery. We have an uneasy supsicion, for instance,
   123 // that there may be a theoretical possibility of delay/starvation in the
   124 // low-level lock/wait/notify scheme used for the baton-passing because of
   125 // potential intereference with the priority scheme embodied in the
   126 // CMS-token-passing protocol. See related comments at a CGC_lock->wait()
   127 // invocation further below and marked with "XXX 20011219YSR".
   128 // Indeed, as we note elsewhere, this may become yet more slippery
   129 // in the presence of multiple CMS and/or multiple VM threads. XXX
   131 class CMSTokenSync: public StackObj {
   132  private:
   133   bool _is_cms_thread;
   134  public:
   135   CMSTokenSync(bool is_cms_thread):
   136     _is_cms_thread(is_cms_thread) {
   137     assert(is_cms_thread == Thread::current()->is_ConcurrentGC_thread(),
   138            "Incorrect argument to constructor");
   139     ConcurrentMarkSweepThread::synchronize(_is_cms_thread);
   140   }
   142   ~CMSTokenSync() {
   143     assert(_is_cms_thread ?
   144              ConcurrentMarkSweepThread::cms_thread_has_cms_token() :
   145              ConcurrentMarkSweepThread::vm_thread_has_cms_token(),
   146           "Incorrect state");
   147     ConcurrentMarkSweepThread::desynchronize(_is_cms_thread);
   148   }
   149 };
   151 // Convenience class that does a CMSTokenSync, and then acquires
   152 // upto three locks.
   153 class CMSTokenSyncWithLocks: public CMSTokenSync {
   154  private:
   155   // Note: locks are acquired in textual declaration order
   156   // and released in the opposite order
   157   MutexLockerEx _locker1, _locker2, _locker3;
   158  public:
   159   CMSTokenSyncWithLocks(bool is_cms_thread, Mutex* mutex1,
   160                         Mutex* mutex2 = NULL, Mutex* mutex3 = NULL):
   161     CMSTokenSync(is_cms_thread),
   162     _locker1(mutex1, Mutex::_no_safepoint_check_flag),
   163     _locker2(mutex2, Mutex::_no_safepoint_check_flag),
   164     _locker3(mutex3, Mutex::_no_safepoint_check_flag)
   165   { }
   166 };
   169 // Wrapper class to temporarily disable icms during a foreground cms collection.
   170 class ICMSDisabler: public StackObj {
   171  public:
   172   // The ctor disables icms and wakes up the thread so it notices the change;
   173   // the dtor re-enables icms.  Note that the CMSCollector methods will check
   174   // CMSIncrementalMode.
   175   ICMSDisabler()  { CMSCollector::disable_icms(); CMSCollector::start_icms(); }
   176   ~ICMSDisabler() { CMSCollector::enable_icms(); }
   177 };
   179 //////////////////////////////////////////////////////////////////
   180 //  Concurrent Mark-Sweep Generation /////////////////////////////
   181 //////////////////////////////////////////////////////////////////
   183 NOT_PRODUCT(CompactibleFreeListSpace* debug_cms_space;)
   185 // This struct contains per-thread things necessary to support parallel
   186 // young-gen collection.
   187 class CMSParGCThreadState: public CHeapObj<mtGC> {
   188  public:
   189   CFLS_LAB lab;
   190   PromotionInfo promo;
   192   // Constructor.
   193   CMSParGCThreadState(CompactibleFreeListSpace* cfls) : lab(cfls) {
   194     promo.setSpace(cfls);
   195   }
   196 };
   198 ConcurrentMarkSweepGeneration::ConcurrentMarkSweepGeneration(
   199      ReservedSpace rs, size_t initial_byte_size, int level,
   200      CardTableRS* ct, bool use_adaptive_freelists,
   201      FreeBlockDictionary<FreeChunk>::DictionaryChoice dictionaryChoice) :
   202   CardGeneration(rs, initial_byte_size, level, ct),
   203   _dilatation_factor(((double)MinChunkSize)/((double)(CollectedHeap::min_fill_size()))),
   204   _debug_collection_type(Concurrent_collection_type),
   205   _did_compact(false)
   206 {
   207   HeapWord* bottom = (HeapWord*) _virtual_space.low();
   208   HeapWord* end    = (HeapWord*) _virtual_space.high();
   210   _direct_allocated_words = 0;
   211   NOT_PRODUCT(
   212     _numObjectsPromoted = 0;
   213     _numWordsPromoted = 0;
   214     _numObjectsAllocated = 0;
   215     _numWordsAllocated = 0;
   216   )
   218   _cmsSpace = new CompactibleFreeListSpace(_bts, MemRegion(bottom, end),
   219                                            use_adaptive_freelists,
   220                                            dictionaryChoice);
   221   NOT_PRODUCT(debug_cms_space = _cmsSpace;)
   222   if (_cmsSpace == NULL) {
   223     vm_exit_during_initialization(
   224       "CompactibleFreeListSpace allocation failure");
   225   }
   226   _cmsSpace->_gen = this;
   228   _gc_stats = new CMSGCStats();
   230   // Verify the assumption that FreeChunk::_prev and OopDesc::_klass
   231   // offsets match. The ability to tell free chunks from objects
   232   // depends on this property.
   233   debug_only(
   234     FreeChunk* junk = NULL;
   235     assert(UseCompressedClassPointers ||
   236            junk->prev_addr() == (void*)(oop(junk)->klass_addr()),
   237            "Offset of FreeChunk::_prev within FreeChunk must match"
   238            "  that of OopDesc::_klass within OopDesc");
   239   )
   240   if (CollectedHeap::use_parallel_gc_threads()) {
   241     typedef CMSParGCThreadState* CMSParGCThreadStatePtr;
   242     _par_gc_thread_states =
   243       NEW_C_HEAP_ARRAY(CMSParGCThreadStatePtr, ParallelGCThreads, mtGC);
   244     if (_par_gc_thread_states == NULL) {
   245       vm_exit_during_initialization("Could not allocate par gc structs");
   246     }
   247     for (uint i = 0; i < ParallelGCThreads; i++) {
   248       _par_gc_thread_states[i] = new CMSParGCThreadState(cmsSpace());
   249       if (_par_gc_thread_states[i] == NULL) {
   250         vm_exit_during_initialization("Could not allocate par gc structs");
   251       }
   252     }
   253   } else {
   254     _par_gc_thread_states = NULL;
   255   }
   256   _incremental_collection_failed = false;
   257   // The "dilatation_factor" is the expansion that can occur on
   258   // account of the fact that the minimum object size in the CMS
   259   // generation may be larger than that in, say, a contiguous young
   260   //  generation.
   261   // Ideally, in the calculation below, we'd compute the dilatation
   262   // factor as: MinChunkSize/(promoting_gen's min object size)
   263   // Since we do not have such a general query interface for the
   264   // promoting generation, we'll instead just use the mimimum
   265   // object size (which today is a header's worth of space);
   266   // note that all arithmetic is in units of HeapWords.
   267   assert(MinChunkSize >= CollectedHeap::min_fill_size(), "just checking");
   268   assert(_dilatation_factor >= 1.0, "from previous assert");
   269 }
   272 // The field "_initiating_occupancy" represents the occupancy percentage
   273 // at which we trigger a new collection cycle.  Unless explicitly specified
   274 // via CMSInitiatingOccupancyFraction (argument "io" below), it
   275 // is calculated by:
   276 //
   277 //   Let "f" be MinHeapFreeRatio in
   278 //
   279 //    _intiating_occupancy = 100-f +
   280 //                           f * (CMSTriggerRatio/100)
   281 //   where CMSTriggerRatio is the argument "tr" below.
   282 //
   283 // That is, if we assume the heap is at its desired maximum occupancy at the
   284 // end of a collection, we let CMSTriggerRatio of the (purported) free
   285 // space be allocated before initiating a new collection cycle.
   286 //
   287 void ConcurrentMarkSweepGeneration::init_initiating_occupancy(intx io, uintx tr) {
   288   assert(io <= 100 && tr <= 100, "Check the arguments");
   289   if (io >= 0) {
   290     _initiating_occupancy = (double)io / 100.0;
   291   } else {
   292     _initiating_occupancy = ((100 - MinHeapFreeRatio) +
   293                              (double)(tr * MinHeapFreeRatio) / 100.0)
   294                             / 100.0;
   295   }
   296 }
   298 void ConcurrentMarkSweepGeneration::ref_processor_init() {
   299   assert(collector() != NULL, "no collector");
   300   collector()->ref_processor_init();
   301 }
   303 void CMSCollector::ref_processor_init() {
   304   if (_ref_processor == NULL) {
   305     // Allocate and initialize a reference processor
   306     _ref_processor =
   307       new ReferenceProcessor(_span,                               // span
   308                              (ParallelGCThreads > 1) && ParallelRefProcEnabled, // mt processing
   309                              (int) ParallelGCThreads,             // mt processing degree
   310                              _cmsGen->refs_discovery_is_mt(),     // mt discovery
   311                              (int) MAX2(ConcGCThreads, ParallelGCThreads), // mt discovery degree
   312                              _cmsGen->refs_discovery_is_atomic(), // discovery is not atomic
   313                              &_is_alive_closure,                  // closure for liveness info
   314                              false);                              // next field updates do not need write barrier
   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);
  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   NOT_PRODUCT(GCTraceTime t("CMS:MS (foreground) ", PrintGCDetails && Verbose,
  2514     true, NULL);)
  2515   if (UseAdaptiveSizePolicy) {
  2516     size_policy()->ms_collection_begin();
  2518   COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact);
  2520   HandleMark hm;  // Discard invalid handles created during verification
  2522   if (VerifyBeforeGC &&
  2523       GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2524     Universe::verify();
  2527   // Snapshot the soft reference policy to be used in this collection cycle.
  2528   ref_processor()->setup_policy(clear_all_soft_refs);
  2530   // Decide if class unloading should be done
  2531   update_should_unload_classes();
  2533   bool init_mark_was_synchronous = false; // until proven otherwise
  2534   while (_collectorState != Idling) {
  2535     if (TraceCMSState) {
  2536       gclog_or_tty->print_cr("Thread " INTPTR_FORMAT " in CMS state %d",
  2537         Thread::current(), _collectorState);
  2539     switch (_collectorState) {
  2540       case InitialMarking:
  2541         register_foreground_gc_start(cause);
  2542         init_mark_was_synchronous = true;  // fact to be exploited in re-mark
  2543         checkpointRootsInitial(false);
  2544         assert(_collectorState == Marking, "Collector state should have changed"
  2545           " within checkpointRootsInitial()");
  2546         break;
  2547       case Marking:
  2548         // initial marking in checkpointRootsInitialWork has been completed
  2549         if (VerifyDuringGC &&
  2550             GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2551           Universe::verify("Verify before initial mark: ");
  2554           bool res = markFromRoots(false);
  2555           assert(res && _collectorState == FinalMarking, "Collector state should "
  2556             "have changed");
  2557           break;
  2559       case FinalMarking:
  2560         if (VerifyDuringGC &&
  2561             GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2562           Universe::verify("Verify before re-mark: ");
  2564         checkpointRootsFinal(false, clear_all_soft_refs,
  2565                              init_mark_was_synchronous);
  2566         assert(_collectorState == Sweeping, "Collector state should not "
  2567           "have changed within checkpointRootsFinal()");
  2568         break;
  2569       case Sweeping:
  2570         // final marking in checkpointRootsFinal has been completed
  2571         if (VerifyDuringGC &&
  2572             GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2573           Universe::verify("Verify before sweep: ");
  2575         sweep(false);
  2576         assert(_collectorState == Resizing, "Incorrect state");
  2577         break;
  2578       case Resizing: {
  2579         // Sweeping has been completed; the actual resize in this case
  2580         // is done separately; nothing to be done in this state.
  2581         _collectorState = Resetting;
  2582         break;
  2584       case Resetting:
  2585         // The heap has been resized.
  2586         if (VerifyDuringGC &&
  2587             GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2588           Universe::verify("Verify before reset: ");
  2590         save_heap_summary();
  2591         reset(false);
  2592         assert(_collectorState == Idling, "Collector state should "
  2593           "have changed");
  2594         break;
  2595       case Precleaning:
  2596       case AbortablePreclean:
  2597         // Elide the preclean phase
  2598         _collectorState = FinalMarking;
  2599         break;
  2600       default:
  2601         ShouldNotReachHere();
  2603     if (TraceCMSState) {
  2604       gclog_or_tty->print_cr("  Thread " INTPTR_FORMAT " done - next CMS state %d",
  2605         Thread::current(), _collectorState);
  2609   if (UseAdaptiveSizePolicy) {
  2610     GenCollectedHeap* gch = GenCollectedHeap::heap();
  2611     size_policy()->ms_collection_end(gch->gc_cause());
  2614   if (VerifyAfterGC &&
  2615       GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2616     Universe::verify();
  2618   if (TraceCMSState) {
  2619     gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT
  2620       " exiting collection CMS state %d",
  2621       Thread::current(), _collectorState);
  2625 bool CMSCollector::waitForForegroundGC() {
  2626   bool res = false;
  2627   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  2628          "CMS thread should have CMS token");
  2629   // Block the foreground collector until the
  2630   // background collectors decides whether to
  2631   // yield.
  2632   MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
  2633   _foregroundGCShouldWait = true;
  2634   if (_foregroundGCIsActive) {
  2635     // The background collector yields to the
  2636     // foreground collector and returns a value
  2637     // indicating that it has yielded.  The foreground
  2638     // collector can proceed.
  2639     res = true;
  2640     _foregroundGCShouldWait = false;
  2641     ConcurrentMarkSweepThread::clear_CMS_flag(
  2642       ConcurrentMarkSweepThread::CMS_cms_has_token);
  2643     ConcurrentMarkSweepThread::set_CMS_flag(
  2644       ConcurrentMarkSweepThread::CMS_cms_wants_token);
  2645     // Get a possibly blocked foreground thread going
  2646     CGC_lock->notify();
  2647     if (TraceCMSState) {
  2648       gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT " waiting at CMS state %d",
  2649         Thread::current(), _collectorState);
  2651     while (_foregroundGCIsActive) {
  2652       CGC_lock->wait(Mutex::_no_safepoint_check_flag);
  2654     ConcurrentMarkSweepThread::set_CMS_flag(
  2655       ConcurrentMarkSweepThread::CMS_cms_has_token);
  2656     ConcurrentMarkSweepThread::clear_CMS_flag(
  2657       ConcurrentMarkSweepThread::CMS_cms_wants_token);
  2659   if (TraceCMSState) {
  2660     gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT " continuing at CMS state %d",
  2661       Thread::current(), _collectorState);
  2663   return res;
  2666 // Because of the need to lock the free lists and other structures in
  2667 // the collector, common to all the generations that the collector is
  2668 // collecting, we need the gc_prologues of individual CMS generations
  2669 // delegate to their collector. It may have been simpler had the
  2670 // current infrastructure allowed one to call a prologue on a
  2671 // collector. In the absence of that we have the generation's
  2672 // prologue delegate to the collector, which delegates back
  2673 // some "local" work to a worker method in the individual generations
  2674 // that it's responsible for collecting, while itself doing any
  2675 // work common to all generations it's responsible for. A similar
  2676 // comment applies to the  gc_epilogue()'s.
  2677 // The role of the varaible _between_prologue_and_epilogue is to
  2678 // enforce the invocation protocol.
  2679 void CMSCollector::gc_prologue(bool full) {
  2680   // Call gc_prologue_work() for the CMSGen
  2681   // we are responsible for.
  2683   // The following locking discipline assumes that we are only called
  2684   // when the world is stopped.
  2685   assert(SafepointSynchronize::is_at_safepoint(), "world is stopped assumption");
  2687   // The CMSCollector prologue must call the gc_prologues for the
  2688   // "generations" that it's responsible
  2689   // for.
  2691   assert(   Thread::current()->is_VM_thread()
  2692          || (   CMSScavengeBeforeRemark
  2693              && Thread::current()->is_ConcurrentGC_thread()),
  2694          "Incorrect thread type for prologue execution");
  2696   if (_between_prologue_and_epilogue) {
  2697     // We have already been invoked; this is a gc_prologue delegation
  2698     // from yet another CMS generation that we are responsible for, just
  2699     // ignore it since all relevant work has already been done.
  2700     return;
  2703   // set a bit saying prologue has been called; cleared in epilogue
  2704   _between_prologue_and_epilogue = true;
  2705   // Claim locks for common data structures, then call gc_prologue_work()
  2706   // for each CMSGen.
  2708   getFreelistLocks();   // gets free list locks on constituent spaces
  2709   bitMapLock()->lock_without_safepoint_check();
  2711   // Should call gc_prologue_work() for all cms gens we are responsible for
  2712   bool duringMarking =    _collectorState >= Marking
  2713                          && _collectorState < Sweeping;
  2715   // The young collections clear the modified oops state, which tells if
  2716   // there are any modified oops in the class. The remark phase also needs
  2717   // that information. Tell the young collection to save the union of all
  2718   // modified klasses.
  2719   if (duringMarking) {
  2720     _ct->klass_rem_set()->set_accumulate_modified_oops(true);
  2723   bool registerClosure = duringMarking;
  2725   ModUnionClosure* muc = CollectedHeap::use_parallel_gc_threads() ?
  2726                                                &_modUnionClosurePar
  2727                                                : &_modUnionClosure;
  2728   _cmsGen->gc_prologue_work(full, registerClosure, muc);
  2730   if (!full) {
  2731     stats().record_gc0_begin();
  2735 void ConcurrentMarkSweepGeneration::gc_prologue(bool full) {
  2737   _capacity_at_prologue = capacity();
  2738   _used_at_prologue = used();
  2740   // Delegate to CMScollector which knows how to coordinate between
  2741   // this and any other CMS generations that it is responsible for
  2742   // collecting.
  2743   collector()->gc_prologue(full);
  2746 // This is a "private" interface for use by this generation's CMSCollector.
  2747 // Not to be called directly by any other entity (for instance,
  2748 // GenCollectedHeap, which calls the "public" gc_prologue method above).
  2749 void ConcurrentMarkSweepGeneration::gc_prologue_work(bool full,
  2750   bool registerClosure, ModUnionClosure* modUnionClosure) {
  2751   assert(!incremental_collection_failed(), "Shouldn't be set yet");
  2752   assert(cmsSpace()->preconsumptionDirtyCardClosure() == NULL,
  2753     "Should be NULL");
  2754   if (registerClosure) {
  2755     cmsSpace()->setPreconsumptionDirtyCardClosure(modUnionClosure);
  2757   cmsSpace()->gc_prologue();
  2758   // Clear stat counters
  2759   NOT_PRODUCT(
  2760     assert(_numObjectsPromoted == 0, "check");
  2761     assert(_numWordsPromoted   == 0, "check");
  2762     if (Verbose && PrintGC) {
  2763       gclog_or_tty->print("Allocated "SIZE_FORMAT" objects, "
  2764                           SIZE_FORMAT" bytes concurrently",
  2765       _numObjectsAllocated, _numWordsAllocated*sizeof(HeapWord));
  2767     _numObjectsAllocated = 0;
  2768     _numWordsAllocated   = 0;
  2772 void CMSCollector::gc_epilogue(bool full) {
  2773   // The following locking discipline assumes that we are only called
  2774   // when the world is stopped.
  2775   assert(SafepointSynchronize::is_at_safepoint(),
  2776          "world is stopped assumption");
  2778   // Currently the CMS epilogue (see CompactibleFreeListSpace) merely checks
  2779   // if linear allocation blocks need to be appropriately marked to allow the
  2780   // the blocks to be parsable. We also check here whether we need to nudge the
  2781   // CMS collector thread to start a new cycle (if it's not already active).
  2782   assert(   Thread::current()->is_VM_thread()
  2783          || (   CMSScavengeBeforeRemark
  2784              && Thread::current()->is_ConcurrentGC_thread()),
  2785          "Incorrect thread type for epilogue execution");
  2787   if (!_between_prologue_and_epilogue) {
  2788     // We have already been invoked; this is a gc_epilogue delegation
  2789     // from yet another CMS generation that we are responsible for, just
  2790     // ignore it since all relevant work has already been done.
  2791     return;
  2793   assert(haveFreelistLocks(), "must have freelist locks");
  2794   assert_lock_strong(bitMapLock());
  2796   _ct->klass_rem_set()->set_accumulate_modified_oops(false);
  2798   _cmsGen->gc_epilogue_work(full);
  2800   if (_collectorState == AbortablePreclean || _collectorState == Precleaning) {
  2801     // in case sampling was not already enabled, enable it
  2802     _start_sampling = true;
  2804   // reset _eden_chunk_array so sampling starts afresh
  2805   _eden_chunk_index = 0;
  2807   size_t cms_used   = _cmsGen->cmsSpace()->used();
  2809   // update performance counters - this uses a special version of
  2810   // update_counters() that allows the utilization to be passed as a
  2811   // parameter, avoiding multiple calls to used().
  2812   //
  2813   _cmsGen->update_counters(cms_used);
  2815   if (CMSIncrementalMode) {
  2816     icms_update_allocation_limits();
  2819   bitMapLock()->unlock();
  2820   releaseFreelistLocks();
  2822   if (!CleanChunkPoolAsync) {
  2823     Chunk::clean_chunk_pool();
  2826   set_did_compact(false);
  2827   _between_prologue_and_epilogue = false;  // ready for next cycle
  2830 void ConcurrentMarkSweepGeneration::gc_epilogue(bool full) {
  2831   collector()->gc_epilogue(full);
  2833   // Also reset promotion tracking in par gc thread states.
  2834   if (CollectedHeap::use_parallel_gc_threads()) {
  2835     for (uint i = 0; i < ParallelGCThreads; i++) {
  2836       _par_gc_thread_states[i]->promo.stopTrackingPromotions(i);
  2841 void ConcurrentMarkSweepGeneration::gc_epilogue_work(bool full) {
  2842   assert(!incremental_collection_failed(), "Should have been cleared");
  2843   cmsSpace()->setPreconsumptionDirtyCardClosure(NULL);
  2844   cmsSpace()->gc_epilogue();
  2845     // Print stat counters
  2846   NOT_PRODUCT(
  2847     assert(_numObjectsAllocated == 0, "check");
  2848     assert(_numWordsAllocated == 0, "check");
  2849     if (Verbose && PrintGC) {
  2850       gclog_or_tty->print("Promoted "SIZE_FORMAT" objects, "
  2851                           SIZE_FORMAT" bytes",
  2852                  _numObjectsPromoted, _numWordsPromoted*sizeof(HeapWord));
  2854     _numObjectsPromoted = 0;
  2855     _numWordsPromoted   = 0;
  2858   if (PrintGC && Verbose) {
  2859     // Call down the chain in contiguous_available needs the freelistLock
  2860     // so print this out before releasing the freeListLock.
  2861     gclog_or_tty->print(" Contiguous available "SIZE_FORMAT" bytes ",
  2862                         contiguous_available());
  2866 #ifndef PRODUCT
  2867 bool CMSCollector::have_cms_token() {
  2868   Thread* thr = Thread::current();
  2869   if (thr->is_VM_thread()) {
  2870     return ConcurrentMarkSweepThread::vm_thread_has_cms_token();
  2871   } else if (thr->is_ConcurrentGC_thread()) {
  2872     return ConcurrentMarkSweepThread::cms_thread_has_cms_token();
  2873   } else if (thr->is_GC_task_thread()) {
  2874     return ConcurrentMarkSweepThread::vm_thread_has_cms_token() &&
  2875            ParGCRareEvent_lock->owned_by_self();
  2877   return false;
  2879 #endif
  2881 // Check reachability of the given heap address in CMS generation,
  2882 // treating all other generations as roots.
  2883 bool CMSCollector::is_cms_reachable(HeapWord* addr) {
  2884   // We could "guarantee" below, rather than assert, but i'll
  2885   // leave these as "asserts" so that an adventurous debugger
  2886   // could try this in the product build provided some subset of
  2887   // the conditions were met, provided they were intersted in the
  2888   // results and knew that the computation below wouldn't interfere
  2889   // with other concurrent computations mutating the structures
  2890   // being read or written.
  2891   assert(SafepointSynchronize::is_at_safepoint(),
  2892          "Else mutations in object graph will make answer suspect");
  2893   assert(have_cms_token(), "Should hold cms token");
  2894   assert(haveFreelistLocks(), "must hold free list locks");
  2895   assert_lock_strong(bitMapLock());
  2897   // Clear the marking bit map array before starting, but, just
  2898   // for kicks, first report if the given address is already marked
  2899   gclog_or_tty->print_cr("Start: Address 0x%x is%s marked", addr,
  2900                 _markBitMap.isMarked(addr) ? "" : " not");
  2902   if (verify_after_remark()) {
  2903     MutexLockerEx x(verification_mark_bm()->lock(), Mutex::_no_safepoint_check_flag);
  2904     bool result = verification_mark_bm()->isMarked(addr);
  2905     gclog_or_tty->print_cr("TransitiveMark: Address 0x%x %s marked", addr,
  2906                            result ? "IS" : "is NOT");
  2907     return result;
  2908   } else {
  2909     gclog_or_tty->print_cr("Could not compute result");
  2910     return false;
  2915 void
  2916 CMSCollector::print_on_error(outputStream* st) {
  2917   CMSCollector* collector = ConcurrentMarkSweepGeneration::_collector;
  2918   if (collector != NULL) {
  2919     CMSBitMap* bitmap = &collector->_markBitMap;
  2920     st->print_cr("Marking Bits: (CMSBitMap*) " PTR_FORMAT, bitmap);
  2921     bitmap->print_on_error(st, " Bits: ");
  2923     st->cr();
  2925     CMSBitMap* mut_bitmap = &collector->_modUnionTable;
  2926     st->print_cr("Mod Union Table: (CMSBitMap*) " PTR_FORMAT, mut_bitmap);
  2927     mut_bitmap->print_on_error(st, " Bits: ");
  2931 ////////////////////////////////////////////////////////
  2932 // CMS Verification Support
  2933 ////////////////////////////////////////////////////////
  2934 // Following the remark phase, the following invariant
  2935 // should hold -- each object in the CMS heap which is
  2936 // marked in markBitMap() should be marked in the verification_mark_bm().
  2938 class VerifyMarkedClosure: public BitMapClosure {
  2939   CMSBitMap* _marks;
  2940   bool       _failed;
  2942  public:
  2943   VerifyMarkedClosure(CMSBitMap* bm): _marks(bm), _failed(false) {}
  2945   bool do_bit(size_t offset) {
  2946     HeapWord* addr = _marks->offsetToHeapWord(offset);
  2947     if (!_marks->isMarked(addr)) {
  2948       oop(addr)->print_on(gclog_or_tty);
  2949       gclog_or_tty->print_cr(" ("INTPTR_FORMAT" should have been marked)", addr);
  2950       _failed = true;
  2952     return true;
  2955   bool failed() { return _failed; }
  2956 };
  2958 bool CMSCollector::verify_after_remark(bool silent) {
  2959   if (!silent) gclog_or_tty->print(" [Verifying CMS Marking... ");
  2960   MutexLockerEx ml(verification_mark_bm()->lock(), Mutex::_no_safepoint_check_flag);
  2961   static bool init = false;
  2963   assert(SafepointSynchronize::is_at_safepoint(),
  2964          "Else mutations in object graph will make answer suspect");
  2965   assert(have_cms_token(),
  2966          "Else there may be mutual interference in use of "
  2967          " verification data structures");
  2968   assert(_collectorState > Marking && _collectorState <= Sweeping,
  2969          "Else marking info checked here may be obsolete");
  2970   assert(haveFreelistLocks(), "must hold free list locks");
  2971   assert_lock_strong(bitMapLock());
  2974   // Allocate marking bit map if not already allocated
  2975   if (!init) { // first time
  2976     if (!verification_mark_bm()->allocate(_span)) {
  2977       return false;
  2979     init = true;
  2982   assert(verification_mark_stack()->isEmpty(), "Should be empty");
  2984   // Turn off refs discovery -- so we will be tracing through refs.
  2985   // This is as intended, because by this time
  2986   // GC must already have cleared any refs that need to be cleared,
  2987   // and traced those that need to be marked; moreover,
  2988   // the marking done here is not going to intefere in any
  2989   // way with the marking information used by GC.
  2990   NoRefDiscovery no_discovery(ref_processor());
  2992   COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;)
  2994   // Clear any marks from a previous round
  2995   verification_mark_bm()->clear_all();
  2996   assert(verification_mark_stack()->isEmpty(), "markStack should be empty");
  2997   verify_work_stacks_empty();
  2999   GenCollectedHeap* gch = GenCollectedHeap::heap();
  3000   gch->ensure_parsability(false);  // fill TLABs, but no need to retire them
  3001   // Update the saved marks which may affect the root scans.
  3002   gch->save_marks();
  3004   if (CMSRemarkVerifyVariant == 1) {
  3005     // In this first variant of verification, we complete
  3006     // all marking, then check if the new marks-verctor is
  3007     // a subset of the CMS marks-vector.
  3008     verify_after_remark_work_1();
  3009   } else if (CMSRemarkVerifyVariant == 2) {
  3010     // In this second variant of verification, we flag an error
  3011     // (i.e. an object reachable in the new marks-vector not reachable
  3012     // in the CMS marks-vector) immediately, also indicating the
  3013     // identify of an object (A) that references the unmarked object (B) --
  3014     // presumably, a mutation to A failed to be picked up by preclean/remark?
  3015     verify_after_remark_work_2();
  3016   } else {
  3017     warning("Unrecognized value %d for CMSRemarkVerifyVariant",
  3018             CMSRemarkVerifyVariant);
  3020   if (!silent) gclog_or_tty->print(" done] ");
  3021   return true;
  3024 void CMSCollector::verify_after_remark_work_1() {
  3025   ResourceMark rm;
  3026   HandleMark  hm;
  3027   GenCollectedHeap* gch = GenCollectedHeap::heap();
  3029   // Get a clear set of claim bits for the strong roots processing to work with.
  3030   ClassLoaderDataGraph::clear_claimed_marks();
  3032   // Mark from roots one level into CMS
  3033   MarkRefsIntoClosure notOlder(_span, verification_mark_bm());
  3034   gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
  3036   gch->gen_process_strong_roots(_cmsGen->level(),
  3037                                 true,   // younger gens are roots
  3038                                 true,   // activate StrongRootsScope
  3039                                 false,  // not scavenging
  3040                                 SharedHeap::ScanningOption(roots_scanning_options()),
  3041                                 &notOlder,
  3042                                 true,   // walk code active on stacks
  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                                 false,  // not scavenging
  3108                                 SharedHeap::ScanningOption(roots_scanning_options()),
  3109                                 &notOlder,
  3110                                 true,   // walk code active on stacks
  3111                                 NULL,
  3112                                 &klass_closure);
  3114   // Now mark from the roots
  3115   MarkFromRootsVerifyClosure markFromRootsClosure(this, _span,
  3116     verification_mark_bm(), markBitMap(), verification_mark_stack());
  3117   assert(_restart_addr == NULL, "Expected pre-condition");
  3118   verification_mark_bm()->iterate(&markFromRootsClosure);
  3119   while (_restart_addr != NULL) {
  3120     // Deal with stack overflow: by restarting at the indicated
  3121     // address.
  3122     HeapWord* ra = _restart_addr;
  3123     markFromRootsClosure.reset(ra);
  3124     _restart_addr = NULL;
  3125     verification_mark_bm()->iterate(&markFromRootsClosure, ra, _span.end());
  3127   assert(verification_mark_stack()->isEmpty(), "Should have been drained");
  3128   verify_work_stacks_empty();
  3130   VerifyKlassOopsKlassClosure verify_klass_oops(verification_mark_bm());
  3131   ClassLoaderDataGraph::classes_do(&verify_klass_oops);
  3133   // Marking completed -- now verify that each bit marked in
  3134   // verification_mark_bm() is also marked in markBitMap(); flag all
  3135   // errors by printing corresponding objects.
  3136   VerifyMarkedClosure vcl(markBitMap());
  3137   verification_mark_bm()->iterate(&vcl);
  3138   assert(!vcl.failed(), "Else verification above should not have succeeded");
  3141 void ConcurrentMarkSweepGeneration::save_marks() {
  3142   // delegate to CMS space
  3143   cmsSpace()->save_marks();
  3144   for (uint i = 0; i < ParallelGCThreads; i++) {
  3145     _par_gc_thread_states[i]->promo.startTrackingPromotions();
  3149 bool ConcurrentMarkSweepGeneration::no_allocs_since_save_marks() {
  3150   return cmsSpace()->no_allocs_since_save_marks();
  3153 #define CMS_SINCE_SAVE_MARKS_DEFN(OopClosureType, nv_suffix)    \
  3155 void ConcurrentMarkSweepGeneration::                            \
  3156 oop_since_save_marks_iterate##nv_suffix(OopClosureType* cl) {   \
  3157   cl->set_generation(this);                                     \
  3158   cmsSpace()->oop_since_save_marks_iterate##nv_suffix(cl);      \
  3159   cl->reset_generation();                                       \
  3160   save_marks();                                                 \
  3163 ALL_SINCE_SAVE_MARKS_CLOSURES(CMS_SINCE_SAVE_MARKS_DEFN)
  3165 void
  3166 ConcurrentMarkSweepGeneration::younger_refs_iterate(OopsInGenClosure* cl) {
  3167   cl->set_generation(this);
  3168   younger_refs_in_space_iterate(_cmsSpace, cl);
  3169   cl->reset_generation();
  3172 void
  3173 ConcurrentMarkSweepGeneration::oop_iterate(MemRegion mr, ExtendedOopClosure* cl) {
  3174   if (freelistLock()->owned_by_self()) {
  3175     Generation::oop_iterate(mr, cl);
  3176   } else {
  3177     MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
  3178     Generation::oop_iterate(mr, cl);
  3182 void
  3183 ConcurrentMarkSweepGeneration::oop_iterate(ExtendedOopClosure* cl) {
  3184   if (freelistLock()->owned_by_self()) {
  3185     Generation::oop_iterate(cl);
  3186   } else {
  3187     MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
  3188     Generation::oop_iterate(cl);
  3192 void
  3193 ConcurrentMarkSweepGeneration::object_iterate(ObjectClosure* cl) {
  3194   if (freelistLock()->owned_by_self()) {
  3195     Generation::object_iterate(cl);
  3196   } else {
  3197     MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
  3198     Generation::object_iterate(cl);
  3202 void
  3203 ConcurrentMarkSweepGeneration::safe_object_iterate(ObjectClosure* cl) {
  3204   if (freelistLock()->owned_by_self()) {
  3205     Generation::safe_object_iterate(cl);
  3206   } else {
  3207     MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
  3208     Generation::safe_object_iterate(cl);
  3212 void
  3213 ConcurrentMarkSweepGeneration::post_compact() {
  3216 void
  3217 ConcurrentMarkSweepGeneration::prepare_for_verify() {
  3218   // Fix the linear allocation blocks to look like free blocks.
  3220   // Locks are normally acquired/released in gc_prologue/gc_epilogue, but those
  3221   // are not called when the heap is verified during universe initialization and
  3222   // at vm shutdown.
  3223   if (freelistLock()->owned_by_self()) {
  3224     cmsSpace()->prepare_for_verify();
  3225   } else {
  3226     MutexLockerEx fll(freelistLock(), Mutex::_no_safepoint_check_flag);
  3227     cmsSpace()->prepare_for_verify();
  3231 void
  3232 ConcurrentMarkSweepGeneration::verify() {
  3233   // Locks are normally acquired/released in gc_prologue/gc_epilogue, but those
  3234   // are not called when the heap is verified during universe initialization and
  3235   // at vm shutdown.
  3236   if (freelistLock()->owned_by_self()) {
  3237     cmsSpace()->verify();
  3238   } else {
  3239     MutexLockerEx fll(freelistLock(), Mutex::_no_safepoint_check_flag);
  3240     cmsSpace()->verify();
  3244 void CMSCollector::verify() {
  3245   _cmsGen->verify();
  3248 #ifndef PRODUCT
  3249 bool CMSCollector::overflow_list_is_empty() const {
  3250   assert(_num_par_pushes >= 0, "Inconsistency");
  3251   if (_overflow_list == NULL) {
  3252     assert(_num_par_pushes == 0, "Inconsistency");
  3254   return _overflow_list == NULL;
  3257 // The methods verify_work_stacks_empty() and verify_overflow_empty()
  3258 // merely consolidate assertion checks that appear to occur together frequently.
  3259 void CMSCollector::verify_work_stacks_empty() const {
  3260   assert(_markStack.isEmpty(), "Marking stack should be empty");
  3261   assert(overflow_list_is_empty(), "Overflow list should be empty");
  3264 void CMSCollector::verify_overflow_empty() const {
  3265   assert(overflow_list_is_empty(), "Overflow list should be empty");
  3266   assert(no_preserved_marks(), "No preserved marks");
  3268 #endif // PRODUCT
  3270 // Decide if we want to enable class unloading as part of the
  3271 // ensuing concurrent GC cycle. We will collect and
  3272 // unload classes if it's the case that:
  3273 // (1) an explicit gc request has been made and the flag
  3274 //     ExplicitGCInvokesConcurrentAndUnloadsClasses is set, OR
  3275 // (2) (a) class unloading is enabled at the command line, and
  3276 //     (b) old gen is getting really full
  3277 // NOTE: Provided there is no change in the state of the heap between
  3278 // calls to this method, it should have idempotent results. Moreover,
  3279 // its results should be monotonically increasing (i.e. going from 0 to 1,
  3280 // but not 1 to 0) between successive calls between which the heap was
  3281 // not collected. For the implementation below, it must thus rely on
  3282 // the property that concurrent_cycles_since_last_unload()
  3283 // will not decrease unless a collection cycle happened and that
  3284 // _cmsGen->is_too_full() are
  3285 // themselves also monotonic in that sense. See check_monotonicity()
  3286 // below.
  3287 void CMSCollector::update_should_unload_classes() {
  3288   _should_unload_classes = false;
  3289   // Condition 1 above
  3290   if (_full_gc_requested && ExplicitGCInvokesConcurrentAndUnloadsClasses) {
  3291     _should_unload_classes = true;
  3292   } else if (CMSClassUnloadingEnabled) { // Condition 2.a above
  3293     // Disjuncts 2.b.(i,ii,iii) above
  3294     _should_unload_classes = (concurrent_cycles_since_last_unload() >=
  3295                               CMSClassUnloadingMaxInterval)
  3296                            || _cmsGen->is_too_full();
  3300 bool ConcurrentMarkSweepGeneration::is_too_full() const {
  3301   bool res = should_concurrent_collect();
  3302   res = res && (occupancy() > (double)CMSIsTooFullPercentage/100.0);
  3303   return res;
  3306 void CMSCollector::setup_cms_unloading_and_verification_state() {
  3307   const  bool should_verify =   VerifyBeforeGC || VerifyAfterGC || VerifyDuringGC
  3308                              || VerifyBeforeExit;
  3309   const  int  rso           =   SharedHeap::SO_Strings | SharedHeap::SO_CodeCache;
  3311   // We set the proper root for this CMS cycle here.
  3312   if (should_unload_classes()) {   // Should unload classes this cycle
  3313     remove_root_scanning_option(SharedHeap::SO_AllClasses);
  3314     add_root_scanning_option(SharedHeap::SO_SystemClasses);
  3315     remove_root_scanning_option(rso);  // Shrink the root set appropriately
  3316     set_verifying(should_verify);    // Set verification state for this cycle
  3317     return;                            // Nothing else needs to be done at this time
  3320   // Not unloading classes this cycle
  3321   assert(!should_unload_classes(), "Inconsitency!");
  3322   remove_root_scanning_option(SharedHeap::SO_SystemClasses);
  3323   add_root_scanning_option(SharedHeap::SO_AllClasses);
  3325   if ((!verifying() || unloaded_classes_last_cycle()) && should_verify) {
  3326     // Include symbols, strings and code cache elements to prevent their resurrection.
  3327     add_root_scanning_option(rso);
  3328     set_verifying(true);
  3329   } else if (verifying() && !should_verify) {
  3330     // We were verifying, but some verification flags got disabled.
  3331     set_verifying(false);
  3332     // Exclude symbols, strings and code cache elements from root scanning to
  3333     // reduce IM and RM pauses.
  3334     remove_root_scanning_option(rso);
  3339 #ifndef PRODUCT
  3340 HeapWord* CMSCollector::block_start(const void* p) const {
  3341   const HeapWord* addr = (HeapWord*)p;
  3342   if (_span.contains(p)) {
  3343     if (_cmsGen->cmsSpace()->is_in_reserved(addr)) {
  3344       return _cmsGen->cmsSpace()->block_start(p);
  3347   return NULL;
  3349 #endif
  3351 HeapWord*
  3352 ConcurrentMarkSweepGeneration::expand_and_allocate(size_t word_size,
  3353                                                    bool   tlab,
  3354                                                    bool   parallel) {
  3355   CMSSynchronousYieldRequest yr;
  3356   assert(!tlab, "Can't deal with TLAB allocation");
  3357   MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
  3358   expand(word_size*HeapWordSize, MinHeapDeltaBytes,
  3359     CMSExpansionCause::_satisfy_allocation);
  3360   if (GCExpandToAllocateDelayMillis > 0) {
  3361     os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
  3363   return have_lock_and_allocate(word_size, tlab);
  3366 // YSR: All of this generation expansion/shrinking stuff is an exact copy of
  3367 // OneContigSpaceCardGeneration, which makes me wonder if we should move this
  3368 // to CardGeneration and share it...
  3369 bool ConcurrentMarkSweepGeneration::expand(size_t bytes, size_t expand_bytes) {
  3370   return CardGeneration::expand(bytes, expand_bytes);
  3373 void ConcurrentMarkSweepGeneration::expand(size_t bytes, size_t expand_bytes,
  3374   CMSExpansionCause::Cause cause)
  3377   bool success = expand(bytes, expand_bytes);
  3379   // remember why we expanded; this information is used
  3380   // by shouldConcurrentCollect() when making decisions on whether to start
  3381   // a new CMS cycle.
  3382   if (success) {
  3383     set_expansion_cause(cause);
  3384     if (PrintGCDetails && Verbose) {
  3385       gclog_or_tty->print_cr("Expanded CMS gen for %s",
  3386         CMSExpansionCause::to_string(cause));
  3391 HeapWord* ConcurrentMarkSweepGeneration::expand_and_par_lab_allocate(CMSParGCThreadState* ps, size_t word_sz) {
  3392   HeapWord* res = NULL;
  3393   MutexLocker x(ParGCRareEvent_lock);
  3394   while (true) {
  3395     // Expansion by some other thread might make alloc OK now:
  3396     res = ps->lab.alloc(word_sz);
  3397     if (res != NULL) return res;
  3398     // If there's not enough expansion space available, give up.
  3399     if (_virtual_space.uncommitted_size() < (word_sz * HeapWordSize)) {
  3400       return NULL;
  3402     // Otherwise, we try expansion.
  3403     expand(word_sz*HeapWordSize, MinHeapDeltaBytes,
  3404       CMSExpansionCause::_allocate_par_lab);
  3405     // Now go around the loop and try alloc again;
  3406     // A competing par_promote might beat us to the expansion space,
  3407     // so we may go around the loop again if promotion fails agaion.
  3408     if (GCExpandToAllocateDelayMillis > 0) {
  3409       os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
  3415 bool ConcurrentMarkSweepGeneration::expand_and_ensure_spooling_space(
  3416   PromotionInfo* promo) {
  3417   MutexLocker x(ParGCRareEvent_lock);
  3418   size_t refill_size_bytes = promo->refillSize() * HeapWordSize;
  3419   while (true) {
  3420     // Expansion by some other thread might make alloc OK now:
  3421     if (promo->ensure_spooling_space()) {
  3422       assert(promo->has_spooling_space(),
  3423              "Post-condition of successful ensure_spooling_space()");
  3424       return true;
  3426     // If there's not enough expansion space available, give up.
  3427     if (_virtual_space.uncommitted_size() < refill_size_bytes) {
  3428       return false;
  3430     // Otherwise, we try expansion.
  3431     expand(refill_size_bytes, MinHeapDeltaBytes,
  3432       CMSExpansionCause::_allocate_par_spooling_space);
  3433     // Now go around the loop and try alloc again;
  3434     // A competing allocation might beat us to the expansion space,
  3435     // so we may go around the loop again if allocation fails again.
  3436     if (GCExpandToAllocateDelayMillis > 0) {
  3437       os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
  3443 void ConcurrentMarkSweepGeneration::shrink_by(size_t bytes) {
  3444   assert_locked_or_safepoint(ExpandHeap_lock);
  3445   // Shrink committed space
  3446   _virtual_space.shrink_by(bytes);
  3447   // Shrink space; this also shrinks the space's BOT
  3448   _cmsSpace->set_end((HeapWord*) _virtual_space.high());
  3449   size_t new_word_size = heap_word_size(_cmsSpace->capacity());
  3450   // Shrink the shared block offset array
  3451   _bts->resize(new_word_size);
  3452   MemRegion mr(_cmsSpace->bottom(), new_word_size);
  3453   // Shrink the card table
  3454   Universe::heap()->barrier_set()->resize_covered_region(mr);
  3456   if (Verbose && PrintGC) {
  3457     size_t new_mem_size = _virtual_space.committed_size();
  3458     size_t old_mem_size = new_mem_size + bytes;
  3459     gclog_or_tty->print_cr("Shrinking %s from " SIZE_FORMAT "K to " SIZE_FORMAT "K",
  3460                   name(), old_mem_size/K, new_mem_size/K);
  3464 void ConcurrentMarkSweepGeneration::shrink(size_t bytes) {
  3465   assert_locked_or_safepoint(Heap_lock);
  3466   size_t size = ReservedSpace::page_align_size_down(bytes);
  3467   // Only shrink if a compaction was done so that all the free space
  3468   // in the generation is in a contiguous block at the end.
  3469   if (size > 0 && did_compact()) {
  3470     shrink_by(size);
  3474 bool ConcurrentMarkSweepGeneration::grow_by(size_t bytes) {
  3475   assert_locked_or_safepoint(Heap_lock);
  3476   bool result = _virtual_space.expand_by(bytes);
  3477   if (result) {
  3478     size_t new_word_size =
  3479       heap_word_size(_virtual_space.committed_size());
  3480     MemRegion mr(_cmsSpace->bottom(), new_word_size);
  3481     _bts->resize(new_word_size);  // resize the block offset shared array
  3482     Universe::heap()->barrier_set()->resize_covered_region(mr);
  3483     // Hmmmm... why doesn't CFLS::set_end verify locking?
  3484     // This is quite ugly; FIX ME XXX
  3485     _cmsSpace->assert_locked(freelistLock());
  3486     _cmsSpace->set_end((HeapWord*)_virtual_space.high());
  3488     // update the space and generation capacity counters
  3489     if (UsePerfData) {
  3490       _space_counters->update_capacity();
  3491       _gen_counters->update_all();
  3494     if (Verbose && PrintGC) {
  3495       size_t new_mem_size = _virtual_space.committed_size();
  3496       size_t old_mem_size = new_mem_size - bytes;
  3497       gclog_or_tty->print_cr("Expanding %s from " SIZE_FORMAT "K by " SIZE_FORMAT "K to " SIZE_FORMAT "K",
  3498                     name(), old_mem_size/K, bytes/K, new_mem_size/K);
  3501   return result;
  3504 bool ConcurrentMarkSweepGeneration::grow_to_reserved() {
  3505   assert_locked_or_safepoint(Heap_lock);
  3506   bool success = true;
  3507   const size_t remaining_bytes = _virtual_space.uncommitted_size();
  3508   if (remaining_bytes > 0) {
  3509     success = grow_by(remaining_bytes);
  3510     DEBUG_ONLY(if (!success) warning("grow to reserved failed");)
  3512   return success;
  3515 void ConcurrentMarkSweepGeneration::shrink_free_list_by(size_t bytes) {
  3516   assert_locked_or_safepoint(Heap_lock);
  3517   assert_lock_strong(freelistLock());
  3518   if (PrintGCDetails && Verbose) {
  3519     warning("Shrinking of CMS not yet implemented");
  3521   return;
  3525 // Simple ctor/dtor wrapper for accounting & timer chores around concurrent
  3526 // phases.
  3527 class CMSPhaseAccounting: public StackObj {
  3528  public:
  3529   CMSPhaseAccounting(CMSCollector *collector,
  3530                      const char *phase,
  3531                      bool print_cr = true);
  3532   ~CMSPhaseAccounting();
  3534  private:
  3535   CMSCollector *_collector;
  3536   const char *_phase;
  3537   elapsedTimer _wallclock;
  3538   bool _print_cr;
  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                                        bool print_cr) :
  3555   _collector(collector), _phase(phase), _print_cr(print_cr) {
  3557   if (PrintCMSStatistics != 0) {
  3558     _collector->resetYields();
  3560   if (PrintGCDetails) {
  3561     gclog_or_tty->date_stamp(PrintGCDateStamps);
  3562     gclog_or_tty->stamp(PrintGCTimeStamps);
  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->date_stamp(PrintGCDateStamps);
  3577     gclog_or_tty->stamp(PrintGCTimeStamps);
  3578     gclog_or_tty->print("[%s-concurrent-%s: %3.3f/%3.3f secs]",
  3579                  _collector->cmsGen()->short_name(),
  3580                  _phase, _collector->timerValue(), _wallclock.seconds());
  3581     if (_print_cr) {
  3582       gclog_or_tty->cr();
  3584     if (PrintCMSStatistics != 0) {
  3585       gclog_or_tty->print_cr(" (CMS-concurrent-%s yielded %d times)", _phase,
  3586                     _collector->yields());
  3591 // CMS work
  3593 // The common parts of CMSParInitialMarkTask and CMSParRemarkTask.
  3594 class CMSParMarkTask : public AbstractGangTask {
  3595  protected:
  3596   CMSCollector*     _collector;
  3597   int               _n_workers;
  3598   CMSParMarkTask(const char* name, CMSCollector* collector, int n_workers) :
  3599       AbstractGangTask(name),
  3600       _collector(collector),
  3601       _n_workers(n_workers) {}
  3602   // Work method in support of parallel rescan ... of young gen spaces
  3603   void do_young_space_rescan(uint worker_id, OopsInGenClosure* cl,
  3604                              ContiguousSpace* space,
  3605                              HeapWord** chunk_array, size_t chunk_top);
  3606   void work_on_young_gen_roots(uint worker_id, OopsInGenClosure* cl);
  3607 };
  3609 // Parallel initial mark task
  3610 class CMSParInitialMarkTask: public CMSParMarkTask {
  3611  public:
  3612   CMSParInitialMarkTask(CMSCollector* collector, int n_workers) :
  3613       CMSParMarkTask("Scan roots and young gen for initial mark in parallel",
  3614                      collector, n_workers) {}
  3615   void work(uint worker_id);
  3616 };
  3618 // Checkpoint the roots into this generation from outside
  3619 // this generation. [Note this initial checkpoint need only
  3620 // be approximate -- we'll do a catch up phase subsequently.]
  3621 void CMSCollector::checkpointRootsInitial(bool asynch) {
  3622   assert(_collectorState == InitialMarking, "Wrong collector state");
  3623   check_correct_thread_executing();
  3624   TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause());
  3626   save_heap_summary();
  3627   report_heap_summary(GCWhen::BeforeGC);
  3629   ReferenceProcessor* rp = ref_processor();
  3630   SpecializationStats::clear();
  3631   assert(_restart_addr == NULL, "Control point invariant");
  3632   if (asynch) {
  3633     // acquire locks for subsequent manipulations
  3634     MutexLockerEx x(bitMapLock(),
  3635                     Mutex::_no_safepoint_check_flag);
  3636     checkpointRootsInitialWork(asynch);
  3637     // enable ("weak") refs discovery
  3638     rp->enable_discovery(true /*verify_disabled*/, true /*check_no_refs*/);
  3639     _collectorState = Marking;
  3640   } else {
  3641     // (Weak) Refs discovery: this is controlled from genCollectedHeap::do_collection
  3642     // which recognizes if we are a CMS generation, and doesn't try to turn on
  3643     // discovery; verify that they aren't meddling.
  3644     assert(!rp->discovery_is_atomic(),
  3645            "incorrect setting of discovery predicate");
  3646     assert(!rp->discovery_enabled(), "genCollectedHeap shouldn't control "
  3647            "ref discovery for this generation kind");
  3648     // already have locks
  3649     checkpointRootsInitialWork(asynch);
  3650     // now enable ("weak") refs discovery
  3651     rp->enable_discovery(true /*verify_disabled*/, false /*verify_no_refs*/);
  3652     _collectorState = Marking;
  3654   SpecializationStats::print();
  3657 void CMSCollector::checkpointRootsInitialWork(bool asynch) {
  3658   assert(SafepointSynchronize::is_at_safepoint(), "world should be stopped");
  3659   assert(_collectorState == InitialMarking, "just checking");
  3661   // If there has not been a GC[n-1] since last GC[n] cycle completed,
  3662   // precede our marking with a collection of all
  3663   // younger generations to keep floating garbage to a minimum.
  3664   // XXX: we won't do this for now -- it's an optimization to be done later.
  3666   // already have locks
  3667   assert_lock_strong(bitMapLock());
  3668   assert(_markBitMap.isAllClear(), "was reset at end of previous cycle");
  3670   // Setup the verification and class unloading state for this
  3671   // CMS collection cycle.
  3672   setup_cms_unloading_and_verification_state();
  3674   NOT_PRODUCT(GCTraceTime t("\ncheckpointRootsInitialWork",
  3675     PrintGCDetails && Verbose, true, _gc_timer_cm);)
  3676   if (UseAdaptiveSizePolicy) {
  3677     size_policy()->checkpoint_roots_initial_begin();
  3680   // Reset all the PLAB chunk arrays if necessary.
  3681   if (_survivor_plab_array != NULL && !CMSPLABRecordAlways) {
  3682     reset_survivor_plab_arrays();
  3685   ResourceMark rm;
  3686   HandleMark  hm;
  3688   FalseClosure falseClosure;
  3689   // In the case of a synchronous collection, we will elide the
  3690   // remark step, so it's important to catch all the nmethod oops
  3691   // in this step.
  3692   // The final 'true' flag to gen_process_strong_roots will ensure this.
  3693   // If 'async' is true, we can relax the nmethod tracing.
  3694   MarkRefsIntoClosure notOlder(_span, &_markBitMap);
  3695   GenCollectedHeap* gch = GenCollectedHeap::heap();
  3697   verify_work_stacks_empty();
  3698   verify_overflow_empty();
  3700   gch->ensure_parsability(false);  // fill TLABs, but no need to retire them
  3701   // Update the saved marks which may affect the root scans.
  3702   gch->save_marks();
  3704   // weak reference processing has not started yet.
  3705   ref_processor()->set_enqueuing_is_done(false);
  3707   // Need to remember all newly created CLDs,
  3708   // so that we can guarantee that the remark finds them.
  3709   ClassLoaderDataGraph::remember_new_clds(true);
  3711   // Whenever a CLD is found, it will be claimed before proceeding to mark
  3712   // the klasses. The claimed marks need to be cleared before marking starts.
  3713   ClassLoaderDataGraph::clear_claimed_marks();
  3715   if (CMSPrintEdenSurvivorChunks) {
  3716     print_eden_and_survivor_chunk_arrays();
  3720     COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;)
  3721     if (CMSParallelInitialMarkEnabled && CollectedHeap::use_parallel_gc_threads()) {
  3722       // The parallel version.
  3723       FlexibleWorkGang* workers = gch->workers();
  3724       assert(workers != NULL, "Need parallel worker threads.");
  3725       int n_workers = workers->active_workers();
  3726       CMSParInitialMarkTask tsk(this, n_workers);
  3727       gch->set_par_threads(n_workers);
  3728       initialize_sequential_subtasks_for_young_gen_rescan(n_workers);
  3729       if (n_workers > 1) {
  3730         GenCollectedHeap::StrongRootsScope srs(gch);
  3731         workers->run_task(&tsk);
  3732       } else {
  3733         GenCollectedHeap::StrongRootsScope srs(gch);
  3734         tsk.work(0);
  3736       gch->set_par_threads(0);
  3737     } else {
  3738       // The serial version.
  3739       CMKlassClosure klass_closure(&notOlder);
  3740       gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
  3741       gch->gen_process_strong_roots(_cmsGen->level(),
  3742                                     true,   // younger gens are roots
  3743                                     true,   // activate StrongRootsScope
  3744                                     false,  // not scavenging
  3745                                     SharedHeap::ScanningOption(roots_scanning_options()),
  3746                                     &notOlder,
  3747                                     true,   // walk all of code cache if (so & SO_CodeCache)
  3748                                     NULL,
  3749                                     &klass_closure);
  3753   // Clear mod-union table; it will be dirtied in the prologue of
  3754   // CMS generation per each younger generation collection.
  3756   assert(_modUnionTable.isAllClear(),
  3757        "Was cleared in most recent final checkpoint phase"
  3758        " or no bits are set in the gc_prologue before the start of the next "
  3759        "subsequent marking phase.");
  3761   assert(_ct->klass_rem_set()->mod_union_is_clear(), "Must be");
  3763   // Save the end of the used_region of the constituent generations
  3764   // to be used to limit the extent of sweep in each generation.
  3765   save_sweep_limits();
  3766   if (UseAdaptiveSizePolicy) {
  3767     size_policy()->checkpoint_roots_initial_end(gch->gc_cause());
  3769   verify_overflow_empty();
  3772 bool CMSCollector::markFromRoots(bool asynch) {
  3773   // we might be tempted to assert that:
  3774   // assert(asynch == !SafepointSynchronize::is_at_safepoint(),
  3775   //        "inconsistent argument?");
  3776   // However that wouldn't be right, because it's possible that
  3777   // a safepoint is indeed in progress as a younger generation
  3778   // stop-the-world GC happens even as we mark in this generation.
  3779   assert(_collectorState == Marking, "inconsistent state?");
  3780   check_correct_thread_executing();
  3781   verify_overflow_empty();
  3783   bool res;
  3784   if (asynch) {
  3786     // Start the timers for adaptive size policy for the concurrent phases
  3787     // Do it here so that the foreground MS can use the concurrent
  3788     // timer since a foreground MS might has the sweep done concurrently
  3789     // or STW.
  3790     if (UseAdaptiveSizePolicy) {
  3791       size_policy()->concurrent_marking_begin();
  3794     // Weak ref discovery note: We may be discovering weak
  3795     // refs in this generation concurrent (but interleaved) with
  3796     // weak ref discovery by a younger generation collector.
  3798     CMSTokenSyncWithLocks ts(true, bitMapLock());
  3799     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  3800     CMSPhaseAccounting pa(this, "mark", !PrintGCDetails);
  3801     res = markFromRootsWork(asynch);
  3802     if (res) {
  3803       _collectorState = Precleaning;
  3804     } else { // We failed and a foreground collection wants to take over
  3805       assert(_foregroundGCIsActive, "internal state inconsistency");
  3806       assert(_restart_addr == NULL,  "foreground will restart from scratch");
  3807       if (PrintGCDetails) {
  3808         gclog_or_tty->print_cr("bailing out to foreground collection");
  3811     if (UseAdaptiveSizePolicy) {
  3812       size_policy()->concurrent_marking_end();
  3814   } else {
  3815     assert(SafepointSynchronize::is_at_safepoint(),
  3816            "inconsistent with asynch == false");
  3817     if (UseAdaptiveSizePolicy) {
  3818       size_policy()->ms_collection_marking_begin();
  3820     // already have locks
  3821     res = markFromRootsWork(asynch);
  3822     _collectorState = FinalMarking;
  3823     if (UseAdaptiveSizePolicy) {
  3824       GenCollectedHeap* gch = GenCollectedHeap::heap();
  3825       size_policy()->ms_collection_marking_end(gch->gc_cause());
  3828   verify_overflow_empty();
  3829   return res;
  3832 bool CMSCollector::markFromRootsWork(bool asynch) {
  3833   // iterate over marked bits in bit map, doing a full scan and mark
  3834   // from these roots using the following algorithm:
  3835   // . if oop is to the right of the current scan pointer,
  3836   //   mark corresponding bit (we'll process it later)
  3837   // . else (oop is to left of current scan pointer)
  3838   //   push oop on marking stack
  3839   // . drain the marking stack
  3841   // Note that when we do a marking step we need to hold the
  3842   // bit map lock -- recall that direct allocation (by mutators)
  3843   // and promotion (by younger generation collectors) is also
  3844   // marking the bit map. [the so-called allocate live policy.]
  3845   // Because the implementation of bit map marking is not
  3846   // robust wrt simultaneous marking of bits in the same word,
  3847   // we need to make sure that there is no such interference
  3848   // between concurrent such updates.
  3850   // already have locks
  3851   assert_lock_strong(bitMapLock());
  3853   verify_work_stacks_empty();
  3854   verify_overflow_empty();
  3855   bool result = false;
  3856   if (CMSConcurrentMTEnabled && ConcGCThreads > 0) {
  3857     result = do_marking_mt(asynch);
  3858   } else {
  3859     result = do_marking_st(asynch);
  3861   return result;
  3864 // Forward decl
  3865 class CMSConcMarkingTask;
  3867 class CMSConcMarkingTerminator: public ParallelTaskTerminator {
  3868   CMSCollector*       _collector;
  3869   CMSConcMarkingTask* _task;
  3870  public:
  3871   virtual void yield();
  3873   // "n_threads" is the number of threads to be terminated.
  3874   // "queue_set" is a set of work queues of other threads.
  3875   // "collector" is the CMS collector associated with this task terminator.
  3876   // "yield" indicates whether we need the gang as a whole to yield.
  3877   CMSConcMarkingTerminator(int n_threads, TaskQueueSetSuper* queue_set, CMSCollector* collector) :
  3878     ParallelTaskTerminator(n_threads, queue_set),
  3879     _collector(collector) { }
  3881   void set_task(CMSConcMarkingTask* task) {
  3882     _task = task;
  3884 };
  3886 class CMSConcMarkingTerminatorTerminator: public TerminatorTerminator {
  3887   CMSConcMarkingTask* _task;
  3888  public:
  3889   bool should_exit_termination();
  3890   void set_task(CMSConcMarkingTask* task) {
  3891     _task = task;
  3893 };
  3895 // MT Concurrent Marking Task
  3896 class CMSConcMarkingTask: public YieldingFlexibleGangTask {
  3897   CMSCollector* _collector;
  3898   int           _n_workers;                  // requested/desired # workers
  3899   bool          _asynch;
  3900   bool          _result;
  3901   CompactibleFreeListSpace*  _cms_space;
  3902   char          _pad_front[64];   // padding to ...
  3903   HeapWord*     _global_finger;   // ... avoid sharing cache line
  3904   char          _pad_back[64];
  3905   HeapWord*     _restart_addr;
  3907   //  Exposed here for yielding support
  3908   Mutex* const _bit_map_lock;
  3910   // The per thread work queues, available here for stealing
  3911   OopTaskQueueSet*  _task_queues;
  3913   // Termination (and yielding) support
  3914   CMSConcMarkingTerminator _term;
  3915   CMSConcMarkingTerminatorTerminator _term_term;
  3917  public:
  3918   CMSConcMarkingTask(CMSCollector* collector,
  3919                  CompactibleFreeListSpace* cms_space,
  3920                  bool asynch,
  3921                  YieldingFlexibleWorkGang* workers,
  3922                  OopTaskQueueSet* task_queues):
  3923     YieldingFlexibleGangTask("Concurrent marking done multi-threaded"),
  3924     _collector(collector),
  3925     _cms_space(cms_space),
  3926     _asynch(asynch), _n_workers(0), _result(true),
  3927     _task_queues(task_queues),
  3928     _term(_n_workers, task_queues, _collector),
  3929     _bit_map_lock(collector->bitMapLock())
  3931     _requested_size = _n_workers;
  3932     _term.set_task(this);
  3933     _term_term.set_task(this);
  3934     _restart_addr = _global_finger = _cms_space->bottom();
  3938   OopTaskQueueSet* task_queues()  { return _task_queues; }
  3940   OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); }
  3942   HeapWord** global_finger_addr() { return &_global_finger; }
  3944   CMSConcMarkingTerminator* terminator() { return &_term; }
  3946   virtual void set_for_termination(int active_workers) {
  3947     terminator()->reset_for_reuse(active_workers);
  3950   void work(uint worker_id);
  3951   bool should_yield() {
  3952     return    ConcurrentMarkSweepThread::should_yield()
  3953            && !_collector->foregroundGCIsActive()
  3954            && _asynch;
  3957   virtual void coordinator_yield();  // stuff done by coordinator
  3958   bool result() { return _result; }
  3960   void reset(HeapWord* ra) {
  3961     assert(_global_finger >= _cms_space->end(),  "Postcondition of ::work(i)");
  3962     _restart_addr = _global_finger = ra;
  3963     _term.reset_for_reuse();
  3966   static bool get_work_from_overflow_stack(CMSMarkStack* ovflw_stk,
  3967                                            OopTaskQueue* work_q);
  3969  private:
  3970   void do_scan_and_mark(int i, CompactibleFreeListSpace* sp);
  3971   void do_work_steal(int i);
  3972   void bump_global_finger(HeapWord* f);
  3973 };
  3975 bool CMSConcMarkingTerminatorTerminator::should_exit_termination() {
  3976   assert(_task != NULL, "Error");
  3977   return _task->yielding();
  3978   // Note that we do not need the disjunct || _task->should_yield() above
  3979   // because we want terminating threads to yield only if the task
  3980   // is already in the midst of yielding, which happens only after at least one
  3981   // thread has yielded.
  3984 void CMSConcMarkingTerminator::yield() {
  3985   if (_task->should_yield()) {
  3986     _task->yield();
  3987   } else {
  3988     ParallelTaskTerminator::yield();
  3992 ////////////////////////////////////////////////////////////////
  3993 // Concurrent Marking Algorithm Sketch
  3994 ////////////////////////////////////////////////////////////////
  3995 // Until all tasks exhausted (both spaces):
  3996 // -- claim next available chunk
  3997 // -- bump global finger via CAS
  3998 // -- find first object that starts in this chunk
  3999 //    and start scanning bitmap from that position
  4000 // -- scan marked objects for oops
  4001 // -- CAS-mark target, and if successful:
  4002 //    . if target oop is above global finger (volatile read)
  4003 //      nothing to do
  4004 //    . if target oop is in chunk and above local finger
  4005 //        then nothing to do
  4006 //    . else push on work-queue
  4007 // -- Deal with possible overflow issues:
  4008 //    . local work-queue overflow causes stuff to be pushed on
  4009 //      global (common) overflow queue
  4010 //    . always first empty local work queue
  4011 //    . then get a batch of oops from global work queue if any
  4012 //    . then do work stealing
  4013 // -- When all tasks claimed (both spaces)
  4014 //    and local work queue empty,
  4015 //    then in a loop do:
  4016 //    . check global overflow stack; steal a batch of oops and trace
  4017 //    . try to steal from other threads oif GOS is empty
  4018 //    . if neither is available, offer termination
  4019 // -- Terminate and return result
  4020 //
  4021 void CMSConcMarkingTask::work(uint worker_id) {
  4022   elapsedTimer _timer;
  4023   ResourceMark rm;
  4024   HandleMark hm;
  4026   DEBUG_ONLY(_collector->verify_overflow_empty();)
  4028   // Before we begin work, our work queue should be empty
  4029   assert(work_queue(worker_id)->size() == 0, "Expected to be empty");
  4030   // Scan the bitmap covering _cms_space, tracing through grey objects.
  4031   _timer.start();
  4032   do_scan_and_mark(worker_id, _cms_space);
  4033   _timer.stop();
  4034   if (PrintCMSStatistics != 0) {
  4035     gclog_or_tty->print_cr("Finished cms space scanning in %dth thread: %3.3f sec",
  4036       worker_id, _timer.seconds());
  4037       // XXX: need xxx/xxx type of notation, two timers
  4040   // ... do work stealing
  4041   _timer.reset();
  4042   _timer.start();
  4043   do_work_steal(worker_id);
  4044   _timer.stop();
  4045   if (PrintCMSStatistics != 0) {
  4046     gclog_or_tty->print_cr("Finished work stealing in %dth thread: %3.3f sec",
  4047       worker_id, _timer.seconds());
  4048       // XXX: need xxx/xxx type of notation, two timers
  4050   assert(_collector->_markStack.isEmpty(), "Should have been emptied");
  4051   assert(work_queue(worker_id)->size() == 0, "Should have been emptied");
  4052   // Note that under the current task protocol, the
  4053   // following assertion is true even of the spaces
  4054   // expanded since the completion of the concurrent
  4055   // marking. XXX This will likely change under a strict
  4056   // ABORT semantics.
  4057   // After perm removal the comparison was changed to
  4058   // greater than or equal to from strictly greater than.
  4059   // Before perm removal the highest address sweep would
  4060   // have been at the end of perm gen but now is at the
  4061   // end of the tenured gen.
  4062   assert(_global_finger >=  _cms_space->end(),
  4063          "All tasks have been completed");
  4064   DEBUG_ONLY(_collector->verify_overflow_empty();)
  4067 void CMSConcMarkingTask::bump_global_finger(HeapWord* f) {
  4068   HeapWord* read = _global_finger;
  4069   HeapWord* cur  = read;
  4070   while (f > read) {
  4071     cur = read;
  4072     read = (HeapWord*) Atomic::cmpxchg_ptr(f, &_global_finger, cur);
  4073     if (cur == read) {
  4074       // our cas succeeded
  4075       assert(_global_finger >= f, "protocol consistency");
  4076       break;
  4081 // This is really inefficient, and should be redone by
  4082 // using (not yet available) block-read and -write interfaces to the
  4083 // stack and the work_queue. XXX FIX ME !!!
  4084 bool CMSConcMarkingTask::get_work_from_overflow_stack(CMSMarkStack* ovflw_stk,
  4085                                                       OopTaskQueue* work_q) {
  4086   // Fast lock-free check
  4087   if (ovflw_stk->length() == 0) {
  4088     return false;
  4090   assert(work_q->size() == 0, "Shouldn't steal");
  4091   MutexLockerEx ml(ovflw_stk->par_lock(),
  4092                    Mutex::_no_safepoint_check_flag);
  4093   // Grab up to 1/4 the size of the work queue
  4094   size_t num = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
  4095                     (size_t)ParGCDesiredObjsFromOverflowList);
  4096   num = MIN2(num, ovflw_stk->length());
  4097   for (int i = (int) num; i > 0; i--) {
  4098     oop cur = ovflw_stk->pop();
  4099     assert(cur != NULL, "Counted wrong?");
  4100     work_q->push(cur);
  4102   return num > 0;
  4105 void CMSConcMarkingTask::do_scan_and_mark(int i, CompactibleFreeListSpace* sp) {
  4106   SequentialSubTasksDone* pst = sp->conc_par_seq_tasks();
  4107   int n_tasks = pst->n_tasks();
  4108   // We allow that there may be no tasks to do here because
  4109   // we are restarting after a stack overflow.
  4110   assert(pst->valid() || n_tasks == 0, "Uninitialized use?");
  4111   uint nth_task = 0;
  4113   HeapWord* aligned_start = sp->bottom();
  4114   if (sp->used_region().contains(_restart_addr)) {
  4115     // Align down to a card boundary for the start of 0th task
  4116     // for this space.
  4117     aligned_start =
  4118       (HeapWord*)align_size_down((uintptr_t)_restart_addr,
  4119                                  CardTableModRefBS::card_size);
  4122   size_t chunk_size = sp->marking_task_size();
  4123   while (!pst->is_task_claimed(/* reference */ nth_task)) {
  4124     // Having claimed the nth task in this space,
  4125     // compute the chunk that it corresponds to:
  4126     MemRegion span = MemRegion(aligned_start + nth_task*chunk_size,
  4127                                aligned_start + (nth_task+1)*chunk_size);
  4128     // Try and bump the global finger via a CAS;
  4129     // note that we need to do the global finger bump
  4130     // _before_ taking the intersection below, because
  4131     // the task corresponding to that region will be
  4132     // deemed done even if the used_region() expands
  4133     // because of allocation -- as it almost certainly will
  4134     // during start-up while the threads yield in the
  4135     // closure below.
  4136     HeapWord* finger = span.end();
  4137     bump_global_finger(finger);   // atomically
  4138     // There are null tasks here corresponding to chunks
  4139     // beyond the "top" address of the space.
  4140     span = span.intersection(sp->used_region());
  4141     if (!span.is_empty()) {  // Non-null task
  4142       HeapWord* prev_obj;
  4143       assert(!span.contains(_restart_addr) || nth_task == 0,
  4144              "Inconsistency");
  4145       if (nth_task == 0) {
  4146         // For the 0th task, we'll not need to compute a block_start.
  4147         if (span.contains(_restart_addr)) {
  4148           // In the case of a restart because of stack overflow,
  4149           // we might additionally skip a chunk prefix.
  4150           prev_obj = _restart_addr;
  4151         } else {
  4152           prev_obj = span.start();
  4154       } else {
  4155         // We want to skip the first object because
  4156         // the protocol is to scan any object in its entirety
  4157         // that _starts_ in this span; a fortiori, any
  4158         // object starting in an earlier span is scanned
  4159         // as part of an earlier claimed task.
  4160         // Below we use the "careful" version of block_start
  4161         // so we do not try to navigate uninitialized objects.
  4162         prev_obj = sp->block_start_careful(span.start());
  4163         // Below we use a variant of block_size that uses the
  4164         // Printezis bits to avoid waiting for allocated
  4165         // objects to become initialized/parsable.
  4166         while (prev_obj < span.start()) {
  4167           size_t sz = sp->block_size_no_stall(prev_obj, _collector);
  4168           if (sz > 0) {
  4169             prev_obj += sz;
  4170           } else {
  4171             // In this case we may end up doing a bit of redundant
  4172             // scanning, but that appears unavoidable, short of
  4173             // locking the free list locks; see bug 6324141.
  4174             break;
  4178       if (prev_obj < span.end()) {
  4179         MemRegion my_span = MemRegion(prev_obj, span.end());
  4180         // Do the marking work within a non-empty span --
  4181         // the last argument to the constructor indicates whether the
  4182         // iteration should be incremental with periodic yields.
  4183         Par_MarkFromRootsClosure cl(this, _collector, my_span,
  4184                                     &_collector->_markBitMap,
  4185                                     work_queue(i),
  4186                                     &_collector->_markStack,
  4187                                     _asynch);
  4188         _collector->_markBitMap.iterate(&cl, my_span.start(), my_span.end());
  4189       } // else nothing to do for this task
  4190     }   // else nothing to do for this task
  4192   // We'd be tempted to assert here that since there are no
  4193   // more tasks left to claim in this space, the global_finger
  4194   // must exceed space->top() and a fortiori space->end(). However,
  4195   // that would not quite be correct because the bumping of
  4196   // global_finger occurs strictly after the claiming of a task,
  4197   // so by the time we reach here the global finger may not yet
  4198   // have been bumped up by the thread that claimed the last
  4199   // task.
  4200   pst->all_tasks_completed();
  4203 class Par_ConcMarkingClosure: public CMSOopClosure {
  4204  private:
  4205   CMSCollector* _collector;
  4206   CMSConcMarkingTask* _task;
  4207   MemRegion     _span;
  4208   CMSBitMap*    _bit_map;
  4209   CMSMarkStack* _overflow_stack;
  4210   OopTaskQueue* _work_queue;
  4211  protected:
  4212   DO_OOP_WORK_DEFN
  4213  public:
  4214   Par_ConcMarkingClosure(CMSCollector* collector, CMSConcMarkingTask* task, OopTaskQueue* work_queue,
  4215                          CMSBitMap* bit_map, CMSMarkStack* overflow_stack):
  4216     CMSOopClosure(collector->ref_processor()),
  4217     _collector(collector),
  4218     _task(task),
  4219     _span(collector->_span),
  4220     _work_queue(work_queue),
  4221     _bit_map(bit_map),
  4222     _overflow_stack(overflow_stack)
  4223   { }
  4224   virtual void do_oop(oop* p);
  4225   virtual void do_oop(narrowOop* p);
  4227   void trim_queue(size_t max);
  4228   void handle_stack_overflow(HeapWord* lost);
  4229   void do_yield_check() {
  4230     if (_task->should_yield()) {
  4231       _task->yield();
  4234 };
  4236 // Grey object scanning during work stealing phase --
  4237 // the salient assumption here is that any references
  4238 // that are in these stolen objects being scanned must
  4239 // already have been initialized (else they would not have
  4240 // been published), so we do not need to check for
  4241 // uninitialized objects before pushing here.
  4242 void Par_ConcMarkingClosure::do_oop(oop obj) {
  4243   assert(obj->is_oop_or_null(true), "expected an oop or NULL");
  4244   HeapWord* addr = (HeapWord*)obj;
  4245   // Check if oop points into the CMS generation
  4246   // and is not marked
  4247   if (_span.contains(addr) && !_bit_map->isMarked(addr)) {
  4248     // a white object ...
  4249     // If we manage to "claim" the object, by being the
  4250     // first thread to mark it, then we push it on our
  4251     // marking stack
  4252     if (_bit_map->par_mark(addr)) {     // ... now grey
  4253       // push on work queue (grey set)
  4254       bool simulate_overflow = false;
  4255       NOT_PRODUCT(
  4256         if (CMSMarkStackOverflowALot &&
  4257             _collector->simulate_overflow()) {
  4258           // simulate a stack overflow
  4259           simulate_overflow = true;
  4262       if (simulate_overflow ||
  4263           !(_work_queue->push(obj) || _overflow_stack->par_push(obj))) {
  4264         // stack overflow
  4265         if (PrintCMSStatistics != 0) {
  4266           gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
  4267                                  SIZE_FORMAT, _overflow_stack->capacity());
  4269         // We cannot assert that the overflow stack is full because
  4270         // it may have been emptied since.
  4271         assert(simulate_overflow ||
  4272                _work_queue->size() == _work_queue->max_elems(),
  4273               "Else push should have succeeded");
  4274         handle_stack_overflow(addr);
  4276     } // Else, some other thread got there first
  4277     do_yield_check();
  4281 void Par_ConcMarkingClosure::do_oop(oop* p)       { Par_ConcMarkingClosure::do_oop_work(p); }
  4282 void Par_ConcMarkingClosure::do_oop(narrowOop* p) { Par_ConcMarkingClosure::do_oop_work(p); }
  4284 void Par_ConcMarkingClosure::trim_queue(size_t max) {
  4285   while (_work_queue->size() > max) {
  4286     oop new_oop;
  4287     if (_work_queue->pop_local(new_oop)) {
  4288       assert(new_oop->is_oop(), "Should be an oop");
  4289       assert(_bit_map->isMarked((HeapWord*)new_oop), "Grey object");
  4290       assert(_span.contains((HeapWord*)new_oop), "Not in span");
  4291       new_oop->oop_iterate(this);  // do_oop() above
  4292       do_yield_check();
  4297 // Upon stack overflow, we discard (part of) the stack,
  4298 // remembering the least address amongst those discarded
  4299 // in CMSCollector's _restart_address.
  4300 void Par_ConcMarkingClosure::handle_stack_overflow(HeapWord* lost) {
  4301   // We need to do this under a mutex to prevent other
  4302   // workers from interfering with the work done below.
  4303   MutexLockerEx ml(_overflow_stack->par_lock(),
  4304                    Mutex::_no_safepoint_check_flag);
  4305   // Remember the least grey address discarded
  4306   HeapWord* ra = (HeapWord*)_overflow_stack->least_value(lost);
  4307   _collector->lower_restart_addr(ra);
  4308   _overflow_stack->reset();  // discard stack contents
  4309   _overflow_stack->expand(); // expand the stack if possible
  4313 void CMSConcMarkingTask::do_work_steal(int i) {
  4314   OopTaskQueue* work_q = work_queue(i);
  4315   oop obj_to_scan;
  4316   CMSBitMap* bm = &(_collector->_markBitMap);
  4317   CMSMarkStack* ovflw = &(_collector->_markStack);
  4318   int* seed = _collector->hash_seed(i);
  4319   Par_ConcMarkingClosure cl(_collector, this, work_q, bm, ovflw);
  4320   while (true) {
  4321     cl.trim_queue(0);
  4322     assert(work_q->size() == 0, "Should have been emptied above");
  4323     if (get_work_from_overflow_stack(ovflw, work_q)) {
  4324       // Can't assert below because the work obtained from the
  4325       // overflow stack may already have been stolen from us.
  4326       // assert(work_q->size() > 0, "Work from overflow stack");
  4327       continue;
  4328     } else if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) {
  4329       assert(obj_to_scan->is_oop(), "Should be an oop");
  4330       assert(bm->isMarked((HeapWord*)obj_to_scan), "Grey object");
  4331       obj_to_scan->oop_iterate(&cl);
  4332     } else if (terminator()->offer_termination(&_term_term)) {
  4333       assert(work_q->size() == 0, "Impossible!");
  4334       break;
  4335     } else if (yielding() || should_yield()) {
  4336       yield();
  4341 // This is run by the CMS (coordinator) thread.
  4342 void CMSConcMarkingTask::coordinator_yield() {
  4343   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  4344          "CMS thread should hold CMS token");
  4345   // First give up the locks, then yield, then re-lock
  4346   // We should probably use a constructor/destructor idiom to
  4347   // do this unlock/lock or modify the MutexUnlocker class to
  4348   // serve our purpose. XXX
  4349   assert_lock_strong(_bit_map_lock);
  4350   _bit_map_lock->unlock();
  4351   ConcurrentMarkSweepThread::desynchronize(true);
  4352   ConcurrentMarkSweepThread::acknowledge_yield_request();
  4353   _collector->stopTimer();
  4354   if (PrintCMSStatistics != 0) {
  4355     _collector->incrementYields();
  4357   _collector->icms_wait();
  4359   // It is possible for whichever thread initiated the yield request
  4360   // not to get a chance to wake up and take the bitmap lock between
  4361   // this thread releasing it and reacquiring it. So, while the
  4362   // should_yield() flag is on, let's sleep for a bit to give the
  4363   // other thread a chance to wake up. The limit imposed on the number
  4364   // of iterations is defensive, to avoid any unforseen circumstances
  4365   // putting us into an infinite loop. Since it's always been this
  4366   // (coordinator_yield()) method that was observed to cause the
  4367   // problem, we are using a parameter (CMSCoordinatorYieldSleepCount)
  4368   // which is by default non-zero. For the other seven methods that
  4369   // also perform the yield operation, as are using a different
  4370   // parameter (CMSYieldSleepCount) which is by default zero. This way we
  4371   // can enable the sleeping for those methods too, if necessary.
  4372   // See 6442774.
  4373   //
  4374   // We really need to reconsider the synchronization between the GC
  4375   // thread and the yield-requesting threads in the future and we
  4376   // should really use wait/notify, which is the recommended
  4377   // way of doing this type of interaction. Additionally, we should
  4378   // consolidate the eight methods that do the yield operation and they
  4379   // are almost identical into one for better maintenability and
  4380   // readability. See 6445193.
  4381   //
  4382   // Tony 2006.06.29
  4383   for (unsigned i = 0; i < CMSCoordinatorYieldSleepCount &&
  4384                    ConcurrentMarkSweepThread::should_yield() &&
  4385                    !CMSCollector::foregroundGCIsActive(); ++i) {
  4386     os::sleep(Thread::current(), 1, false);
  4387     ConcurrentMarkSweepThread::acknowledge_yield_request();
  4390   ConcurrentMarkSweepThread::synchronize(true);
  4391   _bit_map_lock->lock_without_safepoint_check();
  4392   _collector->startTimer();
  4395 bool CMSCollector::do_marking_mt(bool asynch) {
  4396   assert(ConcGCThreads > 0 && conc_workers() != NULL, "precondition");
  4397   int num_workers = AdaptiveSizePolicy::calc_active_conc_workers(
  4398                                        conc_workers()->total_workers(),
  4399                                        conc_workers()->active_workers(),
  4400                                        Threads::number_of_non_daemon_threads());
  4401   conc_workers()->set_active_workers(num_workers);
  4403   CompactibleFreeListSpace* cms_space  = _cmsGen->cmsSpace();
  4405   CMSConcMarkingTask tsk(this,
  4406                          cms_space,
  4407                          asynch,
  4408                          conc_workers(),
  4409                          task_queues());
  4411   // Since the actual number of workers we get may be different
  4412   // from the number we requested above, do we need to do anything different
  4413   // below? In particular, may be we need to subclass the SequantialSubTasksDone
  4414   // class?? XXX
  4415   cms_space ->initialize_sequential_subtasks_for_marking(num_workers);
  4417   // Refs discovery is already non-atomic.
  4418   assert(!ref_processor()->discovery_is_atomic(), "Should be non-atomic");
  4419   assert(ref_processor()->discovery_is_mt(), "Discovery should be MT");
  4420   conc_workers()->start_task(&tsk);
  4421   while (tsk.yielded()) {
  4422     tsk.coordinator_yield();
  4423     conc_workers()->continue_task(&tsk);
  4425   // If the task was aborted, _restart_addr will be non-NULL
  4426   assert(tsk.completed() || _restart_addr != NULL, "Inconsistency");
  4427   while (_restart_addr != NULL) {
  4428     // XXX For now we do not make use of ABORTED state and have not
  4429     // yet implemented the right abort semantics (even in the original
  4430     // single-threaded CMS case). That needs some more investigation
  4431     // and is deferred for now; see CR# TBF. 07252005YSR. XXX
  4432     assert(!CMSAbortSemantics || tsk.aborted(), "Inconsistency");
  4433     // If _restart_addr is non-NULL, a marking stack overflow
  4434     // occurred; we need to do a fresh marking iteration from the
  4435     // indicated restart address.
  4436     if (_foregroundGCIsActive && asynch) {
  4437       // We may be running into repeated stack overflows, having
  4438       // reached the limit of the stack size, while making very
  4439       // slow forward progress. It may be best to bail out and
  4440       // let the foreground collector do its job.
  4441       // Clear _restart_addr, so that foreground GC
  4442       // works from scratch. This avoids the headache of
  4443       // a "rescan" which would otherwise be needed because
  4444       // of the dirty mod union table & card table.
  4445       _restart_addr = NULL;
  4446       return false;
  4448     // Adjust the task to restart from _restart_addr
  4449     tsk.reset(_restart_addr);
  4450     cms_space ->initialize_sequential_subtasks_for_marking(num_workers,
  4451                   _restart_addr);
  4452     _restart_addr = NULL;
  4453     // Get the workers going again
  4454     conc_workers()->start_task(&tsk);
  4455     while (tsk.yielded()) {
  4456       tsk.coordinator_yield();
  4457       conc_workers()->continue_task(&tsk);
  4460   assert(tsk.completed(), "Inconsistency");
  4461   assert(tsk.result() == true, "Inconsistency");
  4462   return true;
  4465 bool CMSCollector::do_marking_st(bool asynch) {
  4466   ResourceMark rm;
  4467   HandleMark   hm;
  4469   // Temporarily make refs discovery single threaded (non-MT)
  4470   ReferenceProcessorMTDiscoveryMutator rp_mut_discovery(ref_processor(), false);
  4471   MarkFromRootsClosure markFromRootsClosure(this, _span, &_markBitMap,
  4472     &_markStack, CMSYield && asynch);
  4473   // the last argument to iterate indicates whether the iteration
  4474   // should be incremental with periodic yields.
  4475   _markBitMap.iterate(&markFromRootsClosure);
  4476   // If _restart_addr is non-NULL, a marking stack overflow
  4477   // occurred; we need to do a fresh iteration from the
  4478   // indicated restart address.
  4479   while (_restart_addr != NULL) {
  4480     if (_foregroundGCIsActive && asynch) {
  4481       // We may be running into repeated stack overflows, having
  4482       // reached the limit of the stack size, while making very
  4483       // slow forward progress. It may be best to bail out and
  4484       // let the foreground collector do its job.
  4485       // Clear _restart_addr, so that foreground GC
  4486       // works from scratch. This avoids the headache of
  4487       // a "rescan" which would otherwise be needed because
  4488       // of the dirty mod union table & card table.
  4489       _restart_addr = NULL;
  4490       return false;  // indicating failure to complete marking
  4492     // Deal with stack overflow:
  4493     // we restart marking from _restart_addr
  4494     HeapWord* ra = _restart_addr;
  4495     markFromRootsClosure.reset(ra);
  4496     _restart_addr = NULL;
  4497     _markBitMap.iterate(&markFromRootsClosure, ra, _span.end());
  4499   return true;
  4502 void CMSCollector::preclean() {
  4503   check_correct_thread_executing();
  4504   assert(Thread::current()->is_ConcurrentGC_thread(), "Wrong thread");
  4505   verify_work_stacks_empty();
  4506   verify_overflow_empty();
  4507   _abort_preclean = false;
  4508   if (CMSPrecleaningEnabled) {
  4509     if (!CMSEdenChunksRecordAlways) {
  4510       _eden_chunk_index = 0;
  4512     size_t used = get_eden_used();
  4513     size_t capacity = get_eden_capacity();
  4514     // Don't start sampling unless we will get sufficiently
  4515     // many samples.
  4516     if (used < (capacity/(CMSScheduleRemarkSamplingRatio * 100)
  4517                 * CMSScheduleRemarkEdenPenetration)) {
  4518       _start_sampling = true;
  4519     } else {
  4520       _start_sampling = false;
  4522     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  4523     CMSPhaseAccounting pa(this, "preclean", !PrintGCDetails);
  4524     preclean_work(CMSPrecleanRefLists1, CMSPrecleanSurvivors1);
  4526   CMSTokenSync x(true); // is cms thread
  4527   if (CMSPrecleaningEnabled) {
  4528     sample_eden();
  4529     _collectorState = AbortablePreclean;
  4530   } else {
  4531     _collectorState = FinalMarking;
  4533   verify_work_stacks_empty();
  4534   verify_overflow_empty();
  4537 // Try and schedule the remark such that young gen
  4538 // occupancy is CMSScheduleRemarkEdenPenetration %.
  4539 void CMSCollector::abortable_preclean() {
  4540   check_correct_thread_executing();
  4541   assert(CMSPrecleaningEnabled,  "Inconsistent control state");
  4542   assert(_collectorState == AbortablePreclean, "Inconsistent control state");
  4544   // If Eden's current occupancy is below this threshold,
  4545   // immediately schedule the remark; else preclean
  4546   // past the next scavenge in an effort to
  4547   // schedule the pause as described avove. By choosing
  4548   // CMSScheduleRemarkEdenSizeThreshold >= max eden size
  4549   // we will never do an actual abortable preclean cycle.
  4550   if (get_eden_used() > CMSScheduleRemarkEdenSizeThreshold) {
  4551     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  4552     CMSPhaseAccounting pa(this, "abortable-preclean", !PrintGCDetails);
  4553     // We need more smarts in the abortable preclean
  4554     // loop below to deal with cases where allocation
  4555     // in young gen is very very slow, and our precleaning
  4556     // is running a losing race against a horde of
  4557     // mutators intent on flooding us with CMS updates
  4558     // (dirty cards).
  4559     // One, admittedly dumb, strategy is to give up
  4560     // after a certain number of abortable precleaning loops
  4561     // or after a certain maximum time. We want to make
  4562     // this smarter in the next iteration.
  4563     // XXX FIX ME!!! YSR
  4564     size_t loops = 0, workdone = 0, cumworkdone = 0, waited = 0;
  4565     while (!(should_abort_preclean() ||
  4566              ConcurrentMarkSweepThread::should_terminate())) {
  4567       workdone = preclean_work(CMSPrecleanRefLists2, CMSPrecleanSurvivors2);
  4568       cumworkdone += workdone;
  4569       loops++;
  4570       // Voluntarily terminate abortable preclean phase if we have
  4571       // been at it for too long.
  4572       if ((CMSMaxAbortablePrecleanLoops != 0) &&
  4573           loops >= CMSMaxAbortablePrecleanLoops) {
  4574         if (PrintGCDetails) {
  4575           gclog_or_tty->print(" CMS: abort preclean due to loops ");
  4577         break;
  4579       if (pa.wallclock_millis() > CMSMaxAbortablePrecleanTime) {
  4580         if (PrintGCDetails) {
  4581           gclog_or_tty->print(" CMS: abort preclean due to time ");
  4583         break;
  4585       // If we are doing little work each iteration, we should
  4586       // take a short break.
  4587       if (workdone < CMSAbortablePrecleanMinWorkPerIteration) {
  4588         // Sleep for some time, waiting for work to accumulate
  4589         stopTimer();
  4590         cmsThread()->wait_on_cms_lock(CMSAbortablePrecleanWaitMillis);
  4591         startTimer();
  4592         waited++;
  4595     if (PrintCMSStatistics > 0) {
  4596       gclog_or_tty->print(" [%d iterations, %d waits, %d cards)] ",
  4597                           loops, waited, cumworkdone);
  4600   CMSTokenSync x(true); // is cms thread
  4601   if (_collectorState != Idling) {
  4602     assert(_collectorState == AbortablePreclean,
  4603            "Spontaneous state transition?");
  4604     _collectorState = FinalMarking;
  4605   } // Else, a foreground collection completed this CMS cycle.
  4606   return;
  4609 // Respond to an Eden sampling opportunity
  4610 void CMSCollector::sample_eden() {
  4611   // Make sure a young gc cannot sneak in between our
  4612   // reading and recording of a sample.
  4613   assert(Thread::current()->is_ConcurrentGC_thread(),
  4614          "Only the cms thread may collect Eden samples");
  4615   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  4616          "Should collect samples while holding CMS token");
  4617   if (!_start_sampling) {
  4618     return;
  4620   // When CMSEdenChunksRecordAlways is true, the eden chunk array
  4621   // is populated by the young generation.
  4622   if (_eden_chunk_array != NULL && !CMSEdenChunksRecordAlways) {
  4623     if (_eden_chunk_index < _eden_chunk_capacity) {
  4624       _eden_chunk_array[_eden_chunk_index] = *_top_addr;   // take sample
  4625       assert(_eden_chunk_array[_eden_chunk_index] <= *_end_addr,
  4626              "Unexpected state of Eden");
  4627       // We'd like to check that what we just sampled is an oop-start address;
  4628       // however, we cannot do that here since the object may not yet have been
  4629       // initialized. So we'll instead do the check when we _use_ this sample
  4630       // later.
  4631       if (_eden_chunk_index == 0 ||
  4632           (pointer_delta(_eden_chunk_array[_eden_chunk_index],
  4633                          _eden_chunk_array[_eden_chunk_index-1])
  4634            >= CMSSamplingGrain)) {
  4635         _eden_chunk_index++;  // commit sample
  4639   if ((_collectorState == AbortablePreclean) && !_abort_preclean) {
  4640     size_t used = get_eden_used();
  4641     size_t capacity = get_eden_capacity();
  4642     assert(used <= capacity, "Unexpected state of Eden");
  4643     if (used >  (capacity/100 * CMSScheduleRemarkEdenPenetration)) {
  4644       _abort_preclean = true;
  4650 size_t CMSCollector::preclean_work(bool clean_refs, bool clean_survivor) {
  4651   assert(_collectorState == Precleaning ||
  4652          _collectorState == AbortablePreclean, "incorrect state");
  4653   ResourceMark rm;
  4654   HandleMark   hm;
  4656   // Precleaning is currently not MT but the reference processor
  4657   // may be set for MT.  Disable it temporarily here.
  4658   ReferenceProcessor* rp = ref_processor();
  4659   ReferenceProcessorMTDiscoveryMutator rp_mut_discovery(rp, false);
  4661   // Do one pass of scrubbing the discovered reference lists
  4662   // to remove any reference objects with strongly-reachable
  4663   // referents.
  4664   if (clean_refs) {
  4665     CMSPrecleanRefsYieldClosure yield_cl(this);
  4666     assert(rp->span().equals(_span), "Spans should be equal");
  4667     CMSKeepAliveClosure keep_alive(this, _span, &_markBitMap,
  4668                                    &_markStack, true /* preclean */);
  4669     CMSDrainMarkingStackClosure complete_trace(this,
  4670                                    _span, &_markBitMap, &_markStack,
  4671                                    &keep_alive, true /* preclean */);
  4673     // We don't want this step to interfere with a young
  4674     // collection because we don't want to take CPU
  4675     // or memory bandwidth away from the young GC threads
  4676     // (which may be as many as there are CPUs).
  4677     // Note that we don't need to protect ourselves from
  4678     // interference with mutators because they can't
  4679     // manipulate the discovered reference lists nor affect
  4680     // the computed reachability of the referents, the
  4681     // only properties manipulated by the precleaning
  4682     // of these reference lists.
  4683     stopTimer();
  4684     CMSTokenSyncWithLocks x(true /* is cms thread */,
  4685                             bitMapLock());
  4686     startTimer();
  4687     sample_eden();
  4689     // The following will yield to allow foreground
  4690     // collection to proceed promptly. XXX YSR:
  4691     // The code in this method may need further
  4692     // tweaking for better performance and some restructuring
  4693     // for cleaner interfaces.
  4694     GCTimer *gc_timer = NULL; // Currently not tracing concurrent phases
  4695     rp->preclean_discovered_references(
  4696           rp->is_alive_non_header(), &keep_alive, &complete_trace, &yield_cl,
  4697           gc_timer);
  4700   if (clean_survivor) {  // preclean the active survivor space(s)
  4701     assert(_young_gen->kind() == Generation::DefNew ||
  4702            _young_gen->kind() == Generation::ParNew ||
  4703            _young_gen->kind() == Generation::ASParNew,
  4704          "incorrect type for cast");
  4705     DefNewGeneration* dng = (DefNewGeneration*)_young_gen;
  4706     PushAndMarkClosure pam_cl(this, _span, ref_processor(),
  4707                              &_markBitMap, &_modUnionTable,
  4708                              &_markStack, true /* precleaning phase */);
  4709     stopTimer();
  4710     CMSTokenSyncWithLocks ts(true /* is cms thread */,
  4711                              bitMapLock());
  4712     startTimer();
  4713     unsigned int before_count =
  4714       GenCollectedHeap::heap()->total_collections();
  4715     SurvivorSpacePrecleanClosure
  4716       sss_cl(this, _span, &_markBitMap, &_markStack,
  4717              &pam_cl, before_count, CMSYield);
  4718     dng->from()->object_iterate_careful(&sss_cl);
  4719     dng->to()->object_iterate_careful(&sss_cl);
  4721   MarkRefsIntoAndScanClosure
  4722     mrias_cl(_span, ref_processor(), &_markBitMap, &_modUnionTable,
  4723              &_markStack, this, CMSYield,
  4724              true /* precleaning phase */);
  4725   // CAUTION: The following closure has persistent state that may need to
  4726   // be reset upon a decrease in the sequence of addresses it
  4727   // processes.
  4728   ScanMarkedObjectsAgainCarefullyClosure
  4729     smoac_cl(this, _span,
  4730       &_markBitMap, &_markStack, &mrias_cl, CMSYield);
  4732   // Preclean dirty cards in ModUnionTable and CardTable using
  4733   // appropriate convergence criterion;
  4734   // repeat CMSPrecleanIter times unless we find that
  4735   // we are losing.
  4736   assert(CMSPrecleanIter < 10, "CMSPrecleanIter is too large");
  4737   assert(CMSPrecleanNumerator < CMSPrecleanDenominator,
  4738          "Bad convergence multiplier");
  4739   assert(CMSPrecleanThreshold >= 100,
  4740          "Unreasonably low CMSPrecleanThreshold");
  4742   size_t numIter, cumNumCards, lastNumCards, curNumCards;
  4743   for (numIter = 0, cumNumCards = lastNumCards = curNumCards = 0;
  4744        numIter < CMSPrecleanIter;
  4745        numIter++, lastNumCards = curNumCards, cumNumCards += curNumCards) {
  4746     curNumCards  = preclean_mod_union_table(_cmsGen, &smoac_cl);
  4747     if (Verbose && PrintGCDetails) {
  4748       gclog_or_tty->print(" (modUnionTable: %d cards)", curNumCards);
  4750     // Either there are very few dirty cards, so re-mark
  4751     // pause will be small anyway, or our pre-cleaning isn't
  4752     // that much faster than the rate at which cards are being
  4753     // dirtied, so we might as well stop and re-mark since
  4754     // precleaning won't improve our re-mark time by much.
  4755     if (curNumCards <= CMSPrecleanThreshold ||
  4756         (numIter > 0 &&
  4757          (curNumCards * CMSPrecleanDenominator >
  4758          lastNumCards * CMSPrecleanNumerator))) {
  4759       numIter++;
  4760       cumNumCards += curNumCards;
  4761       break;
  4765   preclean_klasses(&mrias_cl, _cmsGen->freelistLock());
  4767   curNumCards = preclean_card_table(_cmsGen, &smoac_cl);
  4768   cumNumCards += curNumCards;
  4769   if (PrintGCDetails && PrintCMSStatistics != 0) {
  4770     gclog_or_tty->print_cr(" (cardTable: %d cards, re-scanned %d cards, %d iterations)",
  4771                   curNumCards, cumNumCards, numIter);
  4773   return cumNumCards;   // as a measure of useful work done
  4776 // PRECLEANING NOTES:
  4777 // Precleaning involves:
  4778 // . reading the bits of the modUnionTable and clearing the set bits.
  4779 // . For the cards corresponding to the set bits, we scan the
  4780 //   objects on those cards. This means we need the free_list_lock
  4781 //   so that we can safely iterate over the CMS space when scanning
  4782 //   for oops.
  4783 // . When we scan the objects, we'll be both reading and setting
  4784 //   marks in the marking bit map, so we'll need the marking bit map.
  4785 // . For protecting _collector_state transitions, we take the CGC_lock.
  4786 //   Note that any races in the reading of of card table entries by the
  4787 //   CMS thread on the one hand and the clearing of those entries by the
  4788 //   VM thread or the setting of those entries by the mutator threads on the
  4789 //   other are quite benign. However, for efficiency it makes sense to keep
  4790 //   the VM thread from racing with the CMS thread while the latter is
  4791 //   dirty card info to the modUnionTable. We therefore also use the
  4792 //   CGC_lock to protect the reading of the card table and the mod union
  4793 //   table by the CM thread.
  4794 // . We run concurrently with mutator updates, so scanning
  4795 //   needs to be done carefully  -- we should not try to scan
  4796 //   potentially uninitialized objects.
  4797 //
  4798 // Locking strategy: While holding the CGC_lock, we scan over and
  4799 // reset a maximal dirty range of the mod union / card tables, then lock
  4800 // the free_list_lock and bitmap lock to do a full marking, then
  4801 // release these locks; and repeat the cycle. This allows for a
  4802 // certain amount of fairness in the sharing of these locks between
  4803 // the CMS collector on the one hand, and the VM thread and the
  4804 // mutators on the other.
  4806 // NOTE: preclean_mod_union_table() and preclean_card_table()
  4807 // further below are largely identical; if you need to modify
  4808 // one of these methods, please check the other method too.
  4810 size_t CMSCollector::preclean_mod_union_table(
  4811   ConcurrentMarkSweepGeneration* gen,
  4812   ScanMarkedObjectsAgainCarefullyClosure* cl) {
  4813   verify_work_stacks_empty();
  4814   verify_overflow_empty();
  4816   // strategy: starting with the first card, accumulate contiguous
  4817   // ranges of dirty cards; clear these cards, then scan the region
  4818   // covered by these cards.
  4820   // Since all of the MUT is committed ahead, we can just use
  4821   // that, in case the generations expand while we are precleaning.
  4822   // It might also be fine to just use the committed part of the
  4823   // generation, but we might potentially miss cards when the
  4824   // generation is rapidly expanding while we are in the midst
  4825   // of precleaning.
  4826   HeapWord* startAddr = gen->reserved().start();
  4827   HeapWord* endAddr   = gen->reserved().end();
  4829   cl->setFreelistLock(gen->freelistLock());   // needed for yielding
  4831   size_t numDirtyCards, cumNumDirtyCards;
  4832   HeapWord *nextAddr, *lastAddr;
  4833   for (cumNumDirtyCards = numDirtyCards = 0,
  4834        nextAddr = lastAddr = startAddr;
  4835        nextAddr < endAddr;
  4836        nextAddr = lastAddr, cumNumDirtyCards += numDirtyCards) {
  4838     ResourceMark rm;
  4839     HandleMark   hm;
  4841     MemRegion dirtyRegion;
  4843       stopTimer();
  4844       // Potential yield point
  4845       CMSTokenSync ts(true);
  4846       startTimer();
  4847       sample_eden();
  4848       // Get dirty region starting at nextOffset (inclusive),
  4849       // simultaneously clearing it.
  4850       dirtyRegion =
  4851         _modUnionTable.getAndClearMarkedRegion(nextAddr, endAddr);
  4852       assert(dirtyRegion.start() >= nextAddr,
  4853              "returned region inconsistent?");
  4855     // Remember where the next search should begin.
  4856     // The returned region (if non-empty) is a right open interval,
  4857     // so lastOffset is obtained from the right end of that
  4858     // interval.
  4859     lastAddr = dirtyRegion.end();
  4860     // Should do something more transparent and less hacky XXX
  4861     numDirtyCards =
  4862       _modUnionTable.heapWordDiffToOffsetDiff(dirtyRegion.word_size());
  4864     // We'll scan the cards in the dirty region (with periodic
  4865     // yields for foreground GC as needed).
  4866     if (!dirtyRegion.is_empty()) {
  4867       assert(numDirtyCards > 0, "consistency check");
  4868       HeapWord* stop_point = NULL;
  4869       stopTimer();
  4870       // Potential yield point
  4871       CMSTokenSyncWithLocks ts(true, gen->freelistLock(),
  4872                                bitMapLock());
  4873       startTimer();
  4875         verify_work_stacks_empty();
  4876         verify_overflow_empty();
  4877         sample_eden();
  4878         stop_point =
  4879           gen->cmsSpace()->object_iterate_careful_m(dirtyRegion, cl);
  4881       if (stop_point != NULL) {
  4882         // The careful iteration stopped early either because it found an
  4883         // uninitialized object, or because we were in the midst of an
  4884         // "abortable preclean", which should now be aborted. Redirty
  4885         // the bits corresponding to the partially-scanned or unscanned
  4886         // cards. We'll either restart at the next block boundary or
  4887         // abort the preclean.
  4888         assert((_collectorState == AbortablePreclean && should_abort_preclean()),
  4889                "Should only be AbortablePreclean.");
  4890         _modUnionTable.mark_range(MemRegion(stop_point, dirtyRegion.end()));
  4891         if (should_abort_preclean()) {
  4892           break; // out of preclean loop
  4893         } else {
  4894           // Compute the next address at which preclean should pick up;
  4895           // might need bitMapLock in order to read P-bits.
  4896           lastAddr = next_card_start_after_block(stop_point);
  4899     } else {
  4900       assert(lastAddr == endAddr, "consistency check");
  4901       assert(numDirtyCards == 0, "consistency check");
  4902       break;
  4905   verify_work_stacks_empty();
  4906   verify_overflow_empty();
  4907   return cumNumDirtyCards;
  4910 // NOTE: preclean_mod_union_table() above and preclean_card_table()
  4911 // below are largely identical; if you need to modify
  4912 // one of these methods, please check the other method too.
  4914 size_t CMSCollector::preclean_card_table(ConcurrentMarkSweepGeneration* gen,
  4915   ScanMarkedObjectsAgainCarefullyClosure* cl) {
  4916   // strategy: it's similar to precleamModUnionTable above, in that
  4917   // we accumulate contiguous ranges of dirty cards, mark these cards
  4918   // precleaned, then scan the region covered by these cards.
  4919   HeapWord* endAddr   = (HeapWord*)(gen->_virtual_space.high());
  4920   HeapWord* startAddr = (HeapWord*)(gen->_virtual_space.low());
  4922   cl->setFreelistLock(gen->freelistLock());   // needed for yielding
  4924   size_t numDirtyCards, cumNumDirtyCards;
  4925   HeapWord *lastAddr, *nextAddr;
  4927   for (cumNumDirtyCards = numDirtyCards = 0,
  4928        nextAddr = lastAddr = startAddr;
  4929        nextAddr < endAddr;
  4930        nextAddr = lastAddr, cumNumDirtyCards += numDirtyCards) {
  4932     ResourceMark rm;
  4933     HandleMark   hm;
  4935     MemRegion dirtyRegion;
  4937       // See comments in "Precleaning notes" above on why we
  4938       // do this locking. XXX Could the locking overheads be
  4939       // too high when dirty cards are sparse? [I don't think so.]
  4940       stopTimer();
  4941       CMSTokenSync x(true); // is cms thread
  4942       startTimer();
  4943       sample_eden();
  4944       // Get and clear dirty region from card table
  4945       dirtyRegion = _ct->ct_bs()->dirty_card_range_after_reset(
  4946                                     MemRegion(nextAddr, endAddr),
  4947                                     true,
  4948                                     CardTableModRefBS::precleaned_card_val());
  4950       assert(dirtyRegion.start() >= nextAddr,
  4951              "returned region inconsistent?");
  4953     lastAddr = dirtyRegion.end();
  4954     numDirtyCards =
  4955       dirtyRegion.word_size()/CardTableModRefBS::card_size_in_words;
  4957     if (!dirtyRegion.is_empty()) {
  4958       stopTimer();
  4959       CMSTokenSyncWithLocks ts(true, gen->freelistLock(), bitMapLock());
  4960       startTimer();
  4961       sample_eden();
  4962       verify_work_stacks_empty();
  4963       verify_overflow_empty();
  4964       HeapWord* stop_point =
  4965         gen->cmsSpace()->object_iterate_careful_m(dirtyRegion, cl);
  4966       if (stop_point != NULL) {
  4967         assert((_collectorState == AbortablePreclean && should_abort_preclean()),
  4968                "Should only be AbortablePreclean.");
  4969         _ct->ct_bs()->invalidate(MemRegion(stop_point, dirtyRegion.end()));
  4970         if (should_abort_preclean()) {
  4971           break; // out of preclean loop
  4972         } else {
  4973           // Compute the next address at which preclean should pick up.
  4974           lastAddr = next_card_start_after_block(stop_point);
  4977     } else {
  4978       break;
  4981   verify_work_stacks_empty();
  4982   verify_overflow_empty();
  4983   return cumNumDirtyCards;
  4986 class PrecleanKlassClosure : public KlassClosure {
  4987   CMKlassClosure _cm_klass_closure;
  4988  public:
  4989   PrecleanKlassClosure(OopClosure* oop_closure) : _cm_klass_closure(oop_closure) {}
  4990   void do_klass(Klass* k) {
  4991     if (k->has_accumulated_modified_oops()) {
  4992       k->clear_accumulated_modified_oops();
  4994       _cm_klass_closure.do_klass(k);
  4997 };
  4999 // The freelist lock is needed to prevent asserts, is it really needed?
  5000 void CMSCollector::preclean_klasses(MarkRefsIntoAndScanClosure* cl, Mutex* freelistLock) {
  5002   cl->set_freelistLock(freelistLock);
  5004   CMSTokenSyncWithLocks ts(true, freelistLock, bitMapLock());
  5006   // SSS: Add equivalent to ScanMarkedObjectsAgainCarefullyClosure::do_yield_check and should_abort_preclean?
  5007   // SSS: We should probably check if precleaning should be aborted, at suitable intervals?
  5008   PrecleanKlassClosure preclean_klass_closure(cl);
  5009   ClassLoaderDataGraph::classes_do(&preclean_klass_closure);
  5011   verify_work_stacks_empty();
  5012   verify_overflow_empty();
  5015 void CMSCollector::checkpointRootsFinal(bool asynch,
  5016   bool clear_all_soft_refs, bool init_mark_was_synchronous) {
  5017   assert(_collectorState == FinalMarking, "incorrect state transition?");
  5018   check_correct_thread_executing();
  5019   // world is stopped at this checkpoint
  5020   assert(SafepointSynchronize::is_at_safepoint(),
  5021          "world should be stopped");
  5022   TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause());
  5024   verify_work_stacks_empty();
  5025   verify_overflow_empty();
  5027   SpecializationStats::clear();
  5028   if (PrintGCDetails) {
  5029     gclog_or_tty->print("[YG occupancy: "SIZE_FORMAT" K ("SIZE_FORMAT" K)]",
  5030                         _young_gen->used() / K,
  5031                         _young_gen->capacity() / K);
  5033   if (asynch) {
  5034     if (CMSScavengeBeforeRemark) {
  5035       GenCollectedHeap* gch = GenCollectedHeap::heap();
  5036       // Temporarily set flag to false, GCH->do_collection will
  5037       // expect it to be false and set to true
  5038       FlagSetting fl(gch->_is_gc_active, false);
  5039       NOT_PRODUCT(GCTraceTime t("Scavenge-Before-Remark",
  5040         PrintGCDetails && Verbose, true, _gc_timer_cm);)
  5041       int level = _cmsGen->level() - 1;
  5042       if (level >= 0) {
  5043         gch->do_collection(true,        // full (i.e. force, see below)
  5044                            false,       // !clear_all_soft_refs
  5045                            0,           // size
  5046                            false,       // is_tlab
  5047                            level        // max_level
  5048                           );
  5051     FreelistLocker x(this);
  5052     MutexLockerEx y(bitMapLock(),
  5053                     Mutex::_no_safepoint_check_flag);
  5054     assert(!init_mark_was_synchronous, "but that's impossible!");
  5055     checkpointRootsFinalWork(asynch, clear_all_soft_refs, false);
  5056   } else {
  5057     // already have all the locks
  5058     checkpointRootsFinalWork(asynch, clear_all_soft_refs,
  5059                              init_mark_was_synchronous);
  5061   verify_work_stacks_empty();
  5062   verify_overflow_empty();
  5063   SpecializationStats::print();
  5066 void CMSCollector::checkpointRootsFinalWork(bool asynch,
  5067   bool clear_all_soft_refs, bool init_mark_was_synchronous) {
  5069   NOT_PRODUCT(GCTraceTime tr("checkpointRootsFinalWork", PrintGCDetails, false, _gc_timer_cm);)
  5071   assert(haveFreelistLocks(), "must have free list locks");
  5072   assert_lock_strong(bitMapLock());
  5074   if (UseAdaptiveSizePolicy) {
  5075     size_policy()->checkpoint_roots_final_begin();
  5078   ResourceMark rm;
  5079   HandleMark   hm;
  5081   GenCollectedHeap* gch = GenCollectedHeap::heap();
  5083   if (should_unload_classes()) {
  5084     CodeCache::gc_prologue();
  5086   assert(haveFreelistLocks(), "must have free list locks");
  5087   assert_lock_strong(bitMapLock());
  5089   if (!init_mark_was_synchronous) {
  5090     // We might assume that we need not fill TLAB's when
  5091     // CMSScavengeBeforeRemark is set, because we may have just done
  5092     // a scavenge which would have filled all TLAB's -- and besides
  5093     // Eden would be empty. This however may not always be the case --
  5094     // for instance although we asked for a scavenge, it may not have
  5095     // happened because of a JNI critical section. We probably need
  5096     // a policy for deciding whether we can in that case wait until
  5097     // the critical section releases and then do the remark following
  5098     // the scavenge, and skip it here. In the absence of that policy,
  5099     // or of an indication of whether the scavenge did indeed occur,
  5100     // we cannot rely on TLAB's having been filled and must do
  5101     // so here just in case a scavenge did not happen.
  5102     gch->ensure_parsability(false);  // fill TLAB's, but no need to retire them
  5103     // Update the saved marks which may affect the root scans.
  5104     gch->save_marks();
  5106     if (CMSPrintEdenSurvivorChunks) {
  5107       print_eden_and_survivor_chunk_arrays();
  5111       COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;)
  5113       // Note on the role of the mod union table:
  5114       // Since the marker in "markFromRoots" marks concurrently with
  5115       // mutators, it is possible for some reachable objects not to have been
  5116       // scanned. For instance, an only reference to an object A was
  5117       // placed in object B after the marker scanned B. Unless B is rescanned,
  5118       // A would be collected. Such updates to references in marked objects
  5119       // are detected via the mod union table which is the set of all cards
  5120       // dirtied since the first checkpoint in this GC cycle and prior to
  5121       // the most recent young generation GC, minus those cleaned up by the
  5122       // concurrent precleaning.
  5123       if (CMSParallelRemarkEnabled && CollectedHeap::use_parallel_gc_threads()) {
  5124         GCTraceTime t("Rescan (parallel) ", PrintGCDetails, false, _gc_timer_cm);
  5125         do_remark_parallel();
  5126       } else {
  5127         GCTraceTime t("Rescan (non-parallel) ", PrintGCDetails, false,
  5128                     _gc_timer_cm);
  5129         do_remark_non_parallel();
  5132   } else {
  5133     assert(!asynch, "Can't have init_mark_was_synchronous in asynch mode");
  5134     // The initial mark was stop-world, so there's no rescanning to
  5135     // do; go straight on to the next step below.
  5137   verify_work_stacks_empty();
  5138   verify_overflow_empty();
  5141     NOT_PRODUCT(GCTraceTime ts("refProcessingWork", PrintGCDetails, false, _gc_timer_cm);)
  5142     refProcessingWork(asynch, clear_all_soft_refs);
  5144   verify_work_stacks_empty();
  5145   verify_overflow_empty();
  5147   if (should_unload_classes()) {
  5148     CodeCache::gc_epilogue();
  5150   JvmtiExport::gc_epilogue();
  5152   // If we encountered any (marking stack / work queue) overflow
  5153   // events during the current CMS cycle, take appropriate
  5154   // remedial measures, where possible, so as to try and avoid
  5155   // recurrence of that condition.
  5156   assert(_markStack.isEmpty(), "No grey objects");
  5157   size_t ser_ovflw = _ser_pmc_remark_ovflw + _ser_pmc_preclean_ovflw +
  5158                      _ser_kac_ovflw        + _ser_kac_preclean_ovflw;
  5159   if (ser_ovflw > 0) {
  5160     if (PrintCMSStatistics != 0) {
  5161       gclog_or_tty->print_cr("Marking stack overflow (benign) "
  5162         "(pmc_pc="SIZE_FORMAT", pmc_rm="SIZE_FORMAT", kac="SIZE_FORMAT
  5163         ", kac_preclean="SIZE_FORMAT")",
  5164         _ser_pmc_preclean_ovflw, _ser_pmc_remark_ovflw,
  5165         _ser_kac_ovflw, _ser_kac_preclean_ovflw);
  5167     _markStack.expand();
  5168     _ser_pmc_remark_ovflw = 0;
  5169     _ser_pmc_preclean_ovflw = 0;
  5170     _ser_kac_preclean_ovflw = 0;
  5171     _ser_kac_ovflw = 0;
  5173   if (_par_pmc_remark_ovflw > 0 || _par_kac_ovflw > 0) {
  5174     if (PrintCMSStatistics != 0) {
  5175       gclog_or_tty->print_cr("Work queue overflow (benign) "
  5176         "(pmc_rm="SIZE_FORMAT", kac="SIZE_FORMAT")",
  5177         _par_pmc_remark_ovflw, _par_kac_ovflw);
  5179     _par_pmc_remark_ovflw = 0;
  5180     _par_kac_ovflw = 0;
  5182   if (PrintCMSStatistics != 0) {
  5183      if (_markStack._hit_limit > 0) {
  5184        gclog_or_tty->print_cr(" (benign) Hit max stack size limit ("SIZE_FORMAT")",
  5185                               _markStack._hit_limit);
  5187      if (_markStack._failed_double > 0) {
  5188        gclog_or_tty->print_cr(" (benign) Failed stack doubling ("SIZE_FORMAT"),"
  5189                               " current capacity "SIZE_FORMAT,
  5190                               _markStack._failed_double,
  5191                               _markStack.capacity());
  5194   _markStack._hit_limit = 0;
  5195   _markStack._failed_double = 0;
  5197   if ((VerifyAfterGC || VerifyDuringGC) &&
  5198       GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  5199     verify_after_remark();
  5202   _gc_tracer_cm->report_object_count_after_gc(&_is_alive_closure);
  5204   // Change under the freelistLocks.
  5205   _collectorState = Sweeping;
  5206   // Call isAllClear() under bitMapLock
  5207   assert(_modUnionTable.isAllClear(),
  5208       "Should be clear by end of the final marking");
  5209   assert(_ct->klass_rem_set()->mod_union_is_clear(),
  5210       "Should be clear by end of the final marking");
  5211   if (UseAdaptiveSizePolicy) {
  5212     size_policy()->checkpoint_roots_final_end(gch->gc_cause());
  5216 void CMSParInitialMarkTask::work(uint worker_id) {
  5217   elapsedTimer _timer;
  5218   ResourceMark rm;
  5219   HandleMark   hm;
  5221   // ---------- scan from roots --------------
  5222   _timer.start();
  5223   GenCollectedHeap* gch = GenCollectedHeap::heap();
  5224   Par_MarkRefsIntoClosure par_mri_cl(_collector->_span, &(_collector->_markBitMap));
  5225   CMKlassClosure klass_closure(&par_mri_cl);
  5227   // ---------- young gen roots --------------
  5229     work_on_young_gen_roots(worker_id, &par_mri_cl);
  5230     _timer.stop();
  5231     if (PrintCMSStatistics != 0) {
  5232       gclog_or_tty->print_cr(
  5233         "Finished young gen initial mark scan work in %dth thread: %3.3f sec",
  5234         worker_id, _timer.seconds());
  5238   // ---------- remaining roots --------------
  5239   _timer.reset();
  5240   _timer.start();
  5241   gch->gen_process_strong_roots(_collector->_cmsGen->level(),
  5242                                 false,     // yg was scanned above
  5243                                 false,     // this is parallel code
  5244                                 false,     // not scavenging
  5245                                 SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()),
  5246                                 &par_mri_cl,
  5247                                 true,   // walk all of code cache if (so & SO_CodeCache)
  5248                                 NULL,
  5249                                 &klass_closure);
  5250   assert(_collector->should_unload_classes()
  5251          || (_collector->CMSCollector::roots_scanning_options() & SharedHeap::SO_CodeCache),
  5252          "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops");
  5253   _timer.stop();
  5254   if (PrintCMSStatistics != 0) {
  5255     gclog_or_tty->print_cr(
  5256       "Finished remaining root initial mark scan work in %dth thread: %3.3f sec",
  5257       worker_id, _timer.seconds());
  5261 // Parallel remark task
  5262 class CMSParRemarkTask: public CMSParMarkTask {
  5263   CompactibleFreeListSpace* _cms_space;
  5265   // The per-thread work queues, available here for stealing.
  5266   OopTaskQueueSet*       _task_queues;
  5267   ParallelTaskTerminator _term;
  5269  public:
  5270   // A value of 0 passed to n_workers will cause the number of
  5271   // workers to be taken from the active workers in the work gang.
  5272   CMSParRemarkTask(CMSCollector* collector,
  5273                    CompactibleFreeListSpace* cms_space,
  5274                    int n_workers, FlexibleWorkGang* workers,
  5275                    OopTaskQueueSet* task_queues):
  5276     CMSParMarkTask("Rescan roots and grey objects in parallel",
  5277                    collector, n_workers),
  5278     _cms_space(cms_space),
  5279     _task_queues(task_queues),
  5280     _term(n_workers, task_queues) { }
  5282   OopTaskQueueSet* task_queues() { return _task_queues; }
  5284   OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); }
  5286   ParallelTaskTerminator* terminator() { return &_term; }
  5287   int n_workers() { return _n_workers; }
  5289   void work(uint worker_id);
  5291  private:
  5292   // ... of  dirty cards in old space
  5293   void do_dirty_card_rescan_tasks(CompactibleFreeListSpace* sp, int i,
  5294                                   Par_MarkRefsIntoAndScanClosure* cl);
  5296   // ... work stealing for the above
  5297   void do_work_steal(int i, Par_MarkRefsIntoAndScanClosure* cl, int* seed);
  5298 };
  5300 class RemarkKlassClosure : public KlassClosure {
  5301   CMKlassClosure _cm_klass_closure;
  5302  public:
  5303   RemarkKlassClosure(OopClosure* oop_closure) : _cm_klass_closure(oop_closure) {}
  5304   void do_klass(Klass* k) {
  5305     // Check if we have modified any oops in the Klass during the concurrent marking.
  5306     if (k->has_accumulated_modified_oops()) {
  5307       k->clear_accumulated_modified_oops();
  5309       // We could have transfered the current modified marks to the accumulated marks,
  5310       // like we do with the Card Table to Mod Union Table. But it's not really necessary.
  5311     } else if (k->has_modified_oops()) {
  5312       // Don't clear anything, this info is needed by the next young collection.
  5313     } else {
  5314       // No modified oops in the Klass.
  5315       return;
  5318     // The klass has modified fields, need to scan the klass.
  5319     _cm_klass_closure.do_klass(k);
  5321 };
  5323 void CMSParMarkTask::work_on_young_gen_roots(uint worker_id, OopsInGenClosure* cl) {
  5324   DefNewGeneration* dng = _collector->_young_gen->as_DefNewGeneration();
  5325   EdenSpace* eden_space = dng->eden();
  5326   ContiguousSpace* from_space = dng->from();
  5327   ContiguousSpace* to_space   = dng->to();
  5329   HeapWord** eca = _collector->_eden_chunk_array;
  5330   size_t     ect = _collector->_eden_chunk_index;
  5331   HeapWord** sca = _collector->_survivor_chunk_array;
  5332   size_t     sct = _collector->_survivor_chunk_index;
  5334   assert(ect <= _collector->_eden_chunk_capacity, "out of bounds");
  5335   assert(sct <= _collector->_survivor_chunk_capacity, "out of bounds");
  5337   do_young_space_rescan(worker_id, cl, to_space, NULL, 0);
  5338   do_young_space_rescan(worker_id, cl, from_space, sca, sct);
  5339   do_young_space_rescan(worker_id, cl, eden_space, eca, ect);
  5342 // work_queue(i) is passed to the closure
  5343 // Par_MarkRefsIntoAndScanClosure.  The "i" parameter
  5344 // also is passed to do_dirty_card_rescan_tasks() and to
  5345 // do_work_steal() to select the i-th task_queue.
  5347 void CMSParRemarkTask::work(uint worker_id) {
  5348   elapsedTimer _timer;
  5349   ResourceMark rm;
  5350   HandleMark   hm;
  5352   // ---------- rescan from roots --------------
  5353   _timer.start();
  5354   GenCollectedHeap* gch = GenCollectedHeap::heap();
  5355   Par_MarkRefsIntoAndScanClosure par_mrias_cl(_collector,
  5356     _collector->_span, _collector->ref_processor(),
  5357     &(_collector->_markBitMap),
  5358     work_queue(worker_id));
  5360   // Rescan young gen roots first since these are likely
  5361   // coarsely partitioned and may, on that account, constitute
  5362   // the critical path; thus, it's best to start off that
  5363   // work first.
  5364   // ---------- young gen roots --------------
  5366     work_on_young_gen_roots(worker_id, &par_mrias_cl);
  5367     _timer.stop();
  5368     if (PrintCMSStatistics != 0) {
  5369       gclog_or_tty->print_cr(
  5370         "Finished young gen rescan work in %dth thread: %3.3f sec",
  5371         worker_id, _timer.seconds());
  5375   // ---------- remaining roots --------------
  5376   _timer.reset();
  5377   _timer.start();
  5378   gch->gen_process_strong_roots(_collector->_cmsGen->level(),
  5379                                 false,     // yg was scanned above
  5380                                 false,     // this is parallel code
  5381                                 false,     // not scavenging
  5382                                 SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()),
  5383                                 &par_mrias_cl,
  5384                                 true,   // walk all of code cache if (so & SO_CodeCache)
  5385                                 NULL,
  5386                                 NULL);     // The dirty klasses will be handled below
  5387   assert(_collector->should_unload_classes()
  5388          || (_collector->CMSCollector::roots_scanning_options() & SharedHeap::SO_CodeCache),
  5389          "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops");
  5390   _timer.stop();
  5391   if (PrintCMSStatistics != 0) {
  5392     gclog_or_tty->print_cr(
  5393       "Finished remaining root rescan work in %dth thread: %3.3f sec",
  5394       worker_id, _timer.seconds());
  5397   // ---------- unhandled CLD scanning ----------
  5398   if (worker_id == 0) { // Single threaded at the moment.
  5399     _timer.reset();
  5400     _timer.start();
  5402     // Scan all new class loader data objects and new dependencies that were
  5403     // introduced during concurrent marking.
  5404     ResourceMark rm;
  5405     GrowableArray<ClassLoaderData*>* array = ClassLoaderDataGraph::new_clds();
  5406     for (int i = 0; i < array->length(); i++) {
  5407       par_mrias_cl.do_class_loader_data(array->at(i));
  5410     // We don't need to keep track of new CLDs anymore.
  5411     ClassLoaderDataGraph::remember_new_clds(false);
  5413     _timer.stop();
  5414     if (PrintCMSStatistics != 0) {
  5415       gclog_or_tty->print_cr(
  5416           "Finished unhandled CLD scanning work in %dth thread: %3.3f sec",
  5417           worker_id, _timer.seconds());
  5421   // ---------- dirty klass scanning ----------
  5422   if (worker_id == 0) { // Single threaded at the moment.
  5423     _timer.reset();
  5424     _timer.start();
  5426     // Scan all classes that was dirtied during the concurrent marking phase.
  5427     RemarkKlassClosure remark_klass_closure(&par_mrias_cl);
  5428     ClassLoaderDataGraph::classes_do(&remark_klass_closure);
  5430     _timer.stop();
  5431     if (PrintCMSStatistics != 0) {
  5432       gclog_or_tty->print_cr(
  5433           "Finished dirty klass scanning work in %dth thread: %3.3f sec",
  5434           worker_id, _timer.seconds());
  5438   // We might have added oops to ClassLoaderData::_handles during the
  5439   // concurrent marking phase. These oops point to newly allocated objects
  5440   // that are guaranteed to be kept alive. Either by the direct allocation
  5441   // code, or when the young collector processes the strong roots. Hence,
  5442   // we don't have to revisit the _handles block during the remark phase.
  5444   // ---------- rescan dirty cards ------------
  5445   _timer.reset();
  5446   _timer.start();
  5448   // Do the rescan tasks for each of the two spaces
  5449   // (cms_space) in turn.
  5450   // "worker_id" is passed to select the task_queue for "worker_id"
  5451   do_dirty_card_rescan_tasks(_cms_space, worker_id, &par_mrias_cl);
  5452   _timer.stop();
  5453   if (PrintCMSStatistics != 0) {
  5454     gclog_or_tty->print_cr(
  5455       "Finished dirty card rescan work in %dth thread: %3.3f sec",
  5456       worker_id, _timer.seconds());
  5459   // ---------- steal work from other threads ...
  5460   // ---------- ... and drain overflow list.
  5461   _timer.reset();
  5462   _timer.start();
  5463   do_work_steal(worker_id, &par_mrias_cl, _collector->hash_seed(worker_id));
  5464   _timer.stop();
  5465   if (PrintCMSStatistics != 0) {
  5466     gclog_or_tty->print_cr(
  5467       "Finished work stealing in %dth thread: %3.3f sec",
  5468       worker_id, _timer.seconds());
  5472 // Note that parameter "i" is not used.
  5473 void
  5474 CMSParMarkTask::do_young_space_rescan(uint worker_id,
  5475   OopsInGenClosure* cl, ContiguousSpace* space,
  5476   HeapWord** chunk_array, size_t chunk_top) {
  5477   // Until all tasks completed:
  5478   // . claim an unclaimed task
  5479   // . compute region boundaries corresponding to task claimed
  5480   //   using chunk_array
  5481   // . par_oop_iterate(cl) over that region
  5483   ResourceMark rm;
  5484   HandleMark   hm;
  5486   SequentialSubTasksDone* pst = space->par_seq_tasks();
  5488   uint nth_task = 0;
  5489   uint n_tasks  = pst->n_tasks();
  5491   if (n_tasks > 0) {
  5492     assert(pst->valid(), "Uninitialized use?");
  5493     HeapWord *start, *end;
  5494     while (!pst->is_task_claimed(/* reference */ nth_task)) {
  5495       // We claimed task # nth_task; compute its boundaries.
  5496       if (chunk_top == 0) {  // no samples were taken
  5497         assert(nth_task == 0 && n_tasks == 1, "Can have only 1 EdenSpace task");
  5498         start = space->bottom();
  5499         end   = space->top();
  5500       } else if (nth_task == 0) {
  5501         start = space->bottom();
  5502         end   = chunk_array[nth_task];
  5503       } else if (nth_task < (uint)chunk_top) {
  5504         assert(nth_task >= 1, "Control point invariant");
  5505         start = chunk_array[nth_task - 1];
  5506         end   = chunk_array[nth_task];
  5507       } else {
  5508         assert(nth_task == (uint)chunk_top, "Control point invariant");
  5509         start = chunk_array[chunk_top - 1];
  5510         end   = space->top();
  5512       MemRegion mr(start, end);
  5513       // Verify that mr is in space
  5514       assert(mr.is_empty() || space->used_region().contains(mr),
  5515              "Should be in space");
  5516       // Verify that "start" is an object boundary
  5517       assert(mr.is_empty() || oop(mr.start())->is_oop(),
  5518              "Should be an oop");
  5519       space->par_oop_iterate(mr, cl);
  5521     pst->all_tasks_completed();
  5525 void
  5526 CMSParRemarkTask::do_dirty_card_rescan_tasks(
  5527   CompactibleFreeListSpace* sp, int i,
  5528   Par_MarkRefsIntoAndScanClosure* cl) {
  5529   // Until all tasks completed:
  5530   // . claim an unclaimed task
  5531   // . compute region boundaries corresponding to task claimed
  5532   // . transfer dirty bits ct->mut for that region
  5533   // . apply rescanclosure to dirty mut bits for that region
  5535   ResourceMark rm;
  5536   HandleMark   hm;
  5538   OopTaskQueue* work_q = work_queue(i);
  5539   ModUnionClosure modUnionClosure(&(_collector->_modUnionTable));
  5540   // CAUTION! CAUTION! CAUTION! CAUTION! CAUTION! CAUTION! CAUTION!
  5541   // CAUTION: This closure has state that persists across calls to
  5542   // the work method dirty_range_iterate_clear() in that it has
  5543   // imbedded in it a (subtype of) UpwardsObjectClosure. The
  5544   // use of that state in the imbedded UpwardsObjectClosure instance
  5545   // assumes that the cards are always iterated (even if in parallel
  5546   // by several threads) in monotonically increasing order per each
  5547   // thread. This is true of the implementation below which picks
  5548   // card ranges (chunks) in monotonically increasing order globally
  5549   // and, a-fortiori, in monotonically increasing order per thread
  5550   // (the latter order being a subsequence of the former).
  5551   // If the work code below is ever reorganized into a more chaotic
  5552   // work-partitioning form than the current "sequential tasks"
  5553   // paradigm, the use of that persistent state will have to be
  5554   // revisited and modified appropriately. See also related
  5555   // bug 4756801 work on which should examine this code to make
  5556   // sure that the changes there do not run counter to the
  5557   // assumptions made here and necessary for correctness and
  5558   // efficiency. Note also that this code might yield inefficient
  5559   // behaviour in the case of very large objects that span one or
  5560   // more work chunks. Such objects would potentially be scanned
  5561   // several times redundantly. Work on 4756801 should try and
  5562   // address that performance anomaly if at all possible. XXX
  5563   MemRegion  full_span  = _collector->_span;
  5564   CMSBitMap* bm    = &(_collector->_markBitMap);     // shared
  5565   MarkFromDirtyCardsClosure
  5566     greyRescanClosure(_collector, full_span, // entire span of interest
  5567                       sp, bm, work_q, cl);
  5569   SequentialSubTasksDone* pst = sp->conc_par_seq_tasks();
  5570   assert(pst->valid(), "Uninitialized use?");
  5571   uint nth_task = 0;
  5572   const int alignment = CardTableModRefBS::card_size * BitsPerWord;
  5573   MemRegion span = sp->used_region();
  5574   HeapWord* start_addr = span.start();
  5575   HeapWord* end_addr = (HeapWord*)round_to((intptr_t)span.end(),
  5576                                            alignment);
  5577   const size_t chunk_size = sp->rescan_task_size(); // in HeapWord units
  5578   assert((HeapWord*)round_to((intptr_t)start_addr, alignment) ==
  5579          start_addr, "Check alignment");
  5580   assert((size_t)round_to((intptr_t)chunk_size, alignment) ==
  5581          chunk_size, "Check alignment");
  5583   while (!pst->is_task_claimed(/* reference */ nth_task)) {
  5584     // Having claimed the nth_task, compute corresponding mem-region,
  5585     // which is a-fortiori aligned correctly (i.e. at a MUT bopundary).
  5586     // The alignment restriction ensures that we do not need any
  5587     // synchronization with other gang-workers while setting or
  5588     // clearing bits in thus chunk of the MUT.
  5589     MemRegion this_span = MemRegion(start_addr + nth_task*chunk_size,
  5590                                     start_addr + (nth_task+1)*chunk_size);
  5591     // The last chunk's end might be way beyond end of the
  5592     // used region. In that case pull back appropriately.
  5593     if (this_span.end() > end_addr) {
  5594       this_span.set_end(end_addr);
  5595       assert(!this_span.is_empty(), "Program logic (calculation of n_tasks)");
  5597     // Iterate over the dirty cards covering this chunk, marking them
  5598     // precleaned, and setting the corresponding bits in the mod union
  5599     // table. Since we have been careful to partition at Card and MUT-word
  5600     // boundaries no synchronization is needed between parallel threads.
  5601     _collector->_ct->ct_bs()->dirty_card_iterate(this_span,
  5602                                                  &modUnionClosure);
  5604     // Having transferred these marks into the modUnionTable,
  5605     // rescan the marked objects on the dirty cards in the modUnionTable.
  5606     // Even if this is at a synchronous collection, the initial marking
  5607     // may have been done during an asynchronous collection so there
  5608     // may be dirty bits in the mod-union table.
  5609     _collector->_modUnionTable.dirty_range_iterate_clear(
  5610                   this_span, &greyRescanClosure);
  5611     _collector->_modUnionTable.verifyNoOneBitsInRange(
  5612                                  this_span.start(),
  5613                                  this_span.end());
  5615   pst->all_tasks_completed();  // declare that i am done
  5618 // . see if we can share work_queues with ParNew? XXX
  5619 void
  5620 CMSParRemarkTask::do_work_steal(int i, Par_MarkRefsIntoAndScanClosure* cl,
  5621                                 int* seed) {
  5622   OopTaskQueue* work_q = work_queue(i);
  5623   NOT_PRODUCT(int num_steals = 0;)
  5624   oop obj_to_scan;
  5625   CMSBitMap* bm = &(_collector->_markBitMap);
  5627   while (true) {
  5628     // Completely finish any left over work from (an) earlier round(s)
  5629     cl->trim_queue(0);
  5630     size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
  5631                                          (size_t)ParGCDesiredObjsFromOverflowList);
  5632     // Now check if there's any work in the overflow list
  5633     // Passing ParallelGCThreads as the third parameter, no_of_gc_threads,
  5634     // only affects the number of attempts made to get work from the
  5635     // overflow list and does not affect the number of workers.  Just
  5636     // pass ParallelGCThreads so this behavior is unchanged.
  5637     if (_collector->par_take_from_overflow_list(num_from_overflow_list,
  5638                                                 work_q,
  5639                                                 ParallelGCThreads)) {
  5640       // found something in global overflow list;
  5641       // not yet ready to go stealing work from others.
  5642       // We'd like to assert(work_q->size() != 0, ...)
  5643       // because we just took work from the overflow list,
  5644       // but of course we can't since all of that could have
  5645       // been already stolen from us.
  5646       // "He giveth and He taketh away."
  5647       continue;
  5649     // Verify that we have no work before we resort to stealing
  5650     assert(work_q->size() == 0, "Have work, shouldn't steal");
  5651     // Try to steal from other queues that have work
  5652     if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) {
  5653       NOT_PRODUCT(num_steals++;)
  5654       assert(obj_to_scan->is_oop(), "Oops, not an oop!");
  5655       assert(bm->isMarked((HeapWord*)obj_to_scan), "Stole an unmarked oop?");
  5656       // Do scanning work
  5657       obj_to_scan->oop_iterate(cl);
  5658       // Loop around, finish this work, and try to steal some more
  5659     } else if (terminator()->offer_termination()) {
  5660         break;  // nirvana from the infinite cycle
  5663   NOT_PRODUCT(
  5664     if (PrintCMSStatistics != 0) {
  5665       gclog_or_tty->print("\n\t(%d: stole %d oops)", i, num_steals);
  5668   assert(work_q->size() == 0 && _collector->overflow_list_is_empty(),
  5669          "Else our work is not yet done");
  5672 // Record object boundaries in _eden_chunk_array by sampling the eden
  5673 // top in the slow-path eden object allocation code path and record
  5674 // the boundaries, if CMSEdenChunksRecordAlways is true. If
  5675 // CMSEdenChunksRecordAlways is false, we use the other asynchronous
  5676 // sampling in sample_eden() that activates during the part of the
  5677 // preclean phase.
  5678 void CMSCollector::sample_eden_chunk() {
  5679   if (CMSEdenChunksRecordAlways && _eden_chunk_array != NULL) {
  5680     if (_eden_chunk_lock->try_lock()) {
  5681       // Record a sample. This is the critical section. The contents
  5682       // of the _eden_chunk_array have to be non-decreasing in the
  5683       // address order.
  5684       _eden_chunk_array[_eden_chunk_index] = *_top_addr;
  5685       assert(_eden_chunk_array[_eden_chunk_index] <= *_end_addr,
  5686              "Unexpected state of Eden");
  5687       if (_eden_chunk_index == 0 ||
  5688           ((_eden_chunk_array[_eden_chunk_index] > _eden_chunk_array[_eden_chunk_index-1]) &&
  5689            (pointer_delta(_eden_chunk_array[_eden_chunk_index],
  5690                           _eden_chunk_array[_eden_chunk_index-1]) >= CMSSamplingGrain))) {
  5691         _eden_chunk_index++;  // commit sample
  5693       _eden_chunk_lock->unlock();
  5698 // Return a thread-local PLAB recording array, as appropriate.
  5699 void* CMSCollector::get_data_recorder(int thr_num) {
  5700   if (_survivor_plab_array != NULL &&
  5701       (CMSPLABRecordAlways ||
  5702        (_collectorState > Marking && _collectorState < FinalMarking))) {
  5703     assert(thr_num < (int)ParallelGCThreads, "thr_num is out of bounds");
  5704     ChunkArray* ca = &_survivor_plab_array[thr_num];
  5705     ca->reset();   // clear it so that fresh data is recorded
  5706     return (void*) ca;
  5707   } else {
  5708     return NULL;
  5712 // Reset all the thread-local PLAB recording arrays
  5713 void CMSCollector::reset_survivor_plab_arrays() {
  5714   for (uint i = 0; i < ParallelGCThreads; i++) {
  5715     _survivor_plab_array[i].reset();
  5719 // Merge the per-thread plab arrays into the global survivor chunk
  5720 // array which will provide the partitioning of the survivor space
  5721 // for CMS initial scan and rescan.
  5722 void CMSCollector::merge_survivor_plab_arrays(ContiguousSpace* surv,
  5723                                               int no_of_gc_threads) {
  5724   assert(_survivor_plab_array  != NULL, "Error");
  5725   assert(_survivor_chunk_array != NULL, "Error");
  5726   assert(_collectorState == FinalMarking ||
  5727          (CMSParallelInitialMarkEnabled && _collectorState == InitialMarking), "Error");
  5728   for (int j = 0; j < no_of_gc_threads; j++) {
  5729     _cursor[j] = 0;
  5731   HeapWord* top = surv->top();
  5732   size_t i;
  5733   for (i = 0; i < _survivor_chunk_capacity; i++) {  // all sca entries
  5734     HeapWord* min_val = top;          // Higher than any PLAB address
  5735     uint      min_tid = 0;            // position of min_val this round
  5736     for (int j = 0; j < no_of_gc_threads; j++) {
  5737       ChunkArray* cur_sca = &_survivor_plab_array[j];
  5738       if (_cursor[j] == cur_sca->end()) {
  5739         continue;
  5741       assert(_cursor[j] < cur_sca->end(), "ctl pt invariant");
  5742       HeapWord* cur_val = cur_sca->nth(_cursor[j]);
  5743       assert(surv->used_region().contains(cur_val), "Out of bounds value");
  5744       if (cur_val < min_val) {
  5745         min_tid = j;
  5746         min_val = cur_val;
  5747       } else {
  5748         assert(cur_val < top, "All recorded addresses should be less");
  5751     // At this point min_val and min_tid are respectively
  5752     // the least address in _survivor_plab_array[j]->nth(_cursor[j])
  5753     // and the thread (j) that witnesses that address.
  5754     // We record this address in the _survivor_chunk_array[i]
  5755     // and increment _cursor[min_tid] prior to the next round i.
  5756     if (min_val == top) {
  5757       break;
  5759     _survivor_chunk_array[i] = min_val;
  5760     _cursor[min_tid]++;
  5762   // We are all done; record the size of the _survivor_chunk_array
  5763   _survivor_chunk_index = i; // exclusive: [0, i)
  5764   if (PrintCMSStatistics > 0) {
  5765     gclog_or_tty->print(" (Survivor:" SIZE_FORMAT "chunks) ", i);
  5767   // Verify that we used up all the recorded entries
  5768   #ifdef ASSERT
  5769     size_t total = 0;
  5770     for (int j = 0; j < no_of_gc_threads; j++) {
  5771       assert(_cursor[j] == _survivor_plab_array[j].end(), "Ctl pt invariant");
  5772       total += _cursor[j];
  5774     assert(total == _survivor_chunk_index, "Ctl Pt Invariant");
  5775     // Check that the merged array is in sorted order
  5776     if (total > 0) {
  5777       for (size_t i = 0; i < total - 1; i++) {
  5778         if (PrintCMSStatistics > 0) {
  5779           gclog_or_tty->print(" (chunk" SIZE_FORMAT ":" INTPTR_FORMAT ") ",
  5780                               i, _survivor_chunk_array[i]);
  5782         assert(_survivor_chunk_array[i] < _survivor_chunk_array[i+1],
  5783                "Not sorted");
  5786   #endif // ASSERT
  5789 // Set up the space's par_seq_tasks structure for work claiming
  5790 // for parallel initial scan and rescan of young gen.
  5791 // See ParRescanTask where this is currently used.
  5792 void
  5793 CMSCollector::
  5794 initialize_sequential_subtasks_for_young_gen_rescan(int n_threads) {
  5795   assert(n_threads > 0, "Unexpected n_threads argument");
  5796   DefNewGeneration* dng = (DefNewGeneration*)_young_gen;
  5798   // Eden space
  5799   if (!dng->eden()->is_empty()) {
  5800     SequentialSubTasksDone* pst = dng->eden()->par_seq_tasks();
  5801     assert(!pst->valid(), "Clobbering existing data?");
  5802     // Each valid entry in [0, _eden_chunk_index) represents a task.
  5803     size_t n_tasks = _eden_chunk_index + 1;
  5804     assert(n_tasks == 1 || _eden_chunk_array != NULL, "Error");
  5805     // Sets the condition for completion of the subtask (how many threads
  5806     // need to finish in order to be done).
  5807     pst->set_n_threads(n_threads);
  5808     pst->set_n_tasks((int)n_tasks);
  5811   // Merge the survivor plab arrays into _survivor_chunk_array
  5812   if (_survivor_plab_array != NULL) {
  5813     merge_survivor_plab_arrays(dng->from(), n_threads);
  5814   } else {
  5815     assert(_survivor_chunk_index == 0, "Error");
  5818   // To space
  5820     SequentialSubTasksDone* pst = dng->to()->par_seq_tasks();
  5821     assert(!pst->valid(), "Clobbering existing data?");
  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(1);
  5826     assert(pst->valid(), "Error");
  5829   // From space
  5831     SequentialSubTasksDone* pst = dng->from()->par_seq_tasks();
  5832     assert(!pst->valid(), "Clobbering existing data?");
  5833     size_t n_tasks = _survivor_chunk_index + 1;
  5834     assert(n_tasks == 1 || _survivor_chunk_array != NULL, "Error");
  5835     // Sets the condition for completion of the subtask (how many threads
  5836     // need to finish in order to be done).
  5837     pst->set_n_threads(n_threads);
  5838     pst->set_n_tasks((int)n_tasks);
  5839     assert(pst->valid(), "Error");
  5843 // Parallel version of remark
  5844 void CMSCollector::do_remark_parallel() {
  5845   GenCollectedHeap* gch = GenCollectedHeap::heap();
  5846   FlexibleWorkGang* workers = gch->workers();
  5847   assert(workers != NULL, "Need parallel worker threads.");
  5848   // Choose to use the number of GC workers most recently set
  5849   // into "active_workers".  If active_workers is not set, set it
  5850   // to ParallelGCThreads.
  5851   int n_workers = workers->active_workers();
  5852   if (n_workers == 0) {
  5853     assert(n_workers > 0, "Should have been set during scavenge");
  5854     n_workers = ParallelGCThreads;
  5855     workers->set_active_workers(n_workers);
  5857   CompactibleFreeListSpace* cms_space  = _cmsGen->cmsSpace();
  5859   CMSParRemarkTask tsk(this,
  5860     cms_space,
  5861     n_workers, workers, task_queues());
  5863   // Set up for parallel process_strong_roots work.
  5864   gch->set_par_threads(n_workers);
  5865   // We won't be iterating over the cards in the card table updating
  5866   // the younger_gen cards, so we shouldn't call the following else
  5867   // the verification code as well as subsequent younger_refs_iterate
  5868   // code would get confused. XXX
  5869   // gch->rem_set()->prepare_for_younger_refs_iterate(true); // parallel
  5871   // The young gen rescan work will not be done as part of
  5872   // process_strong_roots (which currently doesn't knw how to
  5873   // parallelize such a scan), but rather will be broken up into
  5874   // a set of parallel tasks (via the sampling that the [abortable]
  5875   // preclean phase did of EdenSpace, plus the [two] tasks of
  5876   // scanning the [two] survivor spaces. Further fine-grain
  5877   // parallelization of the scanning of the survivor spaces
  5878   // themselves, and of precleaning of the younger gen itself
  5879   // is deferred to the future.
  5880   initialize_sequential_subtasks_for_young_gen_rescan(n_workers);
  5882   // The dirty card rescan work is broken up into a "sequence"
  5883   // of parallel tasks (per constituent space) that are dynamically
  5884   // claimed by the parallel threads.
  5885   cms_space->initialize_sequential_subtasks_for_rescan(n_workers);
  5887   // It turns out that even when we're using 1 thread, doing the work in a
  5888   // separate thread causes wide variance in run times.  We can't help this
  5889   // in the multi-threaded case, but we special-case n=1 here to get
  5890   // repeatable measurements of the 1-thread overhead of the parallel code.
  5891   if (n_workers > 1) {
  5892     // Make refs discovery MT-safe, if it isn't already: it may not
  5893     // necessarily be so, since it's possible that we are doing
  5894     // ST marking.
  5895     ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), true);
  5896     GenCollectedHeap::StrongRootsScope srs(gch);
  5897     workers->run_task(&tsk);
  5898   } else {
  5899     ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), false);
  5900     GenCollectedHeap::StrongRootsScope srs(gch);
  5901     tsk.work(0);
  5904   gch->set_par_threads(0);  // 0 ==> non-parallel.
  5905   // restore, single-threaded for now, any preserved marks
  5906   // as a result of work_q overflow
  5907   restore_preserved_marks_if_any();
  5910 // Non-parallel version of remark
  5911 void CMSCollector::do_remark_non_parallel() {
  5912   ResourceMark rm;
  5913   HandleMark   hm;
  5914   GenCollectedHeap* gch = GenCollectedHeap::heap();
  5915   ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), false);
  5917   MarkRefsIntoAndScanClosure
  5918     mrias_cl(_span, ref_processor(), &_markBitMap, NULL /* not precleaning */,
  5919              &_markStack, this,
  5920              false /* should_yield */, false /* not precleaning */);
  5921   MarkFromDirtyCardsClosure
  5922     markFromDirtyCardsClosure(this, _span,
  5923                               NULL,  // space is set further below
  5924                               &_markBitMap, &_markStack, &mrias_cl);
  5926     GCTraceTime t("grey object rescan", PrintGCDetails, false, _gc_timer_cm);
  5927     // Iterate over the dirty cards, setting the corresponding bits in the
  5928     // mod union table.
  5930       ModUnionClosure modUnionClosure(&_modUnionTable);
  5931       _ct->ct_bs()->dirty_card_iterate(
  5932                       _cmsGen->used_region(),
  5933                       &modUnionClosure);
  5935     // Having transferred these marks into the modUnionTable, we just need
  5936     // to rescan the marked objects on the dirty cards in the modUnionTable.
  5937     // The initial marking may have been done during an asynchronous
  5938     // collection so there may be dirty bits in the mod-union table.
  5939     const int alignment =
  5940       CardTableModRefBS::card_size * BitsPerWord;
  5942       // ... First handle dirty cards in CMS gen
  5943       markFromDirtyCardsClosure.set_space(_cmsGen->cmsSpace());
  5944       MemRegion ur = _cmsGen->used_region();
  5945       HeapWord* lb = ur.start();
  5946       HeapWord* ub = (HeapWord*)round_to((intptr_t)ur.end(), alignment);
  5947       MemRegion cms_span(lb, ub);
  5948       _modUnionTable.dirty_range_iterate_clear(cms_span,
  5949                                                &markFromDirtyCardsClosure);
  5950       verify_work_stacks_empty();
  5951       if (PrintCMSStatistics != 0) {
  5952         gclog_or_tty->print(" (re-scanned "SIZE_FORMAT" dirty cards in cms gen) ",
  5953           markFromDirtyCardsClosure.num_dirty_cards());
  5957   if (VerifyDuringGC &&
  5958       GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  5959     HandleMark hm;  // Discard invalid handles created during verification
  5960     Universe::verify();
  5963     GCTraceTime t("root rescan", PrintGCDetails, false, _gc_timer_cm);
  5965     verify_work_stacks_empty();
  5967     gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
  5968     GenCollectedHeap::StrongRootsScope srs(gch);
  5969     gch->gen_process_strong_roots(_cmsGen->level(),
  5970                                   true,  // younger gens as roots
  5971                                   false, // use the local StrongRootsScope
  5972                                   false, // not scavenging
  5973                                   SharedHeap::ScanningOption(roots_scanning_options()),
  5974                                   &mrias_cl,
  5975                                   true,   // walk code active on stacks
  5976                                   NULL,
  5977                                   NULL);  // The dirty klasses will be handled below
  5979     assert(should_unload_classes()
  5980            || (roots_scanning_options() & SharedHeap::SO_CodeCache),
  5981            "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops");
  5985     GCTraceTime t("visit unhandled CLDs", PrintGCDetails, false, _gc_timer_cm);
  5987     verify_work_stacks_empty();
  5989     // Scan all class loader data objects that might have been introduced
  5990     // during concurrent marking.
  5991     ResourceMark rm;
  5992     GrowableArray<ClassLoaderData*>* array = ClassLoaderDataGraph::new_clds();
  5993     for (int i = 0; i < array->length(); i++) {
  5994       mrias_cl.do_class_loader_data(array->at(i));
  5997     // We don't need to keep track of new CLDs anymore.
  5998     ClassLoaderDataGraph::remember_new_clds(false);
  6000     verify_work_stacks_empty();
  6004     GCTraceTime t("dirty klass scan", PrintGCDetails, false, _gc_timer_cm);
  6006     verify_work_stacks_empty();
  6008     RemarkKlassClosure remark_klass_closure(&mrias_cl);
  6009     ClassLoaderDataGraph::classes_do(&remark_klass_closure);
  6011     verify_work_stacks_empty();
  6014   // We might have added oops to ClassLoaderData::_handles during the
  6015   // concurrent marking phase. These oops point to newly allocated objects
  6016   // that are guaranteed to be kept alive. Either by the direct allocation
  6017   // code, or when the young collector processes the strong roots. Hence,
  6018   // we don't have to revisit the _handles block during the remark phase.
  6020   verify_work_stacks_empty();
  6021   // Restore evacuated mark words, if any, used for overflow list links
  6022   if (!CMSOverflowEarlyRestoration) {
  6023     restore_preserved_marks_if_any();
  6025   verify_overflow_empty();
  6028 ////////////////////////////////////////////////////////
  6029 // Parallel Reference Processing Task Proxy Class
  6030 ////////////////////////////////////////////////////////
  6031 class CMSRefProcTaskProxy: public AbstractGangTaskWOopQueues {
  6032   typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
  6033   CMSCollector*          _collector;
  6034   CMSBitMap*             _mark_bit_map;
  6035   const MemRegion        _span;
  6036   ProcessTask&           _task;
  6038 public:
  6039   CMSRefProcTaskProxy(ProcessTask&     task,
  6040                       CMSCollector*    collector,
  6041                       const MemRegion& span,
  6042                       CMSBitMap*       mark_bit_map,
  6043                       AbstractWorkGang* workers,
  6044                       OopTaskQueueSet* task_queues):
  6045     // XXX Should superclass AGTWOQ also know about AWG since it knows
  6046     // about the task_queues used by the AWG? Then it could initialize
  6047     // the terminator() object. See 6984287. The set_for_termination()
  6048     // below is a temporary band-aid for the regression in 6984287.
  6049     AbstractGangTaskWOopQueues("Process referents by policy in parallel",
  6050       task_queues),
  6051     _task(task),
  6052     _collector(collector), _span(span), _mark_bit_map(mark_bit_map)
  6054     assert(_collector->_span.equals(_span) && !_span.is_empty(),
  6055            "Inconsistency in _span");
  6056     set_for_termination(workers->active_workers());
  6059   OopTaskQueueSet* task_queues() { return queues(); }
  6061   OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); }
  6063   void do_work_steal(int i,
  6064                      CMSParDrainMarkingStackClosure* drain,
  6065                      CMSParKeepAliveClosure* keep_alive,
  6066                      int* seed);
  6068   virtual void work(uint worker_id);
  6069 };
  6071 void CMSRefProcTaskProxy::work(uint worker_id) {
  6072   assert(_collector->_span.equals(_span), "Inconsistency in _span");
  6073   CMSParKeepAliveClosure par_keep_alive(_collector, _span,
  6074                                         _mark_bit_map,
  6075                                         work_queue(worker_id));
  6076   CMSParDrainMarkingStackClosure par_drain_stack(_collector, _span,
  6077                                                  _mark_bit_map,
  6078                                                  work_queue(worker_id));
  6079   CMSIsAliveClosure is_alive_closure(_span, _mark_bit_map);
  6080   _task.work(worker_id, is_alive_closure, par_keep_alive, par_drain_stack);
  6081   if (_task.marks_oops_alive()) {
  6082     do_work_steal(worker_id, &par_drain_stack, &par_keep_alive,
  6083                   _collector->hash_seed(worker_id));
  6085   assert(work_queue(worker_id)->size() == 0, "work_queue should be empty");
  6086   assert(_collector->_overflow_list == NULL, "non-empty _overflow_list");
  6089 class CMSRefEnqueueTaskProxy: public AbstractGangTask {
  6090   typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
  6091   EnqueueTask& _task;
  6093 public:
  6094   CMSRefEnqueueTaskProxy(EnqueueTask& task)
  6095     : AbstractGangTask("Enqueue reference objects in parallel"),
  6096       _task(task)
  6097   { }
  6099   virtual void work(uint worker_id)
  6101     _task.work(worker_id);
  6103 };
  6105 CMSParKeepAliveClosure::CMSParKeepAliveClosure(CMSCollector* collector,
  6106   MemRegion span, CMSBitMap* bit_map, OopTaskQueue* work_queue):
  6107    _span(span),
  6108    _bit_map(bit_map),
  6109    _work_queue(work_queue),
  6110    _mark_and_push(collector, span, bit_map, work_queue),
  6111    _low_water_mark(MIN2((uint)(work_queue->max_elems()/4),
  6112                         (uint)(CMSWorkQueueDrainThreshold * ParallelGCThreads)))
  6113 { }
  6115 // . see if we can share work_queues with ParNew? XXX
  6116 void CMSRefProcTaskProxy::do_work_steal(int i,
  6117   CMSParDrainMarkingStackClosure* drain,
  6118   CMSParKeepAliveClosure* keep_alive,
  6119   int* seed) {
  6120   OopTaskQueue* work_q = work_queue(i);
  6121   NOT_PRODUCT(int num_steals = 0;)
  6122   oop obj_to_scan;
  6124   while (true) {
  6125     // Completely finish any left over work from (an) earlier round(s)
  6126     drain->trim_queue(0);
  6127     size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
  6128                                          (size_t)ParGCDesiredObjsFromOverflowList);
  6129     // Now check if there's any work in the overflow list
  6130     // Passing ParallelGCThreads as the third parameter, no_of_gc_threads,
  6131     // only affects the number of attempts made to get work from the
  6132     // overflow list and does not affect the number of workers.  Just
  6133     // pass ParallelGCThreads so this behavior is unchanged.
  6134     if (_collector->par_take_from_overflow_list(num_from_overflow_list,
  6135                                                 work_q,
  6136                                                 ParallelGCThreads)) {
  6137       // Found something in global overflow list;
  6138       // not yet ready to go stealing work from others.
  6139       // We'd like to assert(work_q->size() != 0, ...)
  6140       // because we just took work from the overflow list,
  6141       // but of course we can't, since all of that might have
  6142       // been already stolen from us.
  6143       continue;
  6145     // Verify that we have no work before we resort to stealing
  6146     assert(work_q->size() == 0, "Have work, shouldn't steal");
  6147     // Try to steal from other queues that have work
  6148     if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) {
  6149       NOT_PRODUCT(num_steals++;)
  6150       assert(obj_to_scan->is_oop(), "Oops, not an oop!");
  6151       assert(_mark_bit_map->isMarked((HeapWord*)obj_to_scan), "Stole an unmarked oop?");
  6152       // Do scanning work
  6153       obj_to_scan->oop_iterate(keep_alive);
  6154       // Loop around, finish this work, and try to steal some more
  6155     } else if (terminator()->offer_termination()) {
  6156       break;  // nirvana from the infinite cycle
  6159   NOT_PRODUCT(
  6160     if (PrintCMSStatistics != 0) {
  6161       gclog_or_tty->print("\n\t(%d: stole %d oops)", i, num_steals);
  6166 void CMSRefProcTaskExecutor::execute(ProcessTask& task)
  6168   GenCollectedHeap* gch = GenCollectedHeap::heap();
  6169   FlexibleWorkGang* workers = gch->workers();
  6170   assert(workers != NULL, "Need parallel worker threads.");
  6171   CMSRefProcTaskProxy rp_task(task, &_collector,
  6172                               _collector.ref_processor()->span(),
  6173                               _collector.markBitMap(),
  6174                               workers, _collector.task_queues());
  6175   workers->run_task(&rp_task);
  6178 void CMSRefProcTaskExecutor::execute(EnqueueTask& task)
  6181   GenCollectedHeap* gch = GenCollectedHeap::heap();
  6182   FlexibleWorkGang* workers = gch->workers();
  6183   assert(workers != NULL, "Need parallel worker threads.");
  6184   CMSRefEnqueueTaskProxy enq_task(task);
  6185   workers->run_task(&enq_task);
  6188 void CMSCollector::refProcessingWork(bool asynch, bool clear_all_soft_refs) {
  6190   ResourceMark rm;
  6191   HandleMark   hm;
  6193   ReferenceProcessor* rp = ref_processor();
  6194   assert(rp->span().equals(_span), "Spans should be equal");
  6195   assert(!rp->enqueuing_is_done(), "Enqueuing should not be complete");
  6196   // Process weak references.
  6197   rp->setup_policy(clear_all_soft_refs);
  6198   verify_work_stacks_empty();
  6200   CMSKeepAliveClosure cmsKeepAliveClosure(this, _span, &_markBitMap,
  6201                                           &_markStack, false /* !preclean */);
  6202   CMSDrainMarkingStackClosure cmsDrainMarkingStackClosure(this,
  6203                                 _span, &_markBitMap, &_markStack,
  6204                                 &cmsKeepAliveClosure, false /* !preclean */);
  6206     GCTraceTime t("weak refs processing", PrintGCDetails, false, _gc_timer_cm);
  6208     ReferenceProcessorStats stats;
  6209     if (rp->processing_is_mt()) {
  6210       // Set the degree of MT here.  If the discovery is done MT, there
  6211       // may have been a different number of threads doing the discovery
  6212       // and a different number of discovered lists may have Ref objects.
  6213       // That is OK as long as the Reference lists are balanced (see
  6214       // balance_all_queues() and balance_queues()).
  6215       GenCollectedHeap* gch = GenCollectedHeap::heap();
  6216       int active_workers = ParallelGCThreads;
  6217       FlexibleWorkGang* workers = gch->workers();
  6218       if (workers != NULL) {
  6219         active_workers = workers->active_workers();
  6220         // The expectation is that active_workers will have already
  6221         // been set to a reasonable value.  If it has not been set,
  6222         // investigate.
  6223         assert(active_workers > 0, "Should have been set during scavenge");
  6225       rp->set_active_mt_degree(active_workers);
  6226       CMSRefProcTaskExecutor task_executor(*this);
  6227       stats = rp->process_discovered_references(&_is_alive_closure,
  6228                                         &cmsKeepAliveClosure,
  6229                                         &cmsDrainMarkingStackClosure,
  6230                                         &task_executor,
  6231                                         _gc_timer_cm);
  6232     } else {
  6233       stats = rp->process_discovered_references(&_is_alive_closure,
  6234                                         &cmsKeepAliveClosure,
  6235                                         &cmsDrainMarkingStackClosure,
  6236                                         NULL,
  6237                                         _gc_timer_cm);
  6239     _gc_tracer_cm->report_gc_reference_stats(stats);
  6243   // This is the point where the entire marking should have completed.
  6244   verify_work_stacks_empty();
  6246   if (should_unload_classes()) {
  6248       GCTraceTime t("class unloading", PrintGCDetails, false, _gc_timer_cm);
  6250       // Unload classes and purge the SystemDictionary.
  6251       bool purged_class = SystemDictionary::do_unloading(&_is_alive_closure);
  6253       // Unload nmethods.
  6254       CodeCache::do_unloading(&_is_alive_closure, purged_class);
  6256       // Prune dead klasses from subklass/sibling/implementor lists.
  6257       Klass::clean_weak_klass_links(&_is_alive_closure);
  6261       GCTraceTime t("scrub symbol table", PrintGCDetails, false, _gc_timer_cm);
  6262       // Clean up unreferenced symbols in symbol table.
  6263       SymbolTable::unlink();
  6267   // CMS doesn't use the StringTable as hard roots when class unloading is turned off.
  6268   // Need to check if we really scanned the StringTable.
  6269   if ((roots_scanning_options() & SharedHeap::SO_Strings) == 0) {
  6270     GCTraceTime t("scrub string table", PrintGCDetails, false, _gc_timer_cm);
  6271     // Delete entries for dead interned strings.
  6272     StringTable::unlink(&_is_alive_closure);
  6275   // Restore any preserved marks as a result of mark stack or
  6276   // work queue overflow
  6277   restore_preserved_marks_if_any();  // done single-threaded for now
  6279   rp->set_enqueuing_is_done(true);
  6280   if (rp->processing_is_mt()) {
  6281     rp->balance_all_queues();
  6282     CMSRefProcTaskExecutor task_executor(*this);
  6283     rp->enqueue_discovered_references(&task_executor);
  6284   } else {
  6285     rp->enqueue_discovered_references(NULL);
  6287   rp->verify_no_references_recorded();
  6288   assert(!rp->discovery_enabled(), "should have been disabled");
  6291 #ifndef PRODUCT
  6292 void CMSCollector::check_correct_thread_executing() {
  6293   Thread* t = Thread::current();
  6294   // Only the VM thread or the CMS thread should be here.
  6295   assert(t->is_ConcurrentGC_thread() || t->is_VM_thread(),
  6296          "Unexpected thread type");
  6297   // If this is the vm thread, the foreground process
  6298   // should not be waiting.  Note that _foregroundGCIsActive is
  6299   // true while the foreground collector is waiting.
  6300   if (_foregroundGCShouldWait) {
  6301     // We cannot be the VM thread
  6302     assert(t->is_ConcurrentGC_thread(),
  6303            "Should be CMS thread");
  6304   } else {
  6305     // We can be the CMS thread only if we are in a stop-world
  6306     // phase of CMS collection.
  6307     if (t->is_ConcurrentGC_thread()) {
  6308       assert(_collectorState == InitialMarking ||
  6309              _collectorState == FinalMarking,
  6310              "Should be a stop-world phase");
  6311       // The CMS thread should be holding the CMS_token.
  6312       assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  6313              "Potential interference with concurrently "
  6314              "executing VM thread");
  6318 #endif
  6320 void CMSCollector::sweep(bool asynch) {
  6321   assert(_collectorState == Sweeping, "just checking");
  6322   check_correct_thread_executing();
  6323   verify_work_stacks_empty();
  6324   verify_overflow_empty();
  6325   increment_sweep_count();
  6326   TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause());
  6328   _inter_sweep_timer.stop();
  6329   _inter_sweep_estimate.sample(_inter_sweep_timer.seconds());
  6330   size_policy()->avg_cms_free_at_sweep()->sample(_cmsGen->free());
  6332   assert(!_intra_sweep_timer.is_active(), "Should not be active");
  6333   _intra_sweep_timer.reset();
  6334   _intra_sweep_timer.start();
  6335   if (asynch) {
  6336     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  6337     CMSPhaseAccounting pa(this, "sweep", !PrintGCDetails);
  6338     // First sweep the old gen
  6340       CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock(),
  6341                                bitMapLock());
  6342       sweepWork(_cmsGen, asynch);
  6345     // Update Universe::_heap_*_at_gc figures.
  6346     // We need all the free list locks to make the abstract state
  6347     // transition from Sweeping to Resetting. See detailed note
  6348     // further below.
  6350       CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock());
  6351       // Update heap occupancy information which is used as
  6352       // input to soft ref clearing policy at the next gc.
  6353       Universe::update_heap_info_at_gc();
  6354       _collectorState = Resizing;
  6356   } else {
  6357     // already have needed locks
  6358     sweepWork(_cmsGen,  asynch);
  6359     // Update heap occupancy information which is used as
  6360     // input to soft ref clearing policy at the next gc.
  6361     Universe::update_heap_info_at_gc();
  6362     _collectorState = Resizing;
  6364   verify_work_stacks_empty();
  6365   verify_overflow_empty();
  6367   if (should_unload_classes()) {
  6368     // Delay purge to the beginning of the next safepoint.  Metaspace::contains
  6369     // requires that the virtual spaces are stable and not deleted.
  6370     ClassLoaderDataGraph::set_should_purge(true);
  6373   _intra_sweep_timer.stop();
  6374   _intra_sweep_estimate.sample(_intra_sweep_timer.seconds());
  6376   _inter_sweep_timer.reset();
  6377   _inter_sweep_timer.start();
  6379   // We need to use a monotonically non-deccreasing time in ms
  6380   // or we will see time-warp warnings and os::javaTimeMillis()
  6381   // does not guarantee monotonicity.
  6382   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
  6383   update_time_of_last_gc(now);
  6385   // NOTE on abstract state transitions:
  6386   // Mutators allocate-live and/or mark the mod-union table dirty
  6387   // based on the state of the collection.  The former is done in
  6388   // the interval [Marking, Sweeping] and the latter in the interval
  6389   // [Marking, Sweeping).  Thus the transitions into the Marking state
  6390   // and out of the Sweeping state must be synchronously visible
  6391   // globally to the mutators.
  6392   // The transition into the Marking state happens with the world
  6393   // stopped so the mutators will globally see it.  Sweeping is
  6394   // done asynchronously by the background collector so the transition
  6395   // from the Sweeping state to the Resizing state must be done
  6396   // under the freelistLock (as is the check for whether to
  6397   // allocate-live and whether to dirty the mod-union table).
  6398   assert(_collectorState == Resizing, "Change of collector state to"
  6399     " Resizing must be done under the freelistLocks (plural)");
  6401   // Now that sweeping has been completed, we clear
  6402   // the incremental_collection_failed flag,
  6403   // thus inviting a younger gen collection to promote into
  6404   // this generation. If such a promotion may still fail,
  6405   // the flag will be set again when a young collection is
  6406   // attempted.
  6407   GenCollectedHeap* gch = GenCollectedHeap::heap();
  6408   gch->clear_incremental_collection_failed();  // Worth retrying as fresh space may have been freed up
  6409   gch->update_full_collections_completed(_collection_count_start);
  6412 // FIX ME!!! Looks like this belongs in CFLSpace, with
  6413 // CMSGen merely delegating to it.
  6414 void ConcurrentMarkSweepGeneration::setNearLargestChunk() {
  6415   double nearLargestPercent = FLSLargestBlockCoalesceProximity;
  6416   HeapWord*  minAddr        = _cmsSpace->bottom();
  6417   HeapWord*  largestAddr    =
  6418     (HeapWord*) _cmsSpace->dictionary()->find_largest_dict();
  6419   if (largestAddr == NULL) {
  6420     // The dictionary appears to be empty.  In this case
  6421     // try to coalesce at the end of the heap.
  6422     largestAddr = _cmsSpace->end();
  6424   size_t largestOffset     = pointer_delta(largestAddr, minAddr);
  6425   size_t nearLargestOffset =
  6426     (size_t)((double)largestOffset * nearLargestPercent) - MinChunkSize;
  6427   if (PrintFLSStatistics != 0) {
  6428     gclog_or_tty->print_cr(
  6429       "CMS: Large Block: " PTR_FORMAT ";"
  6430       " Proximity: " PTR_FORMAT " -> " PTR_FORMAT,
  6431       largestAddr,
  6432       _cmsSpace->nearLargestChunk(), minAddr + nearLargestOffset);
  6434   _cmsSpace->set_nearLargestChunk(minAddr + nearLargestOffset);
  6437 bool ConcurrentMarkSweepGeneration::isNearLargestChunk(HeapWord* addr) {
  6438   return addr >= _cmsSpace->nearLargestChunk();
  6441 FreeChunk* ConcurrentMarkSweepGeneration::find_chunk_at_end() {
  6442   return _cmsSpace->find_chunk_at_end();
  6445 void ConcurrentMarkSweepGeneration::update_gc_stats(int current_level,
  6446                                                     bool full) {
  6447   // The next lower level has been collected.  Gather any statistics
  6448   // that are of interest at this point.
  6449   if (!full && (current_level + 1) == level()) {
  6450     // Gather statistics on the young generation collection.
  6451     collector()->stats().record_gc0_end(used());
  6455 CMSAdaptiveSizePolicy* ConcurrentMarkSweepGeneration::size_policy() {
  6456   GenCollectedHeap* gch = GenCollectedHeap::heap();
  6457   assert(gch->kind() == CollectedHeap::GenCollectedHeap,
  6458     "Wrong type of heap");
  6459   CMSAdaptiveSizePolicy* sp = (CMSAdaptiveSizePolicy*)
  6460     gch->gen_policy()->size_policy();
  6461   assert(sp->is_gc_cms_adaptive_size_policy(),
  6462     "Wrong type of size policy");
  6463   return sp;
  6466 void ConcurrentMarkSweepGeneration::rotate_debug_collection_type() {
  6467   if (PrintGCDetails && Verbose) {
  6468     gclog_or_tty->print("Rotate from %d ", _debug_collection_type);
  6470   _debug_collection_type = (CollectionTypes) (_debug_collection_type + 1);
  6471   _debug_collection_type =
  6472     (CollectionTypes) (_debug_collection_type % Unknown_collection_type);
  6473   if (PrintGCDetails && Verbose) {
  6474     gclog_or_tty->print_cr("to %d ", _debug_collection_type);
  6478 void CMSCollector::sweepWork(ConcurrentMarkSweepGeneration* gen,
  6479   bool asynch) {
  6480   // We iterate over the space(s) underlying this generation,
  6481   // checking the mark bit map to see if the bits corresponding
  6482   // to specific blocks are marked or not. Blocks that are
  6483   // marked are live and are not swept up. All remaining blocks
  6484   // are swept up, with coalescing on-the-fly as we sweep up
  6485   // contiguous free and/or garbage blocks:
  6486   // We need to ensure that the sweeper synchronizes with allocators
  6487   // and stop-the-world collectors. In particular, the following
  6488   // locks are used:
  6489   // . CMS token: if this is held, a stop the world collection cannot occur
  6490   // . freelistLock: if this is held no allocation can occur from this
  6491   //                 generation by another thread
  6492   // . bitMapLock: if this is held, no other thread can access or update
  6493   //
  6495   // Note that we need to hold the freelistLock if we use
  6496   // block iterate below; else the iterator might go awry if
  6497   // a mutator (or promotion) causes block contents to change
  6498   // (for instance if the allocator divvies up a block).
  6499   // If we hold the free list lock, for all practical purposes
  6500   // young generation GC's can't occur (they'll usually need to
  6501   // promote), so we might as well prevent all young generation
  6502   // GC's while we do a sweeping step. For the same reason, we might
  6503   // as well take the bit map lock for the entire duration
  6505   // check that we hold the requisite locks
  6506   assert(have_cms_token(), "Should hold cms token");
  6507   assert(   (asynch && ConcurrentMarkSweepThread::cms_thread_has_cms_token())
  6508          || (!asynch && ConcurrentMarkSweepThread::vm_thread_has_cms_token()),
  6509         "Should possess CMS token to sweep");
  6510   assert_lock_strong(gen->freelistLock());
  6511   assert_lock_strong(bitMapLock());
  6513   assert(!_inter_sweep_timer.is_active(), "Was switched off in an outer context");
  6514   assert(_intra_sweep_timer.is_active(),  "Was switched on  in an outer context");
  6515   gen->cmsSpace()->beginSweepFLCensus((float)(_inter_sweep_timer.seconds()),
  6516                                       _inter_sweep_estimate.padded_average(),
  6517                                       _intra_sweep_estimate.padded_average());
  6518   gen->setNearLargestChunk();
  6521     SweepClosure sweepClosure(this, gen, &_markBitMap,
  6522                             CMSYield && asynch);
  6523     gen->cmsSpace()->blk_iterate_careful(&sweepClosure);
  6524     // We need to free-up/coalesce garbage/blocks from a
  6525     // co-terminal free run. This is done in the SweepClosure
  6526     // destructor; so, do not remove this scope, else the
  6527     // end-of-sweep-census below will be off by a little bit.
  6529   gen->cmsSpace()->sweep_completed();
  6530   gen->cmsSpace()->endSweepFLCensus(sweep_count());
  6531   if (should_unload_classes()) {                // unloaded classes this cycle,
  6532     _concurrent_cycles_since_last_unload = 0;   // ... reset count
  6533   } else {                                      // did not unload classes,
  6534     _concurrent_cycles_since_last_unload++;     // ... increment count
  6538 // Reset CMS data structures (for now just the marking bit map)
  6539 // preparatory for the next cycle.
  6540 void CMSCollector::reset(bool asynch) {
  6541   GenCollectedHeap* gch = GenCollectedHeap::heap();
  6542   CMSAdaptiveSizePolicy* sp = size_policy();
  6543   AdaptiveSizePolicyOutput(sp, gch->total_collections());
  6544   if (asynch) {
  6545     CMSTokenSyncWithLocks ts(true, bitMapLock());
  6547     // If the state is not "Resetting", the foreground  thread
  6548     // has done a collection and the resetting.
  6549     if (_collectorState != Resetting) {
  6550       assert(_collectorState == Idling, "The state should only change"
  6551         " because the foreground collector has finished the collection");
  6552       return;
  6555     // Clear the mark bitmap (no grey objects to start with)
  6556     // for the next cycle.
  6557     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  6558     CMSPhaseAccounting cmspa(this, "reset", !PrintGCDetails);
  6560     HeapWord* curAddr = _markBitMap.startWord();
  6561     while (curAddr < _markBitMap.endWord()) {
  6562       size_t remaining  = pointer_delta(_markBitMap.endWord(), curAddr);
  6563       MemRegion chunk(curAddr, MIN2(CMSBitMapYieldQuantum, remaining));
  6564       _markBitMap.clear_large_range(chunk);
  6565       if (ConcurrentMarkSweepThread::should_yield() &&
  6566           !foregroundGCIsActive() &&
  6567           CMSYield) {
  6568         assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  6569                "CMS thread should hold CMS token");
  6570         assert_lock_strong(bitMapLock());
  6571         bitMapLock()->unlock();
  6572         ConcurrentMarkSweepThread::desynchronize(true);
  6573         ConcurrentMarkSweepThread::acknowledge_yield_request();
  6574         stopTimer();
  6575         if (PrintCMSStatistics != 0) {
  6576           incrementYields();
  6578         icms_wait();
  6580         // See the comment in coordinator_yield()
  6581         for (unsigned i = 0; i < CMSYieldSleepCount &&
  6582                          ConcurrentMarkSweepThread::should_yield() &&
  6583                          !CMSCollector::foregroundGCIsActive(); ++i) {
  6584           os::sleep(Thread::current(), 1, false);
  6585           ConcurrentMarkSweepThread::acknowledge_yield_request();
  6588         ConcurrentMarkSweepThread::synchronize(true);
  6589         bitMapLock()->lock_without_safepoint_check();
  6590         startTimer();
  6592       curAddr = chunk.end();
  6594     // A successful mostly concurrent collection has been done.
  6595     // Because only the full (i.e., concurrent mode failure) collections
  6596     // are being measured for gc overhead limits, clean the "near" flag
  6597     // and count.
  6598     sp->reset_gc_overhead_limit_count();
  6599     _collectorState = Idling;
  6600   } else {
  6601     // already have the lock
  6602     assert(_collectorState == Resetting, "just checking");
  6603     assert_lock_strong(bitMapLock());
  6604     _markBitMap.clear_all();
  6605     _collectorState = Idling;
  6608   // Stop incremental mode after a cycle completes, so that any future cycles
  6609   // are triggered by allocation.
  6610   stop_icms();
  6612   NOT_PRODUCT(
  6613     if (RotateCMSCollectionTypes) {
  6614       _cmsGen->rotate_debug_collection_type();
  6618   register_gc_end();
  6621 void CMSCollector::do_CMS_operation(CMS_op_type op, GCCause::Cause gc_cause) {
  6622   gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
  6623   TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  6624   GCTraceTime t(GCCauseString("GC", gc_cause), PrintGC, !PrintGCDetails, NULL);
  6625   TraceCollectorStats tcs(counters());
  6627   switch (op) {
  6628     case CMS_op_checkpointRootsInitial: {
  6629       SvcGCMarker sgcm(SvcGCMarker::OTHER);
  6630       checkpointRootsInitial(true);       // asynch
  6631       if (PrintGC) {
  6632         _cmsGen->printOccupancy("initial-mark");
  6634       break;
  6636     case CMS_op_checkpointRootsFinal: {
  6637       SvcGCMarker sgcm(SvcGCMarker::OTHER);
  6638       checkpointRootsFinal(true,    // asynch
  6639                            false,   // !clear_all_soft_refs
  6640                            false);  // !init_mark_was_synchronous
  6641       if (PrintGC) {
  6642         _cmsGen->printOccupancy("remark");
  6644       break;
  6646     default:
  6647       fatal("No such CMS_op");
  6651 #ifndef PRODUCT
  6652 size_t const CMSCollector::skip_header_HeapWords() {
  6653   return FreeChunk::header_size();
  6656 // Try and collect here conditions that should hold when
  6657 // CMS thread is exiting. The idea is that the foreground GC
  6658 // thread should not be blocked if it wants to terminate
  6659 // the CMS thread and yet continue to run the VM for a while
  6660 // after that.
  6661 void CMSCollector::verify_ok_to_terminate() const {
  6662   assert(Thread::current()->is_ConcurrentGC_thread(),
  6663          "should be called by CMS thread");
  6664   assert(!_foregroundGCShouldWait, "should be false");
  6665   // We could check here that all the various low-level locks
  6666   // are not held by the CMS thread, but that is overkill; see
  6667   // also CMSThread::verify_ok_to_terminate() where the CGC_lock
  6668   // is checked.
  6670 #endif
  6672 size_t CMSCollector::block_size_using_printezis_bits(HeapWord* addr) const {
  6673    assert(_markBitMap.isMarked(addr) && _markBitMap.isMarked(addr + 1),
  6674           "missing Printezis mark?");
  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;
  6683 // A variant of the above (block_size_using_printezis_bits()) except
  6684 // that we return 0 if the P-bits are not yet set.
  6685 size_t CMSCollector::block_size_if_printezis_bits(HeapWord* addr) const {
  6686   if (_markBitMap.isMarked(addr + 1)) {
  6687     assert(_markBitMap.isMarked(addr), "P-bit can be set only for marked objects");
  6688     HeapWord* nextOneAddr = _markBitMap.getNextMarkedWordAddress(addr + 2);
  6689     size_t size = pointer_delta(nextOneAddr + 1, addr);
  6690     assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
  6691            "alignment problem");
  6692     assert(size >= 3, "Necessary for Printezis marks to work");
  6693     return size;
  6695   return 0;
  6698 HeapWord* CMSCollector::next_card_start_after_block(HeapWord* addr) const {
  6699   size_t sz = 0;
  6700   oop p = (oop)addr;
  6701   if (p->klass_or_null() != NULL) {
  6702     sz = CompactibleFreeListSpace::adjustObjectSize(p->size());
  6703   } else {
  6704     sz = block_size_using_printezis_bits(addr);
  6706   assert(sz > 0, "size must be nonzero");
  6707   HeapWord* next_block = addr + sz;
  6708   HeapWord* next_card  = (HeapWord*)round_to((uintptr_t)next_block,
  6709                                              CardTableModRefBS::card_size);
  6710   assert(round_down((uintptr_t)addr,      CardTableModRefBS::card_size) <
  6711          round_down((uintptr_t)next_card, CardTableModRefBS::card_size),
  6712          "must be different cards");
  6713   return next_card;
  6717 // CMS Bit Map Wrapper /////////////////////////////////////////
  6719 // Construct a CMS bit map infrastructure, but don't create the
  6720 // bit vector itself. That is done by a separate call CMSBitMap::allocate()
  6721 // further below.
  6722 CMSBitMap::CMSBitMap(int shifter, int mutex_rank, const char* mutex_name):
  6723   _bm(),
  6724   _shifter(shifter),
  6725   _lock(mutex_rank >= 0 ? new Mutex(mutex_rank, mutex_name, true) : NULL)
  6727   _bmStartWord = 0;
  6728   _bmWordSize  = 0;
  6731 bool CMSBitMap::allocate(MemRegion mr) {
  6732   _bmStartWord = mr.start();
  6733   _bmWordSize  = mr.word_size();
  6734   ReservedSpace brs(ReservedSpace::allocation_align_size_up(
  6735                      (_bmWordSize >> (_shifter + LogBitsPerByte)) + 1));
  6736   if (!brs.is_reserved()) {
  6737     warning("CMS bit map allocation failure");
  6738     return false;
  6740   // For now we'll just commit all of the bit map up fromt.
  6741   // Later on we'll try to be more parsimonious with swap.
  6742   if (!_virtual_space.initialize(brs, brs.size())) {
  6743     warning("CMS bit map backing store failure");
  6744     return false;
  6746   assert(_virtual_space.committed_size() == brs.size(),
  6747          "didn't reserve backing store for all of CMS bit map?");
  6748   _bm.set_map((BitMap::bm_word_t*)_virtual_space.low());
  6749   assert(_virtual_space.committed_size() << (_shifter + LogBitsPerByte) >=
  6750          _bmWordSize, "inconsistency in bit map sizing");
  6751   _bm.set_size(_bmWordSize >> _shifter);
  6753   // bm.clear(); // can we rely on getting zero'd memory? verify below
  6754   assert(isAllClear(),
  6755          "Expected zero'd memory from ReservedSpace constructor");
  6756   assert(_bm.size() == heapWordDiffToOffsetDiff(sizeInWords()),
  6757          "consistency check");
  6758   return true;
  6761 void CMSBitMap::dirty_range_iterate_clear(MemRegion mr, MemRegionClosure* cl) {
  6762   HeapWord *next_addr, *end_addr, *last_addr;
  6763   assert_locked();
  6764   assert(covers(mr), "out-of-range error");
  6765   // XXX assert that start and end are appropriately aligned
  6766   for (next_addr = mr.start(), end_addr = mr.end();
  6767        next_addr < end_addr; next_addr = last_addr) {
  6768     MemRegion dirty_region = getAndClearMarkedRegion(next_addr, end_addr);
  6769     last_addr = dirty_region.end();
  6770     if (!dirty_region.is_empty()) {
  6771       cl->do_MemRegion(dirty_region);
  6772     } else {
  6773       assert(last_addr == end_addr, "program logic");
  6774       return;
  6779 void CMSBitMap::print_on_error(outputStream* st, const char* prefix) const {
  6780   _bm.print_on_error(st, prefix);
  6783 #ifndef PRODUCT
  6784 void CMSBitMap::assert_locked() const {
  6785   CMSLockVerifier::assert_locked(lock());
  6788 bool CMSBitMap::covers(MemRegion mr) const {
  6789   // assert(_bm.map() == _virtual_space.low(), "map inconsistency");
  6790   assert((size_t)_bm.size() == (_bmWordSize >> _shifter),
  6791          "size inconsistency");
  6792   return (mr.start() >= _bmStartWord) &&
  6793          (mr.end()   <= endWord());
  6796 bool CMSBitMap::covers(HeapWord* start, size_t size) const {
  6797     return (start >= _bmStartWord && (start + size) <= endWord());
  6800 void CMSBitMap::verifyNoOneBitsInRange(HeapWord* left, HeapWord* right) {
  6801   // verify that there are no 1 bits in the interval [left, right)
  6802   FalseBitMapClosure falseBitMapClosure;
  6803   iterate(&falseBitMapClosure, left, right);
  6806 void CMSBitMap::region_invariant(MemRegion mr)
  6808   assert_locked();
  6809   // mr = mr.intersection(MemRegion(_bmStartWord, _bmWordSize));
  6810   assert(!mr.is_empty(), "unexpected empty region");
  6811   assert(covers(mr), "mr should be covered by bit map");
  6812   // convert address range into offset range
  6813   size_t start_ofs = heapWordToOffset(mr.start());
  6814   // Make sure that end() is appropriately aligned
  6815   assert(mr.end() == (HeapWord*)round_to((intptr_t)mr.end(),
  6816                         (1 << (_shifter+LogHeapWordSize))),
  6817          "Misaligned mr.end()");
  6818   size_t end_ofs   = heapWordToOffset(mr.end());
  6819   assert(end_ofs > start_ofs, "Should mark at least one bit");
  6822 #endif
  6824 bool CMSMarkStack::allocate(size_t size) {
  6825   // allocate a stack of the requisite depth
  6826   ReservedSpace rs(ReservedSpace::allocation_align_size_up(
  6827                    size * sizeof(oop)));
  6828   if (!rs.is_reserved()) {
  6829     warning("CMSMarkStack allocation failure");
  6830     return false;
  6832   if (!_virtual_space.initialize(rs, rs.size())) {
  6833     warning("CMSMarkStack backing store failure");
  6834     return false;
  6836   assert(_virtual_space.committed_size() == rs.size(),
  6837          "didn't reserve backing store for all of CMS stack?");
  6838   _base = (oop*)(_virtual_space.low());
  6839   _index = 0;
  6840   _capacity = size;
  6841   NOT_PRODUCT(_max_depth = 0);
  6842   return true;
  6845 // XXX FIX ME !!! In the MT case we come in here holding a
  6846 // leaf lock. For printing we need to take a further lock
  6847 // which has lower rank. We need to recallibrate the two
  6848 // lock-ranks involved in order to be able to rpint the
  6849 // messages below. (Or defer the printing to the caller.
  6850 // For now we take the expedient path of just disabling the
  6851 // messages for the problematic case.)
  6852 void CMSMarkStack::expand() {
  6853   assert(_capacity <= MarkStackSizeMax, "stack bigger than permitted");
  6854   if (_capacity == MarkStackSizeMax) {
  6855     if (_hit_limit++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) {
  6856       // We print a warning message only once per CMS cycle.
  6857       gclog_or_tty->print_cr(" (benign) Hit CMSMarkStack max size limit");
  6859     return;
  6861   // Double capacity if possible
  6862   size_t new_capacity = MIN2(_capacity*2, MarkStackSizeMax);
  6863   // Do not give up existing stack until we have managed to
  6864   // get the double capacity that we desired.
  6865   ReservedSpace rs(ReservedSpace::allocation_align_size_up(
  6866                    new_capacity * sizeof(oop)));
  6867   if (rs.is_reserved()) {
  6868     // Release the backing store associated with old stack
  6869     _virtual_space.release();
  6870     // Reinitialize virtual space for new stack
  6871     if (!_virtual_space.initialize(rs, rs.size())) {
  6872       fatal("Not enough swap for expanded marking stack");
  6874     _base = (oop*)(_virtual_space.low());
  6875     _index = 0;
  6876     _capacity = new_capacity;
  6877   } else if (_failed_double++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) {
  6878     // Failed to double capacity, continue;
  6879     // we print a detail message only once per CMS cycle.
  6880     gclog_or_tty->print(" (benign) Failed to expand marking stack from "SIZE_FORMAT"K to "
  6881             SIZE_FORMAT"K",
  6882             _capacity / K, new_capacity / K);
  6887 // Closures
  6888 // XXX: there seems to be a lot of code  duplication here;
  6889 // should refactor and consolidate common code.
  6891 // This closure is used to mark refs into the CMS generation in
  6892 // the CMS bit map. Called at the first checkpoint. This closure
  6893 // assumes that we do not need to re-mark dirty cards; if the CMS
  6894 // generation on which this is used is not an oldest
  6895 // generation then this will lose younger_gen cards!
  6897 MarkRefsIntoClosure::MarkRefsIntoClosure(
  6898   MemRegion span, CMSBitMap* bitMap):
  6899     _span(span),
  6900     _bitMap(bitMap)
  6902     assert(_ref_processor == NULL, "deliberately left NULL");
  6903     assert(_bitMap->covers(_span), "_bitMap/_span mismatch");
  6906 void MarkRefsIntoClosure::do_oop(oop obj) {
  6907   // if p points into _span, then mark corresponding bit in _markBitMap
  6908   assert(obj->is_oop(), "expected an oop");
  6909   HeapWord* addr = (HeapWord*)obj;
  6910   if (_span.contains(addr)) {
  6911     // this should be made more efficient
  6912     _bitMap->mark(addr);
  6916 void MarkRefsIntoClosure::do_oop(oop* p)       { MarkRefsIntoClosure::do_oop_work(p); }
  6917 void MarkRefsIntoClosure::do_oop(narrowOop* p) { MarkRefsIntoClosure::do_oop_work(p); }
  6919 Par_MarkRefsIntoClosure::Par_MarkRefsIntoClosure(
  6920   MemRegion span, CMSBitMap* bitMap):
  6921     _span(span),
  6922     _bitMap(bitMap)
  6924     assert(_ref_processor == NULL, "deliberately left NULL");
  6925     assert(_bitMap->covers(_span), "_bitMap/_span mismatch");
  6928 void Par_MarkRefsIntoClosure::do_oop(oop obj) {
  6929   // if p points into _span, then mark corresponding bit in _markBitMap
  6930   assert(obj->is_oop(), "expected an oop");
  6931   HeapWord* addr = (HeapWord*)obj;
  6932   if (_span.contains(addr)) {
  6933     // this should be made more efficient
  6934     _bitMap->par_mark(addr);
  6938 void Par_MarkRefsIntoClosure::do_oop(oop* p)       { Par_MarkRefsIntoClosure::do_oop_work(p); }
  6939 void Par_MarkRefsIntoClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoClosure::do_oop_work(p); }
  6941 // A variant of the above, used for CMS marking verification.
  6942 MarkRefsIntoVerifyClosure::MarkRefsIntoVerifyClosure(
  6943   MemRegion span, CMSBitMap* verification_bm, CMSBitMap* cms_bm):
  6944     _span(span),
  6945     _verification_bm(verification_bm),
  6946     _cms_bm(cms_bm)
  6948     assert(_ref_processor == NULL, "deliberately left NULL");
  6949     assert(_verification_bm->covers(_span), "_verification_bm/_span mismatch");
  6952 void MarkRefsIntoVerifyClosure::do_oop(oop obj) {
  6953   // if p points into _span, then mark corresponding bit in _markBitMap
  6954   assert(obj->is_oop(), "expected an oop");
  6955   HeapWord* addr = (HeapWord*)obj;
  6956   if (_span.contains(addr)) {
  6957     _verification_bm->mark(addr);
  6958     if (!_cms_bm->isMarked(addr)) {
  6959       oop(addr)->print();
  6960       gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)", addr);
  6961       fatal("... aborting");
  6966 void MarkRefsIntoVerifyClosure::do_oop(oop* p)       { MarkRefsIntoVerifyClosure::do_oop_work(p); }
  6967 void MarkRefsIntoVerifyClosure::do_oop(narrowOop* p) { MarkRefsIntoVerifyClosure::do_oop_work(p); }
  6969 //////////////////////////////////////////////////
  6970 // MarkRefsIntoAndScanClosure
  6971 //////////////////////////////////////////////////
  6973 MarkRefsIntoAndScanClosure::MarkRefsIntoAndScanClosure(MemRegion span,
  6974                                                        ReferenceProcessor* rp,
  6975                                                        CMSBitMap* bit_map,
  6976                                                        CMSBitMap* mod_union_table,
  6977                                                        CMSMarkStack*  mark_stack,
  6978                                                        CMSCollector* collector,
  6979                                                        bool should_yield,
  6980                                                        bool concurrent_precleaning):
  6981   _collector(collector),
  6982   _span(span),
  6983   _bit_map(bit_map),
  6984   _mark_stack(mark_stack),
  6985   _pushAndMarkClosure(collector, span, rp, bit_map, mod_union_table,
  6986                       mark_stack, concurrent_precleaning),
  6987   _yield(should_yield),
  6988   _concurrent_precleaning(concurrent_precleaning),
  6989   _freelistLock(NULL)
  6991   _ref_processor = rp;
  6992   assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL");
  6995 // This closure is used to mark refs into the CMS generation at the
  6996 // second (final) checkpoint, and to scan and transitively follow
  6997 // the unmarked oops. It is also used during the concurrent precleaning
  6998 // phase while scanning objects on dirty cards in the CMS generation.
  6999 // The marks are made in the marking bit map and the marking stack is
  7000 // used for keeping the (newly) grey objects during the scan.
  7001 // The parallel version (Par_...) appears further below.
  7002 void MarkRefsIntoAndScanClosure::do_oop(oop obj) {
  7003   if (obj != NULL) {
  7004     assert(obj->is_oop(), "expected an oop");
  7005     HeapWord* addr = (HeapWord*)obj;
  7006     assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)");
  7007     assert(_collector->overflow_list_is_empty(),
  7008            "overflow list should be empty");
  7009     if (_span.contains(addr) &&
  7010         !_bit_map->isMarked(addr)) {
  7011       // mark bit map (object is now grey)
  7012       _bit_map->mark(addr);
  7013       // push on marking stack (stack should be empty), and drain the
  7014       // stack by applying this closure to the oops in the oops popped
  7015       // from the stack (i.e. blacken the grey objects)
  7016       bool res = _mark_stack->push(obj);
  7017       assert(res, "Should have space to push on empty stack");
  7018       do {
  7019         oop new_oop = _mark_stack->pop();
  7020         assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop");
  7021         assert(_bit_map->isMarked((HeapWord*)new_oop),
  7022                "only grey objects on this stack");
  7023         // iterate over the oops in this oop, marking and pushing
  7024         // the ones in CMS heap (i.e. in _span).
  7025         new_oop->oop_iterate(&_pushAndMarkClosure);
  7026         // check if it's time to yield
  7027         do_yield_check();
  7028       } while (!_mark_stack->isEmpty() ||
  7029                (!_concurrent_precleaning && take_from_overflow_list()));
  7030         // if marking stack is empty, and we are not doing this
  7031         // during precleaning, then check the overflow list
  7033     assert(_mark_stack->isEmpty(), "post-condition (eager drainage)");
  7034     assert(_collector->overflow_list_is_empty(),
  7035            "overflow list was drained above");
  7036     // We could restore evacuated mark words, if any, used for
  7037     // overflow list links here because the overflow list is
  7038     // provably empty here. That would reduce the maximum
  7039     // size requirements for preserved_{oop,mark}_stack.
  7040     // But we'll just postpone it until we are all done
  7041     // so we can just stream through.
  7042     if (!_concurrent_precleaning && CMSOverflowEarlyRestoration) {
  7043       _collector->restore_preserved_marks_if_any();
  7044       assert(_collector->no_preserved_marks(), "No preserved marks");
  7046     assert(!CMSOverflowEarlyRestoration || _collector->no_preserved_marks(),
  7047            "All preserved marks should have been restored above");
  7051 void MarkRefsIntoAndScanClosure::do_oop(oop* p)       { MarkRefsIntoAndScanClosure::do_oop_work(p); }
  7052 void MarkRefsIntoAndScanClosure::do_oop(narrowOop* p) { MarkRefsIntoAndScanClosure::do_oop_work(p); }
  7054 void MarkRefsIntoAndScanClosure::do_yield_work() {
  7055   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  7056          "CMS thread should hold CMS token");
  7057   assert_lock_strong(_freelistLock);
  7058   assert_lock_strong(_bit_map->lock());
  7059   // relinquish the free_list_lock and bitMaplock()
  7060   _bit_map->lock()->unlock();
  7061   _freelistLock->unlock();
  7062   ConcurrentMarkSweepThread::desynchronize(true);
  7063   ConcurrentMarkSweepThread::acknowledge_yield_request();
  7064   _collector->stopTimer();
  7065   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  7066   if (PrintCMSStatistics != 0) {
  7067     _collector->incrementYields();
  7069   _collector->icms_wait();
  7071   // See the comment in coordinator_yield()
  7072   for (unsigned i = 0;
  7073        i < CMSYieldSleepCount &&
  7074        ConcurrentMarkSweepThread::should_yield() &&
  7075        !CMSCollector::foregroundGCIsActive();
  7076        ++i) {
  7077     os::sleep(Thread::current(), 1, false);
  7078     ConcurrentMarkSweepThread::acknowledge_yield_request();
  7081   ConcurrentMarkSweepThread::synchronize(true);
  7082   _freelistLock->lock_without_safepoint_check();
  7083   _bit_map->lock()->lock_without_safepoint_check();
  7084   _collector->startTimer();
  7087 ///////////////////////////////////////////////////////////
  7088 // Par_MarkRefsIntoAndScanClosure: a parallel version of
  7089 //                                 MarkRefsIntoAndScanClosure
  7090 ///////////////////////////////////////////////////////////
  7091 Par_MarkRefsIntoAndScanClosure::Par_MarkRefsIntoAndScanClosure(
  7092   CMSCollector* collector, MemRegion span, ReferenceProcessor* rp,
  7093   CMSBitMap* bit_map, OopTaskQueue* work_queue):
  7094   _span(span),
  7095   _bit_map(bit_map),
  7096   _work_queue(work_queue),
  7097   _low_water_mark(MIN2((uint)(work_queue->max_elems()/4),
  7098                        (uint)(CMSWorkQueueDrainThreshold * ParallelGCThreads))),
  7099   _par_pushAndMarkClosure(collector, span, rp, bit_map, work_queue)
  7101   _ref_processor = rp;
  7102   assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL");
  7105 // This closure is used to mark refs into the CMS generation at the
  7106 // second (final) checkpoint, and to scan and transitively follow
  7107 // the unmarked oops. The marks are made in the marking bit map and
  7108 // the work_queue is used for keeping the (newly) grey objects during
  7109 // the scan phase whence they are also available for stealing by parallel
  7110 // threads. Since the marking bit map is shared, updates are
  7111 // synchronized (via CAS).
  7112 void Par_MarkRefsIntoAndScanClosure::do_oop(oop obj) {
  7113   if (obj != NULL) {
  7114     // Ignore mark word because this could be an already marked oop
  7115     // that may be chained at the end of the overflow list.
  7116     assert(obj->is_oop(true), "expected an oop");
  7117     HeapWord* addr = (HeapWord*)obj;
  7118     if (_span.contains(addr) &&
  7119         !_bit_map->isMarked(addr)) {
  7120       // mark bit map (object will become grey):
  7121       // It is possible for several threads to be
  7122       // trying to "claim" this object concurrently;
  7123       // the unique thread that succeeds in marking the
  7124       // object first will do the subsequent push on
  7125       // to the work queue (or overflow list).
  7126       if (_bit_map->par_mark(addr)) {
  7127         // push on work_queue (which may not be empty), and trim the
  7128         // queue to an appropriate length by applying this closure to
  7129         // the oops in the oops popped from the stack (i.e. blacken the
  7130         // grey objects)
  7131         bool res = _work_queue->push(obj);
  7132         assert(res, "Low water mark should be less than capacity?");
  7133         trim_queue(_low_water_mark);
  7134       } // Else, another thread claimed the object
  7139 void Par_MarkRefsIntoAndScanClosure::do_oop(oop* p)       { Par_MarkRefsIntoAndScanClosure::do_oop_work(p); }
  7140 void Par_MarkRefsIntoAndScanClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoAndScanClosure::do_oop_work(p); }
  7142 // This closure is used to rescan the marked objects on the dirty cards
  7143 // in the mod union table and the card table proper.
  7144 size_t ScanMarkedObjectsAgainCarefullyClosure::do_object_careful_m(
  7145   oop p, MemRegion mr) {
  7147   size_t size = 0;
  7148   HeapWord* addr = (HeapWord*)p;
  7149   DEBUG_ONLY(_collector->verify_work_stacks_empty();)
  7150   assert(_span.contains(addr), "we are scanning the CMS generation");
  7151   // check if it's time to yield
  7152   if (do_yield_check()) {
  7153     // We yielded for some foreground stop-world work,
  7154     // and we have been asked to abort this ongoing preclean cycle.
  7155     return 0;
  7157   if (_bitMap->isMarked(addr)) {
  7158     // it's marked; is it potentially uninitialized?
  7159     if (p->klass_or_null() != NULL) {
  7160         // an initialized object; ignore mark word in verification below
  7161         // since we are running concurrent with mutators
  7162         assert(p->is_oop(true), "should be an oop");
  7163         if (p->is_objArray()) {
  7164           // objArrays are precisely marked; restrict scanning
  7165           // to dirty cards only.
  7166           size = CompactibleFreeListSpace::adjustObjectSize(
  7167                    p->oop_iterate(_scanningClosure, mr));
  7168         } else {
  7169           // A non-array may have been imprecisely marked; we need
  7170           // to scan object in its entirety.
  7171           size = CompactibleFreeListSpace::adjustObjectSize(
  7172                    p->oop_iterate(_scanningClosure));
  7174         #ifdef ASSERT
  7175           size_t direct_size =
  7176             CompactibleFreeListSpace::adjustObjectSize(p->size());
  7177           assert(size == direct_size, "Inconsistency in size");
  7178           assert(size >= 3, "Necessary for Printezis marks to work");
  7179           if (!_bitMap->isMarked(addr+1)) {
  7180             _bitMap->verifyNoOneBitsInRange(addr+2, addr+size);
  7181           } else {
  7182             _bitMap->verifyNoOneBitsInRange(addr+2, addr+size-1);
  7183             assert(_bitMap->isMarked(addr+size-1),
  7184                    "inconsistent Printezis mark");
  7186         #endif // ASSERT
  7187     } else {
  7188       // an unitialized object
  7189       assert(_bitMap->isMarked(addr+1), "missing Printezis mark?");
  7190       HeapWord* nextOneAddr = _bitMap->getNextMarkedWordAddress(addr + 2);
  7191       size = pointer_delta(nextOneAddr + 1, addr);
  7192       assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
  7193              "alignment problem");
  7194       // Note that pre-cleaning needn't redirty the card. OopDesc::set_klass()
  7195       // will dirty the card when the klass pointer is installed in the
  7196       // object (signalling the completion of initialization).
  7198   } else {
  7199     // Either a not yet marked object or an uninitialized object
  7200     if (p->klass_or_null() == NULL) {
  7201       // An uninitialized object, skip to the next card, since
  7202       // we may not be able to read its P-bits yet.
  7203       assert(size == 0, "Initial value");
  7204     } else {
  7205       // An object not (yet) reached by marking: we merely need to
  7206       // compute its size so as to go look at the next block.
  7207       assert(p->is_oop(true), "should be an oop");
  7208       size = CompactibleFreeListSpace::adjustObjectSize(p->size());
  7211   DEBUG_ONLY(_collector->verify_work_stacks_empty();)
  7212   return size;
  7215 void ScanMarkedObjectsAgainCarefullyClosure::do_yield_work() {
  7216   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  7217          "CMS thread should hold CMS token");
  7218   assert_lock_strong(_freelistLock);
  7219   assert_lock_strong(_bitMap->lock());
  7220   // relinquish the free_list_lock and bitMaplock()
  7221   _bitMap->lock()->unlock();
  7222   _freelistLock->unlock();
  7223   ConcurrentMarkSweepThread::desynchronize(true);
  7224   ConcurrentMarkSweepThread::acknowledge_yield_request();
  7225   _collector->stopTimer();
  7226   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  7227   if (PrintCMSStatistics != 0) {
  7228     _collector->incrementYields();
  7230   _collector->icms_wait();
  7232   // See the comment in coordinator_yield()
  7233   for (unsigned i = 0; i < CMSYieldSleepCount &&
  7234                    ConcurrentMarkSweepThread::should_yield() &&
  7235                    !CMSCollector::foregroundGCIsActive(); ++i) {
  7236     os::sleep(Thread::current(), 1, false);
  7237     ConcurrentMarkSweepThread::acknowledge_yield_request();
  7240   ConcurrentMarkSweepThread::synchronize(true);
  7241   _freelistLock->lock_without_safepoint_check();
  7242   _bitMap->lock()->lock_without_safepoint_check();
  7243   _collector->startTimer();
  7247 //////////////////////////////////////////////////////////////////
  7248 // SurvivorSpacePrecleanClosure
  7249 //////////////////////////////////////////////////////////////////
  7250 // This (single-threaded) closure is used to preclean the oops in
  7251 // the survivor spaces.
  7252 size_t SurvivorSpacePrecleanClosure::do_object_careful(oop p) {
  7254   HeapWord* addr = (HeapWord*)p;
  7255   DEBUG_ONLY(_collector->verify_work_stacks_empty();)
  7256   assert(!_span.contains(addr), "we are scanning the survivor spaces");
  7257   assert(p->klass_or_null() != NULL, "object should be initializd");
  7258   // an initialized object; ignore mark word in verification below
  7259   // since we are running concurrent with mutators
  7260   assert(p->is_oop(true), "should be an oop");
  7261   // Note that we do not yield while we iterate over
  7262   // the interior oops of p, pushing the relevant ones
  7263   // on our marking stack.
  7264   size_t size = p->oop_iterate(_scanning_closure);
  7265   do_yield_check();
  7266   // Observe that below, we do not abandon the preclean
  7267   // phase as soon as we should; rather we empty the
  7268   // marking stack before returning. This is to satisfy
  7269   // some existing assertions. In general, it may be a
  7270   // good idea to abort immediately and complete the marking
  7271   // from the grey objects at a later time.
  7272   while (!_mark_stack->isEmpty()) {
  7273     oop new_oop = _mark_stack->pop();
  7274     assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop");
  7275     assert(_bit_map->isMarked((HeapWord*)new_oop),
  7276            "only grey objects on this stack");
  7277     // iterate over the oops in this oop, marking and pushing
  7278     // the ones in CMS heap (i.e. in _span).
  7279     new_oop->oop_iterate(_scanning_closure);
  7280     // check if it's time to yield
  7281     do_yield_check();
  7283   unsigned int after_count =
  7284     GenCollectedHeap::heap()->total_collections();
  7285   bool abort = (_before_count != after_count) ||
  7286                _collector->should_abort_preclean();
  7287   return abort ? 0 : size;
  7290 void SurvivorSpacePrecleanClosure::do_yield_work() {
  7291   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  7292          "CMS thread should hold CMS token");
  7293   assert_lock_strong(_bit_map->lock());
  7294   // Relinquish the bit map lock
  7295   _bit_map->lock()->unlock();
  7296   ConcurrentMarkSweepThread::desynchronize(true);
  7297   ConcurrentMarkSweepThread::acknowledge_yield_request();
  7298   _collector->stopTimer();
  7299   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  7300   if (PrintCMSStatistics != 0) {
  7301     _collector->incrementYields();
  7303   _collector->icms_wait();
  7305   // See the comment in coordinator_yield()
  7306   for (unsigned i = 0; i < CMSYieldSleepCount &&
  7307                        ConcurrentMarkSweepThread::should_yield() &&
  7308                        !CMSCollector::foregroundGCIsActive(); ++i) {
  7309     os::sleep(Thread::current(), 1, false);
  7310     ConcurrentMarkSweepThread::acknowledge_yield_request();
  7313   ConcurrentMarkSweepThread::synchronize(true);
  7314   _bit_map->lock()->lock_without_safepoint_check();
  7315   _collector->startTimer();
  7318 // This closure is used to rescan the marked objects on the dirty cards
  7319 // in the mod union table and the card table proper. In the parallel
  7320 // case, although the bitMap is shared, we do a single read so the
  7321 // isMarked() query is "safe".
  7322 bool ScanMarkedObjectsAgainClosure::do_object_bm(oop p, MemRegion mr) {
  7323   // Ignore mark word because we are running concurrent with mutators
  7324   assert(p->is_oop_or_null(true), "expected an oop or null");
  7325   HeapWord* addr = (HeapWord*)p;
  7326   assert(_span.contains(addr), "we are scanning the CMS generation");
  7327   bool is_obj_array = false;
  7328   #ifdef ASSERT
  7329     if (!_parallel) {
  7330       assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)");
  7331       assert(_collector->overflow_list_is_empty(),
  7332              "overflow list should be empty");
  7335   #endif // ASSERT
  7336   if (_bit_map->isMarked(addr)) {
  7337     // Obj arrays are precisely marked, non-arrays are not;
  7338     // so we scan objArrays precisely and non-arrays in their
  7339     // entirety.
  7340     if (p->is_objArray()) {
  7341       is_obj_array = true;
  7342       if (_parallel) {
  7343         p->oop_iterate(_par_scan_closure, mr);
  7344       } else {
  7345         p->oop_iterate(_scan_closure, mr);
  7347     } else {
  7348       if (_parallel) {
  7349         p->oop_iterate(_par_scan_closure);
  7350       } else {
  7351         p->oop_iterate(_scan_closure);
  7355   #ifdef ASSERT
  7356     if (!_parallel) {
  7357       assert(_mark_stack->isEmpty(), "post-condition (eager drainage)");
  7358       assert(_collector->overflow_list_is_empty(),
  7359              "overflow list should be empty");
  7362   #endif // ASSERT
  7363   return is_obj_array;
  7366 MarkFromRootsClosure::MarkFromRootsClosure(CMSCollector* collector,
  7367                         MemRegion span,
  7368                         CMSBitMap* bitMap, CMSMarkStack*  markStack,
  7369                         bool should_yield, bool verifying):
  7370   _collector(collector),
  7371   _span(span),
  7372   _bitMap(bitMap),
  7373   _mut(&collector->_modUnionTable),
  7374   _markStack(markStack),
  7375   _yield(should_yield),
  7376   _skipBits(0)
  7378   assert(_markStack->isEmpty(), "stack should be empty");
  7379   _finger = _bitMap->startWord();
  7380   _threshold = _finger;
  7381   assert(_collector->_restart_addr == NULL, "Sanity check");
  7382   assert(_span.contains(_finger), "Out of bounds _finger?");
  7383   DEBUG_ONLY(_verifying = verifying;)
  7386 void MarkFromRootsClosure::reset(HeapWord* addr) {
  7387   assert(_markStack->isEmpty(), "would cause duplicates on stack");
  7388   assert(_span.contains(addr), "Out of bounds _finger?");
  7389   _finger = addr;
  7390   _threshold = (HeapWord*)round_to(
  7391                  (intptr_t)_finger, CardTableModRefBS::card_size);
  7394 // Should revisit to see if this should be restructured for
  7395 // greater efficiency.
  7396 bool MarkFromRootsClosure::do_bit(size_t offset) {
  7397   if (_skipBits > 0) {
  7398     _skipBits--;
  7399     return true;
  7401   // convert offset into a HeapWord*
  7402   HeapWord* addr = _bitMap->startWord() + offset;
  7403   assert(_bitMap->endWord() && addr < _bitMap->endWord(),
  7404          "address out of range");
  7405   assert(_bitMap->isMarked(addr), "tautology");
  7406   if (_bitMap->isMarked(addr+1)) {
  7407     // this is an allocated but not yet initialized object
  7408     assert(_skipBits == 0, "tautology");
  7409     _skipBits = 2;  // skip next two marked bits ("Printezis-marks")
  7410     oop p = oop(addr);
  7411     if (p->klass_or_null() == NULL) {
  7412       DEBUG_ONLY(if (!_verifying) {)
  7413         // We re-dirty the cards on which this object lies and increase
  7414         // the _threshold so that we'll come back to scan this object
  7415         // during the preclean or remark phase. (CMSCleanOnEnter)
  7416         if (CMSCleanOnEnter) {
  7417           size_t sz = _collector->block_size_using_printezis_bits(addr);
  7418           HeapWord* end_card_addr   = (HeapWord*)round_to(
  7419                                          (intptr_t)(addr+sz), CardTableModRefBS::card_size);
  7420           MemRegion redirty_range = MemRegion(addr, end_card_addr);
  7421           assert(!redirty_range.is_empty(), "Arithmetical tautology");
  7422           // Bump _threshold to end_card_addr; note that
  7423           // _threshold cannot possibly exceed end_card_addr, anyhow.
  7424           // This prevents future clearing of the card as the scan proceeds
  7425           // to the right.
  7426           assert(_threshold <= end_card_addr,
  7427                  "Because we are just scanning into this object");
  7428           if (_threshold < end_card_addr) {
  7429             _threshold = end_card_addr;
  7431           if (p->klass_or_null() != NULL) {
  7432             // Redirty the range of cards...
  7433             _mut->mark_range(redirty_range);
  7434           } // ...else the setting of klass will dirty the card anyway.
  7436       DEBUG_ONLY(})
  7437       return true;
  7440   scanOopsInOop(addr);
  7441   return true;
  7444 // We take a break if we've been at this for a while,
  7445 // so as to avoid monopolizing the locks involved.
  7446 void MarkFromRootsClosure::do_yield_work() {
  7447   // First give up the locks, then yield, then re-lock
  7448   // We should probably use a constructor/destructor idiom to
  7449   // do this unlock/lock or modify the MutexUnlocker class to
  7450   // serve our purpose. XXX
  7451   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  7452          "CMS thread should hold CMS token");
  7453   assert_lock_strong(_bitMap->lock());
  7454   _bitMap->lock()->unlock();
  7455   ConcurrentMarkSweepThread::desynchronize(true);
  7456   ConcurrentMarkSweepThread::acknowledge_yield_request();
  7457   _collector->stopTimer();
  7458   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  7459   if (PrintCMSStatistics != 0) {
  7460     _collector->incrementYields();
  7462   _collector->icms_wait();
  7464   // See the comment in coordinator_yield()
  7465   for (unsigned i = 0; i < CMSYieldSleepCount &&
  7466                        ConcurrentMarkSweepThread::should_yield() &&
  7467                        !CMSCollector::foregroundGCIsActive(); ++i) {
  7468     os::sleep(Thread::current(), 1, false);
  7469     ConcurrentMarkSweepThread::acknowledge_yield_request();
  7472   ConcurrentMarkSweepThread::synchronize(true);
  7473   _bitMap->lock()->lock_without_safepoint_check();
  7474   _collector->startTimer();
  7477 void MarkFromRootsClosure::scanOopsInOop(HeapWord* ptr) {
  7478   assert(_bitMap->isMarked(ptr), "expected bit to be set");
  7479   assert(_markStack->isEmpty(),
  7480          "should drain stack to limit stack usage");
  7481   // convert ptr to an oop preparatory to scanning
  7482   oop obj = oop(ptr);
  7483   // Ignore mark word in verification below, since we
  7484   // may be running concurrent with mutators.
  7485   assert(obj->is_oop(true), "should be an oop");
  7486   assert(_finger <= ptr, "_finger runneth ahead");
  7487   // advance the finger to right end of this object
  7488   _finger = ptr + obj->size();
  7489   assert(_finger > ptr, "we just incremented it above");
  7490   // On large heaps, it may take us some time to get through
  7491   // the marking phase (especially if running iCMS). During
  7492   // this time it's possible that a lot of mutations have
  7493   // accumulated in the card table and the mod union table --
  7494   // these mutation records are redundant until we have
  7495   // actually traced into the corresponding card.
  7496   // Here, we check whether advancing the finger would make
  7497   // us cross into a new card, and if so clear corresponding
  7498   // cards in the MUT (preclean them in the card-table in the
  7499   // future).
  7501   DEBUG_ONLY(if (!_verifying) {)
  7502     // The clean-on-enter optimization is disabled by default,
  7503     // until we fix 6178663.
  7504     if (CMSCleanOnEnter && (_finger > _threshold)) {
  7505       // [_threshold, _finger) represents the interval
  7506       // of cards to be cleared  in MUT (or precleaned in card table).
  7507       // The set of cards to be cleared is all those that overlap
  7508       // with the interval [_threshold, _finger); note that
  7509       // _threshold is always kept card-aligned but _finger isn't
  7510       // always card-aligned.
  7511       HeapWord* old_threshold = _threshold;
  7512       assert(old_threshold == (HeapWord*)round_to(
  7513               (intptr_t)old_threshold, CardTableModRefBS::card_size),
  7514              "_threshold should always be card-aligned");
  7515       _threshold = (HeapWord*)round_to(
  7516                      (intptr_t)_finger, CardTableModRefBS::card_size);
  7517       MemRegion mr(old_threshold, _threshold);
  7518       assert(!mr.is_empty(), "Control point invariant");
  7519       assert(_span.contains(mr), "Should clear within span");
  7520       _mut->clear_range(mr);
  7522   DEBUG_ONLY(})
  7523   // Note: the finger doesn't advance while we drain
  7524   // the stack below.
  7525   PushOrMarkClosure pushOrMarkClosure(_collector,
  7526                                       _span, _bitMap, _markStack,
  7527                                       _finger, this);
  7528   bool res = _markStack->push(obj);
  7529   assert(res, "Empty non-zero size stack should have space for single push");
  7530   while (!_markStack->isEmpty()) {
  7531     oop new_oop = _markStack->pop();
  7532     // Skip verifying header mark word below because we are
  7533     // running concurrent with mutators.
  7534     assert(new_oop->is_oop(true), "Oops! expected to pop an oop");
  7535     // now scan this oop's oops
  7536     new_oop->oop_iterate(&pushOrMarkClosure);
  7537     do_yield_check();
  7539   assert(_markStack->isEmpty(), "tautology, emphasizing post-condition");
  7542 Par_MarkFromRootsClosure::Par_MarkFromRootsClosure(CMSConcMarkingTask* task,
  7543                        CMSCollector* collector, MemRegion span,
  7544                        CMSBitMap* bit_map,
  7545                        OopTaskQueue* work_queue,
  7546                        CMSMarkStack*  overflow_stack,
  7547                        bool should_yield):
  7548   _collector(collector),
  7549   _whole_span(collector->_span),
  7550   _span(span),
  7551   _bit_map(bit_map),
  7552   _mut(&collector->_modUnionTable),
  7553   _work_queue(work_queue),
  7554   _overflow_stack(overflow_stack),
  7555   _yield(should_yield),
  7556   _skip_bits(0),
  7557   _task(task)
  7559   assert(_work_queue->size() == 0, "work_queue should be empty");
  7560   _finger = span.start();
  7561   _threshold = _finger;     // XXX Defer clear-on-enter optimization for now
  7562   assert(_span.contains(_finger), "Out of bounds _finger?");
  7565 // Should revisit to see if this should be restructured for
  7566 // greater efficiency.
  7567 bool Par_MarkFromRootsClosure::do_bit(size_t offset) {
  7568   if (_skip_bits > 0) {
  7569     _skip_bits--;
  7570     return true;
  7572   // convert offset into a HeapWord*
  7573   HeapWord* addr = _bit_map->startWord() + offset;
  7574   assert(_bit_map->endWord() && addr < _bit_map->endWord(),
  7575          "address out of range");
  7576   assert(_bit_map->isMarked(addr), "tautology");
  7577   if (_bit_map->isMarked(addr+1)) {
  7578     // this is an allocated object that might not yet be initialized
  7579     assert(_skip_bits == 0, "tautology");
  7580     _skip_bits = 2;  // skip next two marked bits ("Printezis-marks")
  7581     oop p = oop(addr);
  7582     if (p->klass_or_null() == NULL) {
  7583       // in the case of Clean-on-Enter optimization, redirty card
  7584       // and avoid clearing card by increasing  the threshold.
  7585       return true;
  7588   scan_oops_in_oop(addr);
  7589   return true;
  7592 void Par_MarkFromRootsClosure::scan_oops_in_oop(HeapWord* ptr) {
  7593   assert(_bit_map->isMarked(ptr), "expected bit to be set");
  7594   // Should we assert that our work queue is empty or
  7595   // below some drain limit?
  7596   assert(_work_queue->size() == 0,
  7597          "should drain stack to limit stack usage");
  7598   // convert ptr to an oop preparatory to scanning
  7599   oop obj = oop(ptr);
  7600   // Ignore mark word in verification below, since we
  7601   // may be running concurrent with mutators.
  7602   assert(obj->is_oop(true), "should be an oop");
  7603   assert(_finger <= ptr, "_finger runneth ahead");
  7604   // advance the finger to right end of this object
  7605   _finger = ptr + obj->size();
  7606   assert(_finger > ptr, "we just incremented it above");
  7607   // On large heaps, it may take us some time to get through
  7608   // the marking phase (especially if running iCMS). During
  7609   // this time it's possible that a lot of mutations have
  7610   // accumulated in the card table and the mod union table --
  7611   // these mutation records are redundant until we have
  7612   // actually traced into the corresponding card.
  7613   // Here, we check whether advancing the finger would make
  7614   // us cross into a new card, and if so clear corresponding
  7615   // cards in the MUT (preclean them in the card-table in the
  7616   // future).
  7618   // The clean-on-enter optimization is disabled by default,
  7619   // until we fix 6178663.
  7620   if (CMSCleanOnEnter && (_finger > _threshold)) {
  7621     // [_threshold, _finger) represents the interval
  7622     // of cards to be cleared  in MUT (or precleaned in card table).
  7623     // The set of cards to be cleared is all those that overlap
  7624     // with the interval [_threshold, _finger); note that
  7625     // _threshold is always kept card-aligned but _finger isn't
  7626     // always card-aligned.
  7627     HeapWord* old_threshold = _threshold;
  7628     assert(old_threshold == (HeapWord*)round_to(
  7629             (intptr_t)old_threshold, CardTableModRefBS::card_size),
  7630            "_threshold should always be card-aligned");
  7631     _threshold = (HeapWord*)round_to(
  7632                    (intptr_t)_finger, CardTableModRefBS::card_size);
  7633     MemRegion mr(old_threshold, _threshold);
  7634     assert(!mr.is_empty(), "Control point invariant");
  7635     assert(_span.contains(mr), "Should clear within span"); // _whole_span ??
  7636     _mut->clear_range(mr);
  7639   // Note: the local finger doesn't advance while we drain
  7640   // the stack below, but the global finger sure can and will.
  7641   HeapWord** gfa = _task->global_finger_addr();
  7642   Par_PushOrMarkClosure pushOrMarkClosure(_collector,
  7643                                       _span, _bit_map,
  7644                                       _work_queue,
  7645                                       _overflow_stack,
  7646                                       _finger,
  7647                                       gfa, this);
  7648   bool res = _work_queue->push(obj);   // overflow could occur here
  7649   assert(res, "Will hold once we use workqueues");
  7650   while (true) {
  7651     oop new_oop;
  7652     if (!_work_queue->pop_local(new_oop)) {
  7653       // We emptied our work_queue; check if there's stuff that can
  7654       // be gotten from the overflow stack.
  7655       if (CMSConcMarkingTask::get_work_from_overflow_stack(
  7656             _overflow_stack, _work_queue)) {
  7657         do_yield_check();
  7658         continue;
  7659       } else {  // done
  7660         break;
  7663     // Skip verifying header mark word below because we are
  7664     // running concurrent with mutators.
  7665     assert(new_oop->is_oop(true), "Oops! expected to pop an oop");
  7666     // now scan this oop's oops
  7667     new_oop->oop_iterate(&pushOrMarkClosure);
  7668     do_yield_check();
  7670   assert(_work_queue->size() == 0, "tautology, emphasizing post-condition");
  7673 // Yield in response to a request from VM Thread or
  7674 // from mutators.
  7675 void Par_MarkFromRootsClosure::do_yield_work() {
  7676   assert(_task != NULL, "sanity");
  7677   _task->yield();
  7680 // A variant of the above used for verifying CMS marking work.
  7681 MarkFromRootsVerifyClosure::MarkFromRootsVerifyClosure(CMSCollector* collector,
  7682                         MemRegion span,
  7683                         CMSBitMap* verification_bm, CMSBitMap* cms_bm,
  7684                         CMSMarkStack*  mark_stack):
  7685   _collector(collector),
  7686   _span(span),
  7687   _verification_bm(verification_bm),
  7688   _cms_bm(cms_bm),
  7689   _mark_stack(mark_stack),
  7690   _pam_verify_closure(collector, span, verification_bm, cms_bm,
  7691                       mark_stack)
  7693   assert(_mark_stack->isEmpty(), "stack should be empty");
  7694   _finger = _verification_bm->startWord();
  7695   assert(_collector->_restart_addr == NULL, "Sanity check");
  7696   assert(_span.contains(_finger), "Out of bounds _finger?");
  7699 void MarkFromRootsVerifyClosure::reset(HeapWord* addr) {
  7700   assert(_mark_stack->isEmpty(), "would cause duplicates on stack");
  7701   assert(_span.contains(addr), "Out of bounds _finger?");
  7702   _finger = addr;
  7705 // Should revisit to see if this should be restructured for
  7706 // greater efficiency.
  7707 bool MarkFromRootsVerifyClosure::do_bit(size_t offset) {
  7708   // convert offset into a HeapWord*
  7709   HeapWord* addr = _verification_bm->startWord() + offset;
  7710   assert(_verification_bm->endWord() && addr < _verification_bm->endWord(),
  7711          "address out of range");
  7712   assert(_verification_bm->isMarked(addr), "tautology");
  7713   assert(_cms_bm->isMarked(addr), "tautology");
  7715   assert(_mark_stack->isEmpty(),
  7716          "should drain stack to limit stack usage");
  7717   // convert addr to an oop preparatory to scanning
  7718   oop obj = oop(addr);
  7719   assert(obj->is_oop(), "should be an oop");
  7720   assert(_finger <= addr, "_finger runneth ahead");
  7721   // advance the finger to right end of this object
  7722   _finger = addr + obj->size();
  7723   assert(_finger > addr, "we just incremented it above");
  7724   // Note: the finger doesn't advance while we drain
  7725   // the stack below.
  7726   bool res = _mark_stack->push(obj);
  7727   assert(res, "Empty non-zero size stack should have space for single push");
  7728   while (!_mark_stack->isEmpty()) {
  7729     oop new_oop = _mark_stack->pop();
  7730     assert(new_oop->is_oop(), "Oops! expected to pop an oop");
  7731     // now scan this oop's oops
  7732     new_oop->oop_iterate(&_pam_verify_closure);
  7734   assert(_mark_stack->isEmpty(), "tautology, emphasizing post-condition");
  7735   return true;
  7738 PushAndMarkVerifyClosure::PushAndMarkVerifyClosure(
  7739   CMSCollector* collector, MemRegion span,
  7740   CMSBitMap* verification_bm, CMSBitMap* cms_bm,
  7741   CMSMarkStack*  mark_stack):
  7742   CMSOopClosure(collector->ref_processor()),
  7743   _collector(collector),
  7744   _span(span),
  7745   _verification_bm(verification_bm),
  7746   _cms_bm(cms_bm),
  7747   _mark_stack(mark_stack)
  7748 { }
  7750 void PushAndMarkVerifyClosure::do_oop(oop* p)       { PushAndMarkVerifyClosure::do_oop_work(p); }
  7751 void PushAndMarkVerifyClosure::do_oop(narrowOop* p) { PushAndMarkVerifyClosure::do_oop_work(p); }
  7753 // Upon stack overflow, we discard (part of) the stack,
  7754 // remembering the least address amongst those discarded
  7755 // in CMSCollector's _restart_address.
  7756 void PushAndMarkVerifyClosure::handle_stack_overflow(HeapWord* lost) {
  7757   // Remember the least grey address discarded
  7758   HeapWord* ra = (HeapWord*)_mark_stack->least_value(lost);
  7759   _collector->lower_restart_addr(ra);
  7760   _mark_stack->reset();  // discard stack contents
  7761   _mark_stack->expand(); // expand the stack if possible
  7764 void PushAndMarkVerifyClosure::do_oop(oop obj) {
  7765   assert(obj->is_oop_or_null(), "expected an oop or NULL");
  7766   HeapWord* addr = (HeapWord*)obj;
  7767   if (_span.contains(addr) && !_verification_bm->isMarked(addr)) {
  7768     // Oop lies in _span and isn't yet grey or black
  7769     _verification_bm->mark(addr);            // now grey
  7770     if (!_cms_bm->isMarked(addr)) {
  7771       oop(addr)->print();
  7772       gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)",
  7773                              addr);
  7774       fatal("... aborting");
  7777     if (!_mark_stack->push(obj)) { // stack overflow
  7778       if (PrintCMSStatistics != 0) {
  7779         gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
  7780                                SIZE_FORMAT, _mark_stack->capacity());
  7782       assert(_mark_stack->isFull(), "Else push should have succeeded");
  7783       handle_stack_overflow(addr);
  7785     // anything including and to the right of _finger
  7786     // will be scanned as we iterate over the remainder of the
  7787     // bit map
  7791 PushOrMarkClosure::PushOrMarkClosure(CMSCollector* collector,
  7792                      MemRegion span,
  7793                      CMSBitMap* bitMap, CMSMarkStack*  markStack,
  7794                      HeapWord* finger, MarkFromRootsClosure* parent) :
  7795   CMSOopClosure(collector->ref_processor()),
  7796   _collector(collector),
  7797   _span(span),
  7798   _bitMap(bitMap),
  7799   _markStack(markStack),
  7800   _finger(finger),
  7801   _parent(parent)
  7802 { }
  7804 Par_PushOrMarkClosure::Par_PushOrMarkClosure(CMSCollector* collector,
  7805                      MemRegion span,
  7806                      CMSBitMap* bit_map,
  7807                      OopTaskQueue* work_queue,
  7808                      CMSMarkStack*  overflow_stack,
  7809                      HeapWord* finger,
  7810                      HeapWord** global_finger_addr,
  7811                      Par_MarkFromRootsClosure* parent) :
  7812   CMSOopClosure(collector->ref_processor()),
  7813   _collector(collector),
  7814   _whole_span(collector->_span),
  7815   _span(span),
  7816   _bit_map(bit_map),
  7817   _work_queue(work_queue),
  7818   _overflow_stack(overflow_stack),
  7819   _finger(finger),
  7820   _global_finger_addr(global_finger_addr),
  7821   _parent(parent)
  7822 { }
  7824 // Assumes thread-safe access by callers, who are
  7825 // responsible for mutual exclusion.
  7826 void CMSCollector::lower_restart_addr(HeapWord* low) {
  7827   assert(_span.contains(low), "Out of bounds addr");
  7828   if (_restart_addr == NULL) {
  7829     _restart_addr = low;
  7830   } else {
  7831     _restart_addr = MIN2(_restart_addr, low);
  7835 // Upon stack overflow, we discard (part of) the stack,
  7836 // remembering the least address amongst those discarded
  7837 // in CMSCollector's _restart_address.
  7838 void PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) {
  7839   // Remember the least grey address discarded
  7840   HeapWord* ra = (HeapWord*)_markStack->least_value(lost);
  7841   _collector->lower_restart_addr(ra);
  7842   _markStack->reset();  // discard stack contents
  7843   _markStack->expand(); // expand the stack if possible
  7846 // Upon stack overflow, we discard (part of) the stack,
  7847 // remembering the least address amongst those discarded
  7848 // in CMSCollector's _restart_address.
  7849 void Par_PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) {
  7850   // We need to do this under a mutex to prevent other
  7851   // workers from interfering with the work done below.
  7852   MutexLockerEx ml(_overflow_stack->par_lock(),
  7853                    Mutex::_no_safepoint_check_flag);
  7854   // Remember the least grey address discarded
  7855   HeapWord* ra = (HeapWord*)_overflow_stack->least_value(lost);
  7856   _collector->lower_restart_addr(ra);
  7857   _overflow_stack->reset();  // discard stack contents
  7858   _overflow_stack->expand(); // expand the stack if possible
  7861 void CMKlassClosure::do_klass(Klass* k) {
  7862   assert(_oop_closure != NULL, "Not initialized?");
  7863   k->oops_do(_oop_closure);
  7866 void PushOrMarkClosure::do_oop(oop obj) {
  7867   // Ignore mark word because we are running concurrent with mutators.
  7868   assert(obj->is_oop_or_null(true), "expected an oop or NULL");
  7869   HeapWord* addr = (HeapWord*)obj;
  7870   if (_span.contains(addr) && !_bitMap->isMarked(addr)) {
  7871     // Oop lies in _span and isn't yet grey or black
  7872     _bitMap->mark(addr);            // now grey
  7873     if (addr < _finger) {
  7874       // the bit map iteration has already either passed, or
  7875       // sampled, this bit in the bit map; we'll need to
  7876       // use the marking stack to scan this oop's oops.
  7877       bool simulate_overflow = false;
  7878       NOT_PRODUCT(
  7879         if (CMSMarkStackOverflowALot &&
  7880             _collector->simulate_overflow()) {
  7881           // simulate a stack overflow
  7882           simulate_overflow = true;
  7885       if (simulate_overflow || !_markStack->push(obj)) { // stack overflow
  7886         if (PrintCMSStatistics != 0) {
  7887           gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
  7888                                  SIZE_FORMAT, _markStack->capacity());
  7890         assert(simulate_overflow || _markStack->isFull(), "Else push should have succeeded");
  7891         handle_stack_overflow(addr);
  7894     // anything including and to the right of _finger
  7895     // will be scanned as we iterate over the remainder of the
  7896     // bit map
  7897     do_yield_check();
  7901 void PushOrMarkClosure::do_oop(oop* p)       { PushOrMarkClosure::do_oop_work(p); }
  7902 void PushOrMarkClosure::do_oop(narrowOop* p) { PushOrMarkClosure::do_oop_work(p); }
  7904 void Par_PushOrMarkClosure::do_oop(oop obj) {
  7905   // Ignore mark word because we are running concurrent with mutators.
  7906   assert(obj->is_oop_or_null(true), "expected an oop or NULL");
  7907   HeapWord* addr = (HeapWord*)obj;
  7908   if (_whole_span.contains(addr) && !_bit_map->isMarked(addr)) {
  7909     // Oop lies in _span and isn't yet grey or black
  7910     // We read the global_finger (volatile read) strictly after marking oop
  7911     bool res = _bit_map->par_mark(addr);    // now grey
  7912     volatile HeapWord** gfa = (volatile HeapWord**)_global_finger_addr;
  7913     // Should we push this marked oop on our stack?
  7914     // -- if someone else marked it, nothing to do
  7915     // -- if target oop is above global finger nothing to do
  7916     // -- if target oop is in chunk and above local finger
  7917     //      then nothing to do
  7918     // -- else push on work queue
  7919     if (   !res       // someone else marked it, they will deal with it
  7920         || (addr >= *gfa)  // will be scanned in a later task
  7921         || (_span.contains(addr) && addr >= _finger)) { // later in this chunk
  7922       return;
  7924     // the bit map iteration has already either passed, or
  7925     // sampled, this bit in the bit map; we'll need to
  7926     // use the marking stack to scan this oop's oops.
  7927     bool simulate_overflow = false;
  7928     NOT_PRODUCT(
  7929       if (CMSMarkStackOverflowALot &&
  7930           _collector->simulate_overflow()) {
  7931         // simulate a stack overflow
  7932         simulate_overflow = true;
  7935     if (simulate_overflow ||
  7936         !(_work_queue->push(obj) || _overflow_stack->par_push(obj))) {
  7937       // stack overflow
  7938       if (PrintCMSStatistics != 0) {
  7939         gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
  7940                                SIZE_FORMAT, _overflow_stack->capacity());
  7942       // We cannot assert that the overflow stack is full because
  7943       // it may have been emptied since.
  7944       assert(simulate_overflow ||
  7945              _work_queue->size() == _work_queue->max_elems(),
  7946             "Else push should have succeeded");
  7947       handle_stack_overflow(addr);
  7949     do_yield_check();
  7953 void Par_PushOrMarkClosure::do_oop(oop* p)       { Par_PushOrMarkClosure::do_oop_work(p); }
  7954 void Par_PushOrMarkClosure::do_oop(narrowOop* p) { Par_PushOrMarkClosure::do_oop_work(p); }
  7956 PushAndMarkClosure::PushAndMarkClosure(CMSCollector* collector,
  7957                                        MemRegion span,
  7958                                        ReferenceProcessor* rp,
  7959                                        CMSBitMap* bit_map,
  7960                                        CMSBitMap* mod_union_table,
  7961                                        CMSMarkStack*  mark_stack,
  7962                                        bool           concurrent_precleaning):
  7963   CMSOopClosure(rp),
  7964   _collector(collector),
  7965   _span(span),
  7966   _bit_map(bit_map),
  7967   _mod_union_table(mod_union_table),
  7968   _mark_stack(mark_stack),
  7969   _concurrent_precleaning(concurrent_precleaning)
  7971   assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL");
  7974 // Grey object rescan during pre-cleaning and second checkpoint phases --
  7975 // the non-parallel version (the parallel version appears further below.)
  7976 void PushAndMarkClosure::do_oop(oop obj) {
  7977   // Ignore mark word verification. If during concurrent precleaning,
  7978   // the object monitor may be locked. If during the checkpoint
  7979   // phases, the object may already have been reached by a  different
  7980   // path and may be at the end of the global overflow list (so
  7981   // the mark word may be NULL).
  7982   assert(obj->is_oop_or_null(true /* ignore mark word */),
  7983          "expected an oop or NULL");
  7984   HeapWord* addr = (HeapWord*)obj;
  7985   // Check if oop points into the CMS generation
  7986   // and is not marked
  7987   if (_span.contains(addr) && !_bit_map->isMarked(addr)) {
  7988     // a white object ...
  7989     _bit_map->mark(addr);         // ... now grey
  7990     // push on the marking stack (grey set)
  7991     bool simulate_overflow = false;
  7992     NOT_PRODUCT(
  7993       if (CMSMarkStackOverflowALot &&
  7994           _collector->simulate_overflow()) {
  7995         // simulate a stack overflow
  7996         simulate_overflow = true;
  7999     if (simulate_overflow || !_mark_stack->push(obj)) {
  8000       if (_concurrent_precleaning) {
  8001          // During precleaning we can just dirty the appropriate card(s)
  8002          // in the mod union table, thus ensuring that the object remains
  8003          // in the grey set  and continue. In the case of object arrays
  8004          // we need to dirty all of the cards that the object spans,
  8005          // since the rescan of object arrays will be limited to the
  8006          // dirty cards.
  8007          // Note that no one can be intefering with us in this action
  8008          // of dirtying the mod union table, so no locking or atomics
  8009          // are required.
  8010          if (obj->is_objArray()) {
  8011            size_t sz = obj->size();
  8012            HeapWord* end_card_addr = (HeapWord*)round_to(
  8013                                         (intptr_t)(addr+sz), CardTableModRefBS::card_size);
  8014            MemRegion redirty_range = MemRegion(addr, end_card_addr);
  8015            assert(!redirty_range.is_empty(), "Arithmetical tautology");
  8016            _mod_union_table->mark_range(redirty_range);
  8017          } else {
  8018            _mod_union_table->mark(addr);
  8020          _collector->_ser_pmc_preclean_ovflw++;
  8021       } else {
  8022          // During the remark phase, we need to remember this oop
  8023          // in the overflow list.
  8024          _collector->push_on_overflow_list(obj);
  8025          _collector->_ser_pmc_remark_ovflw++;
  8031 Par_PushAndMarkClosure::Par_PushAndMarkClosure(CMSCollector* collector,
  8032                                                MemRegion span,
  8033                                                ReferenceProcessor* rp,
  8034                                                CMSBitMap* bit_map,
  8035                                                OopTaskQueue* work_queue):
  8036   CMSOopClosure(rp),
  8037   _collector(collector),
  8038   _span(span),
  8039   _bit_map(bit_map),
  8040   _work_queue(work_queue)
  8042   assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL");
  8045 void PushAndMarkClosure::do_oop(oop* p)       { PushAndMarkClosure::do_oop_work(p); }
  8046 void PushAndMarkClosure::do_oop(narrowOop* p) { PushAndMarkClosure::do_oop_work(p); }
  8048 // Grey object rescan during second checkpoint phase --
  8049 // the parallel version.
  8050 void Par_PushAndMarkClosure::do_oop(oop obj) {
  8051   // In the assert below, we ignore the mark word because
  8052   // this oop may point to an already visited object that is
  8053   // on the overflow stack (in which case the mark word has
  8054   // been hijacked for chaining into the overflow stack --
  8055   // if this is the last object in the overflow stack then
  8056   // its mark word will be NULL). Because this object may
  8057   // have been subsequently popped off the global overflow
  8058   // stack, and the mark word possibly restored to the prototypical
  8059   // value, by the time we get to examined this failing assert in
  8060   // the debugger, is_oop_or_null(false) may subsequently start
  8061   // to hold.
  8062   assert(obj->is_oop_or_null(true),
  8063          "expected an oop or NULL");
  8064   HeapWord* addr = (HeapWord*)obj;
  8065   // Check if oop points into the CMS generation
  8066   // and is not marked
  8067   if (_span.contains(addr) && !_bit_map->isMarked(addr)) {
  8068     // a white object ...
  8069     // If we manage to "claim" the object, by being the
  8070     // first thread to mark it, then we push it on our
  8071     // marking stack
  8072     if (_bit_map->par_mark(addr)) {     // ... now grey
  8073       // push on work queue (grey set)
  8074       bool simulate_overflow = false;
  8075       NOT_PRODUCT(
  8076         if (CMSMarkStackOverflowALot &&
  8077             _collector->par_simulate_overflow()) {
  8078           // simulate a stack overflow
  8079           simulate_overflow = true;
  8082       if (simulate_overflow || !_work_queue->push(obj)) {
  8083         _collector->par_push_on_overflow_list(obj);
  8084         _collector->_par_pmc_remark_ovflw++; //  imprecise OK: no need to CAS
  8086     } // Else, some other thread got there first
  8090 void Par_PushAndMarkClosure::do_oop(oop* p)       { Par_PushAndMarkClosure::do_oop_work(p); }
  8091 void Par_PushAndMarkClosure::do_oop(narrowOop* p) { Par_PushAndMarkClosure::do_oop_work(p); }
  8093 void CMSPrecleanRefsYieldClosure::do_yield_work() {
  8094   Mutex* bml = _collector->bitMapLock();
  8095   assert_lock_strong(bml);
  8096   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  8097          "CMS thread should hold CMS token");
  8099   bml->unlock();
  8100   ConcurrentMarkSweepThread::desynchronize(true);
  8102   ConcurrentMarkSweepThread::acknowledge_yield_request();
  8104   _collector->stopTimer();
  8105   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  8106   if (PrintCMSStatistics != 0) {
  8107     _collector->incrementYields();
  8109   _collector->icms_wait();
  8111   // See the comment in coordinator_yield()
  8112   for (unsigned i = 0; i < CMSYieldSleepCount &&
  8113                        ConcurrentMarkSweepThread::should_yield() &&
  8114                        !CMSCollector::foregroundGCIsActive(); ++i) {
  8115     os::sleep(Thread::current(), 1, false);
  8116     ConcurrentMarkSweepThread::acknowledge_yield_request();
  8119   ConcurrentMarkSweepThread::synchronize(true);
  8120   bml->lock();
  8122   _collector->startTimer();
  8125 bool CMSPrecleanRefsYieldClosure::should_return() {
  8126   if (ConcurrentMarkSweepThread::should_yield()) {
  8127     do_yield_work();
  8129   return _collector->foregroundGCIsActive();
  8132 void MarkFromDirtyCardsClosure::do_MemRegion(MemRegion mr) {
  8133   assert(((size_t)mr.start())%CardTableModRefBS::card_size_in_words == 0,
  8134          "mr should be aligned to start at a card boundary");
  8135   // We'd like to assert:
  8136   // assert(mr.word_size()%CardTableModRefBS::card_size_in_words == 0,
  8137   //        "mr should be a range of cards");
  8138   // However, that would be too strong in one case -- the last
  8139   // partition ends at _unallocated_block which, in general, can be
  8140   // an arbitrary boundary, not necessarily card aligned.
  8141   if (PrintCMSStatistics != 0) {
  8142     _num_dirty_cards +=
  8143          mr.word_size()/CardTableModRefBS::card_size_in_words;
  8145   _space->object_iterate_mem(mr, &_scan_cl);
  8148 SweepClosure::SweepClosure(CMSCollector* collector,
  8149                            ConcurrentMarkSweepGeneration* g,
  8150                            CMSBitMap* bitMap, bool should_yield) :
  8151   _collector(collector),
  8152   _g(g),
  8153   _sp(g->cmsSpace()),
  8154   _limit(_sp->sweep_limit()),
  8155   _freelistLock(_sp->freelistLock()),
  8156   _bitMap(bitMap),
  8157   _yield(should_yield),
  8158   _inFreeRange(false),           // No free range at beginning of sweep
  8159   _freeRangeInFreeLists(false),  // No free range at beginning of sweep
  8160   _lastFreeRangeCoalesced(false),
  8161   _freeFinger(g->used_region().start())
  8163   NOT_PRODUCT(
  8164     _numObjectsFreed = 0;
  8165     _numWordsFreed   = 0;
  8166     _numObjectsLive = 0;
  8167     _numWordsLive = 0;
  8168     _numObjectsAlreadyFree = 0;
  8169     _numWordsAlreadyFree = 0;
  8170     _last_fc = NULL;
  8172     _sp->initializeIndexedFreeListArrayReturnedBytes();
  8173     _sp->dictionary()->initialize_dict_returned_bytes();
  8175   assert(_limit >= _sp->bottom() && _limit <= _sp->end(),
  8176          "sweep _limit out of bounds");
  8177   if (CMSTraceSweeper) {
  8178     gclog_or_tty->print_cr("\n====================\nStarting new sweep with limit " PTR_FORMAT,
  8179                         _limit);
  8183 void SweepClosure::print_on(outputStream* st) const {
  8184   tty->print_cr("_sp = [" PTR_FORMAT "," PTR_FORMAT ")",
  8185                 _sp->bottom(), _sp->end());
  8186   tty->print_cr("_limit = " PTR_FORMAT, _limit);
  8187   tty->print_cr("_freeFinger = " PTR_FORMAT, _freeFinger);
  8188   NOT_PRODUCT(tty->print_cr("_last_fc = " PTR_FORMAT, _last_fc);)
  8189   tty->print_cr("_inFreeRange = %d, _freeRangeInFreeLists = %d, _lastFreeRangeCoalesced = %d",
  8190                 _inFreeRange, _freeRangeInFreeLists, _lastFreeRangeCoalesced);
  8193 #ifndef PRODUCT
  8194 // Assertion checking only:  no useful work in product mode --
  8195 // however, if any of the flags below become product flags,
  8196 // you may need to review this code to see if it needs to be
  8197 // enabled in product mode.
  8198 SweepClosure::~SweepClosure() {
  8199   assert_lock_strong(_freelistLock);
  8200   assert(_limit >= _sp->bottom() && _limit <= _sp->end(),
  8201          "sweep _limit out of bounds");
  8202   if (inFreeRange()) {
  8203     warning("inFreeRange() should have been reset; dumping state of SweepClosure");
  8204     print();
  8205     ShouldNotReachHere();
  8207   if (Verbose && PrintGC) {
  8208     gclog_or_tty->print("Collected "SIZE_FORMAT" objects, " SIZE_FORMAT " bytes",
  8209                         _numObjectsFreed, _numWordsFreed*sizeof(HeapWord));
  8210     gclog_or_tty->print_cr("\nLive "SIZE_FORMAT" objects,  "
  8211                            SIZE_FORMAT" bytes  "
  8212       "Already free "SIZE_FORMAT" objects, "SIZE_FORMAT" bytes",
  8213       _numObjectsLive, _numWordsLive*sizeof(HeapWord),
  8214       _numObjectsAlreadyFree, _numWordsAlreadyFree*sizeof(HeapWord));
  8215     size_t totalBytes = (_numWordsFreed + _numWordsLive + _numWordsAlreadyFree)
  8216                         * sizeof(HeapWord);
  8217     gclog_or_tty->print_cr("Total sweep: "SIZE_FORMAT" bytes", totalBytes);
  8219     if (PrintCMSStatistics && CMSVerifyReturnedBytes) {
  8220       size_t indexListReturnedBytes = _sp->sumIndexedFreeListArrayReturnedBytes();
  8221       size_t dict_returned_bytes = _sp->dictionary()->sum_dict_returned_bytes();
  8222       size_t returned_bytes = indexListReturnedBytes + dict_returned_bytes;
  8223       gclog_or_tty->print("Returned "SIZE_FORMAT" bytes", returned_bytes);
  8224       gclog_or_tty->print("   Indexed List Returned "SIZE_FORMAT" bytes",
  8225         indexListReturnedBytes);
  8226       gclog_or_tty->print_cr("        Dictionary Returned "SIZE_FORMAT" bytes",
  8227         dict_returned_bytes);
  8230   if (CMSTraceSweeper) {
  8231     gclog_or_tty->print_cr("end of sweep with _limit = " PTR_FORMAT "\n================",
  8232                            _limit);
  8235 #endif  // PRODUCT
  8237 void SweepClosure::initialize_free_range(HeapWord* freeFinger,
  8238     bool freeRangeInFreeLists) {
  8239   if (CMSTraceSweeper) {
  8240     gclog_or_tty->print("---- Start free range at 0x%x with free block (%d)\n",
  8241                freeFinger, freeRangeInFreeLists);
  8243   assert(!inFreeRange(), "Trampling existing free range");
  8244   set_inFreeRange(true);
  8245   set_lastFreeRangeCoalesced(false);
  8247   set_freeFinger(freeFinger);
  8248   set_freeRangeInFreeLists(freeRangeInFreeLists);
  8249   if (CMSTestInFreeList) {
  8250     if (freeRangeInFreeLists) {
  8251       FreeChunk* fc = (FreeChunk*) freeFinger;
  8252       assert(fc->is_free(), "A chunk on the free list should be free.");
  8253       assert(fc->size() > 0, "Free range should have a size");
  8254       assert(_sp->verify_chunk_in_free_list(fc), "Chunk is not in free lists");
  8259 // Note that the sweeper runs concurrently with mutators. Thus,
  8260 // it is possible for direct allocation in this generation to happen
  8261 // in the middle of the sweep. Note that the sweeper also coalesces
  8262 // contiguous free blocks. Thus, unless the sweeper and the allocator
  8263 // synchronize appropriately freshly allocated blocks may get swept up.
  8264 // This is accomplished by the sweeper locking the free lists while
  8265 // it is sweeping. Thus blocks that are determined to be free are
  8266 // indeed free. There is however one additional complication:
  8267 // blocks that have been allocated since the final checkpoint and
  8268 // mark, will not have been marked and so would be treated as
  8269 // unreachable and swept up. To prevent this, the allocator marks
  8270 // the bit map when allocating during the sweep phase. This leads,
  8271 // however, to a further complication -- objects may have been allocated
  8272 // but not yet initialized -- in the sense that the header isn't yet
  8273 // installed. The sweeper can not then determine the size of the block
  8274 // in order to skip over it. To deal with this case, we use a technique
  8275 // (due to Printezis) to encode such uninitialized block sizes in the
  8276 // bit map. Since the bit map uses a bit per every HeapWord, but the
  8277 // CMS generation has a minimum object size of 3 HeapWords, it follows
  8278 // that "normal marks" won't be adjacent in the bit map (there will
  8279 // always be at least two 0 bits between successive 1 bits). We make use
  8280 // of these "unused" bits to represent uninitialized blocks -- the bit
  8281 // corresponding to the start of the uninitialized object and the next
  8282 // bit are both set. Finally, a 1 bit marks the end of the object that
  8283 // started with the two consecutive 1 bits to indicate its potentially
  8284 // uninitialized state.
  8286 size_t SweepClosure::do_blk_careful(HeapWord* addr) {
  8287   FreeChunk* fc = (FreeChunk*)addr;
  8288   size_t res;
  8290   // Check if we are done sweeping. Below we check "addr >= _limit" rather
  8291   // than "addr == _limit" because although _limit was a block boundary when
  8292   // we started the sweep, it may no longer be one because heap expansion
  8293   // may have caused us to coalesce the block ending at the address _limit
  8294   // with a newly expanded chunk (this happens when _limit was set to the
  8295   // previous _end of the space), so we may have stepped past _limit:
  8296   // see the following Zeno-like trail of CRs 6977970, 7008136, 7042740.
  8297   if (addr >= _limit) { // we have swept up to or past the limit: finish up
  8298     assert(_limit >= _sp->bottom() && _limit <= _sp->end(),
  8299            "sweep _limit out of bounds");
  8300     assert(addr < _sp->end(), "addr out of bounds");
  8301     // Flush any free range we might be holding as a single
  8302     // coalesced chunk to the appropriate free list.
  8303     if (inFreeRange()) {
  8304       assert(freeFinger() >= _sp->bottom() && freeFinger() < _limit,
  8305              err_msg("freeFinger() " PTR_FORMAT" is out-of-bounds", freeFinger()));
  8306       flush_cur_free_chunk(freeFinger(),
  8307                            pointer_delta(addr, freeFinger()));
  8308       if (CMSTraceSweeper) {
  8309         gclog_or_tty->print("Sweep: last chunk: ");
  8310         gclog_or_tty->print("put_free_blk 0x%x ("SIZE_FORMAT") "
  8311                    "[coalesced:"SIZE_FORMAT"]\n",
  8312                    freeFinger(), pointer_delta(addr, freeFinger()),
  8313                    lastFreeRangeCoalesced());
  8317     // help the iterator loop finish
  8318     return pointer_delta(_sp->end(), addr);
  8321   assert(addr < _limit, "sweep invariant");
  8322   // check if we should yield
  8323   do_yield_check(addr);
  8324   if (fc->is_free()) {
  8325     // Chunk that is already free
  8326     res = fc->size();
  8327     do_already_free_chunk(fc);
  8328     debug_only(_sp->verifyFreeLists());
  8329     // If we flush the chunk at hand in lookahead_and_flush()
  8330     // and it's coalesced with a preceding chunk, then the
  8331     // process of "mangling" the payload of the coalesced block
  8332     // will cause erasure of the size information from the
  8333     // (erstwhile) header of all the coalesced blocks but the
  8334     // first, so the first disjunct in the assert will not hold
  8335     // in that specific case (in which case the second disjunct
  8336     // will hold).
  8337     assert(res == fc->size() || ((HeapWord*)fc) + res >= _limit,
  8338            "Otherwise the size info doesn't change at this step");
  8339     NOT_PRODUCT(
  8340       _numObjectsAlreadyFree++;
  8341       _numWordsAlreadyFree += res;
  8343     NOT_PRODUCT(_last_fc = fc;)
  8344   } else if (!_bitMap->isMarked(addr)) {
  8345     // Chunk is fresh garbage
  8346     res = do_garbage_chunk(fc);
  8347     debug_only(_sp->verifyFreeLists());
  8348     NOT_PRODUCT(
  8349       _numObjectsFreed++;
  8350       _numWordsFreed += res;
  8352   } else {
  8353     // Chunk that is alive.
  8354     res = do_live_chunk(fc);
  8355     debug_only(_sp->verifyFreeLists());
  8356     NOT_PRODUCT(
  8357         _numObjectsLive++;
  8358         _numWordsLive += res;
  8361   return res;
  8364 // For the smart allocation, record following
  8365 //  split deaths - a free chunk is removed from its free list because
  8366 //      it is being split into two or more chunks.
  8367 //  split birth - a free chunk is being added to its free list because
  8368 //      a larger free chunk has been split and resulted in this free chunk.
  8369 //  coal death - a free chunk is being removed from its free list because
  8370 //      it is being coalesced into a large free chunk.
  8371 //  coal birth - a free chunk is being added to its free list because
  8372 //      it was created when two or more free chunks where coalesced into
  8373 //      this free chunk.
  8374 //
  8375 // These statistics are used to determine the desired number of free
  8376 // chunks of a given size.  The desired number is chosen to be relative
  8377 // to the end of a CMS sweep.  The desired number at the end of a sweep
  8378 // is the
  8379 //      count-at-end-of-previous-sweep (an amount that was enough)
  8380 //              - count-at-beginning-of-current-sweep  (the excess)
  8381 //              + split-births  (gains in this size during interval)
  8382 //              - split-deaths  (demands on this size during interval)
  8383 // where the interval is from the end of one sweep to the end of the
  8384 // next.
  8385 //
  8386 // When sweeping the sweeper maintains an accumulated chunk which is
  8387 // the chunk that is made up of chunks that have been coalesced.  That
  8388 // will be termed the left-hand chunk.  A new chunk of garbage that
  8389 // is being considered for coalescing will be referred to as the
  8390 // right-hand chunk.
  8391 //
  8392 // When making a decision on whether to coalesce a right-hand chunk with
  8393 // the current left-hand chunk, the current count vs. the desired count
  8394 // of the left-hand chunk is considered.  Also if the right-hand chunk
  8395 // is near the large chunk at the end of the heap (see
  8396 // ConcurrentMarkSweepGeneration::isNearLargestChunk()), then the
  8397 // left-hand chunk is coalesced.
  8398 //
  8399 // When making a decision about whether to split a chunk, the desired count
  8400 // vs. the current count of the candidate to be split is also considered.
  8401 // If the candidate is underpopulated (currently fewer chunks than desired)
  8402 // a chunk of an overpopulated (currently more chunks than desired) size may
  8403 // be chosen.  The "hint" associated with a free list, if non-null, points
  8404 // to a free list which may be overpopulated.
  8405 //
  8407 void SweepClosure::do_already_free_chunk(FreeChunk* fc) {
  8408   const size_t size = fc->size();
  8409   // Chunks that cannot be coalesced are not in the
  8410   // free lists.
  8411   if (CMSTestInFreeList && !fc->cantCoalesce()) {
  8412     assert(_sp->verify_chunk_in_free_list(fc),
  8413       "free chunk should be in free lists");
  8415   // a chunk that is already free, should not have been
  8416   // marked in the bit map
  8417   HeapWord* const addr = (HeapWord*) fc;
  8418   assert(!_bitMap->isMarked(addr), "free chunk should be unmarked");
  8419   // Verify that the bit map has no bits marked between
  8420   // addr and purported end of this block.
  8421   _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size);
  8423   // Some chunks cannot be coalesced under any circumstances.
  8424   // See the definition of cantCoalesce().
  8425   if (!fc->cantCoalesce()) {
  8426     // This chunk can potentially be coalesced.
  8427     if (_sp->adaptive_freelists()) {
  8428       // All the work is done in
  8429       do_post_free_or_garbage_chunk(fc, size);
  8430     } else {  // Not adaptive free lists
  8431       // this is a free chunk that can potentially be coalesced by the sweeper;
  8432       if (!inFreeRange()) {
  8433         // if the next chunk is a free block that can't be coalesced
  8434         // it doesn't make sense to remove this chunk from the free lists
  8435         FreeChunk* nextChunk = (FreeChunk*)(addr + size);
  8436         assert((HeapWord*)nextChunk <= _sp->end(), "Chunk size out of bounds?");
  8437         if ((HeapWord*)nextChunk < _sp->end() &&     // There is another free chunk to the right ...
  8438             nextChunk->is_free()               &&     // ... which is free...
  8439             nextChunk->cantCoalesce()) {             // ... but can't be coalesced
  8440           // nothing to do
  8441         } else {
  8442           // Potentially the start of a new free range:
  8443           // Don't eagerly remove it from the free lists.
  8444           // No need to remove it if it will just be put
  8445           // back again.  (Also from a pragmatic point of view
  8446           // if it is a free block in a region that is beyond
  8447           // any allocated blocks, an assertion will fail)
  8448           // Remember the start of a free run.
  8449           initialize_free_range(addr, true);
  8450           // end - can coalesce with next chunk
  8452       } else {
  8453         // the midst of a free range, we are coalescing
  8454         print_free_block_coalesced(fc);
  8455         if (CMSTraceSweeper) {
  8456           gclog_or_tty->print("  -- pick up free block 0x%x (%d)\n", fc, size);
  8458         // remove it from the free lists
  8459         _sp->removeFreeChunkFromFreeLists(fc);
  8460         set_lastFreeRangeCoalesced(true);
  8461         // If the chunk is being coalesced and the current free range is
  8462         // in the free lists, remove the current free range so that it
  8463         // will be returned to the free lists in its entirety - all
  8464         // the coalesced pieces included.
  8465         if (freeRangeInFreeLists()) {
  8466           FreeChunk* ffc = (FreeChunk*) freeFinger();
  8467           assert(ffc->size() == pointer_delta(addr, freeFinger()),
  8468             "Size of free range is inconsistent with chunk size.");
  8469           if (CMSTestInFreeList) {
  8470             assert(_sp->verify_chunk_in_free_list(ffc),
  8471               "free range is not in free lists");
  8473           _sp->removeFreeChunkFromFreeLists(ffc);
  8474           set_freeRangeInFreeLists(false);
  8478     // Note that if the chunk is not coalescable (the else arm
  8479     // below), we unconditionally flush, without needing to do
  8480     // a "lookahead," as we do below.
  8481     if (inFreeRange()) lookahead_and_flush(fc, size);
  8482   } else {
  8483     // Code path common to both original and adaptive free lists.
  8485     // cant coalesce with previous block; this should be treated
  8486     // as the end of a free run if any
  8487     if (inFreeRange()) {
  8488       // we kicked some butt; time to pick up the garbage
  8489       assert(freeFinger() < addr, "freeFinger points too high");
  8490       flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger()));
  8492     // else, nothing to do, just continue
  8496 size_t SweepClosure::do_garbage_chunk(FreeChunk* fc) {
  8497   // This is a chunk of garbage.  It is not in any free list.
  8498   // Add it to a free list or let it possibly be coalesced into
  8499   // a larger chunk.
  8500   HeapWord* const addr = (HeapWord*) fc;
  8501   const size_t size = CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size());
  8503   if (_sp->adaptive_freelists()) {
  8504     // Verify that the bit map has no bits marked between
  8505     // addr and purported end of just dead object.
  8506     _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size);
  8508     do_post_free_or_garbage_chunk(fc, size);
  8509   } else {
  8510     if (!inFreeRange()) {
  8511       // start of a new free range
  8512       assert(size > 0, "A free range should have a size");
  8513       initialize_free_range(addr, false);
  8514     } else {
  8515       // this will be swept up when we hit the end of the
  8516       // free range
  8517       if (CMSTraceSweeper) {
  8518         gclog_or_tty->print("  -- pick up garbage 0x%x (%d) \n", fc, size);
  8520       // If the chunk is being coalesced and the current free range is
  8521       // in the free lists, remove the current free range so that it
  8522       // will be returned to the free lists in its entirety - all
  8523       // the coalesced pieces included.
  8524       if (freeRangeInFreeLists()) {
  8525         FreeChunk* ffc = (FreeChunk*)freeFinger();
  8526         assert(ffc->size() == pointer_delta(addr, freeFinger()),
  8527           "Size of free range is inconsistent with chunk size.");
  8528         if (CMSTestInFreeList) {
  8529           assert(_sp->verify_chunk_in_free_list(ffc),
  8530             "free range is not in free lists");
  8532         _sp->removeFreeChunkFromFreeLists(ffc);
  8533         set_freeRangeInFreeLists(false);
  8535       set_lastFreeRangeCoalesced(true);
  8537     // this will be swept up when we hit the end of the free range
  8539     // Verify that the bit map has no bits marked between
  8540     // addr and purported end of just dead object.
  8541     _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size);
  8543   assert(_limit >= addr + size,
  8544          "A freshly garbage chunk can't possibly straddle over _limit");
  8545   if (inFreeRange()) lookahead_and_flush(fc, size);
  8546   return size;
  8549 size_t SweepClosure::do_live_chunk(FreeChunk* fc) {
  8550   HeapWord* addr = (HeapWord*) fc;
  8551   // The sweeper has just found a live object. Return any accumulated
  8552   // left hand chunk to the free lists.
  8553   if (inFreeRange()) {
  8554     assert(freeFinger() < addr, "freeFinger points too high");
  8555     flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger()));
  8558   // This object is live: we'd normally expect this to be
  8559   // an oop, and like to assert the following:
  8560   // assert(oop(addr)->is_oop(), "live block should be an oop");
  8561   // However, as we commented above, this may be an object whose
  8562   // header hasn't yet been initialized.
  8563   size_t size;
  8564   assert(_bitMap->isMarked(addr), "Tautology for this control point");
  8565   if (_bitMap->isMarked(addr + 1)) {
  8566     // Determine the size from the bit map, rather than trying to
  8567     // compute it from the object header.
  8568     HeapWord* nextOneAddr = _bitMap->getNextMarkedWordAddress(addr + 2);
  8569     size = pointer_delta(nextOneAddr + 1, addr);
  8570     assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
  8571            "alignment problem");
  8573 #ifdef ASSERT
  8574       if (oop(addr)->klass_or_null() != NULL) {
  8575         // Ignore mark word because we are running concurrent with mutators
  8576         assert(oop(addr)->is_oop(true), "live block should be an oop");
  8577         assert(size ==
  8578                CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size()),
  8579                "P-mark and computed size do not agree");
  8581 #endif
  8583   } else {
  8584     // This should be an initialized object that's alive.
  8585     assert(oop(addr)->klass_or_null() != NULL,
  8586            "Should be an initialized object");
  8587     // Ignore mark word because we are running concurrent with mutators
  8588     assert(oop(addr)->is_oop(true), "live block should be an oop");
  8589     // Verify that the bit map has no bits marked between
  8590     // addr and purported end of this block.
  8591     size = CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size());
  8592     assert(size >= 3, "Necessary for Printezis marks to work");
  8593     assert(!_bitMap->isMarked(addr+1), "Tautology for this control point");
  8594     DEBUG_ONLY(_bitMap->verifyNoOneBitsInRange(addr+2, addr+size);)
  8596   return size;
  8599 void SweepClosure::do_post_free_or_garbage_chunk(FreeChunk* fc,
  8600                                                  size_t chunkSize) {
  8601   // do_post_free_or_garbage_chunk() should only be called in the case
  8602   // of the adaptive free list allocator.
  8603   const bool fcInFreeLists = fc->is_free();
  8604   assert(_sp->adaptive_freelists(), "Should only be used in this case.");
  8605   assert((HeapWord*)fc <= _limit, "sweep invariant");
  8606   if (CMSTestInFreeList && fcInFreeLists) {
  8607     assert(_sp->verify_chunk_in_free_list(fc), "free chunk is not in free lists");
  8610   if (CMSTraceSweeper) {
  8611     gclog_or_tty->print_cr("  -- pick up another chunk at 0x%x (%d)", fc, chunkSize);
  8614   HeapWord* const fc_addr = (HeapWord*) fc;
  8616   bool coalesce;
  8617   const size_t left  = pointer_delta(fc_addr, freeFinger());
  8618   const size_t right = chunkSize;
  8619   switch (FLSCoalescePolicy) {
  8620     // numeric value forms a coalition aggressiveness metric
  8621     case 0:  { // never coalesce
  8622       coalesce = false;
  8623       break;
  8625     case 1: { // coalesce if left & right chunks on overpopulated lists
  8626       coalesce = _sp->coalOverPopulated(left) &&
  8627                  _sp->coalOverPopulated(right);
  8628       break;
  8630     case 2: { // coalesce if left chunk on overpopulated list (default)
  8631       coalesce = _sp->coalOverPopulated(left);
  8632       break;
  8634     case 3: { // coalesce if left OR right chunk on overpopulated list
  8635       coalesce = _sp->coalOverPopulated(left) ||
  8636                  _sp->coalOverPopulated(right);
  8637       break;
  8639     case 4: { // always coalesce
  8640       coalesce = true;
  8641       break;
  8643     default:
  8644      ShouldNotReachHere();
  8647   // Should the current free range be coalesced?
  8648   // If the chunk is in a free range and either we decided to coalesce above
  8649   // or the chunk is near the large block at the end of the heap
  8650   // (isNearLargestChunk() returns true), then coalesce this chunk.
  8651   const bool doCoalesce = inFreeRange()
  8652                           && (coalesce || _g->isNearLargestChunk(fc_addr));
  8653   if (doCoalesce) {
  8654     // Coalesce the current free range on the left with the new
  8655     // chunk on the right.  If either is on a free list,
  8656     // it must be removed from the list and stashed in the closure.
  8657     if (freeRangeInFreeLists()) {
  8658       FreeChunk* const ffc = (FreeChunk*)freeFinger();
  8659       assert(ffc->size() == pointer_delta(fc_addr, freeFinger()),
  8660         "Size of free range is inconsistent with chunk size.");
  8661       if (CMSTestInFreeList) {
  8662         assert(_sp->verify_chunk_in_free_list(ffc),
  8663           "Chunk is not in free lists");
  8665       _sp->coalDeath(ffc->size());
  8666       _sp->removeFreeChunkFromFreeLists(ffc);
  8667       set_freeRangeInFreeLists(false);
  8669     if (fcInFreeLists) {
  8670       _sp->coalDeath(chunkSize);
  8671       assert(fc->size() == chunkSize,
  8672         "The chunk has the wrong size or is not in the free lists");
  8673       _sp->removeFreeChunkFromFreeLists(fc);
  8675     set_lastFreeRangeCoalesced(true);
  8676     print_free_block_coalesced(fc);
  8677   } else {  // not in a free range and/or should not coalesce
  8678     // Return the current free range and start a new one.
  8679     if (inFreeRange()) {
  8680       // In a free range but cannot coalesce with the right hand chunk.
  8681       // Put the current free range into the free lists.
  8682       flush_cur_free_chunk(freeFinger(),
  8683                            pointer_delta(fc_addr, freeFinger()));
  8685     // Set up for new free range.  Pass along whether the right hand
  8686     // chunk is in the free lists.
  8687     initialize_free_range((HeapWord*)fc, fcInFreeLists);
  8691 // Lookahead flush:
  8692 // If we are tracking a free range, and this is the last chunk that
  8693 // we'll look at because its end crosses past _limit, we'll preemptively
  8694 // flush it along with any free range we may be holding on to. Note that
  8695 // this can be the case only for an already free or freshly garbage
  8696 // chunk. If this block is an object, it can never straddle
  8697 // over _limit. The "straddling" occurs when _limit is set at
  8698 // the previous end of the space when this cycle started, and
  8699 // a subsequent heap expansion caused the previously co-terminal
  8700 // free block to be coalesced with the newly expanded portion,
  8701 // thus rendering _limit a non-block-boundary making it dangerous
  8702 // for the sweeper to step over and examine.
  8703 void SweepClosure::lookahead_and_flush(FreeChunk* fc, size_t chunk_size) {
  8704   assert(inFreeRange(), "Should only be called if currently in a free range.");
  8705   HeapWord* const eob = ((HeapWord*)fc) + chunk_size;
  8706   assert(_sp->used_region().contains(eob - 1),
  8707          err_msg("eob = " PTR_FORMAT " eob-1 = " PTR_FORMAT " _limit = " PTR_FORMAT
  8708                  " out of bounds wrt _sp = [" PTR_FORMAT "," PTR_FORMAT ")"
  8709                  " when examining fc = " PTR_FORMAT "(" SIZE_FORMAT ")",
  8710                  eob, eob-1, _limit, _sp->bottom(), _sp->end(), fc, chunk_size));
  8711   if (eob >= _limit) {
  8712     assert(eob == _limit || fc->is_free(), "Only a free chunk should allow us to cross over the limit");
  8713     if (CMSTraceSweeper) {
  8714       gclog_or_tty->print_cr("_limit " PTR_FORMAT " reached or crossed by block "
  8715                              "[" PTR_FORMAT "," PTR_FORMAT ") in space "
  8716                              "[" PTR_FORMAT "," PTR_FORMAT ")",
  8717                              _limit, fc, eob, _sp->bottom(), _sp->end());
  8719     // Return the storage we are tracking back into the free lists.
  8720     if (CMSTraceSweeper) {
  8721       gclog_or_tty->print_cr("Flushing ... ");
  8723     assert(freeFinger() < eob, "Error");
  8724     flush_cur_free_chunk( freeFinger(), pointer_delta(eob, freeFinger()));
  8728 void SweepClosure::flush_cur_free_chunk(HeapWord* chunk, size_t size) {
  8729   assert(inFreeRange(), "Should only be called if currently in a free range.");
  8730   assert(size > 0,
  8731     "A zero sized chunk cannot be added to the free lists.");
  8732   if (!freeRangeInFreeLists()) {
  8733     if (CMSTestInFreeList) {
  8734       FreeChunk* fc = (FreeChunk*) chunk;
  8735       fc->set_size(size);
  8736       assert(!_sp->verify_chunk_in_free_list(fc),
  8737         "chunk should not be in free lists yet");
  8739     if (CMSTraceSweeper) {
  8740       gclog_or_tty->print_cr(" -- add free block 0x%x (%d) to free lists",
  8741                     chunk, size);
  8743     // A new free range is going to be starting.  The current
  8744     // free range has not been added to the free lists yet or
  8745     // was removed so add it back.
  8746     // If the current free range was coalesced, then the death
  8747     // of the free range was recorded.  Record a birth now.
  8748     if (lastFreeRangeCoalesced()) {
  8749       _sp->coalBirth(size);
  8751     _sp->addChunkAndRepairOffsetTable(chunk, size,
  8752             lastFreeRangeCoalesced());
  8753   } else if (CMSTraceSweeper) {
  8754     gclog_or_tty->print_cr("Already in free list: nothing to flush");
  8756   set_inFreeRange(false);
  8757   set_freeRangeInFreeLists(false);
  8760 // We take a break if we've been at this for a while,
  8761 // so as to avoid monopolizing the locks involved.
  8762 void SweepClosure::do_yield_work(HeapWord* addr) {
  8763   // Return current free chunk being used for coalescing (if any)
  8764   // to the appropriate freelist.  After yielding, the next
  8765   // free block encountered will start a coalescing range of
  8766   // free blocks.  If the next free block is adjacent to the
  8767   // chunk just flushed, they will need to wait for the next
  8768   // sweep to be coalesced.
  8769   if (inFreeRange()) {
  8770     flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger()));
  8773   // First give up the locks, then yield, then re-lock.
  8774   // We should probably use a constructor/destructor idiom to
  8775   // do this unlock/lock or modify the MutexUnlocker class to
  8776   // serve our purpose. XXX
  8777   assert_lock_strong(_bitMap->lock());
  8778   assert_lock_strong(_freelistLock);
  8779   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  8780          "CMS thread should hold CMS token");
  8781   _bitMap->lock()->unlock();
  8782   _freelistLock->unlock();
  8783   ConcurrentMarkSweepThread::desynchronize(true);
  8784   ConcurrentMarkSweepThread::acknowledge_yield_request();
  8785   _collector->stopTimer();
  8786   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  8787   if (PrintCMSStatistics != 0) {
  8788     _collector->incrementYields();
  8790   _collector->icms_wait();
  8792   // See the comment in coordinator_yield()
  8793   for (unsigned i = 0; i < CMSYieldSleepCount &&
  8794                        ConcurrentMarkSweepThread::should_yield() &&
  8795                        !CMSCollector::foregroundGCIsActive(); ++i) {
  8796     os::sleep(Thread::current(), 1, false);
  8797     ConcurrentMarkSweepThread::acknowledge_yield_request();
  8800   ConcurrentMarkSweepThread::synchronize(true);
  8801   _freelistLock->lock();
  8802   _bitMap->lock()->lock_without_safepoint_check();
  8803   _collector->startTimer();
  8806 #ifndef PRODUCT
  8807 // This is actually very useful in a product build if it can
  8808 // be called from the debugger.  Compile it into the product
  8809 // as needed.
  8810 bool debug_verify_chunk_in_free_list(FreeChunk* fc) {
  8811   return debug_cms_space->verify_chunk_in_free_list(fc);
  8813 #endif
  8815 void SweepClosure::print_free_block_coalesced(FreeChunk* fc) const {
  8816   if (CMSTraceSweeper) {
  8817     gclog_or_tty->print_cr("Sweep:coal_free_blk " PTR_FORMAT " (" SIZE_FORMAT ")",
  8818                            fc, fc->size());
  8822 // CMSIsAliveClosure
  8823 bool CMSIsAliveClosure::do_object_b(oop obj) {
  8824   HeapWord* addr = (HeapWord*)obj;
  8825   return addr != NULL &&
  8826          (!_span.contains(addr) || _bit_map->isMarked(addr));
  8830 CMSKeepAliveClosure::CMSKeepAliveClosure( CMSCollector* collector,
  8831                       MemRegion span,
  8832                       CMSBitMap* bit_map, CMSMarkStack* mark_stack,
  8833                       bool cpc):
  8834   _collector(collector),
  8835   _span(span),
  8836   _bit_map(bit_map),
  8837   _mark_stack(mark_stack),
  8838   _concurrent_precleaning(cpc) {
  8839   assert(!_span.is_empty(), "Empty span could spell trouble");
  8843 // CMSKeepAliveClosure: the serial version
  8844 void CMSKeepAliveClosure::do_oop(oop obj) {
  8845   HeapWord* addr = (HeapWord*)obj;
  8846   if (_span.contains(addr) &&
  8847       !_bit_map->isMarked(addr)) {
  8848     _bit_map->mark(addr);
  8849     bool simulate_overflow = false;
  8850     NOT_PRODUCT(
  8851       if (CMSMarkStackOverflowALot &&
  8852           _collector->simulate_overflow()) {
  8853         // simulate a stack overflow
  8854         simulate_overflow = true;
  8857     if (simulate_overflow || !_mark_stack->push(obj)) {
  8858       if (_concurrent_precleaning) {
  8859         // We dirty the overflown object and let the remark
  8860         // phase deal with it.
  8861         assert(_collector->overflow_list_is_empty(), "Error");
  8862         // In the case of object arrays, we need to dirty all of
  8863         // the cards that the object spans. No locking or atomics
  8864         // are needed since no one else can be mutating the mod union
  8865         // table.
  8866         if (obj->is_objArray()) {
  8867           size_t sz = obj->size();
  8868           HeapWord* end_card_addr =
  8869             (HeapWord*)round_to((intptr_t)(addr+sz), CardTableModRefBS::card_size);
  8870           MemRegion redirty_range = MemRegion(addr, end_card_addr);
  8871           assert(!redirty_range.is_empty(), "Arithmetical tautology");
  8872           _collector->_modUnionTable.mark_range(redirty_range);
  8873         } else {
  8874           _collector->_modUnionTable.mark(addr);
  8876         _collector->_ser_kac_preclean_ovflw++;
  8877       } else {
  8878         _collector->push_on_overflow_list(obj);
  8879         _collector->_ser_kac_ovflw++;
  8885 void CMSKeepAliveClosure::do_oop(oop* p)       { CMSKeepAliveClosure::do_oop_work(p); }
  8886 void CMSKeepAliveClosure::do_oop(narrowOop* p) { CMSKeepAliveClosure::do_oop_work(p); }
  8888 // CMSParKeepAliveClosure: a parallel version of the above.
  8889 // The work queues are private to each closure (thread),
  8890 // but (may be) available for stealing by other threads.
  8891 void CMSParKeepAliveClosure::do_oop(oop obj) {
  8892   HeapWord* addr = (HeapWord*)obj;
  8893   if (_span.contains(addr) &&
  8894       !_bit_map->isMarked(addr)) {
  8895     // In general, during recursive tracing, several threads
  8896     // may be concurrently getting here; the first one to
  8897     // "tag" it, claims it.
  8898     if (_bit_map->par_mark(addr)) {
  8899       bool res = _work_queue->push(obj);
  8900       assert(res, "Low water mark should be much less than capacity");
  8901       // Do a recursive trim in the hope that this will keep
  8902       // stack usage lower, but leave some oops for potential stealers
  8903       trim_queue(_low_water_mark);
  8904     } // Else, another thread got there first
  8908 void CMSParKeepAliveClosure::do_oop(oop* p)       { CMSParKeepAliveClosure::do_oop_work(p); }
  8909 void CMSParKeepAliveClosure::do_oop(narrowOop* p) { CMSParKeepAliveClosure::do_oop_work(p); }
  8911 void CMSParKeepAliveClosure::trim_queue(uint max) {
  8912   while (_work_queue->size() > max) {
  8913     oop new_oop;
  8914     if (_work_queue->pop_local(new_oop)) {
  8915       assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop");
  8916       assert(_bit_map->isMarked((HeapWord*)new_oop),
  8917              "no white objects on this stack!");
  8918       assert(_span.contains((HeapWord*)new_oop), "Out of bounds oop");
  8919       // iterate over the oops in this oop, marking and pushing
  8920       // the ones in CMS heap (i.e. in _span).
  8921       new_oop->oop_iterate(&_mark_and_push);
  8926 CMSInnerParMarkAndPushClosure::CMSInnerParMarkAndPushClosure(
  8927                                 CMSCollector* collector,
  8928                                 MemRegion span, CMSBitMap* bit_map,
  8929                                 OopTaskQueue* work_queue):
  8930   _collector(collector),
  8931   _span(span),
  8932   _bit_map(bit_map),
  8933   _work_queue(work_queue) { }
  8935 void CMSInnerParMarkAndPushClosure::do_oop(oop obj) {
  8936   HeapWord* addr = (HeapWord*)obj;
  8937   if (_span.contains(addr) &&
  8938       !_bit_map->isMarked(addr)) {
  8939     if (_bit_map->par_mark(addr)) {
  8940       bool simulate_overflow = false;
  8941       NOT_PRODUCT(
  8942         if (CMSMarkStackOverflowALot &&
  8943             _collector->par_simulate_overflow()) {
  8944           // simulate a stack overflow
  8945           simulate_overflow = true;
  8948       if (simulate_overflow || !_work_queue->push(obj)) {
  8949         _collector->par_push_on_overflow_list(obj);
  8950         _collector->_par_kac_ovflw++;
  8952     } // Else another thread got there already
  8956 void CMSInnerParMarkAndPushClosure::do_oop(oop* p)       { CMSInnerParMarkAndPushClosure::do_oop_work(p); }
  8957 void CMSInnerParMarkAndPushClosure::do_oop(narrowOop* p) { CMSInnerParMarkAndPushClosure::do_oop_work(p); }
  8959 //////////////////////////////////////////////////////////////////
  8960 //  CMSExpansionCause                /////////////////////////////
  8961 //////////////////////////////////////////////////////////////////
  8962 const char* CMSExpansionCause::to_string(CMSExpansionCause::Cause cause) {
  8963   switch (cause) {
  8964     case _no_expansion:
  8965       return "No expansion";
  8966     case _satisfy_free_ratio:
  8967       return "Free ratio";
  8968     case _satisfy_promotion:
  8969       return "Satisfy promotion";
  8970     case _satisfy_allocation:
  8971       return "allocation";
  8972     case _allocate_par_lab:
  8973       return "Par LAB";
  8974     case _allocate_par_spooling_space:
  8975       return "Par Spooling Space";
  8976     case _adaptive_size_policy:
  8977       return "Ergonomics";
  8978     default:
  8979       return "unknown";
  8983 void CMSDrainMarkingStackClosure::do_void() {
  8984   // the max number to take from overflow list at a time
  8985   const size_t num = _mark_stack->capacity()/4;
  8986   assert(!_concurrent_precleaning || _collector->overflow_list_is_empty(),
  8987          "Overflow list should be NULL during concurrent phases");
  8988   while (!_mark_stack->isEmpty() ||
  8989          // if stack is empty, check the overflow list
  8990          _collector->take_from_overflow_list(num, _mark_stack)) {
  8991     oop obj = _mark_stack->pop();
  8992     HeapWord* addr = (HeapWord*)obj;
  8993     assert(_span.contains(addr), "Should be within span");
  8994     assert(_bit_map->isMarked(addr), "Should be marked");
  8995     assert(obj->is_oop(), "Should be an oop");
  8996     obj->oop_iterate(_keep_alive);
  9000 void CMSParDrainMarkingStackClosure::do_void() {
  9001   // drain queue
  9002   trim_queue(0);
  9005 // Trim our work_queue so its length is below max at return
  9006 void CMSParDrainMarkingStackClosure::trim_queue(uint max) {
  9007   while (_work_queue->size() > max) {
  9008     oop new_oop;
  9009     if (_work_queue->pop_local(new_oop)) {
  9010       assert(new_oop->is_oop(), "Expected an oop");
  9011       assert(_bit_map->isMarked((HeapWord*)new_oop),
  9012              "no white objects on this stack!");
  9013       assert(_span.contains((HeapWord*)new_oop), "Out of bounds oop");
  9014       // iterate over the oops in this oop, marking and pushing
  9015       // the ones in CMS heap (i.e. in _span).
  9016       new_oop->oop_iterate(&_mark_and_push);
  9021 ////////////////////////////////////////////////////////////////////
  9022 // Support for Marking Stack Overflow list handling and related code
  9023 ////////////////////////////////////////////////////////////////////
  9024 // Much of the following code is similar in shape and spirit to the
  9025 // code used in ParNewGC. We should try and share that code
  9026 // as much as possible in the future.
  9028 #ifndef PRODUCT
  9029 // Debugging support for CMSStackOverflowALot
  9031 // It's OK to call this multi-threaded;  the worst thing
  9032 // that can happen is that we'll get a bunch of closely
  9033 // spaced simulated oveflows, but that's OK, in fact
  9034 // probably good as it would exercise the overflow code
  9035 // under contention.
  9036 bool CMSCollector::simulate_overflow() {
  9037   if (_overflow_counter-- <= 0) { // just being defensive
  9038     _overflow_counter = CMSMarkStackOverflowInterval;
  9039     return true;
  9040   } else {
  9041     return false;
  9045 bool CMSCollector::par_simulate_overflow() {
  9046   return simulate_overflow();
  9048 #endif
  9050 // Single-threaded
  9051 bool CMSCollector::take_from_overflow_list(size_t num, CMSMarkStack* stack) {
  9052   assert(stack->isEmpty(), "Expected precondition");
  9053   assert(stack->capacity() > num, "Shouldn't bite more than can chew");
  9054   size_t i = num;
  9055   oop  cur = _overflow_list;
  9056   const markOop proto = markOopDesc::prototype();
  9057   NOT_PRODUCT(ssize_t n = 0;)
  9058   for (oop next; i > 0 && cur != NULL; cur = next, i--) {
  9059     next = oop(cur->mark());
  9060     cur->set_mark(proto);   // until proven otherwise
  9061     assert(cur->is_oop(), "Should be an oop");
  9062     bool res = stack->push(cur);
  9063     assert(res, "Bit off more than can chew?");
  9064     NOT_PRODUCT(n++;)
  9066   _overflow_list = cur;
  9067 #ifndef PRODUCT
  9068   assert(_num_par_pushes >= n, "Too many pops?");
  9069   _num_par_pushes -=n;
  9070 #endif
  9071   return !stack->isEmpty();
  9074 #define BUSY  (cast_to_oop<intptr_t>(0x1aff1aff))
  9075 // (MT-safe) Get a prefix of at most "num" from the list.
  9076 // The overflow list is chained through the mark word of
  9077 // each object in the list. We fetch the entire list,
  9078 // break off a prefix of the right size and return the
  9079 // remainder. If other threads try to take objects from
  9080 // the overflow list at that time, they will wait for
  9081 // some time to see if data becomes available. If (and
  9082 // only if) another thread places one or more object(s)
  9083 // on the global list before we have returned the suffix
  9084 // to the global list, we will walk down our local list
  9085 // to find its end and append the global list to
  9086 // our suffix before returning it. This suffix walk can
  9087 // prove to be expensive (quadratic in the amount of traffic)
  9088 // when there are many objects in the overflow list and
  9089 // there is much producer-consumer contention on the list.
  9090 // *NOTE*: The overflow list manipulation code here and
  9091 // in ParNewGeneration:: are very similar in shape,
  9092 // except that in the ParNew case we use the old (from/eden)
  9093 // copy of the object to thread the list via its klass word.
  9094 // Because of the common code, if you make any changes in
  9095 // the code below, please check the ParNew version to see if
  9096 // similar changes might be needed.
  9097 // CR 6797058 has been filed to consolidate the common code.
  9098 bool CMSCollector::par_take_from_overflow_list(size_t num,
  9099                                                OopTaskQueue* work_q,
  9100                                                int no_of_gc_threads) {
  9101   assert(work_q->size() == 0, "First empty local work queue");
  9102   assert(num < work_q->max_elems(), "Can't bite more than we can chew");
  9103   if (_overflow_list == NULL) {
  9104     return false;
  9106   // Grab the entire list; we'll put back a suffix
  9107   oop prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list));
  9108   Thread* tid = Thread::current();
  9109   // Before "no_of_gc_threads" was introduced CMSOverflowSpinCount was
  9110   // set to ParallelGCThreads.
  9111   size_t CMSOverflowSpinCount = (size_t) no_of_gc_threads; // was ParallelGCThreads;
  9112   size_t sleep_time_millis = MAX2((size_t)1, num/100);
  9113   // If the list is busy, we spin for a short while,
  9114   // sleeping between attempts to get the list.
  9115   for (size_t spin = 0; prefix == BUSY && spin < CMSOverflowSpinCount; spin++) {
  9116     os::sleep(tid, sleep_time_millis, false);
  9117     if (_overflow_list == NULL) {
  9118       // Nothing left to take
  9119       return false;
  9120     } else if (_overflow_list != BUSY) {
  9121       // Try and grab the prefix
  9122       prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list));
  9125   // If the list was found to be empty, or we spun long
  9126   // enough, we give up and return empty-handed. If we leave
  9127   // the list in the BUSY state below, it must be the case that
  9128   // some other thread holds the overflow list and will set it
  9129   // to a non-BUSY state in the future.
  9130   if (prefix == NULL || prefix == BUSY) {
  9131      // Nothing to take or waited long enough
  9132      if (prefix == NULL) {
  9133        // Write back the NULL in case we overwrote it with BUSY above
  9134        // and it is still the same value.
  9135        (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY);
  9137      return false;
  9139   assert(prefix != NULL && prefix != BUSY, "Error");
  9140   size_t i = num;
  9141   oop cur = prefix;
  9142   // Walk down the first "num" objects, unless we reach the end.
  9143   for (; i > 1 && cur->mark() != NULL; cur = oop(cur->mark()), i--);
  9144   if (cur->mark() == NULL) {
  9145     // We have "num" or fewer elements in the list, so there
  9146     // is nothing to return to the global list.
  9147     // Write back the NULL in lieu of the BUSY we wrote
  9148     // above, if it is still the same value.
  9149     if (_overflow_list == BUSY) {
  9150       (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY);
  9152   } else {
  9153     // Chop off the suffix and rerturn it to the global list.
  9154     assert(cur->mark() != BUSY, "Error");
  9155     oop suffix_head = cur->mark(); // suffix will be put back on global list
  9156     cur->set_mark(NULL);           // break off suffix
  9157     // It's possible that the list is still in the empty(busy) state
  9158     // we left it in a short while ago; in that case we may be
  9159     // able to place back the suffix without incurring the cost
  9160     // of a walk down the list.
  9161     oop observed_overflow_list = _overflow_list;
  9162     oop cur_overflow_list = observed_overflow_list;
  9163     bool attached = false;
  9164     while (observed_overflow_list == BUSY || observed_overflow_list == NULL) {
  9165       observed_overflow_list =
  9166         (oop) Atomic::cmpxchg_ptr(suffix_head, &_overflow_list, cur_overflow_list);
  9167       if (cur_overflow_list == observed_overflow_list) {
  9168         attached = true;
  9169         break;
  9170       } else cur_overflow_list = observed_overflow_list;
  9172     if (!attached) {
  9173       // Too bad, someone else sneaked in (at least) an element; we'll need
  9174       // to do a splice. Find tail of suffix so we can prepend suffix to global
  9175       // list.
  9176       for (cur = suffix_head; cur->mark() != NULL; cur = (oop)(cur->mark()));
  9177       oop suffix_tail = cur;
  9178       assert(suffix_tail != NULL && suffix_tail->mark() == NULL,
  9179              "Tautology");
  9180       observed_overflow_list = _overflow_list;
  9181       do {
  9182         cur_overflow_list = observed_overflow_list;
  9183         if (cur_overflow_list != BUSY) {
  9184           // Do the splice ...
  9185           suffix_tail->set_mark(markOop(cur_overflow_list));
  9186         } else { // cur_overflow_list == BUSY
  9187           suffix_tail->set_mark(NULL);
  9189         // ... and try to place spliced list back on overflow_list ...
  9190         observed_overflow_list =
  9191           (oop) Atomic::cmpxchg_ptr(suffix_head, &_overflow_list, cur_overflow_list);
  9192       } while (cur_overflow_list != observed_overflow_list);
  9193       // ... until we have succeeded in doing so.
  9197   // Push the prefix elements on work_q
  9198   assert(prefix != NULL, "control point invariant");
  9199   const markOop proto = markOopDesc::prototype();
  9200   oop next;
  9201   NOT_PRODUCT(ssize_t n = 0;)
  9202   for (cur = prefix; cur != NULL; cur = next) {
  9203     next = oop(cur->mark());
  9204     cur->set_mark(proto);   // until proven otherwise
  9205     assert(cur->is_oop(), "Should be an oop");
  9206     bool res = work_q->push(cur);
  9207     assert(res, "Bit off more than we can chew?");
  9208     NOT_PRODUCT(n++;)
  9210 #ifndef PRODUCT
  9211   assert(_num_par_pushes >= n, "Too many pops?");
  9212   Atomic::add_ptr(-(intptr_t)n, &_num_par_pushes);
  9213 #endif
  9214   return true;
  9217 // Single-threaded
  9218 void CMSCollector::push_on_overflow_list(oop p) {
  9219   NOT_PRODUCT(_num_par_pushes++;)
  9220   assert(p->is_oop(), "Not an oop");
  9221   preserve_mark_if_necessary(p);
  9222   p->set_mark((markOop)_overflow_list);
  9223   _overflow_list = p;
  9226 // Multi-threaded; use CAS to prepend to overflow list
  9227 void CMSCollector::par_push_on_overflow_list(oop p) {
  9228   NOT_PRODUCT(Atomic::inc_ptr(&_num_par_pushes);)
  9229   assert(p->is_oop(), "Not an oop");
  9230   par_preserve_mark_if_necessary(p);
  9231   oop observed_overflow_list = _overflow_list;
  9232   oop cur_overflow_list;
  9233   do {
  9234     cur_overflow_list = observed_overflow_list;
  9235     if (cur_overflow_list != BUSY) {
  9236       p->set_mark(markOop(cur_overflow_list));
  9237     } else {
  9238       p->set_mark(NULL);
  9240     observed_overflow_list =
  9241       (oop) Atomic::cmpxchg_ptr(p, &_overflow_list, cur_overflow_list);
  9242   } while (cur_overflow_list != observed_overflow_list);
  9244 #undef BUSY
  9246 // Single threaded
  9247 // General Note on GrowableArray: pushes may silently fail
  9248 // because we are (temporarily) out of C-heap for expanding
  9249 // the stack. The problem is quite ubiquitous and affects
  9250 // a lot of code in the JVM. The prudent thing for GrowableArray
  9251 // to do (for now) is to exit with an error. However, that may
  9252 // be too draconian in some cases because the caller may be
  9253 // able to recover without much harm. For such cases, we
  9254 // should probably introduce a "soft_push" method which returns
  9255 // an indication of success or failure with the assumption that
  9256 // the caller may be able to recover from a failure; code in
  9257 // the VM can then be changed, incrementally, to deal with such
  9258 // failures where possible, thus, incrementally hardening the VM
  9259 // in such low resource situations.
  9260 void CMSCollector::preserve_mark_work(oop p, markOop m) {
  9261   _preserved_oop_stack.push(p);
  9262   _preserved_mark_stack.push(m);
  9263   assert(m == p->mark(), "Mark word changed");
  9264   assert(_preserved_oop_stack.size() == _preserved_mark_stack.size(),
  9265          "bijection");
  9268 // Single threaded
  9269 void CMSCollector::preserve_mark_if_necessary(oop p) {
  9270   markOop m = p->mark();
  9271   if (m->must_be_preserved(p)) {
  9272     preserve_mark_work(p, m);
  9276 void CMSCollector::par_preserve_mark_if_necessary(oop p) {
  9277   markOop m = p->mark();
  9278   if (m->must_be_preserved(p)) {
  9279     MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
  9280     // Even though we read the mark word without holding
  9281     // the lock, we are assured that it will not change
  9282     // because we "own" this oop, so no other thread can
  9283     // be trying to push it on the overflow list; see
  9284     // the assertion in preserve_mark_work() that checks
  9285     // that m == p->mark().
  9286     preserve_mark_work(p, m);
  9290 // We should be able to do this multi-threaded,
  9291 // a chunk of stack being a task (this is
  9292 // correct because each oop only ever appears
  9293 // once in the overflow list. However, it's
  9294 // not very easy to completely overlap this with
  9295 // other operations, so will generally not be done
  9296 // until all work's been completed. Because we
  9297 // expect the preserved oop stack (set) to be small,
  9298 // it's probably fine to do this single-threaded.
  9299 // We can explore cleverer concurrent/overlapped/parallel
  9300 // processing of preserved marks if we feel the
  9301 // need for this in the future. Stack overflow should
  9302 // be so rare in practice and, when it happens, its
  9303 // effect on performance so great that this will
  9304 // likely just be in the noise anyway.
  9305 void CMSCollector::restore_preserved_marks_if_any() {
  9306   assert(SafepointSynchronize::is_at_safepoint(),
  9307          "world should be stopped");
  9308   assert(Thread::current()->is_ConcurrentGC_thread() ||
  9309          Thread::current()->is_VM_thread(),
  9310          "should be single-threaded");
  9311   assert(_preserved_oop_stack.size() == _preserved_mark_stack.size(),
  9312          "bijection");
  9314   while (!_preserved_oop_stack.is_empty()) {
  9315     oop p = _preserved_oop_stack.pop();
  9316     assert(p->is_oop(), "Should be an oop");
  9317     assert(_span.contains(p), "oop should be in _span");
  9318     assert(p->mark() == markOopDesc::prototype(),
  9319            "Set when taken from overflow list");
  9320     markOop m = _preserved_mark_stack.pop();
  9321     p->set_mark(m);
  9323   assert(_preserved_mark_stack.is_empty() && _preserved_oop_stack.is_empty(),
  9324          "stacks were cleared above");
  9327 #ifndef PRODUCT
  9328 bool CMSCollector::no_preserved_marks() const {
  9329   return _preserved_mark_stack.is_empty() && _preserved_oop_stack.is_empty();
  9331 #endif
  9333 CMSAdaptiveSizePolicy* ASConcurrentMarkSweepGeneration::cms_size_policy() const
  9335   GenCollectedHeap* gch = (GenCollectedHeap*) GenCollectedHeap::heap();
  9336   CMSAdaptiveSizePolicy* size_policy =
  9337     (CMSAdaptiveSizePolicy*) gch->gen_policy()->size_policy();
  9338   assert(size_policy->is_gc_cms_adaptive_size_policy(),
  9339     "Wrong type for size policy");
  9340   return size_policy;
  9343 void ASConcurrentMarkSweepGeneration::resize(size_t cur_promo_size,
  9344                                            size_t desired_promo_size) {
  9345   if (cur_promo_size < desired_promo_size) {
  9346     size_t expand_bytes = desired_promo_size - cur_promo_size;
  9347     if (PrintAdaptiveSizePolicy && Verbose) {
  9348       gclog_or_tty->print_cr(" ASConcurrentMarkSweepGeneration::resize "
  9349         "Expanding tenured generation by " SIZE_FORMAT " (bytes)",
  9350         expand_bytes);
  9352     expand(expand_bytes,
  9353            MinHeapDeltaBytes,
  9354            CMSExpansionCause::_adaptive_size_policy);
  9355   } else if (desired_promo_size < cur_promo_size) {
  9356     size_t shrink_bytes = cur_promo_size - desired_promo_size;
  9357     if (PrintAdaptiveSizePolicy && Verbose) {
  9358       gclog_or_tty->print_cr(" ASConcurrentMarkSweepGeneration::resize "
  9359         "Shrinking tenured generation by " SIZE_FORMAT " (bytes)",
  9360         shrink_bytes);
  9362     shrink(shrink_bytes);
  9366 CMSGCAdaptivePolicyCounters* ASConcurrentMarkSweepGeneration::gc_adaptive_policy_counters() {
  9367   GenCollectedHeap* gch = GenCollectedHeap::heap();
  9368   CMSGCAdaptivePolicyCounters* counters =
  9369     (CMSGCAdaptivePolicyCounters*) gch->collector_policy()->counters();
  9370   assert(counters->kind() == GCPolicyCounters::CMSGCAdaptivePolicyCountersKind,
  9371     "Wrong kind of counters");
  9372   return counters;
  9376 void ASConcurrentMarkSweepGeneration::update_counters() {
  9377   if (UsePerfData) {
  9378     _space_counters->update_all();
  9379     _gen_counters->update_all();
  9380     CMSGCAdaptivePolicyCounters* counters = gc_adaptive_policy_counters();
  9381     GenCollectedHeap* gch = GenCollectedHeap::heap();
  9382     CMSGCStats* gc_stats_l = (CMSGCStats*) gc_stats();
  9383     assert(gc_stats_l->kind() == GCStats::CMSGCStatsKind,
  9384       "Wrong gc statistics type");
  9385     counters->update_counters(gc_stats_l);
  9389 void ASConcurrentMarkSweepGeneration::update_counters(size_t used) {
  9390   if (UsePerfData) {
  9391     _space_counters->update_used(used);
  9392     _space_counters->update_capacity();
  9393     _gen_counters->update_all();
  9395     CMSGCAdaptivePolicyCounters* counters = gc_adaptive_policy_counters();
  9396     GenCollectedHeap* gch = GenCollectedHeap::heap();
  9397     CMSGCStats* gc_stats_l = (CMSGCStats*) gc_stats();
  9398     assert(gc_stats_l->kind() == GCStats::CMSGCStatsKind,
  9399       "Wrong gc statistics type");
  9400     counters->update_counters(gc_stats_l);
  9404 void ASConcurrentMarkSweepGeneration::shrink_by(size_t desired_bytes) {
  9405   assert_locked_or_safepoint(Heap_lock);
  9406   assert_lock_strong(freelistLock());
  9407   HeapWord* old_end = _cmsSpace->end();
  9408   HeapWord* unallocated_start = _cmsSpace->unallocated_block();
  9409   assert(old_end >= unallocated_start, "Miscalculation of unallocated_start");
  9410   FreeChunk* chunk_at_end = find_chunk_at_end();
  9411   if (chunk_at_end == NULL) {
  9412     // No room to shrink
  9413     if (PrintGCDetails && Verbose) {
  9414       gclog_or_tty->print_cr("No room to shrink: old_end  "
  9415         PTR_FORMAT "  unallocated_start  " PTR_FORMAT
  9416         " chunk_at_end  " PTR_FORMAT,
  9417         old_end, unallocated_start, chunk_at_end);
  9419     return;
  9420   } else {
  9422     // Find the chunk at the end of the space and determine
  9423     // how much it can be shrunk.
  9424     size_t shrinkable_size_in_bytes = chunk_at_end->size();
  9425     size_t aligned_shrinkable_size_in_bytes =
  9426       align_size_down(shrinkable_size_in_bytes, os::vm_page_size());
  9427     assert(unallocated_start <= (HeapWord*) chunk_at_end->end(),
  9428       "Inconsistent chunk at end of space");
  9429     size_t bytes = MIN2(desired_bytes, aligned_shrinkable_size_in_bytes);
  9430     size_t word_size_before = heap_word_size(_virtual_space.committed_size());
  9432     // Shrink the underlying space
  9433     _virtual_space.shrink_by(bytes);
  9434     if (PrintGCDetails && Verbose) {
  9435       gclog_or_tty->print_cr("ConcurrentMarkSweepGeneration::shrink_by:"
  9436         " desired_bytes " SIZE_FORMAT
  9437         " shrinkable_size_in_bytes " SIZE_FORMAT
  9438         " aligned_shrinkable_size_in_bytes " SIZE_FORMAT
  9439         "  bytes  " SIZE_FORMAT,
  9440         desired_bytes, shrinkable_size_in_bytes,
  9441         aligned_shrinkable_size_in_bytes, bytes);
  9442       gclog_or_tty->print_cr("          old_end  " SIZE_FORMAT
  9443         "  unallocated_start  " SIZE_FORMAT,
  9444         old_end, unallocated_start);
  9447     // If the space did shrink (shrinking is not guaranteed),
  9448     // shrink the chunk at the end by the appropriate amount.
  9449     if (((HeapWord*)_virtual_space.high()) < old_end) {
  9450       size_t new_word_size =
  9451         heap_word_size(_virtual_space.committed_size());
  9453       // Have to remove the chunk from the dictionary because it is changing
  9454       // size and might be someplace elsewhere in the dictionary.
  9456       // Get the chunk at end, shrink it, and put it
  9457       // back.
  9458       _cmsSpace->removeChunkFromDictionary(chunk_at_end);
  9459       size_t word_size_change = word_size_before - new_word_size;
  9460       size_t chunk_at_end_old_size = chunk_at_end->size();
  9461       assert(chunk_at_end_old_size >= word_size_change,
  9462         "Shrink is too large");
  9463       chunk_at_end->set_size(chunk_at_end_old_size -
  9464                           word_size_change);
  9465       _cmsSpace->freed((HeapWord*) chunk_at_end->end(),
  9466         word_size_change);
  9468       _cmsSpace->returnChunkToDictionary(chunk_at_end);
  9470       MemRegion mr(_cmsSpace->bottom(), new_word_size);
  9471       _bts->resize(new_word_size);  // resize the block offset shared array
  9472       Universe::heap()->barrier_set()->resize_covered_region(mr);
  9473       _cmsSpace->assert_locked();
  9474       _cmsSpace->set_end((HeapWord*)_virtual_space.high());
  9476       NOT_PRODUCT(_cmsSpace->dictionary()->verify());
  9478       // update the space and generation capacity counters
  9479       if (UsePerfData) {
  9480         _space_counters->update_capacity();
  9481         _gen_counters->update_all();
  9484       if (Verbose && PrintGCDetails) {
  9485         size_t new_mem_size = _virtual_space.committed_size();
  9486         size_t old_mem_size = new_mem_size + bytes;
  9487         gclog_or_tty->print_cr("Shrinking %s from " SIZE_FORMAT "K by " SIZE_FORMAT "K to " SIZE_FORMAT "K",
  9488                       name(), old_mem_size/K, bytes/K, new_mem_size/K);
  9492     assert(_cmsSpace->unallocated_block() <= _cmsSpace->end(),
  9493       "Inconsistency at end of space");
  9494     assert(chunk_at_end->end() == (uintptr_t*) _cmsSpace->end(),
  9495       "Shrinking is inconsistent");
  9496     return;
  9499 // Transfer some number of overflown objects to usual marking
  9500 // stack. Return true if some objects were transferred.
  9501 bool MarkRefsIntoAndScanClosure::take_from_overflow_list() {
  9502   size_t num = MIN2((size_t)(_mark_stack->capacity() - _mark_stack->length())/4,
  9503                     (size_t)ParGCDesiredObjsFromOverflowList);
  9505   bool res = _collector->take_from_overflow_list(num, _mark_stack);
  9506   assert(_collector->overflow_list_is_empty() || res,
  9507          "If list is not empty, we should have taken something");
  9508   assert(!res || !_mark_stack->isEmpty(),
  9509          "If we took something, it should now be on our stack");
  9510   return res;
  9513 size_t MarkDeadObjectsClosure::do_blk(HeapWord* addr) {
  9514   size_t res = _sp->block_size_no_stall(addr, _collector);
  9515   if (_sp->block_is_obj(addr)) {
  9516     if (_live_bit_map->isMarked(addr)) {
  9517       // It can't have been dead in a previous cycle
  9518       guarantee(!_dead_bit_map->isMarked(addr), "No resurrection!");
  9519     } else {
  9520       _dead_bit_map->mark(addr);      // mark the dead object
  9523   // Could be 0, if the block size could not be computed without stalling.
  9524   return res;
  9527 TraceCMSMemoryManagerStats::TraceCMSMemoryManagerStats(CMSCollector::CollectorState phase, GCCause::Cause cause): TraceMemoryManagerStats() {
  9529   switch (phase) {
  9530     case CMSCollector::InitialMarking:
  9531       initialize(true  /* fullGC */ ,
  9532                  cause /* cause of the GC */,
  9533                  true  /* recordGCBeginTime */,
  9534                  true  /* recordPreGCUsage */,
  9535                  false /* recordPeakUsage */,
  9536                  false /* recordPostGCusage */,
  9537                  true  /* recordAccumulatedGCTime */,
  9538                  false /* recordGCEndTime */,
  9539                  false /* countCollection */  );
  9540       break;
  9542     case CMSCollector::FinalMarking:
  9543       initialize(true  /* fullGC */ ,
  9544                  cause /* cause of the GC */,
  9545                  false /* recordGCBeginTime */,
  9546                  false /* recordPreGCUsage */,
  9547                  false /* recordPeakUsage */,
  9548                  false /* recordPostGCusage */,
  9549                  true  /* recordAccumulatedGCTime */,
  9550                  false /* recordGCEndTime */,
  9551                  false /* countCollection */  );
  9552       break;
  9554     case CMSCollector::Sweeping:
  9555       initialize(true  /* fullGC */ ,
  9556                  cause /* cause of the GC */,
  9557                  false /* recordGCBeginTime */,
  9558                  false /* recordPreGCUsage */,
  9559                  true  /* recordPeakUsage */,
  9560                  true  /* recordPostGCusage */,
  9561                  false /* recordAccumulatedGCTime */,
  9562                  true  /* recordGCEndTime */,
  9563                  true  /* countCollection */  );
  9564       break;
  9566     default:
  9567       ShouldNotReachHere();

mercurial