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