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