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