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