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