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