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