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