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

Wed, 11 Jun 2014 10:46:47 +0200

author
brutisso
date
Wed, 11 Jun 2014 10:46:47 +0200
changeset 6719
8e20ef014b08
parent 6680
78bbf4d43a14
child 6876
710a3c8b516e
child 6904
0982ec23da03
child 7470
060cdf93040c
permissions
-rw-r--r--

8043239: G1: Missing post barrier in processing of j.l.ref.Reference objects
Summary: Removed all write barriers during reference processing and added explicit write barriers when iterating through the discovered list.
Reviewed-by: pliden, jmasa, tschatzl

     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     // Initialize the _ref_processor field of CMSGen
   315     _cmsGen->set_ref_processor(_ref_processor);
   317   }
   318 }
   320 CMSAdaptiveSizePolicy* CMSCollector::size_policy() {
   321   GenCollectedHeap* gch = GenCollectedHeap::heap();
   322   assert(gch->kind() == CollectedHeap::GenCollectedHeap,
   323     "Wrong type of heap");
   324   CMSAdaptiveSizePolicy* sp = (CMSAdaptiveSizePolicy*)
   325     gch->gen_policy()->size_policy();
   326   assert(sp->is_gc_cms_adaptive_size_policy(),
   327     "Wrong type of size policy");
   328   return sp;
   329 }
   331 CMSGCAdaptivePolicyCounters* CMSCollector::gc_adaptive_policy_counters() {
   332   CMSGCAdaptivePolicyCounters* results =
   333     (CMSGCAdaptivePolicyCounters*) collector_policy()->counters();
   334   assert(
   335     results->kind() == GCPolicyCounters::CMSGCAdaptivePolicyCountersKind,
   336     "Wrong gc policy counter kind");
   337   return results;
   338 }
   341 void ConcurrentMarkSweepGeneration::initialize_performance_counters() {
   343   const char* gen_name = "old";
   345   // Generation Counters - generation 1, 1 subspace
   346   _gen_counters = new GenerationCounters(gen_name, 1, 1, &_virtual_space);
   348   _space_counters = new GSpaceCounters(gen_name, 0,
   349                                        _virtual_space.reserved_size(),
   350                                        this, _gen_counters);
   351 }
   353 CMSStats::CMSStats(ConcurrentMarkSweepGeneration* cms_gen, unsigned int alpha):
   354   _cms_gen(cms_gen)
   355 {
   356   assert(alpha <= 100, "bad value");
   357   _saved_alpha = alpha;
   359   // Initialize the alphas to the bootstrap value of 100.
   360   _gc0_alpha = _cms_alpha = 100;
   362   _cms_begin_time.update();
   363   _cms_end_time.update();
   365   _gc0_duration = 0.0;
   366   _gc0_period = 0.0;
   367   _gc0_promoted = 0;
   369   _cms_duration = 0.0;
   370   _cms_period = 0.0;
   371   _cms_allocated = 0;
   373   _cms_used_at_gc0_begin = 0;
   374   _cms_used_at_gc0_end = 0;
   375   _allow_duty_cycle_reduction = false;
   376   _valid_bits = 0;
   377   _icms_duty_cycle = CMSIncrementalDutyCycle;
   378 }
   380 double CMSStats::cms_free_adjustment_factor(size_t free) const {
   381   // TBD: CR 6909490
   382   return 1.0;
   383 }
   385 void CMSStats::adjust_cms_free_adjustment_factor(bool fail, size_t free) {
   386 }
   388 // If promotion failure handling is on use
   389 // the padded average size of the promotion for each
   390 // young generation collection.
   391 double CMSStats::time_until_cms_gen_full() const {
   392   size_t cms_free = _cms_gen->cmsSpace()->free();
   393   GenCollectedHeap* gch = GenCollectedHeap::heap();
   394   size_t expected_promotion = MIN2(gch->get_gen(0)->capacity(),
   395                                    (size_t) _cms_gen->gc_stats()->avg_promoted()->padded_average());
   396   if (cms_free > expected_promotion) {
   397     // Start a cms collection if there isn't enough space to promote
   398     // for the next minor collection.  Use the padded average as
   399     // a safety factor.
   400     cms_free -= expected_promotion;
   402     // Adjust by the safety factor.
   403     double cms_free_dbl = (double)cms_free;
   404     double cms_adjustment = (100.0 - CMSIncrementalSafetyFactor)/100.0;
   405     // Apply a further correction factor which tries to adjust
   406     // for recent occurance of concurrent mode failures.
   407     cms_adjustment = cms_adjustment * cms_free_adjustment_factor(cms_free);
   408     cms_free_dbl = cms_free_dbl * cms_adjustment;
   410     if (PrintGCDetails && Verbose) {
   411       gclog_or_tty->print_cr("CMSStats::time_until_cms_gen_full: cms_free "
   412         SIZE_FORMAT " expected_promotion " SIZE_FORMAT,
   413         cms_free, expected_promotion);
   414       gclog_or_tty->print_cr("  cms_free_dbl %f cms_consumption_rate %f",
   415         cms_free_dbl, cms_consumption_rate() + 1.0);
   416     }
   417     // Add 1 in case the consumption rate goes to zero.
   418     return cms_free_dbl / (cms_consumption_rate() + 1.0);
   419   }
   420   return 0.0;
   421 }
   423 // Compare the duration of the cms collection to the
   424 // time remaining before the cms generation is empty.
   425 // Note that the time from the start of the cms collection
   426 // to the start of the cms sweep (less than the total
   427 // duration of the cms collection) can be used.  This
   428 // has been tried and some applications experienced
   429 // promotion failures early in execution.  This was
   430 // possibly because the averages were not accurate
   431 // enough at the beginning.
   432 double CMSStats::time_until_cms_start() const {
   433   // We add "gc0_period" to the "work" calculation
   434   // below because this query is done (mostly) at the
   435   // end of a scavenge, so we need to conservatively
   436   // account for that much possible delay
   437   // in the query so as to avoid concurrent mode failures
   438   // due to starting the collection just a wee bit too
   439   // late.
   440   double work = cms_duration() + gc0_period();
   441   double deadline = time_until_cms_gen_full();
   442   // If a concurrent mode failure occurred recently, we want to be
   443   // more conservative and halve our expected time_until_cms_gen_full()
   444   if (work > deadline) {
   445     if (Verbose && PrintGCDetails) {
   446       gclog_or_tty->print(
   447         " CMSCollector: collect because of anticipated promotion "
   448         "before full %3.7f + %3.7f > %3.7f ", cms_duration(),
   449         gc0_period(), time_until_cms_gen_full());
   450     }
   451     return 0.0;
   452   }
   453   return work - deadline;
   454 }
   456 // Return a duty cycle based on old_duty_cycle and new_duty_cycle, limiting the
   457 // amount of change to prevent wild oscillation.
   458 unsigned int CMSStats::icms_damped_duty_cycle(unsigned int old_duty_cycle,
   459                                               unsigned int new_duty_cycle) {
   460   assert(old_duty_cycle <= 100, "bad input value");
   461   assert(new_duty_cycle <= 100, "bad input value");
   463   // Note:  use subtraction with caution since it may underflow (values are
   464   // unsigned).  Addition is safe since we're in the range 0-100.
   465   unsigned int damped_duty_cycle = new_duty_cycle;
   466   if (new_duty_cycle < old_duty_cycle) {
   467     const unsigned int largest_delta = MAX2(old_duty_cycle / 4, 5U);
   468     if (new_duty_cycle + largest_delta < old_duty_cycle) {
   469       damped_duty_cycle = old_duty_cycle - largest_delta;
   470     }
   471   } else if (new_duty_cycle > old_duty_cycle) {
   472     const unsigned int largest_delta = MAX2(old_duty_cycle / 4, 15U);
   473     if (new_duty_cycle > old_duty_cycle + largest_delta) {
   474       damped_duty_cycle = MIN2(old_duty_cycle + largest_delta, 100U);
   475     }
   476   }
   477   assert(damped_duty_cycle <= 100, "invalid duty cycle computed");
   479   if (CMSTraceIncrementalPacing) {
   480     gclog_or_tty->print(" [icms_damped_duty_cycle(%d,%d) = %d] ",
   481                            old_duty_cycle, new_duty_cycle, damped_duty_cycle);
   482   }
   483   return damped_duty_cycle;
   484 }
   486 unsigned int CMSStats::icms_update_duty_cycle_impl() {
   487   assert(CMSIncrementalPacing && valid(),
   488          "should be handled in icms_update_duty_cycle()");
   490   double cms_time_so_far = cms_timer().seconds();
   491   double scaled_duration = cms_duration_per_mb() * _cms_used_at_gc0_end / M;
   492   double scaled_duration_remaining = fabsd(scaled_duration - cms_time_so_far);
   494   // Avoid division by 0.
   495   double time_until_full = MAX2(time_until_cms_gen_full(), 0.01);
   496   double duty_cycle_dbl = 100.0 * scaled_duration_remaining / time_until_full;
   498   unsigned int new_duty_cycle = MIN2((unsigned int)duty_cycle_dbl, 100U);
   499   if (new_duty_cycle > _icms_duty_cycle) {
   500     // Avoid very small duty cycles (1 or 2); 0 is allowed.
   501     if (new_duty_cycle > 2) {
   502       _icms_duty_cycle = icms_damped_duty_cycle(_icms_duty_cycle,
   503                                                 new_duty_cycle);
   504     }
   505   } else if (_allow_duty_cycle_reduction) {
   506     // The duty cycle is reduced only once per cms cycle (see record_cms_end()).
   507     new_duty_cycle = icms_damped_duty_cycle(_icms_duty_cycle, new_duty_cycle);
   508     // Respect the minimum duty cycle.
   509     unsigned int min_duty_cycle = (unsigned int)CMSIncrementalDutyCycleMin;
   510     _icms_duty_cycle = MAX2(new_duty_cycle, min_duty_cycle);
   511   }
   513   if (PrintGCDetails || CMSTraceIncrementalPacing) {
   514     gclog_or_tty->print(" icms_dc=%d ", _icms_duty_cycle);
   515   }
   517   _allow_duty_cycle_reduction = false;
   518   return _icms_duty_cycle;
   519 }
   521 #ifndef PRODUCT
   522 void CMSStats::print_on(outputStream *st) const {
   523   st->print(" gc0_alpha=%d,cms_alpha=%d", _gc0_alpha, _cms_alpha);
   524   st->print(",gc0_dur=%g,gc0_per=%g,gc0_promo=" SIZE_FORMAT,
   525                gc0_duration(), gc0_period(), gc0_promoted());
   526   st->print(",cms_dur=%g,cms_dur_per_mb=%g,cms_per=%g,cms_alloc=" SIZE_FORMAT,
   527             cms_duration(), cms_duration_per_mb(),
   528             cms_period(), cms_allocated());
   529   st->print(",cms_since_beg=%g,cms_since_end=%g",
   530             cms_time_since_begin(), cms_time_since_end());
   531   st->print(",cms_used_beg=" SIZE_FORMAT ",cms_used_end=" SIZE_FORMAT,
   532             _cms_used_at_gc0_begin, _cms_used_at_gc0_end);
   533   if (CMSIncrementalMode) {
   534     st->print(",dc=%d", icms_duty_cycle());
   535   }
   537   if (valid()) {
   538     st->print(",promo_rate=%g,cms_alloc_rate=%g",
   539               promotion_rate(), cms_allocation_rate());
   540     st->print(",cms_consumption_rate=%g,time_until_full=%g",
   541               cms_consumption_rate(), time_until_cms_gen_full());
   542   }
   543   st->print(" ");
   544 }
   545 #endif // #ifndef PRODUCT
   547 CMSCollector::CollectorState CMSCollector::_collectorState =
   548                              CMSCollector::Idling;
   549 bool CMSCollector::_foregroundGCIsActive = false;
   550 bool CMSCollector::_foregroundGCShouldWait = false;
   552 CMSCollector::CMSCollector(ConcurrentMarkSweepGeneration* cmsGen,
   553                            CardTableRS*                   ct,
   554                            ConcurrentMarkSweepPolicy*     cp):
   555   _cmsGen(cmsGen),
   556   _ct(ct),
   557   _ref_processor(NULL),    // will be set later
   558   _conc_workers(NULL),     // may be set later
   559   _abort_preclean(false),
   560   _start_sampling(false),
   561   _between_prologue_and_epilogue(false),
   562   _markBitMap(0, Mutex::leaf + 1, "CMS_markBitMap_lock"),
   563   _modUnionTable((CardTableModRefBS::card_shift - LogHeapWordSize),
   564                  -1 /* lock-free */, "No_lock" /* dummy */),
   565   _modUnionClosure(&_modUnionTable),
   566   _modUnionClosurePar(&_modUnionTable),
   567   // Adjust my span to cover old (cms) gen
   568   _span(cmsGen->reserved()),
   569   // Construct the is_alive_closure with _span & markBitMap
   570   _is_alive_closure(_span, &_markBitMap),
   571   _restart_addr(NULL),
   572   _overflow_list(NULL),
   573   _stats(cmsGen),
   574   _eden_chunk_lock(new Mutex(Mutex::leaf + 1, "CMS_eden_chunk_lock", true)),
   575   _eden_chunk_array(NULL),     // may be set in ctor body
   576   _eden_chunk_capacity(0),     // -- ditto --
   577   _eden_chunk_index(0),        // -- ditto --
   578   _survivor_plab_array(NULL),  // -- ditto --
   579   _survivor_chunk_array(NULL), // -- ditto --
   580   _survivor_chunk_capacity(0), // -- ditto --
   581   _survivor_chunk_index(0),    // -- ditto --
   582   _ser_pmc_preclean_ovflw(0),
   583   _ser_kac_preclean_ovflw(0),
   584   _ser_pmc_remark_ovflw(0),
   585   _par_pmc_remark_ovflw(0),
   586   _ser_kac_ovflw(0),
   587   _par_kac_ovflw(0),
   588 #ifndef PRODUCT
   589   _num_par_pushes(0),
   590 #endif
   591   _collection_count_start(0),
   592   _verifying(false),
   593   _icms_start_limit(NULL),
   594   _icms_stop_limit(NULL),
   595   _verification_mark_bm(0, Mutex::leaf + 1, "CMS_verification_mark_bm_lock"),
   596   _completed_initialization(false),
   597   _collector_policy(cp),
   598   _should_unload_classes(CMSClassUnloadingEnabled),
   599   _concurrent_cycles_since_last_unload(0),
   600   _roots_scanning_options(SharedHeap::SO_None),
   601   _inter_sweep_estimate(CMS_SweepWeight, CMS_SweepPadding),
   602   _intra_sweep_estimate(CMS_SweepWeight, CMS_SweepPadding),
   603   _gc_tracer_cm(new (ResourceObj::C_HEAP, mtGC) CMSTracer()),
   604   _gc_timer_cm(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
   605   _cms_start_registered(false)
   606 {
   607   if (ExplicitGCInvokesConcurrentAndUnloadsClasses) {
   608     ExplicitGCInvokesConcurrent = true;
   609   }
   610   // Now expand the span and allocate the collection support structures
   611   // (MUT, marking bit map etc.) to cover both generations subject to
   612   // collection.
   614   // For use by dirty card to oop closures.
   615   _cmsGen->cmsSpace()->set_collector(this);
   617   // Allocate MUT and marking bit map
   618   {
   619     MutexLockerEx x(_markBitMap.lock(), Mutex::_no_safepoint_check_flag);
   620     if (!_markBitMap.allocate(_span)) {
   621       warning("Failed to allocate CMS Bit Map");
   622       return;
   623     }
   624     assert(_markBitMap.covers(_span), "_markBitMap inconsistency?");
   625   }
   626   {
   627     _modUnionTable.allocate(_span);
   628     assert(_modUnionTable.covers(_span), "_modUnionTable inconsistency?");
   629   }
   631   if (!_markStack.allocate(MarkStackSize)) {
   632     warning("Failed to allocate CMS Marking Stack");
   633     return;
   634   }
   636   // Support for multi-threaded concurrent phases
   637   if (CMSConcurrentMTEnabled) {
   638     if (FLAG_IS_DEFAULT(ConcGCThreads)) {
   639       // just for now
   640       FLAG_SET_DEFAULT(ConcGCThreads, (ParallelGCThreads + 3)/4);
   641     }
   642     if (ConcGCThreads > 1) {
   643       _conc_workers = new YieldingFlexibleWorkGang("Parallel CMS Threads",
   644                                  ConcGCThreads, true);
   645       if (_conc_workers == NULL) {
   646         warning("GC/CMS: _conc_workers allocation failure: "
   647               "forcing -CMSConcurrentMTEnabled");
   648         CMSConcurrentMTEnabled = false;
   649       } else {
   650         _conc_workers->initialize_workers();
   651       }
   652     } else {
   653       CMSConcurrentMTEnabled = false;
   654     }
   655   }
   656   if (!CMSConcurrentMTEnabled) {
   657     ConcGCThreads = 0;
   658   } else {
   659     // Turn off CMSCleanOnEnter optimization temporarily for
   660     // the MT case where it's not fixed yet; see 6178663.
   661     CMSCleanOnEnter = false;
   662   }
   663   assert((_conc_workers != NULL) == (ConcGCThreads > 1),
   664          "Inconsistency");
   666   // Parallel task queues; these are shared for the
   667   // concurrent and stop-world phases of CMS, but
   668   // are not shared with parallel scavenge (ParNew).
   669   {
   670     uint i;
   671     uint num_queues = (uint) MAX2(ParallelGCThreads, ConcGCThreads);
   673     if ((CMSParallelRemarkEnabled || CMSConcurrentMTEnabled
   674          || ParallelRefProcEnabled)
   675         && num_queues > 0) {
   676       _task_queues = new OopTaskQueueSet(num_queues);
   677       if (_task_queues == NULL) {
   678         warning("task_queues allocation failure.");
   679         return;
   680       }
   681       _hash_seed = NEW_C_HEAP_ARRAY(int, num_queues, mtGC);
   682       if (_hash_seed == NULL) {
   683         warning("_hash_seed array allocation failure");
   684         return;
   685       }
   687       typedef Padded<OopTaskQueue> PaddedOopTaskQueue;
   688       for (i = 0; i < num_queues; i++) {
   689         PaddedOopTaskQueue *q = new PaddedOopTaskQueue();
   690         if (q == NULL) {
   691           warning("work_queue allocation failure.");
   692           return;
   693         }
   694         _task_queues->register_queue(i, q);
   695       }
   696       for (i = 0; i < num_queues; i++) {
   697         _task_queues->queue(i)->initialize();
   698         _hash_seed[i] = 17;  // copied from ParNew
   699       }
   700     }
   701   }
   703   _cmsGen ->init_initiating_occupancy(CMSInitiatingOccupancyFraction, CMSTriggerRatio);
   705   // Clip CMSBootstrapOccupancy between 0 and 100.
   706   _bootstrap_occupancy = ((double)CMSBootstrapOccupancy)/(double)100;
   708   _full_gcs_since_conc_gc = 0;
   710   // Now tell CMS generations the identity of their collector
   711   ConcurrentMarkSweepGeneration::set_collector(this);
   713   // Create & start a CMS thread for this CMS collector
   714   _cmsThread = ConcurrentMarkSweepThread::start(this);
   715   assert(cmsThread() != NULL, "CMS Thread should have been created");
   716   assert(cmsThread()->collector() == this,
   717          "CMS Thread should refer to this gen");
   718   assert(CGC_lock != NULL, "Where's the CGC_lock?");
   720   // Support for parallelizing young gen rescan
   721   GenCollectedHeap* gch = GenCollectedHeap::heap();
   722   _young_gen = gch->prev_gen(_cmsGen);
   723   if (gch->supports_inline_contig_alloc()) {
   724     _top_addr = gch->top_addr();
   725     _end_addr = gch->end_addr();
   726     assert(_young_gen != NULL, "no _young_gen");
   727     _eden_chunk_index = 0;
   728     _eden_chunk_capacity = (_young_gen->max_capacity()+CMSSamplingGrain)/CMSSamplingGrain;
   729     _eden_chunk_array = NEW_C_HEAP_ARRAY(HeapWord*, _eden_chunk_capacity, mtGC);
   730     if (_eden_chunk_array == NULL) {
   731       _eden_chunk_capacity = 0;
   732       warning("GC/CMS: _eden_chunk_array allocation failure");
   733     }
   734   }
   735   assert(_eden_chunk_array != NULL || _eden_chunk_capacity == 0, "Error");
   737   // Support for parallelizing survivor space rescan
   738   if ((CMSParallelRemarkEnabled && CMSParallelSurvivorRemarkEnabled) || CMSParallelInitialMarkEnabled) {
   739     const size_t max_plab_samples =
   740       ((DefNewGeneration*)_young_gen)->max_survivor_size()/MinTLABSize;
   742     _survivor_plab_array  = NEW_C_HEAP_ARRAY(ChunkArray, ParallelGCThreads, mtGC);
   743     _survivor_chunk_array = NEW_C_HEAP_ARRAY(HeapWord*, 2*max_plab_samples, mtGC);
   744     _cursor               = NEW_C_HEAP_ARRAY(size_t, ParallelGCThreads, mtGC);
   745     if (_survivor_plab_array == NULL || _survivor_chunk_array == NULL
   746         || _cursor == NULL) {
   747       warning("Failed to allocate survivor plab/chunk array");
   748       if (_survivor_plab_array  != NULL) {
   749         FREE_C_HEAP_ARRAY(ChunkArray, _survivor_plab_array, mtGC);
   750         _survivor_plab_array = NULL;
   751       }
   752       if (_survivor_chunk_array != NULL) {
   753         FREE_C_HEAP_ARRAY(HeapWord*, _survivor_chunk_array, mtGC);
   754         _survivor_chunk_array = NULL;
   755       }
   756       if (_cursor != NULL) {
   757         FREE_C_HEAP_ARRAY(size_t, _cursor, mtGC);
   758         _cursor = NULL;
   759       }
   760     } else {
   761       _survivor_chunk_capacity = 2*max_plab_samples;
   762       for (uint i = 0; i < ParallelGCThreads; i++) {
   763         HeapWord** vec = NEW_C_HEAP_ARRAY(HeapWord*, max_plab_samples, mtGC);
   764         if (vec == NULL) {
   765           warning("Failed to allocate survivor plab array");
   766           for (int j = i; j > 0; j--) {
   767             FREE_C_HEAP_ARRAY(HeapWord*, _survivor_plab_array[j-1].array(), mtGC);
   768           }
   769           FREE_C_HEAP_ARRAY(ChunkArray, _survivor_plab_array, mtGC);
   770           FREE_C_HEAP_ARRAY(HeapWord*, _survivor_chunk_array, mtGC);
   771           _survivor_plab_array = NULL;
   772           _survivor_chunk_array = NULL;
   773           _survivor_chunk_capacity = 0;
   774           break;
   775         } else {
   776           ChunkArray* cur =
   777             ::new (&_survivor_plab_array[i]) ChunkArray(vec,
   778                                                         max_plab_samples);
   779           assert(cur->end() == 0, "Should be 0");
   780           assert(cur->array() == vec, "Should be vec");
   781           assert(cur->capacity() == max_plab_samples, "Error");
   782         }
   783       }
   784     }
   785   }
   786   assert(   (   _survivor_plab_array  != NULL
   787              && _survivor_chunk_array != NULL)
   788          || (   _survivor_chunk_capacity == 0
   789              && _survivor_chunk_index == 0),
   790          "Error");
   792   NOT_PRODUCT(_overflow_counter = CMSMarkStackOverflowInterval;)
   793   _gc_counters = new CollectorCounters("CMS", 1);
   794   _completed_initialization = true;
   795   _inter_sweep_timer.start();  // start of time
   796 }
   798 const char* ConcurrentMarkSweepGeneration::name() const {
   799   return "concurrent mark-sweep generation";
   800 }
   801 void ConcurrentMarkSweepGeneration::update_counters() {
   802   if (UsePerfData) {
   803     _space_counters->update_all();
   804     _gen_counters->update_all();
   805   }
   806 }
   808 // this is an optimized version of update_counters(). it takes the
   809 // used value as a parameter rather than computing it.
   810 //
   811 void ConcurrentMarkSweepGeneration::update_counters(size_t used) {
   812   if (UsePerfData) {
   813     _space_counters->update_used(used);
   814     _space_counters->update_capacity();
   815     _gen_counters->update_all();
   816   }
   817 }
   819 void ConcurrentMarkSweepGeneration::print() const {
   820   Generation::print();
   821   cmsSpace()->print();
   822 }
   824 #ifndef PRODUCT
   825 void ConcurrentMarkSweepGeneration::print_statistics() {
   826   cmsSpace()->printFLCensus(0);
   827 }
   828 #endif
   830 void ConcurrentMarkSweepGeneration::printOccupancy(const char *s) {
   831   GenCollectedHeap* gch = GenCollectedHeap::heap();
   832   if (PrintGCDetails) {
   833     if (Verbose) {
   834       gclog_or_tty->print("[%d %s-%s: "SIZE_FORMAT"("SIZE_FORMAT")]",
   835         level(), short_name(), s, used(), capacity());
   836     } else {
   837       gclog_or_tty->print("[%d %s-%s: "SIZE_FORMAT"K("SIZE_FORMAT"K)]",
   838         level(), short_name(), s, used() / K, capacity() / K);
   839     }
   840   }
   841   if (Verbose) {
   842     gclog_or_tty->print(" "SIZE_FORMAT"("SIZE_FORMAT")",
   843               gch->used(), gch->capacity());
   844   } else {
   845     gclog_or_tty->print(" "SIZE_FORMAT"K("SIZE_FORMAT"K)",
   846               gch->used() / K, gch->capacity() / K);
   847   }
   848 }
   850 size_t
   851 ConcurrentMarkSweepGeneration::contiguous_available() const {
   852   // dld proposes an improvement in precision here. If the committed
   853   // part of the space ends in a free block we should add that to
   854   // uncommitted size in the calculation below. Will make this
   855   // change later, staying with the approximation below for the
   856   // time being. -- ysr.
   857   return MAX2(_virtual_space.uncommitted_size(), unsafe_max_alloc_nogc());
   858 }
   860 size_t
   861 ConcurrentMarkSweepGeneration::unsafe_max_alloc_nogc() const {
   862   return _cmsSpace->max_alloc_in_words() * HeapWordSize;
   863 }
   865 size_t ConcurrentMarkSweepGeneration::max_available() const {
   866   return free() + _virtual_space.uncommitted_size();
   867 }
   869 bool ConcurrentMarkSweepGeneration::promotion_attempt_is_safe(size_t max_promotion_in_bytes) const {
   870   size_t available = max_available();
   871   size_t av_promo  = (size_t)gc_stats()->avg_promoted()->padded_average();
   872   bool   res = (available >= av_promo) || (available >= max_promotion_in_bytes);
   873   if (Verbose && PrintGCDetails) {
   874     gclog_or_tty->print_cr(
   875       "CMS: promo attempt is%s safe: available("SIZE_FORMAT") %s av_promo("SIZE_FORMAT"),"
   876       "max_promo("SIZE_FORMAT")",
   877       res? "":" not", available, res? ">=":"<",
   878       av_promo, max_promotion_in_bytes);
   879   }
   880   return res;
   881 }
   883 // At a promotion failure dump information on block layout in heap
   884 // (cms old generation).
   885 void ConcurrentMarkSweepGeneration::promotion_failure_occurred() {
   886   if (CMSDumpAtPromotionFailure) {
   887     cmsSpace()->dump_at_safepoint_with_locks(collector(), gclog_or_tty);
   888   }
   889 }
   891 CompactibleSpace*
   892 ConcurrentMarkSweepGeneration::first_compaction_space() const {
   893   return _cmsSpace;
   894 }
   896 void ConcurrentMarkSweepGeneration::reset_after_compaction() {
   897   // Clear the promotion information.  These pointers can be adjusted
   898   // along with all the other pointers into the heap but
   899   // compaction is expected to be a rare event with
   900   // a heap using cms so don't do it without seeing the need.
   901   if (CollectedHeap::use_parallel_gc_threads()) {
   902     for (uint i = 0; i < ParallelGCThreads; i++) {
   903       _par_gc_thread_states[i]->promo.reset();
   904     }
   905   }
   906 }
   908 void ConcurrentMarkSweepGeneration::space_iterate(SpaceClosure* blk, bool usedOnly) {
   909   blk->do_space(_cmsSpace);
   910 }
   912 void ConcurrentMarkSweepGeneration::compute_new_size() {
   913   assert_locked_or_safepoint(Heap_lock);
   915   // If incremental collection failed, we just want to expand
   916   // to the limit.
   917   if (incremental_collection_failed()) {
   918     clear_incremental_collection_failed();
   919     grow_to_reserved();
   920     return;
   921   }
   923   // The heap has been compacted but not reset yet.
   924   // Any metric such as free() or used() will be incorrect.
   926   CardGeneration::compute_new_size();
   928   // Reset again after a possible resizing
   929   if (did_compact()) {
   930     cmsSpace()->reset_after_compaction();
   931   }
   932 }
   934 void ConcurrentMarkSweepGeneration::compute_new_size_free_list() {
   935   assert_locked_or_safepoint(Heap_lock);
   937   // If incremental collection failed, we just want to expand
   938   // to the limit.
   939   if (incremental_collection_failed()) {
   940     clear_incremental_collection_failed();
   941     grow_to_reserved();
   942     return;
   943   }
   945   double free_percentage = ((double) free()) / capacity();
   946   double desired_free_percentage = (double) MinHeapFreeRatio / 100;
   947   double maximum_free_percentage = (double) MaxHeapFreeRatio / 100;
   949   // compute expansion delta needed for reaching desired free percentage
   950   if (free_percentage < desired_free_percentage) {
   951     size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage));
   952     assert(desired_capacity >= capacity(), "invalid expansion size");
   953     size_t expand_bytes = MAX2(desired_capacity - capacity(), MinHeapDeltaBytes);
   954     if (PrintGCDetails && Verbose) {
   955       size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage));
   956       gclog_or_tty->print_cr("\nFrom compute_new_size: ");
   957       gclog_or_tty->print_cr("  Free fraction %f", free_percentage);
   958       gclog_or_tty->print_cr("  Desired free fraction %f",
   959         desired_free_percentage);
   960       gclog_or_tty->print_cr("  Maximum free fraction %f",
   961         maximum_free_percentage);
   962       gclog_or_tty->print_cr("  Capactiy "SIZE_FORMAT, capacity()/1000);
   963       gclog_or_tty->print_cr("  Desired capacity "SIZE_FORMAT,
   964         desired_capacity/1000);
   965       int prev_level = level() - 1;
   966       if (prev_level >= 0) {
   967         size_t prev_size = 0;
   968         GenCollectedHeap* gch = GenCollectedHeap::heap();
   969         Generation* prev_gen = gch->_gens[prev_level];
   970         prev_size = prev_gen->capacity();
   971           gclog_or_tty->print_cr("  Younger gen size "SIZE_FORMAT,
   972                                  prev_size/1000);
   973       }
   974       gclog_or_tty->print_cr("  unsafe_max_alloc_nogc "SIZE_FORMAT,
   975         unsafe_max_alloc_nogc()/1000);
   976       gclog_or_tty->print_cr("  contiguous available "SIZE_FORMAT,
   977         contiguous_available()/1000);
   978       gclog_or_tty->print_cr("  Expand by "SIZE_FORMAT" (bytes)",
   979         expand_bytes);
   980     }
   981     // safe if expansion fails
   982     expand(expand_bytes, 0, CMSExpansionCause::_satisfy_free_ratio);
   983     if (PrintGCDetails && Verbose) {
   984       gclog_or_tty->print_cr("  Expanded free fraction %f",
   985         ((double) free()) / capacity());
   986     }
   987   } else {
   988     size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage));
   989     assert(desired_capacity <= capacity(), "invalid expansion size");
   990     size_t shrink_bytes = capacity() - desired_capacity;
   991     // Don't shrink unless the delta is greater than the minimum shrink we want
   992     if (shrink_bytes >= MinHeapDeltaBytes) {
   993       shrink_free_list_by(shrink_bytes);
   994     }
   995   }
   996 }
   998 Mutex* ConcurrentMarkSweepGeneration::freelistLock() const {
   999   return cmsSpace()->freelistLock();
  1002 HeapWord* ConcurrentMarkSweepGeneration::allocate(size_t size,
  1003                                                   bool   tlab) {
  1004   CMSSynchronousYieldRequest yr;
  1005   MutexLockerEx x(freelistLock(),
  1006                   Mutex::_no_safepoint_check_flag);
  1007   return have_lock_and_allocate(size, tlab);
  1010 HeapWord* ConcurrentMarkSweepGeneration::have_lock_and_allocate(size_t size,
  1011                                                   bool   tlab /* ignored */) {
  1012   assert_lock_strong(freelistLock());
  1013   size_t adjustedSize = CompactibleFreeListSpace::adjustObjectSize(size);
  1014   HeapWord* res = cmsSpace()->allocate(adjustedSize);
  1015   // Allocate the object live (grey) if the background collector has
  1016   // started marking. This is necessary because the marker may
  1017   // have passed this address and consequently this object will
  1018   // not otherwise be greyed and would be incorrectly swept up.
  1019   // Note that if this object contains references, the writing
  1020   // of those references will dirty the card containing this object
  1021   // allowing the object to be blackened (and its references scanned)
  1022   // either during a preclean phase or at the final checkpoint.
  1023   if (res != NULL) {
  1024     // We may block here with an uninitialized object with
  1025     // its mark-bit or P-bits not yet set. Such objects need
  1026     // to be safely navigable by block_start().
  1027     assert(oop(res)->klass_or_null() == NULL, "Object should be uninitialized here.");
  1028     assert(!((FreeChunk*)res)->is_free(), "Error, block will look free but show wrong size");
  1029     collector()->direct_allocated(res, adjustedSize);
  1030     _direct_allocated_words += adjustedSize;
  1031     // allocation counters
  1032     NOT_PRODUCT(
  1033       _numObjectsAllocated++;
  1034       _numWordsAllocated += (int)adjustedSize;
  1037   return res;
  1040 // In the case of direct allocation by mutators in a generation that
  1041 // is being concurrently collected, the object must be allocated
  1042 // live (grey) if the background collector has started marking.
  1043 // This is necessary because the marker may
  1044 // have passed this address and consequently this object will
  1045 // not otherwise be greyed and would be incorrectly swept up.
  1046 // Note that if this object contains references, the writing
  1047 // of those references will dirty the card containing this object
  1048 // allowing the object to be blackened (and its references scanned)
  1049 // either during a preclean phase or at the final checkpoint.
  1050 void CMSCollector::direct_allocated(HeapWord* start, size_t size) {
  1051   assert(_markBitMap.covers(start, size), "Out of bounds");
  1052   if (_collectorState >= Marking) {
  1053     MutexLockerEx y(_markBitMap.lock(),
  1054                     Mutex::_no_safepoint_check_flag);
  1055     // [see comments preceding SweepClosure::do_blk() below for details]
  1056     //
  1057     // Can the P-bits be deleted now?  JJJ
  1058     //
  1059     // 1. need to mark the object as live so it isn't collected
  1060     // 2. need to mark the 2nd bit to indicate the object may be uninitialized
  1061     // 3. need to mark the end of the object so marking, precleaning or sweeping
  1062     //    can skip over uninitialized or unparsable objects. An allocated
  1063     //    object is considered uninitialized for our purposes as long as
  1064     //    its klass word is NULL.  All old gen objects are parsable
  1065     //    as soon as they are initialized.)
  1066     _markBitMap.mark(start);          // object is live
  1067     _markBitMap.mark(start + 1);      // object is potentially uninitialized?
  1068     _markBitMap.mark(start + size - 1);
  1069                                       // mark end of object
  1071   // check that oop looks uninitialized
  1072   assert(oop(start)->klass_or_null() == NULL, "_klass should be NULL");
  1075 void CMSCollector::promoted(bool par, HeapWord* start,
  1076                             bool is_obj_array, size_t obj_size) {
  1077   assert(_markBitMap.covers(start), "Out of bounds");
  1078   // See comment in direct_allocated() about when objects should
  1079   // be allocated live.
  1080   if (_collectorState >= Marking) {
  1081     // we already hold the marking bit map lock, taken in
  1082     // the prologue
  1083     if (par) {
  1084       _markBitMap.par_mark(start);
  1085     } else {
  1086       _markBitMap.mark(start);
  1088     // We don't need to mark the object as uninitialized (as
  1089     // in direct_allocated above) because this is being done with the
  1090     // world stopped and the object will be initialized by the
  1091     // time the marking, precleaning or sweeping get to look at it.
  1092     // But see the code for copying objects into the CMS generation,
  1093     // where we need to ensure that concurrent readers of the
  1094     // block offset table are able to safely navigate a block that
  1095     // is in flux from being free to being allocated (and in
  1096     // transition while being copied into) and subsequently
  1097     // becoming a bona-fide object when the copy/promotion is complete.
  1098     assert(SafepointSynchronize::is_at_safepoint(),
  1099            "expect promotion only at safepoints");
  1101     if (_collectorState < Sweeping) {
  1102       // Mark the appropriate cards in the modUnionTable, so that
  1103       // this object gets scanned before the sweep. If this is
  1104       // not done, CMS generation references in the object might
  1105       // not get marked.
  1106       // For the case of arrays, which are otherwise precisely
  1107       // marked, we need to dirty the entire array, not just its head.
  1108       if (is_obj_array) {
  1109         // The [par_]mark_range() method expects mr.end() below to
  1110         // be aligned to the granularity of a bit's representation
  1111         // in the heap. In the case of the MUT below, that's a
  1112         // card size.
  1113         MemRegion mr(start,
  1114                      (HeapWord*)round_to((intptr_t)(start + obj_size),
  1115                         CardTableModRefBS::card_size /* bytes */));
  1116         if (par) {
  1117           _modUnionTable.par_mark_range(mr);
  1118         } else {
  1119           _modUnionTable.mark_range(mr);
  1121       } else {  // not an obj array; we can just mark the head
  1122         if (par) {
  1123           _modUnionTable.par_mark(start);
  1124         } else {
  1125           _modUnionTable.mark(start);
  1132 static inline size_t percent_of_space(Space* space, HeapWord* addr)
  1134   size_t delta = pointer_delta(addr, space->bottom());
  1135   return (size_t)(delta * 100.0 / (space->capacity() / HeapWordSize));
  1138 void CMSCollector::icms_update_allocation_limits()
  1140   Generation* gen0 = GenCollectedHeap::heap()->get_gen(0);
  1141   EdenSpace* eden = gen0->as_DefNewGeneration()->eden();
  1143   const unsigned int duty_cycle = stats().icms_update_duty_cycle();
  1144   if (CMSTraceIncrementalPacing) {
  1145     stats().print();
  1148   assert(duty_cycle <= 100, "invalid duty cycle");
  1149   if (duty_cycle != 0) {
  1150     // The duty_cycle is a percentage between 0 and 100; convert to words and
  1151     // then compute the offset from the endpoints of the space.
  1152     size_t free_words = eden->free() / HeapWordSize;
  1153     double free_words_dbl = (double)free_words;
  1154     size_t duty_cycle_words = (size_t)(free_words_dbl * duty_cycle / 100.0);
  1155     size_t offset_words = (free_words - duty_cycle_words) / 2;
  1157     _icms_start_limit = eden->top() + offset_words;
  1158     _icms_stop_limit = eden->end() - offset_words;
  1160     // The limits may be adjusted (shifted to the right) by
  1161     // CMSIncrementalOffset, to allow the application more mutator time after a
  1162     // young gen gc (when all mutators were stopped) and before CMS starts and
  1163     // takes away one or more cpus.
  1164     if (CMSIncrementalOffset != 0) {
  1165       double adjustment_dbl = free_words_dbl * CMSIncrementalOffset / 100.0;
  1166       size_t adjustment = (size_t)adjustment_dbl;
  1167       HeapWord* tmp_stop = _icms_stop_limit + adjustment;
  1168       if (tmp_stop > _icms_stop_limit && tmp_stop < eden->end()) {
  1169         _icms_start_limit += adjustment;
  1170         _icms_stop_limit = tmp_stop;
  1174   if (duty_cycle == 0 || (_icms_start_limit == _icms_stop_limit)) {
  1175     _icms_start_limit = _icms_stop_limit = eden->end();
  1178   // Install the new start limit.
  1179   eden->set_soft_end(_icms_start_limit);
  1181   if (CMSTraceIncrementalMode) {
  1182     gclog_or_tty->print(" icms alloc limits:  "
  1183                            PTR_FORMAT "," PTR_FORMAT
  1184                            " (" SIZE_FORMAT "%%," SIZE_FORMAT "%%) ",
  1185                            p2i(_icms_start_limit), p2i(_icms_stop_limit),
  1186                            percent_of_space(eden, _icms_start_limit),
  1187                            percent_of_space(eden, _icms_stop_limit));
  1188     if (Verbose) {
  1189       gclog_or_tty->print("eden:  ");
  1190       eden->print_on(gclog_or_tty);
  1195 // Any changes here should try to maintain the invariant
  1196 // that if this method is called with _icms_start_limit
  1197 // and _icms_stop_limit both NULL, then it should return NULL
  1198 // and not notify the icms thread.
  1199 HeapWord*
  1200 CMSCollector::allocation_limit_reached(Space* space, HeapWord* top,
  1201                                        size_t word_size)
  1203   // A start_limit equal to end() means the duty cycle is 0, so treat that as a
  1204   // nop.
  1205   if (CMSIncrementalMode && _icms_start_limit != space->end()) {
  1206     if (top <= _icms_start_limit) {
  1207       if (CMSTraceIncrementalMode) {
  1208         space->print_on(gclog_or_tty);
  1209         gclog_or_tty->stamp();
  1210         gclog_or_tty->print_cr(" start limit top=" PTR_FORMAT
  1211                                ", new limit=" PTR_FORMAT
  1212                                " (" SIZE_FORMAT "%%)",
  1213                                p2i(top), p2i(_icms_stop_limit),
  1214                                percent_of_space(space, _icms_stop_limit));
  1216       ConcurrentMarkSweepThread::start_icms();
  1217       assert(top < _icms_stop_limit, "Tautology");
  1218       if (word_size < pointer_delta(_icms_stop_limit, top)) {
  1219         return _icms_stop_limit;
  1222       // The allocation will cross both the _start and _stop limits, so do the
  1223       // stop notification also and return end().
  1224       if (CMSTraceIncrementalMode) {
  1225         space->print_on(gclog_or_tty);
  1226         gclog_or_tty->stamp();
  1227         gclog_or_tty->print_cr(" +stop limit top=" PTR_FORMAT
  1228                                ", new limit=" PTR_FORMAT
  1229                                " (" SIZE_FORMAT "%%)",
  1230                                p2i(top), p2i(space->end()),
  1231                                percent_of_space(space, space->end()));
  1233       ConcurrentMarkSweepThread::stop_icms();
  1234       return space->end();
  1237     if (top <= _icms_stop_limit) {
  1238       if (CMSTraceIncrementalMode) {
  1239         space->print_on(gclog_or_tty);
  1240         gclog_or_tty->stamp();
  1241         gclog_or_tty->print_cr(" stop limit top=" PTR_FORMAT
  1242                                ", new limit=" PTR_FORMAT
  1243                                " (" SIZE_FORMAT "%%)",
  1244                                top, space->end(),
  1245                                percent_of_space(space, space->end()));
  1247       ConcurrentMarkSweepThread::stop_icms();
  1248       return space->end();
  1251     if (CMSTraceIncrementalMode) {
  1252       space->print_on(gclog_or_tty);
  1253       gclog_or_tty->stamp();
  1254       gclog_or_tty->print_cr(" end limit top=" PTR_FORMAT
  1255                              ", new limit=" PTR_FORMAT,
  1256                              top, NULL);
  1260   return NULL;
  1263 oop ConcurrentMarkSweepGeneration::promote(oop obj, size_t obj_size) {
  1264   assert(obj_size == (size_t)obj->size(), "bad obj_size passed in");
  1265   // allocate, copy and if necessary update promoinfo --
  1266   // delegate to underlying space.
  1267   assert_lock_strong(freelistLock());
  1269 #ifndef PRODUCT
  1270   if (Universe::heap()->promotion_should_fail()) {
  1271     return NULL;
  1273 #endif  // #ifndef PRODUCT
  1275   oop res = _cmsSpace->promote(obj, obj_size);
  1276   if (res == NULL) {
  1277     // expand and retry
  1278     size_t s = _cmsSpace->expansionSpaceRequired(obj_size);  // HeapWords
  1279     expand(s*HeapWordSize, MinHeapDeltaBytes,
  1280       CMSExpansionCause::_satisfy_promotion);
  1281     // Since there's currently no next generation, we don't try to promote
  1282     // into a more senior generation.
  1283     assert(next_gen() == NULL, "assumption, based upon which no attempt "
  1284                                "is made to pass on a possibly failing "
  1285                                "promotion to next generation");
  1286     res = _cmsSpace->promote(obj, obj_size);
  1288   if (res != NULL) {
  1289     // See comment in allocate() about when objects should
  1290     // be allocated live.
  1291     assert(obj->is_oop(), "Will dereference klass pointer below");
  1292     collector()->promoted(false,           // Not parallel
  1293                           (HeapWord*)res, obj->is_objArray(), obj_size);
  1294     // promotion counters
  1295     NOT_PRODUCT(
  1296       _numObjectsPromoted++;
  1297       _numWordsPromoted +=
  1298         (int)(CompactibleFreeListSpace::adjustObjectSize(obj->size()));
  1301   return res;
  1305 HeapWord*
  1306 ConcurrentMarkSweepGeneration::allocation_limit_reached(Space* space,
  1307                                              HeapWord* top,
  1308                                              size_t word_sz)
  1310   return collector()->allocation_limit_reached(space, top, word_sz);
  1313 // IMPORTANT: Notes on object size recognition in CMS.
  1314 // ---------------------------------------------------
  1315 // A block of storage in the CMS generation is always in
  1316 // one of three states. A free block (FREE), an allocated
  1317 // object (OBJECT) whose size() method reports the correct size,
  1318 // and an intermediate state (TRANSIENT) in which its size cannot
  1319 // be accurately determined.
  1320 // STATE IDENTIFICATION:   (32 bit and 64 bit w/o COOPS)
  1321 // -----------------------------------------------------
  1322 // FREE:      klass_word & 1 == 1; mark_word holds block size
  1323 //
  1324 // OBJECT:    klass_word installed; klass_word != 0 && klass_word & 1 == 0;
  1325 //            obj->size() computes correct size
  1326 //
  1327 // TRANSIENT: klass_word == 0; size is indeterminate until we become an OBJECT
  1328 //
  1329 // STATE IDENTIFICATION: (64 bit+COOPS)
  1330 // ------------------------------------
  1331 // FREE:      mark_word & CMS_FREE_BIT == 1; mark_word & ~CMS_FREE_BIT gives block_size
  1332 //
  1333 // OBJECT:    klass_word installed; klass_word != 0;
  1334 //            obj->size() computes correct size
  1335 //
  1336 // TRANSIENT: klass_word == 0; size is indeterminate until we become an OBJECT
  1337 //
  1338 //
  1339 // STATE TRANSITION DIAGRAM
  1340 //
  1341 //        mut / parnew                     mut  /  parnew
  1342 // FREE --------------------> TRANSIENT ---------------------> OBJECT --|
  1343 //  ^                                                                   |
  1344 //  |------------------------ DEAD <------------------------------------|
  1345 //         sweep                            mut
  1346 //
  1347 // While a block is in TRANSIENT state its size cannot be determined
  1348 // so readers will either need to come back later or stall until
  1349 // the size can be determined. Note that for the case of direct
  1350 // allocation, P-bits, when available, may be used to determine the
  1351 // size of an object that may not yet have been initialized.
  1353 // Things to support parallel young-gen collection.
  1354 oop
  1355 ConcurrentMarkSweepGeneration::par_promote(int thread_num,
  1356                                            oop old, markOop m,
  1357                                            size_t word_sz) {
  1358 #ifndef PRODUCT
  1359   if (Universe::heap()->promotion_should_fail()) {
  1360     return NULL;
  1362 #endif  // #ifndef PRODUCT
  1364   CMSParGCThreadState* ps = _par_gc_thread_states[thread_num];
  1365   PromotionInfo* promoInfo = &ps->promo;
  1366   // if we are tracking promotions, then first ensure space for
  1367   // promotion (including spooling space for saving header if necessary).
  1368   // then allocate and copy, then track promoted info if needed.
  1369   // When tracking (see PromotionInfo::track()), the mark word may
  1370   // be displaced and in this case restoration of the mark word
  1371   // occurs in the (oop_since_save_marks_)iterate phase.
  1372   if (promoInfo->tracking() && !promoInfo->ensure_spooling_space()) {
  1373     // Out of space for allocating spooling buffers;
  1374     // try expanding and allocating spooling buffers.
  1375     if (!expand_and_ensure_spooling_space(promoInfo)) {
  1376       return NULL;
  1379   assert(promoInfo->has_spooling_space(), "Control point invariant");
  1380   const size_t alloc_sz = CompactibleFreeListSpace::adjustObjectSize(word_sz);
  1381   HeapWord* obj_ptr = ps->lab.alloc(alloc_sz);
  1382   if (obj_ptr == NULL) {
  1383      obj_ptr = expand_and_par_lab_allocate(ps, alloc_sz);
  1384      if (obj_ptr == NULL) {
  1385        return NULL;
  1388   oop obj = oop(obj_ptr);
  1389   OrderAccess::storestore();
  1390   assert(obj->klass_or_null() == NULL, "Object should be uninitialized here.");
  1391   assert(!((FreeChunk*)obj_ptr)->is_free(), "Error, block will look free but show wrong size");
  1392   // IMPORTANT: See note on object initialization for CMS above.
  1393   // Otherwise, copy the object.  Here we must be careful to insert the
  1394   // klass pointer last, since this marks the block as an allocated object.
  1395   // Except with compressed oops it's the mark word.
  1396   HeapWord* old_ptr = (HeapWord*)old;
  1397   // Restore the mark word copied above.
  1398   obj->set_mark(m);
  1399   assert(obj->klass_or_null() == NULL, "Object should be uninitialized here.");
  1400   assert(!((FreeChunk*)obj_ptr)->is_free(), "Error, block will look free but show wrong size");
  1401   OrderAccess::storestore();
  1403   if (UseCompressedClassPointers) {
  1404     // Copy gap missed by (aligned) header size calculation below
  1405     obj->set_klass_gap(old->klass_gap());
  1407   if (word_sz > (size_t)oopDesc::header_size()) {
  1408     Copy::aligned_disjoint_words(old_ptr + oopDesc::header_size(),
  1409                                  obj_ptr + oopDesc::header_size(),
  1410                                  word_sz - oopDesc::header_size());
  1413   // Now we can track the promoted object, if necessary.  We take care
  1414   // to delay the transition from uninitialized to full object
  1415   // (i.e., insertion of klass pointer) until after, so that it
  1416   // atomically becomes a promoted object.
  1417   if (promoInfo->tracking()) {
  1418     promoInfo->track((PromotedObject*)obj, old->klass());
  1420   assert(obj->klass_or_null() == NULL, "Object should be uninitialized here.");
  1421   assert(!((FreeChunk*)obj_ptr)->is_free(), "Error, block will look free but show wrong size");
  1422   assert(old->is_oop(), "Will use and dereference old klass ptr below");
  1424   // Finally, install the klass pointer (this should be volatile).
  1425   OrderAccess::storestore();
  1426   obj->set_klass(old->klass());
  1427   // We should now be able to calculate the right size for this object
  1428   assert(obj->is_oop() && obj->size() == (int)word_sz, "Error, incorrect size computed for promoted object");
  1430   collector()->promoted(true,          // parallel
  1431                         obj_ptr, old->is_objArray(), word_sz);
  1433   NOT_PRODUCT(
  1434     Atomic::inc_ptr(&_numObjectsPromoted);
  1435     Atomic::add_ptr(alloc_sz, &_numWordsPromoted);
  1438   return obj;
  1441 void
  1442 ConcurrentMarkSweepGeneration::
  1443 par_promote_alloc_undo(int thread_num,
  1444                        HeapWord* obj, size_t word_sz) {
  1445   // CMS does not support promotion undo.
  1446   ShouldNotReachHere();
  1449 void
  1450 ConcurrentMarkSweepGeneration::
  1451 par_promote_alloc_done(int thread_num) {
  1452   CMSParGCThreadState* ps = _par_gc_thread_states[thread_num];
  1453   ps->lab.retire(thread_num);
  1456 void
  1457 ConcurrentMarkSweepGeneration::
  1458 par_oop_since_save_marks_iterate_done(int thread_num) {
  1459   CMSParGCThreadState* ps = _par_gc_thread_states[thread_num];
  1460   ParScanWithoutBarrierClosure* dummy_cl = NULL;
  1461   ps->promo.promoted_oops_iterate_nv(dummy_cl);
  1464 bool ConcurrentMarkSweepGeneration::should_collect(bool   full,
  1465                                                    size_t size,
  1466                                                    bool   tlab)
  1468   // We allow a STW collection only if a full
  1469   // collection was requested.
  1470   return full || should_allocate(size, tlab); // FIX ME !!!
  1471   // This and promotion failure handling are connected at the
  1472   // hip and should be fixed by untying them.
  1475 bool CMSCollector::shouldConcurrentCollect() {
  1476   if (_full_gc_requested) {
  1477     if (Verbose && PrintGCDetails) {
  1478       gclog_or_tty->print_cr("CMSCollector: collect because of explicit "
  1479                              " gc request (or gc_locker)");
  1481     return true;
  1484   // For debugging purposes, change the type of collection.
  1485   // If the rotation is not on the concurrent collection
  1486   // type, don't start a concurrent collection.
  1487   NOT_PRODUCT(
  1488     if (RotateCMSCollectionTypes &&
  1489         (_cmsGen->debug_collection_type() !=
  1490           ConcurrentMarkSweepGeneration::Concurrent_collection_type)) {
  1491       assert(_cmsGen->debug_collection_type() !=
  1492         ConcurrentMarkSweepGeneration::Unknown_collection_type,
  1493         "Bad cms collection type");
  1494       return false;
  1498   FreelistLocker x(this);
  1499   // ------------------------------------------------------------------
  1500   // Print out lots of information which affects the initiation of
  1501   // a collection.
  1502   if (PrintCMSInitiationStatistics && stats().valid()) {
  1503     gclog_or_tty->print("CMSCollector shouldConcurrentCollect: ");
  1504     gclog_or_tty->stamp();
  1505     gclog_or_tty->cr();
  1506     stats().print_on(gclog_or_tty);
  1507     gclog_or_tty->print_cr("time_until_cms_gen_full %3.7f",
  1508       stats().time_until_cms_gen_full());
  1509     gclog_or_tty->print_cr("free="SIZE_FORMAT, _cmsGen->free());
  1510     gclog_or_tty->print_cr("contiguous_available="SIZE_FORMAT,
  1511                            _cmsGen->contiguous_available());
  1512     gclog_or_tty->print_cr("promotion_rate=%g", stats().promotion_rate());
  1513     gclog_or_tty->print_cr("cms_allocation_rate=%g", stats().cms_allocation_rate());
  1514     gclog_or_tty->print_cr("occupancy=%3.7f", _cmsGen->occupancy());
  1515     gclog_or_tty->print_cr("initiatingOccupancy=%3.7f", _cmsGen->initiating_occupancy());
  1516     gclog_or_tty->print_cr("metadata initialized %d",
  1517       MetaspaceGC::should_concurrent_collect());
  1519   // ------------------------------------------------------------------
  1521   // If the estimated time to complete a cms collection (cms_duration())
  1522   // is less than the estimated time remaining until the cms generation
  1523   // is full, start a collection.
  1524   if (!UseCMSInitiatingOccupancyOnly) {
  1525     if (stats().valid()) {
  1526       if (stats().time_until_cms_start() == 0.0) {
  1527         return true;
  1529     } else {
  1530       // We want to conservatively collect somewhat early in order
  1531       // to try and "bootstrap" our CMS/promotion statistics;
  1532       // this branch will not fire after the first successful CMS
  1533       // collection because the stats should then be valid.
  1534       if (_cmsGen->occupancy() >= _bootstrap_occupancy) {
  1535         if (Verbose && PrintGCDetails) {
  1536           gclog_or_tty->print_cr(
  1537             " CMSCollector: collect for bootstrapping statistics:"
  1538             " occupancy = %f, boot occupancy = %f", _cmsGen->occupancy(),
  1539             _bootstrap_occupancy);
  1541         return true;
  1546   // Otherwise, we start a collection cycle if
  1547   // old gen want a collection cycle started. Each may use
  1548   // an appropriate criterion for making this decision.
  1549   // XXX We need to make sure that the gen expansion
  1550   // criterion dovetails well with this. XXX NEED TO FIX THIS
  1551   if (_cmsGen->should_concurrent_collect()) {
  1552     if (Verbose && PrintGCDetails) {
  1553       gclog_or_tty->print_cr("CMS old gen initiated");
  1555     return true;
  1558   // We start a collection if we believe an incremental collection may fail;
  1559   // this is not likely to be productive in practice because it's probably too
  1560   // late anyway.
  1561   GenCollectedHeap* gch = GenCollectedHeap::heap();
  1562   assert(gch->collector_policy()->is_two_generation_policy(),
  1563          "You may want to check the correctness of the following");
  1564   if (gch->incremental_collection_will_fail(true /* consult_young */)) {
  1565     if (Verbose && PrintGCDetails) {
  1566       gclog_or_tty->print("CMSCollector: collect because incremental collection will fail ");
  1568     return true;
  1571   if (MetaspaceGC::should_concurrent_collect()) {
  1572       if (Verbose && PrintGCDetails) {
  1573       gclog_or_tty->print("CMSCollector: collect for metadata allocation ");
  1575       return true;
  1578   return false;
  1581 void CMSCollector::set_did_compact(bool v) { _cmsGen->set_did_compact(v); }
  1583 // Clear _expansion_cause fields of constituent generations
  1584 void CMSCollector::clear_expansion_cause() {
  1585   _cmsGen->clear_expansion_cause();
  1588 // We should be conservative in starting a collection cycle.  To
  1589 // start too eagerly runs the risk of collecting too often in the
  1590 // extreme.  To collect too rarely falls back on full collections,
  1591 // which works, even if not optimum in terms of concurrent work.
  1592 // As a work around for too eagerly collecting, use the flag
  1593 // UseCMSInitiatingOccupancyOnly.  This also has the advantage of
  1594 // giving the user an easily understandable way of controlling the
  1595 // collections.
  1596 // We want to start a new collection cycle if any of the following
  1597 // conditions hold:
  1598 // . our current occupancy exceeds the configured initiating occupancy
  1599 //   for this generation, or
  1600 // . we recently needed to expand this space and have not, since that
  1601 //   expansion, done a collection of this generation, or
  1602 // . the underlying space believes that it may be a good idea to initiate
  1603 //   a concurrent collection (this may be based on criteria such as the
  1604 //   following: the space uses linear allocation and linear allocation is
  1605 //   going to fail, or there is believed to be excessive fragmentation in
  1606 //   the generation, etc... or ...
  1607 // [.(currently done by CMSCollector::shouldConcurrentCollect() only for
  1608 //   the case of the old generation; see CR 6543076):
  1609 //   we may be approaching a point at which allocation requests may fail because
  1610 //   we will be out of sufficient free space given allocation rate estimates.]
  1611 bool ConcurrentMarkSweepGeneration::should_concurrent_collect() const {
  1613   assert_lock_strong(freelistLock());
  1614   if (occupancy() > initiating_occupancy()) {
  1615     if (PrintGCDetails && Verbose) {
  1616       gclog_or_tty->print(" %s: collect because of occupancy %f / %f  ",
  1617         short_name(), occupancy(), initiating_occupancy());
  1619     return true;
  1621   if (UseCMSInitiatingOccupancyOnly) {
  1622     return false;
  1624   if (expansion_cause() == CMSExpansionCause::_satisfy_allocation) {
  1625     if (PrintGCDetails && Verbose) {
  1626       gclog_or_tty->print(" %s: collect because expanded for allocation ",
  1627         short_name());
  1629     return true;
  1631   if (_cmsSpace->should_concurrent_collect()) {
  1632     if (PrintGCDetails && Verbose) {
  1633       gclog_or_tty->print(" %s: collect because cmsSpace says so ",
  1634         short_name());
  1636     return true;
  1638   return false;
  1641 void ConcurrentMarkSweepGeneration::collect(bool   full,
  1642                                             bool   clear_all_soft_refs,
  1643                                             size_t size,
  1644                                             bool   tlab)
  1646   collector()->collect(full, clear_all_soft_refs, size, tlab);
  1649 void CMSCollector::collect(bool   full,
  1650                            bool   clear_all_soft_refs,
  1651                            size_t size,
  1652                            bool   tlab)
  1654   if (!UseCMSCollectionPassing && _collectorState > Idling) {
  1655     // For debugging purposes skip the collection if the state
  1656     // is not currently idle
  1657     if (TraceCMSState) {
  1658       gclog_or_tty->print_cr("Thread " INTPTR_FORMAT " skipped full:%d CMS state %d",
  1659         Thread::current(), full, _collectorState);
  1661     return;
  1664   // The following "if" branch is present for defensive reasons.
  1665   // In the current uses of this interface, it can be replaced with:
  1666   // assert(!GC_locker.is_active(), "Can't be called otherwise");
  1667   // But I am not placing that assert here to allow future
  1668   // generality in invoking this interface.
  1669   if (GC_locker::is_active()) {
  1670     // A consistency test for GC_locker
  1671     assert(GC_locker::needs_gc(), "Should have been set already");
  1672     // Skip this foreground collection, instead
  1673     // expanding the heap if necessary.
  1674     // Need the free list locks for the call to free() in compute_new_size()
  1675     compute_new_size();
  1676     return;
  1678   acquire_control_and_collect(full, clear_all_soft_refs);
  1679   _full_gcs_since_conc_gc++;
  1682 void CMSCollector::request_full_gc(unsigned int full_gc_count, GCCause::Cause cause) {
  1683   GenCollectedHeap* gch = GenCollectedHeap::heap();
  1684   unsigned int gc_count = gch->total_full_collections();
  1685   if (gc_count == full_gc_count) {
  1686     MutexLockerEx y(CGC_lock, Mutex::_no_safepoint_check_flag);
  1687     _full_gc_requested = true;
  1688     _full_gc_cause = cause;
  1689     CGC_lock->notify();   // nudge CMS thread
  1690   } else {
  1691     assert(gc_count > full_gc_count, "Error: causal loop");
  1695 bool CMSCollector::is_external_interruption() {
  1696   GCCause::Cause cause = GenCollectedHeap::heap()->gc_cause();
  1697   return GCCause::is_user_requested_gc(cause) ||
  1698          GCCause::is_serviceability_requested_gc(cause);
  1701 void CMSCollector::report_concurrent_mode_interruption() {
  1702   if (is_external_interruption()) {
  1703     if (PrintGCDetails) {
  1704       gclog_or_tty->print(" (concurrent mode interrupted)");
  1706   } else {
  1707     if (PrintGCDetails) {
  1708       gclog_or_tty->print(" (concurrent mode failure)");
  1710     _gc_tracer_cm->report_concurrent_mode_failure();
  1715 // The foreground and background collectors need to coordinate in order
  1716 // to make sure that they do not mutually interfere with CMS collections.
  1717 // When a background collection is active,
  1718 // the foreground collector may need to take over (preempt) and
  1719 // synchronously complete an ongoing collection. Depending on the
  1720 // frequency of the background collections and the heap usage
  1721 // of the application, this preemption can be seldom or frequent.
  1722 // There are only certain
  1723 // points in the background collection that the "collection-baton"
  1724 // can be passed to the foreground collector.
  1725 //
  1726 // The foreground collector will wait for the baton before
  1727 // starting any part of the collection.  The foreground collector
  1728 // will only wait at one location.
  1729 //
  1730 // The background collector will yield the baton before starting a new
  1731 // phase of the collection (e.g., before initial marking, marking from roots,
  1732 // precleaning, final re-mark, sweep etc.)  This is normally done at the head
  1733 // of the loop which switches the phases. The background collector does some
  1734 // of the phases (initial mark, final re-mark) with the world stopped.
  1735 // Because of locking involved in stopping the world,
  1736 // the foreground collector should not block waiting for the background
  1737 // collector when it is doing a stop-the-world phase.  The background
  1738 // collector will yield the baton at an additional point just before
  1739 // it enters a stop-the-world phase.  Once the world is stopped, the
  1740 // background collector checks the phase of the collection.  If the
  1741 // phase has not changed, it proceeds with the collection.  If the
  1742 // phase has changed, it skips that phase of the collection.  See
  1743 // the comments on the use of the Heap_lock in collect_in_background().
  1744 //
  1745 // Variable used in baton passing.
  1746 //   _foregroundGCIsActive - Set to true by the foreground collector when
  1747 //      it wants the baton.  The foreground clears it when it has finished
  1748 //      the collection.
  1749 //   _foregroundGCShouldWait - Set to true by the background collector
  1750 //        when it is running.  The foreground collector waits while
  1751 //      _foregroundGCShouldWait is true.
  1752 //  CGC_lock - monitor used to protect access to the above variables
  1753 //      and to notify the foreground and background collectors.
  1754 //  _collectorState - current state of the CMS collection.
  1755 //
  1756 // The foreground collector
  1757 //   acquires the CGC_lock
  1758 //   sets _foregroundGCIsActive
  1759 //   waits on the CGC_lock for _foregroundGCShouldWait to be false
  1760 //     various locks acquired in preparation for the collection
  1761 //     are released so as not to block the background collector
  1762 //     that is in the midst of a collection
  1763 //   proceeds with the collection
  1764 //   clears _foregroundGCIsActive
  1765 //   returns
  1766 //
  1767 // The background collector in a loop iterating on the phases of the
  1768 //      collection
  1769 //   acquires the CGC_lock
  1770 //   sets _foregroundGCShouldWait
  1771 //   if _foregroundGCIsActive is set
  1772 //     clears _foregroundGCShouldWait, notifies _CGC_lock
  1773 //     waits on _CGC_lock for _foregroundGCIsActive to become false
  1774 //     and exits the loop.
  1775 //   otherwise
  1776 //     proceed with that phase of the collection
  1777 //     if the phase is a stop-the-world phase,
  1778 //       yield the baton once more just before enqueueing
  1779 //       the stop-world CMS operation (executed by the VM thread).
  1780 //   returns after all phases of the collection are done
  1781 //
  1783 void CMSCollector::acquire_control_and_collect(bool full,
  1784         bool clear_all_soft_refs) {
  1785   assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");
  1786   assert(!Thread::current()->is_ConcurrentGC_thread(),
  1787          "shouldn't try to acquire control from self!");
  1789   // Start the protocol for acquiring control of the
  1790   // collection from the background collector (aka CMS thread).
  1791   assert(ConcurrentMarkSweepThread::vm_thread_has_cms_token(),
  1792          "VM thread should have CMS token");
  1793   // Remember the possibly interrupted state of an ongoing
  1794   // concurrent collection
  1795   CollectorState first_state = _collectorState;
  1797   // Signal to a possibly ongoing concurrent collection that
  1798   // we want to do a foreground collection.
  1799   _foregroundGCIsActive = true;
  1801   // Disable incremental mode during a foreground collection.
  1802   ICMSDisabler icms_disabler;
  1804   // release locks and wait for a notify from the background collector
  1805   // releasing the locks in only necessary for phases which
  1806   // do yields to improve the granularity of the collection.
  1807   assert_lock_strong(bitMapLock());
  1808   // We need to lock the Free list lock for the space that we are
  1809   // currently collecting.
  1810   assert(haveFreelistLocks(), "Must be holding free list locks");
  1811   bitMapLock()->unlock();
  1812   releaseFreelistLocks();
  1814     MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
  1815     if (_foregroundGCShouldWait) {
  1816       // We are going to be waiting for action for the CMS thread;
  1817       // it had better not be gone (for instance at shutdown)!
  1818       assert(ConcurrentMarkSweepThread::cmst() != NULL,
  1819              "CMS thread must be running");
  1820       // Wait here until the background collector gives us the go-ahead
  1821       ConcurrentMarkSweepThread::clear_CMS_flag(
  1822         ConcurrentMarkSweepThread::CMS_vm_has_token);  // release token
  1823       // Get a possibly blocked CMS thread going:
  1824       //   Note that we set _foregroundGCIsActive true above,
  1825       //   without protection of the CGC_lock.
  1826       CGC_lock->notify();
  1827       assert(!ConcurrentMarkSweepThread::vm_thread_wants_cms_token(),
  1828              "Possible deadlock");
  1829       while (_foregroundGCShouldWait) {
  1830         // wait for notification
  1831         CGC_lock->wait(Mutex::_no_safepoint_check_flag);
  1832         // Possibility of delay/starvation here, since CMS token does
  1833         // not know to give priority to VM thread? Actually, i think
  1834         // there wouldn't be any delay/starvation, but the proof of
  1835         // that "fact" (?) appears non-trivial. XXX 20011219YSR
  1837       ConcurrentMarkSweepThread::set_CMS_flag(
  1838         ConcurrentMarkSweepThread::CMS_vm_has_token);
  1841   // The CMS_token is already held.  Get back the other locks.
  1842   assert(ConcurrentMarkSweepThread::vm_thread_has_cms_token(),
  1843          "VM thread should have CMS token");
  1844   getFreelistLocks();
  1845   bitMapLock()->lock_without_safepoint_check();
  1846   if (TraceCMSState) {
  1847     gclog_or_tty->print_cr("CMS foreground collector has asked for control "
  1848       INTPTR_FORMAT " with first state %d", Thread::current(), first_state);
  1849     gclog_or_tty->print_cr("    gets control with state %d", _collectorState);
  1852   // Check if we need to do a compaction, or if not, whether
  1853   // we need to start the mark-sweep from scratch.
  1854   bool should_compact    = false;
  1855   bool should_start_over = false;
  1856   decide_foreground_collection_type(clear_all_soft_refs,
  1857     &should_compact, &should_start_over);
  1859 NOT_PRODUCT(
  1860   if (RotateCMSCollectionTypes) {
  1861     if (_cmsGen->debug_collection_type() ==
  1862         ConcurrentMarkSweepGeneration::MSC_foreground_collection_type) {
  1863       should_compact = true;
  1864     } else if (_cmsGen->debug_collection_type() ==
  1865                ConcurrentMarkSweepGeneration::MS_foreground_collection_type) {
  1866       should_compact = false;
  1871   if (first_state > Idling) {
  1872     report_concurrent_mode_interruption();
  1875   set_did_compact(should_compact);
  1876   if (should_compact) {
  1877     // If the collection is being acquired from the background
  1878     // collector, there may be references on the discovered
  1879     // references lists that have NULL referents (being those
  1880     // that were concurrently cleared by a mutator) or
  1881     // that are no longer active (having been enqueued concurrently
  1882     // by the mutator).
  1883     // Scrub the list of those references because Mark-Sweep-Compact
  1884     // code assumes referents are not NULL and that all discovered
  1885     // Reference objects are active.
  1886     ref_processor()->clean_up_discovered_references();
  1888     if (first_state > Idling) {
  1889       save_heap_summary();
  1892     do_compaction_work(clear_all_soft_refs);
  1894     // Has the GC time limit been exceeded?
  1895     DefNewGeneration* young_gen = _young_gen->as_DefNewGeneration();
  1896     size_t max_eden_size = young_gen->max_capacity() -
  1897                            young_gen->to()->capacity() -
  1898                            young_gen->from()->capacity();
  1899     GenCollectedHeap* gch = GenCollectedHeap::heap();
  1900     GCCause::Cause gc_cause = gch->gc_cause();
  1901     size_policy()->check_gc_overhead_limit(_young_gen->used(),
  1902                                            young_gen->eden()->used(),
  1903                                            _cmsGen->max_capacity(),
  1904                                            max_eden_size,
  1905                                            full,
  1906                                            gc_cause,
  1907                                            gch->collector_policy());
  1908   } else {
  1909     do_mark_sweep_work(clear_all_soft_refs, first_state,
  1910       should_start_over);
  1912   // Reset the expansion cause, now that we just completed
  1913   // a collection cycle.
  1914   clear_expansion_cause();
  1915   _foregroundGCIsActive = false;
  1916   return;
  1919 // Resize the tenured generation
  1920 // after obtaining the free list locks for the
  1921 // two generations.
  1922 void CMSCollector::compute_new_size() {
  1923   assert_locked_or_safepoint(Heap_lock);
  1924   FreelistLocker z(this);
  1925   MetaspaceGC::compute_new_size();
  1926   _cmsGen->compute_new_size_free_list();
  1929 // A work method used by foreground collection to determine
  1930 // what type of collection (compacting or not, continuing or fresh)
  1931 // it should do.
  1932 // NOTE: the intent is to make UseCMSCompactAtFullCollection
  1933 // and CMSCompactWhenClearAllSoftRefs the default in the future
  1934 // and do away with the flags after a suitable period.
  1935 void CMSCollector::decide_foreground_collection_type(
  1936   bool clear_all_soft_refs, bool* should_compact,
  1937   bool* should_start_over) {
  1938   // Normally, we'll compact only if the UseCMSCompactAtFullCollection
  1939   // flag is set, and we have either requested a System.gc() or
  1940   // the number of full gc's since the last concurrent cycle
  1941   // has exceeded the threshold set by CMSFullGCsBeforeCompaction,
  1942   // or if an incremental collection has failed
  1943   GenCollectedHeap* gch = GenCollectedHeap::heap();
  1944   assert(gch->collector_policy()->is_two_generation_policy(),
  1945          "You may want to check the correctness of the following");
  1946   // Inform cms gen if this was due to partial collection failing.
  1947   // The CMS gen may use this fact to determine its expansion policy.
  1948   if (gch->incremental_collection_will_fail(false /* don't consult_young */)) {
  1949     assert(!_cmsGen->incremental_collection_failed(),
  1950            "Should have been noticed, reacted to and cleared");
  1951     _cmsGen->set_incremental_collection_failed();
  1953   *should_compact =
  1954     UseCMSCompactAtFullCollection &&
  1955     ((_full_gcs_since_conc_gc >= CMSFullGCsBeforeCompaction) ||
  1956      GCCause::is_user_requested_gc(gch->gc_cause()) ||
  1957      gch->incremental_collection_will_fail(true /* consult_young */));
  1958   *should_start_over = false;
  1959   if (clear_all_soft_refs && !*should_compact) {
  1960     // We are about to do a last ditch collection attempt
  1961     // so it would normally make sense to do a compaction
  1962     // to reclaim as much space as possible.
  1963     if (CMSCompactWhenClearAllSoftRefs) {
  1964       // Default: The rationale is that in this case either
  1965       // we are past the final marking phase, in which case
  1966       // we'd have to start over, or so little has been done
  1967       // that there's little point in saving that work. Compaction
  1968       // appears to be the sensible choice in either case.
  1969       *should_compact = true;
  1970     } else {
  1971       // We have been asked to clear all soft refs, but not to
  1972       // compact. Make sure that we aren't past the final checkpoint
  1973       // phase, for that is where we process soft refs. If we are already
  1974       // past that phase, we'll need to redo the refs discovery phase and
  1975       // if necessary clear soft refs that weren't previously
  1976       // cleared. We do so by remembering the phase in which
  1977       // we came in, and if we are past the refs processing
  1978       // phase, we'll choose to just redo the mark-sweep
  1979       // collection from scratch.
  1980       if (_collectorState > FinalMarking) {
  1981         // We are past the refs processing phase;
  1982         // start over and do a fresh synchronous CMS cycle
  1983         _collectorState = Resetting; // skip to reset to start new cycle
  1984         reset(false /* == !asynch */);
  1985         *should_start_over = true;
  1986       } // else we can continue a possibly ongoing current cycle
  1991 // A work method used by the foreground collector to do
  1992 // a mark-sweep-compact.
  1993 void CMSCollector::do_compaction_work(bool clear_all_soft_refs) {
  1994   GenCollectedHeap* gch = GenCollectedHeap::heap();
  1996   STWGCTimer* gc_timer = GenMarkSweep::gc_timer();
  1997   gc_timer->register_gc_start();
  1999   SerialOldTracer* gc_tracer = GenMarkSweep::gc_tracer();
  2000   gc_tracer->report_gc_start(gch->gc_cause(), gc_timer->gc_start());
  2002   GCTraceTime t("CMS:MSC ", PrintGCDetails && Verbose, true, NULL);
  2003   if (PrintGC && Verbose && !(GCCause::is_user_requested_gc(gch->gc_cause()))) {
  2004     gclog_or_tty->print_cr("Compact ConcurrentMarkSweepGeneration after %d "
  2005       "collections passed to foreground collector", _full_gcs_since_conc_gc);
  2008   // Sample collection interval time and reset for collection pause.
  2009   if (UseAdaptiveSizePolicy) {
  2010     size_policy()->msc_collection_begin();
  2013   // Temporarily widen the span of the weak reference processing to
  2014   // the entire heap.
  2015   MemRegion new_span(GenCollectedHeap::heap()->reserved_region());
  2016   ReferenceProcessorSpanMutator rp_mut_span(ref_processor(), new_span);
  2017   // Temporarily, clear the "is_alive_non_header" field of the
  2018   // reference processor.
  2019   ReferenceProcessorIsAliveMutator rp_mut_closure(ref_processor(), NULL);
  2020   // Temporarily make reference _processing_ single threaded (non-MT).
  2021   ReferenceProcessorMTProcMutator rp_mut_mt_processing(ref_processor(), false);
  2022   // Temporarily make refs discovery atomic
  2023   ReferenceProcessorAtomicMutator rp_mut_atomic(ref_processor(), true);
  2024   // Temporarily make reference _discovery_ single threaded (non-MT)
  2025   ReferenceProcessorMTDiscoveryMutator rp_mut_discovery(ref_processor(), false);
  2027   ref_processor()->set_enqueuing_is_done(false);
  2028   ref_processor()->enable_discovery(false /*verify_disabled*/, false /*check_no_refs*/);
  2029   ref_processor()->setup_policy(clear_all_soft_refs);
  2030   // If an asynchronous collection finishes, the _modUnionTable is
  2031   // all clear.  If we are assuming the collection from an asynchronous
  2032   // collection, clear the _modUnionTable.
  2033   assert(_collectorState != Idling || _modUnionTable.isAllClear(),
  2034     "_modUnionTable should be clear if the baton was not passed");
  2035   _modUnionTable.clear_all();
  2036   assert(_collectorState != Idling || _ct->klass_rem_set()->mod_union_is_clear(),
  2037     "mod union for klasses should be clear if the baton was passed");
  2038   _ct->klass_rem_set()->clear_mod_union();
  2040   // We must adjust the allocation statistics being maintained
  2041   // in the free list space. We do so by reading and clearing
  2042   // the sweep timer and updating the block flux rate estimates below.
  2043   assert(!_intra_sweep_timer.is_active(), "_intra_sweep_timer should be inactive");
  2044   if (_inter_sweep_timer.is_active()) {
  2045     _inter_sweep_timer.stop();
  2046     // Note that we do not use this sample to update the _inter_sweep_estimate.
  2047     _cmsGen->cmsSpace()->beginSweepFLCensus((float)(_inter_sweep_timer.seconds()),
  2048                                             _inter_sweep_estimate.padded_average(),
  2049                                             _intra_sweep_estimate.padded_average());
  2052   GenMarkSweep::invoke_at_safepoint(_cmsGen->level(),
  2053     ref_processor(), clear_all_soft_refs);
  2054   #ifdef ASSERT
  2055     CompactibleFreeListSpace* cms_space = _cmsGen->cmsSpace();
  2056     size_t free_size = cms_space->free();
  2057     assert(free_size ==
  2058            pointer_delta(cms_space->end(), cms_space->compaction_top())
  2059            * HeapWordSize,
  2060       "All the free space should be compacted into one chunk at top");
  2061     assert(cms_space->dictionary()->total_chunk_size(
  2062                                       debug_only(cms_space->freelistLock())) == 0 ||
  2063            cms_space->totalSizeInIndexedFreeLists() == 0,
  2064       "All the free space should be in a single chunk");
  2065     size_t num = cms_space->totalCount();
  2066     assert((free_size == 0 && num == 0) ||
  2067            (free_size > 0  && (num == 1 || num == 2)),
  2068          "There should be at most 2 free chunks after compaction");
  2069   #endif // ASSERT
  2070   _collectorState = Resetting;
  2071   assert(_restart_addr == NULL,
  2072          "Should have been NULL'd before baton was passed");
  2073   reset(false /* == !asynch */);
  2074   _cmsGen->reset_after_compaction();
  2075   _concurrent_cycles_since_last_unload = 0;
  2077   // Clear any data recorded in the PLAB chunk arrays.
  2078   if (_survivor_plab_array != NULL) {
  2079     reset_survivor_plab_arrays();
  2082   // Adjust the per-size allocation stats for the next epoch.
  2083   _cmsGen->cmsSpace()->endSweepFLCensus(sweep_count() /* fake */);
  2084   // Restart the "inter sweep timer" for the next epoch.
  2085   _inter_sweep_timer.reset();
  2086   _inter_sweep_timer.start();
  2088   // Sample collection pause time and reset for collection interval.
  2089   if (UseAdaptiveSizePolicy) {
  2090     size_policy()->msc_collection_end(gch->gc_cause());
  2093   gc_timer->register_gc_end();
  2095   gc_tracer->report_gc_end(gc_timer->gc_end(), gc_timer->time_partitions());
  2097   // For a mark-sweep-compact, compute_new_size() will be called
  2098   // in the heap's do_collection() method.
  2101 // A work method used by the foreground collector to do
  2102 // a mark-sweep, after taking over from a possibly on-going
  2103 // concurrent mark-sweep collection.
  2104 void CMSCollector::do_mark_sweep_work(bool clear_all_soft_refs,
  2105   CollectorState first_state, bool should_start_over) {
  2106   if (PrintGC && Verbose) {
  2107     gclog_or_tty->print_cr("Pass concurrent collection to foreground "
  2108       "collector with count %d",
  2109       _full_gcs_since_conc_gc);
  2111   switch (_collectorState) {
  2112     case Idling:
  2113       if (first_state == Idling || should_start_over) {
  2114         // The background GC was not active, or should
  2115         // restarted from scratch;  start the cycle.
  2116         _collectorState = InitialMarking;
  2118       // If first_state was not Idling, then a background GC
  2119       // was in progress and has now finished.  No need to do it
  2120       // again.  Leave the state as Idling.
  2121       break;
  2122     case Precleaning:
  2123       // In the foreground case don't do the precleaning since
  2124       // it is not done concurrently and there is extra work
  2125       // required.
  2126       _collectorState = FinalMarking;
  2128   collect_in_foreground(clear_all_soft_refs, GenCollectedHeap::heap()->gc_cause());
  2130   // For a mark-sweep, compute_new_size() will be called
  2131   // in the heap's do_collection() method.
  2135 void CMSCollector::print_eden_and_survivor_chunk_arrays() {
  2136   DefNewGeneration* dng = _young_gen->as_DefNewGeneration();
  2137   EdenSpace* eden_space = dng->eden();
  2138   ContiguousSpace* from_space = dng->from();
  2139   ContiguousSpace* to_space   = dng->to();
  2140   // Eden
  2141   if (_eden_chunk_array != NULL) {
  2142     gclog_or_tty->print_cr("eden " PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "(" SIZE_FORMAT ")",
  2143                            eden_space->bottom(), eden_space->top(),
  2144                            eden_space->end(), eden_space->capacity());
  2145     gclog_or_tty->print_cr("_eden_chunk_index=" SIZE_FORMAT ", "
  2146                            "_eden_chunk_capacity=" SIZE_FORMAT,
  2147                            _eden_chunk_index, _eden_chunk_capacity);
  2148     for (size_t i = 0; i < _eden_chunk_index; i++) {
  2149       gclog_or_tty->print_cr("_eden_chunk_array[" SIZE_FORMAT "]=" PTR_FORMAT,
  2150                              i, _eden_chunk_array[i]);
  2153   // Survivor
  2154   if (_survivor_chunk_array != NULL) {
  2155     gclog_or_tty->print_cr("survivor " PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "(" SIZE_FORMAT ")",
  2156                            from_space->bottom(), from_space->top(),
  2157                            from_space->end(), from_space->capacity());
  2158     gclog_or_tty->print_cr("_survivor_chunk_index=" SIZE_FORMAT ", "
  2159                            "_survivor_chunk_capacity=" SIZE_FORMAT,
  2160                            _survivor_chunk_index, _survivor_chunk_capacity);
  2161     for (size_t i = 0; i < _survivor_chunk_index; i++) {
  2162       gclog_or_tty->print_cr("_survivor_chunk_array[" SIZE_FORMAT "]=" PTR_FORMAT,
  2163                              i, _survivor_chunk_array[i]);
  2168 void CMSCollector::getFreelistLocks() const {
  2169   // Get locks for all free lists in all generations that this
  2170   // collector is responsible for
  2171   _cmsGen->freelistLock()->lock_without_safepoint_check();
  2174 void CMSCollector::releaseFreelistLocks() const {
  2175   // Release locks for all free lists in all generations that this
  2176   // collector is responsible for
  2177   _cmsGen->freelistLock()->unlock();
  2180 bool CMSCollector::haveFreelistLocks() const {
  2181   // Check locks for all free lists in all generations that this
  2182   // collector is responsible for
  2183   assert_lock_strong(_cmsGen->freelistLock());
  2184   PRODUCT_ONLY(ShouldNotReachHere());
  2185   return true;
  2188 // A utility class that is used by the CMS collector to
  2189 // temporarily "release" the foreground collector from its
  2190 // usual obligation to wait for the background collector to
  2191 // complete an ongoing phase before proceeding.
  2192 class ReleaseForegroundGC: public StackObj {
  2193  private:
  2194   CMSCollector* _c;
  2195  public:
  2196   ReleaseForegroundGC(CMSCollector* c) : _c(c) {
  2197     assert(_c->_foregroundGCShouldWait, "Else should not need to call");
  2198     MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
  2199     // allow a potentially blocked foreground collector to proceed
  2200     _c->_foregroundGCShouldWait = false;
  2201     if (_c->_foregroundGCIsActive) {
  2202       CGC_lock->notify();
  2204     assert(!ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  2205            "Possible deadlock");
  2208   ~ReleaseForegroundGC() {
  2209     assert(!_c->_foregroundGCShouldWait, "Usage protocol violation?");
  2210     MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
  2211     _c->_foregroundGCShouldWait = true;
  2213 };
  2215 // There are separate collect_in_background and collect_in_foreground because of
  2216 // the different locking requirements of the background collector and the
  2217 // foreground collector.  There was originally an attempt to share
  2218 // one "collect" method between the background collector and the foreground
  2219 // collector but the if-then-else required made it cleaner to have
  2220 // separate methods.
  2221 void CMSCollector::collect_in_background(bool clear_all_soft_refs, GCCause::Cause cause) {
  2222   assert(Thread::current()->is_ConcurrentGC_thread(),
  2223     "A CMS asynchronous collection is only allowed on a CMS thread.");
  2225   GenCollectedHeap* gch = GenCollectedHeap::heap();
  2227     bool safepoint_check = Mutex::_no_safepoint_check_flag;
  2228     MutexLockerEx hl(Heap_lock, safepoint_check);
  2229     FreelistLocker fll(this);
  2230     MutexLockerEx x(CGC_lock, safepoint_check);
  2231     if (_foregroundGCIsActive || !UseAsyncConcMarkSweepGC) {
  2232       // The foreground collector is active or we're
  2233       // not using asynchronous collections.  Skip this
  2234       // background collection.
  2235       assert(!_foregroundGCShouldWait, "Should be clear");
  2236       return;
  2237     } else {
  2238       assert(_collectorState == Idling, "Should be idling before start.");
  2239       _collectorState = InitialMarking;
  2240       register_gc_start(cause);
  2241       // Reset the expansion cause, now that we are about to begin
  2242       // a new cycle.
  2243       clear_expansion_cause();
  2245       // Clear the MetaspaceGC flag since a concurrent collection
  2246       // is starting but also clear it after the collection.
  2247       MetaspaceGC::set_should_concurrent_collect(false);
  2249     // Decide if we want to enable class unloading as part of the
  2250     // ensuing concurrent GC cycle.
  2251     update_should_unload_classes();
  2252     _full_gc_requested = false;           // acks all outstanding full gc requests
  2253     _full_gc_cause = GCCause::_no_gc;
  2254     // Signal that we are about to start a collection
  2255     gch->increment_total_full_collections();  // ... starting a collection cycle
  2256     _collection_count_start = gch->total_full_collections();
  2259   // Used for PrintGC
  2260   size_t prev_used;
  2261   if (PrintGC && Verbose) {
  2262     prev_used = _cmsGen->used(); // XXXPERM
  2265   // The change of the collection state is normally done at this level;
  2266   // the exceptions are phases that are executed while the world is
  2267   // stopped.  For those phases the change of state is done while the
  2268   // world is stopped.  For baton passing purposes this allows the
  2269   // background collector to finish the phase and change state atomically.
  2270   // The foreground collector cannot wait on a phase that is done
  2271   // while the world is stopped because the foreground collector already
  2272   // has the world stopped and would deadlock.
  2273   while (_collectorState != Idling) {
  2274     if (TraceCMSState) {
  2275       gclog_or_tty->print_cr("Thread " INTPTR_FORMAT " in CMS state %d",
  2276         Thread::current(), _collectorState);
  2278     // The foreground collector
  2279     //   holds the Heap_lock throughout its collection.
  2280     //   holds the CMS token (but not the lock)
  2281     //     except while it is waiting for the background collector to yield.
  2282     //
  2283     // The foreground collector should be blocked (not for long)
  2284     //   if the background collector is about to start a phase
  2285     //   executed with world stopped.  If the background
  2286     //   collector has already started such a phase, the
  2287     //   foreground collector is blocked waiting for the
  2288     //   Heap_lock.  The stop-world phases (InitialMarking and FinalMarking)
  2289     //   are executed in the VM thread.
  2290     //
  2291     // The locking order is
  2292     //   PendingListLock (PLL)  -- if applicable (FinalMarking)
  2293     //   Heap_lock  (both this & PLL locked in VM_CMS_Operation::prologue())
  2294     //   CMS token  (claimed in
  2295     //                stop_world_and_do() -->
  2296     //                  safepoint_synchronize() -->
  2297     //                    CMSThread::synchronize())
  2300       // Check if the FG collector wants us to yield.
  2301       CMSTokenSync x(true); // is cms thread
  2302       if (waitForForegroundGC()) {
  2303         // We yielded to a foreground GC, nothing more to be
  2304         // done this round.
  2305         assert(_foregroundGCShouldWait == false, "We set it to false in "
  2306                "waitForForegroundGC()");
  2307         if (TraceCMSState) {
  2308           gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT
  2309             " exiting collection CMS state %d",
  2310             Thread::current(), _collectorState);
  2312         return;
  2313       } else {
  2314         // The background collector can run but check to see if the
  2315         // foreground collector has done a collection while the
  2316         // background collector was waiting to get the CGC_lock
  2317         // above.  If yes, break so that _foregroundGCShouldWait
  2318         // is cleared before returning.
  2319         if (_collectorState == Idling) {
  2320           break;
  2325     assert(_foregroundGCShouldWait, "Foreground collector, if active, "
  2326       "should be waiting");
  2328     switch (_collectorState) {
  2329       case InitialMarking:
  2331           ReleaseForegroundGC x(this);
  2332           stats().record_cms_begin();
  2333           VM_CMS_Initial_Mark initial_mark_op(this);
  2334           VMThread::execute(&initial_mark_op);
  2336         // The collector state may be any legal state at this point
  2337         // since the background collector may have yielded to the
  2338         // foreground collector.
  2339         break;
  2340       case Marking:
  2341         // initial marking in checkpointRootsInitialWork has been completed
  2342         if (markFromRoots(true)) { // we were successful
  2343           assert(_collectorState == Precleaning, "Collector state should "
  2344             "have changed");
  2345         } else {
  2346           assert(_foregroundGCIsActive, "Internal state inconsistency");
  2348         break;
  2349       case Precleaning:
  2350         if (UseAdaptiveSizePolicy) {
  2351           size_policy()->concurrent_precleaning_begin();
  2353         // marking from roots in markFromRoots has been completed
  2354         preclean();
  2355         if (UseAdaptiveSizePolicy) {
  2356           size_policy()->concurrent_precleaning_end();
  2358         assert(_collectorState == AbortablePreclean ||
  2359                _collectorState == FinalMarking,
  2360                "Collector state should have changed");
  2361         break;
  2362       case AbortablePreclean:
  2363         if (UseAdaptiveSizePolicy) {
  2364         size_policy()->concurrent_phases_resume();
  2366         abortable_preclean();
  2367         if (UseAdaptiveSizePolicy) {
  2368           size_policy()->concurrent_precleaning_end();
  2370         assert(_collectorState == FinalMarking, "Collector state should "
  2371           "have changed");
  2372         break;
  2373       case FinalMarking:
  2375           ReleaseForegroundGC x(this);
  2377           VM_CMS_Final_Remark final_remark_op(this);
  2378           VMThread::execute(&final_remark_op);
  2380         assert(_foregroundGCShouldWait, "block post-condition");
  2381         break;
  2382       case Sweeping:
  2383         if (UseAdaptiveSizePolicy) {
  2384           size_policy()->concurrent_sweeping_begin();
  2386         // final marking in checkpointRootsFinal has been completed
  2387         sweep(true);
  2388         assert(_collectorState == Resizing, "Collector state change "
  2389           "to Resizing must be done under the free_list_lock");
  2390         _full_gcs_since_conc_gc = 0;
  2392         // Stop the timers for adaptive size policy for the concurrent phases
  2393         if (UseAdaptiveSizePolicy) {
  2394           size_policy()->concurrent_sweeping_end();
  2395           size_policy()->concurrent_phases_end(gch->gc_cause(),
  2396                                              gch->prev_gen(_cmsGen)->capacity(),
  2397                                              _cmsGen->free());
  2400       case Resizing: {
  2401         // Sweeping has been completed...
  2402         // At this point the background collection has completed.
  2403         // Don't move the call to compute_new_size() down
  2404         // into code that might be executed if the background
  2405         // collection was preempted.
  2407           ReleaseForegroundGC x(this);   // unblock FG collection
  2408           MutexLockerEx       y(Heap_lock, Mutex::_no_safepoint_check_flag);
  2409           CMSTokenSync        z(true);   // not strictly needed.
  2410           if (_collectorState == Resizing) {
  2411             compute_new_size();
  2412             save_heap_summary();
  2413             _collectorState = Resetting;
  2414           } else {
  2415             assert(_collectorState == Idling, "The state should only change"
  2416                    " because the foreground collector has finished the collection");
  2419         break;
  2421       case Resetting:
  2422         // CMS heap resizing has been completed
  2423         reset(true);
  2424         assert(_collectorState == Idling, "Collector state should "
  2425           "have changed");
  2427         MetaspaceGC::set_should_concurrent_collect(false);
  2429         stats().record_cms_end();
  2430         // Don't move the concurrent_phases_end() and compute_new_size()
  2431         // calls to here because a preempted background collection
  2432         // has it's state set to "Resetting".
  2433         break;
  2434       case Idling:
  2435       default:
  2436         ShouldNotReachHere();
  2437         break;
  2439     if (TraceCMSState) {
  2440       gclog_or_tty->print_cr("  Thread " INTPTR_FORMAT " done - next CMS state %d",
  2441         Thread::current(), _collectorState);
  2443     assert(_foregroundGCShouldWait, "block post-condition");
  2446   // Should this be in gc_epilogue?
  2447   collector_policy()->counters()->update_counters();
  2450     // Clear _foregroundGCShouldWait and, in the event that the
  2451     // foreground collector is waiting, notify it, before
  2452     // returning.
  2453     MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
  2454     _foregroundGCShouldWait = false;
  2455     if (_foregroundGCIsActive) {
  2456       CGC_lock->notify();
  2458     assert(!ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  2459            "Possible deadlock");
  2461   if (TraceCMSState) {
  2462     gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT
  2463       " exiting collection CMS state %d",
  2464       Thread::current(), _collectorState);
  2466   if (PrintGC && Verbose) {
  2467     _cmsGen->print_heap_change(prev_used);
  2471 void CMSCollector::register_foreground_gc_start(GCCause::Cause cause) {
  2472   if (!_cms_start_registered) {
  2473     register_gc_start(cause);
  2477 void CMSCollector::register_gc_start(GCCause::Cause cause) {
  2478   _cms_start_registered = true;
  2479   _gc_timer_cm->register_gc_start();
  2480   _gc_tracer_cm->report_gc_start(cause, _gc_timer_cm->gc_start());
  2483 void CMSCollector::register_gc_end() {
  2484   if (_cms_start_registered) {
  2485     report_heap_summary(GCWhen::AfterGC);
  2487     _gc_timer_cm->register_gc_end();
  2488     _gc_tracer_cm->report_gc_end(_gc_timer_cm->gc_end(), _gc_timer_cm->time_partitions());
  2489     _cms_start_registered = false;
  2493 void CMSCollector::save_heap_summary() {
  2494   GenCollectedHeap* gch = GenCollectedHeap::heap();
  2495   _last_heap_summary = gch->create_heap_summary();
  2496   _last_metaspace_summary = gch->create_metaspace_summary();
  2499 void CMSCollector::report_heap_summary(GCWhen::Type when) {
  2500   _gc_tracer_cm->report_gc_heap_summary(when, _last_heap_summary);
  2501   _gc_tracer_cm->report_metaspace_summary(when, _last_metaspace_summary);
  2504 void CMSCollector::collect_in_foreground(bool clear_all_soft_refs, GCCause::Cause cause) {
  2505   assert(_foregroundGCIsActive && !_foregroundGCShouldWait,
  2506          "Foreground collector should be waiting, not executing");
  2507   assert(Thread::current()->is_VM_thread(), "A foreground collection"
  2508     "may only be done by the VM Thread with the world stopped");
  2509   assert(ConcurrentMarkSweepThread::vm_thread_has_cms_token(),
  2510          "VM thread should have CMS token");
  2512   NOT_PRODUCT(GCTraceTime t("CMS:MS (foreground) ", PrintGCDetails && Verbose,
  2513     true, NULL);)
  2514   if (UseAdaptiveSizePolicy) {
  2515     size_policy()->ms_collection_begin();
  2517   COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact);
  2519   HandleMark hm;  // Discard invalid handles created during verification
  2521   if (VerifyBeforeGC &&
  2522       GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2523     Universe::verify();
  2526   // Snapshot the soft reference policy to be used in this collection cycle.
  2527   ref_processor()->setup_policy(clear_all_soft_refs);
  2529   // Decide if class unloading should be done
  2530   update_should_unload_classes();
  2532   bool init_mark_was_synchronous = false; // until proven otherwise
  2533   while (_collectorState != Idling) {
  2534     if (TraceCMSState) {
  2535       gclog_or_tty->print_cr("Thread " INTPTR_FORMAT " in CMS state %d",
  2536         Thread::current(), _collectorState);
  2538     switch (_collectorState) {
  2539       case InitialMarking:
  2540         register_foreground_gc_start(cause);
  2541         init_mark_was_synchronous = true;  // fact to be exploited in re-mark
  2542         checkpointRootsInitial(false);
  2543         assert(_collectorState == Marking, "Collector state should have changed"
  2544           " within checkpointRootsInitial()");
  2545         break;
  2546       case Marking:
  2547         // initial marking in checkpointRootsInitialWork has been completed
  2548         if (VerifyDuringGC &&
  2549             GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2550           Universe::verify("Verify before initial mark: ");
  2553           bool res = markFromRoots(false);
  2554           assert(res && _collectorState == FinalMarking, "Collector state should "
  2555             "have changed");
  2556           break;
  2558       case FinalMarking:
  2559         if (VerifyDuringGC &&
  2560             GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2561           Universe::verify("Verify before re-mark: ");
  2563         checkpointRootsFinal(false, clear_all_soft_refs,
  2564                              init_mark_was_synchronous);
  2565         assert(_collectorState == Sweeping, "Collector state should not "
  2566           "have changed within checkpointRootsFinal()");
  2567         break;
  2568       case Sweeping:
  2569         // final marking in checkpointRootsFinal has been completed
  2570         if (VerifyDuringGC &&
  2571             GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2572           Universe::verify("Verify before sweep: ");
  2574         sweep(false);
  2575         assert(_collectorState == Resizing, "Incorrect state");
  2576         break;
  2577       case Resizing: {
  2578         // Sweeping has been completed; the actual resize in this case
  2579         // is done separately; nothing to be done in this state.
  2580         _collectorState = Resetting;
  2581         break;
  2583       case Resetting:
  2584         // The heap has been resized.
  2585         if (VerifyDuringGC &&
  2586             GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2587           Universe::verify("Verify before reset: ");
  2589         save_heap_summary();
  2590         reset(false);
  2591         assert(_collectorState == Idling, "Collector state should "
  2592           "have changed");
  2593         break;
  2594       case Precleaning:
  2595       case AbortablePreclean:
  2596         // Elide the preclean phase
  2597         _collectorState = FinalMarking;
  2598         break;
  2599       default:
  2600         ShouldNotReachHere();
  2602     if (TraceCMSState) {
  2603       gclog_or_tty->print_cr("  Thread " INTPTR_FORMAT " done - next CMS state %d",
  2604         Thread::current(), _collectorState);
  2608   if (UseAdaptiveSizePolicy) {
  2609     GenCollectedHeap* gch = GenCollectedHeap::heap();
  2610     size_policy()->ms_collection_end(gch->gc_cause());
  2613   if (VerifyAfterGC &&
  2614       GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  2615     Universe::verify();
  2617   if (TraceCMSState) {
  2618     gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT
  2619       " exiting collection CMS state %d",
  2620       Thread::current(), _collectorState);
  2624 bool CMSCollector::waitForForegroundGC() {
  2625   bool res = false;
  2626   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  2627          "CMS thread should have CMS token");
  2628   // Block the foreground collector until the
  2629   // background collectors decides whether to
  2630   // yield.
  2631   MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
  2632   _foregroundGCShouldWait = true;
  2633   if (_foregroundGCIsActive) {
  2634     // The background collector yields to the
  2635     // foreground collector and returns a value
  2636     // indicating that it has yielded.  The foreground
  2637     // collector can proceed.
  2638     res = true;
  2639     _foregroundGCShouldWait = false;
  2640     ConcurrentMarkSweepThread::clear_CMS_flag(
  2641       ConcurrentMarkSweepThread::CMS_cms_has_token);
  2642     ConcurrentMarkSweepThread::set_CMS_flag(
  2643       ConcurrentMarkSweepThread::CMS_cms_wants_token);
  2644     // Get a possibly blocked foreground thread going
  2645     CGC_lock->notify();
  2646     if (TraceCMSState) {
  2647       gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT " waiting at CMS state %d",
  2648         Thread::current(), _collectorState);
  2650     while (_foregroundGCIsActive) {
  2651       CGC_lock->wait(Mutex::_no_safepoint_check_flag);
  2653     ConcurrentMarkSweepThread::set_CMS_flag(
  2654       ConcurrentMarkSweepThread::CMS_cms_has_token);
  2655     ConcurrentMarkSweepThread::clear_CMS_flag(
  2656       ConcurrentMarkSweepThread::CMS_cms_wants_token);
  2658   if (TraceCMSState) {
  2659     gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT " continuing at CMS state %d",
  2660       Thread::current(), _collectorState);
  2662   return res;
  2665 // Because of the need to lock the free lists and other structures in
  2666 // the collector, common to all the generations that the collector is
  2667 // collecting, we need the gc_prologues of individual CMS generations
  2668 // delegate to their collector. It may have been simpler had the
  2669 // current infrastructure allowed one to call a prologue on a
  2670 // collector. In the absence of that we have the generation's
  2671 // prologue delegate to the collector, which delegates back
  2672 // some "local" work to a worker method in the individual generations
  2673 // that it's responsible for collecting, while itself doing any
  2674 // work common to all generations it's responsible for. A similar
  2675 // comment applies to the  gc_epilogue()'s.
  2676 // The role of the varaible _between_prologue_and_epilogue is to
  2677 // enforce the invocation protocol.
  2678 void CMSCollector::gc_prologue(bool full) {
  2679   // Call gc_prologue_work() for the CMSGen
  2680   // we are responsible for.
  2682   // The following locking discipline assumes that we are only called
  2683   // when the world is stopped.
  2684   assert(SafepointSynchronize::is_at_safepoint(), "world is stopped assumption");
  2686   // The CMSCollector prologue must call the gc_prologues for the
  2687   // "generations" that it's responsible
  2688   // for.
  2690   assert(   Thread::current()->is_VM_thread()
  2691          || (   CMSScavengeBeforeRemark
  2692              && Thread::current()->is_ConcurrentGC_thread()),
  2693          "Incorrect thread type for prologue execution");
  2695   if (_between_prologue_and_epilogue) {
  2696     // We have already been invoked; this is a gc_prologue delegation
  2697     // from yet another CMS generation that we are responsible for, just
  2698     // ignore it since all relevant work has already been done.
  2699     return;
  2702   // set a bit saying prologue has been called; cleared in epilogue
  2703   _between_prologue_and_epilogue = true;
  2704   // Claim locks for common data structures, then call gc_prologue_work()
  2705   // for each CMSGen.
  2707   getFreelistLocks();   // gets free list locks on constituent spaces
  2708   bitMapLock()->lock_without_safepoint_check();
  2710   // Should call gc_prologue_work() for all cms gens we are responsible for
  2711   bool duringMarking =    _collectorState >= Marking
  2712                          && _collectorState < Sweeping;
  2714   // The young collections clear the modified oops state, which tells if
  2715   // there are any modified oops in the class. The remark phase also needs
  2716   // that information. Tell the young collection to save the union of all
  2717   // modified klasses.
  2718   if (duringMarking) {
  2719     _ct->klass_rem_set()->set_accumulate_modified_oops(true);
  2722   bool registerClosure = duringMarking;
  2724   ModUnionClosure* muc = CollectedHeap::use_parallel_gc_threads() ?
  2725                                                &_modUnionClosurePar
  2726                                                : &_modUnionClosure;
  2727   _cmsGen->gc_prologue_work(full, registerClosure, muc);
  2729   if (!full) {
  2730     stats().record_gc0_begin();
  2734 void ConcurrentMarkSweepGeneration::gc_prologue(bool full) {
  2736   _capacity_at_prologue = capacity();
  2737   _used_at_prologue = used();
  2739   // Delegate to CMScollector which knows how to coordinate between
  2740   // this and any other CMS generations that it is responsible for
  2741   // collecting.
  2742   collector()->gc_prologue(full);
  2745 // This is a "private" interface for use by this generation's CMSCollector.
  2746 // Not to be called directly by any other entity (for instance,
  2747 // GenCollectedHeap, which calls the "public" gc_prologue method above).
  2748 void ConcurrentMarkSweepGeneration::gc_prologue_work(bool full,
  2749   bool registerClosure, ModUnionClosure* modUnionClosure) {
  2750   assert(!incremental_collection_failed(), "Shouldn't be set yet");
  2751   assert(cmsSpace()->preconsumptionDirtyCardClosure() == NULL,
  2752     "Should be NULL");
  2753   if (registerClosure) {
  2754     cmsSpace()->setPreconsumptionDirtyCardClosure(modUnionClosure);
  2756   cmsSpace()->gc_prologue();
  2757   // Clear stat counters
  2758   NOT_PRODUCT(
  2759     assert(_numObjectsPromoted == 0, "check");
  2760     assert(_numWordsPromoted   == 0, "check");
  2761     if (Verbose && PrintGC) {
  2762       gclog_or_tty->print("Allocated "SIZE_FORMAT" objects, "
  2763                           SIZE_FORMAT" bytes concurrently",
  2764       _numObjectsAllocated, _numWordsAllocated*sizeof(HeapWord));
  2766     _numObjectsAllocated = 0;
  2767     _numWordsAllocated   = 0;
  2771 void CMSCollector::gc_epilogue(bool full) {
  2772   // The following locking discipline assumes that we are only called
  2773   // when the world is stopped.
  2774   assert(SafepointSynchronize::is_at_safepoint(),
  2775          "world is stopped assumption");
  2777   // Currently the CMS epilogue (see CompactibleFreeListSpace) merely checks
  2778   // if linear allocation blocks need to be appropriately marked to allow the
  2779   // the blocks to be parsable. We also check here whether we need to nudge the
  2780   // CMS collector thread to start a new cycle (if it's not already active).
  2781   assert(   Thread::current()->is_VM_thread()
  2782          || (   CMSScavengeBeforeRemark
  2783              && Thread::current()->is_ConcurrentGC_thread()),
  2784          "Incorrect thread type for epilogue execution");
  2786   if (!_between_prologue_and_epilogue) {
  2787     // We have already been invoked; this is a gc_epilogue delegation
  2788     // from yet another CMS generation that we are responsible for, just
  2789     // ignore it since all relevant work has already been done.
  2790     return;
  2792   assert(haveFreelistLocks(), "must have freelist locks");
  2793   assert_lock_strong(bitMapLock());
  2795   _ct->klass_rem_set()->set_accumulate_modified_oops(false);
  2797   _cmsGen->gc_epilogue_work(full);
  2799   if (_collectorState == AbortablePreclean || _collectorState == Precleaning) {
  2800     // in case sampling was not already enabled, enable it
  2801     _start_sampling = true;
  2803   // reset _eden_chunk_array so sampling starts afresh
  2804   _eden_chunk_index = 0;
  2806   size_t cms_used   = _cmsGen->cmsSpace()->used();
  2808   // update performance counters - this uses a special version of
  2809   // update_counters() that allows the utilization to be passed as a
  2810   // parameter, avoiding multiple calls to used().
  2811   //
  2812   _cmsGen->update_counters(cms_used);
  2814   if (CMSIncrementalMode) {
  2815     icms_update_allocation_limits();
  2818   bitMapLock()->unlock();
  2819   releaseFreelistLocks();
  2821   if (!CleanChunkPoolAsync) {
  2822     Chunk::clean_chunk_pool();
  2825   set_did_compact(false);
  2826   _between_prologue_and_epilogue = false;  // ready for next cycle
  2829 void ConcurrentMarkSweepGeneration::gc_epilogue(bool full) {
  2830   collector()->gc_epilogue(full);
  2832   // Also reset promotion tracking in par gc thread states.
  2833   if (CollectedHeap::use_parallel_gc_threads()) {
  2834     for (uint i = 0; i < ParallelGCThreads; i++) {
  2835       _par_gc_thread_states[i]->promo.stopTrackingPromotions(i);
  2840 void ConcurrentMarkSweepGeneration::gc_epilogue_work(bool full) {
  2841   assert(!incremental_collection_failed(), "Should have been cleared");
  2842   cmsSpace()->setPreconsumptionDirtyCardClosure(NULL);
  2843   cmsSpace()->gc_epilogue();
  2844     // Print stat counters
  2845   NOT_PRODUCT(
  2846     assert(_numObjectsAllocated == 0, "check");
  2847     assert(_numWordsAllocated == 0, "check");
  2848     if (Verbose && PrintGC) {
  2849       gclog_or_tty->print("Promoted "SIZE_FORMAT" objects, "
  2850                           SIZE_FORMAT" bytes",
  2851                  _numObjectsPromoted, _numWordsPromoted*sizeof(HeapWord));
  2853     _numObjectsPromoted = 0;
  2854     _numWordsPromoted   = 0;
  2857   if (PrintGC && Verbose) {
  2858     // Call down the chain in contiguous_available needs the freelistLock
  2859     // so print this out before releasing the freeListLock.
  2860     gclog_or_tty->print(" Contiguous available "SIZE_FORMAT" bytes ",
  2861                         contiguous_available());
  2865 #ifndef PRODUCT
  2866 bool CMSCollector::have_cms_token() {
  2867   Thread* thr = Thread::current();
  2868   if (thr->is_VM_thread()) {
  2869     return ConcurrentMarkSweepThread::vm_thread_has_cms_token();
  2870   } else if (thr->is_ConcurrentGC_thread()) {
  2871     return ConcurrentMarkSweepThread::cms_thread_has_cms_token();
  2872   } else if (thr->is_GC_task_thread()) {
  2873     return ConcurrentMarkSweepThread::vm_thread_has_cms_token() &&
  2874            ParGCRareEvent_lock->owned_by_self();
  2876   return false;
  2878 #endif
  2880 // Check reachability of the given heap address in CMS generation,
  2881 // treating all other generations as roots.
  2882 bool CMSCollector::is_cms_reachable(HeapWord* addr) {
  2883   // We could "guarantee" below, rather than assert, but i'll
  2884   // leave these as "asserts" so that an adventurous debugger
  2885   // could try this in the product build provided some subset of
  2886   // the conditions were met, provided they were intersted in the
  2887   // results and knew that the computation below wouldn't interfere
  2888   // with other concurrent computations mutating the structures
  2889   // being read or written.
  2890   assert(SafepointSynchronize::is_at_safepoint(),
  2891          "Else mutations in object graph will make answer suspect");
  2892   assert(have_cms_token(), "Should hold cms token");
  2893   assert(haveFreelistLocks(), "must hold free list locks");
  2894   assert_lock_strong(bitMapLock());
  2896   // Clear the marking bit map array before starting, but, just
  2897   // for kicks, first report if the given address is already marked
  2898   gclog_or_tty->print_cr("Start: Address 0x%x is%s marked", addr,
  2899                 _markBitMap.isMarked(addr) ? "" : " not");
  2901   if (verify_after_remark()) {
  2902     MutexLockerEx x(verification_mark_bm()->lock(), Mutex::_no_safepoint_check_flag);
  2903     bool result = verification_mark_bm()->isMarked(addr);
  2904     gclog_or_tty->print_cr("TransitiveMark: Address 0x%x %s marked", addr,
  2905                            result ? "IS" : "is NOT");
  2906     return result;
  2907   } else {
  2908     gclog_or_tty->print_cr("Could not compute result");
  2909     return false;
  2914 void
  2915 CMSCollector::print_on_error(outputStream* st) {
  2916   CMSCollector* collector = ConcurrentMarkSweepGeneration::_collector;
  2917   if (collector != NULL) {
  2918     CMSBitMap* bitmap = &collector->_markBitMap;
  2919     st->print_cr("Marking Bits: (CMSBitMap*) " PTR_FORMAT, bitmap);
  2920     bitmap->print_on_error(st, " Bits: ");
  2922     st->cr();
  2924     CMSBitMap* mut_bitmap = &collector->_modUnionTable;
  2925     st->print_cr("Mod Union Table: (CMSBitMap*) " PTR_FORMAT, mut_bitmap);
  2926     mut_bitmap->print_on_error(st, " Bits: ");
  2930 ////////////////////////////////////////////////////////
  2931 // CMS Verification Support
  2932 ////////////////////////////////////////////////////////
  2933 // Following the remark phase, the following invariant
  2934 // should hold -- each object in the CMS heap which is
  2935 // marked in markBitMap() should be marked in the verification_mark_bm().
  2937 class VerifyMarkedClosure: public BitMapClosure {
  2938   CMSBitMap* _marks;
  2939   bool       _failed;
  2941  public:
  2942   VerifyMarkedClosure(CMSBitMap* bm): _marks(bm), _failed(false) {}
  2944   bool do_bit(size_t offset) {
  2945     HeapWord* addr = _marks->offsetToHeapWord(offset);
  2946     if (!_marks->isMarked(addr)) {
  2947       oop(addr)->print_on(gclog_or_tty);
  2948       gclog_or_tty->print_cr(" ("INTPTR_FORMAT" should have been marked)", addr);
  2949       _failed = true;
  2951     return true;
  2954   bool failed() { return _failed; }
  2955 };
  2957 bool CMSCollector::verify_after_remark(bool silent) {
  2958   if (!silent) gclog_or_tty->print(" [Verifying CMS Marking... ");
  2959   MutexLockerEx ml(verification_mark_bm()->lock(), Mutex::_no_safepoint_check_flag);
  2960   static bool init = false;
  2962   assert(SafepointSynchronize::is_at_safepoint(),
  2963          "Else mutations in object graph will make answer suspect");
  2964   assert(have_cms_token(),
  2965          "Else there may be mutual interference in use of "
  2966          " verification data structures");
  2967   assert(_collectorState > Marking && _collectorState <= Sweeping,
  2968          "Else marking info checked here may be obsolete");
  2969   assert(haveFreelistLocks(), "must hold free list locks");
  2970   assert_lock_strong(bitMapLock());
  2973   // Allocate marking bit map if not already allocated
  2974   if (!init) { // first time
  2975     if (!verification_mark_bm()->allocate(_span)) {
  2976       return false;
  2978     init = true;
  2981   assert(verification_mark_stack()->isEmpty(), "Should be empty");
  2983   // Turn off refs discovery -- so we will be tracing through refs.
  2984   // This is as intended, because by this time
  2985   // GC must already have cleared any refs that need to be cleared,
  2986   // and traced those that need to be marked; moreover,
  2987   // the marking done here is not going to intefere in any
  2988   // way with the marking information used by GC.
  2989   NoRefDiscovery no_discovery(ref_processor());
  2991   COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;)
  2993   // Clear any marks from a previous round
  2994   verification_mark_bm()->clear_all();
  2995   assert(verification_mark_stack()->isEmpty(), "markStack should be empty");
  2996   verify_work_stacks_empty();
  2998   GenCollectedHeap* gch = GenCollectedHeap::heap();
  2999   gch->ensure_parsability(false);  // fill TLABs, but no need to retire them
  3000   // Update the saved marks which may affect the root scans.
  3001   gch->save_marks();
  3003   if (CMSRemarkVerifyVariant == 1) {
  3004     // In this first variant of verification, we complete
  3005     // all marking, then check if the new marks-verctor is
  3006     // a subset of the CMS marks-vector.
  3007     verify_after_remark_work_1();
  3008   } else if (CMSRemarkVerifyVariant == 2) {
  3009     // In this second variant of verification, we flag an error
  3010     // (i.e. an object reachable in the new marks-vector not reachable
  3011     // in the CMS marks-vector) immediately, also indicating the
  3012     // identify of an object (A) that references the unmarked object (B) --
  3013     // presumably, a mutation to A failed to be picked up by preclean/remark?
  3014     verify_after_remark_work_2();
  3015   } else {
  3016     warning("Unrecognized value %d for CMSRemarkVerifyVariant",
  3017             CMSRemarkVerifyVariant);
  3019   if (!silent) gclog_or_tty->print(" done] ");
  3020   return true;
  3023 void CMSCollector::verify_after_remark_work_1() {
  3024   ResourceMark rm;
  3025   HandleMark  hm;
  3026   GenCollectedHeap* gch = GenCollectedHeap::heap();
  3028   // Get a clear set of claim bits for the strong roots processing to work with.
  3029   ClassLoaderDataGraph::clear_claimed_marks();
  3031   // Mark from roots one level into CMS
  3032   MarkRefsIntoClosure notOlder(_span, verification_mark_bm());
  3033   gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
  3035   gch->gen_process_strong_roots(_cmsGen->level(),
  3036                                 true,   // younger gens are roots
  3037                                 true,   // activate StrongRootsScope
  3038                                 false,  // not scavenging
  3039                                 SharedHeap::ScanningOption(roots_scanning_options()),
  3040                                 &notOlder,
  3041                                 true,   // walk code active on stacks
  3042                                 NULL,
  3043                                 NULL); // SSS: Provide correct closure
  3045   // Now mark from the roots
  3046   MarkFromRootsClosure markFromRootsClosure(this, _span,
  3047     verification_mark_bm(), verification_mark_stack(),
  3048     false /* don't yield */, true /* verifying */);
  3049   assert(_restart_addr == NULL, "Expected pre-condition");
  3050   verification_mark_bm()->iterate(&markFromRootsClosure);
  3051   while (_restart_addr != NULL) {
  3052     // Deal with stack overflow: by restarting at the indicated
  3053     // address.
  3054     HeapWord* ra = _restart_addr;
  3055     markFromRootsClosure.reset(ra);
  3056     _restart_addr = NULL;
  3057     verification_mark_bm()->iterate(&markFromRootsClosure, ra, _span.end());
  3059   assert(verification_mark_stack()->isEmpty(), "Should have been drained");
  3060   verify_work_stacks_empty();
  3062   // Marking completed -- now verify that each bit marked in
  3063   // verification_mark_bm() is also marked in markBitMap(); flag all
  3064   // errors by printing corresponding objects.
  3065   VerifyMarkedClosure vcl(markBitMap());
  3066   verification_mark_bm()->iterate(&vcl);
  3067   if (vcl.failed()) {
  3068     gclog_or_tty->print("Verification failed");
  3069     Universe::heap()->print_on(gclog_or_tty);
  3070     fatal("CMS: failed marking verification after remark");
  3074 class VerifyKlassOopsKlassClosure : public KlassClosure {
  3075   class VerifyKlassOopsClosure : public OopClosure {
  3076     CMSBitMap* _bitmap;
  3077    public:
  3078     VerifyKlassOopsClosure(CMSBitMap* bitmap) : _bitmap(bitmap) { }
  3079     void do_oop(oop* p)       { guarantee(*p == NULL || _bitmap->isMarked((HeapWord*) *p), "Should be marked"); }
  3080     void do_oop(narrowOop* p) { ShouldNotReachHere(); }
  3081   } _oop_closure;
  3082  public:
  3083   VerifyKlassOopsKlassClosure(CMSBitMap* bitmap) : _oop_closure(bitmap) {}
  3084   void do_klass(Klass* k) {
  3085     k->oops_do(&_oop_closure);
  3087 };
  3089 void CMSCollector::verify_after_remark_work_2() {
  3090   ResourceMark rm;
  3091   HandleMark  hm;
  3092   GenCollectedHeap* gch = GenCollectedHeap::heap();
  3094   // Get a clear set of claim bits for the strong roots processing to work with.
  3095   ClassLoaderDataGraph::clear_claimed_marks();
  3097   // Mark from roots one level into CMS
  3098   MarkRefsIntoVerifyClosure notOlder(_span, verification_mark_bm(),
  3099                                      markBitMap());
  3100   CMKlassClosure klass_closure(&notOlder);
  3102   gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
  3103   gch->gen_process_strong_roots(_cmsGen->level(),
  3104                                 true,   // younger gens are roots
  3105                                 true,   // activate StrongRootsScope
  3106                                 false,  // not scavenging
  3107                                 SharedHeap::ScanningOption(roots_scanning_options()),
  3108                                 &notOlder,
  3109                                 true,   // walk code active on stacks
  3110                                 NULL,
  3111                                 &klass_closure);
  3113   // Now mark from the roots
  3114   MarkFromRootsVerifyClosure markFromRootsClosure(this, _span,
  3115     verification_mark_bm(), markBitMap(), verification_mark_stack());
  3116   assert(_restart_addr == NULL, "Expected pre-condition");
  3117   verification_mark_bm()->iterate(&markFromRootsClosure);
  3118   while (_restart_addr != NULL) {
  3119     // Deal with stack overflow: by restarting at the indicated
  3120     // address.
  3121     HeapWord* ra = _restart_addr;
  3122     markFromRootsClosure.reset(ra);
  3123     _restart_addr = NULL;
  3124     verification_mark_bm()->iterate(&markFromRootsClosure, ra, _span.end());
  3126   assert(verification_mark_stack()->isEmpty(), "Should have been drained");
  3127   verify_work_stacks_empty();
  3129   VerifyKlassOopsKlassClosure verify_klass_oops(verification_mark_bm());
  3130   ClassLoaderDataGraph::classes_do(&verify_klass_oops);
  3132   // Marking completed -- now verify that each bit marked in
  3133   // verification_mark_bm() is also marked in markBitMap(); flag all
  3134   // errors by printing corresponding objects.
  3135   VerifyMarkedClosure vcl(markBitMap());
  3136   verification_mark_bm()->iterate(&vcl);
  3137   assert(!vcl.failed(), "Else verification above should not have succeeded");
  3140 void ConcurrentMarkSweepGeneration::save_marks() {
  3141   // delegate to CMS space
  3142   cmsSpace()->save_marks();
  3143   for (uint i = 0; i < ParallelGCThreads; i++) {
  3144     _par_gc_thread_states[i]->promo.startTrackingPromotions();
  3148 bool ConcurrentMarkSweepGeneration::no_allocs_since_save_marks() {
  3149   return cmsSpace()->no_allocs_since_save_marks();
  3152 #define CMS_SINCE_SAVE_MARKS_DEFN(OopClosureType, nv_suffix)    \
  3154 void ConcurrentMarkSweepGeneration::                            \
  3155 oop_since_save_marks_iterate##nv_suffix(OopClosureType* cl) {   \
  3156   cl->set_generation(this);                                     \
  3157   cmsSpace()->oop_since_save_marks_iterate##nv_suffix(cl);      \
  3158   cl->reset_generation();                                       \
  3159   save_marks();                                                 \
  3162 ALL_SINCE_SAVE_MARKS_CLOSURES(CMS_SINCE_SAVE_MARKS_DEFN)
  3164 void
  3165 ConcurrentMarkSweepGeneration::younger_refs_iterate(OopsInGenClosure* cl) {
  3166   cl->set_generation(this);
  3167   younger_refs_in_space_iterate(_cmsSpace, cl);
  3168   cl->reset_generation();
  3171 void
  3172 ConcurrentMarkSweepGeneration::oop_iterate(MemRegion mr, ExtendedOopClosure* cl) {
  3173   if (freelistLock()->owned_by_self()) {
  3174     Generation::oop_iterate(mr, cl);
  3175   } else {
  3176     MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
  3177     Generation::oop_iterate(mr, cl);
  3181 void
  3182 ConcurrentMarkSweepGeneration::oop_iterate(ExtendedOopClosure* cl) {
  3183   if (freelistLock()->owned_by_self()) {
  3184     Generation::oop_iterate(cl);
  3185   } else {
  3186     MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
  3187     Generation::oop_iterate(cl);
  3191 void
  3192 ConcurrentMarkSweepGeneration::object_iterate(ObjectClosure* cl) {
  3193   if (freelistLock()->owned_by_self()) {
  3194     Generation::object_iterate(cl);
  3195   } else {
  3196     MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
  3197     Generation::object_iterate(cl);
  3201 void
  3202 ConcurrentMarkSweepGeneration::safe_object_iterate(ObjectClosure* cl) {
  3203   if (freelistLock()->owned_by_self()) {
  3204     Generation::safe_object_iterate(cl);
  3205   } else {
  3206     MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
  3207     Generation::safe_object_iterate(cl);
  3211 void
  3212 ConcurrentMarkSweepGeneration::post_compact() {
  3215 void
  3216 ConcurrentMarkSweepGeneration::prepare_for_verify() {
  3217   // Fix the linear allocation blocks to look like free blocks.
  3219   // Locks are normally acquired/released in gc_prologue/gc_epilogue, but those
  3220   // are not called when the heap is verified during universe initialization and
  3221   // at vm shutdown.
  3222   if (freelistLock()->owned_by_self()) {
  3223     cmsSpace()->prepare_for_verify();
  3224   } else {
  3225     MutexLockerEx fll(freelistLock(), Mutex::_no_safepoint_check_flag);
  3226     cmsSpace()->prepare_for_verify();
  3230 void
  3231 ConcurrentMarkSweepGeneration::verify() {
  3232   // Locks are normally acquired/released in gc_prologue/gc_epilogue, but those
  3233   // are not called when the heap is verified during universe initialization and
  3234   // at vm shutdown.
  3235   if (freelistLock()->owned_by_self()) {
  3236     cmsSpace()->verify();
  3237   } else {
  3238     MutexLockerEx fll(freelistLock(), Mutex::_no_safepoint_check_flag);
  3239     cmsSpace()->verify();
  3243 void CMSCollector::verify() {
  3244   _cmsGen->verify();
  3247 #ifndef PRODUCT
  3248 bool CMSCollector::overflow_list_is_empty() const {
  3249   assert(_num_par_pushes >= 0, "Inconsistency");
  3250   if (_overflow_list == NULL) {
  3251     assert(_num_par_pushes == 0, "Inconsistency");
  3253   return _overflow_list == NULL;
  3256 // The methods verify_work_stacks_empty() and verify_overflow_empty()
  3257 // merely consolidate assertion checks that appear to occur together frequently.
  3258 void CMSCollector::verify_work_stacks_empty() const {
  3259   assert(_markStack.isEmpty(), "Marking stack should be empty");
  3260   assert(overflow_list_is_empty(), "Overflow list should be empty");
  3263 void CMSCollector::verify_overflow_empty() const {
  3264   assert(overflow_list_is_empty(), "Overflow list should be empty");
  3265   assert(no_preserved_marks(), "No preserved marks");
  3267 #endif // PRODUCT
  3269 // Decide if we want to enable class unloading as part of the
  3270 // ensuing concurrent GC cycle. We will collect and
  3271 // unload classes if it's the case that:
  3272 // (1) an explicit gc request has been made and the flag
  3273 //     ExplicitGCInvokesConcurrentAndUnloadsClasses is set, OR
  3274 // (2) (a) class unloading is enabled at the command line, and
  3275 //     (b) old gen is getting really full
  3276 // NOTE: Provided there is no change in the state of the heap between
  3277 // calls to this method, it should have idempotent results. Moreover,
  3278 // its results should be monotonically increasing (i.e. going from 0 to 1,
  3279 // but not 1 to 0) between successive calls between which the heap was
  3280 // not collected. For the implementation below, it must thus rely on
  3281 // the property that concurrent_cycles_since_last_unload()
  3282 // will not decrease unless a collection cycle happened and that
  3283 // _cmsGen->is_too_full() are
  3284 // themselves also monotonic in that sense. See check_monotonicity()
  3285 // below.
  3286 void CMSCollector::update_should_unload_classes() {
  3287   _should_unload_classes = false;
  3288   // Condition 1 above
  3289   if (_full_gc_requested && ExplicitGCInvokesConcurrentAndUnloadsClasses) {
  3290     _should_unload_classes = true;
  3291   } else if (CMSClassUnloadingEnabled) { // Condition 2.a above
  3292     // Disjuncts 2.b.(i,ii,iii) above
  3293     _should_unload_classes = (concurrent_cycles_since_last_unload() >=
  3294                               CMSClassUnloadingMaxInterval)
  3295                            || _cmsGen->is_too_full();
  3299 bool ConcurrentMarkSweepGeneration::is_too_full() const {
  3300   bool res = should_concurrent_collect();
  3301   res = res && (occupancy() > (double)CMSIsTooFullPercentage/100.0);
  3302   return res;
  3305 void CMSCollector::setup_cms_unloading_and_verification_state() {
  3306   const  bool should_verify =   VerifyBeforeGC || VerifyAfterGC || VerifyDuringGC
  3307                              || VerifyBeforeExit;
  3308   const  int  rso           =   SharedHeap::SO_Strings | SharedHeap::SO_CodeCache;
  3310   // We set the proper root for this CMS cycle here.
  3311   if (should_unload_classes()) {   // Should unload classes this cycle
  3312     remove_root_scanning_option(SharedHeap::SO_AllClasses);
  3313     add_root_scanning_option(SharedHeap::SO_SystemClasses);
  3314     remove_root_scanning_option(rso);  // Shrink the root set appropriately
  3315     set_verifying(should_verify);    // Set verification state for this cycle
  3316     return;                            // Nothing else needs to be done at this time
  3319   // Not unloading classes this cycle
  3320   assert(!should_unload_classes(), "Inconsitency!");
  3321   remove_root_scanning_option(SharedHeap::SO_SystemClasses);
  3322   add_root_scanning_option(SharedHeap::SO_AllClasses);
  3324   if ((!verifying() || unloaded_classes_last_cycle()) && should_verify) {
  3325     // Include symbols, strings and code cache elements to prevent their resurrection.
  3326     add_root_scanning_option(rso);
  3327     set_verifying(true);
  3328   } else if (verifying() && !should_verify) {
  3329     // We were verifying, but some verification flags got disabled.
  3330     set_verifying(false);
  3331     // Exclude symbols, strings and code cache elements from root scanning to
  3332     // reduce IM and RM pauses.
  3333     remove_root_scanning_option(rso);
  3338 #ifndef PRODUCT
  3339 HeapWord* CMSCollector::block_start(const void* p) const {
  3340   const HeapWord* addr = (HeapWord*)p;
  3341   if (_span.contains(p)) {
  3342     if (_cmsGen->cmsSpace()->is_in_reserved(addr)) {
  3343       return _cmsGen->cmsSpace()->block_start(p);
  3346   return NULL;
  3348 #endif
  3350 HeapWord*
  3351 ConcurrentMarkSweepGeneration::expand_and_allocate(size_t word_size,
  3352                                                    bool   tlab,
  3353                                                    bool   parallel) {
  3354   CMSSynchronousYieldRequest yr;
  3355   assert(!tlab, "Can't deal with TLAB allocation");
  3356   MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
  3357   expand(word_size*HeapWordSize, MinHeapDeltaBytes,
  3358     CMSExpansionCause::_satisfy_allocation);
  3359   if (GCExpandToAllocateDelayMillis > 0) {
  3360     os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
  3362   return have_lock_and_allocate(word_size, tlab);
  3365 // YSR: All of this generation expansion/shrinking stuff is an exact copy of
  3366 // OneContigSpaceCardGeneration, which makes me wonder if we should move this
  3367 // to CardGeneration and share it...
  3368 bool ConcurrentMarkSweepGeneration::expand(size_t bytes, size_t expand_bytes) {
  3369   return CardGeneration::expand(bytes, expand_bytes);
  3372 void ConcurrentMarkSweepGeneration::expand(size_t bytes, size_t expand_bytes,
  3373   CMSExpansionCause::Cause cause)
  3376   bool success = expand(bytes, expand_bytes);
  3378   // remember why we expanded; this information is used
  3379   // by shouldConcurrentCollect() when making decisions on whether to start
  3380   // a new CMS cycle.
  3381   if (success) {
  3382     set_expansion_cause(cause);
  3383     if (PrintGCDetails && Verbose) {
  3384       gclog_or_tty->print_cr("Expanded CMS gen for %s",
  3385         CMSExpansionCause::to_string(cause));
  3390 HeapWord* ConcurrentMarkSweepGeneration::expand_and_par_lab_allocate(CMSParGCThreadState* ps, size_t word_sz) {
  3391   HeapWord* res = NULL;
  3392   MutexLocker x(ParGCRareEvent_lock);
  3393   while (true) {
  3394     // Expansion by some other thread might make alloc OK now:
  3395     res = ps->lab.alloc(word_sz);
  3396     if (res != NULL) return res;
  3397     // If there's not enough expansion space available, give up.
  3398     if (_virtual_space.uncommitted_size() < (word_sz * HeapWordSize)) {
  3399       return NULL;
  3401     // Otherwise, we try expansion.
  3402     expand(word_sz*HeapWordSize, MinHeapDeltaBytes,
  3403       CMSExpansionCause::_allocate_par_lab);
  3404     // Now go around the loop and try alloc again;
  3405     // A competing par_promote might beat us to the expansion space,
  3406     // so we may go around the loop again if promotion fails agaion.
  3407     if (GCExpandToAllocateDelayMillis > 0) {
  3408       os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
  3414 bool ConcurrentMarkSweepGeneration::expand_and_ensure_spooling_space(
  3415   PromotionInfo* promo) {
  3416   MutexLocker x(ParGCRareEvent_lock);
  3417   size_t refill_size_bytes = promo->refillSize() * HeapWordSize;
  3418   while (true) {
  3419     // Expansion by some other thread might make alloc OK now:
  3420     if (promo->ensure_spooling_space()) {
  3421       assert(promo->has_spooling_space(),
  3422              "Post-condition of successful ensure_spooling_space()");
  3423       return true;
  3425     // If there's not enough expansion space available, give up.
  3426     if (_virtual_space.uncommitted_size() < refill_size_bytes) {
  3427       return false;
  3429     // Otherwise, we try expansion.
  3430     expand(refill_size_bytes, MinHeapDeltaBytes,
  3431       CMSExpansionCause::_allocate_par_spooling_space);
  3432     // Now go around the loop and try alloc again;
  3433     // A competing allocation might beat us to the expansion space,
  3434     // so we may go around the loop again if allocation fails again.
  3435     if (GCExpandToAllocateDelayMillis > 0) {
  3436       os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
  3442 void ConcurrentMarkSweepGeneration::shrink_by(size_t bytes) {
  3443   assert_locked_or_safepoint(ExpandHeap_lock);
  3444   // Shrink committed space
  3445   _virtual_space.shrink_by(bytes);
  3446   // Shrink space; this also shrinks the space's BOT
  3447   _cmsSpace->set_end((HeapWord*) _virtual_space.high());
  3448   size_t new_word_size = heap_word_size(_cmsSpace->capacity());
  3449   // Shrink the shared block offset array
  3450   _bts->resize(new_word_size);
  3451   MemRegion mr(_cmsSpace->bottom(), new_word_size);
  3452   // Shrink the card table
  3453   Universe::heap()->barrier_set()->resize_covered_region(mr);
  3455   if (Verbose && PrintGC) {
  3456     size_t new_mem_size = _virtual_space.committed_size();
  3457     size_t old_mem_size = new_mem_size + bytes;
  3458     gclog_or_tty->print_cr("Shrinking %s from " SIZE_FORMAT "K to " SIZE_FORMAT "K",
  3459                   name(), old_mem_size/K, new_mem_size/K);
  3463 void ConcurrentMarkSweepGeneration::shrink(size_t bytes) {
  3464   assert_locked_or_safepoint(Heap_lock);
  3465   size_t size = ReservedSpace::page_align_size_down(bytes);
  3466   // Only shrink if a compaction was done so that all the free space
  3467   // in the generation is in a contiguous block at the end.
  3468   if (size > 0 && did_compact()) {
  3469     shrink_by(size);
  3473 bool ConcurrentMarkSweepGeneration::grow_by(size_t bytes) {
  3474   assert_locked_or_safepoint(Heap_lock);
  3475   bool result = _virtual_space.expand_by(bytes);
  3476   if (result) {
  3477     size_t new_word_size =
  3478       heap_word_size(_virtual_space.committed_size());
  3479     MemRegion mr(_cmsSpace->bottom(), new_word_size);
  3480     _bts->resize(new_word_size);  // resize the block offset shared array
  3481     Universe::heap()->barrier_set()->resize_covered_region(mr);
  3482     // Hmmmm... why doesn't CFLS::set_end verify locking?
  3483     // This is quite ugly; FIX ME XXX
  3484     _cmsSpace->assert_locked(freelistLock());
  3485     _cmsSpace->set_end((HeapWord*)_virtual_space.high());
  3487     // update the space and generation capacity counters
  3488     if (UsePerfData) {
  3489       _space_counters->update_capacity();
  3490       _gen_counters->update_all();
  3493     if (Verbose && PrintGC) {
  3494       size_t new_mem_size = _virtual_space.committed_size();
  3495       size_t old_mem_size = new_mem_size - bytes;
  3496       gclog_or_tty->print_cr("Expanding %s from " SIZE_FORMAT "K by " SIZE_FORMAT "K to " SIZE_FORMAT "K",
  3497                     name(), old_mem_size/K, bytes/K, new_mem_size/K);
  3500   return result;
  3503 bool ConcurrentMarkSweepGeneration::grow_to_reserved() {
  3504   assert_locked_or_safepoint(Heap_lock);
  3505   bool success = true;
  3506   const size_t remaining_bytes = _virtual_space.uncommitted_size();
  3507   if (remaining_bytes > 0) {
  3508     success = grow_by(remaining_bytes);
  3509     DEBUG_ONLY(if (!success) warning("grow to reserved failed");)
  3511   return success;
  3514 void ConcurrentMarkSweepGeneration::shrink_free_list_by(size_t bytes) {
  3515   assert_locked_or_safepoint(Heap_lock);
  3516   assert_lock_strong(freelistLock());
  3517   if (PrintGCDetails && Verbose) {
  3518     warning("Shrinking of CMS not yet implemented");
  3520   return;
  3524 // Simple ctor/dtor wrapper for accounting & timer chores around concurrent
  3525 // phases.
  3526 class CMSPhaseAccounting: public StackObj {
  3527  public:
  3528   CMSPhaseAccounting(CMSCollector *collector,
  3529                      const char *phase,
  3530                      bool print_cr = true);
  3531   ~CMSPhaseAccounting();
  3533  private:
  3534   CMSCollector *_collector;
  3535   const char *_phase;
  3536   elapsedTimer _wallclock;
  3537   bool _print_cr;
  3539  public:
  3540   // Not MT-safe; so do not pass around these StackObj's
  3541   // where they may be accessed by other threads.
  3542   jlong wallclock_millis() {
  3543     assert(_wallclock.is_active(), "Wall clock should not stop");
  3544     _wallclock.stop();  // to record time
  3545     jlong ret = _wallclock.milliseconds();
  3546     _wallclock.start(); // restart
  3547     return ret;
  3549 };
  3551 CMSPhaseAccounting::CMSPhaseAccounting(CMSCollector *collector,
  3552                                        const char *phase,
  3553                                        bool print_cr) :
  3554   _collector(collector), _phase(phase), _print_cr(print_cr) {
  3556   if (PrintCMSStatistics != 0) {
  3557     _collector->resetYields();
  3559   if (PrintGCDetails) {
  3560     gclog_or_tty->date_stamp(PrintGCDateStamps);
  3561     gclog_or_tty->stamp(PrintGCTimeStamps);
  3562     gclog_or_tty->print_cr("[%s-concurrent-%s-start]",
  3563       _collector->cmsGen()->short_name(), _phase);
  3565   _collector->resetTimer();
  3566   _wallclock.start();
  3567   _collector->startTimer();
  3570 CMSPhaseAccounting::~CMSPhaseAccounting() {
  3571   assert(_wallclock.is_active(), "Wall clock should not have stopped");
  3572   _collector->stopTimer();
  3573   _wallclock.stop();
  3574   if (PrintGCDetails) {
  3575     gclog_or_tty->date_stamp(PrintGCDateStamps);
  3576     gclog_or_tty->stamp(PrintGCTimeStamps);
  3577     gclog_or_tty->print("[%s-concurrent-%s: %3.3f/%3.3f secs]",
  3578                  _collector->cmsGen()->short_name(),
  3579                  _phase, _collector->timerValue(), _wallclock.seconds());
  3580     if (_print_cr) {
  3581       gclog_or_tty->cr();
  3583     if (PrintCMSStatistics != 0) {
  3584       gclog_or_tty->print_cr(" (CMS-concurrent-%s yielded %d times)", _phase,
  3585                     _collector->yields());
  3590 // CMS work
  3592 // The common parts of CMSParInitialMarkTask and CMSParRemarkTask.
  3593 class CMSParMarkTask : public AbstractGangTask {
  3594  protected:
  3595   CMSCollector*     _collector;
  3596   int               _n_workers;
  3597   CMSParMarkTask(const char* name, CMSCollector* collector, int n_workers) :
  3598       AbstractGangTask(name),
  3599       _collector(collector),
  3600       _n_workers(n_workers) {}
  3601   // Work method in support of parallel rescan ... of young gen spaces
  3602   void do_young_space_rescan(uint worker_id, OopsInGenClosure* cl,
  3603                              ContiguousSpace* space,
  3604                              HeapWord** chunk_array, size_t chunk_top);
  3605   void work_on_young_gen_roots(uint worker_id, OopsInGenClosure* cl);
  3606 };
  3608 // Parallel initial mark task
  3609 class CMSParInitialMarkTask: public CMSParMarkTask {
  3610  public:
  3611   CMSParInitialMarkTask(CMSCollector* collector, int n_workers) :
  3612       CMSParMarkTask("Scan roots and young gen for initial mark in parallel",
  3613                      collector, n_workers) {}
  3614   void work(uint worker_id);
  3615 };
  3617 // Checkpoint the roots into this generation from outside
  3618 // this generation. [Note this initial checkpoint need only
  3619 // be approximate -- we'll do a catch up phase subsequently.]
  3620 void CMSCollector::checkpointRootsInitial(bool asynch) {
  3621   assert(_collectorState == InitialMarking, "Wrong collector state");
  3622   check_correct_thread_executing();
  3623   TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause());
  3625   save_heap_summary();
  3626   report_heap_summary(GCWhen::BeforeGC);
  3628   ReferenceProcessor* rp = ref_processor();
  3629   SpecializationStats::clear();
  3630   assert(_restart_addr == NULL, "Control point invariant");
  3631   if (asynch) {
  3632     // acquire locks for subsequent manipulations
  3633     MutexLockerEx x(bitMapLock(),
  3634                     Mutex::_no_safepoint_check_flag);
  3635     checkpointRootsInitialWork(asynch);
  3636     // enable ("weak") refs discovery
  3637     rp->enable_discovery(true /*verify_disabled*/, true /*check_no_refs*/);
  3638     _collectorState = Marking;
  3639   } else {
  3640     // (Weak) Refs discovery: this is controlled from genCollectedHeap::do_collection
  3641     // which recognizes if we are a CMS generation, and doesn't try to turn on
  3642     // discovery; verify that they aren't meddling.
  3643     assert(!rp->discovery_is_atomic(),
  3644            "incorrect setting of discovery predicate");
  3645     assert(!rp->discovery_enabled(), "genCollectedHeap shouldn't control "
  3646            "ref discovery for this generation kind");
  3647     // already have locks
  3648     checkpointRootsInitialWork(asynch);
  3649     // now enable ("weak") refs discovery
  3650     rp->enable_discovery(true /*verify_disabled*/, false /*verify_no_refs*/);
  3651     _collectorState = Marking;
  3653   SpecializationStats::print();
  3656 void CMSCollector::checkpointRootsInitialWork(bool asynch) {
  3657   assert(SafepointSynchronize::is_at_safepoint(), "world should be stopped");
  3658   assert(_collectorState == InitialMarking, "just checking");
  3660   // If there has not been a GC[n-1] since last GC[n] cycle completed,
  3661   // precede our marking with a collection of all
  3662   // younger generations to keep floating garbage to a minimum.
  3663   // XXX: we won't do this for now -- it's an optimization to be done later.
  3665   // already have locks
  3666   assert_lock_strong(bitMapLock());
  3667   assert(_markBitMap.isAllClear(), "was reset at end of previous cycle");
  3669   // Setup the verification and class unloading state for this
  3670   // CMS collection cycle.
  3671   setup_cms_unloading_and_verification_state();
  3673   NOT_PRODUCT(GCTraceTime t("\ncheckpointRootsInitialWork",
  3674     PrintGCDetails && Verbose, true, _gc_timer_cm);)
  3675   if (UseAdaptiveSizePolicy) {
  3676     size_policy()->checkpoint_roots_initial_begin();
  3679   // Reset all the PLAB chunk arrays if necessary.
  3680   if (_survivor_plab_array != NULL && !CMSPLABRecordAlways) {
  3681     reset_survivor_plab_arrays();
  3684   ResourceMark rm;
  3685   HandleMark  hm;
  3687   FalseClosure falseClosure;
  3688   // In the case of a synchronous collection, we will elide the
  3689   // remark step, so it's important to catch all the nmethod oops
  3690   // in this step.
  3691   // The final 'true' flag to gen_process_strong_roots will ensure this.
  3692   // If 'async' is true, we can relax the nmethod tracing.
  3693   MarkRefsIntoClosure notOlder(_span, &_markBitMap);
  3694   GenCollectedHeap* gch = GenCollectedHeap::heap();
  3696   verify_work_stacks_empty();
  3697   verify_overflow_empty();
  3699   gch->ensure_parsability(false);  // fill TLABs, but no need to retire them
  3700   // Update the saved marks which may affect the root scans.
  3701   gch->save_marks();
  3703   // weak reference processing has not started yet.
  3704   ref_processor()->set_enqueuing_is_done(false);
  3706   // Need to remember all newly created CLDs,
  3707   // so that we can guarantee that the remark finds them.
  3708   ClassLoaderDataGraph::remember_new_clds(true);
  3710   // Whenever a CLD is found, it will be claimed before proceeding to mark
  3711   // the klasses. The claimed marks need to be cleared before marking starts.
  3712   ClassLoaderDataGraph::clear_claimed_marks();
  3714   if (CMSPrintEdenSurvivorChunks) {
  3715     print_eden_and_survivor_chunk_arrays();
  3719     COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;)
  3720     if (CMSParallelInitialMarkEnabled && CollectedHeap::use_parallel_gc_threads()) {
  3721       // The parallel version.
  3722       FlexibleWorkGang* workers = gch->workers();
  3723       assert(workers != NULL, "Need parallel worker threads.");
  3724       int n_workers = workers->active_workers();
  3725       CMSParInitialMarkTask tsk(this, n_workers);
  3726       gch->set_par_threads(n_workers);
  3727       initialize_sequential_subtasks_for_young_gen_rescan(n_workers);
  3728       if (n_workers > 1) {
  3729         GenCollectedHeap::StrongRootsScope srs(gch);
  3730         workers->run_task(&tsk);
  3731       } else {
  3732         GenCollectedHeap::StrongRootsScope srs(gch);
  3733         tsk.work(0);
  3735       gch->set_par_threads(0);
  3736     } else {
  3737       // The serial version.
  3738       CMKlassClosure klass_closure(&notOlder);
  3739       gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
  3740       gch->gen_process_strong_roots(_cmsGen->level(),
  3741                                     true,   // younger gens are roots
  3742                                     true,   // activate StrongRootsScope
  3743                                     false,  // not scavenging
  3744                                     SharedHeap::ScanningOption(roots_scanning_options()),
  3745                                     &notOlder,
  3746                                     true,   // walk all of code cache if (so & SO_CodeCache)
  3747                                     NULL,
  3748                                     &klass_closure);
  3752   // Clear mod-union table; it will be dirtied in the prologue of
  3753   // CMS generation per each younger generation collection.
  3755   assert(_modUnionTable.isAllClear(),
  3756        "Was cleared in most recent final checkpoint phase"
  3757        " or no bits are set in the gc_prologue before the start of the next "
  3758        "subsequent marking phase.");
  3760   assert(_ct->klass_rem_set()->mod_union_is_clear(), "Must be");
  3762   // Save the end of the used_region of the constituent generations
  3763   // to be used to limit the extent of sweep in each generation.
  3764   save_sweep_limits();
  3765   if (UseAdaptiveSizePolicy) {
  3766     size_policy()->checkpoint_roots_initial_end(gch->gc_cause());
  3768   verify_overflow_empty();
  3771 bool CMSCollector::markFromRoots(bool asynch) {
  3772   // we might be tempted to assert that:
  3773   // assert(asynch == !SafepointSynchronize::is_at_safepoint(),
  3774   //        "inconsistent argument?");
  3775   // However that wouldn't be right, because it's possible that
  3776   // a safepoint is indeed in progress as a younger generation
  3777   // stop-the-world GC happens even as we mark in this generation.
  3778   assert(_collectorState == Marking, "inconsistent state?");
  3779   check_correct_thread_executing();
  3780   verify_overflow_empty();
  3782   bool res;
  3783   if (asynch) {
  3785     // Start the timers for adaptive size policy for the concurrent phases
  3786     // Do it here so that the foreground MS can use the concurrent
  3787     // timer since a foreground MS might has the sweep done concurrently
  3788     // or STW.
  3789     if (UseAdaptiveSizePolicy) {
  3790       size_policy()->concurrent_marking_begin();
  3793     // Weak ref discovery note: We may be discovering weak
  3794     // refs in this generation concurrent (but interleaved) with
  3795     // weak ref discovery by a younger generation collector.
  3797     CMSTokenSyncWithLocks ts(true, bitMapLock());
  3798     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  3799     CMSPhaseAccounting pa(this, "mark", !PrintGCDetails);
  3800     res = markFromRootsWork(asynch);
  3801     if (res) {
  3802       _collectorState = Precleaning;
  3803     } else { // We failed and a foreground collection wants to take over
  3804       assert(_foregroundGCIsActive, "internal state inconsistency");
  3805       assert(_restart_addr == NULL,  "foreground will restart from scratch");
  3806       if (PrintGCDetails) {
  3807         gclog_or_tty->print_cr("bailing out to foreground collection");
  3810     if (UseAdaptiveSizePolicy) {
  3811       size_policy()->concurrent_marking_end();
  3813   } else {
  3814     assert(SafepointSynchronize::is_at_safepoint(),
  3815            "inconsistent with asynch == false");
  3816     if (UseAdaptiveSizePolicy) {
  3817       size_policy()->ms_collection_marking_begin();
  3819     // already have locks
  3820     res = markFromRootsWork(asynch);
  3821     _collectorState = FinalMarking;
  3822     if (UseAdaptiveSizePolicy) {
  3823       GenCollectedHeap* gch = GenCollectedHeap::heap();
  3824       size_policy()->ms_collection_marking_end(gch->gc_cause());
  3827   verify_overflow_empty();
  3828   return res;
  3831 bool CMSCollector::markFromRootsWork(bool asynch) {
  3832   // iterate over marked bits in bit map, doing a full scan and mark
  3833   // from these roots using the following algorithm:
  3834   // . if oop is to the right of the current scan pointer,
  3835   //   mark corresponding bit (we'll process it later)
  3836   // . else (oop is to left of current scan pointer)
  3837   //   push oop on marking stack
  3838   // . drain the marking stack
  3840   // Note that when we do a marking step we need to hold the
  3841   // bit map lock -- recall that direct allocation (by mutators)
  3842   // and promotion (by younger generation collectors) is also
  3843   // marking the bit map. [the so-called allocate live policy.]
  3844   // Because the implementation of bit map marking is not
  3845   // robust wrt simultaneous marking of bits in the same word,
  3846   // we need to make sure that there is no such interference
  3847   // between concurrent such updates.
  3849   // already have locks
  3850   assert_lock_strong(bitMapLock());
  3852   verify_work_stacks_empty();
  3853   verify_overflow_empty();
  3854   bool result = false;
  3855   if (CMSConcurrentMTEnabled && ConcGCThreads > 0) {
  3856     result = do_marking_mt(asynch);
  3857   } else {
  3858     result = do_marking_st(asynch);
  3860   return result;
  3863 // Forward decl
  3864 class CMSConcMarkingTask;
  3866 class CMSConcMarkingTerminator: public ParallelTaskTerminator {
  3867   CMSCollector*       _collector;
  3868   CMSConcMarkingTask* _task;
  3869  public:
  3870   virtual void yield();
  3872   // "n_threads" is the number of threads to be terminated.
  3873   // "queue_set" is a set of work queues of other threads.
  3874   // "collector" is the CMS collector associated with this task terminator.
  3875   // "yield" indicates whether we need the gang as a whole to yield.
  3876   CMSConcMarkingTerminator(int n_threads, TaskQueueSetSuper* queue_set, CMSCollector* collector) :
  3877     ParallelTaskTerminator(n_threads, queue_set),
  3878     _collector(collector) { }
  3880   void set_task(CMSConcMarkingTask* task) {
  3881     _task = task;
  3883 };
  3885 class CMSConcMarkingTerminatorTerminator: public TerminatorTerminator {
  3886   CMSConcMarkingTask* _task;
  3887  public:
  3888   bool should_exit_termination();
  3889   void set_task(CMSConcMarkingTask* task) {
  3890     _task = task;
  3892 };
  3894 // MT Concurrent Marking Task
  3895 class CMSConcMarkingTask: public YieldingFlexibleGangTask {
  3896   CMSCollector* _collector;
  3897   int           _n_workers;                  // requested/desired # workers
  3898   bool          _asynch;
  3899   bool          _result;
  3900   CompactibleFreeListSpace*  _cms_space;
  3901   char          _pad_front[64];   // padding to ...
  3902   HeapWord*     _global_finger;   // ... avoid sharing cache line
  3903   char          _pad_back[64];
  3904   HeapWord*     _restart_addr;
  3906   //  Exposed here for yielding support
  3907   Mutex* const _bit_map_lock;
  3909   // The per thread work queues, available here for stealing
  3910   OopTaskQueueSet*  _task_queues;
  3912   // Termination (and yielding) support
  3913   CMSConcMarkingTerminator _term;
  3914   CMSConcMarkingTerminatorTerminator _term_term;
  3916  public:
  3917   CMSConcMarkingTask(CMSCollector* collector,
  3918                  CompactibleFreeListSpace* cms_space,
  3919                  bool asynch,
  3920                  YieldingFlexibleWorkGang* workers,
  3921                  OopTaskQueueSet* task_queues):
  3922     YieldingFlexibleGangTask("Concurrent marking done multi-threaded"),
  3923     _collector(collector),
  3924     _cms_space(cms_space),
  3925     _asynch(asynch), _n_workers(0), _result(true),
  3926     _task_queues(task_queues),
  3927     _term(_n_workers, task_queues, _collector),
  3928     _bit_map_lock(collector->bitMapLock())
  3930     _requested_size = _n_workers;
  3931     _term.set_task(this);
  3932     _term_term.set_task(this);
  3933     _restart_addr = _global_finger = _cms_space->bottom();
  3937   OopTaskQueueSet* task_queues()  { return _task_queues; }
  3939   OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); }
  3941   HeapWord** global_finger_addr() { return &_global_finger; }
  3943   CMSConcMarkingTerminator* terminator() { return &_term; }
  3945   virtual void set_for_termination(int active_workers) {
  3946     terminator()->reset_for_reuse(active_workers);
  3949   void work(uint worker_id);
  3950   bool should_yield() {
  3951     return    ConcurrentMarkSweepThread::should_yield()
  3952            && !_collector->foregroundGCIsActive()
  3953            && _asynch;
  3956   virtual void coordinator_yield();  // stuff done by coordinator
  3957   bool result() { return _result; }
  3959   void reset(HeapWord* ra) {
  3960     assert(_global_finger >= _cms_space->end(),  "Postcondition of ::work(i)");
  3961     _restart_addr = _global_finger = ra;
  3962     _term.reset_for_reuse();
  3965   static bool get_work_from_overflow_stack(CMSMarkStack* ovflw_stk,
  3966                                            OopTaskQueue* work_q);
  3968  private:
  3969   void do_scan_and_mark(int i, CompactibleFreeListSpace* sp);
  3970   void do_work_steal(int i);
  3971   void bump_global_finger(HeapWord* f);
  3972 };
  3974 bool CMSConcMarkingTerminatorTerminator::should_exit_termination() {
  3975   assert(_task != NULL, "Error");
  3976   return _task->yielding();
  3977   // Note that we do not need the disjunct || _task->should_yield() above
  3978   // because we want terminating threads to yield only if the task
  3979   // is already in the midst of yielding, which happens only after at least one
  3980   // thread has yielded.
  3983 void CMSConcMarkingTerminator::yield() {
  3984   if (_task->should_yield()) {
  3985     _task->yield();
  3986   } else {
  3987     ParallelTaskTerminator::yield();
  3991 ////////////////////////////////////////////////////////////////
  3992 // Concurrent Marking Algorithm Sketch
  3993 ////////////////////////////////////////////////////////////////
  3994 // Until all tasks exhausted (both spaces):
  3995 // -- claim next available chunk
  3996 // -- bump global finger via CAS
  3997 // -- find first object that starts in this chunk
  3998 //    and start scanning bitmap from that position
  3999 // -- scan marked objects for oops
  4000 // -- CAS-mark target, and if successful:
  4001 //    . if target oop is above global finger (volatile read)
  4002 //      nothing to do
  4003 //    . if target oop is in chunk and above local finger
  4004 //        then nothing to do
  4005 //    . else push on work-queue
  4006 // -- Deal with possible overflow issues:
  4007 //    . local work-queue overflow causes stuff to be pushed on
  4008 //      global (common) overflow queue
  4009 //    . always first empty local work queue
  4010 //    . then get a batch of oops from global work queue if any
  4011 //    . then do work stealing
  4012 // -- When all tasks claimed (both spaces)
  4013 //    and local work queue empty,
  4014 //    then in a loop do:
  4015 //    . check global overflow stack; steal a batch of oops and trace
  4016 //    . try to steal from other threads oif GOS is empty
  4017 //    . if neither is available, offer termination
  4018 // -- Terminate and return result
  4019 //
  4020 void CMSConcMarkingTask::work(uint worker_id) {
  4021   elapsedTimer _timer;
  4022   ResourceMark rm;
  4023   HandleMark hm;
  4025   DEBUG_ONLY(_collector->verify_overflow_empty();)
  4027   // Before we begin work, our work queue should be empty
  4028   assert(work_queue(worker_id)->size() == 0, "Expected to be empty");
  4029   // Scan the bitmap covering _cms_space, tracing through grey objects.
  4030   _timer.start();
  4031   do_scan_and_mark(worker_id, _cms_space);
  4032   _timer.stop();
  4033   if (PrintCMSStatistics != 0) {
  4034     gclog_or_tty->print_cr("Finished cms space scanning in %dth thread: %3.3f sec",
  4035       worker_id, _timer.seconds());
  4036       // XXX: need xxx/xxx type of notation, two timers
  4039   // ... do work stealing
  4040   _timer.reset();
  4041   _timer.start();
  4042   do_work_steal(worker_id);
  4043   _timer.stop();
  4044   if (PrintCMSStatistics != 0) {
  4045     gclog_or_tty->print_cr("Finished work stealing in %dth thread: %3.3f sec",
  4046       worker_id, _timer.seconds());
  4047       // XXX: need xxx/xxx type of notation, two timers
  4049   assert(_collector->_markStack.isEmpty(), "Should have been emptied");
  4050   assert(work_queue(worker_id)->size() == 0, "Should have been emptied");
  4051   // Note that under the current task protocol, the
  4052   // following assertion is true even of the spaces
  4053   // expanded since the completion of the concurrent
  4054   // marking. XXX This will likely change under a strict
  4055   // ABORT semantics.
  4056   // After perm removal the comparison was changed to
  4057   // greater than or equal to from strictly greater than.
  4058   // Before perm removal the highest address sweep would
  4059   // have been at the end of perm gen but now is at the
  4060   // end of the tenured gen.
  4061   assert(_global_finger >=  _cms_space->end(),
  4062          "All tasks have been completed");
  4063   DEBUG_ONLY(_collector->verify_overflow_empty();)
  4066 void CMSConcMarkingTask::bump_global_finger(HeapWord* f) {
  4067   HeapWord* read = _global_finger;
  4068   HeapWord* cur  = read;
  4069   while (f > read) {
  4070     cur = read;
  4071     read = (HeapWord*) Atomic::cmpxchg_ptr(f, &_global_finger, cur);
  4072     if (cur == read) {
  4073       // our cas succeeded
  4074       assert(_global_finger >= f, "protocol consistency");
  4075       break;
  4080 // This is really inefficient, and should be redone by
  4081 // using (not yet available) block-read and -write interfaces to the
  4082 // stack and the work_queue. XXX FIX ME !!!
  4083 bool CMSConcMarkingTask::get_work_from_overflow_stack(CMSMarkStack* ovflw_stk,
  4084                                                       OopTaskQueue* work_q) {
  4085   // Fast lock-free check
  4086   if (ovflw_stk->length() == 0) {
  4087     return false;
  4089   assert(work_q->size() == 0, "Shouldn't steal");
  4090   MutexLockerEx ml(ovflw_stk->par_lock(),
  4091                    Mutex::_no_safepoint_check_flag);
  4092   // Grab up to 1/4 the size of the work queue
  4093   size_t num = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
  4094                     (size_t)ParGCDesiredObjsFromOverflowList);
  4095   num = MIN2(num, ovflw_stk->length());
  4096   for (int i = (int) num; i > 0; i--) {
  4097     oop cur = ovflw_stk->pop();
  4098     assert(cur != NULL, "Counted wrong?");
  4099     work_q->push(cur);
  4101   return num > 0;
  4104 void CMSConcMarkingTask::do_scan_and_mark(int i, CompactibleFreeListSpace* sp) {
  4105   SequentialSubTasksDone* pst = sp->conc_par_seq_tasks();
  4106   int n_tasks = pst->n_tasks();
  4107   // We allow that there may be no tasks to do here because
  4108   // we are restarting after a stack overflow.
  4109   assert(pst->valid() || n_tasks == 0, "Uninitialized use?");
  4110   uint nth_task = 0;
  4112   HeapWord* aligned_start = sp->bottom();
  4113   if (sp->used_region().contains(_restart_addr)) {
  4114     // Align down to a card boundary for the start of 0th task
  4115     // for this space.
  4116     aligned_start =
  4117       (HeapWord*)align_size_down((uintptr_t)_restart_addr,
  4118                                  CardTableModRefBS::card_size);
  4121   size_t chunk_size = sp->marking_task_size();
  4122   while (!pst->is_task_claimed(/* reference */ nth_task)) {
  4123     // Having claimed the nth task in this space,
  4124     // compute the chunk that it corresponds to:
  4125     MemRegion span = MemRegion(aligned_start + nth_task*chunk_size,
  4126                                aligned_start + (nth_task+1)*chunk_size);
  4127     // Try and bump the global finger via a CAS;
  4128     // note that we need to do the global finger bump
  4129     // _before_ taking the intersection below, because
  4130     // the task corresponding to that region will be
  4131     // deemed done even if the used_region() expands
  4132     // because of allocation -- as it almost certainly will
  4133     // during start-up while the threads yield in the
  4134     // closure below.
  4135     HeapWord* finger = span.end();
  4136     bump_global_finger(finger);   // atomically
  4137     // There are null tasks here corresponding to chunks
  4138     // beyond the "top" address of the space.
  4139     span = span.intersection(sp->used_region());
  4140     if (!span.is_empty()) {  // Non-null task
  4141       HeapWord* prev_obj;
  4142       assert(!span.contains(_restart_addr) || nth_task == 0,
  4143              "Inconsistency");
  4144       if (nth_task == 0) {
  4145         // For the 0th task, we'll not need to compute a block_start.
  4146         if (span.contains(_restart_addr)) {
  4147           // In the case of a restart because of stack overflow,
  4148           // we might additionally skip a chunk prefix.
  4149           prev_obj = _restart_addr;
  4150         } else {
  4151           prev_obj = span.start();
  4153       } else {
  4154         // We want to skip the first object because
  4155         // the protocol is to scan any object in its entirety
  4156         // that _starts_ in this span; a fortiori, any
  4157         // object starting in an earlier span is scanned
  4158         // as part of an earlier claimed task.
  4159         // Below we use the "careful" version of block_start
  4160         // so we do not try to navigate uninitialized objects.
  4161         prev_obj = sp->block_start_careful(span.start());
  4162         // Below we use a variant of block_size that uses the
  4163         // Printezis bits to avoid waiting for allocated
  4164         // objects to become initialized/parsable.
  4165         while (prev_obj < span.start()) {
  4166           size_t sz = sp->block_size_no_stall(prev_obj, _collector);
  4167           if (sz > 0) {
  4168             prev_obj += sz;
  4169           } else {
  4170             // In this case we may end up doing a bit of redundant
  4171             // scanning, but that appears unavoidable, short of
  4172             // locking the free list locks; see bug 6324141.
  4173             break;
  4177       if (prev_obj < span.end()) {
  4178         MemRegion my_span = MemRegion(prev_obj, span.end());
  4179         // Do the marking work within a non-empty span --
  4180         // the last argument to the constructor indicates whether the
  4181         // iteration should be incremental with periodic yields.
  4182         Par_MarkFromRootsClosure cl(this, _collector, my_span,
  4183                                     &_collector->_markBitMap,
  4184                                     work_queue(i),
  4185                                     &_collector->_markStack,
  4186                                     _asynch);
  4187         _collector->_markBitMap.iterate(&cl, my_span.start(), my_span.end());
  4188       } // else nothing to do for this task
  4189     }   // else nothing to do for this task
  4191   // We'd be tempted to assert here that since there are no
  4192   // more tasks left to claim in this space, the global_finger
  4193   // must exceed space->top() and a fortiori space->end(). However,
  4194   // that would not quite be correct because the bumping of
  4195   // global_finger occurs strictly after the claiming of a task,
  4196   // so by the time we reach here the global finger may not yet
  4197   // have been bumped up by the thread that claimed the last
  4198   // task.
  4199   pst->all_tasks_completed();
  4202 class Par_ConcMarkingClosure: public CMSOopClosure {
  4203  private:
  4204   CMSCollector* _collector;
  4205   CMSConcMarkingTask* _task;
  4206   MemRegion     _span;
  4207   CMSBitMap*    _bit_map;
  4208   CMSMarkStack* _overflow_stack;
  4209   OopTaskQueue* _work_queue;
  4210  protected:
  4211   DO_OOP_WORK_DEFN
  4212  public:
  4213   Par_ConcMarkingClosure(CMSCollector* collector, CMSConcMarkingTask* task, OopTaskQueue* work_queue,
  4214                          CMSBitMap* bit_map, CMSMarkStack* overflow_stack):
  4215     CMSOopClosure(collector->ref_processor()),
  4216     _collector(collector),
  4217     _task(task),
  4218     _span(collector->_span),
  4219     _work_queue(work_queue),
  4220     _bit_map(bit_map),
  4221     _overflow_stack(overflow_stack)
  4222   { }
  4223   virtual void do_oop(oop* p);
  4224   virtual void do_oop(narrowOop* p);
  4226   void trim_queue(size_t max);
  4227   void handle_stack_overflow(HeapWord* lost);
  4228   void do_yield_check() {
  4229     if (_task->should_yield()) {
  4230       _task->yield();
  4233 };
  4235 // Grey object scanning during work stealing phase --
  4236 // the salient assumption here is that any references
  4237 // that are in these stolen objects being scanned must
  4238 // already have been initialized (else they would not have
  4239 // been published), so we do not need to check for
  4240 // uninitialized objects before pushing here.
  4241 void Par_ConcMarkingClosure::do_oop(oop obj) {
  4242   assert(obj->is_oop_or_null(true), "expected an oop or NULL");
  4243   HeapWord* addr = (HeapWord*)obj;
  4244   // Check if oop points into the CMS generation
  4245   // and is not marked
  4246   if (_span.contains(addr) && !_bit_map->isMarked(addr)) {
  4247     // a white object ...
  4248     // If we manage to "claim" the object, by being the
  4249     // first thread to mark it, then we push it on our
  4250     // marking stack
  4251     if (_bit_map->par_mark(addr)) {     // ... now grey
  4252       // push on work queue (grey set)
  4253       bool simulate_overflow = false;
  4254       NOT_PRODUCT(
  4255         if (CMSMarkStackOverflowALot &&
  4256             _collector->simulate_overflow()) {
  4257           // simulate a stack overflow
  4258           simulate_overflow = true;
  4261       if (simulate_overflow ||
  4262           !(_work_queue->push(obj) || _overflow_stack->par_push(obj))) {
  4263         // stack overflow
  4264         if (PrintCMSStatistics != 0) {
  4265           gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
  4266                                  SIZE_FORMAT, _overflow_stack->capacity());
  4268         // We cannot assert that the overflow stack is full because
  4269         // it may have been emptied since.
  4270         assert(simulate_overflow ||
  4271                _work_queue->size() == _work_queue->max_elems(),
  4272               "Else push should have succeeded");
  4273         handle_stack_overflow(addr);
  4275     } // Else, some other thread got there first
  4276     do_yield_check();
  4280 void Par_ConcMarkingClosure::do_oop(oop* p)       { Par_ConcMarkingClosure::do_oop_work(p); }
  4281 void Par_ConcMarkingClosure::do_oop(narrowOop* p) { Par_ConcMarkingClosure::do_oop_work(p); }
  4283 void Par_ConcMarkingClosure::trim_queue(size_t max) {
  4284   while (_work_queue->size() > max) {
  4285     oop new_oop;
  4286     if (_work_queue->pop_local(new_oop)) {
  4287       assert(new_oop->is_oop(), "Should be an oop");
  4288       assert(_bit_map->isMarked((HeapWord*)new_oop), "Grey object");
  4289       assert(_span.contains((HeapWord*)new_oop), "Not in span");
  4290       new_oop->oop_iterate(this);  // do_oop() above
  4291       do_yield_check();
  4296 // Upon stack overflow, we discard (part of) the stack,
  4297 // remembering the least address amongst those discarded
  4298 // in CMSCollector's _restart_address.
  4299 void Par_ConcMarkingClosure::handle_stack_overflow(HeapWord* lost) {
  4300   // We need to do this under a mutex to prevent other
  4301   // workers from interfering with the work done below.
  4302   MutexLockerEx ml(_overflow_stack->par_lock(),
  4303                    Mutex::_no_safepoint_check_flag);
  4304   // Remember the least grey address discarded
  4305   HeapWord* ra = (HeapWord*)_overflow_stack->least_value(lost);
  4306   _collector->lower_restart_addr(ra);
  4307   _overflow_stack->reset();  // discard stack contents
  4308   _overflow_stack->expand(); // expand the stack if possible
  4312 void CMSConcMarkingTask::do_work_steal(int i) {
  4313   OopTaskQueue* work_q = work_queue(i);
  4314   oop obj_to_scan;
  4315   CMSBitMap* bm = &(_collector->_markBitMap);
  4316   CMSMarkStack* ovflw = &(_collector->_markStack);
  4317   int* seed = _collector->hash_seed(i);
  4318   Par_ConcMarkingClosure cl(_collector, this, work_q, bm, ovflw);
  4319   while (true) {
  4320     cl.trim_queue(0);
  4321     assert(work_q->size() == 0, "Should have been emptied above");
  4322     if (get_work_from_overflow_stack(ovflw, work_q)) {
  4323       // Can't assert below because the work obtained from the
  4324       // overflow stack may already have been stolen from us.
  4325       // assert(work_q->size() > 0, "Work from overflow stack");
  4326       continue;
  4327     } else if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) {
  4328       assert(obj_to_scan->is_oop(), "Should be an oop");
  4329       assert(bm->isMarked((HeapWord*)obj_to_scan), "Grey object");
  4330       obj_to_scan->oop_iterate(&cl);
  4331     } else if (terminator()->offer_termination(&_term_term)) {
  4332       assert(work_q->size() == 0, "Impossible!");
  4333       break;
  4334     } else if (yielding() || should_yield()) {
  4335       yield();
  4340 // This is run by the CMS (coordinator) thread.
  4341 void CMSConcMarkingTask::coordinator_yield() {
  4342   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  4343          "CMS thread should hold CMS token");
  4344   // First give up the locks, then yield, then re-lock
  4345   // We should probably use a constructor/destructor idiom to
  4346   // do this unlock/lock or modify the MutexUnlocker class to
  4347   // serve our purpose. XXX
  4348   assert_lock_strong(_bit_map_lock);
  4349   _bit_map_lock->unlock();
  4350   ConcurrentMarkSweepThread::desynchronize(true);
  4351   ConcurrentMarkSweepThread::acknowledge_yield_request();
  4352   _collector->stopTimer();
  4353   if (PrintCMSStatistics != 0) {
  4354     _collector->incrementYields();
  4356   _collector->icms_wait();
  4358   // It is possible for whichever thread initiated the yield request
  4359   // not to get a chance to wake up and take the bitmap lock between
  4360   // this thread releasing it and reacquiring it. So, while the
  4361   // should_yield() flag is on, let's sleep for a bit to give the
  4362   // other thread a chance to wake up. The limit imposed on the number
  4363   // of iterations is defensive, to avoid any unforseen circumstances
  4364   // putting us into an infinite loop. Since it's always been this
  4365   // (coordinator_yield()) method that was observed to cause the
  4366   // problem, we are using a parameter (CMSCoordinatorYieldSleepCount)
  4367   // which is by default non-zero. For the other seven methods that
  4368   // also perform the yield operation, as are using a different
  4369   // parameter (CMSYieldSleepCount) which is by default zero. This way we
  4370   // can enable the sleeping for those methods too, if necessary.
  4371   // See 6442774.
  4372   //
  4373   // We really need to reconsider the synchronization between the GC
  4374   // thread and the yield-requesting threads in the future and we
  4375   // should really use wait/notify, which is the recommended
  4376   // way of doing this type of interaction. Additionally, we should
  4377   // consolidate the eight methods that do the yield operation and they
  4378   // are almost identical into one for better maintenability and
  4379   // readability. See 6445193.
  4380   //
  4381   // Tony 2006.06.29
  4382   for (unsigned i = 0; i < CMSCoordinatorYieldSleepCount &&
  4383                    ConcurrentMarkSweepThread::should_yield() &&
  4384                    !CMSCollector::foregroundGCIsActive(); ++i) {
  4385     os::sleep(Thread::current(), 1, false);
  4386     ConcurrentMarkSweepThread::acknowledge_yield_request();
  4389   ConcurrentMarkSweepThread::synchronize(true);
  4390   _bit_map_lock->lock_without_safepoint_check();
  4391   _collector->startTimer();
  4394 bool CMSCollector::do_marking_mt(bool asynch) {
  4395   assert(ConcGCThreads > 0 && conc_workers() != NULL, "precondition");
  4396   int num_workers = AdaptiveSizePolicy::calc_active_conc_workers(
  4397                                        conc_workers()->total_workers(),
  4398                                        conc_workers()->active_workers(),
  4399                                        Threads::number_of_non_daemon_threads());
  4400   conc_workers()->set_active_workers(num_workers);
  4402   CompactibleFreeListSpace* cms_space  = _cmsGen->cmsSpace();
  4404   CMSConcMarkingTask tsk(this,
  4405                          cms_space,
  4406                          asynch,
  4407                          conc_workers(),
  4408                          task_queues());
  4410   // Since the actual number of workers we get may be different
  4411   // from the number we requested above, do we need to do anything different
  4412   // below? In particular, may be we need to subclass the SequantialSubTasksDone
  4413   // class?? XXX
  4414   cms_space ->initialize_sequential_subtasks_for_marking(num_workers);
  4416   // Refs discovery is already non-atomic.
  4417   assert(!ref_processor()->discovery_is_atomic(), "Should be non-atomic");
  4418   assert(ref_processor()->discovery_is_mt(), "Discovery should be MT");
  4419   conc_workers()->start_task(&tsk);
  4420   while (tsk.yielded()) {
  4421     tsk.coordinator_yield();
  4422     conc_workers()->continue_task(&tsk);
  4424   // If the task was aborted, _restart_addr will be non-NULL
  4425   assert(tsk.completed() || _restart_addr != NULL, "Inconsistency");
  4426   while (_restart_addr != NULL) {
  4427     // XXX For now we do not make use of ABORTED state and have not
  4428     // yet implemented the right abort semantics (even in the original
  4429     // single-threaded CMS case). That needs some more investigation
  4430     // and is deferred for now; see CR# TBF. 07252005YSR. XXX
  4431     assert(!CMSAbortSemantics || tsk.aborted(), "Inconsistency");
  4432     // If _restart_addr is non-NULL, a marking stack overflow
  4433     // occurred; we need to do a fresh marking iteration from the
  4434     // indicated restart address.
  4435     if (_foregroundGCIsActive && asynch) {
  4436       // We may be running into repeated stack overflows, having
  4437       // reached the limit of the stack size, while making very
  4438       // slow forward progress. It may be best to bail out and
  4439       // let the foreground collector do its job.
  4440       // Clear _restart_addr, so that foreground GC
  4441       // works from scratch. This avoids the headache of
  4442       // a "rescan" which would otherwise be needed because
  4443       // of the dirty mod union table & card table.
  4444       _restart_addr = NULL;
  4445       return false;
  4447     // Adjust the task to restart from _restart_addr
  4448     tsk.reset(_restart_addr);
  4449     cms_space ->initialize_sequential_subtasks_for_marking(num_workers,
  4450                   _restart_addr);
  4451     _restart_addr = NULL;
  4452     // Get the workers going again
  4453     conc_workers()->start_task(&tsk);
  4454     while (tsk.yielded()) {
  4455       tsk.coordinator_yield();
  4456       conc_workers()->continue_task(&tsk);
  4459   assert(tsk.completed(), "Inconsistency");
  4460   assert(tsk.result() == true, "Inconsistency");
  4461   return true;
  4464 bool CMSCollector::do_marking_st(bool asynch) {
  4465   ResourceMark rm;
  4466   HandleMark   hm;
  4468   // Temporarily make refs discovery single threaded (non-MT)
  4469   ReferenceProcessorMTDiscoveryMutator rp_mut_discovery(ref_processor(), false);
  4470   MarkFromRootsClosure markFromRootsClosure(this, _span, &_markBitMap,
  4471     &_markStack, CMSYield && asynch);
  4472   // the last argument to iterate indicates whether the iteration
  4473   // should be incremental with periodic yields.
  4474   _markBitMap.iterate(&markFromRootsClosure);
  4475   // If _restart_addr is non-NULL, a marking stack overflow
  4476   // occurred; we need to do a fresh iteration from the
  4477   // indicated restart address.
  4478   while (_restart_addr != NULL) {
  4479     if (_foregroundGCIsActive && asynch) {
  4480       // We may be running into repeated stack overflows, having
  4481       // reached the limit of the stack size, while making very
  4482       // slow forward progress. It may be best to bail out and
  4483       // let the foreground collector do its job.
  4484       // Clear _restart_addr, so that foreground GC
  4485       // works from scratch. This avoids the headache of
  4486       // a "rescan" which would otherwise be needed because
  4487       // of the dirty mod union table & card table.
  4488       _restart_addr = NULL;
  4489       return false;  // indicating failure to complete marking
  4491     // Deal with stack overflow:
  4492     // we restart marking from _restart_addr
  4493     HeapWord* ra = _restart_addr;
  4494     markFromRootsClosure.reset(ra);
  4495     _restart_addr = NULL;
  4496     _markBitMap.iterate(&markFromRootsClosure, ra, _span.end());
  4498   return true;
  4501 void CMSCollector::preclean() {
  4502   check_correct_thread_executing();
  4503   assert(Thread::current()->is_ConcurrentGC_thread(), "Wrong thread");
  4504   verify_work_stacks_empty();
  4505   verify_overflow_empty();
  4506   _abort_preclean = false;
  4507   if (CMSPrecleaningEnabled) {
  4508     if (!CMSEdenChunksRecordAlways) {
  4509       _eden_chunk_index = 0;
  4511     size_t used = get_eden_used();
  4512     size_t capacity = get_eden_capacity();
  4513     // Don't start sampling unless we will get sufficiently
  4514     // many samples.
  4515     if (used < (capacity/(CMSScheduleRemarkSamplingRatio * 100)
  4516                 * CMSScheduleRemarkEdenPenetration)) {
  4517       _start_sampling = true;
  4518     } else {
  4519       _start_sampling = false;
  4521     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  4522     CMSPhaseAccounting pa(this, "preclean", !PrintGCDetails);
  4523     preclean_work(CMSPrecleanRefLists1, CMSPrecleanSurvivors1);
  4525   CMSTokenSync x(true); // is cms thread
  4526   if (CMSPrecleaningEnabled) {
  4527     sample_eden();
  4528     _collectorState = AbortablePreclean;
  4529   } else {
  4530     _collectorState = FinalMarking;
  4532   verify_work_stacks_empty();
  4533   verify_overflow_empty();
  4536 // Try and schedule the remark such that young gen
  4537 // occupancy is CMSScheduleRemarkEdenPenetration %.
  4538 void CMSCollector::abortable_preclean() {
  4539   check_correct_thread_executing();
  4540   assert(CMSPrecleaningEnabled,  "Inconsistent control state");
  4541   assert(_collectorState == AbortablePreclean, "Inconsistent control state");
  4543   // If Eden's current occupancy is below this threshold,
  4544   // immediately schedule the remark; else preclean
  4545   // past the next scavenge in an effort to
  4546   // schedule the pause as described avove. By choosing
  4547   // CMSScheduleRemarkEdenSizeThreshold >= max eden size
  4548   // we will never do an actual abortable preclean cycle.
  4549   if (get_eden_used() > CMSScheduleRemarkEdenSizeThreshold) {
  4550     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  4551     CMSPhaseAccounting pa(this, "abortable-preclean", !PrintGCDetails);
  4552     // We need more smarts in the abortable preclean
  4553     // loop below to deal with cases where allocation
  4554     // in young gen is very very slow, and our precleaning
  4555     // is running a losing race against a horde of
  4556     // mutators intent on flooding us with CMS updates
  4557     // (dirty cards).
  4558     // One, admittedly dumb, strategy is to give up
  4559     // after a certain number of abortable precleaning loops
  4560     // or after a certain maximum time. We want to make
  4561     // this smarter in the next iteration.
  4562     // XXX FIX ME!!! YSR
  4563     size_t loops = 0, workdone = 0, cumworkdone = 0, waited = 0;
  4564     while (!(should_abort_preclean() ||
  4565              ConcurrentMarkSweepThread::should_terminate())) {
  4566       workdone = preclean_work(CMSPrecleanRefLists2, CMSPrecleanSurvivors2);
  4567       cumworkdone += workdone;
  4568       loops++;
  4569       // Voluntarily terminate abortable preclean phase if we have
  4570       // been at it for too long.
  4571       if ((CMSMaxAbortablePrecleanLoops != 0) &&
  4572           loops >= CMSMaxAbortablePrecleanLoops) {
  4573         if (PrintGCDetails) {
  4574           gclog_or_tty->print(" CMS: abort preclean due to loops ");
  4576         break;
  4578       if (pa.wallclock_millis() > CMSMaxAbortablePrecleanTime) {
  4579         if (PrintGCDetails) {
  4580           gclog_or_tty->print(" CMS: abort preclean due to time ");
  4582         break;
  4584       // If we are doing little work each iteration, we should
  4585       // take a short break.
  4586       if (workdone < CMSAbortablePrecleanMinWorkPerIteration) {
  4587         // Sleep for some time, waiting for work to accumulate
  4588         stopTimer();
  4589         cmsThread()->wait_on_cms_lock(CMSAbortablePrecleanWaitMillis);
  4590         startTimer();
  4591         waited++;
  4594     if (PrintCMSStatistics > 0) {
  4595       gclog_or_tty->print(" [%d iterations, %d waits, %d cards)] ",
  4596                           loops, waited, cumworkdone);
  4599   CMSTokenSync x(true); // is cms thread
  4600   if (_collectorState != Idling) {
  4601     assert(_collectorState == AbortablePreclean,
  4602            "Spontaneous state transition?");
  4603     _collectorState = FinalMarking;
  4604   } // Else, a foreground collection completed this CMS cycle.
  4605   return;
  4608 // Respond to an Eden sampling opportunity
  4609 void CMSCollector::sample_eden() {
  4610   // Make sure a young gc cannot sneak in between our
  4611   // reading and recording of a sample.
  4612   assert(Thread::current()->is_ConcurrentGC_thread(),
  4613          "Only the cms thread may collect Eden samples");
  4614   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  4615          "Should collect samples while holding CMS token");
  4616   if (!_start_sampling) {
  4617     return;
  4619   // When CMSEdenChunksRecordAlways is true, the eden chunk array
  4620   // is populated by the young generation.
  4621   if (_eden_chunk_array != NULL && !CMSEdenChunksRecordAlways) {
  4622     if (_eden_chunk_index < _eden_chunk_capacity) {
  4623       _eden_chunk_array[_eden_chunk_index] = *_top_addr;   // take sample
  4624       assert(_eden_chunk_array[_eden_chunk_index] <= *_end_addr,
  4625              "Unexpected state of Eden");
  4626       // We'd like to check that what we just sampled is an oop-start address;
  4627       // however, we cannot do that here since the object may not yet have been
  4628       // initialized. So we'll instead do the check when we _use_ this sample
  4629       // later.
  4630       if (_eden_chunk_index == 0 ||
  4631           (pointer_delta(_eden_chunk_array[_eden_chunk_index],
  4632                          _eden_chunk_array[_eden_chunk_index-1])
  4633            >= CMSSamplingGrain)) {
  4634         _eden_chunk_index++;  // commit sample
  4638   if ((_collectorState == AbortablePreclean) && !_abort_preclean) {
  4639     size_t used = get_eden_used();
  4640     size_t capacity = get_eden_capacity();
  4641     assert(used <= capacity, "Unexpected state of Eden");
  4642     if (used >  (capacity/100 * CMSScheduleRemarkEdenPenetration)) {
  4643       _abort_preclean = true;
  4649 size_t CMSCollector::preclean_work(bool clean_refs, bool clean_survivor) {
  4650   assert(_collectorState == Precleaning ||
  4651          _collectorState == AbortablePreclean, "incorrect state");
  4652   ResourceMark rm;
  4653   HandleMark   hm;
  4655   // Precleaning is currently not MT but the reference processor
  4656   // may be set for MT.  Disable it temporarily here.
  4657   ReferenceProcessor* rp = ref_processor();
  4658   ReferenceProcessorMTDiscoveryMutator rp_mut_discovery(rp, false);
  4660   // Do one pass of scrubbing the discovered reference lists
  4661   // to remove any reference objects with strongly-reachable
  4662   // referents.
  4663   if (clean_refs) {
  4664     CMSPrecleanRefsYieldClosure yield_cl(this);
  4665     assert(rp->span().equals(_span), "Spans should be equal");
  4666     CMSKeepAliveClosure keep_alive(this, _span, &_markBitMap,
  4667                                    &_markStack, true /* preclean */);
  4668     CMSDrainMarkingStackClosure complete_trace(this,
  4669                                    _span, &_markBitMap, &_markStack,
  4670                                    &keep_alive, true /* preclean */);
  4672     // We don't want this step to interfere with a young
  4673     // collection because we don't want to take CPU
  4674     // or memory bandwidth away from the young GC threads
  4675     // (which may be as many as there are CPUs).
  4676     // Note that we don't need to protect ourselves from
  4677     // interference with mutators because they can't
  4678     // manipulate the discovered reference lists nor affect
  4679     // the computed reachability of the referents, the
  4680     // only properties manipulated by the precleaning
  4681     // of these reference lists.
  4682     stopTimer();
  4683     CMSTokenSyncWithLocks x(true /* is cms thread */,
  4684                             bitMapLock());
  4685     startTimer();
  4686     sample_eden();
  4688     // The following will yield to allow foreground
  4689     // collection to proceed promptly. XXX YSR:
  4690     // The code in this method may need further
  4691     // tweaking for better performance and some restructuring
  4692     // for cleaner interfaces.
  4693     GCTimer *gc_timer = NULL; // Currently not tracing concurrent phases
  4694     rp->preclean_discovered_references(
  4695           rp->is_alive_non_header(), &keep_alive, &complete_trace, &yield_cl,
  4696           gc_timer);
  4699   if (clean_survivor) {  // preclean the active survivor space(s)
  4700     assert(_young_gen->kind() == Generation::DefNew ||
  4701            _young_gen->kind() == Generation::ParNew ||
  4702            _young_gen->kind() == Generation::ASParNew,
  4703          "incorrect type for cast");
  4704     DefNewGeneration* dng = (DefNewGeneration*)_young_gen;
  4705     PushAndMarkClosure pam_cl(this, _span, ref_processor(),
  4706                              &_markBitMap, &_modUnionTable,
  4707                              &_markStack, true /* precleaning phase */);
  4708     stopTimer();
  4709     CMSTokenSyncWithLocks ts(true /* is cms thread */,
  4710                              bitMapLock());
  4711     startTimer();
  4712     unsigned int before_count =
  4713       GenCollectedHeap::heap()->total_collections();
  4714     SurvivorSpacePrecleanClosure
  4715       sss_cl(this, _span, &_markBitMap, &_markStack,
  4716              &pam_cl, before_count, CMSYield);
  4717     dng->from()->object_iterate_careful(&sss_cl);
  4718     dng->to()->object_iterate_careful(&sss_cl);
  4720   MarkRefsIntoAndScanClosure
  4721     mrias_cl(_span, ref_processor(), &_markBitMap, &_modUnionTable,
  4722              &_markStack, this, CMSYield,
  4723              true /* precleaning phase */);
  4724   // CAUTION: The following closure has persistent state that may need to
  4725   // be reset upon a decrease in the sequence of addresses it
  4726   // processes.
  4727   ScanMarkedObjectsAgainCarefullyClosure
  4728     smoac_cl(this, _span,
  4729       &_markBitMap, &_markStack, &mrias_cl, CMSYield);
  4731   // Preclean dirty cards in ModUnionTable and CardTable using
  4732   // appropriate convergence criterion;
  4733   // repeat CMSPrecleanIter times unless we find that
  4734   // we are losing.
  4735   assert(CMSPrecleanIter < 10, "CMSPrecleanIter is too large");
  4736   assert(CMSPrecleanNumerator < CMSPrecleanDenominator,
  4737          "Bad convergence multiplier");
  4738   assert(CMSPrecleanThreshold >= 100,
  4739          "Unreasonably low CMSPrecleanThreshold");
  4741   size_t numIter, cumNumCards, lastNumCards, curNumCards;
  4742   for (numIter = 0, cumNumCards = lastNumCards = curNumCards = 0;
  4743        numIter < CMSPrecleanIter;
  4744        numIter++, lastNumCards = curNumCards, cumNumCards += curNumCards) {
  4745     curNumCards  = preclean_mod_union_table(_cmsGen, &smoac_cl);
  4746     if (Verbose && PrintGCDetails) {
  4747       gclog_or_tty->print(" (modUnionTable: %d cards)", curNumCards);
  4749     // Either there are very few dirty cards, so re-mark
  4750     // pause will be small anyway, or our pre-cleaning isn't
  4751     // that much faster than the rate at which cards are being
  4752     // dirtied, so we might as well stop and re-mark since
  4753     // precleaning won't improve our re-mark time by much.
  4754     if (curNumCards <= CMSPrecleanThreshold ||
  4755         (numIter > 0 &&
  4756          (curNumCards * CMSPrecleanDenominator >
  4757          lastNumCards * CMSPrecleanNumerator))) {
  4758       numIter++;
  4759       cumNumCards += curNumCards;
  4760       break;
  4764   preclean_klasses(&mrias_cl, _cmsGen->freelistLock());
  4766   curNumCards = preclean_card_table(_cmsGen, &smoac_cl);
  4767   cumNumCards += curNumCards;
  4768   if (PrintGCDetails && PrintCMSStatistics != 0) {
  4769     gclog_or_tty->print_cr(" (cardTable: %d cards, re-scanned %d cards, %d iterations)",
  4770                   curNumCards, cumNumCards, numIter);
  4772   return cumNumCards;   // as a measure of useful work done
  4775 // PRECLEANING NOTES:
  4776 // Precleaning involves:
  4777 // . reading the bits of the modUnionTable and clearing the set bits.
  4778 // . For the cards corresponding to the set bits, we scan the
  4779 //   objects on those cards. This means we need the free_list_lock
  4780 //   so that we can safely iterate over the CMS space when scanning
  4781 //   for oops.
  4782 // . When we scan the objects, we'll be both reading and setting
  4783 //   marks in the marking bit map, so we'll need the marking bit map.
  4784 // . For protecting _collector_state transitions, we take the CGC_lock.
  4785 //   Note that any races in the reading of of card table entries by the
  4786 //   CMS thread on the one hand and the clearing of those entries by the
  4787 //   VM thread or the setting of those entries by the mutator threads on the
  4788 //   other are quite benign. However, for efficiency it makes sense to keep
  4789 //   the VM thread from racing with the CMS thread while the latter is
  4790 //   dirty card info to the modUnionTable. We therefore also use the
  4791 //   CGC_lock to protect the reading of the card table and the mod union
  4792 //   table by the CM thread.
  4793 // . We run concurrently with mutator updates, so scanning
  4794 //   needs to be done carefully  -- we should not try to scan
  4795 //   potentially uninitialized objects.
  4796 //
  4797 // Locking strategy: While holding the CGC_lock, we scan over and
  4798 // reset a maximal dirty range of the mod union / card tables, then lock
  4799 // the free_list_lock and bitmap lock to do a full marking, then
  4800 // release these locks; and repeat the cycle. This allows for a
  4801 // certain amount of fairness in the sharing of these locks between
  4802 // the CMS collector on the one hand, and the VM thread and the
  4803 // mutators on the other.
  4805 // NOTE: preclean_mod_union_table() and preclean_card_table()
  4806 // further below are largely identical; if you need to modify
  4807 // one of these methods, please check the other method too.
  4809 size_t CMSCollector::preclean_mod_union_table(
  4810   ConcurrentMarkSweepGeneration* gen,
  4811   ScanMarkedObjectsAgainCarefullyClosure* cl) {
  4812   verify_work_stacks_empty();
  4813   verify_overflow_empty();
  4815   // strategy: starting with the first card, accumulate contiguous
  4816   // ranges of dirty cards; clear these cards, then scan the region
  4817   // covered by these cards.
  4819   // Since all of the MUT is committed ahead, we can just use
  4820   // that, in case the generations expand while we are precleaning.
  4821   // It might also be fine to just use the committed part of the
  4822   // generation, but we might potentially miss cards when the
  4823   // generation is rapidly expanding while we are in the midst
  4824   // of precleaning.
  4825   HeapWord* startAddr = gen->reserved().start();
  4826   HeapWord* endAddr   = gen->reserved().end();
  4828   cl->setFreelistLock(gen->freelistLock());   // needed for yielding
  4830   size_t numDirtyCards, cumNumDirtyCards;
  4831   HeapWord *nextAddr, *lastAddr;
  4832   for (cumNumDirtyCards = numDirtyCards = 0,
  4833        nextAddr = lastAddr = startAddr;
  4834        nextAddr < endAddr;
  4835        nextAddr = lastAddr, cumNumDirtyCards += numDirtyCards) {
  4837     ResourceMark rm;
  4838     HandleMark   hm;
  4840     MemRegion dirtyRegion;
  4842       stopTimer();
  4843       // Potential yield point
  4844       CMSTokenSync ts(true);
  4845       startTimer();
  4846       sample_eden();
  4847       // Get dirty region starting at nextOffset (inclusive),
  4848       // simultaneously clearing it.
  4849       dirtyRegion =
  4850         _modUnionTable.getAndClearMarkedRegion(nextAddr, endAddr);
  4851       assert(dirtyRegion.start() >= nextAddr,
  4852              "returned region inconsistent?");
  4854     // Remember where the next search should begin.
  4855     // The returned region (if non-empty) is a right open interval,
  4856     // so lastOffset is obtained from the right end of that
  4857     // interval.
  4858     lastAddr = dirtyRegion.end();
  4859     // Should do something more transparent and less hacky XXX
  4860     numDirtyCards =
  4861       _modUnionTable.heapWordDiffToOffsetDiff(dirtyRegion.word_size());
  4863     // We'll scan the cards in the dirty region (with periodic
  4864     // yields for foreground GC as needed).
  4865     if (!dirtyRegion.is_empty()) {
  4866       assert(numDirtyCards > 0, "consistency check");
  4867       HeapWord* stop_point = NULL;
  4868       stopTimer();
  4869       // Potential yield point
  4870       CMSTokenSyncWithLocks ts(true, gen->freelistLock(),
  4871                                bitMapLock());
  4872       startTimer();
  4874         verify_work_stacks_empty();
  4875         verify_overflow_empty();
  4876         sample_eden();
  4877         stop_point =
  4878           gen->cmsSpace()->object_iterate_careful_m(dirtyRegion, cl);
  4880       if (stop_point != NULL) {
  4881         // The careful iteration stopped early either because it found an
  4882         // uninitialized object, or because we were in the midst of an
  4883         // "abortable preclean", which should now be aborted. Redirty
  4884         // the bits corresponding to the partially-scanned or unscanned
  4885         // cards. We'll either restart at the next block boundary or
  4886         // abort the preclean.
  4887         assert((_collectorState == AbortablePreclean && should_abort_preclean()),
  4888                "Should only be AbortablePreclean.");
  4889         _modUnionTable.mark_range(MemRegion(stop_point, dirtyRegion.end()));
  4890         if (should_abort_preclean()) {
  4891           break; // out of preclean loop
  4892         } else {
  4893           // Compute the next address at which preclean should pick up;
  4894           // might need bitMapLock in order to read P-bits.
  4895           lastAddr = next_card_start_after_block(stop_point);
  4898     } else {
  4899       assert(lastAddr == endAddr, "consistency check");
  4900       assert(numDirtyCards == 0, "consistency check");
  4901       break;
  4904   verify_work_stacks_empty();
  4905   verify_overflow_empty();
  4906   return cumNumDirtyCards;
  4909 // NOTE: preclean_mod_union_table() above and preclean_card_table()
  4910 // below are largely identical; if you need to modify
  4911 // one of these methods, please check the other method too.
  4913 size_t CMSCollector::preclean_card_table(ConcurrentMarkSweepGeneration* gen,
  4914   ScanMarkedObjectsAgainCarefullyClosure* cl) {
  4915   // strategy: it's similar to precleamModUnionTable above, in that
  4916   // we accumulate contiguous ranges of dirty cards, mark these cards
  4917   // precleaned, then scan the region covered by these cards.
  4918   HeapWord* endAddr   = (HeapWord*)(gen->_virtual_space.high());
  4919   HeapWord* startAddr = (HeapWord*)(gen->_virtual_space.low());
  4921   cl->setFreelistLock(gen->freelistLock());   // needed for yielding
  4923   size_t numDirtyCards, cumNumDirtyCards;
  4924   HeapWord *lastAddr, *nextAddr;
  4926   for (cumNumDirtyCards = numDirtyCards = 0,
  4927        nextAddr = lastAddr = startAddr;
  4928        nextAddr < endAddr;
  4929        nextAddr = lastAddr, cumNumDirtyCards += numDirtyCards) {
  4931     ResourceMark rm;
  4932     HandleMark   hm;
  4934     MemRegion dirtyRegion;
  4936       // See comments in "Precleaning notes" above on why we
  4937       // do this locking. XXX Could the locking overheads be
  4938       // too high when dirty cards are sparse? [I don't think so.]
  4939       stopTimer();
  4940       CMSTokenSync x(true); // is cms thread
  4941       startTimer();
  4942       sample_eden();
  4943       // Get and clear dirty region from card table
  4944       dirtyRegion = _ct->ct_bs()->dirty_card_range_after_reset(
  4945                                     MemRegion(nextAddr, endAddr),
  4946                                     true,
  4947                                     CardTableModRefBS::precleaned_card_val());
  4949       assert(dirtyRegion.start() >= nextAddr,
  4950              "returned region inconsistent?");
  4952     lastAddr = dirtyRegion.end();
  4953     numDirtyCards =
  4954       dirtyRegion.word_size()/CardTableModRefBS::card_size_in_words;
  4956     if (!dirtyRegion.is_empty()) {
  4957       stopTimer();
  4958       CMSTokenSyncWithLocks ts(true, gen->freelistLock(), bitMapLock());
  4959       startTimer();
  4960       sample_eden();
  4961       verify_work_stacks_empty();
  4962       verify_overflow_empty();
  4963       HeapWord* stop_point =
  4964         gen->cmsSpace()->object_iterate_careful_m(dirtyRegion, cl);
  4965       if (stop_point != NULL) {
  4966         assert((_collectorState == AbortablePreclean && should_abort_preclean()),
  4967                "Should only be AbortablePreclean.");
  4968         _ct->ct_bs()->invalidate(MemRegion(stop_point, dirtyRegion.end()));
  4969         if (should_abort_preclean()) {
  4970           break; // out of preclean loop
  4971         } else {
  4972           // Compute the next address at which preclean should pick up.
  4973           lastAddr = next_card_start_after_block(stop_point);
  4976     } else {
  4977       break;
  4980   verify_work_stacks_empty();
  4981   verify_overflow_empty();
  4982   return cumNumDirtyCards;
  4985 class PrecleanKlassClosure : public KlassClosure {
  4986   CMKlassClosure _cm_klass_closure;
  4987  public:
  4988   PrecleanKlassClosure(OopClosure* oop_closure) : _cm_klass_closure(oop_closure) {}
  4989   void do_klass(Klass* k) {
  4990     if (k->has_accumulated_modified_oops()) {
  4991       k->clear_accumulated_modified_oops();
  4993       _cm_klass_closure.do_klass(k);
  4996 };
  4998 // The freelist lock is needed to prevent asserts, is it really needed?
  4999 void CMSCollector::preclean_klasses(MarkRefsIntoAndScanClosure* cl, Mutex* freelistLock) {
  5001   cl->set_freelistLock(freelistLock);
  5003   CMSTokenSyncWithLocks ts(true, freelistLock, bitMapLock());
  5005   // SSS: Add equivalent to ScanMarkedObjectsAgainCarefullyClosure::do_yield_check and should_abort_preclean?
  5006   // SSS: We should probably check if precleaning should be aborted, at suitable intervals?
  5007   PrecleanKlassClosure preclean_klass_closure(cl);
  5008   ClassLoaderDataGraph::classes_do(&preclean_klass_closure);
  5010   verify_work_stacks_empty();
  5011   verify_overflow_empty();
  5014 void CMSCollector::checkpointRootsFinal(bool asynch,
  5015   bool clear_all_soft_refs, bool init_mark_was_synchronous) {
  5016   assert(_collectorState == FinalMarking, "incorrect state transition?");
  5017   check_correct_thread_executing();
  5018   // world is stopped at this checkpoint
  5019   assert(SafepointSynchronize::is_at_safepoint(),
  5020          "world should be stopped");
  5021   TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause());
  5023   verify_work_stacks_empty();
  5024   verify_overflow_empty();
  5026   SpecializationStats::clear();
  5027   if (PrintGCDetails) {
  5028     gclog_or_tty->print("[YG occupancy: "SIZE_FORMAT" K ("SIZE_FORMAT" K)]",
  5029                         _young_gen->used() / K,
  5030                         _young_gen->capacity() / K);
  5032   if (asynch) {
  5033     if (CMSScavengeBeforeRemark) {
  5034       GenCollectedHeap* gch = GenCollectedHeap::heap();
  5035       // Temporarily set flag to false, GCH->do_collection will
  5036       // expect it to be false and set to true
  5037       FlagSetting fl(gch->_is_gc_active, false);
  5038       NOT_PRODUCT(GCTraceTime t("Scavenge-Before-Remark",
  5039         PrintGCDetails && Verbose, true, _gc_timer_cm);)
  5040       int level = _cmsGen->level() - 1;
  5041       if (level >= 0) {
  5042         gch->do_collection(true,        // full (i.e. force, see below)
  5043                            false,       // !clear_all_soft_refs
  5044                            0,           // size
  5045                            false,       // is_tlab
  5046                            level        // max_level
  5047                           );
  5050     FreelistLocker x(this);
  5051     MutexLockerEx y(bitMapLock(),
  5052                     Mutex::_no_safepoint_check_flag);
  5053     assert(!init_mark_was_synchronous, "but that's impossible!");
  5054     checkpointRootsFinalWork(asynch, clear_all_soft_refs, false);
  5055   } else {
  5056     // already have all the locks
  5057     checkpointRootsFinalWork(asynch, clear_all_soft_refs,
  5058                              init_mark_was_synchronous);
  5060   verify_work_stacks_empty();
  5061   verify_overflow_empty();
  5062   SpecializationStats::print();
  5065 void CMSCollector::checkpointRootsFinalWork(bool asynch,
  5066   bool clear_all_soft_refs, bool init_mark_was_synchronous) {
  5068   NOT_PRODUCT(GCTraceTime tr("checkpointRootsFinalWork", PrintGCDetails, false, _gc_timer_cm);)
  5070   assert(haveFreelistLocks(), "must have free list locks");
  5071   assert_lock_strong(bitMapLock());
  5073   if (UseAdaptiveSizePolicy) {
  5074     size_policy()->checkpoint_roots_final_begin();
  5077   ResourceMark rm;
  5078   HandleMark   hm;
  5080   GenCollectedHeap* gch = GenCollectedHeap::heap();
  5082   if (should_unload_classes()) {
  5083     CodeCache::gc_prologue();
  5085   assert(haveFreelistLocks(), "must have free list locks");
  5086   assert_lock_strong(bitMapLock());
  5088   if (!init_mark_was_synchronous) {
  5089     // We might assume that we need not fill TLAB's when
  5090     // CMSScavengeBeforeRemark is set, because we may have just done
  5091     // a scavenge which would have filled all TLAB's -- and besides
  5092     // Eden would be empty. This however may not always be the case --
  5093     // for instance although we asked for a scavenge, it may not have
  5094     // happened because of a JNI critical section. We probably need
  5095     // a policy for deciding whether we can in that case wait until
  5096     // the critical section releases and then do the remark following
  5097     // the scavenge, and skip it here. In the absence of that policy,
  5098     // or of an indication of whether the scavenge did indeed occur,
  5099     // we cannot rely on TLAB's having been filled and must do
  5100     // so here just in case a scavenge did not happen.
  5101     gch->ensure_parsability(false);  // fill TLAB's, but no need to retire them
  5102     // Update the saved marks which may affect the root scans.
  5103     gch->save_marks();
  5105     if (CMSPrintEdenSurvivorChunks) {
  5106       print_eden_and_survivor_chunk_arrays();
  5110       COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;)
  5112       // Note on the role of the mod union table:
  5113       // Since the marker in "markFromRoots" marks concurrently with
  5114       // mutators, it is possible for some reachable objects not to have been
  5115       // scanned. For instance, an only reference to an object A was
  5116       // placed in object B after the marker scanned B. Unless B is rescanned,
  5117       // A would be collected. Such updates to references in marked objects
  5118       // are detected via the mod union table which is the set of all cards
  5119       // dirtied since the first checkpoint in this GC cycle and prior to
  5120       // the most recent young generation GC, minus those cleaned up by the
  5121       // concurrent precleaning.
  5122       if (CMSParallelRemarkEnabled && CollectedHeap::use_parallel_gc_threads()) {
  5123         GCTraceTime t("Rescan (parallel) ", PrintGCDetails, false, _gc_timer_cm);
  5124         do_remark_parallel();
  5125       } else {
  5126         GCTraceTime t("Rescan (non-parallel) ", PrintGCDetails, false,
  5127                     _gc_timer_cm);
  5128         do_remark_non_parallel();
  5131   } else {
  5132     assert(!asynch, "Can't have init_mark_was_synchronous in asynch mode");
  5133     // The initial mark was stop-world, so there's no rescanning to
  5134     // do; go straight on to the next step below.
  5136   verify_work_stacks_empty();
  5137   verify_overflow_empty();
  5140     NOT_PRODUCT(GCTraceTime ts("refProcessingWork", PrintGCDetails, false, _gc_timer_cm);)
  5141     refProcessingWork(asynch, clear_all_soft_refs);
  5143   verify_work_stacks_empty();
  5144   verify_overflow_empty();
  5146   if (should_unload_classes()) {
  5147     CodeCache::gc_epilogue();
  5149   JvmtiExport::gc_epilogue();
  5151   // If we encountered any (marking stack / work queue) overflow
  5152   // events during the current CMS cycle, take appropriate
  5153   // remedial measures, where possible, so as to try and avoid
  5154   // recurrence of that condition.
  5155   assert(_markStack.isEmpty(), "No grey objects");
  5156   size_t ser_ovflw = _ser_pmc_remark_ovflw + _ser_pmc_preclean_ovflw +
  5157                      _ser_kac_ovflw        + _ser_kac_preclean_ovflw;
  5158   if (ser_ovflw > 0) {
  5159     if (PrintCMSStatistics != 0) {
  5160       gclog_or_tty->print_cr("Marking stack overflow (benign) "
  5161         "(pmc_pc="SIZE_FORMAT", pmc_rm="SIZE_FORMAT", kac="SIZE_FORMAT
  5162         ", kac_preclean="SIZE_FORMAT")",
  5163         _ser_pmc_preclean_ovflw, _ser_pmc_remark_ovflw,
  5164         _ser_kac_ovflw, _ser_kac_preclean_ovflw);
  5166     _markStack.expand();
  5167     _ser_pmc_remark_ovflw = 0;
  5168     _ser_pmc_preclean_ovflw = 0;
  5169     _ser_kac_preclean_ovflw = 0;
  5170     _ser_kac_ovflw = 0;
  5172   if (_par_pmc_remark_ovflw > 0 || _par_kac_ovflw > 0) {
  5173     if (PrintCMSStatistics != 0) {
  5174       gclog_or_tty->print_cr("Work queue overflow (benign) "
  5175         "(pmc_rm="SIZE_FORMAT", kac="SIZE_FORMAT")",
  5176         _par_pmc_remark_ovflw, _par_kac_ovflw);
  5178     _par_pmc_remark_ovflw = 0;
  5179     _par_kac_ovflw = 0;
  5181   if (PrintCMSStatistics != 0) {
  5182      if (_markStack._hit_limit > 0) {
  5183        gclog_or_tty->print_cr(" (benign) Hit max stack size limit ("SIZE_FORMAT")",
  5184                               _markStack._hit_limit);
  5186      if (_markStack._failed_double > 0) {
  5187        gclog_or_tty->print_cr(" (benign) Failed stack doubling ("SIZE_FORMAT"),"
  5188                               " current capacity "SIZE_FORMAT,
  5189                               _markStack._failed_double,
  5190                               _markStack.capacity());
  5193   _markStack._hit_limit = 0;
  5194   _markStack._failed_double = 0;
  5196   if ((VerifyAfterGC || VerifyDuringGC) &&
  5197       GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  5198     verify_after_remark();
  5201   _gc_tracer_cm->report_object_count_after_gc(&_is_alive_closure);
  5203   // Change under the freelistLocks.
  5204   _collectorState = Sweeping;
  5205   // Call isAllClear() under bitMapLock
  5206   assert(_modUnionTable.isAllClear(),
  5207       "Should be clear by end of the final marking");
  5208   assert(_ct->klass_rem_set()->mod_union_is_clear(),
  5209       "Should be clear by end of the final marking");
  5210   if (UseAdaptiveSizePolicy) {
  5211     size_policy()->checkpoint_roots_final_end(gch->gc_cause());
  5215 void CMSParInitialMarkTask::work(uint worker_id) {
  5216   elapsedTimer _timer;
  5217   ResourceMark rm;
  5218   HandleMark   hm;
  5220   // ---------- scan from roots --------------
  5221   _timer.start();
  5222   GenCollectedHeap* gch = GenCollectedHeap::heap();
  5223   Par_MarkRefsIntoClosure par_mri_cl(_collector->_span, &(_collector->_markBitMap));
  5224   CMKlassClosure klass_closure(&par_mri_cl);
  5226   // ---------- young gen roots --------------
  5228     work_on_young_gen_roots(worker_id, &par_mri_cl);
  5229     _timer.stop();
  5230     if (PrintCMSStatistics != 0) {
  5231       gclog_or_tty->print_cr(
  5232         "Finished young gen initial mark scan work in %dth thread: %3.3f sec",
  5233         worker_id, _timer.seconds());
  5237   // ---------- remaining roots --------------
  5238   _timer.reset();
  5239   _timer.start();
  5240   gch->gen_process_strong_roots(_collector->_cmsGen->level(),
  5241                                 false,     // yg was scanned above
  5242                                 false,     // this is parallel code
  5243                                 false,     // not scavenging
  5244                                 SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()),
  5245                                 &par_mri_cl,
  5246                                 true,   // walk all of code cache if (so & SO_CodeCache)
  5247                                 NULL,
  5248                                 &klass_closure);
  5249   assert(_collector->should_unload_classes()
  5250          || (_collector->CMSCollector::roots_scanning_options() & SharedHeap::SO_CodeCache),
  5251          "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops");
  5252   _timer.stop();
  5253   if (PrintCMSStatistics != 0) {
  5254     gclog_or_tty->print_cr(
  5255       "Finished remaining root initial mark scan work in %dth thread: %3.3f sec",
  5256       worker_id, _timer.seconds());
  5260 // Parallel remark task
  5261 class CMSParRemarkTask: public CMSParMarkTask {
  5262   CompactibleFreeListSpace* _cms_space;
  5264   // The per-thread work queues, available here for stealing.
  5265   OopTaskQueueSet*       _task_queues;
  5266   ParallelTaskTerminator _term;
  5268  public:
  5269   // A value of 0 passed to n_workers will cause the number of
  5270   // workers to be taken from the active workers in the work gang.
  5271   CMSParRemarkTask(CMSCollector* collector,
  5272                    CompactibleFreeListSpace* cms_space,
  5273                    int n_workers, FlexibleWorkGang* workers,
  5274                    OopTaskQueueSet* task_queues):
  5275     CMSParMarkTask("Rescan roots and grey objects in parallel",
  5276                    collector, n_workers),
  5277     _cms_space(cms_space),
  5278     _task_queues(task_queues),
  5279     _term(n_workers, task_queues) { }
  5281   OopTaskQueueSet* task_queues() { return _task_queues; }
  5283   OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); }
  5285   ParallelTaskTerminator* terminator() { return &_term; }
  5286   int n_workers() { return _n_workers; }
  5288   void work(uint worker_id);
  5290  private:
  5291   // ... of  dirty cards in old space
  5292   void do_dirty_card_rescan_tasks(CompactibleFreeListSpace* sp, int i,
  5293                                   Par_MarkRefsIntoAndScanClosure* cl);
  5295   // ... work stealing for the above
  5296   void do_work_steal(int i, Par_MarkRefsIntoAndScanClosure* cl, int* seed);
  5297 };
  5299 class RemarkKlassClosure : public KlassClosure {
  5300   CMKlassClosure _cm_klass_closure;
  5301  public:
  5302   RemarkKlassClosure(OopClosure* oop_closure) : _cm_klass_closure(oop_closure) {}
  5303   void do_klass(Klass* k) {
  5304     // Check if we have modified any oops in the Klass during the concurrent marking.
  5305     if (k->has_accumulated_modified_oops()) {
  5306       k->clear_accumulated_modified_oops();
  5308       // We could have transfered the current modified marks to the accumulated marks,
  5309       // like we do with the Card Table to Mod Union Table. But it's not really necessary.
  5310     } else if (k->has_modified_oops()) {
  5311       // Don't clear anything, this info is needed by the next young collection.
  5312     } else {
  5313       // No modified oops in the Klass.
  5314       return;
  5317     // The klass has modified fields, need to scan the klass.
  5318     _cm_klass_closure.do_klass(k);
  5320 };
  5322 void CMSParMarkTask::work_on_young_gen_roots(uint worker_id, OopsInGenClosure* cl) {
  5323   DefNewGeneration* dng = _collector->_young_gen->as_DefNewGeneration();
  5324   EdenSpace* eden_space = dng->eden();
  5325   ContiguousSpace* from_space = dng->from();
  5326   ContiguousSpace* to_space   = dng->to();
  5328   HeapWord** eca = _collector->_eden_chunk_array;
  5329   size_t     ect = _collector->_eden_chunk_index;
  5330   HeapWord** sca = _collector->_survivor_chunk_array;
  5331   size_t     sct = _collector->_survivor_chunk_index;
  5333   assert(ect <= _collector->_eden_chunk_capacity, "out of bounds");
  5334   assert(sct <= _collector->_survivor_chunk_capacity, "out of bounds");
  5336   do_young_space_rescan(worker_id, cl, to_space, NULL, 0);
  5337   do_young_space_rescan(worker_id, cl, from_space, sca, sct);
  5338   do_young_space_rescan(worker_id, cl, eden_space, eca, ect);
  5341 // work_queue(i) is passed to the closure
  5342 // Par_MarkRefsIntoAndScanClosure.  The "i" parameter
  5343 // also is passed to do_dirty_card_rescan_tasks() and to
  5344 // do_work_steal() to select the i-th task_queue.
  5346 void CMSParRemarkTask::work(uint worker_id) {
  5347   elapsedTimer _timer;
  5348   ResourceMark rm;
  5349   HandleMark   hm;
  5351   // ---------- rescan from roots --------------
  5352   _timer.start();
  5353   GenCollectedHeap* gch = GenCollectedHeap::heap();
  5354   Par_MarkRefsIntoAndScanClosure par_mrias_cl(_collector,
  5355     _collector->_span, _collector->ref_processor(),
  5356     &(_collector->_markBitMap),
  5357     work_queue(worker_id));
  5359   // Rescan young gen roots first since these are likely
  5360   // coarsely partitioned and may, on that account, constitute
  5361   // the critical path; thus, it's best to start off that
  5362   // work first.
  5363   // ---------- young gen roots --------------
  5365     work_on_young_gen_roots(worker_id, &par_mrias_cl);
  5366     _timer.stop();
  5367     if (PrintCMSStatistics != 0) {
  5368       gclog_or_tty->print_cr(
  5369         "Finished young gen rescan work in %dth thread: %3.3f sec",
  5370         worker_id, _timer.seconds());
  5374   // ---------- remaining roots --------------
  5375   _timer.reset();
  5376   _timer.start();
  5377   gch->gen_process_strong_roots(_collector->_cmsGen->level(),
  5378                                 false,     // yg was scanned above
  5379                                 false,     // this is parallel code
  5380                                 false,     // not scavenging
  5381                                 SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()),
  5382                                 &par_mrias_cl,
  5383                                 true,   // walk all of code cache if (so & SO_CodeCache)
  5384                                 NULL,
  5385                                 NULL);     // The dirty klasses will be handled below
  5386   assert(_collector->should_unload_classes()
  5387          || (_collector->CMSCollector::roots_scanning_options() & SharedHeap::SO_CodeCache),
  5388          "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops");
  5389   _timer.stop();
  5390   if (PrintCMSStatistics != 0) {
  5391     gclog_or_tty->print_cr(
  5392       "Finished remaining root rescan work in %dth thread: %3.3f sec",
  5393       worker_id, _timer.seconds());
  5396   // ---------- unhandled CLD scanning ----------
  5397   if (worker_id == 0) { // Single threaded at the moment.
  5398     _timer.reset();
  5399     _timer.start();
  5401     // Scan all new class loader data objects and new dependencies that were
  5402     // introduced during concurrent marking.
  5403     ResourceMark rm;
  5404     GrowableArray<ClassLoaderData*>* array = ClassLoaderDataGraph::new_clds();
  5405     for (int i = 0; i < array->length(); i++) {
  5406       par_mrias_cl.do_class_loader_data(array->at(i));
  5409     // We don't need to keep track of new CLDs anymore.
  5410     ClassLoaderDataGraph::remember_new_clds(false);
  5412     _timer.stop();
  5413     if (PrintCMSStatistics != 0) {
  5414       gclog_or_tty->print_cr(
  5415           "Finished unhandled CLD scanning work in %dth thread: %3.3f sec",
  5416           worker_id, _timer.seconds());
  5420   // ---------- dirty klass scanning ----------
  5421   if (worker_id == 0) { // Single threaded at the moment.
  5422     _timer.reset();
  5423     _timer.start();
  5425     // Scan all classes that was dirtied during the concurrent marking phase.
  5426     RemarkKlassClosure remark_klass_closure(&par_mrias_cl);
  5427     ClassLoaderDataGraph::classes_do(&remark_klass_closure);
  5429     _timer.stop();
  5430     if (PrintCMSStatistics != 0) {
  5431       gclog_or_tty->print_cr(
  5432           "Finished dirty klass scanning work in %dth thread: %3.3f sec",
  5433           worker_id, _timer.seconds());
  5437   // We might have added oops to ClassLoaderData::_handles during the
  5438   // concurrent marking phase. These oops point to newly allocated objects
  5439   // that are guaranteed to be kept alive. Either by the direct allocation
  5440   // code, or when the young collector processes the strong roots. Hence,
  5441   // we don't have to revisit the _handles block during the remark phase.
  5443   // ---------- rescan dirty cards ------------
  5444   _timer.reset();
  5445   _timer.start();
  5447   // Do the rescan tasks for each of the two spaces
  5448   // (cms_space) in turn.
  5449   // "worker_id" is passed to select the task_queue for "worker_id"
  5450   do_dirty_card_rescan_tasks(_cms_space, worker_id, &par_mrias_cl);
  5451   _timer.stop();
  5452   if (PrintCMSStatistics != 0) {
  5453     gclog_or_tty->print_cr(
  5454       "Finished dirty card rescan work in %dth thread: %3.3f sec",
  5455       worker_id, _timer.seconds());
  5458   // ---------- steal work from other threads ...
  5459   // ---------- ... and drain overflow list.
  5460   _timer.reset();
  5461   _timer.start();
  5462   do_work_steal(worker_id, &par_mrias_cl, _collector->hash_seed(worker_id));
  5463   _timer.stop();
  5464   if (PrintCMSStatistics != 0) {
  5465     gclog_or_tty->print_cr(
  5466       "Finished work stealing in %dth thread: %3.3f sec",
  5467       worker_id, _timer.seconds());
  5471 // Note that parameter "i" is not used.
  5472 void
  5473 CMSParMarkTask::do_young_space_rescan(uint worker_id,
  5474   OopsInGenClosure* cl, ContiguousSpace* space,
  5475   HeapWord** chunk_array, size_t chunk_top) {
  5476   // Until all tasks completed:
  5477   // . claim an unclaimed task
  5478   // . compute region boundaries corresponding to task claimed
  5479   //   using chunk_array
  5480   // . par_oop_iterate(cl) over that region
  5482   ResourceMark rm;
  5483   HandleMark   hm;
  5485   SequentialSubTasksDone* pst = space->par_seq_tasks();
  5487   uint nth_task = 0;
  5488   uint n_tasks  = pst->n_tasks();
  5490   if (n_tasks > 0) {
  5491     assert(pst->valid(), "Uninitialized use?");
  5492     HeapWord *start, *end;
  5493     while (!pst->is_task_claimed(/* reference */ nth_task)) {
  5494       // We claimed task # nth_task; compute its boundaries.
  5495       if (chunk_top == 0) {  // no samples were taken
  5496         assert(nth_task == 0 && n_tasks == 1, "Can have only 1 EdenSpace task");
  5497         start = space->bottom();
  5498         end   = space->top();
  5499       } else if (nth_task == 0) {
  5500         start = space->bottom();
  5501         end   = chunk_array[nth_task];
  5502       } else if (nth_task < (uint)chunk_top) {
  5503         assert(nth_task >= 1, "Control point invariant");
  5504         start = chunk_array[nth_task - 1];
  5505         end   = chunk_array[nth_task];
  5506       } else {
  5507         assert(nth_task == (uint)chunk_top, "Control point invariant");
  5508         start = chunk_array[chunk_top - 1];
  5509         end   = space->top();
  5511       MemRegion mr(start, end);
  5512       // Verify that mr is in space
  5513       assert(mr.is_empty() || space->used_region().contains(mr),
  5514              "Should be in space");
  5515       // Verify that "start" is an object boundary
  5516       assert(mr.is_empty() || oop(mr.start())->is_oop(),
  5517              "Should be an oop");
  5518       space->par_oop_iterate(mr, cl);
  5520     pst->all_tasks_completed();
  5524 void
  5525 CMSParRemarkTask::do_dirty_card_rescan_tasks(
  5526   CompactibleFreeListSpace* sp, int i,
  5527   Par_MarkRefsIntoAndScanClosure* cl) {
  5528   // Until all tasks completed:
  5529   // . claim an unclaimed task
  5530   // . compute region boundaries corresponding to task claimed
  5531   // . transfer dirty bits ct->mut for that region
  5532   // . apply rescanclosure to dirty mut bits for that region
  5534   ResourceMark rm;
  5535   HandleMark   hm;
  5537   OopTaskQueue* work_q = work_queue(i);
  5538   ModUnionClosure modUnionClosure(&(_collector->_modUnionTable));
  5539   // CAUTION! CAUTION! CAUTION! CAUTION! CAUTION! CAUTION! CAUTION!
  5540   // CAUTION: This closure has state that persists across calls to
  5541   // the work method dirty_range_iterate_clear() in that it has
  5542   // imbedded in it a (subtype of) UpwardsObjectClosure. The
  5543   // use of that state in the imbedded UpwardsObjectClosure instance
  5544   // assumes that the cards are always iterated (even if in parallel
  5545   // by several threads) in monotonically increasing order per each
  5546   // thread. This is true of the implementation below which picks
  5547   // card ranges (chunks) in monotonically increasing order globally
  5548   // and, a-fortiori, in monotonically increasing order per thread
  5549   // (the latter order being a subsequence of the former).
  5550   // If the work code below is ever reorganized into a more chaotic
  5551   // work-partitioning form than the current "sequential tasks"
  5552   // paradigm, the use of that persistent state will have to be
  5553   // revisited and modified appropriately. See also related
  5554   // bug 4756801 work on which should examine this code to make
  5555   // sure that the changes there do not run counter to the
  5556   // assumptions made here and necessary for correctness and
  5557   // efficiency. Note also that this code might yield inefficient
  5558   // behaviour in the case of very large objects that span one or
  5559   // more work chunks. Such objects would potentially be scanned
  5560   // several times redundantly. Work on 4756801 should try and
  5561   // address that performance anomaly if at all possible. XXX
  5562   MemRegion  full_span  = _collector->_span;
  5563   CMSBitMap* bm    = &(_collector->_markBitMap);     // shared
  5564   MarkFromDirtyCardsClosure
  5565     greyRescanClosure(_collector, full_span, // entire span of interest
  5566                       sp, bm, work_q, cl);
  5568   SequentialSubTasksDone* pst = sp->conc_par_seq_tasks();
  5569   assert(pst->valid(), "Uninitialized use?");
  5570   uint nth_task = 0;
  5571   const int alignment = CardTableModRefBS::card_size * BitsPerWord;
  5572   MemRegion span = sp->used_region();
  5573   HeapWord* start_addr = span.start();
  5574   HeapWord* end_addr = (HeapWord*)round_to((intptr_t)span.end(),
  5575                                            alignment);
  5576   const size_t chunk_size = sp->rescan_task_size(); // in HeapWord units
  5577   assert((HeapWord*)round_to((intptr_t)start_addr, alignment) ==
  5578          start_addr, "Check alignment");
  5579   assert((size_t)round_to((intptr_t)chunk_size, alignment) ==
  5580          chunk_size, "Check alignment");
  5582   while (!pst->is_task_claimed(/* reference */ nth_task)) {
  5583     // Having claimed the nth_task, compute corresponding mem-region,
  5584     // which is a-fortiori aligned correctly (i.e. at a MUT bopundary).
  5585     // The alignment restriction ensures that we do not need any
  5586     // synchronization with other gang-workers while setting or
  5587     // clearing bits in thus chunk of the MUT.
  5588     MemRegion this_span = MemRegion(start_addr + nth_task*chunk_size,
  5589                                     start_addr + (nth_task+1)*chunk_size);
  5590     // The last chunk's end might be way beyond end of the
  5591     // used region. In that case pull back appropriately.
  5592     if (this_span.end() > end_addr) {
  5593       this_span.set_end(end_addr);
  5594       assert(!this_span.is_empty(), "Program logic (calculation of n_tasks)");
  5596     // Iterate over the dirty cards covering this chunk, marking them
  5597     // precleaned, and setting the corresponding bits in the mod union
  5598     // table. Since we have been careful to partition at Card and MUT-word
  5599     // boundaries no synchronization is needed between parallel threads.
  5600     _collector->_ct->ct_bs()->dirty_card_iterate(this_span,
  5601                                                  &modUnionClosure);
  5603     // Having transferred these marks into the modUnionTable,
  5604     // rescan the marked objects on the dirty cards in the modUnionTable.
  5605     // Even if this is at a synchronous collection, the initial marking
  5606     // may have been done during an asynchronous collection so there
  5607     // may be dirty bits in the mod-union table.
  5608     _collector->_modUnionTable.dirty_range_iterate_clear(
  5609                   this_span, &greyRescanClosure);
  5610     _collector->_modUnionTable.verifyNoOneBitsInRange(
  5611                                  this_span.start(),
  5612                                  this_span.end());
  5614   pst->all_tasks_completed();  // declare that i am done
  5617 // . see if we can share work_queues with ParNew? XXX
  5618 void
  5619 CMSParRemarkTask::do_work_steal(int i, Par_MarkRefsIntoAndScanClosure* cl,
  5620                                 int* seed) {
  5621   OopTaskQueue* work_q = work_queue(i);
  5622   NOT_PRODUCT(int num_steals = 0;)
  5623   oop obj_to_scan;
  5624   CMSBitMap* bm = &(_collector->_markBitMap);
  5626   while (true) {
  5627     // Completely finish any left over work from (an) earlier round(s)
  5628     cl->trim_queue(0);
  5629     size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
  5630                                          (size_t)ParGCDesiredObjsFromOverflowList);
  5631     // Now check if there's any work in the overflow list
  5632     // Passing ParallelGCThreads as the third parameter, no_of_gc_threads,
  5633     // only affects the number of attempts made to get work from the
  5634     // overflow list and does not affect the number of workers.  Just
  5635     // pass ParallelGCThreads so this behavior is unchanged.
  5636     if (_collector->par_take_from_overflow_list(num_from_overflow_list,
  5637                                                 work_q,
  5638                                                 ParallelGCThreads)) {
  5639       // found something in global overflow list;
  5640       // not yet ready to go stealing work from others.
  5641       // We'd like to assert(work_q->size() != 0, ...)
  5642       // because we just took work from the overflow list,
  5643       // but of course we can't since all of that could have
  5644       // been already stolen from us.
  5645       // "He giveth and He taketh away."
  5646       continue;
  5648     // Verify that we have no work before we resort to stealing
  5649     assert(work_q->size() == 0, "Have work, shouldn't steal");
  5650     // Try to steal from other queues that have work
  5651     if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) {
  5652       NOT_PRODUCT(num_steals++;)
  5653       assert(obj_to_scan->is_oop(), "Oops, not an oop!");
  5654       assert(bm->isMarked((HeapWord*)obj_to_scan), "Stole an unmarked oop?");
  5655       // Do scanning work
  5656       obj_to_scan->oop_iterate(cl);
  5657       // Loop around, finish this work, and try to steal some more
  5658     } else if (terminator()->offer_termination()) {
  5659         break;  // nirvana from the infinite cycle
  5662   NOT_PRODUCT(
  5663     if (PrintCMSStatistics != 0) {
  5664       gclog_or_tty->print("\n\t(%d: stole %d oops)", i, num_steals);
  5667   assert(work_q->size() == 0 && _collector->overflow_list_is_empty(),
  5668          "Else our work is not yet done");
  5671 // Record object boundaries in _eden_chunk_array by sampling the eden
  5672 // top in the slow-path eden object allocation code path and record
  5673 // the boundaries, if CMSEdenChunksRecordAlways is true. If
  5674 // CMSEdenChunksRecordAlways is false, we use the other asynchronous
  5675 // sampling in sample_eden() that activates during the part of the
  5676 // preclean phase.
  5677 void CMSCollector::sample_eden_chunk() {
  5678   if (CMSEdenChunksRecordAlways && _eden_chunk_array != NULL) {
  5679     if (_eden_chunk_lock->try_lock()) {
  5680       // Record a sample. This is the critical section. The contents
  5681       // of the _eden_chunk_array have to be non-decreasing in the
  5682       // address order.
  5683       _eden_chunk_array[_eden_chunk_index] = *_top_addr;
  5684       assert(_eden_chunk_array[_eden_chunk_index] <= *_end_addr,
  5685              "Unexpected state of Eden");
  5686       if (_eden_chunk_index == 0 ||
  5687           ((_eden_chunk_array[_eden_chunk_index] > _eden_chunk_array[_eden_chunk_index-1]) &&
  5688            (pointer_delta(_eden_chunk_array[_eden_chunk_index],
  5689                           _eden_chunk_array[_eden_chunk_index-1]) >= CMSSamplingGrain))) {
  5690         _eden_chunk_index++;  // commit sample
  5692       _eden_chunk_lock->unlock();
  5697 // Return a thread-local PLAB recording array, as appropriate.
  5698 void* CMSCollector::get_data_recorder(int thr_num) {
  5699   if (_survivor_plab_array != NULL &&
  5700       (CMSPLABRecordAlways ||
  5701        (_collectorState > Marking && _collectorState < FinalMarking))) {
  5702     assert(thr_num < (int)ParallelGCThreads, "thr_num is out of bounds");
  5703     ChunkArray* ca = &_survivor_plab_array[thr_num];
  5704     ca->reset();   // clear it so that fresh data is recorded
  5705     return (void*) ca;
  5706   } else {
  5707     return NULL;
  5711 // Reset all the thread-local PLAB recording arrays
  5712 void CMSCollector::reset_survivor_plab_arrays() {
  5713   for (uint i = 0; i < ParallelGCThreads; i++) {
  5714     _survivor_plab_array[i].reset();
  5718 // Merge the per-thread plab arrays into the global survivor chunk
  5719 // array which will provide the partitioning of the survivor space
  5720 // for CMS initial scan and rescan.
  5721 void CMSCollector::merge_survivor_plab_arrays(ContiguousSpace* surv,
  5722                                               int no_of_gc_threads) {
  5723   assert(_survivor_plab_array  != NULL, "Error");
  5724   assert(_survivor_chunk_array != NULL, "Error");
  5725   assert(_collectorState == FinalMarking ||
  5726          (CMSParallelInitialMarkEnabled && _collectorState == InitialMarking), "Error");
  5727   for (int j = 0; j < no_of_gc_threads; j++) {
  5728     _cursor[j] = 0;
  5730   HeapWord* top = surv->top();
  5731   size_t i;
  5732   for (i = 0; i < _survivor_chunk_capacity; i++) {  // all sca entries
  5733     HeapWord* min_val = top;          // Higher than any PLAB address
  5734     uint      min_tid = 0;            // position of min_val this round
  5735     for (int j = 0; j < no_of_gc_threads; j++) {
  5736       ChunkArray* cur_sca = &_survivor_plab_array[j];
  5737       if (_cursor[j] == cur_sca->end()) {
  5738         continue;
  5740       assert(_cursor[j] < cur_sca->end(), "ctl pt invariant");
  5741       HeapWord* cur_val = cur_sca->nth(_cursor[j]);
  5742       assert(surv->used_region().contains(cur_val), "Out of bounds value");
  5743       if (cur_val < min_val) {
  5744         min_tid = j;
  5745         min_val = cur_val;
  5746       } else {
  5747         assert(cur_val < top, "All recorded addresses should be less");
  5750     // At this point min_val and min_tid are respectively
  5751     // the least address in _survivor_plab_array[j]->nth(_cursor[j])
  5752     // and the thread (j) that witnesses that address.
  5753     // We record this address in the _survivor_chunk_array[i]
  5754     // and increment _cursor[min_tid] prior to the next round i.
  5755     if (min_val == top) {
  5756       break;
  5758     _survivor_chunk_array[i] = min_val;
  5759     _cursor[min_tid]++;
  5761   // We are all done; record the size of the _survivor_chunk_array
  5762   _survivor_chunk_index = i; // exclusive: [0, i)
  5763   if (PrintCMSStatistics > 0) {
  5764     gclog_or_tty->print(" (Survivor:" SIZE_FORMAT "chunks) ", i);
  5766   // Verify that we used up all the recorded entries
  5767   #ifdef ASSERT
  5768     size_t total = 0;
  5769     for (int j = 0; j < no_of_gc_threads; j++) {
  5770       assert(_cursor[j] == _survivor_plab_array[j].end(), "Ctl pt invariant");
  5771       total += _cursor[j];
  5773     assert(total == _survivor_chunk_index, "Ctl Pt Invariant");
  5774     // Check that the merged array is in sorted order
  5775     if (total > 0) {
  5776       for (size_t i = 0; i < total - 1; i++) {
  5777         if (PrintCMSStatistics > 0) {
  5778           gclog_or_tty->print(" (chunk" SIZE_FORMAT ":" INTPTR_FORMAT ") ",
  5779                               i, _survivor_chunk_array[i]);
  5781         assert(_survivor_chunk_array[i] < _survivor_chunk_array[i+1],
  5782                "Not sorted");
  5785   #endif // ASSERT
  5788 // Set up the space's par_seq_tasks structure for work claiming
  5789 // for parallel initial scan and rescan of young gen.
  5790 // See ParRescanTask where this is currently used.
  5791 void
  5792 CMSCollector::
  5793 initialize_sequential_subtasks_for_young_gen_rescan(int n_threads) {
  5794   assert(n_threads > 0, "Unexpected n_threads argument");
  5795   DefNewGeneration* dng = (DefNewGeneration*)_young_gen;
  5797   // Eden space
  5798   if (!dng->eden()->is_empty()) {
  5799     SequentialSubTasksDone* pst = dng->eden()->par_seq_tasks();
  5800     assert(!pst->valid(), "Clobbering existing data?");
  5801     // Each valid entry in [0, _eden_chunk_index) represents a task.
  5802     size_t n_tasks = _eden_chunk_index + 1;
  5803     assert(n_tasks == 1 || _eden_chunk_array != NULL, "Error");
  5804     // Sets the condition for completion of the subtask (how many threads
  5805     // need to finish in order to be done).
  5806     pst->set_n_threads(n_threads);
  5807     pst->set_n_tasks((int)n_tasks);
  5810   // Merge the survivor plab arrays into _survivor_chunk_array
  5811   if (_survivor_plab_array != NULL) {
  5812     merge_survivor_plab_arrays(dng->from(), n_threads);
  5813   } else {
  5814     assert(_survivor_chunk_index == 0, "Error");
  5817   // To space
  5819     SequentialSubTasksDone* pst = dng->to()->par_seq_tasks();
  5820     assert(!pst->valid(), "Clobbering existing data?");
  5821     // Sets the condition for completion of the subtask (how many threads
  5822     // need to finish in order to be done).
  5823     pst->set_n_threads(n_threads);
  5824     pst->set_n_tasks(1);
  5825     assert(pst->valid(), "Error");
  5828   // From space
  5830     SequentialSubTasksDone* pst = dng->from()->par_seq_tasks();
  5831     assert(!pst->valid(), "Clobbering existing data?");
  5832     size_t n_tasks = _survivor_chunk_index + 1;
  5833     assert(n_tasks == 1 || _survivor_chunk_array != NULL, "Error");
  5834     // Sets the condition for completion of the subtask (how many threads
  5835     // need to finish in order to be done).
  5836     pst->set_n_threads(n_threads);
  5837     pst->set_n_tasks((int)n_tasks);
  5838     assert(pst->valid(), "Error");
  5842 // Parallel version of remark
  5843 void CMSCollector::do_remark_parallel() {
  5844   GenCollectedHeap* gch = GenCollectedHeap::heap();
  5845   FlexibleWorkGang* workers = gch->workers();
  5846   assert(workers != NULL, "Need parallel worker threads.");
  5847   // Choose to use the number of GC workers most recently set
  5848   // into "active_workers".  If active_workers is not set, set it
  5849   // to ParallelGCThreads.
  5850   int n_workers = workers->active_workers();
  5851   if (n_workers == 0) {
  5852     assert(n_workers > 0, "Should have been set during scavenge");
  5853     n_workers = ParallelGCThreads;
  5854     workers->set_active_workers(n_workers);
  5856   CompactibleFreeListSpace* cms_space  = _cmsGen->cmsSpace();
  5858   CMSParRemarkTask tsk(this,
  5859     cms_space,
  5860     n_workers, workers, task_queues());
  5862   // Set up for parallel process_strong_roots work.
  5863   gch->set_par_threads(n_workers);
  5864   // We won't be iterating over the cards in the card table updating
  5865   // the younger_gen cards, so we shouldn't call the following else
  5866   // the verification code as well as subsequent younger_refs_iterate
  5867   // code would get confused. XXX
  5868   // gch->rem_set()->prepare_for_younger_refs_iterate(true); // parallel
  5870   // The young gen rescan work will not be done as part of
  5871   // process_strong_roots (which currently doesn't knw how to
  5872   // parallelize such a scan), but rather will be broken up into
  5873   // a set of parallel tasks (via the sampling that the [abortable]
  5874   // preclean phase did of EdenSpace, plus the [two] tasks of
  5875   // scanning the [two] survivor spaces. Further fine-grain
  5876   // parallelization of the scanning of the survivor spaces
  5877   // themselves, and of precleaning of the younger gen itself
  5878   // is deferred to the future.
  5879   initialize_sequential_subtasks_for_young_gen_rescan(n_workers);
  5881   // The dirty card rescan work is broken up into a "sequence"
  5882   // of parallel tasks (per constituent space) that are dynamically
  5883   // claimed by the parallel threads.
  5884   cms_space->initialize_sequential_subtasks_for_rescan(n_workers);
  5886   // It turns out that even when we're using 1 thread, doing the work in a
  5887   // separate thread causes wide variance in run times.  We can't help this
  5888   // in the multi-threaded case, but we special-case n=1 here to get
  5889   // repeatable measurements of the 1-thread overhead of the parallel code.
  5890   if (n_workers > 1) {
  5891     // Make refs discovery MT-safe, if it isn't already: it may not
  5892     // necessarily be so, since it's possible that we are doing
  5893     // ST marking.
  5894     ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), true);
  5895     GenCollectedHeap::StrongRootsScope srs(gch);
  5896     workers->run_task(&tsk);
  5897   } else {
  5898     ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), false);
  5899     GenCollectedHeap::StrongRootsScope srs(gch);
  5900     tsk.work(0);
  5903   gch->set_par_threads(0);  // 0 ==> non-parallel.
  5904   // restore, single-threaded for now, any preserved marks
  5905   // as a result of work_q overflow
  5906   restore_preserved_marks_if_any();
  5909 // Non-parallel version of remark
  5910 void CMSCollector::do_remark_non_parallel() {
  5911   ResourceMark rm;
  5912   HandleMark   hm;
  5913   GenCollectedHeap* gch = GenCollectedHeap::heap();
  5914   ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), false);
  5916   MarkRefsIntoAndScanClosure
  5917     mrias_cl(_span, ref_processor(), &_markBitMap, NULL /* not precleaning */,
  5918              &_markStack, this,
  5919              false /* should_yield */, false /* not precleaning */);
  5920   MarkFromDirtyCardsClosure
  5921     markFromDirtyCardsClosure(this, _span,
  5922                               NULL,  // space is set further below
  5923                               &_markBitMap, &_markStack, &mrias_cl);
  5925     GCTraceTime t("grey object rescan", PrintGCDetails, false, _gc_timer_cm);
  5926     // Iterate over the dirty cards, setting the corresponding bits in the
  5927     // mod union table.
  5929       ModUnionClosure modUnionClosure(&_modUnionTable);
  5930       _ct->ct_bs()->dirty_card_iterate(
  5931                       _cmsGen->used_region(),
  5932                       &modUnionClosure);
  5934     // Having transferred these marks into the modUnionTable, we just need
  5935     // to rescan the marked objects on the dirty cards in the modUnionTable.
  5936     // The initial marking may have been done during an asynchronous
  5937     // collection so there may be dirty bits in the mod-union table.
  5938     const int alignment =
  5939       CardTableModRefBS::card_size * BitsPerWord;
  5941       // ... First handle dirty cards in CMS gen
  5942       markFromDirtyCardsClosure.set_space(_cmsGen->cmsSpace());
  5943       MemRegion ur = _cmsGen->used_region();
  5944       HeapWord* lb = ur.start();
  5945       HeapWord* ub = (HeapWord*)round_to((intptr_t)ur.end(), alignment);
  5946       MemRegion cms_span(lb, ub);
  5947       _modUnionTable.dirty_range_iterate_clear(cms_span,
  5948                                                &markFromDirtyCardsClosure);
  5949       verify_work_stacks_empty();
  5950       if (PrintCMSStatistics != 0) {
  5951         gclog_or_tty->print(" (re-scanned "SIZE_FORMAT" dirty cards in cms gen) ",
  5952           markFromDirtyCardsClosure.num_dirty_cards());
  5956   if (VerifyDuringGC &&
  5957       GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
  5958     HandleMark hm;  // Discard invalid handles created during verification
  5959     Universe::verify();
  5962     GCTraceTime t("root rescan", PrintGCDetails, false, _gc_timer_cm);
  5964     verify_work_stacks_empty();
  5966     gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
  5967     GenCollectedHeap::StrongRootsScope srs(gch);
  5968     gch->gen_process_strong_roots(_cmsGen->level(),
  5969                                   true,  // younger gens as roots
  5970                                   false, // use the local StrongRootsScope
  5971                                   false, // not scavenging
  5972                                   SharedHeap::ScanningOption(roots_scanning_options()),
  5973                                   &mrias_cl,
  5974                                   true,   // walk code active on stacks
  5975                                   NULL,
  5976                                   NULL);  // The dirty klasses will be handled below
  5978     assert(should_unload_classes()
  5979            || (roots_scanning_options() & SharedHeap::SO_CodeCache),
  5980            "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops");
  5984     GCTraceTime t("visit unhandled CLDs", PrintGCDetails, false, _gc_timer_cm);
  5986     verify_work_stacks_empty();
  5988     // Scan all class loader data objects that might have been introduced
  5989     // during concurrent marking.
  5990     ResourceMark rm;
  5991     GrowableArray<ClassLoaderData*>* array = ClassLoaderDataGraph::new_clds();
  5992     for (int i = 0; i < array->length(); i++) {
  5993       mrias_cl.do_class_loader_data(array->at(i));
  5996     // We don't need to keep track of new CLDs anymore.
  5997     ClassLoaderDataGraph::remember_new_clds(false);
  5999     verify_work_stacks_empty();
  6003     GCTraceTime t("dirty klass scan", PrintGCDetails, false, _gc_timer_cm);
  6005     verify_work_stacks_empty();
  6007     RemarkKlassClosure remark_klass_closure(&mrias_cl);
  6008     ClassLoaderDataGraph::classes_do(&remark_klass_closure);
  6010     verify_work_stacks_empty();
  6013   // We might have added oops to ClassLoaderData::_handles during the
  6014   // concurrent marking phase. These oops point to newly allocated objects
  6015   // that are guaranteed to be kept alive. Either by the direct allocation
  6016   // code, or when the young collector processes the strong roots. Hence,
  6017   // we don't have to revisit the _handles block during the remark phase.
  6019   verify_work_stacks_empty();
  6020   // Restore evacuated mark words, if any, used for overflow list links
  6021   if (!CMSOverflowEarlyRestoration) {
  6022     restore_preserved_marks_if_any();
  6024   verify_overflow_empty();
  6027 ////////////////////////////////////////////////////////
  6028 // Parallel Reference Processing Task Proxy Class
  6029 ////////////////////////////////////////////////////////
  6030 class CMSRefProcTaskProxy: public AbstractGangTaskWOopQueues {
  6031   typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
  6032   CMSCollector*          _collector;
  6033   CMSBitMap*             _mark_bit_map;
  6034   const MemRegion        _span;
  6035   ProcessTask&           _task;
  6037 public:
  6038   CMSRefProcTaskProxy(ProcessTask&     task,
  6039                       CMSCollector*    collector,
  6040                       const MemRegion& span,
  6041                       CMSBitMap*       mark_bit_map,
  6042                       AbstractWorkGang* workers,
  6043                       OopTaskQueueSet* task_queues):
  6044     // XXX Should superclass AGTWOQ also know about AWG since it knows
  6045     // about the task_queues used by the AWG? Then it could initialize
  6046     // the terminator() object. See 6984287. The set_for_termination()
  6047     // below is a temporary band-aid for the regression in 6984287.
  6048     AbstractGangTaskWOopQueues("Process referents by policy in parallel",
  6049       task_queues),
  6050     _task(task),
  6051     _collector(collector), _span(span), _mark_bit_map(mark_bit_map)
  6053     assert(_collector->_span.equals(_span) && !_span.is_empty(),
  6054            "Inconsistency in _span");
  6055     set_for_termination(workers->active_workers());
  6058   OopTaskQueueSet* task_queues() { return queues(); }
  6060   OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); }
  6062   void do_work_steal(int i,
  6063                      CMSParDrainMarkingStackClosure* drain,
  6064                      CMSParKeepAliveClosure* keep_alive,
  6065                      int* seed);
  6067   virtual void work(uint worker_id);
  6068 };
  6070 void CMSRefProcTaskProxy::work(uint worker_id) {
  6071   assert(_collector->_span.equals(_span), "Inconsistency in _span");
  6072   CMSParKeepAliveClosure par_keep_alive(_collector, _span,
  6073                                         _mark_bit_map,
  6074                                         work_queue(worker_id));
  6075   CMSParDrainMarkingStackClosure par_drain_stack(_collector, _span,
  6076                                                  _mark_bit_map,
  6077                                                  work_queue(worker_id));
  6078   CMSIsAliveClosure is_alive_closure(_span, _mark_bit_map);
  6079   _task.work(worker_id, is_alive_closure, par_keep_alive, par_drain_stack);
  6080   if (_task.marks_oops_alive()) {
  6081     do_work_steal(worker_id, &par_drain_stack, &par_keep_alive,
  6082                   _collector->hash_seed(worker_id));
  6084   assert(work_queue(worker_id)->size() == 0, "work_queue should be empty");
  6085   assert(_collector->_overflow_list == NULL, "non-empty _overflow_list");
  6088 class CMSRefEnqueueTaskProxy: public AbstractGangTask {
  6089   typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
  6090   EnqueueTask& _task;
  6092 public:
  6093   CMSRefEnqueueTaskProxy(EnqueueTask& task)
  6094     : AbstractGangTask("Enqueue reference objects in parallel"),
  6095       _task(task)
  6096   { }
  6098   virtual void work(uint worker_id)
  6100     _task.work(worker_id);
  6102 };
  6104 CMSParKeepAliveClosure::CMSParKeepAliveClosure(CMSCollector* collector,
  6105   MemRegion span, CMSBitMap* bit_map, OopTaskQueue* work_queue):
  6106    _span(span),
  6107    _bit_map(bit_map),
  6108    _work_queue(work_queue),
  6109    _mark_and_push(collector, span, bit_map, work_queue),
  6110    _low_water_mark(MIN2((uint)(work_queue->max_elems()/4),
  6111                         (uint)(CMSWorkQueueDrainThreshold * ParallelGCThreads)))
  6112 { }
  6114 // . see if we can share work_queues with ParNew? XXX
  6115 void CMSRefProcTaskProxy::do_work_steal(int i,
  6116   CMSParDrainMarkingStackClosure* drain,
  6117   CMSParKeepAliveClosure* keep_alive,
  6118   int* seed) {
  6119   OopTaskQueue* work_q = work_queue(i);
  6120   NOT_PRODUCT(int num_steals = 0;)
  6121   oop obj_to_scan;
  6123   while (true) {
  6124     // Completely finish any left over work from (an) earlier round(s)
  6125     drain->trim_queue(0);
  6126     size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
  6127                                          (size_t)ParGCDesiredObjsFromOverflowList);
  6128     // Now check if there's any work in the overflow list
  6129     // Passing ParallelGCThreads as the third parameter, no_of_gc_threads,
  6130     // only affects the number of attempts made to get work from the
  6131     // overflow list and does not affect the number of workers.  Just
  6132     // pass ParallelGCThreads so this behavior is unchanged.
  6133     if (_collector->par_take_from_overflow_list(num_from_overflow_list,
  6134                                                 work_q,
  6135                                                 ParallelGCThreads)) {
  6136       // Found something in global overflow list;
  6137       // not yet ready to go stealing work from others.
  6138       // We'd like to assert(work_q->size() != 0, ...)
  6139       // because we just took work from the overflow list,
  6140       // but of course we can't, since all of that might have
  6141       // been already stolen from us.
  6142       continue;
  6144     // Verify that we have no work before we resort to stealing
  6145     assert(work_q->size() == 0, "Have work, shouldn't steal");
  6146     // Try to steal from other queues that have work
  6147     if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) {
  6148       NOT_PRODUCT(num_steals++;)
  6149       assert(obj_to_scan->is_oop(), "Oops, not an oop!");
  6150       assert(_mark_bit_map->isMarked((HeapWord*)obj_to_scan), "Stole an unmarked oop?");
  6151       // Do scanning work
  6152       obj_to_scan->oop_iterate(keep_alive);
  6153       // Loop around, finish this work, and try to steal some more
  6154     } else if (terminator()->offer_termination()) {
  6155       break;  // nirvana from the infinite cycle
  6158   NOT_PRODUCT(
  6159     if (PrintCMSStatistics != 0) {
  6160       gclog_or_tty->print("\n\t(%d: stole %d oops)", i, num_steals);
  6165 void CMSRefProcTaskExecutor::execute(ProcessTask& task)
  6167   GenCollectedHeap* gch = GenCollectedHeap::heap();
  6168   FlexibleWorkGang* workers = gch->workers();
  6169   assert(workers != NULL, "Need parallel worker threads.");
  6170   CMSRefProcTaskProxy rp_task(task, &_collector,
  6171                               _collector.ref_processor()->span(),
  6172                               _collector.markBitMap(),
  6173                               workers, _collector.task_queues());
  6174   workers->run_task(&rp_task);
  6177 void CMSRefProcTaskExecutor::execute(EnqueueTask& task)
  6180   GenCollectedHeap* gch = GenCollectedHeap::heap();
  6181   FlexibleWorkGang* workers = gch->workers();
  6182   assert(workers != NULL, "Need parallel worker threads.");
  6183   CMSRefEnqueueTaskProxy enq_task(task);
  6184   workers->run_task(&enq_task);
  6187 void CMSCollector::refProcessingWork(bool asynch, bool clear_all_soft_refs) {
  6189   ResourceMark rm;
  6190   HandleMark   hm;
  6192   ReferenceProcessor* rp = ref_processor();
  6193   assert(rp->span().equals(_span), "Spans should be equal");
  6194   assert(!rp->enqueuing_is_done(), "Enqueuing should not be complete");
  6195   // Process weak references.
  6196   rp->setup_policy(clear_all_soft_refs);
  6197   verify_work_stacks_empty();
  6199   CMSKeepAliveClosure cmsKeepAliveClosure(this, _span, &_markBitMap,
  6200                                           &_markStack, false /* !preclean */);
  6201   CMSDrainMarkingStackClosure cmsDrainMarkingStackClosure(this,
  6202                                 _span, &_markBitMap, &_markStack,
  6203                                 &cmsKeepAliveClosure, false /* !preclean */);
  6205     GCTraceTime t("weak refs processing", PrintGCDetails, false, _gc_timer_cm);
  6207     ReferenceProcessorStats stats;
  6208     if (rp->processing_is_mt()) {
  6209       // Set the degree of MT here.  If the discovery is done MT, there
  6210       // may have been a different number of threads doing the discovery
  6211       // and a different number of discovered lists may have Ref objects.
  6212       // That is OK as long as the Reference lists are balanced (see
  6213       // balance_all_queues() and balance_queues()).
  6214       GenCollectedHeap* gch = GenCollectedHeap::heap();
  6215       int active_workers = ParallelGCThreads;
  6216       FlexibleWorkGang* workers = gch->workers();
  6217       if (workers != NULL) {
  6218         active_workers = workers->active_workers();
  6219         // The expectation is that active_workers will have already
  6220         // been set to a reasonable value.  If it has not been set,
  6221         // investigate.
  6222         assert(active_workers > 0, "Should have been set during scavenge");
  6224       rp->set_active_mt_degree(active_workers);
  6225       CMSRefProcTaskExecutor task_executor(*this);
  6226       stats = rp->process_discovered_references(&_is_alive_closure,
  6227                                         &cmsKeepAliveClosure,
  6228                                         &cmsDrainMarkingStackClosure,
  6229                                         &task_executor,
  6230                                         _gc_timer_cm);
  6231     } else {
  6232       stats = rp->process_discovered_references(&_is_alive_closure,
  6233                                         &cmsKeepAliveClosure,
  6234                                         &cmsDrainMarkingStackClosure,
  6235                                         NULL,
  6236                                         _gc_timer_cm);
  6238     _gc_tracer_cm->report_gc_reference_stats(stats);
  6242   // This is the point where the entire marking should have completed.
  6243   verify_work_stacks_empty();
  6245   if (should_unload_classes()) {
  6247       GCTraceTime t("class unloading", PrintGCDetails, false, _gc_timer_cm);
  6249       // Unload classes and purge the SystemDictionary.
  6250       bool purged_class = SystemDictionary::do_unloading(&_is_alive_closure);
  6252       // Unload nmethods.
  6253       CodeCache::do_unloading(&_is_alive_closure, purged_class);
  6255       // Prune dead klasses from subklass/sibling/implementor lists.
  6256       Klass::clean_weak_klass_links(&_is_alive_closure);
  6260       GCTraceTime t("scrub symbol table", PrintGCDetails, false, _gc_timer_cm);
  6261       // Clean up unreferenced symbols in symbol table.
  6262       SymbolTable::unlink();
  6266   // CMS doesn't use the StringTable as hard roots when class unloading is turned off.
  6267   // Need to check if we really scanned the StringTable.
  6268   if ((roots_scanning_options() & SharedHeap::SO_Strings) == 0) {
  6269     GCTraceTime t("scrub string table", PrintGCDetails, false, _gc_timer_cm);
  6270     // Delete entries for dead interned strings.
  6271     StringTable::unlink(&_is_alive_closure);
  6274   // Restore any preserved marks as a result of mark stack or
  6275   // work queue overflow
  6276   restore_preserved_marks_if_any();  // done single-threaded for now
  6278   rp->set_enqueuing_is_done(true);
  6279   if (rp->processing_is_mt()) {
  6280     rp->balance_all_queues();
  6281     CMSRefProcTaskExecutor task_executor(*this);
  6282     rp->enqueue_discovered_references(&task_executor);
  6283   } else {
  6284     rp->enqueue_discovered_references(NULL);
  6286   rp->verify_no_references_recorded();
  6287   assert(!rp->discovery_enabled(), "should have been disabled");
  6290 #ifndef PRODUCT
  6291 void CMSCollector::check_correct_thread_executing() {
  6292   Thread* t = Thread::current();
  6293   // Only the VM thread or the CMS thread should be here.
  6294   assert(t->is_ConcurrentGC_thread() || t->is_VM_thread(),
  6295          "Unexpected thread type");
  6296   // If this is the vm thread, the foreground process
  6297   // should not be waiting.  Note that _foregroundGCIsActive is
  6298   // true while the foreground collector is waiting.
  6299   if (_foregroundGCShouldWait) {
  6300     // We cannot be the VM thread
  6301     assert(t->is_ConcurrentGC_thread(),
  6302            "Should be CMS thread");
  6303   } else {
  6304     // We can be the CMS thread only if we are in a stop-world
  6305     // phase of CMS collection.
  6306     if (t->is_ConcurrentGC_thread()) {
  6307       assert(_collectorState == InitialMarking ||
  6308              _collectorState == FinalMarking,
  6309              "Should be a stop-world phase");
  6310       // The CMS thread should be holding the CMS_token.
  6311       assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  6312              "Potential interference with concurrently "
  6313              "executing VM thread");
  6317 #endif
  6319 void CMSCollector::sweep(bool asynch) {
  6320   assert(_collectorState == Sweeping, "just checking");
  6321   check_correct_thread_executing();
  6322   verify_work_stacks_empty();
  6323   verify_overflow_empty();
  6324   increment_sweep_count();
  6325   TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause());
  6327   _inter_sweep_timer.stop();
  6328   _inter_sweep_estimate.sample(_inter_sweep_timer.seconds());
  6329   size_policy()->avg_cms_free_at_sweep()->sample(_cmsGen->free());
  6331   assert(!_intra_sweep_timer.is_active(), "Should not be active");
  6332   _intra_sweep_timer.reset();
  6333   _intra_sweep_timer.start();
  6334   if (asynch) {
  6335     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  6336     CMSPhaseAccounting pa(this, "sweep", !PrintGCDetails);
  6337     // First sweep the old gen
  6339       CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock(),
  6340                                bitMapLock());
  6341       sweepWork(_cmsGen, asynch);
  6344     // Update Universe::_heap_*_at_gc figures.
  6345     // We need all the free list locks to make the abstract state
  6346     // transition from Sweeping to Resetting. See detailed note
  6347     // further below.
  6349       CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock());
  6350       // Update heap occupancy information which is used as
  6351       // input to soft ref clearing policy at the next gc.
  6352       Universe::update_heap_info_at_gc();
  6353       _collectorState = Resizing;
  6355   } else {
  6356     // already have needed locks
  6357     sweepWork(_cmsGen,  asynch);
  6358     // Update heap occupancy information which is used as
  6359     // input to soft ref clearing policy at the next gc.
  6360     Universe::update_heap_info_at_gc();
  6361     _collectorState = Resizing;
  6363   verify_work_stacks_empty();
  6364   verify_overflow_empty();
  6366   if (should_unload_classes()) {
  6367     // Delay purge to the beginning of the next safepoint.  Metaspace::contains
  6368     // requires that the virtual spaces are stable and not deleted.
  6369     ClassLoaderDataGraph::set_should_purge(true);
  6372   _intra_sweep_timer.stop();
  6373   _intra_sweep_estimate.sample(_intra_sweep_timer.seconds());
  6375   _inter_sweep_timer.reset();
  6376   _inter_sweep_timer.start();
  6378   // We need to use a monotonically non-deccreasing time in ms
  6379   // or we will see time-warp warnings and os::javaTimeMillis()
  6380   // does not guarantee monotonicity.
  6381   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
  6382   update_time_of_last_gc(now);
  6384   // NOTE on abstract state transitions:
  6385   // Mutators allocate-live and/or mark the mod-union table dirty
  6386   // based on the state of the collection.  The former is done in
  6387   // the interval [Marking, Sweeping] and the latter in the interval
  6388   // [Marking, Sweeping).  Thus the transitions into the Marking state
  6389   // and out of the Sweeping state must be synchronously visible
  6390   // globally to the mutators.
  6391   // The transition into the Marking state happens with the world
  6392   // stopped so the mutators will globally see it.  Sweeping is
  6393   // done asynchronously by the background collector so the transition
  6394   // from the Sweeping state to the Resizing state must be done
  6395   // under the freelistLock (as is the check for whether to
  6396   // allocate-live and whether to dirty the mod-union table).
  6397   assert(_collectorState == Resizing, "Change of collector state to"
  6398     " Resizing must be done under the freelistLocks (plural)");
  6400   // Now that sweeping has been completed, we clear
  6401   // the incremental_collection_failed flag,
  6402   // thus inviting a younger gen collection to promote into
  6403   // this generation. If such a promotion may still fail,
  6404   // the flag will be set again when a young collection is
  6405   // attempted.
  6406   GenCollectedHeap* gch = GenCollectedHeap::heap();
  6407   gch->clear_incremental_collection_failed();  // Worth retrying as fresh space may have been freed up
  6408   gch->update_full_collections_completed(_collection_count_start);
  6411 // FIX ME!!! Looks like this belongs in CFLSpace, with
  6412 // CMSGen merely delegating to it.
  6413 void ConcurrentMarkSweepGeneration::setNearLargestChunk() {
  6414   double nearLargestPercent = FLSLargestBlockCoalesceProximity;
  6415   HeapWord*  minAddr        = _cmsSpace->bottom();
  6416   HeapWord*  largestAddr    =
  6417     (HeapWord*) _cmsSpace->dictionary()->find_largest_dict();
  6418   if (largestAddr == NULL) {
  6419     // The dictionary appears to be empty.  In this case
  6420     // try to coalesce at the end of the heap.
  6421     largestAddr = _cmsSpace->end();
  6423   size_t largestOffset     = pointer_delta(largestAddr, minAddr);
  6424   size_t nearLargestOffset =
  6425     (size_t)((double)largestOffset * nearLargestPercent) - MinChunkSize;
  6426   if (PrintFLSStatistics != 0) {
  6427     gclog_or_tty->print_cr(
  6428       "CMS: Large Block: " PTR_FORMAT ";"
  6429       " Proximity: " PTR_FORMAT " -> " PTR_FORMAT,
  6430       largestAddr,
  6431       _cmsSpace->nearLargestChunk(), minAddr + nearLargestOffset);
  6433   _cmsSpace->set_nearLargestChunk(minAddr + nearLargestOffset);
  6436 bool ConcurrentMarkSweepGeneration::isNearLargestChunk(HeapWord* addr) {
  6437   return addr >= _cmsSpace->nearLargestChunk();
  6440 FreeChunk* ConcurrentMarkSweepGeneration::find_chunk_at_end() {
  6441   return _cmsSpace->find_chunk_at_end();
  6444 void ConcurrentMarkSweepGeneration::update_gc_stats(int current_level,
  6445                                                     bool full) {
  6446   // The next lower level has been collected.  Gather any statistics
  6447   // that are of interest at this point.
  6448   if (!full && (current_level + 1) == level()) {
  6449     // Gather statistics on the young generation collection.
  6450     collector()->stats().record_gc0_end(used());
  6454 CMSAdaptiveSizePolicy* ConcurrentMarkSweepGeneration::size_policy() {
  6455   GenCollectedHeap* gch = GenCollectedHeap::heap();
  6456   assert(gch->kind() == CollectedHeap::GenCollectedHeap,
  6457     "Wrong type of heap");
  6458   CMSAdaptiveSizePolicy* sp = (CMSAdaptiveSizePolicy*)
  6459     gch->gen_policy()->size_policy();
  6460   assert(sp->is_gc_cms_adaptive_size_policy(),
  6461     "Wrong type of size policy");
  6462   return sp;
  6465 void ConcurrentMarkSweepGeneration::rotate_debug_collection_type() {
  6466   if (PrintGCDetails && Verbose) {
  6467     gclog_or_tty->print("Rotate from %d ", _debug_collection_type);
  6469   _debug_collection_type = (CollectionTypes) (_debug_collection_type + 1);
  6470   _debug_collection_type =
  6471     (CollectionTypes) (_debug_collection_type % Unknown_collection_type);
  6472   if (PrintGCDetails && Verbose) {
  6473     gclog_or_tty->print_cr("to %d ", _debug_collection_type);
  6477 void CMSCollector::sweepWork(ConcurrentMarkSweepGeneration* gen,
  6478   bool asynch) {
  6479   // We iterate over the space(s) underlying this generation,
  6480   // checking the mark bit map to see if the bits corresponding
  6481   // to specific blocks are marked or not. Blocks that are
  6482   // marked are live and are not swept up. All remaining blocks
  6483   // are swept up, with coalescing on-the-fly as we sweep up
  6484   // contiguous free and/or garbage blocks:
  6485   // We need to ensure that the sweeper synchronizes with allocators
  6486   // and stop-the-world collectors. In particular, the following
  6487   // locks are used:
  6488   // . CMS token: if this is held, a stop the world collection cannot occur
  6489   // . freelistLock: if this is held no allocation can occur from this
  6490   //                 generation by another thread
  6491   // . bitMapLock: if this is held, no other thread can access or update
  6492   //
  6494   // Note that we need to hold the freelistLock if we use
  6495   // block iterate below; else the iterator might go awry if
  6496   // a mutator (or promotion) causes block contents to change
  6497   // (for instance if the allocator divvies up a block).
  6498   // If we hold the free list lock, for all practical purposes
  6499   // young generation GC's can't occur (they'll usually need to
  6500   // promote), so we might as well prevent all young generation
  6501   // GC's while we do a sweeping step. For the same reason, we might
  6502   // as well take the bit map lock for the entire duration
  6504   // check that we hold the requisite locks
  6505   assert(have_cms_token(), "Should hold cms token");
  6506   assert(   (asynch && ConcurrentMarkSweepThread::cms_thread_has_cms_token())
  6507          || (!asynch && ConcurrentMarkSweepThread::vm_thread_has_cms_token()),
  6508         "Should possess CMS token to sweep");
  6509   assert_lock_strong(gen->freelistLock());
  6510   assert_lock_strong(bitMapLock());
  6512   assert(!_inter_sweep_timer.is_active(), "Was switched off in an outer context");
  6513   assert(_intra_sweep_timer.is_active(),  "Was switched on  in an outer context");
  6514   gen->cmsSpace()->beginSweepFLCensus((float)(_inter_sweep_timer.seconds()),
  6515                                       _inter_sweep_estimate.padded_average(),
  6516                                       _intra_sweep_estimate.padded_average());
  6517   gen->setNearLargestChunk();
  6520     SweepClosure sweepClosure(this, gen, &_markBitMap,
  6521                             CMSYield && asynch);
  6522     gen->cmsSpace()->blk_iterate_careful(&sweepClosure);
  6523     // We need to free-up/coalesce garbage/blocks from a
  6524     // co-terminal free run. This is done in the SweepClosure
  6525     // destructor; so, do not remove this scope, else the
  6526     // end-of-sweep-census below will be off by a little bit.
  6528   gen->cmsSpace()->sweep_completed();
  6529   gen->cmsSpace()->endSweepFLCensus(sweep_count());
  6530   if (should_unload_classes()) {                // unloaded classes this cycle,
  6531     _concurrent_cycles_since_last_unload = 0;   // ... reset count
  6532   } else {                                      // did not unload classes,
  6533     _concurrent_cycles_since_last_unload++;     // ... increment count
  6537 // Reset CMS data structures (for now just the marking bit map)
  6538 // preparatory for the next cycle.
  6539 void CMSCollector::reset(bool asynch) {
  6540   GenCollectedHeap* gch = GenCollectedHeap::heap();
  6541   CMSAdaptiveSizePolicy* sp = size_policy();
  6542   AdaptiveSizePolicyOutput(sp, gch->total_collections());
  6543   if (asynch) {
  6544     CMSTokenSyncWithLocks ts(true, bitMapLock());
  6546     // If the state is not "Resetting", the foreground  thread
  6547     // has done a collection and the resetting.
  6548     if (_collectorState != Resetting) {
  6549       assert(_collectorState == Idling, "The state should only change"
  6550         " because the foreground collector has finished the collection");
  6551       return;
  6554     // Clear the mark bitmap (no grey objects to start with)
  6555     // for the next cycle.
  6556     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  6557     CMSPhaseAccounting cmspa(this, "reset", !PrintGCDetails);
  6559     HeapWord* curAddr = _markBitMap.startWord();
  6560     while (curAddr < _markBitMap.endWord()) {
  6561       size_t remaining  = pointer_delta(_markBitMap.endWord(), curAddr);
  6562       MemRegion chunk(curAddr, MIN2(CMSBitMapYieldQuantum, remaining));
  6563       _markBitMap.clear_large_range(chunk);
  6564       if (ConcurrentMarkSweepThread::should_yield() &&
  6565           !foregroundGCIsActive() &&
  6566           CMSYield) {
  6567         assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  6568                "CMS thread should hold CMS token");
  6569         assert_lock_strong(bitMapLock());
  6570         bitMapLock()->unlock();
  6571         ConcurrentMarkSweepThread::desynchronize(true);
  6572         ConcurrentMarkSweepThread::acknowledge_yield_request();
  6573         stopTimer();
  6574         if (PrintCMSStatistics != 0) {
  6575           incrementYields();
  6577         icms_wait();
  6579         // See the comment in coordinator_yield()
  6580         for (unsigned i = 0; i < CMSYieldSleepCount &&
  6581                          ConcurrentMarkSweepThread::should_yield() &&
  6582                          !CMSCollector::foregroundGCIsActive(); ++i) {
  6583           os::sleep(Thread::current(), 1, false);
  6584           ConcurrentMarkSweepThread::acknowledge_yield_request();
  6587         ConcurrentMarkSweepThread::synchronize(true);
  6588         bitMapLock()->lock_without_safepoint_check();
  6589         startTimer();
  6591       curAddr = chunk.end();
  6593     // A successful mostly concurrent collection has been done.
  6594     // Because only the full (i.e., concurrent mode failure) collections
  6595     // are being measured for gc overhead limits, clean the "near" flag
  6596     // and count.
  6597     sp->reset_gc_overhead_limit_count();
  6598     _collectorState = Idling;
  6599   } else {
  6600     // already have the lock
  6601     assert(_collectorState == Resetting, "just checking");
  6602     assert_lock_strong(bitMapLock());
  6603     _markBitMap.clear_all();
  6604     _collectorState = Idling;
  6607   // Stop incremental mode after a cycle completes, so that any future cycles
  6608   // are triggered by allocation.
  6609   stop_icms();
  6611   NOT_PRODUCT(
  6612     if (RotateCMSCollectionTypes) {
  6613       _cmsGen->rotate_debug_collection_type();
  6617   register_gc_end();
  6620 void CMSCollector::do_CMS_operation(CMS_op_type op, GCCause::Cause gc_cause) {
  6621   gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps);
  6622   TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
  6623   GCTraceTime t(GCCauseString("GC", gc_cause), PrintGC, !PrintGCDetails, NULL);
  6624   TraceCollectorStats tcs(counters());
  6626   switch (op) {
  6627     case CMS_op_checkpointRootsInitial: {
  6628       SvcGCMarker sgcm(SvcGCMarker::OTHER);
  6629       checkpointRootsInitial(true);       // asynch
  6630       if (PrintGC) {
  6631         _cmsGen->printOccupancy("initial-mark");
  6633       break;
  6635     case CMS_op_checkpointRootsFinal: {
  6636       SvcGCMarker sgcm(SvcGCMarker::OTHER);
  6637       checkpointRootsFinal(true,    // asynch
  6638                            false,   // !clear_all_soft_refs
  6639                            false);  // !init_mark_was_synchronous
  6640       if (PrintGC) {
  6641         _cmsGen->printOccupancy("remark");
  6643       break;
  6645     default:
  6646       fatal("No such CMS_op");
  6650 #ifndef PRODUCT
  6651 size_t const CMSCollector::skip_header_HeapWords() {
  6652   return FreeChunk::header_size();
  6655 // Try and collect here conditions that should hold when
  6656 // CMS thread is exiting. The idea is that the foreground GC
  6657 // thread should not be blocked if it wants to terminate
  6658 // the CMS thread and yet continue to run the VM for a while
  6659 // after that.
  6660 void CMSCollector::verify_ok_to_terminate() const {
  6661   assert(Thread::current()->is_ConcurrentGC_thread(),
  6662          "should be called by CMS thread");
  6663   assert(!_foregroundGCShouldWait, "should be false");
  6664   // We could check here that all the various low-level locks
  6665   // are not held by the CMS thread, but that is overkill; see
  6666   // also CMSThread::verify_ok_to_terminate() where the CGC_lock
  6667   // is checked.
  6669 #endif
  6671 size_t CMSCollector::block_size_using_printezis_bits(HeapWord* addr) const {
  6672    assert(_markBitMap.isMarked(addr) && _markBitMap.isMarked(addr + 1),
  6673           "missing Printezis mark?");
  6674   HeapWord* nextOneAddr = _markBitMap.getNextMarkedWordAddress(addr + 2);
  6675   size_t size = pointer_delta(nextOneAddr + 1, addr);
  6676   assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
  6677          "alignment problem");
  6678   assert(size >= 3, "Necessary for Printezis marks to work");
  6679   return size;
  6682 // A variant of the above (block_size_using_printezis_bits()) except
  6683 // that we return 0 if the P-bits are not yet set.
  6684 size_t CMSCollector::block_size_if_printezis_bits(HeapWord* addr) const {
  6685   if (_markBitMap.isMarked(addr + 1)) {
  6686     assert(_markBitMap.isMarked(addr), "P-bit can be set only for marked objects");
  6687     HeapWord* nextOneAddr = _markBitMap.getNextMarkedWordAddress(addr + 2);
  6688     size_t size = pointer_delta(nextOneAddr + 1, addr);
  6689     assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
  6690            "alignment problem");
  6691     assert(size >= 3, "Necessary for Printezis marks to work");
  6692     return size;
  6694   return 0;
  6697 HeapWord* CMSCollector::next_card_start_after_block(HeapWord* addr) const {
  6698   size_t sz = 0;
  6699   oop p = (oop)addr;
  6700   if (p->klass_or_null() != NULL) {
  6701     sz = CompactibleFreeListSpace::adjustObjectSize(p->size());
  6702   } else {
  6703     sz = block_size_using_printezis_bits(addr);
  6705   assert(sz > 0, "size must be nonzero");
  6706   HeapWord* next_block = addr + sz;
  6707   HeapWord* next_card  = (HeapWord*)round_to((uintptr_t)next_block,
  6708                                              CardTableModRefBS::card_size);
  6709   assert(round_down((uintptr_t)addr,      CardTableModRefBS::card_size) <
  6710          round_down((uintptr_t)next_card, CardTableModRefBS::card_size),
  6711          "must be different cards");
  6712   return next_card;
  6716 // CMS Bit Map Wrapper /////////////////////////////////////////
  6718 // Construct a CMS bit map infrastructure, but don't create the
  6719 // bit vector itself. That is done by a separate call CMSBitMap::allocate()
  6720 // further below.
  6721 CMSBitMap::CMSBitMap(int shifter, int mutex_rank, const char* mutex_name):
  6722   _bm(),
  6723   _shifter(shifter),
  6724   _lock(mutex_rank >= 0 ? new Mutex(mutex_rank, mutex_name, true) : NULL)
  6726   _bmStartWord = 0;
  6727   _bmWordSize  = 0;
  6730 bool CMSBitMap::allocate(MemRegion mr) {
  6731   _bmStartWord = mr.start();
  6732   _bmWordSize  = mr.word_size();
  6733   ReservedSpace brs(ReservedSpace::allocation_align_size_up(
  6734                      (_bmWordSize >> (_shifter + LogBitsPerByte)) + 1));
  6735   if (!brs.is_reserved()) {
  6736     warning("CMS bit map allocation failure");
  6737     return false;
  6739   // For now we'll just commit all of the bit map up fromt.
  6740   // Later on we'll try to be more parsimonious with swap.
  6741   if (!_virtual_space.initialize(brs, brs.size())) {
  6742     warning("CMS bit map backing store failure");
  6743     return false;
  6745   assert(_virtual_space.committed_size() == brs.size(),
  6746          "didn't reserve backing store for all of CMS bit map?");
  6747   _bm.set_map((BitMap::bm_word_t*)_virtual_space.low());
  6748   assert(_virtual_space.committed_size() << (_shifter + LogBitsPerByte) >=
  6749          _bmWordSize, "inconsistency in bit map sizing");
  6750   _bm.set_size(_bmWordSize >> _shifter);
  6752   // bm.clear(); // can we rely on getting zero'd memory? verify below
  6753   assert(isAllClear(),
  6754          "Expected zero'd memory from ReservedSpace constructor");
  6755   assert(_bm.size() == heapWordDiffToOffsetDiff(sizeInWords()),
  6756          "consistency check");
  6757   return true;
  6760 void CMSBitMap::dirty_range_iterate_clear(MemRegion mr, MemRegionClosure* cl) {
  6761   HeapWord *next_addr, *end_addr, *last_addr;
  6762   assert_locked();
  6763   assert(covers(mr), "out-of-range error");
  6764   // XXX assert that start and end are appropriately aligned
  6765   for (next_addr = mr.start(), end_addr = mr.end();
  6766        next_addr < end_addr; next_addr = last_addr) {
  6767     MemRegion dirty_region = getAndClearMarkedRegion(next_addr, end_addr);
  6768     last_addr = dirty_region.end();
  6769     if (!dirty_region.is_empty()) {
  6770       cl->do_MemRegion(dirty_region);
  6771     } else {
  6772       assert(last_addr == end_addr, "program logic");
  6773       return;
  6778 void CMSBitMap::print_on_error(outputStream* st, const char* prefix) const {
  6779   _bm.print_on_error(st, prefix);
  6782 #ifndef PRODUCT
  6783 void CMSBitMap::assert_locked() const {
  6784   CMSLockVerifier::assert_locked(lock());
  6787 bool CMSBitMap::covers(MemRegion mr) const {
  6788   // assert(_bm.map() == _virtual_space.low(), "map inconsistency");
  6789   assert((size_t)_bm.size() == (_bmWordSize >> _shifter),
  6790          "size inconsistency");
  6791   return (mr.start() >= _bmStartWord) &&
  6792          (mr.end()   <= endWord());
  6795 bool CMSBitMap::covers(HeapWord* start, size_t size) const {
  6796     return (start >= _bmStartWord && (start + size) <= endWord());
  6799 void CMSBitMap::verifyNoOneBitsInRange(HeapWord* left, HeapWord* right) {
  6800   // verify that there are no 1 bits in the interval [left, right)
  6801   FalseBitMapClosure falseBitMapClosure;
  6802   iterate(&falseBitMapClosure, left, right);
  6805 void CMSBitMap::region_invariant(MemRegion mr)
  6807   assert_locked();
  6808   // mr = mr.intersection(MemRegion(_bmStartWord, _bmWordSize));
  6809   assert(!mr.is_empty(), "unexpected empty region");
  6810   assert(covers(mr), "mr should be covered by bit map");
  6811   // convert address range into offset range
  6812   size_t start_ofs = heapWordToOffset(mr.start());
  6813   // Make sure that end() is appropriately aligned
  6814   assert(mr.end() == (HeapWord*)round_to((intptr_t)mr.end(),
  6815                         (1 << (_shifter+LogHeapWordSize))),
  6816          "Misaligned mr.end()");
  6817   size_t end_ofs   = heapWordToOffset(mr.end());
  6818   assert(end_ofs > start_ofs, "Should mark at least one bit");
  6821 #endif
  6823 bool CMSMarkStack::allocate(size_t size) {
  6824   // allocate a stack of the requisite depth
  6825   ReservedSpace rs(ReservedSpace::allocation_align_size_up(
  6826                    size * sizeof(oop)));
  6827   if (!rs.is_reserved()) {
  6828     warning("CMSMarkStack allocation failure");
  6829     return false;
  6831   if (!_virtual_space.initialize(rs, rs.size())) {
  6832     warning("CMSMarkStack backing store failure");
  6833     return false;
  6835   assert(_virtual_space.committed_size() == rs.size(),
  6836          "didn't reserve backing store for all of CMS stack?");
  6837   _base = (oop*)(_virtual_space.low());
  6838   _index = 0;
  6839   _capacity = size;
  6840   NOT_PRODUCT(_max_depth = 0);
  6841   return true;
  6844 // XXX FIX ME !!! In the MT case we come in here holding a
  6845 // leaf lock. For printing we need to take a further lock
  6846 // which has lower rank. We need to recallibrate the two
  6847 // lock-ranks involved in order to be able to rpint the
  6848 // messages below. (Or defer the printing to the caller.
  6849 // For now we take the expedient path of just disabling the
  6850 // messages for the problematic case.)
  6851 void CMSMarkStack::expand() {
  6852   assert(_capacity <= MarkStackSizeMax, "stack bigger than permitted");
  6853   if (_capacity == MarkStackSizeMax) {
  6854     if (_hit_limit++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) {
  6855       // We print a warning message only once per CMS cycle.
  6856       gclog_or_tty->print_cr(" (benign) Hit CMSMarkStack max size limit");
  6858     return;
  6860   // Double capacity if possible
  6861   size_t new_capacity = MIN2(_capacity*2, MarkStackSizeMax);
  6862   // Do not give up existing stack until we have managed to
  6863   // get the double capacity that we desired.
  6864   ReservedSpace rs(ReservedSpace::allocation_align_size_up(
  6865                    new_capacity * sizeof(oop)));
  6866   if (rs.is_reserved()) {
  6867     // Release the backing store associated with old stack
  6868     _virtual_space.release();
  6869     // Reinitialize virtual space for new stack
  6870     if (!_virtual_space.initialize(rs, rs.size())) {
  6871       fatal("Not enough swap for expanded marking stack");
  6873     _base = (oop*)(_virtual_space.low());
  6874     _index = 0;
  6875     _capacity = new_capacity;
  6876   } else if (_failed_double++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) {
  6877     // Failed to double capacity, continue;
  6878     // we print a detail message only once per CMS cycle.
  6879     gclog_or_tty->print(" (benign) Failed to expand marking stack from "SIZE_FORMAT"K to "
  6880             SIZE_FORMAT"K",
  6881             _capacity / K, new_capacity / K);
  6886 // Closures
  6887 // XXX: there seems to be a lot of code  duplication here;
  6888 // should refactor and consolidate common code.
  6890 // This closure is used to mark refs into the CMS generation in
  6891 // the CMS bit map. Called at the first checkpoint. This closure
  6892 // assumes that we do not need to re-mark dirty cards; if the CMS
  6893 // generation on which this is used is not an oldest
  6894 // generation then this will lose younger_gen cards!
  6896 MarkRefsIntoClosure::MarkRefsIntoClosure(
  6897   MemRegion span, CMSBitMap* bitMap):
  6898     _span(span),
  6899     _bitMap(bitMap)
  6901     assert(_ref_processor == NULL, "deliberately left NULL");
  6902     assert(_bitMap->covers(_span), "_bitMap/_span mismatch");
  6905 void MarkRefsIntoClosure::do_oop(oop obj) {
  6906   // if p points into _span, then mark corresponding bit in _markBitMap
  6907   assert(obj->is_oop(), "expected an oop");
  6908   HeapWord* addr = (HeapWord*)obj;
  6909   if (_span.contains(addr)) {
  6910     // this should be made more efficient
  6911     _bitMap->mark(addr);
  6915 void MarkRefsIntoClosure::do_oop(oop* p)       { MarkRefsIntoClosure::do_oop_work(p); }
  6916 void MarkRefsIntoClosure::do_oop(narrowOop* p) { MarkRefsIntoClosure::do_oop_work(p); }
  6918 Par_MarkRefsIntoClosure::Par_MarkRefsIntoClosure(
  6919   MemRegion span, CMSBitMap* bitMap):
  6920     _span(span),
  6921     _bitMap(bitMap)
  6923     assert(_ref_processor == NULL, "deliberately left NULL");
  6924     assert(_bitMap->covers(_span), "_bitMap/_span mismatch");
  6927 void Par_MarkRefsIntoClosure::do_oop(oop obj) {
  6928   // if p points into _span, then mark corresponding bit in _markBitMap
  6929   assert(obj->is_oop(), "expected an oop");
  6930   HeapWord* addr = (HeapWord*)obj;
  6931   if (_span.contains(addr)) {
  6932     // this should be made more efficient
  6933     _bitMap->par_mark(addr);
  6937 void Par_MarkRefsIntoClosure::do_oop(oop* p)       { Par_MarkRefsIntoClosure::do_oop_work(p); }
  6938 void Par_MarkRefsIntoClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoClosure::do_oop_work(p); }
  6940 // A variant of the above, used for CMS marking verification.
  6941 MarkRefsIntoVerifyClosure::MarkRefsIntoVerifyClosure(
  6942   MemRegion span, CMSBitMap* verification_bm, CMSBitMap* cms_bm):
  6943     _span(span),
  6944     _verification_bm(verification_bm),
  6945     _cms_bm(cms_bm)
  6947     assert(_ref_processor == NULL, "deliberately left NULL");
  6948     assert(_verification_bm->covers(_span), "_verification_bm/_span mismatch");
  6951 void MarkRefsIntoVerifyClosure::do_oop(oop obj) {
  6952   // if p points into _span, then mark corresponding bit in _markBitMap
  6953   assert(obj->is_oop(), "expected an oop");
  6954   HeapWord* addr = (HeapWord*)obj;
  6955   if (_span.contains(addr)) {
  6956     _verification_bm->mark(addr);
  6957     if (!_cms_bm->isMarked(addr)) {
  6958       oop(addr)->print();
  6959       gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)", addr);
  6960       fatal("... aborting");
  6965 void MarkRefsIntoVerifyClosure::do_oop(oop* p)       { MarkRefsIntoVerifyClosure::do_oop_work(p); }
  6966 void MarkRefsIntoVerifyClosure::do_oop(narrowOop* p) { MarkRefsIntoVerifyClosure::do_oop_work(p); }
  6968 //////////////////////////////////////////////////
  6969 // MarkRefsIntoAndScanClosure
  6970 //////////////////////////////////////////////////
  6972 MarkRefsIntoAndScanClosure::MarkRefsIntoAndScanClosure(MemRegion span,
  6973                                                        ReferenceProcessor* rp,
  6974                                                        CMSBitMap* bit_map,
  6975                                                        CMSBitMap* mod_union_table,
  6976                                                        CMSMarkStack*  mark_stack,
  6977                                                        CMSCollector* collector,
  6978                                                        bool should_yield,
  6979                                                        bool concurrent_precleaning):
  6980   _collector(collector),
  6981   _span(span),
  6982   _bit_map(bit_map),
  6983   _mark_stack(mark_stack),
  6984   _pushAndMarkClosure(collector, span, rp, bit_map, mod_union_table,
  6985                       mark_stack, concurrent_precleaning),
  6986   _yield(should_yield),
  6987   _concurrent_precleaning(concurrent_precleaning),
  6988   _freelistLock(NULL)
  6990   _ref_processor = rp;
  6991   assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL");
  6994 // This closure is used to mark refs into the CMS generation at the
  6995 // second (final) checkpoint, and to scan and transitively follow
  6996 // the unmarked oops. It is also used during the concurrent precleaning
  6997 // phase while scanning objects on dirty cards in the CMS generation.
  6998 // The marks are made in the marking bit map and the marking stack is
  6999 // used for keeping the (newly) grey objects during the scan.
  7000 // The parallel version (Par_...) appears further below.
  7001 void MarkRefsIntoAndScanClosure::do_oop(oop obj) {
  7002   if (obj != NULL) {
  7003     assert(obj->is_oop(), "expected an oop");
  7004     HeapWord* addr = (HeapWord*)obj;
  7005     assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)");
  7006     assert(_collector->overflow_list_is_empty(),
  7007            "overflow list should be empty");
  7008     if (_span.contains(addr) &&
  7009         !_bit_map->isMarked(addr)) {
  7010       // mark bit map (object is now grey)
  7011       _bit_map->mark(addr);
  7012       // push on marking stack (stack should be empty), and drain the
  7013       // stack by applying this closure to the oops in the oops popped
  7014       // from the stack (i.e. blacken the grey objects)
  7015       bool res = _mark_stack->push(obj);
  7016       assert(res, "Should have space to push on empty stack");
  7017       do {
  7018         oop new_oop = _mark_stack->pop();
  7019         assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop");
  7020         assert(_bit_map->isMarked((HeapWord*)new_oop),
  7021                "only grey objects on this stack");
  7022         // iterate over the oops in this oop, marking and pushing
  7023         // the ones in CMS heap (i.e. in _span).
  7024         new_oop->oop_iterate(&_pushAndMarkClosure);
  7025         // check if it's time to yield
  7026         do_yield_check();
  7027       } while (!_mark_stack->isEmpty() ||
  7028                (!_concurrent_precleaning && take_from_overflow_list()));
  7029         // if marking stack is empty, and we are not doing this
  7030         // during precleaning, then check the overflow list
  7032     assert(_mark_stack->isEmpty(), "post-condition (eager drainage)");
  7033     assert(_collector->overflow_list_is_empty(),
  7034            "overflow list was drained above");
  7035     // We could restore evacuated mark words, if any, used for
  7036     // overflow list links here because the overflow list is
  7037     // provably empty here. That would reduce the maximum
  7038     // size requirements for preserved_{oop,mark}_stack.
  7039     // But we'll just postpone it until we are all done
  7040     // so we can just stream through.
  7041     if (!_concurrent_precleaning && CMSOverflowEarlyRestoration) {
  7042       _collector->restore_preserved_marks_if_any();
  7043       assert(_collector->no_preserved_marks(), "No preserved marks");
  7045     assert(!CMSOverflowEarlyRestoration || _collector->no_preserved_marks(),
  7046            "All preserved marks should have been restored above");
  7050 void MarkRefsIntoAndScanClosure::do_oop(oop* p)       { MarkRefsIntoAndScanClosure::do_oop_work(p); }
  7051 void MarkRefsIntoAndScanClosure::do_oop(narrowOop* p) { MarkRefsIntoAndScanClosure::do_oop_work(p); }
  7053 void MarkRefsIntoAndScanClosure::do_yield_work() {
  7054   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  7055          "CMS thread should hold CMS token");
  7056   assert_lock_strong(_freelistLock);
  7057   assert_lock_strong(_bit_map->lock());
  7058   // relinquish the free_list_lock and bitMaplock()
  7059   _bit_map->lock()->unlock();
  7060   _freelistLock->unlock();
  7061   ConcurrentMarkSweepThread::desynchronize(true);
  7062   ConcurrentMarkSweepThread::acknowledge_yield_request();
  7063   _collector->stopTimer();
  7064   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  7065   if (PrintCMSStatistics != 0) {
  7066     _collector->incrementYields();
  7068   _collector->icms_wait();
  7070   // See the comment in coordinator_yield()
  7071   for (unsigned i = 0;
  7072        i < CMSYieldSleepCount &&
  7073        ConcurrentMarkSweepThread::should_yield() &&
  7074        !CMSCollector::foregroundGCIsActive();
  7075        ++i) {
  7076     os::sleep(Thread::current(), 1, false);
  7077     ConcurrentMarkSweepThread::acknowledge_yield_request();
  7080   ConcurrentMarkSweepThread::synchronize(true);
  7081   _freelistLock->lock_without_safepoint_check();
  7082   _bit_map->lock()->lock_without_safepoint_check();
  7083   _collector->startTimer();
  7086 ///////////////////////////////////////////////////////////
  7087 // Par_MarkRefsIntoAndScanClosure: a parallel version of
  7088 //                                 MarkRefsIntoAndScanClosure
  7089 ///////////////////////////////////////////////////////////
  7090 Par_MarkRefsIntoAndScanClosure::Par_MarkRefsIntoAndScanClosure(
  7091   CMSCollector* collector, MemRegion span, ReferenceProcessor* rp,
  7092   CMSBitMap* bit_map, OopTaskQueue* work_queue):
  7093   _span(span),
  7094   _bit_map(bit_map),
  7095   _work_queue(work_queue),
  7096   _low_water_mark(MIN2((uint)(work_queue->max_elems()/4),
  7097                        (uint)(CMSWorkQueueDrainThreshold * ParallelGCThreads))),
  7098   _par_pushAndMarkClosure(collector, span, rp, bit_map, work_queue)
  7100   _ref_processor = rp;
  7101   assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL");
  7104 // This closure is used to mark refs into the CMS generation at the
  7105 // second (final) checkpoint, and to scan and transitively follow
  7106 // the unmarked oops. The marks are made in the marking bit map and
  7107 // the work_queue is used for keeping the (newly) grey objects during
  7108 // the scan phase whence they are also available for stealing by parallel
  7109 // threads. Since the marking bit map is shared, updates are
  7110 // synchronized (via CAS).
  7111 void Par_MarkRefsIntoAndScanClosure::do_oop(oop obj) {
  7112   if (obj != NULL) {
  7113     // Ignore mark word because this could be an already marked oop
  7114     // that may be chained at the end of the overflow list.
  7115     assert(obj->is_oop(true), "expected an oop");
  7116     HeapWord* addr = (HeapWord*)obj;
  7117     if (_span.contains(addr) &&
  7118         !_bit_map->isMarked(addr)) {
  7119       // mark bit map (object will become grey):
  7120       // It is possible for several threads to be
  7121       // trying to "claim" this object concurrently;
  7122       // the unique thread that succeeds in marking the
  7123       // object first will do the subsequent push on
  7124       // to the work queue (or overflow list).
  7125       if (_bit_map->par_mark(addr)) {
  7126         // push on work_queue (which may not be empty), and trim the
  7127         // queue to an appropriate length by applying this closure to
  7128         // the oops in the oops popped from the stack (i.e. blacken the
  7129         // grey objects)
  7130         bool res = _work_queue->push(obj);
  7131         assert(res, "Low water mark should be less than capacity?");
  7132         trim_queue(_low_water_mark);
  7133       } // Else, another thread claimed the object
  7138 void Par_MarkRefsIntoAndScanClosure::do_oop(oop* p)       { Par_MarkRefsIntoAndScanClosure::do_oop_work(p); }
  7139 void Par_MarkRefsIntoAndScanClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoAndScanClosure::do_oop_work(p); }
  7141 // This closure is used to rescan the marked objects on the dirty cards
  7142 // in the mod union table and the card table proper.
  7143 size_t ScanMarkedObjectsAgainCarefullyClosure::do_object_careful_m(
  7144   oop p, MemRegion mr) {
  7146   size_t size = 0;
  7147   HeapWord* addr = (HeapWord*)p;
  7148   DEBUG_ONLY(_collector->verify_work_stacks_empty();)
  7149   assert(_span.contains(addr), "we are scanning the CMS generation");
  7150   // check if it's time to yield
  7151   if (do_yield_check()) {
  7152     // We yielded for some foreground stop-world work,
  7153     // and we have been asked to abort this ongoing preclean cycle.
  7154     return 0;
  7156   if (_bitMap->isMarked(addr)) {
  7157     // it's marked; is it potentially uninitialized?
  7158     if (p->klass_or_null() != NULL) {
  7159         // an initialized object; ignore mark word in verification below
  7160         // since we are running concurrent with mutators
  7161         assert(p->is_oop(true), "should be an oop");
  7162         if (p->is_objArray()) {
  7163           // objArrays are precisely marked; restrict scanning
  7164           // to dirty cards only.
  7165           size = CompactibleFreeListSpace::adjustObjectSize(
  7166                    p->oop_iterate(_scanningClosure, mr));
  7167         } else {
  7168           // A non-array may have been imprecisely marked; we need
  7169           // to scan object in its entirety.
  7170           size = CompactibleFreeListSpace::adjustObjectSize(
  7171                    p->oop_iterate(_scanningClosure));
  7173         #ifdef ASSERT
  7174           size_t direct_size =
  7175             CompactibleFreeListSpace::adjustObjectSize(p->size());
  7176           assert(size == direct_size, "Inconsistency in size");
  7177           assert(size >= 3, "Necessary for Printezis marks to work");
  7178           if (!_bitMap->isMarked(addr+1)) {
  7179             _bitMap->verifyNoOneBitsInRange(addr+2, addr+size);
  7180           } else {
  7181             _bitMap->verifyNoOneBitsInRange(addr+2, addr+size-1);
  7182             assert(_bitMap->isMarked(addr+size-1),
  7183                    "inconsistent Printezis mark");
  7185         #endif // ASSERT
  7186     } else {
  7187       // an unitialized object
  7188       assert(_bitMap->isMarked(addr+1), "missing Printezis mark?");
  7189       HeapWord* nextOneAddr = _bitMap->getNextMarkedWordAddress(addr + 2);
  7190       size = pointer_delta(nextOneAddr + 1, addr);
  7191       assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
  7192              "alignment problem");
  7193       // Note that pre-cleaning needn't redirty the card. OopDesc::set_klass()
  7194       // will dirty the card when the klass pointer is installed in the
  7195       // object (signalling the completion of initialization).
  7197   } else {
  7198     // Either a not yet marked object or an uninitialized object
  7199     if (p->klass_or_null() == NULL) {
  7200       // An uninitialized object, skip to the next card, since
  7201       // we may not be able to read its P-bits yet.
  7202       assert(size == 0, "Initial value");
  7203     } else {
  7204       // An object not (yet) reached by marking: we merely need to
  7205       // compute its size so as to go look at the next block.
  7206       assert(p->is_oop(true), "should be an oop");
  7207       size = CompactibleFreeListSpace::adjustObjectSize(p->size());
  7210   DEBUG_ONLY(_collector->verify_work_stacks_empty();)
  7211   return size;
  7214 void ScanMarkedObjectsAgainCarefullyClosure::do_yield_work() {
  7215   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  7216          "CMS thread should hold CMS token");
  7217   assert_lock_strong(_freelistLock);
  7218   assert_lock_strong(_bitMap->lock());
  7219   // relinquish the free_list_lock and bitMaplock()
  7220   _bitMap->lock()->unlock();
  7221   _freelistLock->unlock();
  7222   ConcurrentMarkSweepThread::desynchronize(true);
  7223   ConcurrentMarkSweepThread::acknowledge_yield_request();
  7224   _collector->stopTimer();
  7225   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  7226   if (PrintCMSStatistics != 0) {
  7227     _collector->incrementYields();
  7229   _collector->icms_wait();
  7231   // See the comment in coordinator_yield()
  7232   for (unsigned i = 0; i < CMSYieldSleepCount &&
  7233                    ConcurrentMarkSweepThread::should_yield() &&
  7234                    !CMSCollector::foregroundGCIsActive(); ++i) {
  7235     os::sleep(Thread::current(), 1, false);
  7236     ConcurrentMarkSweepThread::acknowledge_yield_request();
  7239   ConcurrentMarkSweepThread::synchronize(true);
  7240   _freelistLock->lock_without_safepoint_check();
  7241   _bitMap->lock()->lock_without_safepoint_check();
  7242   _collector->startTimer();
  7246 //////////////////////////////////////////////////////////////////
  7247 // SurvivorSpacePrecleanClosure
  7248 //////////////////////////////////////////////////////////////////
  7249 // This (single-threaded) closure is used to preclean the oops in
  7250 // the survivor spaces.
  7251 size_t SurvivorSpacePrecleanClosure::do_object_careful(oop p) {
  7253   HeapWord* addr = (HeapWord*)p;
  7254   DEBUG_ONLY(_collector->verify_work_stacks_empty();)
  7255   assert(!_span.contains(addr), "we are scanning the survivor spaces");
  7256   assert(p->klass_or_null() != NULL, "object should be initializd");
  7257   // an initialized object; ignore mark word in verification below
  7258   // since we are running concurrent with mutators
  7259   assert(p->is_oop(true), "should be an oop");
  7260   // Note that we do not yield while we iterate over
  7261   // the interior oops of p, pushing the relevant ones
  7262   // on our marking stack.
  7263   size_t size = p->oop_iterate(_scanning_closure);
  7264   do_yield_check();
  7265   // Observe that below, we do not abandon the preclean
  7266   // phase as soon as we should; rather we empty the
  7267   // marking stack before returning. This is to satisfy
  7268   // some existing assertions. In general, it may be a
  7269   // good idea to abort immediately and complete the marking
  7270   // from the grey objects at a later time.
  7271   while (!_mark_stack->isEmpty()) {
  7272     oop new_oop = _mark_stack->pop();
  7273     assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop");
  7274     assert(_bit_map->isMarked((HeapWord*)new_oop),
  7275            "only grey objects on this stack");
  7276     // iterate over the oops in this oop, marking and pushing
  7277     // the ones in CMS heap (i.e. in _span).
  7278     new_oop->oop_iterate(_scanning_closure);
  7279     // check if it's time to yield
  7280     do_yield_check();
  7282   unsigned int after_count =
  7283     GenCollectedHeap::heap()->total_collections();
  7284   bool abort = (_before_count != after_count) ||
  7285                _collector->should_abort_preclean();
  7286   return abort ? 0 : size;
  7289 void SurvivorSpacePrecleanClosure::do_yield_work() {
  7290   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  7291          "CMS thread should hold CMS token");
  7292   assert_lock_strong(_bit_map->lock());
  7293   // Relinquish the bit map lock
  7294   _bit_map->lock()->unlock();
  7295   ConcurrentMarkSweepThread::desynchronize(true);
  7296   ConcurrentMarkSweepThread::acknowledge_yield_request();
  7297   _collector->stopTimer();
  7298   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  7299   if (PrintCMSStatistics != 0) {
  7300     _collector->incrementYields();
  7302   _collector->icms_wait();
  7304   // See the comment in coordinator_yield()
  7305   for (unsigned i = 0; i < CMSYieldSleepCount &&
  7306                        ConcurrentMarkSweepThread::should_yield() &&
  7307                        !CMSCollector::foregroundGCIsActive(); ++i) {
  7308     os::sleep(Thread::current(), 1, false);
  7309     ConcurrentMarkSweepThread::acknowledge_yield_request();
  7312   ConcurrentMarkSweepThread::synchronize(true);
  7313   _bit_map->lock()->lock_without_safepoint_check();
  7314   _collector->startTimer();
  7317 // This closure is used to rescan the marked objects on the dirty cards
  7318 // in the mod union table and the card table proper. In the parallel
  7319 // case, although the bitMap is shared, we do a single read so the
  7320 // isMarked() query is "safe".
  7321 bool ScanMarkedObjectsAgainClosure::do_object_bm(oop p, MemRegion mr) {
  7322   // Ignore mark word because we are running concurrent with mutators
  7323   assert(p->is_oop_or_null(true), "expected an oop or null");
  7324   HeapWord* addr = (HeapWord*)p;
  7325   assert(_span.contains(addr), "we are scanning the CMS generation");
  7326   bool is_obj_array = false;
  7327   #ifdef ASSERT
  7328     if (!_parallel) {
  7329       assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)");
  7330       assert(_collector->overflow_list_is_empty(),
  7331              "overflow list should be empty");
  7334   #endif // ASSERT
  7335   if (_bit_map->isMarked(addr)) {
  7336     // Obj arrays are precisely marked, non-arrays are not;
  7337     // so we scan objArrays precisely and non-arrays in their
  7338     // entirety.
  7339     if (p->is_objArray()) {
  7340       is_obj_array = true;
  7341       if (_parallel) {
  7342         p->oop_iterate(_par_scan_closure, mr);
  7343       } else {
  7344         p->oop_iterate(_scan_closure, mr);
  7346     } else {
  7347       if (_parallel) {
  7348         p->oop_iterate(_par_scan_closure);
  7349       } else {
  7350         p->oop_iterate(_scan_closure);
  7354   #ifdef ASSERT
  7355     if (!_parallel) {
  7356       assert(_mark_stack->isEmpty(), "post-condition (eager drainage)");
  7357       assert(_collector->overflow_list_is_empty(),
  7358              "overflow list should be empty");
  7361   #endif // ASSERT
  7362   return is_obj_array;
  7365 MarkFromRootsClosure::MarkFromRootsClosure(CMSCollector* collector,
  7366                         MemRegion span,
  7367                         CMSBitMap* bitMap, CMSMarkStack*  markStack,
  7368                         bool should_yield, bool verifying):
  7369   _collector(collector),
  7370   _span(span),
  7371   _bitMap(bitMap),
  7372   _mut(&collector->_modUnionTable),
  7373   _markStack(markStack),
  7374   _yield(should_yield),
  7375   _skipBits(0)
  7377   assert(_markStack->isEmpty(), "stack should be empty");
  7378   _finger = _bitMap->startWord();
  7379   _threshold = _finger;
  7380   assert(_collector->_restart_addr == NULL, "Sanity check");
  7381   assert(_span.contains(_finger), "Out of bounds _finger?");
  7382   DEBUG_ONLY(_verifying = verifying;)
  7385 void MarkFromRootsClosure::reset(HeapWord* addr) {
  7386   assert(_markStack->isEmpty(), "would cause duplicates on stack");
  7387   assert(_span.contains(addr), "Out of bounds _finger?");
  7388   _finger = addr;
  7389   _threshold = (HeapWord*)round_to(
  7390                  (intptr_t)_finger, CardTableModRefBS::card_size);
  7393 // Should revisit to see if this should be restructured for
  7394 // greater efficiency.
  7395 bool MarkFromRootsClosure::do_bit(size_t offset) {
  7396   if (_skipBits > 0) {
  7397     _skipBits--;
  7398     return true;
  7400   // convert offset into a HeapWord*
  7401   HeapWord* addr = _bitMap->startWord() + offset;
  7402   assert(_bitMap->endWord() && addr < _bitMap->endWord(),
  7403          "address out of range");
  7404   assert(_bitMap->isMarked(addr), "tautology");
  7405   if (_bitMap->isMarked(addr+1)) {
  7406     // this is an allocated but not yet initialized object
  7407     assert(_skipBits == 0, "tautology");
  7408     _skipBits = 2;  // skip next two marked bits ("Printezis-marks")
  7409     oop p = oop(addr);
  7410     if (p->klass_or_null() == NULL) {
  7411       DEBUG_ONLY(if (!_verifying) {)
  7412         // We re-dirty the cards on which this object lies and increase
  7413         // the _threshold so that we'll come back to scan this object
  7414         // during the preclean or remark phase. (CMSCleanOnEnter)
  7415         if (CMSCleanOnEnter) {
  7416           size_t sz = _collector->block_size_using_printezis_bits(addr);
  7417           HeapWord* end_card_addr   = (HeapWord*)round_to(
  7418                                          (intptr_t)(addr+sz), CardTableModRefBS::card_size);
  7419           MemRegion redirty_range = MemRegion(addr, end_card_addr);
  7420           assert(!redirty_range.is_empty(), "Arithmetical tautology");
  7421           // Bump _threshold to end_card_addr; note that
  7422           // _threshold cannot possibly exceed end_card_addr, anyhow.
  7423           // This prevents future clearing of the card as the scan proceeds
  7424           // to the right.
  7425           assert(_threshold <= end_card_addr,
  7426                  "Because we are just scanning into this object");
  7427           if (_threshold < end_card_addr) {
  7428             _threshold = end_card_addr;
  7430           if (p->klass_or_null() != NULL) {
  7431             // Redirty the range of cards...
  7432             _mut->mark_range(redirty_range);
  7433           } // ...else the setting of klass will dirty the card anyway.
  7435       DEBUG_ONLY(})
  7436       return true;
  7439   scanOopsInOop(addr);
  7440   return true;
  7443 // We take a break if we've been at this for a while,
  7444 // so as to avoid monopolizing the locks involved.
  7445 void MarkFromRootsClosure::do_yield_work() {
  7446   // First give up the locks, then yield, then re-lock
  7447   // We should probably use a constructor/destructor idiom to
  7448   // do this unlock/lock or modify the MutexUnlocker class to
  7449   // serve our purpose. XXX
  7450   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  7451          "CMS thread should hold CMS token");
  7452   assert_lock_strong(_bitMap->lock());
  7453   _bitMap->lock()->unlock();
  7454   ConcurrentMarkSweepThread::desynchronize(true);
  7455   ConcurrentMarkSweepThread::acknowledge_yield_request();
  7456   _collector->stopTimer();
  7457   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  7458   if (PrintCMSStatistics != 0) {
  7459     _collector->incrementYields();
  7461   _collector->icms_wait();
  7463   // See the comment in coordinator_yield()
  7464   for (unsigned i = 0; i < CMSYieldSleepCount &&
  7465                        ConcurrentMarkSweepThread::should_yield() &&
  7466                        !CMSCollector::foregroundGCIsActive(); ++i) {
  7467     os::sleep(Thread::current(), 1, false);
  7468     ConcurrentMarkSweepThread::acknowledge_yield_request();
  7471   ConcurrentMarkSweepThread::synchronize(true);
  7472   _bitMap->lock()->lock_without_safepoint_check();
  7473   _collector->startTimer();
  7476 void MarkFromRootsClosure::scanOopsInOop(HeapWord* ptr) {
  7477   assert(_bitMap->isMarked(ptr), "expected bit to be set");
  7478   assert(_markStack->isEmpty(),
  7479          "should drain stack to limit stack usage");
  7480   // convert ptr to an oop preparatory to scanning
  7481   oop obj = oop(ptr);
  7482   // Ignore mark word in verification below, since we
  7483   // may be running concurrent with mutators.
  7484   assert(obj->is_oop(true), "should be an oop");
  7485   assert(_finger <= ptr, "_finger runneth ahead");
  7486   // advance the finger to right end of this object
  7487   _finger = ptr + obj->size();
  7488   assert(_finger > ptr, "we just incremented it above");
  7489   // On large heaps, it may take us some time to get through
  7490   // the marking phase (especially if running iCMS). During
  7491   // this time it's possible that a lot of mutations have
  7492   // accumulated in the card table and the mod union table --
  7493   // these mutation records are redundant until we have
  7494   // actually traced into the corresponding card.
  7495   // Here, we check whether advancing the finger would make
  7496   // us cross into a new card, and if so clear corresponding
  7497   // cards in the MUT (preclean them in the card-table in the
  7498   // future).
  7500   DEBUG_ONLY(if (!_verifying) {)
  7501     // The clean-on-enter optimization is disabled by default,
  7502     // until we fix 6178663.
  7503     if (CMSCleanOnEnter && (_finger > _threshold)) {
  7504       // [_threshold, _finger) represents the interval
  7505       // of cards to be cleared  in MUT (or precleaned in card table).
  7506       // The set of cards to be cleared is all those that overlap
  7507       // with the interval [_threshold, _finger); note that
  7508       // _threshold is always kept card-aligned but _finger isn't
  7509       // always card-aligned.
  7510       HeapWord* old_threshold = _threshold;
  7511       assert(old_threshold == (HeapWord*)round_to(
  7512               (intptr_t)old_threshold, CardTableModRefBS::card_size),
  7513              "_threshold should always be card-aligned");
  7514       _threshold = (HeapWord*)round_to(
  7515                      (intptr_t)_finger, CardTableModRefBS::card_size);
  7516       MemRegion mr(old_threshold, _threshold);
  7517       assert(!mr.is_empty(), "Control point invariant");
  7518       assert(_span.contains(mr), "Should clear within span");
  7519       _mut->clear_range(mr);
  7521   DEBUG_ONLY(})
  7522   // Note: the finger doesn't advance while we drain
  7523   // the stack below.
  7524   PushOrMarkClosure pushOrMarkClosure(_collector,
  7525                                       _span, _bitMap, _markStack,
  7526                                       _finger, this);
  7527   bool res = _markStack->push(obj);
  7528   assert(res, "Empty non-zero size stack should have space for single push");
  7529   while (!_markStack->isEmpty()) {
  7530     oop new_oop = _markStack->pop();
  7531     // Skip verifying header mark word below because we are
  7532     // running concurrent with mutators.
  7533     assert(new_oop->is_oop(true), "Oops! expected to pop an oop");
  7534     // now scan this oop's oops
  7535     new_oop->oop_iterate(&pushOrMarkClosure);
  7536     do_yield_check();
  7538   assert(_markStack->isEmpty(), "tautology, emphasizing post-condition");
  7541 Par_MarkFromRootsClosure::Par_MarkFromRootsClosure(CMSConcMarkingTask* task,
  7542                        CMSCollector* collector, MemRegion span,
  7543                        CMSBitMap* bit_map,
  7544                        OopTaskQueue* work_queue,
  7545                        CMSMarkStack*  overflow_stack,
  7546                        bool should_yield):
  7547   _collector(collector),
  7548   _whole_span(collector->_span),
  7549   _span(span),
  7550   _bit_map(bit_map),
  7551   _mut(&collector->_modUnionTable),
  7552   _work_queue(work_queue),
  7553   _overflow_stack(overflow_stack),
  7554   _yield(should_yield),
  7555   _skip_bits(0),
  7556   _task(task)
  7558   assert(_work_queue->size() == 0, "work_queue should be empty");
  7559   _finger = span.start();
  7560   _threshold = _finger;     // XXX Defer clear-on-enter optimization for now
  7561   assert(_span.contains(_finger), "Out of bounds _finger?");
  7564 // Should revisit to see if this should be restructured for
  7565 // greater efficiency.
  7566 bool Par_MarkFromRootsClosure::do_bit(size_t offset) {
  7567   if (_skip_bits > 0) {
  7568     _skip_bits--;
  7569     return true;
  7571   // convert offset into a HeapWord*
  7572   HeapWord* addr = _bit_map->startWord() + offset;
  7573   assert(_bit_map->endWord() && addr < _bit_map->endWord(),
  7574          "address out of range");
  7575   assert(_bit_map->isMarked(addr), "tautology");
  7576   if (_bit_map->isMarked(addr+1)) {
  7577     // this is an allocated object that might not yet be initialized
  7578     assert(_skip_bits == 0, "tautology");
  7579     _skip_bits = 2;  // skip next two marked bits ("Printezis-marks")
  7580     oop p = oop(addr);
  7581     if (p->klass_or_null() == NULL) {
  7582       // in the case of Clean-on-Enter optimization, redirty card
  7583       // and avoid clearing card by increasing  the threshold.
  7584       return true;
  7587   scan_oops_in_oop(addr);
  7588   return true;
  7591 void Par_MarkFromRootsClosure::scan_oops_in_oop(HeapWord* ptr) {
  7592   assert(_bit_map->isMarked(ptr), "expected bit to be set");
  7593   // Should we assert that our work queue is empty or
  7594   // below some drain limit?
  7595   assert(_work_queue->size() == 0,
  7596          "should drain stack to limit stack usage");
  7597   // convert ptr to an oop preparatory to scanning
  7598   oop obj = oop(ptr);
  7599   // Ignore mark word in verification below, since we
  7600   // may be running concurrent with mutators.
  7601   assert(obj->is_oop(true), "should be an oop");
  7602   assert(_finger <= ptr, "_finger runneth ahead");
  7603   // advance the finger to right end of this object
  7604   _finger = ptr + obj->size();
  7605   assert(_finger > ptr, "we just incremented it above");
  7606   // On large heaps, it may take us some time to get through
  7607   // the marking phase (especially if running iCMS). During
  7608   // this time it's possible that a lot of mutations have
  7609   // accumulated in the card table and the mod union table --
  7610   // these mutation records are redundant until we have
  7611   // actually traced into the corresponding card.
  7612   // Here, we check whether advancing the finger would make
  7613   // us cross into a new card, and if so clear corresponding
  7614   // cards in the MUT (preclean them in the card-table in the
  7615   // future).
  7617   // The clean-on-enter optimization is disabled by default,
  7618   // until we fix 6178663.
  7619   if (CMSCleanOnEnter && (_finger > _threshold)) {
  7620     // [_threshold, _finger) represents the interval
  7621     // of cards to be cleared  in MUT (or precleaned in card table).
  7622     // The set of cards to be cleared is all those that overlap
  7623     // with the interval [_threshold, _finger); note that
  7624     // _threshold is always kept card-aligned but _finger isn't
  7625     // always card-aligned.
  7626     HeapWord* old_threshold = _threshold;
  7627     assert(old_threshold == (HeapWord*)round_to(
  7628             (intptr_t)old_threshold, CardTableModRefBS::card_size),
  7629            "_threshold should always be card-aligned");
  7630     _threshold = (HeapWord*)round_to(
  7631                    (intptr_t)_finger, CardTableModRefBS::card_size);
  7632     MemRegion mr(old_threshold, _threshold);
  7633     assert(!mr.is_empty(), "Control point invariant");
  7634     assert(_span.contains(mr), "Should clear within span"); // _whole_span ??
  7635     _mut->clear_range(mr);
  7638   // Note: the local finger doesn't advance while we drain
  7639   // the stack below, but the global finger sure can and will.
  7640   HeapWord** gfa = _task->global_finger_addr();
  7641   Par_PushOrMarkClosure pushOrMarkClosure(_collector,
  7642                                       _span, _bit_map,
  7643                                       _work_queue,
  7644                                       _overflow_stack,
  7645                                       _finger,
  7646                                       gfa, this);
  7647   bool res = _work_queue->push(obj);   // overflow could occur here
  7648   assert(res, "Will hold once we use workqueues");
  7649   while (true) {
  7650     oop new_oop;
  7651     if (!_work_queue->pop_local(new_oop)) {
  7652       // We emptied our work_queue; check if there's stuff that can
  7653       // be gotten from the overflow stack.
  7654       if (CMSConcMarkingTask::get_work_from_overflow_stack(
  7655             _overflow_stack, _work_queue)) {
  7656         do_yield_check();
  7657         continue;
  7658       } else {  // done
  7659         break;
  7662     // Skip verifying header mark word below because we are
  7663     // running concurrent with mutators.
  7664     assert(new_oop->is_oop(true), "Oops! expected to pop an oop");
  7665     // now scan this oop's oops
  7666     new_oop->oop_iterate(&pushOrMarkClosure);
  7667     do_yield_check();
  7669   assert(_work_queue->size() == 0, "tautology, emphasizing post-condition");
  7672 // Yield in response to a request from VM Thread or
  7673 // from mutators.
  7674 void Par_MarkFromRootsClosure::do_yield_work() {
  7675   assert(_task != NULL, "sanity");
  7676   _task->yield();
  7679 // A variant of the above used for verifying CMS marking work.
  7680 MarkFromRootsVerifyClosure::MarkFromRootsVerifyClosure(CMSCollector* collector,
  7681                         MemRegion span,
  7682                         CMSBitMap* verification_bm, CMSBitMap* cms_bm,
  7683                         CMSMarkStack*  mark_stack):
  7684   _collector(collector),
  7685   _span(span),
  7686   _verification_bm(verification_bm),
  7687   _cms_bm(cms_bm),
  7688   _mark_stack(mark_stack),
  7689   _pam_verify_closure(collector, span, verification_bm, cms_bm,
  7690                       mark_stack)
  7692   assert(_mark_stack->isEmpty(), "stack should be empty");
  7693   _finger = _verification_bm->startWord();
  7694   assert(_collector->_restart_addr == NULL, "Sanity check");
  7695   assert(_span.contains(_finger), "Out of bounds _finger?");
  7698 void MarkFromRootsVerifyClosure::reset(HeapWord* addr) {
  7699   assert(_mark_stack->isEmpty(), "would cause duplicates on stack");
  7700   assert(_span.contains(addr), "Out of bounds _finger?");
  7701   _finger = addr;
  7704 // Should revisit to see if this should be restructured for
  7705 // greater efficiency.
  7706 bool MarkFromRootsVerifyClosure::do_bit(size_t offset) {
  7707   // convert offset into a HeapWord*
  7708   HeapWord* addr = _verification_bm->startWord() + offset;
  7709   assert(_verification_bm->endWord() && addr < _verification_bm->endWord(),
  7710          "address out of range");
  7711   assert(_verification_bm->isMarked(addr), "tautology");
  7712   assert(_cms_bm->isMarked(addr), "tautology");
  7714   assert(_mark_stack->isEmpty(),
  7715          "should drain stack to limit stack usage");
  7716   // convert addr to an oop preparatory to scanning
  7717   oop obj = oop(addr);
  7718   assert(obj->is_oop(), "should be an oop");
  7719   assert(_finger <= addr, "_finger runneth ahead");
  7720   // advance the finger to right end of this object
  7721   _finger = addr + obj->size();
  7722   assert(_finger > addr, "we just incremented it above");
  7723   // Note: the finger doesn't advance while we drain
  7724   // the stack below.
  7725   bool res = _mark_stack->push(obj);
  7726   assert(res, "Empty non-zero size stack should have space for single push");
  7727   while (!_mark_stack->isEmpty()) {
  7728     oop new_oop = _mark_stack->pop();
  7729     assert(new_oop->is_oop(), "Oops! expected to pop an oop");
  7730     // now scan this oop's oops
  7731     new_oop->oop_iterate(&_pam_verify_closure);
  7733   assert(_mark_stack->isEmpty(), "tautology, emphasizing post-condition");
  7734   return true;
  7737 PushAndMarkVerifyClosure::PushAndMarkVerifyClosure(
  7738   CMSCollector* collector, MemRegion span,
  7739   CMSBitMap* verification_bm, CMSBitMap* cms_bm,
  7740   CMSMarkStack*  mark_stack):
  7741   CMSOopClosure(collector->ref_processor()),
  7742   _collector(collector),
  7743   _span(span),
  7744   _verification_bm(verification_bm),
  7745   _cms_bm(cms_bm),
  7746   _mark_stack(mark_stack)
  7747 { }
  7749 void PushAndMarkVerifyClosure::do_oop(oop* p)       { PushAndMarkVerifyClosure::do_oop_work(p); }
  7750 void PushAndMarkVerifyClosure::do_oop(narrowOop* p) { PushAndMarkVerifyClosure::do_oop_work(p); }
  7752 // Upon stack overflow, we discard (part of) the stack,
  7753 // remembering the least address amongst those discarded
  7754 // in CMSCollector's _restart_address.
  7755 void PushAndMarkVerifyClosure::handle_stack_overflow(HeapWord* lost) {
  7756   // Remember the least grey address discarded
  7757   HeapWord* ra = (HeapWord*)_mark_stack->least_value(lost);
  7758   _collector->lower_restart_addr(ra);
  7759   _mark_stack->reset();  // discard stack contents
  7760   _mark_stack->expand(); // expand the stack if possible
  7763 void PushAndMarkVerifyClosure::do_oop(oop obj) {
  7764   assert(obj->is_oop_or_null(), "expected an oop or NULL");
  7765   HeapWord* addr = (HeapWord*)obj;
  7766   if (_span.contains(addr) && !_verification_bm->isMarked(addr)) {
  7767     // Oop lies in _span and isn't yet grey or black
  7768     _verification_bm->mark(addr);            // now grey
  7769     if (!_cms_bm->isMarked(addr)) {
  7770       oop(addr)->print();
  7771       gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)",
  7772                              addr);
  7773       fatal("... aborting");
  7776     if (!_mark_stack->push(obj)) { // stack overflow
  7777       if (PrintCMSStatistics != 0) {
  7778         gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
  7779                                SIZE_FORMAT, _mark_stack->capacity());
  7781       assert(_mark_stack->isFull(), "Else push should have succeeded");
  7782       handle_stack_overflow(addr);
  7784     // anything including and to the right of _finger
  7785     // will be scanned as we iterate over the remainder of the
  7786     // bit map
  7790 PushOrMarkClosure::PushOrMarkClosure(CMSCollector* collector,
  7791                      MemRegion span,
  7792                      CMSBitMap* bitMap, CMSMarkStack*  markStack,
  7793                      HeapWord* finger, MarkFromRootsClosure* parent) :
  7794   CMSOopClosure(collector->ref_processor()),
  7795   _collector(collector),
  7796   _span(span),
  7797   _bitMap(bitMap),
  7798   _markStack(markStack),
  7799   _finger(finger),
  7800   _parent(parent)
  7801 { }
  7803 Par_PushOrMarkClosure::Par_PushOrMarkClosure(CMSCollector* collector,
  7804                      MemRegion span,
  7805                      CMSBitMap* bit_map,
  7806                      OopTaskQueue* work_queue,
  7807                      CMSMarkStack*  overflow_stack,
  7808                      HeapWord* finger,
  7809                      HeapWord** global_finger_addr,
  7810                      Par_MarkFromRootsClosure* parent) :
  7811   CMSOopClosure(collector->ref_processor()),
  7812   _collector(collector),
  7813   _whole_span(collector->_span),
  7814   _span(span),
  7815   _bit_map(bit_map),
  7816   _work_queue(work_queue),
  7817   _overflow_stack(overflow_stack),
  7818   _finger(finger),
  7819   _global_finger_addr(global_finger_addr),
  7820   _parent(parent)
  7821 { }
  7823 // Assumes thread-safe access by callers, who are
  7824 // responsible for mutual exclusion.
  7825 void CMSCollector::lower_restart_addr(HeapWord* low) {
  7826   assert(_span.contains(low), "Out of bounds addr");
  7827   if (_restart_addr == NULL) {
  7828     _restart_addr = low;
  7829   } else {
  7830     _restart_addr = MIN2(_restart_addr, low);
  7834 // Upon stack overflow, we discard (part of) the stack,
  7835 // remembering the least address amongst those discarded
  7836 // in CMSCollector's _restart_address.
  7837 void PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) {
  7838   // Remember the least grey address discarded
  7839   HeapWord* ra = (HeapWord*)_markStack->least_value(lost);
  7840   _collector->lower_restart_addr(ra);
  7841   _markStack->reset();  // discard stack contents
  7842   _markStack->expand(); // expand the stack if possible
  7845 // Upon stack overflow, we discard (part of) the stack,
  7846 // remembering the least address amongst those discarded
  7847 // in CMSCollector's _restart_address.
  7848 void Par_PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) {
  7849   // We need to do this under a mutex to prevent other
  7850   // workers from interfering with the work done below.
  7851   MutexLockerEx ml(_overflow_stack->par_lock(),
  7852                    Mutex::_no_safepoint_check_flag);
  7853   // Remember the least grey address discarded
  7854   HeapWord* ra = (HeapWord*)_overflow_stack->least_value(lost);
  7855   _collector->lower_restart_addr(ra);
  7856   _overflow_stack->reset();  // discard stack contents
  7857   _overflow_stack->expand(); // expand the stack if possible
  7860 void CMKlassClosure::do_klass(Klass* k) {
  7861   assert(_oop_closure != NULL, "Not initialized?");
  7862   k->oops_do(_oop_closure);
  7865 void PushOrMarkClosure::do_oop(oop obj) {
  7866   // Ignore mark word because we are running concurrent with mutators.
  7867   assert(obj->is_oop_or_null(true), "expected an oop or NULL");
  7868   HeapWord* addr = (HeapWord*)obj;
  7869   if (_span.contains(addr) && !_bitMap->isMarked(addr)) {
  7870     // Oop lies in _span and isn't yet grey or black
  7871     _bitMap->mark(addr);            // now grey
  7872     if (addr < _finger) {
  7873       // the bit map iteration has already either passed, or
  7874       // sampled, this bit in the bit map; we'll need to
  7875       // use the marking stack to scan this oop's oops.
  7876       bool simulate_overflow = false;
  7877       NOT_PRODUCT(
  7878         if (CMSMarkStackOverflowALot &&
  7879             _collector->simulate_overflow()) {
  7880           // simulate a stack overflow
  7881           simulate_overflow = true;
  7884       if (simulate_overflow || !_markStack->push(obj)) { // stack overflow
  7885         if (PrintCMSStatistics != 0) {
  7886           gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
  7887                                  SIZE_FORMAT, _markStack->capacity());
  7889         assert(simulate_overflow || _markStack->isFull(), "Else push should have succeeded");
  7890         handle_stack_overflow(addr);
  7893     // anything including and to the right of _finger
  7894     // will be scanned as we iterate over the remainder of the
  7895     // bit map
  7896     do_yield_check();
  7900 void PushOrMarkClosure::do_oop(oop* p)       { PushOrMarkClosure::do_oop_work(p); }
  7901 void PushOrMarkClosure::do_oop(narrowOop* p) { PushOrMarkClosure::do_oop_work(p); }
  7903 void Par_PushOrMarkClosure::do_oop(oop obj) {
  7904   // Ignore mark word because we are running concurrent with mutators.
  7905   assert(obj->is_oop_or_null(true), "expected an oop or NULL");
  7906   HeapWord* addr = (HeapWord*)obj;
  7907   if (_whole_span.contains(addr) && !_bit_map->isMarked(addr)) {
  7908     // Oop lies in _span and isn't yet grey or black
  7909     // We read the global_finger (volatile read) strictly after marking oop
  7910     bool res = _bit_map->par_mark(addr);    // now grey
  7911     volatile HeapWord** gfa = (volatile HeapWord**)_global_finger_addr;
  7912     // Should we push this marked oop on our stack?
  7913     // -- if someone else marked it, nothing to do
  7914     // -- if target oop is above global finger nothing to do
  7915     // -- if target oop is in chunk and above local finger
  7916     //      then nothing to do
  7917     // -- else push on work queue
  7918     if (   !res       // someone else marked it, they will deal with it
  7919         || (addr >= *gfa)  // will be scanned in a later task
  7920         || (_span.contains(addr) && addr >= _finger)) { // later in this chunk
  7921       return;
  7923     // the bit map iteration has already either passed, or
  7924     // sampled, this bit in the bit map; we'll need to
  7925     // use the marking stack to scan this oop's oops.
  7926     bool simulate_overflow = false;
  7927     NOT_PRODUCT(
  7928       if (CMSMarkStackOverflowALot &&
  7929           _collector->simulate_overflow()) {
  7930         // simulate a stack overflow
  7931         simulate_overflow = true;
  7934     if (simulate_overflow ||
  7935         !(_work_queue->push(obj) || _overflow_stack->par_push(obj))) {
  7936       // stack overflow
  7937       if (PrintCMSStatistics != 0) {
  7938         gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
  7939                                SIZE_FORMAT, _overflow_stack->capacity());
  7941       // We cannot assert that the overflow stack is full because
  7942       // it may have been emptied since.
  7943       assert(simulate_overflow ||
  7944              _work_queue->size() == _work_queue->max_elems(),
  7945             "Else push should have succeeded");
  7946       handle_stack_overflow(addr);
  7948     do_yield_check();
  7952 void Par_PushOrMarkClosure::do_oop(oop* p)       { Par_PushOrMarkClosure::do_oop_work(p); }
  7953 void Par_PushOrMarkClosure::do_oop(narrowOop* p) { Par_PushOrMarkClosure::do_oop_work(p); }
  7955 PushAndMarkClosure::PushAndMarkClosure(CMSCollector* collector,
  7956                                        MemRegion span,
  7957                                        ReferenceProcessor* rp,
  7958                                        CMSBitMap* bit_map,
  7959                                        CMSBitMap* mod_union_table,
  7960                                        CMSMarkStack*  mark_stack,
  7961                                        bool           concurrent_precleaning):
  7962   CMSOopClosure(rp),
  7963   _collector(collector),
  7964   _span(span),
  7965   _bit_map(bit_map),
  7966   _mod_union_table(mod_union_table),
  7967   _mark_stack(mark_stack),
  7968   _concurrent_precleaning(concurrent_precleaning)
  7970   assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL");
  7973 // Grey object rescan during pre-cleaning and second checkpoint phases --
  7974 // the non-parallel version (the parallel version appears further below.)
  7975 void PushAndMarkClosure::do_oop(oop obj) {
  7976   // Ignore mark word verification. If during concurrent precleaning,
  7977   // the object monitor may be locked. If during the checkpoint
  7978   // phases, the object may already have been reached by a  different
  7979   // path and may be at the end of the global overflow list (so
  7980   // the mark word may be NULL).
  7981   assert(obj->is_oop_or_null(true /* ignore mark word */),
  7982          "expected an oop or NULL");
  7983   HeapWord* addr = (HeapWord*)obj;
  7984   // Check if oop points into the CMS generation
  7985   // and is not marked
  7986   if (_span.contains(addr) && !_bit_map->isMarked(addr)) {
  7987     // a white object ...
  7988     _bit_map->mark(addr);         // ... now grey
  7989     // push on the marking stack (grey set)
  7990     bool simulate_overflow = false;
  7991     NOT_PRODUCT(
  7992       if (CMSMarkStackOverflowALot &&
  7993           _collector->simulate_overflow()) {
  7994         // simulate a stack overflow
  7995         simulate_overflow = true;
  7998     if (simulate_overflow || !_mark_stack->push(obj)) {
  7999       if (_concurrent_precleaning) {
  8000          // During precleaning we can just dirty the appropriate card(s)
  8001          // in the mod union table, thus ensuring that the object remains
  8002          // in the grey set  and continue. In the case of object arrays
  8003          // we need to dirty all of the cards that the object spans,
  8004          // since the rescan of object arrays will be limited to the
  8005          // dirty cards.
  8006          // Note that no one can be intefering with us in this action
  8007          // of dirtying the mod union table, so no locking or atomics
  8008          // are required.
  8009          if (obj->is_objArray()) {
  8010            size_t sz = obj->size();
  8011            HeapWord* end_card_addr = (HeapWord*)round_to(
  8012                                         (intptr_t)(addr+sz), CardTableModRefBS::card_size);
  8013            MemRegion redirty_range = MemRegion(addr, end_card_addr);
  8014            assert(!redirty_range.is_empty(), "Arithmetical tautology");
  8015            _mod_union_table->mark_range(redirty_range);
  8016          } else {
  8017            _mod_union_table->mark(addr);
  8019          _collector->_ser_pmc_preclean_ovflw++;
  8020       } else {
  8021          // During the remark phase, we need to remember this oop
  8022          // in the overflow list.
  8023          _collector->push_on_overflow_list(obj);
  8024          _collector->_ser_pmc_remark_ovflw++;
  8030 Par_PushAndMarkClosure::Par_PushAndMarkClosure(CMSCollector* collector,
  8031                                                MemRegion span,
  8032                                                ReferenceProcessor* rp,
  8033                                                CMSBitMap* bit_map,
  8034                                                OopTaskQueue* work_queue):
  8035   CMSOopClosure(rp),
  8036   _collector(collector),
  8037   _span(span),
  8038   _bit_map(bit_map),
  8039   _work_queue(work_queue)
  8041   assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL");
  8044 void PushAndMarkClosure::do_oop(oop* p)       { PushAndMarkClosure::do_oop_work(p); }
  8045 void PushAndMarkClosure::do_oop(narrowOop* p) { PushAndMarkClosure::do_oop_work(p); }
  8047 // Grey object rescan during second checkpoint phase --
  8048 // the parallel version.
  8049 void Par_PushAndMarkClosure::do_oop(oop obj) {
  8050   // In the assert below, we ignore the mark word because
  8051   // this oop may point to an already visited object that is
  8052   // on the overflow stack (in which case the mark word has
  8053   // been hijacked for chaining into the overflow stack --
  8054   // if this is the last object in the overflow stack then
  8055   // its mark word will be NULL). Because this object may
  8056   // have been subsequently popped off the global overflow
  8057   // stack, and the mark word possibly restored to the prototypical
  8058   // value, by the time we get to examined this failing assert in
  8059   // the debugger, is_oop_or_null(false) may subsequently start
  8060   // to hold.
  8061   assert(obj->is_oop_or_null(true),
  8062          "expected an oop or NULL");
  8063   HeapWord* addr = (HeapWord*)obj;
  8064   // Check if oop points into the CMS generation
  8065   // and is not marked
  8066   if (_span.contains(addr) && !_bit_map->isMarked(addr)) {
  8067     // a white object ...
  8068     // If we manage to "claim" the object, by being the
  8069     // first thread to mark it, then we push it on our
  8070     // marking stack
  8071     if (_bit_map->par_mark(addr)) {     // ... now grey
  8072       // push on work queue (grey set)
  8073       bool simulate_overflow = false;
  8074       NOT_PRODUCT(
  8075         if (CMSMarkStackOverflowALot &&
  8076             _collector->par_simulate_overflow()) {
  8077           // simulate a stack overflow
  8078           simulate_overflow = true;
  8081       if (simulate_overflow || !_work_queue->push(obj)) {
  8082         _collector->par_push_on_overflow_list(obj);
  8083         _collector->_par_pmc_remark_ovflw++; //  imprecise OK: no need to CAS
  8085     } // Else, some other thread got there first
  8089 void Par_PushAndMarkClosure::do_oop(oop* p)       { Par_PushAndMarkClosure::do_oop_work(p); }
  8090 void Par_PushAndMarkClosure::do_oop(narrowOop* p) { Par_PushAndMarkClosure::do_oop_work(p); }
  8092 void CMSPrecleanRefsYieldClosure::do_yield_work() {
  8093   Mutex* bml = _collector->bitMapLock();
  8094   assert_lock_strong(bml);
  8095   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  8096          "CMS thread should hold CMS token");
  8098   bml->unlock();
  8099   ConcurrentMarkSweepThread::desynchronize(true);
  8101   ConcurrentMarkSweepThread::acknowledge_yield_request();
  8103   _collector->stopTimer();
  8104   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  8105   if (PrintCMSStatistics != 0) {
  8106     _collector->incrementYields();
  8108   _collector->icms_wait();
  8110   // See the comment in coordinator_yield()
  8111   for (unsigned i = 0; i < CMSYieldSleepCount &&
  8112                        ConcurrentMarkSweepThread::should_yield() &&
  8113                        !CMSCollector::foregroundGCIsActive(); ++i) {
  8114     os::sleep(Thread::current(), 1, false);
  8115     ConcurrentMarkSweepThread::acknowledge_yield_request();
  8118   ConcurrentMarkSweepThread::synchronize(true);
  8119   bml->lock();
  8121   _collector->startTimer();
  8124 bool CMSPrecleanRefsYieldClosure::should_return() {
  8125   if (ConcurrentMarkSweepThread::should_yield()) {
  8126     do_yield_work();
  8128   return _collector->foregroundGCIsActive();
  8131 void MarkFromDirtyCardsClosure::do_MemRegion(MemRegion mr) {
  8132   assert(((size_t)mr.start())%CardTableModRefBS::card_size_in_words == 0,
  8133          "mr should be aligned to start at a card boundary");
  8134   // We'd like to assert:
  8135   // assert(mr.word_size()%CardTableModRefBS::card_size_in_words == 0,
  8136   //        "mr should be a range of cards");
  8137   // However, that would be too strong in one case -- the last
  8138   // partition ends at _unallocated_block which, in general, can be
  8139   // an arbitrary boundary, not necessarily card aligned.
  8140   if (PrintCMSStatistics != 0) {
  8141     _num_dirty_cards +=
  8142          mr.word_size()/CardTableModRefBS::card_size_in_words;
  8144   _space->object_iterate_mem(mr, &_scan_cl);
  8147 SweepClosure::SweepClosure(CMSCollector* collector,
  8148                            ConcurrentMarkSweepGeneration* g,
  8149                            CMSBitMap* bitMap, bool should_yield) :
  8150   _collector(collector),
  8151   _g(g),
  8152   _sp(g->cmsSpace()),
  8153   _limit(_sp->sweep_limit()),
  8154   _freelistLock(_sp->freelistLock()),
  8155   _bitMap(bitMap),
  8156   _yield(should_yield),
  8157   _inFreeRange(false),           // No free range at beginning of sweep
  8158   _freeRangeInFreeLists(false),  // No free range at beginning of sweep
  8159   _lastFreeRangeCoalesced(false),
  8160   _freeFinger(g->used_region().start())
  8162   NOT_PRODUCT(
  8163     _numObjectsFreed = 0;
  8164     _numWordsFreed   = 0;
  8165     _numObjectsLive = 0;
  8166     _numWordsLive = 0;
  8167     _numObjectsAlreadyFree = 0;
  8168     _numWordsAlreadyFree = 0;
  8169     _last_fc = NULL;
  8171     _sp->initializeIndexedFreeListArrayReturnedBytes();
  8172     _sp->dictionary()->initialize_dict_returned_bytes();
  8174   assert(_limit >= _sp->bottom() && _limit <= _sp->end(),
  8175          "sweep _limit out of bounds");
  8176   if (CMSTraceSweeper) {
  8177     gclog_or_tty->print_cr("\n====================\nStarting new sweep with limit " PTR_FORMAT,
  8178                         _limit);
  8182 void SweepClosure::print_on(outputStream* st) const {
  8183   tty->print_cr("_sp = [" PTR_FORMAT "," PTR_FORMAT ")",
  8184                 _sp->bottom(), _sp->end());
  8185   tty->print_cr("_limit = " PTR_FORMAT, _limit);
  8186   tty->print_cr("_freeFinger = " PTR_FORMAT, _freeFinger);
  8187   NOT_PRODUCT(tty->print_cr("_last_fc = " PTR_FORMAT, _last_fc);)
  8188   tty->print_cr("_inFreeRange = %d, _freeRangeInFreeLists = %d, _lastFreeRangeCoalesced = %d",
  8189                 _inFreeRange, _freeRangeInFreeLists, _lastFreeRangeCoalesced);
  8192 #ifndef PRODUCT
  8193 // Assertion checking only:  no useful work in product mode --
  8194 // however, if any of the flags below become product flags,
  8195 // you may need to review this code to see if it needs to be
  8196 // enabled in product mode.
  8197 SweepClosure::~SweepClosure() {
  8198   assert_lock_strong(_freelistLock);
  8199   assert(_limit >= _sp->bottom() && _limit <= _sp->end(),
  8200          "sweep _limit out of bounds");
  8201   if (inFreeRange()) {
  8202     warning("inFreeRange() should have been reset; dumping state of SweepClosure");
  8203     print();
  8204     ShouldNotReachHere();
  8206   if (Verbose && PrintGC) {
  8207     gclog_or_tty->print("Collected "SIZE_FORMAT" objects, " SIZE_FORMAT " bytes",
  8208                         _numObjectsFreed, _numWordsFreed*sizeof(HeapWord));
  8209     gclog_or_tty->print_cr("\nLive "SIZE_FORMAT" objects,  "
  8210                            SIZE_FORMAT" bytes  "
  8211       "Already free "SIZE_FORMAT" objects, "SIZE_FORMAT" bytes",
  8212       _numObjectsLive, _numWordsLive*sizeof(HeapWord),
  8213       _numObjectsAlreadyFree, _numWordsAlreadyFree*sizeof(HeapWord));
  8214     size_t totalBytes = (_numWordsFreed + _numWordsLive + _numWordsAlreadyFree)
  8215                         * sizeof(HeapWord);
  8216     gclog_or_tty->print_cr("Total sweep: "SIZE_FORMAT" bytes", totalBytes);
  8218     if (PrintCMSStatistics && CMSVerifyReturnedBytes) {
  8219       size_t indexListReturnedBytes = _sp->sumIndexedFreeListArrayReturnedBytes();
  8220       size_t dict_returned_bytes = _sp->dictionary()->sum_dict_returned_bytes();
  8221       size_t returned_bytes = indexListReturnedBytes + dict_returned_bytes;
  8222       gclog_or_tty->print("Returned "SIZE_FORMAT" bytes", returned_bytes);
  8223       gclog_or_tty->print("   Indexed List Returned "SIZE_FORMAT" bytes",
  8224         indexListReturnedBytes);
  8225       gclog_or_tty->print_cr("        Dictionary Returned "SIZE_FORMAT" bytes",
  8226         dict_returned_bytes);
  8229   if (CMSTraceSweeper) {
  8230     gclog_or_tty->print_cr("end of sweep with _limit = " PTR_FORMAT "\n================",
  8231                            _limit);
  8234 #endif  // PRODUCT
  8236 void SweepClosure::initialize_free_range(HeapWord* freeFinger,
  8237     bool freeRangeInFreeLists) {
  8238   if (CMSTraceSweeper) {
  8239     gclog_or_tty->print("---- Start free range at 0x%x with free block (%d)\n",
  8240                freeFinger, freeRangeInFreeLists);
  8242   assert(!inFreeRange(), "Trampling existing free range");
  8243   set_inFreeRange(true);
  8244   set_lastFreeRangeCoalesced(false);
  8246   set_freeFinger(freeFinger);
  8247   set_freeRangeInFreeLists(freeRangeInFreeLists);
  8248   if (CMSTestInFreeList) {
  8249     if (freeRangeInFreeLists) {
  8250       FreeChunk* fc = (FreeChunk*) freeFinger;
  8251       assert(fc->is_free(), "A chunk on the free list should be free.");
  8252       assert(fc->size() > 0, "Free range should have a size");
  8253       assert(_sp->verify_chunk_in_free_list(fc), "Chunk is not in free lists");
  8258 // Note that the sweeper runs concurrently with mutators. Thus,
  8259 // it is possible for direct allocation in this generation to happen
  8260 // in the middle of the sweep. Note that the sweeper also coalesces
  8261 // contiguous free blocks. Thus, unless the sweeper and the allocator
  8262 // synchronize appropriately freshly allocated blocks may get swept up.
  8263 // This is accomplished by the sweeper locking the free lists while
  8264 // it is sweeping. Thus blocks that are determined to be free are
  8265 // indeed free. There is however one additional complication:
  8266 // blocks that have been allocated since the final checkpoint and
  8267 // mark, will not have been marked and so would be treated as
  8268 // unreachable and swept up. To prevent this, the allocator marks
  8269 // the bit map when allocating during the sweep phase. This leads,
  8270 // however, to a further complication -- objects may have been allocated
  8271 // but not yet initialized -- in the sense that the header isn't yet
  8272 // installed. The sweeper can not then determine the size of the block
  8273 // in order to skip over it. To deal with this case, we use a technique
  8274 // (due to Printezis) to encode such uninitialized block sizes in the
  8275 // bit map. Since the bit map uses a bit per every HeapWord, but the
  8276 // CMS generation has a minimum object size of 3 HeapWords, it follows
  8277 // that "normal marks" won't be adjacent in the bit map (there will
  8278 // always be at least two 0 bits between successive 1 bits). We make use
  8279 // of these "unused" bits to represent uninitialized blocks -- the bit
  8280 // corresponding to the start of the uninitialized object and the next
  8281 // bit are both set. Finally, a 1 bit marks the end of the object that
  8282 // started with the two consecutive 1 bits to indicate its potentially
  8283 // uninitialized state.
  8285 size_t SweepClosure::do_blk_careful(HeapWord* addr) {
  8286   FreeChunk* fc = (FreeChunk*)addr;
  8287   size_t res;
  8289   // Check if we are done sweeping. Below we check "addr >= _limit" rather
  8290   // than "addr == _limit" because although _limit was a block boundary when
  8291   // we started the sweep, it may no longer be one because heap expansion
  8292   // may have caused us to coalesce the block ending at the address _limit
  8293   // with a newly expanded chunk (this happens when _limit was set to the
  8294   // previous _end of the space), so we may have stepped past _limit:
  8295   // see the following Zeno-like trail of CRs 6977970, 7008136, 7042740.
  8296   if (addr >= _limit) { // we have swept up to or past the limit: finish up
  8297     assert(_limit >= _sp->bottom() && _limit <= _sp->end(),
  8298            "sweep _limit out of bounds");
  8299     assert(addr < _sp->end(), "addr out of bounds");
  8300     // Flush any free range we might be holding as a single
  8301     // coalesced chunk to the appropriate free list.
  8302     if (inFreeRange()) {
  8303       assert(freeFinger() >= _sp->bottom() && freeFinger() < _limit,
  8304              err_msg("freeFinger() " PTR_FORMAT" is out-of-bounds", freeFinger()));
  8305       flush_cur_free_chunk(freeFinger(),
  8306                            pointer_delta(addr, freeFinger()));
  8307       if (CMSTraceSweeper) {
  8308         gclog_or_tty->print("Sweep: last chunk: ");
  8309         gclog_or_tty->print("put_free_blk 0x%x ("SIZE_FORMAT") "
  8310                    "[coalesced:"SIZE_FORMAT"]\n",
  8311                    freeFinger(), pointer_delta(addr, freeFinger()),
  8312                    lastFreeRangeCoalesced());
  8316     // help the iterator loop finish
  8317     return pointer_delta(_sp->end(), addr);
  8320   assert(addr < _limit, "sweep invariant");
  8321   // check if we should yield
  8322   do_yield_check(addr);
  8323   if (fc->is_free()) {
  8324     // Chunk that is already free
  8325     res = fc->size();
  8326     do_already_free_chunk(fc);
  8327     debug_only(_sp->verifyFreeLists());
  8328     // If we flush the chunk at hand in lookahead_and_flush()
  8329     // and it's coalesced with a preceding chunk, then the
  8330     // process of "mangling" the payload of the coalesced block
  8331     // will cause erasure of the size information from the
  8332     // (erstwhile) header of all the coalesced blocks but the
  8333     // first, so the first disjunct in the assert will not hold
  8334     // in that specific case (in which case the second disjunct
  8335     // will hold).
  8336     assert(res == fc->size() || ((HeapWord*)fc) + res >= _limit,
  8337            "Otherwise the size info doesn't change at this step");
  8338     NOT_PRODUCT(
  8339       _numObjectsAlreadyFree++;
  8340       _numWordsAlreadyFree += res;
  8342     NOT_PRODUCT(_last_fc = fc;)
  8343   } else if (!_bitMap->isMarked(addr)) {
  8344     // Chunk is fresh garbage
  8345     res = do_garbage_chunk(fc);
  8346     debug_only(_sp->verifyFreeLists());
  8347     NOT_PRODUCT(
  8348       _numObjectsFreed++;
  8349       _numWordsFreed += res;
  8351   } else {
  8352     // Chunk that is alive.
  8353     res = do_live_chunk(fc);
  8354     debug_only(_sp->verifyFreeLists());
  8355     NOT_PRODUCT(
  8356         _numObjectsLive++;
  8357         _numWordsLive += res;
  8360   return res;
  8363 // For the smart allocation, record following
  8364 //  split deaths - a free chunk is removed from its free list because
  8365 //      it is being split into two or more chunks.
  8366 //  split birth - a free chunk is being added to its free list because
  8367 //      a larger free chunk has been split and resulted in this free chunk.
  8368 //  coal death - a free chunk is being removed from its free list because
  8369 //      it is being coalesced into a large free chunk.
  8370 //  coal birth - a free chunk is being added to its free list because
  8371 //      it was created when two or more free chunks where coalesced into
  8372 //      this free chunk.
  8373 //
  8374 // These statistics are used to determine the desired number of free
  8375 // chunks of a given size.  The desired number is chosen to be relative
  8376 // to the end of a CMS sweep.  The desired number at the end of a sweep
  8377 // is the
  8378 //      count-at-end-of-previous-sweep (an amount that was enough)
  8379 //              - count-at-beginning-of-current-sweep  (the excess)
  8380 //              + split-births  (gains in this size during interval)
  8381 //              - split-deaths  (demands on this size during interval)
  8382 // where the interval is from the end of one sweep to the end of the
  8383 // next.
  8384 //
  8385 // When sweeping the sweeper maintains an accumulated chunk which is
  8386 // the chunk that is made up of chunks that have been coalesced.  That
  8387 // will be termed the left-hand chunk.  A new chunk of garbage that
  8388 // is being considered for coalescing will be referred to as the
  8389 // right-hand chunk.
  8390 //
  8391 // When making a decision on whether to coalesce a right-hand chunk with
  8392 // the current left-hand chunk, the current count vs. the desired count
  8393 // of the left-hand chunk is considered.  Also if the right-hand chunk
  8394 // is near the large chunk at the end of the heap (see
  8395 // ConcurrentMarkSweepGeneration::isNearLargestChunk()), then the
  8396 // left-hand chunk is coalesced.
  8397 //
  8398 // When making a decision about whether to split a chunk, the desired count
  8399 // vs. the current count of the candidate to be split is also considered.
  8400 // If the candidate is underpopulated (currently fewer chunks than desired)
  8401 // a chunk of an overpopulated (currently more chunks than desired) size may
  8402 // be chosen.  The "hint" associated with a free list, if non-null, points
  8403 // to a free list which may be overpopulated.
  8404 //
  8406 void SweepClosure::do_already_free_chunk(FreeChunk* fc) {
  8407   const size_t size = fc->size();
  8408   // Chunks that cannot be coalesced are not in the
  8409   // free lists.
  8410   if (CMSTestInFreeList && !fc->cantCoalesce()) {
  8411     assert(_sp->verify_chunk_in_free_list(fc),
  8412       "free chunk should be in free lists");
  8414   // a chunk that is already free, should not have been
  8415   // marked in the bit map
  8416   HeapWord* const addr = (HeapWord*) fc;
  8417   assert(!_bitMap->isMarked(addr), "free chunk should be unmarked");
  8418   // Verify that the bit map has no bits marked between
  8419   // addr and purported end of this block.
  8420   _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size);
  8422   // Some chunks cannot be coalesced under any circumstances.
  8423   // See the definition of cantCoalesce().
  8424   if (!fc->cantCoalesce()) {
  8425     // This chunk can potentially be coalesced.
  8426     if (_sp->adaptive_freelists()) {
  8427       // All the work is done in
  8428       do_post_free_or_garbage_chunk(fc, size);
  8429     } else {  // Not adaptive free lists
  8430       // this is a free chunk that can potentially be coalesced by the sweeper;
  8431       if (!inFreeRange()) {
  8432         // if the next chunk is a free block that can't be coalesced
  8433         // it doesn't make sense to remove this chunk from the free lists
  8434         FreeChunk* nextChunk = (FreeChunk*)(addr + size);
  8435         assert((HeapWord*)nextChunk <= _sp->end(), "Chunk size out of bounds?");
  8436         if ((HeapWord*)nextChunk < _sp->end() &&     // There is another free chunk to the right ...
  8437             nextChunk->is_free()               &&     // ... which is free...
  8438             nextChunk->cantCoalesce()) {             // ... but can't be coalesced
  8439           // nothing to do
  8440         } else {
  8441           // Potentially the start of a new free range:
  8442           // Don't eagerly remove it from the free lists.
  8443           // No need to remove it if it will just be put
  8444           // back again.  (Also from a pragmatic point of view
  8445           // if it is a free block in a region that is beyond
  8446           // any allocated blocks, an assertion will fail)
  8447           // Remember the start of a free run.
  8448           initialize_free_range(addr, true);
  8449           // end - can coalesce with next chunk
  8451       } else {
  8452         // the midst of a free range, we are coalescing
  8453         print_free_block_coalesced(fc);
  8454         if (CMSTraceSweeper) {
  8455           gclog_or_tty->print("  -- pick up free block 0x%x (%d)\n", fc, size);
  8457         // remove it from the free lists
  8458         _sp->removeFreeChunkFromFreeLists(fc);
  8459         set_lastFreeRangeCoalesced(true);
  8460         // If the chunk is being coalesced and the current free range is
  8461         // in the free lists, remove the current free range so that it
  8462         // will be returned to the free lists in its entirety - all
  8463         // the coalesced pieces included.
  8464         if (freeRangeInFreeLists()) {
  8465           FreeChunk* ffc = (FreeChunk*) freeFinger();
  8466           assert(ffc->size() == pointer_delta(addr, freeFinger()),
  8467             "Size of free range is inconsistent with chunk size.");
  8468           if (CMSTestInFreeList) {
  8469             assert(_sp->verify_chunk_in_free_list(ffc),
  8470               "free range is not in free lists");
  8472           _sp->removeFreeChunkFromFreeLists(ffc);
  8473           set_freeRangeInFreeLists(false);
  8477     // Note that if the chunk is not coalescable (the else arm
  8478     // below), we unconditionally flush, without needing to do
  8479     // a "lookahead," as we do below.
  8480     if (inFreeRange()) lookahead_and_flush(fc, size);
  8481   } else {
  8482     // Code path common to both original and adaptive free lists.
  8484     // cant coalesce with previous block; this should be treated
  8485     // as the end of a free run if any
  8486     if (inFreeRange()) {
  8487       // we kicked some butt; time to pick up the garbage
  8488       assert(freeFinger() < addr, "freeFinger points too high");
  8489       flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger()));
  8491     // else, nothing to do, just continue
  8495 size_t SweepClosure::do_garbage_chunk(FreeChunk* fc) {
  8496   // This is a chunk of garbage.  It is not in any free list.
  8497   // Add it to a free list or let it possibly be coalesced into
  8498   // a larger chunk.
  8499   HeapWord* const addr = (HeapWord*) fc;
  8500   const size_t size = CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size());
  8502   if (_sp->adaptive_freelists()) {
  8503     // Verify that the bit map has no bits marked between
  8504     // addr and purported end of just dead object.
  8505     _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size);
  8507     do_post_free_or_garbage_chunk(fc, size);
  8508   } else {
  8509     if (!inFreeRange()) {
  8510       // start of a new free range
  8511       assert(size > 0, "A free range should have a size");
  8512       initialize_free_range(addr, false);
  8513     } else {
  8514       // this will be swept up when we hit the end of the
  8515       // free range
  8516       if (CMSTraceSweeper) {
  8517         gclog_or_tty->print("  -- pick up garbage 0x%x (%d) \n", fc, size);
  8519       // If the chunk is being coalesced and the current free range is
  8520       // in the free lists, remove the current free range so that it
  8521       // will be returned to the free lists in its entirety - all
  8522       // the coalesced pieces included.
  8523       if (freeRangeInFreeLists()) {
  8524         FreeChunk* ffc = (FreeChunk*)freeFinger();
  8525         assert(ffc->size() == pointer_delta(addr, freeFinger()),
  8526           "Size of free range is inconsistent with chunk size.");
  8527         if (CMSTestInFreeList) {
  8528           assert(_sp->verify_chunk_in_free_list(ffc),
  8529             "free range is not in free lists");
  8531         _sp->removeFreeChunkFromFreeLists(ffc);
  8532         set_freeRangeInFreeLists(false);
  8534       set_lastFreeRangeCoalesced(true);
  8536     // this will be swept up when we hit the end of the free range
  8538     // Verify that the bit map has no bits marked between
  8539     // addr and purported end of just dead object.
  8540     _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size);
  8542   assert(_limit >= addr + size,
  8543          "A freshly garbage chunk can't possibly straddle over _limit");
  8544   if (inFreeRange()) lookahead_and_flush(fc, size);
  8545   return size;
  8548 size_t SweepClosure::do_live_chunk(FreeChunk* fc) {
  8549   HeapWord* addr = (HeapWord*) fc;
  8550   // The sweeper has just found a live object. Return any accumulated
  8551   // left hand chunk to the free lists.
  8552   if (inFreeRange()) {
  8553     assert(freeFinger() < addr, "freeFinger points too high");
  8554     flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger()));
  8557   // This object is live: we'd normally expect this to be
  8558   // an oop, and like to assert the following:
  8559   // assert(oop(addr)->is_oop(), "live block should be an oop");
  8560   // However, as we commented above, this may be an object whose
  8561   // header hasn't yet been initialized.
  8562   size_t size;
  8563   assert(_bitMap->isMarked(addr), "Tautology for this control point");
  8564   if (_bitMap->isMarked(addr + 1)) {
  8565     // Determine the size from the bit map, rather than trying to
  8566     // compute it from the object header.
  8567     HeapWord* nextOneAddr = _bitMap->getNextMarkedWordAddress(addr + 2);
  8568     size = pointer_delta(nextOneAddr + 1, addr);
  8569     assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
  8570            "alignment problem");
  8572 #ifdef ASSERT
  8573       if (oop(addr)->klass_or_null() != NULL) {
  8574         // Ignore mark word because we are running concurrent with mutators
  8575         assert(oop(addr)->is_oop(true), "live block should be an oop");
  8576         assert(size ==
  8577                CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size()),
  8578                "P-mark and computed size do not agree");
  8580 #endif
  8582   } else {
  8583     // This should be an initialized object that's alive.
  8584     assert(oop(addr)->klass_or_null() != NULL,
  8585            "Should be an initialized object");
  8586     // Ignore mark word because we are running concurrent with mutators
  8587     assert(oop(addr)->is_oop(true), "live block should be an oop");
  8588     // Verify that the bit map has no bits marked between
  8589     // addr and purported end of this block.
  8590     size = CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size());
  8591     assert(size >= 3, "Necessary for Printezis marks to work");
  8592     assert(!_bitMap->isMarked(addr+1), "Tautology for this control point");
  8593     DEBUG_ONLY(_bitMap->verifyNoOneBitsInRange(addr+2, addr+size);)
  8595   return size;
  8598 void SweepClosure::do_post_free_or_garbage_chunk(FreeChunk* fc,
  8599                                                  size_t chunkSize) {
  8600   // do_post_free_or_garbage_chunk() should only be called in the case
  8601   // of the adaptive free list allocator.
  8602   const bool fcInFreeLists = fc->is_free();
  8603   assert(_sp->adaptive_freelists(), "Should only be used in this case.");
  8604   assert((HeapWord*)fc <= _limit, "sweep invariant");
  8605   if (CMSTestInFreeList && fcInFreeLists) {
  8606     assert(_sp->verify_chunk_in_free_list(fc), "free chunk is not in free lists");
  8609   if (CMSTraceSweeper) {
  8610     gclog_or_tty->print_cr("  -- pick up another chunk at 0x%x (%d)", fc, chunkSize);
  8613   HeapWord* const fc_addr = (HeapWord*) fc;
  8615   bool coalesce;
  8616   const size_t left  = pointer_delta(fc_addr, freeFinger());
  8617   const size_t right = chunkSize;
  8618   switch (FLSCoalescePolicy) {
  8619     // numeric value forms a coalition aggressiveness metric
  8620     case 0:  { // never coalesce
  8621       coalesce = false;
  8622       break;
  8624     case 1: { // coalesce if left & right chunks on overpopulated lists
  8625       coalesce = _sp->coalOverPopulated(left) &&
  8626                  _sp->coalOverPopulated(right);
  8627       break;
  8629     case 2: { // coalesce if left chunk on overpopulated list (default)
  8630       coalesce = _sp->coalOverPopulated(left);
  8631       break;
  8633     case 3: { // coalesce if left OR right chunk on overpopulated list
  8634       coalesce = _sp->coalOverPopulated(left) ||
  8635                  _sp->coalOverPopulated(right);
  8636       break;
  8638     case 4: { // always coalesce
  8639       coalesce = true;
  8640       break;
  8642     default:
  8643      ShouldNotReachHere();
  8646   // Should the current free range be coalesced?
  8647   // If the chunk is in a free range and either we decided to coalesce above
  8648   // or the chunk is near the large block at the end of the heap
  8649   // (isNearLargestChunk() returns true), then coalesce this chunk.
  8650   const bool doCoalesce = inFreeRange()
  8651                           && (coalesce || _g->isNearLargestChunk(fc_addr));
  8652   if (doCoalesce) {
  8653     // Coalesce the current free range on the left with the new
  8654     // chunk on the right.  If either is on a free list,
  8655     // it must be removed from the list and stashed in the closure.
  8656     if (freeRangeInFreeLists()) {
  8657       FreeChunk* const ffc = (FreeChunk*)freeFinger();
  8658       assert(ffc->size() == pointer_delta(fc_addr, freeFinger()),
  8659         "Size of free range is inconsistent with chunk size.");
  8660       if (CMSTestInFreeList) {
  8661         assert(_sp->verify_chunk_in_free_list(ffc),
  8662           "Chunk is not in free lists");
  8664       _sp->coalDeath(ffc->size());
  8665       _sp->removeFreeChunkFromFreeLists(ffc);
  8666       set_freeRangeInFreeLists(false);
  8668     if (fcInFreeLists) {
  8669       _sp->coalDeath(chunkSize);
  8670       assert(fc->size() == chunkSize,
  8671         "The chunk has the wrong size or is not in the free lists");
  8672       _sp->removeFreeChunkFromFreeLists(fc);
  8674     set_lastFreeRangeCoalesced(true);
  8675     print_free_block_coalesced(fc);
  8676   } else {  // not in a free range and/or should not coalesce
  8677     // Return the current free range and start a new one.
  8678     if (inFreeRange()) {
  8679       // In a free range but cannot coalesce with the right hand chunk.
  8680       // Put the current free range into the free lists.
  8681       flush_cur_free_chunk(freeFinger(),
  8682                            pointer_delta(fc_addr, freeFinger()));
  8684     // Set up for new free range.  Pass along whether the right hand
  8685     // chunk is in the free lists.
  8686     initialize_free_range((HeapWord*)fc, fcInFreeLists);
  8690 // Lookahead flush:
  8691 // If we are tracking a free range, and this is the last chunk that
  8692 // we'll look at because its end crosses past _limit, we'll preemptively
  8693 // flush it along with any free range we may be holding on to. Note that
  8694 // this can be the case only for an already free or freshly garbage
  8695 // chunk. If this block is an object, it can never straddle
  8696 // over _limit. The "straddling" occurs when _limit is set at
  8697 // the previous end of the space when this cycle started, and
  8698 // a subsequent heap expansion caused the previously co-terminal
  8699 // free block to be coalesced with the newly expanded portion,
  8700 // thus rendering _limit a non-block-boundary making it dangerous
  8701 // for the sweeper to step over and examine.
  8702 void SweepClosure::lookahead_and_flush(FreeChunk* fc, size_t chunk_size) {
  8703   assert(inFreeRange(), "Should only be called if currently in a free range.");
  8704   HeapWord* const eob = ((HeapWord*)fc) + chunk_size;
  8705   assert(_sp->used_region().contains(eob - 1),
  8706          err_msg("eob = " PTR_FORMAT " eob-1 = " PTR_FORMAT " _limit = " PTR_FORMAT
  8707                  " out of bounds wrt _sp = [" PTR_FORMAT "," PTR_FORMAT ")"
  8708                  " when examining fc = " PTR_FORMAT "(" SIZE_FORMAT ")",
  8709                  eob, eob-1, _limit, _sp->bottom(), _sp->end(), fc, chunk_size));
  8710   if (eob >= _limit) {
  8711     assert(eob == _limit || fc->is_free(), "Only a free chunk should allow us to cross over the limit");
  8712     if (CMSTraceSweeper) {
  8713       gclog_or_tty->print_cr("_limit " PTR_FORMAT " reached or crossed by block "
  8714                              "[" PTR_FORMAT "," PTR_FORMAT ") in space "
  8715                              "[" PTR_FORMAT "," PTR_FORMAT ")",
  8716                              _limit, fc, eob, _sp->bottom(), _sp->end());
  8718     // Return the storage we are tracking back into the free lists.
  8719     if (CMSTraceSweeper) {
  8720       gclog_or_tty->print_cr("Flushing ... ");
  8722     assert(freeFinger() < eob, "Error");
  8723     flush_cur_free_chunk( freeFinger(), pointer_delta(eob, freeFinger()));
  8727 void SweepClosure::flush_cur_free_chunk(HeapWord* chunk, size_t size) {
  8728   assert(inFreeRange(), "Should only be called if currently in a free range.");
  8729   assert(size > 0,
  8730     "A zero sized chunk cannot be added to the free lists.");
  8731   if (!freeRangeInFreeLists()) {
  8732     if (CMSTestInFreeList) {
  8733       FreeChunk* fc = (FreeChunk*) chunk;
  8734       fc->set_size(size);
  8735       assert(!_sp->verify_chunk_in_free_list(fc),
  8736         "chunk should not be in free lists yet");
  8738     if (CMSTraceSweeper) {
  8739       gclog_or_tty->print_cr(" -- add free block 0x%x (%d) to free lists",
  8740                     chunk, size);
  8742     // A new free range is going to be starting.  The current
  8743     // free range has not been added to the free lists yet or
  8744     // was removed so add it back.
  8745     // If the current free range was coalesced, then the death
  8746     // of the free range was recorded.  Record a birth now.
  8747     if (lastFreeRangeCoalesced()) {
  8748       _sp->coalBirth(size);
  8750     _sp->addChunkAndRepairOffsetTable(chunk, size,
  8751             lastFreeRangeCoalesced());
  8752   } else if (CMSTraceSweeper) {
  8753     gclog_or_tty->print_cr("Already in free list: nothing to flush");
  8755   set_inFreeRange(false);
  8756   set_freeRangeInFreeLists(false);
  8759 // We take a break if we've been at this for a while,
  8760 // so as to avoid monopolizing the locks involved.
  8761 void SweepClosure::do_yield_work(HeapWord* addr) {
  8762   // Return current free chunk being used for coalescing (if any)
  8763   // to the appropriate freelist.  After yielding, the next
  8764   // free block encountered will start a coalescing range of
  8765   // free blocks.  If the next free block is adjacent to the
  8766   // chunk just flushed, they will need to wait for the next
  8767   // sweep to be coalesced.
  8768   if (inFreeRange()) {
  8769     flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger()));
  8772   // First give up the locks, then yield, then re-lock.
  8773   // We should probably use a constructor/destructor idiom to
  8774   // do this unlock/lock or modify the MutexUnlocker class to
  8775   // serve our purpose. XXX
  8776   assert_lock_strong(_bitMap->lock());
  8777   assert_lock_strong(_freelistLock);
  8778   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
  8779          "CMS thread should hold CMS token");
  8780   _bitMap->lock()->unlock();
  8781   _freelistLock->unlock();
  8782   ConcurrentMarkSweepThread::desynchronize(true);
  8783   ConcurrentMarkSweepThread::acknowledge_yield_request();
  8784   _collector->stopTimer();
  8785   GCPauseTimer p(_collector->size_policy()->concurrent_timer_ptr());
  8786   if (PrintCMSStatistics != 0) {
  8787     _collector->incrementYields();
  8789   _collector->icms_wait();
  8791   // See the comment in coordinator_yield()
  8792   for (unsigned i = 0; i < CMSYieldSleepCount &&
  8793                        ConcurrentMarkSweepThread::should_yield() &&
  8794                        !CMSCollector::foregroundGCIsActive(); ++i) {
  8795     os::sleep(Thread::current(), 1, false);
  8796     ConcurrentMarkSweepThread::acknowledge_yield_request();
  8799   ConcurrentMarkSweepThread::synchronize(true);
  8800   _freelistLock->lock();
  8801   _bitMap->lock()->lock_without_safepoint_check();
  8802   _collector->startTimer();
  8805 #ifndef PRODUCT
  8806 // This is actually very useful in a product build if it can
  8807 // be called from the debugger.  Compile it into the product
  8808 // as needed.
  8809 bool debug_verify_chunk_in_free_list(FreeChunk* fc) {
  8810   return debug_cms_space->verify_chunk_in_free_list(fc);
  8812 #endif
  8814 void SweepClosure::print_free_block_coalesced(FreeChunk* fc) const {
  8815   if (CMSTraceSweeper) {
  8816     gclog_or_tty->print_cr("Sweep:coal_free_blk " PTR_FORMAT " (" SIZE_FORMAT ")",
  8817                            fc, fc->size());
  8821 // CMSIsAliveClosure
  8822 bool CMSIsAliveClosure::do_object_b(oop obj) {
  8823   HeapWord* addr = (HeapWord*)obj;
  8824   return addr != NULL &&
  8825          (!_span.contains(addr) || _bit_map->isMarked(addr));
  8829 CMSKeepAliveClosure::CMSKeepAliveClosure( CMSCollector* collector,
  8830                       MemRegion span,
  8831                       CMSBitMap* bit_map, CMSMarkStack* mark_stack,
  8832                       bool cpc):
  8833   _collector(collector),
  8834   _span(span),
  8835   _bit_map(bit_map),
  8836   _mark_stack(mark_stack),
  8837   _concurrent_precleaning(cpc) {
  8838   assert(!_span.is_empty(), "Empty span could spell trouble");
  8842 // CMSKeepAliveClosure: the serial version
  8843 void CMSKeepAliveClosure::do_oop(oop obj) {
  8844   HeapWord* addr = (HeapWord*)obj;
  8845   if (_span.contains(addr) &&
  8846       !_bit_map->isMarked(addr)) {
  8847     _bit_map->mark(addr);
  8848     bool simulate_overflow = false;
  8849     NOT_PRODUCT(
  8850       if (CMSMarkStackOverflowALot &&
  8851           _collector->simulate_overflow()) {
  8852         // simulate a stack overflow
  8853         simulate_overflow = true;
  8856     if (simulate_overflow || !_mark_stack->push(obj)) {
  8857       if (_concurrent_precleaning) {
  8858         // We dirty the overflown object and let the remark
  8859         // phase deal with it.
  8860         assert(_collector->overflow_list_is_empty(), "Error");
  8861         // In the case of object arrays, we need to dirty all of
  8862         // the cards that the object spans. No locking or atomics
  8863         // are needed since no one else can be mutating the mod union
  8864         // table.
  8865         if (obj->is_objArray()) {
  8866           size_t sz = obj->size();
  8867           HeapWord* end_card_addr =
  8868             (HeapWord*)round_to((intptr_t)(addr+sz), CardTableModRefBS::card_size);
  8869           MemRegion redirty_range = MemRegion(addr, end_card_addr);
  8870           assert(!redirty_range.is_empty(), "Arithmetical tautology");
  8871           _collector->_modUnionTable.mark_range(redirty_range);
  8872         } else {
  8873           _collector->_modUnionTable.mark(addr);
  8875         _collector->_ser_kac_preclean_ovflw++;
  8876       } else {
  8877         _collector->push_on_overflow_list(obj);
  8878         _collector->_ser_kac_ovflw++;
  8884 void CMSKeepAliveClosure::do_oop(oop* p)       { CMSKeepAliveClosure::do_oop_work(p); }
  8885 void CMSKeepAliveClosure::do_oop(narrowOop* p) { CMSKeepAliveClosure::do_oop_work(p); }
  8887 // CMSParKeepAliveClosure: a parallel version of the above.
  8888 // The work queues are private to each closure (thread),
  8889 // but (may be) available for stealing by other threads.
  8890 void CMSParKeepAliveClosure::do_oop(oop obj) {
  8891   HeapWord* addr = (HeapWord*)obj;
  8892   if (_span.contains(addr) &&
  8893       !_bit_map->isMarked(addr)) {
  8894     // In general, during recursive tracing, several threads
  8895     // may be concurrently getting here; the first one to
  8896     // "tag" it, claims it.
  8897     if (_bit_map->par_mark(addr)) {
  8898       bool res = _work_queue->push(obj);
  8899       assert(res, "Low water mark should be much less than capacity");
  8900       // Do a recursive trim in the hope that this will keep
  8901       // stack usage lower, but leave some oops for potential stealers
  8902       trim_queue(_low_water_mark);
  8903     } // Else, another thread got there first
  8907 void CMSParKeepAliveClosure::do_oop(oop* p)       { CMSParKeepAliveClosure::do_oop_work(p); }
  8908 void CMSParKeepAliveClosure::do_oop(narrowOop* p) { CMSParKeepAliveClosure::do_oop_work(p); }
  8910 void CMSParKeepAliveClosure::trim_queue(uint max) {
  8911   while (_work_queue->size() > max) {
  8912     oop new_oop;
  8913     if (_work_queue->pop_local(new_oop)) {
  8914       assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop");
  8915       assert(_bit_map->isMarked((HeapWord*)new_oop),
  8916              "no white objects on this stack!");
  8917       assert(_span.contains((HeapWord*)new_oop), "Out of bounds oop");
  8918       // iterate over the oops in this oop, marking and pushing
  8919       // the ones in CMS heap (i.e. in _span).
  8920       new_oop->oop_iterate(&_mark_and_push);
  8925 CMSInnerParMarkAndPushClosure::CMSInnerParMarkAndPushClosure(
  8926                                 CMSCollector* collector,
  8927                                 MemRegion span, CMSBitMap* bit_map,
  8928                                 OopTaskQueue* work_queue):
  8929   _collector(collector),
  8930   _span(span),
  8931   _bit_map(bit_map),
  8932   _work_queue(work_queue) { }
  8934 void CMSInnerParMarkAndPushClosure::do_oop(oop obj) {
  8935   HeapWord* addr = (HeapWord*)obj;
  8936   if (_span.contains(addr) &&
  8937       !_bit_map->isMarked(addr)) {
  8938     if (_bit_map->par_mark(addr)) {
  8939       bool simulate_overflow = false;
  8940       NOT_PRODUCT(
  8941         if (CMSMarkStackOverflowALot &&
  8942             _collector->par_simulate_overflow()) {
  8943           // simulate a stack overflow
  8944           simulate_overflow = true;
  8947       if (simulate_overflow || !_work_queue->push(obj)) {
  8948         _collector->par_push_on_overflow_list(obj);
  8949         _collector->_par_kac_ovflw++;
  8951     } // Else another thread got there already
  8955 void CMSInnerParMarkAndPushClosure::do_oop(oop* p)       { CMSInnerParMarkAndPushClosure::do_oop_work(p); }
  8956 void CMSInnerParMarkAndPushClosure::do_oop(narrowOop* p) { CMSInnerParMarkAndPushClosure::do_oop_work(p); }
  8958 //////////////////////////////////////////////////////////////////
  8959 //  CMSExpansionCause                /////////////////////////////
  8960 //////////////////////////////////////////////////////////////////
  8961 const char* CMSExpansionCause::to_string(CMSExpansionCause::Cause cause) {
  8962   switch (cause) {
  8963     case _no_expansion:
  8964       return "No expansion";
  8965     case _satisfy_free_ratio:
  8966       return "Free ratio";
  8967     case _satisfy_promotion:
  8968       return "Satisfy promotion";
  8969     case _satisfy_allocation:
  8970       return "allocation";
  8971     case _allocate_par_lab:
  8972       return "Par LAB";
  8973     case _allocate_par_spooling_space:
  8974       return "Par Spooling Space";
  8975     case _adaptive_size_policy:
  8976       return "Ergonomics";
  8977     default:
  8978       return "unknown";
  8982 void CMSDrainMarkingStackClosure::do_void() {
  8983   // the max number to take from overflow list at a time
  8984   const size_t num = _mark_stack->capacity()/4;
  8985   assert(!_concurrent_precleaning || _collector->overflow_list_is_empty(),
  8986          "Overflow list should be NULL during concurrent phases");
  8987   while (!_mark_stack->isEmpty() ||
  8988          // if stack is empty, check the overflow list
  8989          _collector->take_from_overflow_list(num, _mark_stack)) {
  8990     oop obj = _mark_stack->pop();
  8991     HeapWord* addr = (HeapWord*)obj;
  8992     assert(_span.contains(addr), "Should be within span");
  8993     assert(_bit_map->isMarked(addr), "Should be marked");
  8994     assert(obj->is_oop(), "Should be an oop");
  8995     obj->oop_iterate(_keep_alive);
  8999 void CMSParDrainMarkingStackClosure::do_void() {
  9000   // drain queue
  9001   trim_queue(0);
  9004 // Trim our work_queue so its length is below max at return
  9005 void CMSParDrainMarkingStackClosure::trim_queue(uint max) {
  9006   while (_work_queue->size() > max) {
  9007     oop new_oop;
  9008     if (_work_queue->pop_local(new_oop)) {
  9009       assert(new_oop->is_oop(), "Expected an oop");
  9010       assert(_bit_map->isMarked((HeapWord*)new_oop),
  9011              "no white objects on this stack!");
  9012       assert(_span.contains((HeapWord*)new_oop), "Out of bounds oop");
  9013       // iterate over the oops in this oop, marking and pushing
  9014       // the ones in CMS heap (i.e. in _span).
  9015       new_oop->oop_iterate(&_mark_and_push);
  9020 ////////////////////////////////////////////////////////////////////
  9021 // Support for Marking Stack Overflow list handling and related code
  9022 ////////////////////////////////////////////////////////////////////
  9023 // Much of the following code is similar in shape and spirit to the
  9024 // code used in ParNewGC. We should try and share that code
  9025 // as much as possible in the future.
  9027 #ifndef PRODUCT
  9028 // Debugging support for CMSStackOverflowALot
  9030 // It's OK to call this multi-threaded;  the worst thing
  9031 // that can happen is that we'll get a bunch of closely
  9032 // spaced simulated oveflows, but that's OK, in fact
  9033 // probably good as it would exercise the overflow code
  9034 // under contention.
  9035 bool CMSCollector::simulate_overflow() {
  9036   if (_overflow_counter-- <= 0) { // just being defensive
  9037     _overflow_counter = CMSMarkStackOverflowInterval;
  9038     return true;
  9039   } else {
  9040     return false;
  9044 bool CMSCollector::par_simulate_overflow() {
  9045   return simulate_overflow();
  9047 #endif
  9049 // Single-threaded
  9050 bool CMSCollector::take_from_overflow_list(size_t num, CMSMarkStack* stack) {
  9051   assert(stack->isEmpty(), "Expected precondition");
  9052   assert(stack->capacity() > num, "Shouldn't bite more than can chew");
  9053   size_t i = num;
  9054   oop  cur = _overflow_list;
  9055   const markOop proto = markOopDesc::prototype();
  9056   NOT_PRODUCT(ssize_t n = 0;)
  9057   for (oop next; i > 0 && cur != NULL; cur = next, i--) {
  9058     next = oop(cur->mark());
  9059     cur->set_mark(proto);   // until proven otherwise
  9060     assert(cur->is_oop(), "Should be an oop");
  9061     bool res = stack->push(cur);
  9062     assert(res, "Bit off more than can chew?");
  9063     NOT_PRODUCT(n++;)
  9065   _overflow_list = cur;
  9066 #ifndef PRODUCT
  9067   assert(_num_par_pushes >= n, "Too many pops?");
  9068   _num_par_pushes -=n;
  9069 #endif
  9070   return !stack->isEmpty();
  9073 #define BUSY  (cast_to_oop<intptr_t>(0x1aff1aff))
  9074 // (MT-safe) Get a prefix of at most "num" from the list.
  9075 // The overflow list is chained through the mark word of
  9076 // each object in the list. We fetch the entire list,
  9077 // break off a prefix of the right size and return the
  9078 // remainder. If other threads try to take objects from
  9079 // the overflow list at that time, they will wait for
  9080 // some time to see if data becomes available. If (and
  9081 // only if) another thread places one or more object(s)
  9082 // on the global list before we have returned the suffix
  9083 // to the global list, we will walk down our local list
  9084 // to find its end and append the global list to
  9085 // our suffix before returning it. This suffix walk can
  9086 // prove to be expensive (quadratic in the amount of traffic)
  9087 // when there are many objects in the overflow list and
  9088 // there is much producer-consumer contention on the list.
  9089 // *NOTE*: The overflow list manipulation code here and
  9090 // in ParNewGeneration:: are very similar in shape,
  9091 // except that in the ParNew case we use the old (from/eden)
  9092 // copy of the object to thread the list via its klass word.
  9093 // Because of the common code, if you make any changes in
  9094 // the code below, please check the ParNew version to see if
  9095 // similar changes might be needed.
  9096 // CR 6797058 has been filed to consolidate the common code.
  9097 bool CMSCollector::par_take_from_overflow_list(size_t num,
  9098                                                OopTaskQueue* work_q,
  9099                                                int no_of_gc_threads) {
  9100   assert(work_q->size() == 0, "First empty local work queue");
  9101   assert(num < work_q->max_elems(), "Can't bite more than we can chew");
  9102   if (_overflow_list == NULL) {
  9103     return false;
  9105   // Grab the entire list; we'll put back a suffix
  9106   oop prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list));
  9107   Thread* tid = Thread::current();
  9108   // Before "no_of_gc_threads" was introduced CMSOverflowSpinCount was
  9109   // set to ParallelGCThreads.
  9110   size_t CMSOverflowSpinCount = (size_t) no_of_gc_threads; // was ParallelGCThreads;
  9111   size_t sleep_time_millis = MAX2((size_t)1, num/100);
  9112   // If the list is busy, we spin for a short while,
  9113   // sleeping between attempts to get the list.
  9114   for (size_t spin = 0; prefix == BUSY && spin < CMSOverflowSpinCount; spin++) {
  9115     os::sleep(tid, sleep_time_millis, false);
  9116     if (_overflow_list == NULL) {
  9117       // Nothing left to take
  9118       return false;
  9119     } else if (_overflow_list != BUSY) {
  9120       // Try and grab the prefix
  9121       prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list));
  9124   // If the list was found to be empty, or we spun long
  9125   // enough, we give up and return empty-handed. If we leave
  9126   // the list in the BUSY state below, it must be the case that
  9127   // some other thread holds the overflow list and will set it
  9128   // to a non-BUSY state in the future.
  9129   if (prefix == NULL || prefix == BUSY) {
  9130      // Nothing to take or waited long enough
  9131      if (prefix == NULL) {
  9132        // Write back the NULL in case we overwrote it with BUSY above
  9133        // and it is still the same value.
  9134        (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY);
  9136      return false;
  9138   assert(prefix != NULL && prefix != BUSY, "Error");
  9139   size_t i = num;
  9140   oop cur = prefix;
  9141   // Walk down the first "num" objects, unless we reach the end.
  9142   for (; i > 1 && cur->mark() != NULL; cur = oop(cur->mark()), i--);
  9143   if (cur->mark() == NULL) {
  9144     // We have "num" or fewer elements in the list, so there
  9145     // is nothing to return to the global list.
  9146     // Write back the NULL in lieu of the BUSY we wrote
  9147     // above, if it is still the same value.
  9148     if (_overflow_list == BUSY) {
  9149       (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY);
  9151   } else {
  9152     // Chop off the suffix and rerturn it to the global list.
  9153     assert(cur->mark() != BUSY, "Error");
  9154     oop suffix_head = cur->mark(); // suffix will be put back on global list
  9155     cur->set_mark(NULL);           // break off suffix
  9156     // It's possible that the list is still in the empty(busy) state
  9157     // we left it in a short while ago; in that case we may be
  9158     // able to place back the suffix without incurring the cost
  9159     // of a walk down the list.
  9160     oop observed_overflow_list = _overflow_list;
  9161     oop cur_overflow_list = observed_overflow_list;
  9162     bool attached = false;
  9163     while (observed_overflow_list == BUSY || observed_overflow_list == NULL) {
  9164       observed_overflow_list =
  9165         (oop) Atomic::cmpxchg_ptr(suffix_head, &_overflow_list, cur_overflow_list);
  9166       if (cur_overflow_list == observed_overflow_list) {
  9167         attached = true;
  9168         break;
  9169       } else cur_overflow_list = observed_overflow_list;
  9171     if (!attached) {
  9172       // Too bad, someone else sneaked in (at least) an element; we'll need
  9173       // to do a splice. Find tail of suffix so we can prepend suffix to global
  9174       // list.
  9175       for (cur = suffix_head; cur->mark() != NULL; cur = (oop)(cur->mark()));
  9176       oop suffix_tail = cur;
  9177       assert(suffix_tail != NULL && suffix_tail->mark() == NULL,
  9178              "Tautology");
  9179       observed_overflow_list = _overflow_list;
  9180       do {
  9181         cur_overflow_list = observed_overflow_list;
  9182         if (cur_overflow_list != BUSY) {
  9183           // Do the splice ...
  9184           suffix_tail->set_mark(markOop(cur_overflow_list));
  9185         } else { // cur_overflow_list == BUSY
  9186           suffix_tail->set_mark(NULL);
  9188         // ... and try to place spliced list back on overflow_list ...
  9189         observed_overflow_list =
  9190           (oop) Atomic::cmpxchg_ptr(suffix_head, &_overflow_list, cur_overflow_list);
  9191       } while (cur_overflow_list != observed_overflow_list);
  9192       // ... until we have succeeded in doing so.
  9196   // Push the prefix elements on work_q
  9197   assert(prefix != NULL, "control point invariant");
  9198   const markOop proto = markOopDesc::prototype();
  9199   oop next;
  9200   NOT_PRODUCT(ssize_t n = 0;)
  9201   for (cur = prefix; cur != NULL; cur = next) {
  9202     next = oop(cur->mark());
  9203     cur->set_mark(proto);   // until proven otherwise
  9204     assert(cur->is_oop(), "Should be an oop");
  9205     bool res = work_q->push(cur);
  9206     assert(res, "Bit off more than we can chew?");
  9207     NOT_PRODUCT(n++;)
  9209 #ifndef PRODUCT
  9210   assert(_num_par_pushes >= n, "Too many pops?");
  9211   Atomic::add_ptr(-(intptr_t)n, &_num_par_pushes);
  9212 #endif
  9213   return true;
  9216 // Single-threaded
  9217 void CMSCollector::push_on_overflow_list(oop p) {
  9218   NOT_PRODUCT(_num_par_pushes++;)
  9219   assert(p->is_oop(), "Not an oop");
  9220   preserve_mark_if_necessary(p);
  9221   p->set_mark((markOop)_overflow_list);
  9222   _overflow_list = p;
  9225 // Multi-threaded; use CAS to prepend to overflow list
  9226 void CMSCollector::par_push_on_overflow_list(oop p) {
  9227   NOT_PRODUCT(Atomic::inc_ptr(&_num_par_pushes);)
  9228   assert(p->is_oop(), "Not an oop");
  9229   par_preserve_mark_if_necessary(p);
  9230   oop observed_overflow_list = _overflow_list;
  9231   oop cur_overflow_list;
  9232   do {
  9233     cur_overflow_list = observed_overflow_list;
  9234     if (cur_overflow_list != BUSY) {
  9235       p->set_mark(markOop(cur_overflow_list));
  9236     } else {
  9237       p->set_mark(NULL);
  9239     observed_overflow_list =
  9240       (oop) Atomic::cmpxchg_ptr(p, &_overflow_list, cur_overflow_list);
  9241   } while (cur_overflow_list != observed_overflow_list);
  9243 #undef BUSY
  9245 // Single threaded
  9246 // General Note on GrowableArray: pushes may silently fail
  9247 // because we are (temporarily) out of C-heap for expanding
  9248 // the stack. The problem is quite ubiquitous and affects
  9249 // a lot of code in the JVM. The prudent thing for GrowableArray
  9250 // to do (for now) is to exit with an error. However, that may
  9251 // be too draconian in some cases because the caller may be
  9252 // able to recover without much harm. For such cases, we
  9253 // should probably introduce a "soft_push" method which returns
  9254 // an indication of success or failure with the assumption that
  9255 // the caller may be able to recover from a failure; code in
  9256 // the VM can then be changed, incrementally, to deal with such
  9257 // failures where possible, thus, incrementally hardening the VM
  9258 // in such low resource situations.
  9259 void CMSCollector::preserve_mark_work(oop p, markOop m) {
  9260   _preserved_oop_stack.push(p);
  9261   _preserved_mark_stack.push(m);
  9262   assert(m == p->mark(), "Mark word changed");
  9263   assert(_preserved_oop_stack.size() == _preserved_mark_stack.size(),
  9264          "bijection");
  9267 // Single threaded
  9268 void CMSCollector::preserve_mark_if_necessary(oop p) {
  9269   markOop m = p->mark();
  9270   if (m->must_be_preserved(p)) {
  9271     preserve_mark_work(p, m);
  9275 void CMSCollector::par_preserve_mark_if_necessary(oop p) {
  9276   markOop m = p->mark();
  9277   if (m->must_be_preserved(p)) {
  9278     MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
  9279     // Even though we read the mark word without holding
  9280     // the lock, we are assured that it will not change
  9281     // because we "own" this oop, so no other thread can
  9282     // be trying to push it on the overflow list; see
  9283     // the assertion in preserve_mark_work() that checks
  9284     // that m == p->mark().
  9285     preserve_mark_work(p, m);
  9289 // We should be able to do this multi-threaded,
  9290 // a chunk of stack being a task (this is
  9291 // correct because each oop only ever appears
  9292 // once in the overflow list. However, it's
  9293 // not very easy to completely overlap this with
  9294 // other operations, so will generally not be done
  9295 // until all work's been completed. Because we
  9296 // expect the preserved oop stack (set) to be small,
  9297 // it's probably fine to do this single-threaded.
  9298 // We can explore cleverer concurrent/overlapped/parallel
  9299 // processing of preserved marks if we feel the
  9300 // need for this in the future. Stack overflow should
  9301 // be so rare in practice and, when it happens, its
  9302 // effect on performance so great that this will
  9303 // likely just be in the noise anyway.
  9304 void CMSCollector::restore_preserved_marks_if_any() {
  9305   assert(SafepointSynchronize::is_at_safepoint(),
  9306          "world should be stopped");
  9307   assert(Thread::current()->is_ConcurrentGC_thread() ||
  9308          Thread::current()->is_VM_thread(),
  9309          "should be single-threaded");
  9310   assert(_preserved_oop_stack.size() == _preserved_mark_stack.size(),
  9311          "bijection");
  9313   while (!_preserved_oop_stack.is_empty()) {
  9314     oop p = _preserved_oop_stack.pop();
  9315     assert(p->is_oop(), "Should be an oop");
  9316     assert(_span.contains(p), "oop should be in _span");
  9317     assert(p->mark() == markOopDesc::prototype(),
  9318            "Set when taken from overflow list");
  9319     markOop m = _preserved_mark_stack.pop();
  9320     p->set_mark(m);
  9322   assert(_preserved_mark_stack.is_empty() && _preserved_oop_stack.is_empty(),
  9323          "stacks were cleared above");
  9326 #ifndef PRODUCT
  9327 bool CMSCollector::no_preserved_marks() const {
  9328   return _preserved_mark_stack.is_empty() && _preserved_oop_stack.is_empty();
  9330 #endif
  9332 CMSAdaptiveSizePolicy* ASConcurrentMarkSweepGeneration::cms_size_policy() const
  9334   GenCollectedHeap* gch = (GenCollectedHeap*) GenCollectedHeap::heap();
  9335   CMSAdaptiveSizePolicy* size_policy =
  9336     (CMSAdaptiveSizePolicy*) gch->gen_policy()->size_policy();
  9337   assert(size_policy->is_gc_cms_adaptive_size_policy(),
  9338     "Wrong type for size policy");
  9339   return size_policy;
  9342 void ASConcurrentMarkSweepGeneration::resize(size_t cur_promo_size,
  9343                                            size_t desired_promo_size) {
  9344   if (cur_promo_size < desired_promo_size) {
  9345     size_t expand_bytes = desired_promo_size - cur_promo_size;
  9346     if (PrintAdaptiveSizePolicy && Verbose) {
  9347       gclog_or_tty->print_cr(" ASConcurrentMarkSweepGeneration::resize "
  9348         "Expanding tenured generation by " SIZE_FORMAT " (bytes)",
  9349         expand_bytes);
  9351     expand(expand_bytes,
  9352            MinHeapDeltaBytes,
  9353            CMSExpansionCause::_adaptive_size_policy);
  9354   } else if (desired_promo_size < cur_promo_size) {
  9355     size_t shrink_bytes = cur_promo_size - desired_promo_size;
  9356     if (PrintAdaptiveSizePolicy && Verbose) {
  9357       gclog_or_tty->print_cr(" ASConcurrentMarkSweepGeneration::resize "
  9358         "Shrinking tenured generation by " SIZE_FORMAT " (bytes)",
  9359         shrink_bytes);
  9361     shrink(shrink_bytes);
  9365 CMSGCAdaptivePolicyCounters* ASConcurrentMarkSweepGeneration::gc_adaptive_policy_counters() {
  9366   GenCollectedHeap* gch = GenCollectedHeap::heap();
  9367   CMSGCAdaptivePolicyCounters* counters =
  9368     (CMSGCAdaptivePolicyCounters*) gch->collector_policy()->counters();
  9369   assert(counters->kind() == GCPolicyCounters::CMSGCAdaptivePolicyCountersKind,
  9370     "Wrong kind of counters");
  9371   return counters;
  9375 void ASConcurrentMarkSweepGeneration::update_counters() {
  9376   if (UsePerfData) {
  9377     _space_counters->update_all();
  9378     _gen_counters->update_all();
  9379     CMSGCAdaptivePolicyCounters* counters = gc_adaptive_policy_counters();
  9380     GenCollectedHeap* gch = GenCollectedHeap::heap();
  9381     CMSGCStats* gc_stats_l = (CMSGCStats*) gc_stats();
  9382     assert(gc_stats_l->kind() == GCStats::CMSGCStatsKind,
  9383       "Wrong gc statistics type");
  9384     counters->update_counters(gc_stats_l);
  9388 void ASConcurrentMarkSweepGeneration::update_counters(size_t used) {
  9389   if (UsePerfData) {
  9390     _space_counters->update_used(used);
  9391     _space_counters->update_capacity();
  9392     _gen_counters->update_all();
  9394     CMSGCAdaptivePolicyCounters* counters = gc_adaptive_policy_counters();
  9395     GenCollectedHeap* gch = GenCollectedHeap::heap();
  9396     CMSGCStats* gc_stats_l = (CMSGCStats*) gc_stats();
  9397     assert(gc_stats_l->kind() == GCStats::CMSGCStatsKind,
  9398       "Wrong gc statistics type");
  9399     counters->update_counters(gc_stats_l);
  9403 void ASConcurrentMarkSweepGeneration::shrink_by(size_t desired_bytes) {
  9404   assert_locked_or_safepoint(Heap_lock);
  9405   assert_lock_strong(freelistLock());
  9406   HeapWord* old_end = _cmsSpace->end();
  9407   HeapWord* unallocated_start = _cmsSpace->unallocated_block();
  9408   assert(old_end >= unallocated_start, "Miscalculation of unallocated_start");
  9409   FreeChunk* chunk_at_end = find_chunk_at_end();
  9410   if (chunk_at_end == NULL) {
  9411     // No room to shrink
  9412     if (PrintGCDetails && Verbose) {
  9413       gclog_or_tty->print_cr("No room to shrink: old_end  "
  9414         PTR_FORMAT "  unallocated_start  " PTR_FORMAT
  9415         " chunk_at_end  " PTR_FORMAT,
  9416         old_end, unallocated_start, chunk_at_end);
  9418     return;
  9419   } else {
  9421     // Find the chunk at the end of the space and determine
  9422     // how much it can be shrunk.
  9423     size_t shrinkable_size_in_bytes = chunk_at_end->size();
  9424     size_t aligned_shrinkable_size_in_bytes =
  9425       align_size_down(shrinkable_size_in_bytes, os::vm_page_size());
  9426     assert(unallocated_start <= (HeapWord*) chunk_at_end->end(),
  9427       "Inconsistent chunk at end of space");
  9428     size_t bytes = MIN2(desired_bytes, aligned_shrinkable_size_in_bytes);
  9429     size_t word_size_before = heap_word_size(_virtual_space.committed_size());
  9431     // Shrink the underlying space
  9432     _virtual_space.shrink_by(bytes);
  9433     if (PrintGCDetails && Verbose) {
  9434       gclog_or_tty->print_cr("ConcurrentMarkSweepGeneration::shrink_by:"
  9435         " desired_bytes " SIZE_FORMAT
  9436         " shrinkable_size_in_bytes " SIZE_FORMAT
  9437         " aligned_shrinkable_size_in_bytes " SIZE_FORMAT
  9438         "  bytes  " SIZE_FORMAT,
  9439         desired_bytes, shrinkable_size_in_bytes,
  9440         aligned_shrinkable_size_in_bytes, bytes);
  9441       gclog_or_tty->print_cr("          old_end  " SIZE_FORMAT
  9442         "  unallocated_start  " SIZE_FORMAT,
  9443         old_end, unallocated_start);
  9446     // If the space did shrink (shrinking is not guaranteed),
  9447     // shrink the chunk at the end by the appropriate amount.
  9448     if (((HeapWord*)_virtual_space.high()) < old_end) {
  9449       size_t new_word_size =
  9450         heap_word_size(_virtual_space.committed_size());
  9452       // Have to remove the chunk from the dictionary because it is changing
  9453       // size and might be someplace elsewhere in the dictionary.
  9455       // Get the chunk at end, shrink it, and put it
  9456       // back.
  9457       _cmsSpace->removeChunkFromDictionary(chunk_at_end);
  9458       size_t word_size_change = word_size_before - new_word_size;
  9459       size_t chunk_at_end_old_size = chunk_at_end->size();
  9460       assert(chunk_at_end_old_size >= word_size_change,
  9461         "Shrink is too large");
  9462       chunk_at_end->set_size(chunk_at_end_old_size -
  9463                           word_size_change);
  9464       _cmsSpace->freed((HeapWord*) chunk_at_end->end(),
  9465         word_size_change);
  9467       _cmsSpace->returnChunkToDictionary(chunk_at_end);
  9469       MemRegion mr(_cmsSpace->bottom(), new_word_size);
  9470       _bts->resize(new_word_size);  // resize the block offset shared array
  9471       Universe::heap()->barrier_set()->resize_covered_region(mr);
  9472       _cmsSpace->assert_locked();
  9473       _cmsSpace->set_end((HeapWord*)_virtual_space.high());
  9475       NOT_PRODUCT(_cmsSpace->dictionary()->verify());
  9477       // update the space and generation capacity counters
  9478       if (UsePerfData) {
  9479         _space_counters->update_capacity();
  9480         _gen_counters->update_all();
  9483       if (Verbose && PrintGCDetails) {
  9484         size_t new_mem_size = _virtual_space.committed_size();
  9485         size_t old_mem_size = new_mem_size + bytes;
  9486         gclog_or_tty->print_cr("Shrinking %s from " SIZE_FORMAT "K by " SIZE_FORMAT "K to " SIZE_FORMAT "K",
  9487                       name(), old_mem_size/K, bytes/K, new_mem_size/K);
  9491     assert(_cmsSpace->unallocated_block() <= _cmsSpace->end(),
  9492       "Inconsistency at end of space");
  9493     assert(chunk_at_end->end() == (uintptr_t*) _cmsSpace->end(),
  9494       "Shrinking is inconsistent");
  9495     return;
  9498 // Transfer some number of overflown objects to usual marking
  9499 // stack. Return true if some objects were transferred.
  9500 bool MarkRefsIntoAndScanClosure::take_from_overflow_list() {
  9501   size_t num = MIN2((size_t)(_mark_stack->capacity() - _mark_stack->length())/4,
  9502                     (size_t)ParGCDesiredObjsFromOverflowList);
  9504   bool res = _collector->take_from_overflow_list(num, _mark_stack);
  9505   assert(_collector->overflow_list_is_empty() || res,
  9506          "If list is not empty, we should have taken something");
  9507   assert(!res || !_mark_stack->isEmpty(),
  9508          "If we took something, it should now be on our stack");
  9509   return res;
  9512 size_t MarkDeadObjectsClosure::do_blk(HeapWord* addr) {
  9513   size_t res = _sp->block_size_no_stall(addr, _collector);
  9514   if (_sp->block_is_obj(addr)) {
  9515     if (_live_bit_map->isMarked(addr)) {
  9516       // It can't have been dead in a previous cycle
  9517       guarantee(!_dead_bit_map->isMarked(addr), "No resurrection!");
  9518     } else {
  9519       _dead_bit_map->mark(addr);      // mark the dead object
  9522   // Could be 0, if the block size could not be computed without stalling.
  9523   return res;
  9526 TraceCMSMemoryManagerStats::TraceCMSMemoryManagerStats(CMSCollector::CollectorState phase, GCCause::Cause cause): TraceMemoryManagerStats() {
  9528   switch (phase) {
  9529     case CMSCollector::InitialMarking:
  9530       initialize(true  /* fullGC */ ,
  9531                  cause /* cause of the GC */,
  9532                  true  /* recordGCBeginTime */,
  9533                  true  /* recordPreGCUsage */,
  9534                  false /* recordPeakUsage */,
  9535                  false /* recordPostGCusage */,
  9536                  true  /* recordAccumulatedGCTime */,
  9537                  false /* recordGCEndTime */,
  9538                  false /* countCollection */  );
  9539       break;
  9541     case CMSCollector::FinalMarking:
  9542       initialize(true  /* fullGC */ ,
  9543                  cause /* cause of the GC */,
  9544                  false /* recordGCBeginTime */,
  9545                  false /* recordPreGCUsage */,
  9546                  false /* recordPeakUsage */,
  9547                  false /* recordPostGCusage */,
  9548                  true  /* recordAccumulatedGCTime */,
  9549                  false /* recordGCEndTime */,
  9550                  false /* countCollection */  );
  9551       break;
  9553     case CMSCollector::Sweeping:
  9554       initialize(true  /* fullGC */ ,
  9555                  cause /* cause of the GC */,
  9556                  false /* recordGCBeginTime */,
  9557                  false /* recordPreGCUsage */,
  9558                  true  /* recordPeakUsage */,
  9559                  true  /* recordPostGCusage */,
  9560                  false /* recordAccumulatedGCTime */,
  9561                  true  /* recordGCEndTime */,
  9562                  true  /* countCollection */  );
  9563       break;
  9565     default:
  9566       ShouldNotReachHere();

mercurial