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/symbolTable.hpp"
  29 #include "classfile/systemDictionary.hpp"
  30 #include "code/codeCache.hpp"
  31 #include "gc/cms/cmsCollectorPolicy.hpp"
  32 #include "gc/cms/cmsOopClosures.inline.hpp"
  33 #include "gc/cms/compactibleFreeListSpace.hpp"
  34 #include "gc/cms/concurrentMarkSweepGeneration.inline.hpp"
  35 #include "gc/cms/concurrentMarkSweepThread.hpp"
  36 #include "gc/cms/parNewGeneration.hpp"
  37 #include "gc/cms/vmCMSOperations.hpp"
  38 #include "gc/serial/genMarkSweep.hpp"
  39 #include "gc/serial/tenuredGeneration.hpp"
  40 #include "gc/shared/adaptiveSizePolicy.hpp"
  41 #include "gc/shared/cardGeneration.inline.hpp"
  42 #include "gc/shared/cardTableRS.hpp"
  43 #include "gc/shared/collectedHeap.inline.hpp"
  44 #include "gc/shared/collectorCounters.hpp"
  45 #include "gc/shared/collectorPolicy.hpp"
  46 #include "gc/shared/gcLocker.inline.hpp"
  47 #include "gc/shared/gcPolicyCounters.hpp"
  48 #include "gc/shared/gcTimer.hpp"
  49 #include "gc/shared/gcTrace.hpp"
  50 #include "gc/shared/gcTraceTime.hpp"
  51 #include "gc/shared/genCollectedHeap.hpp"
  52 #include "gc/shared/genOopClosures.inline.hpp"
  53 #include "gc/shared/isGCActiveMark.hpp"
  54 #include "gc/shared/referencePolicy.hpp"
  55 #include "gc/shared/strongRootsScope.hpp"
  56 #include "gc/shared/taskqueue.inline.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 t("CMS:MSC ", PrintGCDetails && Verbose, true, NULL);
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   if (PrintGC && Verbose) {
1968     _cmsGen->print_heap_change(prev_used);
1969   }
1970 }
1971 
1972 void CMSCollector::register_gc_start(GCCause::Cause cause) {
1973   _cms_start_registered = true;
1974   _gc_timer_cm->register_gc_start();
1975   _gc_tracer_cm->report_gc_start(cause, _gc_timer_cm->gc_start());
1976 }
1977 
1978 void CMSCollector::register_gc_end() {
1979   if (_cms_start_registered) {
1980     report_heap_summary(GCWhen::AfterGC);
1981 
1982     _gc_timer_cm->register_gc_end();
1983     _gc_tracer_cm->report_gc_end(_gc_timer_cm->gc_end(), _gc_timer_cm->time_partitions());
1984     _cms_start_registered = false;
1985   }
1986 }
1987 
1988 void CMSCollector::save_heap_summary() {
1989   GenCollectedHeap* gch = GenCollectedHeap::heap();
1990   _last_heap_summary = gch->create_heap_summary();
1991   _last_metaspace_summary = gch->create_metaspace_summary();
1992 }
1993 
1994 void CMSCollector::report_heap_summary(GCWhen::Type when) {
1995   _gc_tracer_cm->report_gc_heap_summary(when, _last_heap_summary);
1996   _gc_tracer_cm->report_metaspace_summary(when, _last_metaspace_summary);
1997 }
1998 
1999 bool CMSCollector::waitForForegroundGC() {
2000   bool res = false;
2001   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
2002          "CMS thread should have CMS token");
2003   // Block the foreground collector until the
2004   // background collectors decides whether to
2005   // yield.
2006   MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
2007   _foregroundGCShouldWait = true;
2008   if (_foregroundGCIsActive) {
2009     // The background collector yields to the
2010     // foreground collector and returns a value
2011     // indicating that it has yielded.  The foreground
2012     // collector can proceed.
2013     res = true;
2014     _foregroundGCShouldWait = false;
2015     ConcurrentMarkSweepThread::clear_CMS_flag(
2016       ConcurrentMarkSweepThread::CMS_cms_has_token);
2017     ConcurrentMarkSweepThread::set_CMS_flag(
2018       ConcurrentMarkSweepThread::CMS_cms_wants_token);
2019     // Get a possibly blocked foreground thread going
2020     CGC_lock->notify();
2021     if (TraceCMSState) {
2022       gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT " waiting at CMS state %d",
2023         p2i(Thread::current()), _collectorState);
2024     }
2025     while (_foregroundGCIsActive) {
2026       CGC_lock->wait(Mutex::_no_safepoint_check_flag);
2027     }
2028     ConcurrentMarkSweepThread::set_CMS_flag(
2029       ConcurrentMarkSweepThread::CMS_cms_has_token);
2030     ConcurrentMarkSweepThread::clear_CMS_flag(
2031       ConcurrentMarkSweepThread::CMS_cms_wants_token);
2032   }
2033   if (TraceCMSState) {
2034     gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT " continuing at CMS state %d",
2035       p2i(Thread::current()), _collectorState);
2036   }
2037   return res;
2038 }
2039 
2040 // Because of the need to lock the free lists and other structures in
2041 // the collector, common to all the generations that the collector is
2042 // collecting, we need the gc_prologues of individual CMS generations
2043 // delegate to their collector. It may have been simpler had the
2044 // current infrastructure allowed one to call a prologue on a
2045 // collector. In the absence of that we have the generation's
2046 // prologue delegate to the collector, which delegates back
2047 // some "local" work to a worker method in the individual generations
2048 // that it's responsible for collecting, while itself doing any
2049 // work common to all generations it's responsible for. A similar
2050 // comment applies to the  gc_epilogue()'s.
2051 // The role of the variable _between_prologue_and_epilogue is to
2052 // enforce the invocation protocol.
2053 void CMSCollector::gc_prologue(bool full) {
2054   // Call gc_prologue_work() for the CMSGen
2055   // we are responsible for.
2056 
2057   // The following locking discipline assumes that we are only called
2058   // when the world is stopped.
2059   assert(SafepointSynchronize::is_at_safepoint(), "world is stopped assumption");
2060 
2061   // The CMSCollector prologue must call the gc_prologues for the
2062   // "generations" that it's responsible
2063   // for.
2064 
2065   assert(   Thread::current()->is_VM_thread()
2066          || (   CMSScavengeBeforeRemark
2067              && Thread::current()->is_ConcurrentGC_thread()),
2068          "Incorrect thread type for prologue execution");
2069 
2070   if (_between_prologue_and_epilogue) {
2071     // We have already been invoked; this is a gc_prologue delegation
2072     // from yet another CMS generation that we are responsible for, just
2073     // ignore it since all relevant work has already been done.
2074     return;
2075   }
2076 
2077   // set a bit saying prologue has been called; cleared in epilogue
2078   _between_prologue_and_epilogue = true;
2079   // Claim locks for common data structures, then call gc_prologue_work()
2080   // for each CMSGen.
2081 
2082   getFreelistLocks();   // gets free list locks on constituent spaces
2083   bitMapLock()->lock_without_safepoint_check();
2084 
2085   // Should call gc_prologue_work() for all cms gens we are responsible for
2086   bool duringMarking =    _collectorState >= Marking
2087                          && _collectorState < Sweeping;
2088 
2089   // The young collections clear the modified oops state, which tells if
2090   // there are any modified oops in the class. The remark phase also needs
2091   // that information. Tell the young collection to save the union of all
2092   // modified klasses.
2093   if (duringMarking) {
2094     _ct->klass_rem_set()->set_accumulate_modified_oops(true);
2095   }
2096 
2097   bool registerClosure = duringMarking;
2098 
2099   _cmsGen->gc_prologue_work(full, registerClosure, &_modUnionClosurePar);
2100 
2101   if (!full) {
2102     stats().record_gc0_begin();
2103   }
2104 }
2105 
2106 void ConcurrentMarkSweepGeneration::gc_prologue(bool full) {
2107 
2108   _capacity_at_prologue = capacity();
2109   _used_at_prologue = used();
2110 
2111   // Delegate to CMScollector which knows how to coordinate between
2112   // this and any other CMS generations that it is responsible for
2113   // collecting.
2114   collector()->gc_prologue(full);
2115 }
2116 
2117 // This is a "private" interface for use by this generation's CMSCollector.
2118 // Not to be called directly by any other entity (for instance,
2119 // GenCollectedHeap, which calls the "public" gc_prologue method above).
2120 void ConcurrentMarkSweepGeneration::gc_prologue_work(bool full,
2121   bool registerClosure, ModUnionClosure* modUnionClosure) {
2122   assert(!incremental_collection_failed(), "Shouldn't be set yet");
2123   assert(cmsSpace()->preconsumptionDirtyCardClosure() == NULL,
2124     "Should be NULL");
2125   if (registerClosure) {
2126     cmsSpace()->setPreconsumptionDirtyCardClosure(modUnionClosure);
2127   }
2128   cmsSpace()->gc_prologue();
2129   // Clear stat counters
2130   NOT_PRODUCT(
2131     assert(_numObjectsPromoted == 0, "check");
2132     assert(_numWordsPromoted   == 0, "check");
2133     if (Verbose && PrintGC) {
2134       gclog_or_tty->print("Allocated " SIZE_FORMAT " objects, "
2135                           SIZE_FORMAT " bytes concurrently",
2136       _numObjectsAllocated, _numWordsAllocated*sizeof(HeapWord));
2137     }
2138     _numObjectsAllocated = 0;
2139     _numWordsAllocated   = 0;
2140   )
2141 }
2142 
2143 void CMSCollector::gc_epilogue(bool full) {
2144   // The following locking discipline assumes that we are only called
2145   // when the world is stopped.
2146   assert(SafepointSynchronize::is_at_safepoint(),
2147          "world is stopped assumption");
2148 
2149   // Currently the CMS epilogue (see CompactibleFreeListSpace) merely checks
2150   // if linear allocation blocks need to be appropriately marked to allow the
2151   // the blocks to be parsable. We also check here whether we need to nudge the
2152   // CMS collector thread to start a new cycle (if it's not already active).
2153   assert(   Thread::current()->is_VM_thread()
2154          || (   CMSScavengeBeforeRemark
2155              && Thread::current()->is_ConcurrentGC_thread()),
2156          "Incorrect thread type for epilogue execution");
2157 
2158   if (!_between_prologue_and_epilogue) {
2159     // We have already been invoked; this is a gc_epilogue delegation
2160     // from yet another CMS generation that we are responsible for, just
2161     // ignore it since all relevant work has already been done.
2162     return;
2163   }
2164   assert(haveFreelistLocks(), "must have freelist locks");
2165   assert_lock_strong(bitMapLock());
2166 
2167   _ct->klass_rem_set()->set_accumulate_modified_oops(false);
2168 
2169   _cmsGen->gc_epilogue_work(full);
2170 
2171   if (_collectorState == AbortablePreclean || _collectorState == Precleaning) {
2172     // in case sampling was not already enabled, enable it
2173     _start_sampling = true;
2174   }
2175   // reset _eden_chunk_array so sampling starts afresh
2176   _eden_chunk_index = 0;
2177 
2178   size_t cms_used   = _cmsGen->cmsSpace()->used();
2179 
2180   // update performance counters - this uses a special version of
2181   // update_counters() that allows the utilization to be passed as a
2182   // parameter, avoiding multiple calls to used().
2183   //
2184   _cmsGen->update_counters(cms_used);
2185 
2186   bitMapLock()->unlock();
2187   releaseFreelistLocks();
2188 
2189   if (!CleanChunkPoolAsync) {
2190     Chunk::clean_chunk_pool();
2191   }
2192 
2193   set_did_compact(false);
2194   _between_prologue_and_epilogue = false;  // ready for next cycle
2195 }
2196 
2197 void ConcurrentMarkSweepGeneration::gc_epilogue(bool full) {
2198   collector()->gc_epilogue(full);
2199 
2200   // Also reset promotion tracking in par gc thread states.
2201   for (uint i = 0; i < ParallelGCThreads; i++) {
2202     _par_gc_thread_states[i]->promo.stopTrackingPromotions(i);
2203   }
2204 }
2205 
2206 void ConcurrentMarkSweepGeneration::gc_epilogue_work(bool full) {
2207   assert(!incremental_collection_failed(), "Should have been cleared");
2208   cmsSpace()->setPreconsumptionDirtyCardClosure(NULL);
2209   cmsSpace()->gc_epilogue();
2210     // Print stat counters
2211   NOT_PRODUCT(
2212     assert(_numObjectsAllocated == 0, "check");
2213     assert(_numWordsAllocated == 0, "check");
2214     if (Verbose && PrintGC) {
2215       gclog_or_tty->print("Promoted " SIZE_FORMAT " objects, "
2216                           SIZE_FORMAT " bytes",
2217                  _numObjectsPromoted, _numWordsPromoted*sizeof(HeapWord));
2218     }
2219     _numObjectsPromoted = 0;
2220     _numWordsPromoted   = 0;
2221   )
2222 
2223   if (PrintGC && Verbose) {
2224     // Call down the chain in contiguous_available needs the freelistLock
2225     // so print this out before releasing the freeListLock.
2226     gclog_or_tty->print(" Contiguous available " SIZE_FORMAT " bytes ",
2227                         contiguous_available());
2228   }
2229 }
2230 
2231 #ifndef PRODUCT
2232 bool CMSCollector::have_cms_token() {
2233   Thread* thr = Thread::current();
2234   if (thr->is_VM_thread()) {
2235     return ConcurrentMarkSweepThread::vm_thread_has_cms_token();
2236   } else if (thr->is_ConcurrentGC_thread()) {
2237     return ConcurrentMarkSweepThread::cms_thread_has_cms_token();
2238   } else if (thr->is_GC_task_thread()) {
2239     return ConcurrentMarkSweepThread::vm_thread_has_cms_token() &&
2240            ParGCRareEvent_lock->owned_by_self();
2241   }
2242   return false;
2243 }
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   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     tty->print_cr("TransitiveMark: Address " PTR_FORMAT " %s marked", p2i(addr),
2270                   result ? "IS" : "is NOT");
2271     return result;
2272   } else {
2273     tty->print_cr("Could not compute result");
2274     return false;
2275   }
2276 }
2277 #endif
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(bool silent) {
2323   if (!silent) gclog_or_tty->print(" [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   if (!silent) gclog_or_tty->print(" done] ");
2387   return true;
2388 }
2389 
2390 void CMSCollector::verify_after_remark_work_1() {
2391   ResourceMark rm;
2392   HandleMark  hm;
2393   GenCollectedHeap* gch = GenCollectedHeap::heap();
2394 
2395   // Get a clear set of claim bits for the roots processing to work with.
2396   ClassLoaderDataGraph::clear_claimed_marks();
2397 
2398   // Mark from roots one level into CMS
2399   MarkRefsIntoClosure notOlder(_span, verification_mark_bm());
2400   gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
2401 
2402   {
2403     StrongRootsScope srs(1);
2404 
2405     gch->gen_process_roots(&srs,
2406                            GenCollectedHeap::OldGen,
2407                            true,   // young gen as roots
2408                            GenCollectedHeap::ScanningOption(roots_scanning_options()),
2409                            should_unload_classes(),
2410                            &notOlder,
2411                            NULL,
2412                            NULL);
2413   }
2414 
2415   // Now mark from the roots
2416   MarkFromRootsClosure markFromRootsClosure(this, _span,
2417     verification_mark_bm(), verification_mark_stack(),
2418     false /* don't yield */, true /* verifying */);
2419   assert(_restart_addr == NULL, "Expected pre-condition");
2420   verification_mark_bm()->iterate(&markFromRootsClosure);
2421   while (_restart_addr != NULL) {
2422     // Deal with stack overflow: by restarting at the indicated
2423     // address.
2424     HeapWord* ra = _restart_addr;
2425     markFromRootsClosure.reset(ra);
2426     _restart_addr = NULL;
2427     verification_mark_bm()->iterate(&markFromRootsClosure, ra, _span.end());
2428   }
2429   assert(verification_mark_stack()->isEmpty(), "Should have been drained");
2430   verify_work_stacks_empty();
2431 
2432   // Marking completed -- now verify that each bit marked in
2433   // verification_mark_bm() is also marked in markBitMap(); flag all
2434   // errors by printing corresponding objects.
2435   VerifyMarkedClosure vcl(markBitMap());
2436   verification_mark_bm()->iterate(&vcl);
2437   if (vcl.failed()) {
2438     gclog_or_tty->print("Verification failed");
2439     gch->print_on(gclog_or_tty);
2440     fatal("CMS: failed marking verification after remark");
2441   }
2442 }
2443 
2444 class VerifyKlassOopsKlassClosure : public KlassClosure {
2445   class VerifyKlassOopsClosure : public OopClosure {
2446     CMSBitMap* _bitmap;
2447    public:
2448     VerifyKlassOopsClosure(CMSBitMap* bitmap) : _bitmap(bitmap) { }
2449     void do_oop(oop* p)       { guarantee(*p == NULL || _bitmap->isMarked((HeapWord*) *p), "Should be marked"); }
2450     void do_oop(narrowOop* p) { ShouldNotReachHere(); }
2451   } _oop_closure;
2452  public:
2453   VerifyKlassOopsKlassClosure(CMSBitMap* bitmap) : _oop_closure(bitmap) {}
2454   void do_klass(Klass* k) {
2455     k->oops_do(&_oop_closure);
2456   }
2457 };
2458 
2459 void CMSCollector::verify_after_remark_work_2() {
2460   ResourceMark rm;
2461   HandleMark  hm;
2462   GenCollectedHeap* gch = GenCollectedHeap::heap();
2463 
2464   // Get a clear set of claim bits for the roots processing to work with.
2465   ClassLoaderDataGraph::clear_claimed_marks();
2466 
2467   // Mark from roots one level into CMS
2468   MarkRefsIntoVerifyClosure notOlder(_span, verification_mark_bm(),
2469                                      markBitMap());
2470   CLDToOopClosure cld_closure(&notOlder, true);
2471 
2472   gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
2473 
2474   {
2475     StrongRootsScope srs(1);
2476 
2477     gch->gen_process_roots(&srs,
2478                            GenCollectedHeap::OldGen,
2479                            true,   // young gen as roots
2480                            GenCollectedHeap::ScanningOption(roots_scanning_options()),
2481                            should_unload_classes(),
2482                            &notOlder,
2483                            NULL,
2484                            &cld_closure);
2485   }
2486 
2487   // Now mark from the roots
2488   MarkFromRootsVerifyClosure markFromRootsClosure(this, _span,
2489     verification_mark_bm(), markBitMap(), verification_mark_stack());
2490   assert(_restart_addr == NULL, "Expected pre-condition");
2491   verification_mark_bm()->iterate(&markFromRootsClosure);
2492   while (_restart_addr != NULL) {
2493     // Deal with stack overflow: by restarting at the indicated
2494     // address.
2495     HeapWord* ra = _restart_addr;
2496     markFromRootsClosure.reset(ra);
2497     _restart_addr = NULL;
2498     verification_mark_bm()->iterate(&markFromRootsClosure, ra, _span.end());
2499   }
2500   assert(verification_mark_stack()->isEmpty(), "Should have been drained");
2501   verify_work_stacks_empty();
2502 
2503   VerifyKlassOopsKlassClosure verify_klass_oops(verification_mark_bm());
2504   ClassLoaderDataGraph::classes_do(&verify_klass_oops);
2505 
2506   // Marking completed -- now verify that each bit marked in
2507   // verification_mark_bm() is also marked in markBitMap(); flag all
2508   // errors by printing corresponding objects.
2509   VerifyMarkedClosure vcl(markBitMap());
2510   verification_mark_bm()->iterate(&vcl);
2511   assert(!vcl.failed(), "Else verification above should not have succeeded");
2512 }
2513 
2514 void ConcurrentMarkSweepGeneration::save_marks() {
2515   // delegate to CMS space
2516   cmsSpace()->save_marks();
2517   for (uint i = 0; i < ParallelGCThreads; i++) {
2518     _par_gc_thread_states[i]->promo.startTrackingPromotions();
2519   }
2520 }
2521 
2522 bool ConcurrentMarkSweepGeneration::no_allocs_since_save_marks() {
2523   return cmsSpace()->no_allocs_since_save_marks();
2524 }
2525 
2526 #define CMS_SINCE_SAVE_MARKS_DEFN(OopClosureType, nv_suffix)    \
2527                                                                 \
2528 void ConcurrentMarkSweepGeneration::                            \
2529 oop_since_save_marks_iterate##nv_suffix(OopClosureType* cl) {   \
2530   cl->set_generation(this);                                     \
2531   cmsSpace()->oop_since_save_marks_iterate##nv_suffix(cl);      \
2532   cl->reset_generation();                                       \
2533   save_marks();                                                 \
2534 }
2535 
2536 ALL_SINCE_SAVE_MARKS_CLOSURES(CMS_SINCE_SAVE_MARKS_DEFN)
2537 
2538 void
2539 ConcurrentMarkSweepGeneration::oop_iterate(ExtendedOopClosure* cl) {
2540   if (freelistLock()->owned_by_self()) {
2541     Generation::oop_iterate(cl);
2542   } else {
2543     MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
2544     Generation::oop_iterate(cl);
2545   }
2546 }
2547 
2548 void
2549 ConcurrentMarkSweepGeneration::object_iterate(ObjectClosure* cl) {
2550   if (freelistLock()->owned_by_self()) {
2551     Generation::object_iterate(cl);
2552   } else {
2553     MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
2554     Generation::object_iterate(cl);
2555   }
2556 }
2557 
2558 void
2559 ConcurrentMarkSweepGeneration::safe_object_iterate(ObjectClosure* cl) {
2560   if (freelistLock()->owned_by_self()) {
2561     Generation::safe_object_iterate(cl);
2562   } else {
2563     MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
2564     Generation::safe_object_iterate(cl);
2565   }
2566 }
2567 
2568 void
2569 ConcurrentMarkSweepGeneration::post_compact() {
2570 }
2571 
2572 void
2573 ConcurrentMarkSweepGeneration::prepare_for_verify() {
2574   // Fix the linear allocation blocks to look like free blocks.
2575 
2576   // Locks are normally acquired/released in gc_prologue/gc_epilogue, but those
2577   // are not called when the heap is verified during universe initialization and
2578   // at vm shutdown.
2579   if (freelistLock()->owned_by_self()) {
2580     cmsSpace()->prepare_for_verify();
2581   } else {
2582     MutexLockerEx fll(freelistLock(), Mutex::_no_safepoint_check_flag);
2583     cmsSpace()->prepare_for_verify();
2584   }
2585 }
2586 
2587 void
2588 ConcurrentMarkSweepGeneration::verify() {
2589   // Locks are normally acquired/released in gc_prologue/gc_epilogue, but those
2590   // are not called when the heap is verified during universe initialization and
2591   // at vm shutdown.
2592   if (freelistLock()->owned_by_self()) {
2593     cmsSpace()->verify();
2594   } else {
2595     MutexLockerEx fll(freelistLock(), Mutex::_no_safepoint_check_flag);
2596     cmsSpace()->verify();
2597   }
2598 }
2599 
2600 void CMSCollector::verify() {
2601   _cmsGen->verify();
2602 }
2603 
2604 #ifndef PRODUCT
2605 bool CMSCollector::overflow_list_is_empty() const {
2606   assert(_num_par_pushes >= 0, "Inconsistency");
2607   if (_overflow_list == NULL) {
2608     assert(_num_par_pushes == 0, "Inconsistency");
2609   }
2610   return _overflow_list == NULL;
2611 }
2612 
2613 // The methods verify_work_stacks_empty() and verify_overflow_empty()
2614 // merely consolidate assertion checks that appear to occur together frequently.
2615 void CMSCollector::verify_work_stacks_empty() const {
2616   assert(_markStack.isEmpty(), "Marking stack should be empty");
2617   assert(overflow_list_is_empty(), "Overflow list should be empty");
2618 }
2619 
2620 void CMSCollector::verify_overflow_empty() const {
2621   assert(overflow_list_is_empty(), "Overflow list should be empty");
2622   assert(no_preserved_marks(), "No preserved marks");
2623 }
2624 #endif // PRODUCT
2625 
2626 // Decide if we want to enable class unloading as part of the
2627 // ensuing concurrent GC cycle. We will collect and
2628 // unload classes if it's the case that:
2629 // (1) an explicit gc request has been made and the flag
2630 //     ExplicitGCInvokesConcurrentAndUnloadsClasses is set, OR
2631 // (2) (a) class unloading is enabled at the command line, and
2632 //     (b) old gen is getting really full
2633 // NOTE: Provided there is no change in the state of the heap between
2634 // calls to this method, it should have idempotent results. Moreover,
2635 // its results should be monotonically increasing (i.e. going from 0 to 1,
2636 // but not 1 to 0) between successive calls between which the heap was
2637 // not collected. For the implementation below, it must thus rely on
2638 // the property that concurrent_cycles_since_last_unload()
2639 // will not decrease unless a collection cycle happened and that
2640 // _cmsGen->is_too_full() are
2641 // themselves also monotonic in that sense. See check_monotonicity()
2642 // below.
2643 void CMSCollector::update_should_unload_classes() {
2644   _should_unload_classes = false;
2645   // Condition 1 above
2646   if (_full_gc_requested && ExplicitGCInvokesConcurrentAndUnloadsClasses) {
2647     _should_unload_classes = true;
2648   } else if (CMSClassUnloadingEnabled) { // Condition 2.a above
2649     // Disjuncts 2.b.(i,ii,iii) above
2650     _should_unload_classes = (concurrent_cycles_since_last_unload() >=
2651                               CMSClassUnloadingMaxInterval)
2652                            || _cmsGen->is_too_full();
2653   }
2654 }
2655 
2656 bool ConcurrentMarkSweepGeneration::is_too_full() const {
2657   bool res = should_concurrent_collect();
2658   res = res && (occupancy() > (double)CMSIsTooFullPercentage/100.0);
2659   return res;
2660 }
2661 
2662 void CMSCollector::setup_cms_unloading_and_verification_state() {
2663   const  bool should_verify =   VerifyBeforeGC || VerifyAfterGC || VerifyDuringGC
2664                              || VerifyBeforeExit;
2665   const  int  rso           =   GenCollectedHeap::SO_AllCodeCache;
2666 
2667   // We set the proper root for this CMS cycle here.
2668   if (should_unload_classes()) {   // Should unload classes this cycle
2669     remove_root_scanning_option(rso);  // Shrink the root set appropriately
2670     set_verifying(should_verify);    // Set verification state for this cycle
2671     return;                            // Nothing else needs to be done at this time
2672   }
2673 
2674   // Not unloading classes this cycle
2675   assert(!should_unload_classes(), "Inconsistency!");
2676 
2677   // If we are not unloading classes then add SO_AllCodeCache to root
2678   // scanning options.
2679   add_root_scanning_option(rso);
2680 
2681   if ((!verifying() || unloaded_classes_last_cycle()) && should_verify) {
2682     set_verifying(true);
2683   } else if (verifying() && !should_verify) {
2684     // We were verifying, but some verification flags got disabled.
2685     set_verifying(false);
2686     // Exclude symbols, strings and code cache elements from root scanning to
2687     // reduce IM and RM pauses.
2688     remove_root_scanning_option(rso);
2689   }
2690 }
2691 
2692 
2693 #ifndef PRODUCT
2694 HeapWord* CMSCollector::block_start(const void* p) const {
2695   const HeapWord* addr = (HeapWord*)p;
2696   if (_span.contains(p)) {
2697     if (_cmsGen->cmsSpace()->is_in_reserved(addr)) {
2698       return _cmsGen->cmsSpace()->block_start(p);
2699     }
2700   }
2701   return NULL;
2702 }
2703 #endif
2704 
2705 HeapWord*
2706 ConcurrentMarkSweepGeneration::expand_and_allocate(size_t word_size,
2707                                                    bool   tlab,
2708                                                    bool   parallel) {
2709   CMSSynchronousYieldRequest yr;
2710   assert(!tlab, "Can't deal with TLAB allocation");
2711   MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag);
2712   expand_for_gc_cause(word_size*HeapWordSize, MinHeapDeltaBytes, CMSExpansionCause::_satisfy_allocation);
2713   if (GCExpandToAllocateDelayMillis > 0) {
2714     os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
2715   }
2716   return have_lock_and_allocate(word_size, tlab);
2717 }
2718 
2719 void ConcurrentMarkSweepGeneration::expand_for_gc_cause(
2720     size_t bytes,
2721     size_t expand_bytes,
2722     CMSExpansionCause::Cause cause)
2723 {
2724 
2725   bool success = expand(bytes, expand_bytes);
2726 
2727   // remember why we expanded; this information is used
2728   // by shouldConcurrentCollect() when making decisions on whether to start
2729   // a new CMS cycle.
2730   if (success) {
2731     set_expansion_cause(cause);
2732     if (PrintGCDetails && Verbose) {
2733       gclog_or_tty->print_cr("Expanded CMS gen for %s",
2734         CMSExpansionCause::to_string(cause));
2735     }
2736   }
2737 }
2738 
2739 HeapWord* ConcurrentMarkSweepGeneration::expand_and_par_lab_allocate(CMSParGCThreadState* ps, size_t word_sz) {
2740   HeapWord* res = NULL;
2741   MutexLocker x(ParGCRareEvent_lock);
2742   while (true) {
2743     // Expansion by some other thread might make alloc OK now:
2744     res = ps->lab.alloc(word_sz);
2745     if (res != NULL) return res;
2746     // If there's not enough expansion space available, give up.
2747     if (_virtual_space.uncommitted_size() < (word_sz * HeapWordSize)) {
2748       return NULL;
2749     }
2750     // Otherwise, we try expansion.
2751     expand_for_gc_cause(word_sz*HeapWordSize, MinHeapDeltaBytes, CMSExpansionCause::_allocate_par_lab);
2752     // Now go around the loop and try alloc again;
2753     // A competing par_promote might beat us to the expansion space,
2754     // so we may go around the loop again if promotion fails again.
2755     if (GCExpandToAllocateDelayMillis > 0) {
2756       os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
2757     }
2758   }
2759 }
2760 
2761 
2762 bool ConcurrentMarkSweepGeneration::expand_and_ensure_spooling_space(
2763   PromotionInfo* promo) {
2764   MutexLocker x(ParGCRareEvent_lock);
2765   size_t refill_size_bytes = promo->refillSize() * HeapWordSize;
2766   while (true) {
2767     // Expansion by some other thread might make alloc OK now:
2768     if (promo->ensure_spooling_space()) {
2769       assert(promo->has_spooling_space(),
2770              "Post-condition of successful ensure_spooling_space()");
2771       return true;
2772     }
2773     // If there's not enough expansion space available, give up.
2774     if (_virtual_space.uncommitted_size() < refill_size_bytes) {
2775       return false;
2776     }
2777     // Otherwise, we try expansion.
2778     expand_for_gc_cause(refill_size_bytes, MinHeapDeltaBytes, CMSExpansionCause::_allocate_par_spooling_space);
2779     // Now go around the loop and try alloc again;
2780     // A competing allocation might beat us to the expansion space,
2781     // so we may go around the loop again if allocation fails again.
2782     if (GCExpandToAllocateDelayMillis > 0) {
2783       os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false);
2784     }
2785   }
2786 }
2787 
2788 void ConcurrentMarkSweepGeneration::shrink(size_t bytes) {
2789   // Only shrink if a compaction was done so that all the free space
2790   // in the generation is in a contiguous block at the end.
2791   if (did_compact()) {
2792     CardGeneration::shrink(bytes);
2793   }
2794 }
2795 
2796 void ConcurrentMarkSweepGeneration::assert_correct_size_change_locking() {
2797   assert_locked_or_safepoint(Heap_lock);
2798 }
2799 
2800 void ConcurrentMarkSweepGeneration::shrink_free_list_by(size_t bytes) {
2801   assert_locked_or_safepoint(Heap_lock);
2802   assert_lock_strong(freelistLock());
2803   if (PrintGCDetails && Verbose) {
2804     warning("Shrinking of CMS not yet implemented");
2805   }
2806   return;
2807 }
2808 
2809 
2810 // Simple ctor/dtor wrapper for accounting & timer chores around concurrent
2811 // phases.
2812 class CMSPhaseAccounting: public StackObj {
2813  public:
2814   CMSPhaseAccounting(CMSCollector *collector,
2815                      const char *phase,
2816                      bool print_cr = true);
2817   ~CMSPhaseAccounting();
2818 
2819  private:
2820   CMSCollector *_collector;
2821   const char *_phase;
2822   elapsedTimer _wallclock;
2823   bool _print_cr;
2824 
2825  public:
2826   // Not MT-safe; so do not pass around these StackObj's
2827   // where they may be accessed by other threads.
2828   jlong wallclock_millis() {
2829     assert(_wallclock.is_active(), "Wall clock should not stop");
2830     _wallclock.stop();  // to record time
2831     jlong ret = _wallclock.milliseconds();
2832     _wallclock.start(); // restart
2833     return ret;
2834   }
2835 };
2836 
2837 CMSPhaseAccounting::CMSPhaseAccounting(CMSCollector *collector,
2838                                        const char *phase,
2839                                        bool print_cr) :
2840   _collector(collector), _phase(phase), _print_cr(print_cr) {
2841 
2842   if (PrintCMSStatistics != 0) {
2843     _collector->resetYields();
2844   }
2845   if (PrintGCDetails) {
2846     gclog_or_tty->gclog_stamp();
2847     gclog_or_tty->print_cr("[%s-concurrent-%s-start]",
2848       _collector->cmsGen()->short_name(), _phase);
2849   }
2850   _collector->resetTimer();
2851   _wallclock.start();
2852   _collector->startTimer();
2853 }
2854 
2855 CMSPhaseAccounting::~CMSPhaseAccounting() {
2856   assert(_wallclock.is_active(), "Wall clock should not have stopped");
2857   _collector->stopTimer();
2858   _wallclock.stop();
2859   if (PrintGCDetails) {
2860     gclog_or_tty->gclog_stamp();
2861     gclog_or_tty->print("[%s-concurrent-%s: %3.3f/%3.3f secs]",
2862                  _collector->cmsGen()->short_name(),
2863                  _phase, _collector->timerValue(), _wallclock.seconds());
2864     if (_print_cr) {
2865       gclog_or_tty->cr();
2866     }
2867     if (PrintCMSStatistics != 0) {
2868       gclog_or_tty->print_cr(" (CMS-concurrent-%s yielded %d times)", _phase,
2869                     _collector->yields());
2870     }
2871   }
2872 }
2873 
2874 // CMS work
2875 
2876 // The common parts of CMSParInitialMarkTask and CMSParRemarkTask.
2877 class CMSParMarkTask : public AbstractGangTask {
2878  protected:
2879   CMSCollector*     _collector;
2880   uint              _n_workers;
2881   CMSParMarkTask(const char* name, CMSCollector* collector, uint n_workers) :
2882       AbstractGangTask(name),
2883       _collector(collector),
2884       _n_workers(n_workers) {}
2885   // Work method in support of parallel rescan ... of young gen spaces
2886   void do_young_space_rescan(uint worker_id, OopsInGenClosure* cl,
2887                              ContiguousSpace* space,
2888                              HeapWord** chunk_array, size_t chunk_top);
2889   void work_on_young_gen_roots(uint worker_id, OopsInGenClosure* cl);
2890 };
2891 
2892 // Parallel initial mark task
2893 class CMSParInitialMarkTask: public CMSParMarkTask {
2894   StrongRootsScope* _strong_roots_scope;
2895  public:
2896   CMSParInitialMarkTask(CMSCollector* collector, StrongRootsScope* strong_roots_scope, uint n_workers) :
2897       CMSParMarkTask("Scan roots and young gen for initial mark in parallel", collector, n_workers),
2898       _strong_roots_scope(strong_roots_scope) {}
2899   void work(uint worker_id);
2900 };
2901 
2902 // Checkpoint the roots into this generation from outside
2903 // this generation. [Note this initial checkpoint need only
2904 // be approximate -- we'll do a catch up phase subsequently.]
2905 void CMSCollector::checkpointRootsInitial() {
2906   assert(_collectorState == InitialMarking, "Wrong collector state");
2907   check_correct_thread_executing();
2908   TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause());
2909 
2910   save_heap_summary();
2911   report_heap_summary(GCWhen::BeforeGC);
2912 
2913   ReferenceProcessor* rp = ref_processor();
2914   assert(_restart_addr == NULL, "Control point invariant");
2915   {
2916     // acquire locks for subsequent manipulations
2917     MutexLockerEx x(bitMapLock(),
2918                     Mutex::_no_safepoint_check_flag);
2919     checkpointRootsInitialWork();
2920     // enable ("weak") refs discovery
2921     rp->enable_discovery();
2922     _collectorState = Marking;
2923   }
2924 }
2925 
2926 void CMSCollector::checkpointRootsInitialWork() {
2927   assert(SafepointSynchronize::is_at_safepoint(), "world should be stopped");
2928   assert(_collectorState == InitialMarking, "just checking");
2929 
2930   // Already have locks.
2931   assert_lock_strong(bitMapLock());
2932   assert(_markBitMap.isAllClear(), "was reset at end of previous cycle");
2933 
2934   // Setup the verification and class unloading state for this
2935   // CMS collection cycle.
2936   setup_cms_unloading_and_verification_state();
2937 
2938   NOT_PRODUCT(GCTraceTime t("\ncheckpointRootsInitialWork",
2939     PrintGCDetails && Verbose, true, _gc_timer_cm);)
2940 
2941   // Reset all the PLAB chunk arrays if necessary.
2942   if (_survivor_plab_array != NULL && !CMSPLABRecordAlways) {
2943     reset_survivor_plab_arrays();
2944   }
2945 
2946   ResourceMark rm;
2947   HandleMark  hm;
2948 
2949   MarkRefsIntoClosure notOlder(_span, &_markBitMap);
2950   GenCollectedHeap* gch = GenCollectedHeap::heap();
2951 
2952   verify_work_stacks_empty();
2953   verify_overflow_empty();
2954 
2955   gch->ensure_parsability(false);  // fill TLABs, but no need to retire them
2956   // Update the saved marks which may affect the root scans.
2957   gch->save_marks();
2958 
2959   // weak reference processing has not started yet.
2960   ref_processor()->set_enqueuing_is_done(false);
2961 
2962   // Need to remember all newly created CLDs,
2963   // so that we can guarantee that the remark finds them.
2964   ClassLoaderDataGraph::remember_new_clds(true);
2965 
2966   // Whenever a CLD is found, it will be claimed before proceeding to mark
2967   // the klasses. The claimed marks need to be cleared before marking starts.
2968   ClassLoaderDataGraph::clear_claimed_marks();
2969 
2970   if (CMSPrintEdenSurvivorChunks) {
2971     print_eden_and_survivor_chunk_arrays();
2972   }
2973 
2974   {
2975 #if defined(COMPILER2) || INCLUDE_JVMCI
2976     DerivedPointerTableDeactivate dpt_deact;
2977 #endif
2978     if (CMSParallelInitialMarkEnabled) {
2979       // The parallel version.
2980       WorkGang* workers = gch->workers();
2981       assert(workers != NULL, "Need parallel worker threads.");
2982       uint n_workers = workers->active_workers();
2983 
2984       StrongRootsScope srs(n_workers);
2985 
2986       CMSParInitialMarkTask tsk(this, &srs, n_workers);
2987       initialize_sequential_subtasks_for_young_gen_rescan(n_workers);
2988       if (n_workers > 1) {
2989         workers->run_task(&tsk);
2990       } else {
2991         tsk.work(0);
2992       }
2993     } else {
2994       // The serial version.
2995       CLDToOopClosure cld_closure(&notOlder, true);
2996       gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
2997 
2998       StrongRootsScope srs(1);
2999 
3000       gch->gen_process_roots(&srs,
3001                              GenCollectedHeap::OldGen,
3002                              true,   // young gen as roots
3003                              GenCollectedHeap::ScanningOption(roots_scanning_options()),
3004                              should_unload_classes(),
3005                              &notOlder,
3006                              NULL,
3007                              &cld_closure);
3008     }
3009   }
3010 
3011   // Clear mod-union table; it will be dirtied in the prologue of
3012   // CMS generation per each young generation collection.
3013 
3014   assert(_modUnionTable.isAllClear(),
3015        "Was cleared in most recent final checkpoint phase"
3016        " or no bits are set in the gc_prologue before the start of the next "
3017        "subsequent marking phase.");
3018 
3019   assert(_ct->klass_rem_set()->mod_union_is_clear(), "Must be");
3020 
3021   // Save the end of the used_region of the constituent generations
3022   // to be used to limit the extent of sweep in each generation.
3023   save_sweep_limits();
3024   verify_overflow_empty();
3025 }
3026 
3027 bool CMSCollector::markFromRoots() {
3028   // we might be tempted to assert that:
3029   // assert(!SafepointSynchronize::is_at_safepoint(),
3030   //        "inconsistent argument?");
3031   // However that wouldn't be right, because it's possible that
3032   // a safepoint is indeed in progress as a young generation
3033   // stop-the-world GC happens even as we mark in this generation.
3034   assert(_collectorState == Marking, "inconsistent state?");
3035   check_correct_thread_executing();
3036   verify_overflow_empty();
3037 
3038   // Weak ref discovery note: We may be discovering weak
3039   // refs in this generation concurrent (but interleaved) with
3040   // weak ref discovery by the young generation collector.
3041 
3042   CMSTokenSyncWithLocks ts(true, bitMapLock());
3043   TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
3044   CMSPhaseAccounting pa(this, "mark", !PrintGCDetails);
3045   bool res = markFromRootsWork();
3046   if (res) {
3047     _collectorState = Precleaning;
3048   } else { // We failed and a foreground collection wants to take over
3049     assert(_foregroundGCIsActive, "internal state inconsistency");
3050     assert(_restart_addr == NULL,  "foreground will restart from scratch");
3051     if (PrintGCDetails) {
3052       gclog_or_tty->print_cr("bailing out to foreground collection");
3053     }
3054   }
3055   verify_overflow_empty();
3056   return res;
3057 }
3058 
3059 bool CMSCollector::markFromRootsWork() {
3060   // iterate over marked bits in bit map, doing a full scan and mark
3061   // from these roots using the following algorithm:
3062   // . if oop is to the right of the current scan pointer,
3063   //   mark corresponding bit (we'll process it later)
3064   // . else (oop is to left of current scan pointer)
3065   //   push oop on marking stack
3066   // . drain the marking stack
3067 
3068   // Note that when we do a marking step we need to hold the
3069   // bit map lock -- recall that direct allocation (by mutators)
3070   // and promotion (by the young generation collector) is also
3071   // marking the bit map. [the so-called allocate live policy.]
3072   // Because the implementation of bit map marking is not
3073   // robust wrt simultaneous marking of bits in the same word,
3074   // we need to make sure that there is no such interference
3075   // between concurrent such updates.
3076 
3077   // already have locks
3078   assert_lock_strong(bitMapLock());
3079 
3080   verify_work_stacks_empty();
3081   verify_overflow_empty();
3082   bool result = false;
3083   if (CMSConcurrentMTEnabled && ConcGCThreads > 0) {
3084     result = do_marking_mt();
3085   } else {
3086     result = do_marking_st();
3087   }
3088   return result;
3089 }
3090 
3091 // Forward decl
3092 class CMSConcMarkingTask;
3093 
3094 class CMSConcMarkingTerminator: public ParallelTaskTerminator {
3095   CMSCollector*       _collector;
3096   CMSConcMarkingTask* _task;
3097  public:
3098   virtual void yield();
3099 
3100   // "n_threads" is the number of threads to be terminated.
3101   // "queue_set" is a set of work queues of other threads.
3102   // "collector" is the CMS collector associated with this task terminator.
3103   // "yield" indicates whether we need the gang as a whole to yield.
3104   CMSConcMarkingTerminator(int n_threads, TaskQueueSetSuper* queue_set, CMSCollector* collector) :
3105     ParallelTaskTerminator(n_threads, queue_set),
3106     _collector(collector) { }
3107 
3108   void set_task(CMSConcMarkingTask* task) {
3109     _task = task;
3110   }
3111 };
3112 
3113 class CMSConcMarkingTerminatorTerminator: public TerminatorTerminator {
3114   CMSConcMarkingTask* _task;
3115  public:
3116   bool should_exit_termination();
3117   void set_task(CMSConcMarkingTask* task) {
3118     _task = task;
3119   }
3120 };
3121 
3122 // MT Concurrent Marking Task
3123 class CMSConcMarkingTask: public YieldingFlexibleGangTask {
3124   CMSCollector* _collector;
3125   uint          _n_workers;       // requested/desired # workers
3126   bool          _result;
3127   CompactibleFreeListSpace*  _cms_space;
3128   char          _pad_front[64];   // padding to ...
3129   HeapWord*     _global_finger;   // ... avoid sharing cache line
3130   char          _pad_back[64];
3131   HeapWord*     _restart_addr;
3132 
3133   //  Exposed here for yielding support
3134   Mutex* const _bit_map_lock;
3135 
3136   // The per thread work queues, available here for stealing
3137   OopTaskQueueSet*  _task_queues;
3138 
3139   // Termination (and yielding) support
3140   CMSConcMarkingTerminator _term;
3141   CMSConcMarkingTerminatorTerminator _term_term;
3142 
3143  public:
3144   CMSConcMarkingTask(CMSCollector* collector,
3145                  CompactibleFreeListSpace* cms_space,
3146                  YieldingFlexibleWorkGang* workers,
3147                  OopTaskQueueSet* task_queues):
3148     YieldingFlexibleGangTask("Concurrent marking done multi-threaded"),
3149     _collector(collector),
3150     _cms_space(cms_space),
3151     _n_workers(0), _result(true),
3152     _task_queues(task_queues),
3153     _term(_n_workers, task_queues, _collector),
3154     _bit_map_lock(collector->bitMapLock())
3155   {
3156     _requested_size = _n_workers;
3157     _term.set_task(this);
3158     _term_term.set_task(this);
3159     _restart_addr = _global_finger = _cms_space->bottom();
3160   }
3161 
3162 
3163   OopTaskQueueSet* task_queues()  { return _task_queues; }
3164 
3165   OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); }
3166 
3167   HeapWord** global_finger_addr() { return &_global_finger; }
3168 
3169   CMSConcMarkingTerminator* terminator() { return &_term; }
3170 
3171   virtual void set_for_termination(uint active_workers) {
3172     terminator()->reset_for_reuse(active_workers);
3173   }
3174 
3175   void work(uint worker_id);
3176   bool should_yield() {
3177     return    ConcurrentMarkSweepThread::should_yield()
3178            && !_collector->foregroundGCIsActive();
3179   }
3180 
3181   virtual void coordinator_yield();  // stuff done by coordinator
3182   bool result() { return _result; }
3183 
3184   void reset(HeapWord* ra) {
3185     assert(_global_finger >= _cms_space->end(),  "Postcondition of ::work(i)");
3186     _restart_addr = _global_finger = ra;
3187     _term.reset_for_reuse();
3188   }
3189 
3190   static bool get_work_from_overflow_stack(CMSMarkStack* ovflw_stk,
3191                                            OopTaskQueue* work_q);
3192 
3193  private:
3194   void do_scan_and_mark(int i, CompactibleFreeListSpace* sp);
3195   void do_work_steal(int i);
3196   void bump_global_finger(HeapWord* f);
3197 };
3198 
3199 bool CMSConcMarkingTerminatorTerminator::should_exit_termination() {
3200   assert(_task != NULL, "Error");
3201   return _task->yielding();
3202   // Note that we do not need the disjunct || _task->should_yield() above
3203   // because we want terminating threads to yield only if the task
3204   // is already in the midst of yielding, which happens only after at least one
3205   // thread has yielded.
3206 }
3207 
3208 void CMSConcMarkingTerminator::yield() {
3209   if (_task->should_yield()) {
3210     _task->yield();
3211   } else {
3212     ParallelTaskTerminator::yield();
3213   }
3214 }
3215 
3216 ////////////////////////////////////////////////////////////////
3217 // Concurrent Marking Algorithm Sketch
3218 ////////////////////////////////////////////////////////////////
3219 // Until all tasks exhausted (both spaces):
3220 // -- claim next available chunk
3221 // -- bump global finger via CAS
3222 // -- find first object that starts in this chunk
3223 //    and start scanning bitmap from that position
3224 // -- scan marked objects for oops
3225 // -- CAS-mark target, and if successful:
3226 //    . if target oop is above global finger (volatile read)
3227 //      nothing to do
3228 //    . if target oop is in chunk and above local finger
3229 //        then nothing to do
3230 //    . else push on work-queue
3231 // -- Deal with possible overflow issues:
3232 //    . local work-queue overflow causes stuff to be pushed on
3233 //      global (common) overflow queue
3234 //    . always first empty local work queue
3235 //    . then get a batch of oops from global work queue if any
3236 //    . then do work stealing
3237 // -- When all tasks claimed (both spaces)
3238 //    and local work queue empty,
3239 //    then in a loop do:
3240 //    . check global overflow stack; steal a batch of oops and trace
3241 //    . try to steal from other threads oif GOS is empty
3242 //    . if neither is available, offer termination
3243 // -- Terminate and return result
3244 //
3245 void CMSConcMarkingTask::work(uint worker_id) {
3246   elapsedTimer _timer;
3247   ResourceMark rm;
3248   HandleMark hm;
3249 
3250   DEBUG_ONLY(_collector->verify_overflow_empty();)
3251 
3252   // Before we begin work, our work queue should be empty
3253   assert(work_queue(worker_id)->size() == 0, "Expected to be empty");
3254   // Scan the bitmap covering _cms_space, tracing through grey objects.
3255   _timer.start();
3256   do_scan_and_mark(worker_id, _cms_space);
3257   _timer.stop();
3258   if (PrintCMSStatistics != 0) {
3259     gclog_or_tty->print_cr("Finished cms space scanning in %dth thread: %3.3f sec",
3260       worker_id, _timer.seconds());
3261       // XXX: need xxx/xxx type of notation, two timers
3262   }
3263 
3264   // ... do work stealing
3265   _timer.reset();
3266   _timer.start();
3267   do_work_steal(worker_id);
3268   _timer.stop();
3269   if (PrintCMSStatistics != 0) {
3270     gclog_or_tty->print_cr("Finished work stealing in %dth thread: %3.3f sec",
3271       worker_id, _timer.seconds());
3272       // XXX: need xxx/xxx type of notation, two timers
3273   }
3274   assert(_collector->_markStack.isEmpty(), "Should have been emptied");
3275   assert(work_queue(worker_id)->size() == 0, "Should have been emptied");
3276   // Note that under the current task protocol, the
3277   // following assertion is true even of the spaces
3278   // expanded since the completion of the concurrent
3279   // marking. XXX This will likely change under a strict
3280   // ABORT semantics.
3281   // After perm removal the comparison was changed to
3282   // greater than or equal to from strictly greater than.
3283   // Before perm removal the highest address sweep would
3284   // have been at the end of perm gen but now is at the
3285   // end of the tenured gen.
3286   assert(_global_finger >=  _cms_space->end(),
3287          "All tasks have been completed");
3288   DEBUG_ONLY(_collector->verify_overflow_empty();)
3289 }
3290 
3291 void CMSConcMarkingTask::bump_global_finger(HeapWord* f) {
3292   HeapWord* read = _global_finger;
3293   HeapWord* cur  = read;
3294   while (f > read) {
3295     cur = read;
3296     read = (HeapWord*) Atomic::cmpxchg_ptr(f, &_global_finger, cur);
3297     if (cur == read) {
3298       // our cas succeeded
3299       assert(_global_finger >= f, "protocol consistency");
3300       break;
3301     }
3302   }
3303 }
3304 
3305 // This is really inefficient, and should be redone by
3306 // using (not yet available) block-read and -write interfaces to the
3307 // stack and the work_queue. XXX FIX ME !!!
3308 bool CMSConcMarkingTask::get_work_from_overflow_stack(CMSMarkStack* ovflw_stk,
3309                                                       OopTaskQueue* work_q) {
3310   // Fast lock-free check
3311   if (ovflw_stk->length() == 0) {
3312     return false;
3313   }
3314   assert(work_q->size() == 0, "Shouldn't steal");
3315   MutexLockerEx ml(ovflw_stk->par_lock(),
3316                    Mutex::_no_safepoint_check_flag);
3317   // Grab up to 1/4 the size of the work queue
3318   size_t num = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
3319                     (size_t)ParGCDesiredObjsFromOverflowList);
3320   num = MIN2(num, ovflw_stk->length());
3321   for (int i = (int) num; i > 0; i--) {
3322     oop cur = ovflw_stk->pop();
3323     assert(cur != NULL, "Counted wrong?");
3324     work_q->push(cur);
3325   }
3326   return num > 0;
3327 }
3328 
3329 void CMSConcMarkingTask::do_scan_and_mark(int i, CompactibleFreeListSpace* sp) {
3330   SequentialSubTasksDone* pst = sp->conc_par_seq_tasks();
3331   int n_tasks = pst->n_tasks();
3332   // We allow that there may be no tasks to do here because
3333   // we are restarting after a stack overflow.
3334   assert(pst->valid() || n_tasks == 0, "Uninitialized use?");
3335   uint nth_task = 0;
3336 
3337   HeapWord* aligned_start = sp->bottom();
3338   if (sp->used_region().contains(_restart_addr)) {
3339     // Align down to a card boundary for the start of 0th task
3340     // for this space.
3341     aligned_start =
3342       (HeapWord*)align_size_down((uintptr_t)_restart_addr,
3343                                  CardTableModRefBS::card_size);
3344   }
3345 
3346   size_t chunk_size = sp->marking_task_size();
3347   while (!pst->is_task_claimed(/* reference */ nth_task)) {
3348     // Having claimed the nth task in this space,
3349     // compute the chunk that it corresponds to:
3350     MemRegion span = MemRegion(aligned_start + nth_task*chunk_size,
3351                                aligned_start + (nth_task+1)*chunk_size);
3352     // Try and bump the global finger via a CAS;
3353     // note that we need to do the global finger bump
3354     // _before_ taking the intersection below, because
3355     // the task corresponding to that region will be
3356     // deemed done even if the used_region() expands
3357     // because of allocation -- as it almost certainly will
3358     // during start-up while the threads yield in the
3359     // closure below.
3360     HeapWord* finger = span.end();
3361     bump_global_finger(finger);   // atomically
3362     // There are null tasks here corresponding to chunks
3363     // beyond the "top" address of the space.
3364     span = span.intersection(sp->used_region());
3365     if (!span.is_empty()) {  // Non-null task
3366       HeapWord* prev_obj;
3367       assert(!span.contains(_restart_addr) || nth_task == 0,
3368              "Inconsistency");
3369       if (nth_task == 0) {
3370         // For the 0th task, we'll not need to compute a block_start.
3371         if (span.contains(_restart_addr)) {
3372           // In the case of a restart because of stack overflow,
3373           // we might additionally skip a chunk prefix.
3374           prev_obj = _restart_addr;
3375         } else {
3376           prev_obj = span.start();
3377         }
3378       } else {
3379         // We want to skip the first object because
3380         // the protocol is to scan any object in its entirety
3381         // that _starts_ in this span; a fortiori, any
3382         // object starting in an earlier span is scanned
3383         // as part of an earlier claimed task.
3384         // Below we use the "careful" version of block_start
3385         // so we do not try to navigate uninitialized objects.
3386         prev_obj = sp->block_start_careful(span.start());
3387         // Below we use a variant of block_size that uses the
3388         // Printezis bits to avoid waiting for allocated
3389         // objects to become initialized/parsable.
3390         while (prev_obj < span.start()) {
3391           size_t sz = sp->block_size_no_stall(prev_obj, _collector);
3392           if (sz > 0) {
3393             prev_obj += sz;
3394           } else {
3395             // In this case we may end up doing a bit of redundant
3396             // scanning, but that appears unavoidable, short of
3397             // locking the free list locks; see bug 6324141.
3398             break;
3399           }
3400         }
3401       }
3402       if (prev_obj < span.end()) {
3403         MemRegion my_span = MemRegion(prev_obj, span.end());
3404         // Do the marking work within a non-empty span --
3405         // the last argument to the constructor indicates whether the
3406         // iteration should be incremental with periodic yields.
3407         Par_MarkFromRootsClosure cl(this, _collector, my_span,
3408                                     &_collector->_markBitMap,
3409                                     work_queue(i),
3410                                     &_collector->_markStack);
3411         _collector->_markBitMap.iterate(&cl, my_span.start(), my_span.end());
3412       } // else nothing to do for this task
3413     }   // else nothing to do for this task
3414   }
3415   // We'd be tempted to assert here that since there are no
3416   // more tasks left to claim in this space, the global_finger
3417   // must exceed space->top() and a fortiori space->end(). However,
3418   // that would not quite be correct because the bumping of
3419   // global_finger occurs strictly after the claiming of a task,
3420   // so by the time we reach here the global finger may not yet
3421   // have been bumped up by the thread that claimed the last
3422   // task.
3423   pst->all_tasks_completed();
3424 }
3425 
3426 class Par_ConcMarkingClosure: public MetadataAwareOopClosure {
3427  private:
3428   CMSCollector* _collector;
3429   CMSConcMarkingTask* _task;
3430   MemRegion     _span;
3431   CMSBitMap*    _bit_map;
3432   CMSMarkStack* _overflow_stack;
3433   OopTaskQueue* _work_queue;
3434  protected:
3435   DO_OOP_WORK_DEFN
3436  public:
3437   Par_ConcMarkingClosure(CMSCollector* collector, CMSConcMarkingTask* task, OopTaskQueue* work_queue,
3438                          CMSBitMap* bit_map, CMSMarkStack* overflow_stack):
3439     MetadataAwareOopClosure(collector->ref_processor()),
3440     _collector(collector),
3441     _task(task),
3442     _span(collector->_span),
3443     _work_queue(work_queue),
3444     _bit_map(bit_map),
3445     _overflow_stack(overflow_stack)
3446   { }
3447   virtual void do_oop(oop* p);
3448   virtual void do_oop(narrowOop* p);
3449 
3450   void trim_queue(size_t max);
3451   void handle_stack_overflow(HeapWord* lost);
3452   void do_yield_check() {
3453     if (_task->should_yield()) {
3454       _task->yield();
3455     }
3456   }
3457 };
3458 
3459 // Grey object scanning during work stealing phase --
3460 // the salient assumption here is that any references
3461 // that are in these stolen objects being scanned must
3462 // already have been initialized (else they would not have
3463 // been published), so we do not need to check for
3464 // uninitialized objects before pushing here.
3465 void Par_ConcMarkingClosure::do_oop(oop obj) {
3466   assert(obj->is_oop_or_null(true), "Expected an oop or NULL at " PTR_FORMAT, p2i(obj));
3467   HeapWord* addr = (HeapWord*)obj;
3468   // Check if oop points into the CMS generation
3469   // and is not marked
3470   if (_span.contains(addr) && !_bit_map->isMarked(addr)) {
3471     // a white object ...
3472     // If we manage to "claim" the object, by being the
3473     // first thread to mark it, then we push it on our
3474     // marking stack
3475     if (_bit_map->par_mark(addr)) {     // ... now grey
3476       // push on work queue (grey set)
3477       bool simulate_overflow = false;
3478       NOT_PRODUCT(
3479         if (CMSMarkStackOverflowALot &&
3480             _collector->simulate_overflow()) {
3481           // simulate a stack overflow
3482           simulate_overflow = true;
3483         }
3484       )
3485       if (simulate_overflow ||
3486           !(_work_queue->push(obj) || _overflow_stack->par_push(obj))) {
3487         // stack overflow
3488         if (PrintCMSStatistics != 0) {
3489           gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
3490                                  SIZE_FORMAT, _overflow_stack->capacity());
3491         }
3492         // We cannot assert that the overflow stack is full because
3493         // it may have been emptied since.
3494         assert(simulate_overflow ||
3495                _work_queue->size() == _work_queue->max_elems(),
3496               "Else push should have succeeded");
3497         handle_stack_overflow(addr);
3498       }
3499     } // Else, some other thread got there first
3500     do_yield_check();
3501   }
3502 }
3503 
3504 void Par_ConcMarkingClosure::do_oop(oop* p)       { Par_ConcMarkingClosure::do_oop_work(p); }
3505 void Par_ConcMarkingClosure::do_oop(narrowOop* p) { Par_ConcMarkingClosure::do_oop_work(p); }
3506 
3507 void Par_ConcMarkingClosure::trim_queue(size_t max) {
3508   while (_work_queue->size() > max) {
3509     oop new_oop;
3510     if (_work_queue->pop_local(new_oop)) {
3511       assert(new_oop->is_oop(), "Should be an oop");
3512       assert(_bit_map->isMarked((HeapWord*)new_oop), "Grey object");
3513       assert(_span.contains((HeapWord*)new_oop), "Not in span");
3514       new_oop->oop_iterate(this);  // do_oop() above
3515       do_yield_check();
3516     }
3517   }
3518 }
3519 
3520 // Upon stack overflow, we discard (part of) the stack,
3521 // remembering the least address amongst those discarded
3522 // in CMSCollector's _restart_address.
3523 void Par_ConcMarkingClosure::handle_stack_overflow(HeapWord* lost) {
3524   // We need to do this under a mutex to prevent other
3525   // workers from interfering with the work done below.
3526   MutexLockerEx ml(_overflow_stack->par_lock(),
3527                    Mutex::_no_safepoint_check_flag);
3528   // Remember the least grey address discarded
3529   HeapWord* ra = (HeapWord*)_overflow_stack->least_value(lost);
3530   _collector->lower_restart_addr(ra);
3531   _overflow_stack->reset();  // discard stack contents
3532   _overflow_stack->expand(); // expand the stack if possible
3533 }
3534 
3535 
3536 void CMSConcMarkingTask::do_work_steal(int i) {
3537   OopTaskQueue* work_q = work_queue(i);
3538   oop obj_to_scan;
3539   CMSBitMap* bm = &(_collector->_markBitMap);
3540   CMSMarkStack* ovflw = &(_collector->_markStack);
3541   int* seed = _collector->hash_seed(i);
3542   Par_ConcMarkingClosure cl(_collector, this, work_q, bm, ovflw);
3543   while (true) {
3544     cl.trim_queue(0);
3545     assert(work_q->size() == 0, "Should have been emptied above");
3546     if (get_work_from_overflow_stack(ovflw, work_q)) {
3547       // Can't assert below because the work obtained from the
3548       // overflow stack may already have been stolen from us.
3549       // assert(work_q->size() > 0, "Work from overflow stack");
3550       continue;
3551     } else if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) {
3552       assert(obj_to_scan->is_oop(), "Should be an oop");
3553       assert(bm->isMarked((HeapWord*)obj_to_scan), "Grey object");
3554       obj_to_scan->oop_iterate(&cl);
3555     } else if (terminator()->offer_termination(&_term_term)) {
3556       assert(work_q->size() == 0, "Impossible!");
3557       break;
3558     } else if (yielding() || should_yield()) {
3559       yield();
3560     }
3561   }
3562 }
3563 
3564 // This is run by the CMS (coordinator) thread.
3565 void CMSConcMarkingTask::coordinator_yield() {
3566   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
3567          "CMS thread should hold CMS token");
3568   // First give up the locks, then yield, then re-lock
3569   // We should probably use a constructor/destructor idiom to
3570   // do this unlock/lock or modify the MutexUnlocker class to
3571   // serve our purpose. XXX
3572   assert_lock_strong(_bit_map_lock);
3573   _bit_map_lock->unlock();
3574   ConcurrentMarkSweepThread::desynchronize(true);
3575   _collector->stopTimer();
3576   if (PrintCMSStatistics != 0) {
3577     _collector->incrementYields();
3578   }
3579 
3580   // It is possible for whichever thread initiated the yield request
3581   // not to get a chance to wake up and take the bitmap lock between
3582   // this thread releasing it and reacquiring it. So, while the
3583   // should_yield() flag is on, let's sleep for a bit to give the
3584   // other thread a chance to wake up. The limit imposed on the number
3585   // of iterations is defensive, to avoid any unforseen circumstances
3586   // putting us into an infinite loop. Since it's always been this
3587   // (coordinator_yield()) method that was observed to cause the
3588   // problem, we are using a parameter (CMSCoordinatorYieldSleepCount)
3589   // which is by default non-zero. For the other seven methods that
3590   // also perform the yield operation, as are using a different
3591   // parameter (CMSYieldSleepCount) which is by default zero. This way we
3592   // can enable the sleeping for those methods too, if necessary.
3593   // See 6442774.
3594   //
3595   // We really need to reconsider the synchronization between the GC
3596   // thread and the yield-requesting threads in the future and we
3597   // should really use wait/notify, which is the recommended
3598   // way of doing this type of interaction. Additionally, we should
3599   // consolidate the eight methods that do the yield operation and they
3600   // are almost identical into one for better maintainability and
3601   // readability. See 6445193.
3602   //
3603   // Tony 2006.06.29
3604   for (unsigned i = 0; i < CMSCoordinatorYieldSleepCount &&
3605                    ConcurrentMarkSweepThread::should_yield() &&
3606                    !CMSCollector::foregroundGCIsActive(); ++i) {
3607     os::sleep(Thread::current(), 1, false);
3608   }
3609 
3610   ConcurrentMarkSweepThread::synchronize(true);
3611   _bit_map_lock->lock_without_safepoint_check();
3612   _collector->startTimer();
3613 }
3614 
3615 bool CMSCollector::do_marking_mt() {
3616   assert(ConcGCThreads > 0 && conc_workers() != NULL, "precondition");
3617   uint num_workers = AdaptiveSizePolicy::calc_active_conc_workers(conc_workers()->total_workers(),
3618                                                                   conc_workers()->active_workers(),
3619                                                                   Threads::number_of_non_daemon_threads());
3620   conc_workers()->set_active_workers(num_workers);
3621 
3622   CompactibleFreeListSpace* cms_space  = _cmsGen->cmsSpace();
3623 
3624   CMSConcMarkingTask tsk(this,
3625                          cms_space,
3626                          conc_workers(),
3627                          task_queues());
3628 
3629   // Since the actual number of workers we get may be different
3630   // from the number we requested above, do we need to do anything different
3631   // below? In particular, may be we need to subclass the SequantialSubTasksDone
3632   // class?? XXX
3633   cms_space ->initialize_sequential_subtasks_for_marking(num_workers);
3634 
3635   // Refs discovery is already non-atomic.
3636   assert(!ref_processor()->discovery_is_atomic(), "Should be non-atomic");
3637   assert(ref_processor()->discovery_is_mt(), "Discovery should be MT");
3638   conc_workers()->start_task(&tsk);
3639   while (tsk.yielded()) {
3640     tsk.coordinator_yield();
3641     conc_workers()->continue_task(&tsk);
3642   }
3643   // If the task was aborted, _restart_addr will be non-NULL
3644   assert(tsk.completed() || _restart_addr != NULL, "Inconsistency");
3645   while (_restart_addr != NULL) {
3646     // XXX For now we do not make use of ABORTED state and have not
3647     // yet implemented the right abort semantics (even in the original
3648     // single-threaded CMS case). That needs some more investigation
3649     // and is deferred for now; see CR# TBF. 07252005YSR. XXX
3650     assert(!CMSAbortSemantics || tsk.aborted(), "Inconsistency");
3651     // If _restart_addr is non-NULL, a marking stack overflow
3652     // occurred; we need to do a fresh marking iteration from the
3653     // indicated restart address.
3654     if (_foregroundGCIsActive) {
3655       // We may be running into repeated stack overflows, having
3656       // reached the limit of the stack size, while making very
3657       // slow forward progress. It may be best to bail out and
3658       // let the foreground collector do its job.
3659       // Clear _restart_addr, so that foreground GC
3660       // works from scratch. This avoids the headache of
3661       // a "rescan" which would otherwise be needed because
3662       // of the dirty mod union table & card table.
3663       _restart_addr = NULL;
3664       return false;
3665     }
3666     // Adjust the task to restart from _restart_addr
3667     tsk.reset(_restart_addr);
3668     cms_space ->initialize_sequential_subtasks_for_marking(num_workers,
3669                   _restart_addr);
3670     _restart_addr = NULL;
3671     // Get the workers going again
3672     conc_workers()->start_task(&tsk);
3673     while (tsk.yielded()) {
3674       tsk.coordinator_yield();
3675       conc_workers()->continue_task(&tsk);
3676     }
3677   }
3678   assert(tsk.completed(), "Inconsistency");
3679   assert(tsk.result() == true, "Inconsistency");
3680   return true;
3681 }
3682 
3683 bool CMSCollector::do_marking_st() {
3684   ResourceMark rm;
3685   HandleMark   hm;
3686 
3687   // Temporarily make refs discovery single threaded (non-MT)
3688   ReferenceProcessorMTDiscoveryMutator rp_mut_discovery(ref_processor(), false);
3689   MarkFromRootsClosure markFromRootsClosure(this, _span, &_markBitMap,
3690     &_markStack, CMSYield);
3691   // the last argument to iterate indicates whether the iteration
3692   // should be incremental with periodic yields.
3693   _markBitMap.iterate(&markFromRootsClosure);
3694   // If _restart_addr is non-NULL, a marking stack overflow
3695   // occurred; we need to do a fresh iteration from the
3696   // indicated restart address.
3697   while (_restart_addr != NULL) {
3698     if (_foregroundGCIsActive) {
3699       // We may be running into repeated stack overflows, having
3700       // reached the limit of the stack size, while making very
3701       // slow forward progress. It may be best to bail out and
3702       // let the foreground collector do its job.
3703       // Clear _restart_addr, so that foreground GC
3704       // works from scratch. This avoids the headache of
3705       // a "rescan" which would otherwise be needed because
3706       // of the dirty mod union table & card table.
3707       _restart_addr = NULL;
3708       return false;  // indicating failure to complete marking
3709     }
3710     // Deal with stack overflow:
3711     // we restart marking from _restart_addr
3712     HeapWord* ra = _restart_addr;
3713     markFromRootsClosure.reset(ra);
3714     _restart_addr = NULL;
3715     _markBitMap.iterate(&markFromRootsClosure, ra, _span.end());
3716   }
3717   return true;
3718 }
3719 
3720 void CMSCollector::preclean() {
3721   check_correct_thread_executing();
3722   assert(Thread::current()->is_ConcurrentGC_thread(), "Wrong thread");
3723   verify_work_stacks_empty();
3724   verify_overflow_empty();
3725   _abort_preclean = false;
3726   if (CMSPrecleaningEnabled) {
3727     if (!CMSEdenChunksRecordAlways) {
3728       _eden_chunk_index = 0;
3729     }
3730     size_t used = get_eden_used();
3731     size_t capacity = get_eden_capacity();
3732     // Don't start sampling unless we will get sufficiently
3733     // many samples.
3734     if (used < (capacity/(CMSScheduleRemarkSamplingRatio * 100)
3735                 * CMSScheduleRemarkEdenPenetration)) {
3736       _start_sampling = true;
3737     } else {
3738       _start_sampling = false;
3739     }
3740     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
3741     CMSPhaseAccounting pa(this, "preclean", !PrintGCDetails);
3742     preclean_work(CMSPrecleanRefLists1, CMSPrecleanSurvivors1);
3743   }
3744   CMSTokenSync x(true); // is cms thread
3745   if (CMSPrecleaningEnabled) {
3746     sample_eden();
3747     _collectorState = AbortablePreclean;
3748   } else {
3749     _collectorState = FinalMarking;
3750   }
3751   verify_work_stacks_empty();
3752   verify_overflow_empty();
3753 }
3754 
3755 // Try and schedule the remark such that young gen
3756 // occupancy is CMSScheduleRemarkEdenPenetration %.
3757 void CMSCollector::abortable_preclean() {
3758   check_correct_thread_executing();
3759   assert(CMSPrecleaningEnabled,  "Inconsistent control state");
3760   assert(_collectorState == AbortablePreclean, "Inconsistent control state");
3761 
3762   // If Eden's current occupancy is below this threshold,
3763   // immediately schedule the remark; else preclean
3764   // past the next scavenge in an effort to
3765   // schedule the pause as described above. By choosing
3766   // CMSScheduleRemarkEdenSizeThreshold >= max eden size
3767   // we will never do an actual abortable preclean cycle.
3768   if (get_eden_used() > CMSScheduleRemarkEdenSizeThreshold) {
3769     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
3770     CMSPhaseAccounting pa(this, "abortable-preclean", !PrintGCDetails);
3771     // We need more smarts in the abortable preclean
3772     // loop below to deal with cases where allocation
3773     // in young gen is very very slow, and our precleaning
3774     // is running a losing race against a horde of
3775     // mutators intent on flooding us with CMS updates
3776     // (dirty cards).
3777     // One, admittedly dumb, strategy is to give up
3778     // after a certain number of abortable precleaning loops
3779     // or after a certain maximum time. We want to make
3780     // this smarter in the next iteration.
3781     // XXX FIX ME!!! YSR
3782     size_t loops = 0, workdone = 0, cumworkdone = 0, waited = 0;
3783     while (!(should_abort_preclean() ||
3784              ConcurrentMarkSweepThread::should_terminate())) {
3785       workdone = preclean_work(CMSPrecleanRefLists2, CMSPrecleanSurvivors2);
3786       cumworkdone += workdone;
3787       loops++;
3788       // Voluntarily terminate abortable preclean phase if we have
3789       // been at it for too long.
3790       if ((CMSMaxAbortablePrecleanLoops != 0) &&
3791           loops >= CMSMaxAbortablePrecleanLoops) {
3792         if (PrintGCDetails) {
3793           gclog_or_tty->print(" CMS: abort preclean due to loops ");
3794         }
3795         break;
3796       }
3797       if (pa.wallclock_millis() > CMSMaxAbortablePrecleanTime) {
3798         if (PrintGCDetails) {
3799           gclog_or_tty->print(" CMS: abort preclean due to time ");
3800         }
3801         break;
3802       }
3803       // If we are doing little work each iteration, we should
3804       // take a short break.
3805       if (workdone < CMSAbortablePrecleanMinWorkPerIteration) {
3806         // Sleep for some time, waiting for work to accumulate
3807         stopTimer();
3808         cmsThread()->wait_on_cms_lock(CMSAbortablePrecleanWaitMillis);
3809         startTimer();
3810         waited++;
3811       }
3812     }
3813     if (PrintCMSStatistics > 0) {
3814       gclog_or_tty->print(" [" SIZE_FORMAT " iterations, " SIZE_FORMAT " waits, " SIZE_FORMAT " cards)] ",
3815                           loops, waited, cumworkdone);
3816     }
3817   }
3818   CMSTokenSync x(true); // is cms thread
3819   if (_collectorState != Idling) {
3820     assert(_collectorState == AbortablePreclean,
3821            "Spontaneous state transition?");
3822     _collectorState = FinalMarking;
3823   } // Else, a foreground collection completed this CMS cycle.
3824   return;
3825 }
3826 
3827 // Respond to an Eden sampling opportunity
3828 void CMSCollector::sample_eden() {
3829   // Make sure a young gc cannot sneak in between our
3830   // reading and recording of a sample.
3831   assert(Thread::current()->is_ConcurrentGC_thread(),
3832          "Only the cms thread may collect Eden samples");
3833   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
3834          "Should collect samples while holding CMS token");
3835   if (!_start_sampling) {
3836     return;
3837   }
3838   // When CMSEdenChunksRecordAlways is true, the eden chunk array
3839   // is populated by the young generation.
3840   if (_eden_chunk_array != NULL && !CMSEdenChunksRecordAlways) {
3841     if (_eden_chunk_index < _eden_chunk_capacity) {
3842       _eden_chunk_array[_eden_chunk_index] = *_top_addr;   // take sample
3843       assert(_eden_chunk_array[_eden_chunk_index] <= *_end_addr,
3844              "Unexpected state of Eden");
3845       // We'd like to check that what we just sampled is an oop-start address;
3846       // however, we cannot do that here since the object may not yet have been
3847       // initialized. So we'll instead do the check when we _use_ this sample
3848       // later.
3849       if (_eden_chunk_index == 0 ||
3850           (pointer_delta(_eden_chunk_array[_eden_chunk_index],
3851                          _eden_chunk_array[_eden_chunk_index-1])
3852            >= CMSSamplingGrain)) {
3853         _eden_chunk_index++;  // commit sample
3854       }
3855     }
3856   }
3857   if ((_collectorState == AbortablePreclean) && !_abort_preclean) {
3858     size_t used = get_eden_used();
3859     size_t capacity = get_eden_capacity();
3860     assert(used <= capacity, "Unexpected state of Eden");
3861     if (used >  (capacity/100 * CMSScheduleRemarkEdenPenetration)) {
3862       _abort_preclean = true;
3863     }
3864   }
3865 }
3866 
3867 
3868 size_t CMSCollector::preclean_work(bool clean_refs, bool clean_survivor) {
3869   assert(_collectorState == Precleaning ||
3870          _collectorState == AbortablePreclean, "incorrect state");
3871   ResourceMark rm;
3872   HandleMark   hm;
3873 
3874   // Precleaning is currently not MT but the reference processor
3875   // may be set for MT.  Disable it temporarily here.
3876   ReferenceProcessor* rp = ref_processor();
3877   ReferenceProcessorMTDiscoveryMutator rp_mut_discovery(rp, false);
3878 
3879   // Do one pass of scrubbing the discovered reference lists
3880   // to remove any reference objects with strongly-reachable
3881   // referents.
3882   if (clean_refs) {
3883     CMSPrecleanRefsYieldClosure yield_cl(this);
3884     assert(rp->span().equals(_span), "Spans should be equal");
3885     CMSKeepAliveClosure keep_alive(this, _span, &_markBitMap,
3886                                    &_markStack, true /* preclean */);
3887     CMSDrainMarkingStackClosure complete_trace(this,
3888                                    _span, &_markBitMap, &_markStack,
3889                                    &keep_alive, true /* preclean */);
3890 
3891     // We don't want this step to interfere with a young
3892     // collection because we don't want to take CPU
3893     // or memory bandwidth away from the young GC threads
3894     // (which may be as many as there are CPUs).
3895     // Note that we don't need to protect ourselves from
3896     // interference with mutators because they can't
3897     // manipulate the discovered reference lists nor affect
3898     // the computed reachability of the referents, the
3899     // only properties manipulated by the precleaning
3900     // of these reference lists.
3901     stopTimer();
3902     CMSTokenSyncWithLocks x(true /* is cms thread */,
3903                             bitMapLock());
3904     startTimer();
3905     sample_eden();
3906 
3907     // The following will yield to allow foreground
3908     // collection to proceed promptly. XXX YSR:
3909     // The code in this method may need further
3910     // tweaking for better performance and some restructuring
3911     // for cleaner interfaces.
3912     GCTimer *gc_timer = NULL; // Currently not tracing concurrent phases
3913     rp->preclean_discovered_references(
3914           rp->is_alive_non_header(), &keep_alive, &complete_trace, &yield_cl,
3915           gc_timer);
3916   }
3917 
3918   if (clean_survivor) {  // preclean the active survivor space(s)
3919     PushAndMarkClosure pam_cl(this, _span, ref_processor(),
3920                              &_markBitMap, &_modUnionTable,
3921                              &_markStack, true /* precleaning phase */);
3922     stopTimer();
3923     CMSTokenSyncWithLocks ts(true /* is cms thread */,
3924                              bitMapLock());
3925     startTimer();
3926     unsigned int before_count =
3927       GenCollectedHeap::heap()->total_collections();
3928     SurvivorSpacePrecleanClosure
3929       sss_cl(this, _span, &_markBitMap, &_markStack,
3930              &pam_cl, before_count, CMSYield);
3931     _young_gen->from()->object_iterate_careful(&sss_cl);
3932     _young_gen->to()->object_iterate_careful(&sss_cl);
3933   }
3934   MarkRefsIntoAndScanClosure
3935     mrias_cl(_span, ref_processor(), &_markBitMap, &_modUnionTable,
3936              &_markStack, this, CMSYield,
3937              true /* precleaning phase */);
3938   // CAUTION: The following closure has persistent state that may need to
3939   // be reset upon a decrease in the sequence of addresses it
3940   // processes.
3941   ScanMarkedObjectsAgainCarefullyClosure
3942     smoac_cl(this, _span,
3943       &_markBitMap, &_markStack, &mrias_cl, CMSYield);
3944 
3945   // Preclean dirty cards in ModUnionTable and CardTable using
3946   // appropriate convergence criterion;
3947   // repeat CMSPrecleanIter times unless we find that
3948   // we are losing.
3949   assert(CMSPrecleanIter < 10, "CMSPrecleanIter is too large");
3950   assert(CMSPrecleanNumerator < CMSPrecleanDenominator,
3951          "Bad convergence multiplier");
3952   assert(CMSPrecleanThreshold >= 100,
3953          "Unreasonably low CMSPrecleanThreshold");
3954 
3955   size_t numIter, cumNumCards, lastNumCards, curNumCards;
3956   for (numIter = 0, cumNumCards = lastNumCards = curNumCards = 0;
3957        numIter < CMSPrecleanIter;
3958        numIter++, lastNumCards = curNumCards, cumNumCards += curNumCards) {
3959     curNumCards  = preclean_mod_union_table(_cmsGen, &smoac_cl);
3960     if (Verbose && PrintGCDetails) {
3961       gclog_or_tty->print(" (modUnionTable: " SIZE_FORMAT " cards)", curNumCards);
3962     }
3963     // Either there are very few dirty cards, so re-mark
3964     // pause will be small anyway, or our pre-cleaning isn't
3965     // that much faster than the rate at which cards are being
3966     // dirtied, so we might as well stop and re-mark since
3967     // precleaning won't improve our re-mark time by much.
3968     if (curNumCards <= CMSPrecleanThreshold ||
3969         (numIter > 0 &&
3970          (curNumCards * CMSPrecleanDenominator >
3971          lastNumCards * CMSPrecleanNumerator))) {
3972       numIter++;
3973       cumNumCards += curNumCards;
3974       break;
3975     }
3976   }
3977 
3978   preclean_klasses(&mrias_cl, _cmsGen->freelistLock());
3979 
3980   curNumCards = preclean_card_table(_cmsGen, &smoac_cl);
3981   cumNumCards += curNumCards;
3982   if (PrintGCDetails && PrintCMSStatistics != 0) {
3983     gclog_or_tty->print_cr(" (cardTable: " SIZE_FORMAT " cards, re-scanned " SIZE_FORMAT " cards, " SIZE_FORMAT " iterations)",
3984                   curNumCards, cumNumCards, numIter);
3985   }
3986   return cumNumCards;   // as a measure of useful work done
3987 }
3988 
3989 // PRECLEANING NOTES:
3990 // Precleaning involves:
3991 // . reading the bits of the modUnionTable and clearing the set bits.
3992 // . For the cards corresponding to the set bits, we scan the
3993 //   objects on those cards. This means we need the free_list_lock
3994 //   so that we can safely iterate over the CMS space when scanning
3995 //   for oops.
3996 // . When we scan the objects, we'll be both reading and setting
3997 //   marks in the marking bit map, so we'll need the marking bit map.
3998 // . For protecting _collector_state transitions, we take the CGC_lock.
3999 //   Note that any races in the reading of of card table entries by the
4000 //   CMS thread on the one hand and the clearing of those entries by the
4001 //   VM thread or the setting of those entries by the mutator threads on the
4002 //   other are quite benign. However, for efficiency it makes sense to keep
4003 //   the VM thread from racing with the CMS thread while the latter is
4004 //   dirty card info to the modUnionTable. We therefore also use the
4005 //   CGC_lock to protect the reading of the card table and the mod union
4006 //   table by the CM thread.
4007 // . We run concurrently with mutator updates, so scanning
4008 //   needs to be done carefully  -- we should not try to scan
4009 //   potentially uninitialized objects.
4010 //
4011 // Locking strategy: While holding the CGC_lock, we scan over and
4012 // reset a maximal dirty range of the mod union / card tables, then lock
4013 // the free_list_lock and bitmap lock to do a full marking, then
4014 // release these locks; and repeat the cycle. This allows for a
4015 // certain amount of fairness in the sharing of these locks between
4016 // the CMS collector on the one hand, and the VM thread and the
4017 // mutators on the other.
4018 
4019 // NOTE: preclean_mod_union_table() and preclean_card_table()
4020 // further below are largely identical; if you need to modify
4021 // one of these methods, please check the other method too.
4022 
4023 size_t CMSCollector::preclean_mod_union_table(
4024   ConcurrentMarkSweepGeneration* old_gen,
4025   ScanMarkedObjectsAgainCarefullyClosure* cl) {
4026   verify_work_stacks_empty();
4027   verify_overflow_empty();
4028 
4029   // strategy: starting with the first card, accumulate contiguous
4030   // ranges of dirty cards; clear these cards, then scan the region
4031   // covered by these cards.
4032 
4033   // Since all of the MUT is committed ahead, we can just use
4034   // that, in case the generations expand while we are precleaning.
4035   // It might also be fine to just use the committed part of the
4036   // generation, but we might potentially miss cards when the
4037   // generation is rapidly expanding while we are in the midst
4038   // of precleaning.
4039   HeapWord* startAddr = old_gen->reserved().start();
4040   HeapWord* endAddr   = old_gen->reserved().end();
4041 
4042   cl->setFreelistLock(old_gen->freelistLock());   // needed for yielding
4043 
4044   size_t numDirtyCards, cumNumDirtyCards;
4045   HeapWord *nextAddr, *lastAddr;
4046   for (cumNumDirtyCards = numDirtyCards = 0,
4047        nextAddr = lastAddr = startAddr;
4048        nextAddr < endAddr;
4049        nextAddr = lastAddr, cumNumDirtyCards += numDirtyCards) {
4050 
4051     ResourceMark rm;
4052     HandleMark   hm;
4053 
4054     MemRegion dirtyRegion;
4055     {
4056       stopTimer();
4057       // Potential yield point
4058       CMSTokenSync ts(true);
4059       startTimer();
4060       sample_eden();
4061       // Get dirty region starting at nextOffset (inclusive),
4062       // simultaneously clearing it.
4063       dirtyRegion =
4064         _modUnionTable.getAndClearMarkedRegion(nextAddr, endAddr);
4065       assert(dirtyRegion.start() >= nextAddr,
4066              "returned region inconsistent?");
4067     }
4068     // Remember where the next search should begin.
4069     // The returned region (if non-empty) is a right open interval,
4070     // so lastOffset is obtained from the right end of that
4071     // interval.
4072     lastAddr = dirtyRegion.end();
4073     // Should do something more transparent and less hacky XXX
4074     numDirtyCards =
4075       _modUnionTable.heapWordDiffToOffsetDiff(dirtyRegion.word_size());
4076 
4077     // We'll scan the cards in the dirty region (with periodic
4078     // yields for foreground GC as needed).
4079     if (!dirtyRegion.is_empty()) {
4080       assert(numDirtyCards > 0, "consistency check");
4081       HeapWord* stop_point = NULL;
4082       stopTimer();
4083       // Potential yield point
4084       CMSTokenSyncWithLocks ts(true, old_gen->freelistLock(),
4085                                bitMapLock());
4086       startTimer();
4087       {
4088         verify_work_stacks_empty();
4089         verify_overflow_empty();
4090         sample_eden();
4091         stop_point =
4092           old_gen->cmsSpace()->object_iterate_careful_m(dirtyRegion, cl);
4093       }
4094       if (stop_point != NULL) {
4095         // The careful iteration stopped early either because it found an
4096         // uninitialized object, or because we were in the midst of an
4097         // "abortable preclean", which should now be aborted. Redirty
4098         // the bits corresponding to the partially-scanned or unscanned
4099         // cards. We'll either restart at the next block boundary or
4100         // abort the preclean.
4101         assert((_collectorState == AbortablePreclean && should_abort_preclean()),
4102                "Should only be AbortablePreclean.");
4103         _modUnionTable.mark_range(MemRegion(stop_point, dirtyRegion.end()));
4104         if (should_abort_preclean()) {
4105           break; // out of preclean loop
4106         } else {
4107           // Compute the next address at which preclean should pick up;
4108           // might need bitMapLock in order to read P-bits.
4109           lastAddr = next_card_start_after_block(stop_point);
4110         }
4111       }
4112     } else {
4113       assert(lastAddr == endAddr, "consistency check");
4114       assert(numDirtyCards == 0, "consistency check");
4115       break;
4116     }
4117   }
4118   verify_work_stacks_empty();
4119   verify_overflow_empty();
4120   return cumNumDirtyCards;
4121 }
4122 
4123 // NOTE: preclean_mod_union_table() above and preclean_card_table()
4124 // below are largely identical; if you need to modify
4125 // one of these methods, please check the other method too.
4126 
4127 size_t CMSCollector::preclean_card_table(ConcurrentMarkSweepGeneration* old_gen,
4128   ScanMarkedObjectsAgainCarefullyClosure* cl) {
4129   // strategy: it's similar to precleamModUnionTable above, in that
4130   // we accumulate contiguous ranges of dirty cards, mark these cards
4131   // precleaned, then scan the region covered by these cards.
4132   HeapWord* endAddr   = (HeapWord*)(old_gen->_virtual_space.high());
4133   HeapWord* startAddr = (HeapWord*)(old_gen->_virtual_space.low());
4134 
4135   cl->setFreelistLock(old_gen->freelistLock());   // needed for yielding
4136 
4137   size_t numDirtyCards, cumNumDirtyCards;
4138   HeapWord *lastAddr, *nextAddr;
4139 
4140   for (cumNumDirtyCards = numDirtyCards = 0,
4141        nextAddr = lastAddr = startAddr;
4142        nextAddr < endAddr;
4143        nextAddr = lastAddr, cumNumDirtyCards += numDirtyCards) {
4144 
4145     ResourceMark rm;
4146     HandleMark   hm;
4147 
4148     MemRegion dirtyRegion;
4149     {
4150       // See comments in "Precleaning notes" above on why we
4151       // do this locking. XXX Could the locking overheads be
4152       // too high when dirty cards are sparse? [I don't think so.]
4153       stopTimer();
4154       CMSTokenSync x(true); // is cms thread
4155       startTimer();
4156       sample_eden();
4157       // Get and clear dirty region from card table
4158       dirtyRegion = _ct->ct_bs()->dirty_card_range_after_reset(
4159                                     MemRegion(nextAddr, endAddr),
4160                                     true,
4161                                     CardTableModRefBS::precleaned_card_val());
4162 
4163       assert(dirtyRegion.start() >= nextAddr,
4164              "returned region inconsistent?");
4165     }
4166     lastAddr = dirtyRegion.end();
4167     numDirtyCards =
4168       dirtyRegion.word_size()/CardTableModRefBS::card_size_in_words;
4169 
4170     if (!dirtyRegion.is_empty()) {
4171       stopTimer();
4172       CMSTokenSyncWithLocks ts(true, old_gen->freelistLock(), bitMapLock());
4173       startTimer();
4174       sample_eden();
4175       verify_work_stacks_empty();
4176       verify_overflow_empty();
4177       HeapWord* stop_point =
4178         old_gen->cmsSpace()->object_iterate_careful_m(dirtyRegion, cl);
4179       if (stop_point != NULL) {
4180         assert((_collectorState == AbortablePreclean && should_abort_preclean()),
4181                "Should only be AbortablePreclean.");
4182         _ct->ct_bs()->invalidate(MemRegion(stop_point, dirtyRegion.end()));
4183         if (should_abort_preclean()) {
4184           break; // out of preclean loop
4185         } else {
4186           // Compute the next address at which preclean should pick up.
4187           lastAddr = next_card_start_after_block(stop_point);
4188         }
4189       }
4190     } else {
4191       break;
4192     }
4193   }
4194   verify_work_stacks_empty();
4195   verify_overflow_empty();
4196   return cumNumDirtyCards;
4197 }
4198 
4199 class PrecleanKlassClosure : public KlassClosure {
4200   KlassToOopClosure _cm_klass_closure;
4201  public:
4202   PrecleanKlassClosure(OopClosure* oop_closure) : _cm_klass_closure(oop_closure) {}
4203   void do_klass(Klass* k) {
4204     if (k->has_accumulated_modified_oops()) {
4205       k->clear_accumulated_modified_oops();
4206 
4207       _cm_klass_closure.do_klass(k);
4208     }
4209   }
4210 };
4211 
4212 // The freelist lock is needed to prevent asserts, is it really needed?
4213 void CMSCollector::preclean_klasses(MarkRefsIntoAndScanClosure* cl, Mutex* freelistLock) {
4214 
4215   cl->set_freelistLock(freelistLock);
4216 
4217   CMSTokenSyncWithLocks ts(true, freelistLock, bitMapLock());
4218 
4219   // SSS: Add equivalent to ScanMarkedObjectsAgainCarefullyClosure::do_yield_check and should_abort_preclean?
4220   // SSS: We should probably check if precleaning should be aborted, at suitable intervals?
4221   PrecleanKlassClosure preclean_klass_closure(cl);
4222   ClassLoaderDataGraph::classes_do(&preclean_klass_closure);
4223 
4224   verify_work_stacks_empty();
4225   verify_overflow_empty();
4226 }
4227 
4228 void CMSCollector::checkpointRootsFinal() {
4229   assert(_collectorState == FinalMarking, "incorrect state transition?");
4230   check_correct_thread_executing();
4231   // world is stopped at this checkpoint
4232   assert(SafepointSynchronize::is_at_safepoint(),
4233          "world should be stopped");
4234   TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause());
4235 
4236   verify_work_stacks_empty();
4237   verify_overflow_empty();
4238 
4239   if (PrintGCDetails) {
4240     gclog_or_tty->print("[YG occupancy: " SIZE_FORMAT " K (" SIZE_FORMAT " K)]",
4241                         _young_gen->used() / K,
4242                         _young_gen->capacity() / K);
4243   }
4244   {
4245     if (CMSScavengeBeforeRemark) {
4246       GenCollectedHeap* gch = GenCollectedHeap::heap();
4247       // Temporarily set flag to false, GCH->do_collection will
4248       // expect it to be false and set to true
4249       FlagSetting fl(gch->_is_gc_active, false);
4250       NOT_PRODUCT(GCTraceTime t("Scavenge-Before-Remark",
4251         PrintGCDetails && Verbose, true, _gc_timer_cm);)
4252       gch->do_collection(true,                      // full (i.e. force, see below)
4253                          false,                     // !clear_all_soft_refs
4254                          0,                         // size
4255                          false,                     // is_tlab
4256                          GenCollectedHeap::YoungGen // type
4257         );
4258     }
4259     FreelistLocker x(this);
4260     MutexLockerEx y(bitMapLock(),
4261                     Mutex::_no_safepoint_check_flag);
4262     checkpointRootsFinalWork();
4263   }
4264   verify_work_stacks_empty();
4265   verify_overflow_empty();
4266 }
4267 
4268 void CMSCollector::checkpointRootsFinalWork() {
4269   NOT_PRODUCT(GCTraceTime tr("checkpointRootsFinalWork", PrintGCDetails, false, _gc_timer_cm);)
4270 
4271   assert(haveFreelistLocks(), "must have free list locks");
4272   assert_lock_strong(bitMapLock());
4273 
4274   ResourceMark rm;
4275   HandleMark   hm;
4276 
4277   GenCollectedHeap* gch = GenCollectedHeap::heap();
4278 
4279   if (should_unload_classes()) {
4280     CodeCache::gc_prologue();
4281   }
4282   assert(haveFreelistLocks(), "must have free list locks");
4283   assert_lock_strong(bitMapLock());
4284 
4285   // We might assume that we need not fill TLAB's when
4286   // CMSScavengeBeforeRemark is set, because we may have just done
4287   // a scavenge which would have filled all TLAB's -- and besides
4288   // Eden would be empty. This however may not always be the case --
4289   // for instance although we asked for a scavenge, it may not have
4290   // happened because of a JNI critical section. We probably need
4291   // a policy for deciding whether we can in that case wait until
4292   // the critical section releases and then do the remark following
4293   // the scavenge, and skip it here. In the absence of that policy,
4294   // or of an indication of whether the scavenge did indeed occur,
4295   // we cannot rely on TLAB's having been filled and must do
4296   // so here just in case a scavenge did not happen.
4297   gch->ensure_parsability(false);  // fill TLAB's, but no need to retire them
4298   // Update the saved marks which may affect the root scans.
4299   gch->save_marks();
4300 
4301   if (CMSPrintEdenSurvivorChunks) {
4302     print_eden_and_survivor_chunk_arrays();
4303   }
4304 
4305   {
4306 #if defined(COMPILER2) || INCLUDE_JVMCI
4307     DerivedPointerTableDeactivate dpt_deact;
4308 #endif
4309 
4310     // Note on the role of the mod union table:
4311     // Since the marker in "markFromRoots" marks concurrently with
4312     // mutators, it is possible for some reachable objects not to have been
4313     // scanned. For instance, an only reference to an object A was
4314     // placed in object B after the marker scanned B. Unless B is rescanned,
4315     // A would be collected. Such updates to references in marked objects
4316     // are detected via the mod union table which is the set of all cards
4317     // dirtied since the first checkpoint in this GC cycle and prior to
4318     // the most recent young generation GC, minus those cleaned up by the
4319     // concurrent precleaning.
4320     if (CMSParallelRemarkEnabled) {
4321       GCTraceTime t("Rescan (parallel) ", PrintGCDetails, false, _gc_timer_cm);
4322       do_remark_parallel();
4323     } else {
4324       GCTraceTime t("Rescan (non-parallel) ", PrintGCDetails, false, _gc_timer_cm);
4325       do_remark_non_parallel();
4326     }
4327   }
4328   verify_work_stacks_empty();
4329   verify_overflow_empty();
4330 
4331   {
4332     NOT_PRODUCT(GCTraceTime ts("refProcessingWork", PrintGCDetails, false, _gc_timer_cm);)
4333     refProcessingWork();
4334   }
4335   verify_work_stacks_empty();
4336   verify_overflow_empty();
4337 
4338   if (should_unload_classes()) {
4339     CodeCache::gc_epilogue();
4340   }
4341   JvmtiExport::gc_epilogue();
4342 
4343   // If we encountered any (marking stack / work queue) overflow
4344   // events during the current CMS cycle, take appropriate
4345   // remedial measures, where possible, so as to try and avoid
4346   // recurrence of that condition.
4347   assert(_markStack.isEmpty(), "No grey objects");
4348   size_t ser_ovflw = _ser_pmc_remark_ovflw + _ser_pmc_preclean_ovflw +
4349                      _ser_kac_ovflw        + _ser_kac_preclean_ovflw;
4350   if (ser_ovflw > 0) {
4351     if (PrintCMSStatistics != 0) {
4352       gclog_or_tty->print_cr("Marking stack overflow (benign) "
4353         "(pmc_pc=" SIZE_FORMAT ", pmc_rm=" SIZE_FORMAT ", kac=" SIZE_FORMAT
4354         ", kac_preclean=" SIZE_FORMAT ")",
4355         _ser_pmc_preclean_ovflw, _ser_pmc_remark_ovflw,
4356         _ser_kac_ovflw, _ser_kac_preclean_ovflw);
4357     }
4358     _markStack.expand();
4359     _ser_pmc_remark_ovflw = 0;
4360     _ser_pmc_preclean_ovflw = 0;
4361     _ser_kac_preclean_ovflw = 0;
4362     _ser_kac_ovflw = 0;
4363   }
4364   if (_par_pmc_remark_ovflw > 0 || _par_kac_ovflw > 0) {
4365     if (PrintCMSStatistics != 0) {
4366       gclog_or_tty->print_cr("Work queue overflow (benign) "
4367         "(pmc_rm=" SIZE_FORMAT ", kac=" SIZE_FORMAT ")",
4368         _par_pmc_remark_ovflw, _par_kac_ovflw);
4369     }
4370     _par_pmc_remark_ovflw = 0;
4371     _par_kac_ovflw = 0;
4372   }
4373   if (PrintCMSStatistics != 0) {
4374      if (_markStack._hit_limit > 0) {
4375        gclog_or_tty->print_cr(" (benign) Hit max stack size limit (" SIZE_FORMAT ")",
4376                               _markStack._hit_limit);
4377      }
4378      if (_markStack._failed_double > 0) {
4379        gclog_or_tty->print_cr(" (benign) Failed stack doubling (" SIZE_FORMAT "),"
4380                               " current capacity " SIZE_FORMAT,
4381                               _markStack._failed_double,
4382                               _markStack.capacity());
4383      }
4384   }
4385   _markStack._hit_limit = 0;
4386   _markStack._failed_double = 0;
4387 
4388   if ((VerifyAfterGC || VerifyDuringGC) &&
4389       GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
4390     verify_after_remark();
4391   }
4392 
4393   _gc_tracer_cm->report_object_count_after_gc(&_is_alive_closure);
4394 
4395   // Change under the freelistLocks.
4396   _collectorState = Sweeping;
4397   // Call isAllClear() under bitMapLock
4398   assert(_modUnionTable.isAllClear(),
4399       "Should be clear by end of the final marking");
4400   assert(_ct->klass_rem_set()->mod_union_is_clear(),
4401       "Should be clear by end of the final marking");
4402 }
4403 
4404 void CMSParInitialMarkTask::work(uint worker_id) {
4405   elapsedTimer _timer;
4406   ResourceMark rm;
4407   HandleMark   hm;
4408 
4409   // ---------- scan from roots --------------
4410   _timer.start();
4411   GenCollectedHeap* gch = GenCollectedHeap::heap();
4412   Par_MarkRefsIntoClosure par_mri_cl(_collector->_span, &(_collector->_markBitMap));
4413 
4414   // ---------- young gen roots --------------
4415   {
4416     work_on_young_gen_roots(worker_id, &par_mri_cl);
4417     _timer.stop();
4418     if (PrintCMSStatistics != 0) {
4419       gclog_or_tty->print_cr(
4420         "Finished young gen initial mark scan work in %dth thread: %3.3f sec",
4421         worker_id, _timer.seconds());
4422     }
4423   }
4424 
4425   // ---------- remaining roots --------------
4426   _timer.reset();
4427   _timer.start();
4428 
4429   CLDToOopClosure cld_closure(&par_mri_cl, true);
4430 
4431   gch->gen_process_roots(_strong_roots_scope,
4432                          GenCollectedHeap::OldGen,
4433                          false,     // yg was scanned above
4434                          GenCollectedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()),
4435                          _collector->should_unload_classes(),
4436                          &par_mri_cl,
4437                          NULL,
4438                          &cld_closure);
4439   assert(_collector->should_unload_classes()
4440          || (_collector->CMSCollector::roots_scanning_options() & GenCollectedHeap::SO_AllCodeCache),
4441          "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops");
4442   _timer.stop();
4443   if (PrintCMSStatistics != 0) {
4444     gclog_or_tty->print_cr(
4445       "Finished remaining root initial mark scan work in %dth thread: %3.3f sec",
4446       worker_id, _timer.seconds());
4447   }
4448 }
4449 
4450 // Parallel remark task
4451 class CMSParRemarkTask: public CMSParMarkTask {
4452   CompactibleFreeListSpace* _cms_space;
4453 
4454   // The per-thread work queues, available here for stealing.
4455   OopTaskQueueSet*       _task_queues;
4456   ParallelTaskTerminator _term;
4457   StrongRootsScope*      _strong_roots_scope;
4458 
4459  public:
4460   // A value of 0 passed to n_workers will cause the number of
4461   // workers to be taken from the active workers in the work gang.
4462   CMSParRemarkTask(CMSCollector* collector,
4463                    CompactibleFreeListSpace* cms_space,
4464                    uint n_workers, WorkGang* workers,
4465                    OopTaskQueueSet* task_queues,
4466                    StrongRootsScope* strong_roots_scope):
4467     CMSParMarkTask("Rescan roots and grey objects in parallel",
4468                    collector, n_workers),
4469     _cms_space(cms_space),
4470     _task_queues(task_queues),
4471     _term(n_workers, task_queues),
4472     _strong_roots_scope(strong_roots_scope) { }
4473 
4474   OopTaskQueueSet* task_queues() { return _task_queues; }
4475 
4476   OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); }
4477 
4478   ParallelTaskTerminator* terminator() { return &_term; }
4479   uint n_workers() { return _n_workers; }
4480 
4481   void work(uint worker_id);
4482 
4483  private:
4484   // ... of  dirty cards in old space
4485   void do_dirty_card_rescan_tasks(CompactibleFreeListSpace* sp, int i,
4486                                   Par_MarkRefsIntoAndScanClosure* cl);
4487 
4488   // ... work stealing for the above
4489   void do_work_steal(int i, Par_MarkRefsIntoAndScanClosure* cl, int* seed);
4490 };
4491 
4492 class RemarkKlassClosure : public KlassClosure {
4493   KlassToOopClosure _cm_klass_closure;
4494  public:
4495   RemarkKlassClosure(OopClosure* oop_closure) : _cm_klass_closure(oop_closure) {}
4496   void do_klass(Klass* k) {
4497     // Check if we have modified any oops in the Klass during the concurrent marking.
4498     if (k->has_accumulated_modified_oops()) {
4499       k->clear_accumulated_modified_oops();
4500 
4501       // We could have transfered the current modified marks to the accumulated marks,
4502       // like we do with the Card Table to Mod Union Table. But it's not really necessary.
4503     } else if (k->has_modified_oops()) {
4504       // Don't clear anything, this info is needed by the next young collection.
4505     } else {
4506       // No modified oops in the Klass.
4507       return;
4508     }
4509 
4510     // The klass has modified fields, need to scan the klass.
4511     _cm_klass_closure.do_klass(k);
4512   }
4513 };
4514 
4515 void CMSParMarkTask::work_on_young_gen_roots(uint worker_id, OopsInGenClosure* cl) {
4516   ParNewGeneration* young_gen = _collector->_young_gen;
4517   ContiguousSpace* eden_space = young_gen->eden();
4518   ContiguousSpace* from_space = young_gen->from();
4519   ContiguousSpace* to_space   = young_gen->to();
4520 
4521   HeapWord** eca = _collector->_eden_chunk_array;
4522   size_t     ect = _collector->_eden_chunk_index;
4523   HeapWord** sca = _collector->_survivor_chunk_array;
4524   size_t     sct = _collector->_survivor_chunk_index;
4525 
4526   assert(ect <= _collector->_eden_chunk_capacity, "out of bounds");
4527   assert(sct <= _collector->_survivor_chunk_capacity, "out of bounds");
4528 
4529   do_young_space_rescan(worker_id, cl, to_space, NULL, 0);
4530   do_young_space_rescan(worker_id, cl, from_space, sca, sct);
4531   do_young_space_rescan(worker_id, cl, eden_space, eca, ect);
4532 }
4533 
4534 // work_queue(i) is passed to the closure
4535 // Par_MarkRefsIntoAndScanClosure.  The "i" parameter
4536 // also is passed to do_dirty_card_rescan_tasks() and to
4537 // do_work_steal() to select the i-th task_queue.
4538 
4539 void CMSParRemarkTask::work(uint worker_id) {
4540   elapsedTimer _timer;
4541   ResourceMark rm;
4542   HandleMark   hm;
4543 
4544   // ---------- rescan from roots --------------
4545   _timer.start();
4546   GenCollectedHeap* gch = GenCollectedHeap::heap();
4547   Par_MarkRefsIntoAndScanClosure par_mrias_cl(_collector,
4548     _collector->_span, _collector->ref_processor(),
4549     &(_collector->_markBitMap),
4550     work_queue(worker_id));
4551 
4552   // Rescan young gen roots first since these are likely
4553   // coarsely partitioned and may, on that account, constitute
4554   // the critical path; thus, it's best to start off that
4555   // work first.
4556   // ---------- young gen roots --------------
4557   {
4558     work_on_young_gen_roots(worker_id, &par_mrias_cl);
4559     _timer.stop();
4560     if (PrintCMSStatistics != 0) {
4561       gclog_or_tty->print_cr(
4562         "Finished young gen rescan work in %dth thread: %3.3f sec",
4563         worker_id, _timer.seconds());
4564     }
4565   }
4566 
4567   // ---------- remaining roots --------------
4568   _timer.reset();
4569   _timer.start();
4570   gch->gen_process_roots(_strong_roots_scope,
4571                          GenCollectedHeap::OldGen,
4572                          false,     // yg was scanned above
4573                          GenCollectedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()),
4574                          _collector->should_unload_classes(),
4575                          &par_mrias_cl,
4576                          NULL,
4577                          NULL);     // The dirty klasses will be handled below
4578 
4579   assert(_collector->should_unload_classes()
4580          || (_collector->CMSCollector::roots_scanning_options() & GenCollectedHeap::SO_AllCodeCache),
4581          "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops");
4582   _timer.stop();
4583   if (PrintCMSStatistics != 0) {
4584     gclog_or_tty->print_cr(
4585       "Finished remaining root rescan work in %dth thread: %3.3f sec",
4586       worker_id, _timer.seconds());
4587   }
4588 
4589   // ---------- unhandled CLD scanning ----------
4590   if (worker_id == 0) { // Single threaded at the moment.
4591     _timer.reset();
4592     _timer.start();
4593 
4594     // Scan all new class loader data objects and new dependencies that were
4595     // introduced during concurrent marking.
4596     ResourceMark rm;
4597     GrowableArray<ClassLoaderData*>* array = ClassLoaderDataGraph::new_clds();
4598     for (int i = 0; i < array->length(); i++) {
4599       par_mrias_cl.do_cld_nv(array->at(i));
4600     }
4601 
4602     // We don't need to keep track of new CLDs anymore.
4603     ClassLoaderDataGraph::remember_new_clds(false);
4604 
4605     _timer.stop();
4606     if (PrintCMSStatistics != 0) {
4607       gclog_or_tty->print_cr(
4608           "Finished unhandled CLD scanning work in %dth thread: %3.3f sec",
4609           worker_id, _timer.seconds());
4610     }
4611   }
4612 
4613   // ---------- dirty klass scanning ----------
4614   if (worker_id == 0) { // Single threaded at the moment.
4615     _timer.reset();
4616     _timer.start();
4617 
4618     // Scan all classes that was dirtied during the concurrent marking phase.
4619     RemarkKlassClosure remark_klass_closure(&par_mrias_cl);
4620     ClassLoaderDataGraph::classes_do(&remark_klass_closure);
4621 
4622     _timer.stop();
4623     if (PrintCMSStatistics != 0) {
4624       gclog_or_tty->print_cr(
4625           "Finished dirty klass scanning work in %dth thread: %3.3f sec",
4626           worker_id, _timer.seconds());
4627     }
4628   }
4629 
4630   // We might have added oops to ClassLoaderData::_handles during the
4631   // concurrent marking phase. These oops point to newly allocated objects
4632   // that are guaranteed to be kept alive. Either by the direct allocation
4633   // code, or when the young collector processes the roots. Hence,
4634   // we don't have to revisit the _handles block during the remark phase.
4635 
4636   // ---------- rescan dirty cards ------------
4637   _timer.reset();
4638   _timer.start();
4639 
4640   // Do the rescan tasks for each of the two spaces
4641   // (cms_space) in turn.
4642   // "worker_id" is passed to select the task_queue for "worker_id"
4643   do_dirty_card_rescan_tasks(_cms_space, worker_id, &par_mrias_cl);
4644   _timer.stop();
4645   if (PrintCMSStatistics != 0) {
4646     gclog_or_tty->print_cr(
4647       "Finished dirty card rescan work in %dth thread: %3.3f sec",
4648       worker_id, _timer.seconds());
4649   }
4650 
4651   // ---------- steal work from other threads ...
4652   // ---------- ... and drain overflow list.
4653   _timer.reset();
4654   _timer.start();
4655   do_work_steal(worker_id, &par_mrias_cl, _collector->hash_seed(worker_id));
4656   _timer.stop();
4657   if (PrintCMSStatistics != 0) {
4658     gclog_or_tty->print_cr(
4659       "Finished work stealing in %dth thread: %3.3f sec",
4660       worker_id, _timer.seconds());
4661   }
4662 }
4663 
4664 // Note that parameter "i" is not used.
4665 void
4666 CMSParMarkTask::do_young_space_rescan(uint worker_id,
4667   OopsInGenClosure* cl, ContiguousSpace* space,
4668   HeapWord** chunk_array, size_t chunk_top) {
4669   // Until all tasks completed:
4670   // . claim an unclaimed task
4671   // . compute region boundaries corresponding to task claimed
4672   //   using chunk_array
4673   // . par_oop_iterate(cl) over that region
4674 
4675   ResourceMark rm;
4676   HandleMark   hm;
4677 
4678   SequentialSubTasksDone* pst = space->par_seq_tasks();
4679 
4680   uint nth_task = 0;
4681   uint n_tasks  = pst->n_tasks();
4682 
4683   if (n_tasks > 0) {
4684     assert(pst->valid(), "Uninitialized use?");
4685     HeapWord *start, *end;
4686     while (!pst->is_task_claimed(/* reference */ nth_task)) {
4687       // We claimed task # nth_task; compute its boundaries.
4688       if (chunk_top == 0) {  // no samples were taken
4689         assert(nth_task == 0 && n_tasks == 1, "Can have only 1 eden task");
4690         start = space->bottom();
4691         end   = space->top();
4692       } else if (nth_task == 0) {
4693         start = space->bottom();
4694         end   = chunk_array[nth_task];
4695       } else if (nth_task < (uint)chunk_top) {
4696         assert(nth_task >= 1, "Control point invariant");
4697         start = chunk_array[nth_task - 1];
4698         end   = chunk_array[nth_task];
4699       } else {
4700         assert(nth_task == (uint)chunk_top, "Control point invariant");
4701         start = chunk_array[chunk_top - 1];
4702         end   = space->top();
4703       }
4704       MemRegion mr(start, end);
4705       // Verify that mr is in space
4706       assert(mr.is_empty() || space->used_region().contains(mr),
4707              "Should be in space");
4708       // Verify that "start" is an object boundary
4709       assert(mr.is_empty() || oop(mr.start())->is_oop(),
4710              "Should be an oop");
4711       space->par_oop_iterate(mr, cl);
4712     }
4713     pst->all_tasks_completed();
4714   }
4715 }
4716 
4717 void
4718 CMSParRemarkTask::do_dirty_card_rescan_tasks(
4719   CompactibleFreeListSpace* sp, int i,
4720   Par_MarkRefsIntoAndScanClosure* cl) {
4721   // Until all tasks completed:
4722   // . claim an unclaimed task
4723   // . compute region boundaries corresponding to task claimed
4724   // . transfer dirty bits ct->mut for that region
4725   // . apply rescanclosure to dirty mut bits for that region
4726 
4727   ResourceMark rm;
4728   HandleMark   hm;
4729 
4730   OopTaskQueue* work_q = work_queue(i);
4731   ModUnionClosure modUnionClosure(&(_collector->_modUnionTable));
4732   // CAUTION! CAUTION! CAUTION! CAUTION! CAUTION! CAUTION! CAUTION!
4733   // CAUTION: This closure has state that persists across calls to
4734   // the work method dirty_range_iterate_clear() in that it has
4735   // embedded in it a (subtype of) UpwardsObjectClosure. The
4736   // use of that state in the embedded UpwardsObjectClosure instance
4737   // assumes that the cards are always iterated (even if in parallel
4738   // by several threads) in monotonically increasing order per each
4739   // thread. This is true of the implementation below which picks
4740   // card ranges (chunks) in monotonically increasing order globally
4741   // and, a-fortiori, in monotonically increasing order per thread
4742   // (the latter order being a subsequence of the former).
4743   // If the work code below is ever reorganized into a more chaotic
4744   // work-partitioning form than the current "sequential tasks"
4745   // paradigm, the use of that persistent state will have to be
4746   // revisited and modified appropriately. See also related
4747   // bug 4756801 work on which should examine this code to make
4748   // sure that the changes there do not run counter to the
4749   // assumptions made here and necessary for correctness and
4750   // efficiency. Note also that this code might yield inefficient
4751   // behavior in the case of very large objects that span one or
4752   // more work chunks. Such objects would potentially be scanned
4753   // several times redundantly. Work on 4756801 should try and
4754   // address that performance anomaly if at all possible. XXX
4755   MemRegion  full_span  = _collector->_span;
4756   CMSBitMap* bm    = &(_collector->_markBitMap);     // shared
4757   MarkFromDirtyCardsClosure
4758     greyRescanClosure(_collector, full_span, // entire span of interest
4759                       sp, bm, work_q, cl);
4760 
4761   SequentialSubTasksDone* pst = sp->conc_par_seq_tasks();
4762   assert(pst->valid(), "Uninitialized use?");
4763   uint nth_task = 0;
4764   const int alignment = CardTableModRefBS::card_size * BitsPerWord;
4765   MemRegion span = sp->used_region();
4766   HeapWord* start_addr = span.start();
4767   HeapWord* end_addr = (HeapWord*)round_to((intptr_t)span.end(),
4768                                            alignment);
4769   const size_t chunk_size = sp->rescan_task_size(); // in HeapWord units
4770   assert((HeapWord*)round_to((intptr_t)start_addr, alignment) ==
4771          start_addr, "Check alignment");
4772   assert((size_t)round_to((intptr_t)chunk_size, alignment) ==
4773          chunk_size, "Check alignment");
4774 
4775   while (!pst->is_task_claimed(/* reference */ nth_task)) {
4776     // Having claimed the nth_task, compute corresponding mem-region,
4777     // which is a-fortiori aligned correctly (i.e. at a MUT boundary).
4778     // The alignment restriction ensures that we do not need any
4779     // synchronization with other gang-workers while setting or
4780     // clearing bits in thus chunk of the MUT.
4781     MemRegion this_span = MemRegion(start_addr + nth_task*chunk_size,
4782                                     start_addr + (nth_task+1)*chunk_size);
4783     // The last chunk's end might be way beyond end of the
4784     // used region. In that case pull back appropriately.
4785     if (this_span.end() > end_addr) {
4786       this_span.set_end(end_addr);
4787       assert(!this_span.is_empty(), "Program logic (calculation of n_tasks)");
4788     }
4789     // Iterate over the dirty cards covering this chunk, marking them
4790     // precleaned, and setting the corresponding bits in the mod union
4791     // table. Since we have been careful to partition at Card and MUT-word
4792     // boundaries no synchronization is needed between parallel threads.
4793     _collector->_ct->ct_bs()->dirty_card_iterate(this_span,
4794                                                  &modUnionClosure);
4795 
4796     // Having transferred these marks into the modUnionTable,
4797     // rescan the marked objects on the dirty cards in the modUnionTable.
4798     // Even if this is at a synchronous collection, the initial marking
4799     // may have been done during an asynchronous collection so there
4800     // may be dirty bits in the mod-union table.
4801     _collector->_modUnionTable.dirty_range_iterate_clear(
4802                   this_span, &greyRescanClosure);
4803     _collector->_modUnionTable.verifyNoOneBitsInRange(
4804                                  this_span.start(),
4805                                  this_span.end());
4806   }
4807   pst->all_tasks_completed();  // declare that i am done
4808 }
4809 
4810 // . see if we can share work_queues with ParNew? XXX
4811 void
4812 CMSParRemarkTask::do_work_steal(int i, Par_MarkRefsIntoAndScanClosure* cl,
4813                                 int* seed) {
4814   OopTaskQueue* work_q = work_queue(i);
4815   NOT_PRODUCT(int num_steals = 0;)
4816   oop obj_to_scan;
4817   CMSBitMap* bm = &(_collector->_markBitMap);
4818 
4819   while (true) {
4820     // Completely finish any left over work from (an) earlier round(s)
4821     cl->trim_queue(0);
4822     size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
4823                                          (size_t)ParGCDesiredObjsFromOverflowList);
4824     // Now check if there's any work in the overflow list
4825     // Passing ParallelGCThreads as the third parameter, no_of_gc_threads,
4826     // only affects the number of attempts made to get work from the
4827     // overflow list and does not affect the number of workers.  Just
4828     // pass ParallelGCThreads so this behavior is unchanged.
4829     if (_collector->par_take_from_overflow_list(num_from_overflow_list,
4830                                                 work_q,
4831                                                 ParallelGCThreads)) {
4832       // found something in global overflow list;
4833       // not yet ready to go stealing work from others.
4834       // We'd like to assert(work_q->size() != 0, ...)
4835       // because we just took work from the overflow list,
4836       // but of course we can't since all of that could have
4837       // been already stolen from us.
4838       // "He giveth and He taketh away."
4839       continue;
4840     }
4841     // Verify that we have no work before we resort to stealing
4842     assert(work_q->size() == 0, "Have work, shouldn't steal");
4843     // Try to steal from other queues that have work
4844     if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) {
4845       NOT_PRODUCT(num_steals++;)
4846       assert(obj_to_scan->is_oop(), "Oops, not an oop!");
4847       assert(bm->isMarked((HeapWord*)obj_to_scan), "Stole an unmarked oop?");
4848       // Do scanning work
4849       obj_to_scan->oop_iterate(cl);
4850       // Loop around, finish this work, and try to steal some more
4851     } else if (terminator()->offer_termination()) {
4852         break;  // nirvana from the infinite cycle
4853     }
4854   }
4855   NOT_PRODUCT(
4856     if (PrintCMSStatistics != 0) {
4857       gclog_or_tty->print("\n\t(%d: stole %d oops)", i, num_steals);
4858     }
4859   )
4860   assert(work_q->size() == 0 && _collector->overflow_list_is_empty(),
4861          "Else our work is not yet done");
4862 }
4863 
4864 // Record object boundaries in _eden_chunk_array by sampling the eden
4865 // top in the slow-path eden object allocation code path and record
4866 // the boundaries, if CMSEdenChunksRecordAlways is true. If
4867 // CMSEdenChunksRecordAlways is false, we use the other asynchronous
4868 // sampling in sample_eden() that activates during the part of the
4869 // preclean phase.
4870 void CMSCollector::sample_eden_chunk() {
4871   if (CMSEdenChunksRecordAlways && _eden_chunk_array != NULL) {
4872     if (_eden_chunk_lock->try_lock()) {
4873       // Record a sample. This is the critical section. The contents
4874       // of the _eden_chunk_array have to be non-decreasing in the
4875       // address order.
4876       _eden_chunk_array[_eden_chunk_index] = *_top_addr;
4877       assert(_eden_chunk_array[_eden_chunk_index] <= *_end_addr,
4878              "Unexpected state of Eden");
4879       if (_eden_chunk_index == 0 ||
4880           ((_eden_chunk_array[_eden_chunk_index] > _eden_chunk_array[_eden_chunk_index-1]) &&
4881            (pointer_delta(_eden_chunk_array[_eden_chunk_index],
4882                           _eden_chunk_array[_eden_chunk_index-1]) >= CMSSamplingGrain))) {
4883         _eden_chunk_index++;  // commit sample
4884       }
4885       _eden_chunk_lock->unlock();
4886     }
4887   }
4888 }
4889 
4890 // Return a thread-local PLAB recording array, as appropriate.
4891 void* CMSCollector::get_data_recorder(int thr_num) {
4892   if (_survivor_plab_array != NULL &&
4893       (CMSPLABRecordAlways ||
4894        (_collectorState > Marking && _collectorState < FinalMarking))) {
4895     assert(thr_num < (int)ParallelGCThreads, "thr_num is out of bounds");
4896     ChunkArray* ca = &_survivor_plab_array[thr_num];
4897     ca->reset();   // clear it so that fresh data is recorded
4898     return (void*) ca;
4899   } else {
4900     return NULL;
4901   }
4902 }
4903 
4904 // Reset all the thread-local PLAB recording arrays
4905 void CMSCollector::reset_survivor_plab_arrays() {
4906   for (uint i = 0; i < ParallelGCThreads; i++) {
4907     _survivor_plab_array[i].reset();
4908   }
4909 }
4910 
4911 // Merge the per-thread plab arrays into the global survivor chunk
4912 // array which will provide the partitioning of the survivor space
4913 // for CMS initial scan and rescan.
4914 void CMSCollector::merge_survivor_plab_arrays(ContiguousSpace* surv,
4915                                               int no_of_gc_threads) {
4916   assert(_survivor_plab_array  != NULL, "Error");
4917   assert(_survivor_chunk_array != NULL, "Error");
4918   assert(_collectorState == FinalMarking ||
4919          (CMSParallelInitialMarkEnabled && _collectorState == InitialMarking), "Error");
4920   for (int j = 0; j < no_of_gc_threads; j++) {
4921     _cursor[j] = 0;
4922   }
4923   HeapWord* top = surv->top();
4924   size_t i;
4925   for (i = 0; i < _survivor_chunk_capacity; i++) {  // all sca entries
4926     HeapWord* min_val = top;          // Higher than any PLAB address
4927     uint      min_tid = 0;            // position of min_val this round
4928     for (int j = 0; j < no_of_gc_threads; j++) {
4929       ChunkArray* cur_sca = &_survivor_plab_array[j];
4930       if (_cursor[j] == cur_sca->end()) {
4931         continue;
4932       }
4933       assert(_cursor[j] < cur_sca->end(), "ctl pt invariant");
4934       HeapWord* cur_val = cur_sca->nth(_cursor[j]);
4935       assert(surv->used_region().contains(cur_val), "Out of bounds value");
4936       if (cur_val < min_val) {
4937         min_tid = j;
4938         min_val = cur_val;
4939       } else {
4940         assert(cur_val < top, "All recorded addresses should be less");
4941       }
4942     }
4943     // At this point min_val and min_tid are respectively
4944     // the least address in _survivor_plab_array[j]->nth(_cursor[j])
4945     // and the thread (j) that witnesses that address.
4946     // We record this address in the _survivor_chunk_array[i]
4947     // and increment _cursor[min_tid] prior to the next round i.
4948     if (min_val == top) {
4949       break;
4950     }
4951     _survivor_chunk_array[i] = min_val;
4952     _cursor[min_tid]++;
4953   }
4954   // We are all done; record the size of the _survivor_chunk_array
4955   _survivor_chunk_index = i; // exclusive: [0, i)
4956   if (PrintCMSStatistics > 0) {
4957     gclog_or_tty->print(" (Survivor:" SIZE_FORMAT "chunks) ", i);
4958   }
4959   // Verify that we used up all the recorded entries
4960   #ifdef ASSERT
4961     size_t total = 0;
4962     for (int j = 0; j < no_of_gc_threads; j++) {
4963       assert(_cursor[j] == _survivor_plab_array[j].end(), "Ctl pt invariant");
4964       total += _cursor[j];
4965     }
4966     assert(total == _survivor_chunk_index, "Ctl Pt Invariant");
4967     // Check that the merged array is in sorted order
4968     if (total > 0) {
4969       for (size_t i = 0; i < total - 1; i++) {
4970         if (PrintCMSStatistics > 0) {
4971           gclog_or_tty->print(" (chunk" SIZE_FORMAT ":" INTPTR_FORMAT ") ",
4972                               i, p2i(_survivor_chunk_array[i]));
4973         }
4974         assert(_survivor_chunk_array[i] < _survivor_chunk_array[i+1],
4975                "Not sorted");
4976       }
4977     }
4978   #endif // ASSERT
4979 }
4980 
4981 // Set up the space's par_seq_tasks structure for work claiming
4982 // for parallel initial scan and rescan of young gen.
4983 // See ParRescanTask where this is currently used.
4984 void
4985 CMSCollector::
4986 initialize_sequential_subtasks_for_young_gen_rescan(int n_threads) {
4987   assert(n_threads > 0, "Unexpected n_threads argument");
4988 
4989   // Eden space
4990   if (!_young_gen->eden()->is_empty()) {
4991     SequentialSubTasksDone* pst = _young_gen->eden()->par_seq_tasks();
4992     assert(!pst->valid(), "Clobbering existing data?");
4993     // Each valid entry in [0, _eden_chunk_index) represents a task.
4994     size_t n_tasks = _eden_chunk_index + 1;
4995     assert(n_tasks == 1 || _eden_chunk_array != NULL, "Error");
4996     // Sets the condition for completion of the subtask (how many threads
4997     // need to finish in order to be done).
4998     pst->set_n_threads(n_threads);
4999     pst->set_n_tasks((int)n_tasks);
5000   }
5001 
5002   // Merge the survivor plab arrays into _survivor_chunk_array
5003   if (_survivor_plab_array != NULL) {
5004     merge_survivor_plab_arrays(_young_gen->from(), n_threads);
5005   } else {
5006     assert(_survivor_chunk_index == 0, "Error");
5007   }
5008 
5009   // To space
5010   {
5011     SequentialSubTasksDone* pst = _young_gen->to()->par_seq_tasks();
5012     assert(!pst->valid(), "Clobbering existing data?");
5013     // Sets the condition for completion of the subtask (how many threads
5014     // need to finish in order to be done).
5015     pst->set_n_threads(n_threads);
5016     pst->set_n_tasks(1);
5017     assert(pst->valid(), "Error");
5018   }
5019 
5020   // From space
5021   {
5022     SequentialSubTasksDone* pst = _young_gen->from()->par_seq_tasks();
5023     assert(!pst->valid(), "Clobbering existing data?");
5024     size_t n_tasks = _survivor_chunk_index + 1;
5025     assert(n_tasks == 1 || _survivor_chunk_array != NULL, "Error");
5026     // Sets the condition for completion of the subtask (how many threads
5027     // need to finish in order to be done).
5028     pst->set_n_threads(n_threads);
5029     pst->set_n_tasks((int)n_tasks);
5030     assert(pst->valid(), "Error");
5031   }
5032 }
5033 
5034 // Parallel version of remark
5035 void CMSCollector::do_remark_parallel() {
5036   GenCollectedHeap* gch = GenCollectedHeap::heap();
5037   WorkGang* workers = gch->workers();
5038   assert(workers != NULL, "Need parallel worker threads.");
5039   // Choose to use the number of GC workers most recently set
5040   // into "active_workers".
5041   uint n_workers = workers->active_workers();
5042 
5043   CompactibleFreeListSpace* cms_space  = _cmsGen->cmsSpace();
5044 
5045   StrongRootsScope srs(n_workers);
5046 
5047   CMSParRemarkTask tsk(this, cms_space, n_workers, workers, task_queues(), &srs);
5048 
5049   // We won't be iterating over the cards in the card table updating
5050   // the younger_gen cards, so we shouldn't call the following else
5051   // the verification code as well as subsequent younger_refs_iterate
5052   // code would get confused. XXX
5053   // gch->rem_set()->prepare_for_younger_refs_iterate(true); // parallel
5054 
5055   // The young gen rescan work will not be done as part of
5056   // process_roots (which currently doesn't know how to
5057   // parallelize such a scan), but rather will be broken up into
5058   // a set of parallel tasks (via the sampling that the [abortable]
5059   // preclean phase did of eden, plus the [two] tasks of
5060   // scanning the [two] survivor spaces. Further fine-grain
5061   // parallelization of the scanning of the survivor spaces
5062   // themselves, and of precleaning of the young gen itself
5063   // is deferred to the future.
5064   initialize_sequential_subtasks_for_young_gen_rescan(n_workers);
5065 
5066   // The dirty card rescan work is broken up into a "sequence"
5067   // of parallel tasks (per constituent space) that are dynamically
5068   // claimed by the parallel threads.
5069   cms_space->initialize_sequential_subtasks_for_rescan(n_workers);
5070 
5071   // It turns out that even when we're using 1 thread, doing the work in a
5072   // separate thread causes wide variance in run times.  We can't help this
5073   // in the multi-threaded case, but we special-case n=1 here to get
5074   // repeatable measurements of the 1-thread overhead of the parallel code.
5075   if (n_workers > 1) {
5076     // Make refs discovery MT-safe, if it isn't already: it may not
5077     // necessarily be so, since it's possible that we are doing
5078     // ST marking.
5079     ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), true);
5080     workers->run_task(&tsk);
5081   } else {
5082     ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), false);
5083     tsk.work(0);
5084   }
5085 
5086   // restore, single-threaded for now, any preserved marks
5087   // as a result of work_q overflow
5088   restore_preserved_marks_if_any();
5089 }
5090 
5091 // Non-parallel version of remark
5092 void CMSCollector::do_remark_non_parallel() {
5093   ResourceMark rm;
5094   HandleMark   hm;
5095   GenCollectedHeap* gch = GenCollectedHeap::heap();
5096   ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), false);
5097 
5098   MarkRefsIntoAndScanClosure
5099     mrias_cl(_span, ref_processor(), &_markBitMap, NULL /* not precleaning */,
5100              &_markStack, this,
5101              false /* should_yield */, false /* not precleaning */);
5102   MarkFromDirtyCardsClosure
5103     markFromDirtyCardsClosure(this, _span,
5104                               NULL,  // space is set further below
5105                               &_markBitMap, &_markStack, &mrias_cl);
5106   {
5107     GCTraceTime t("grey object rescan", PrintGCDetails, false, _gc_timer_cm);
5108     // Iterate over the dirty cards, setting the corresponding bits in the
5109     // mod union table.
5110     {
5111       ModUnionClosure modUnionClosure(&_modUnionTable);
5112       _ct->ct_bs()->dirty_card_iterate(
5113                       _cmsGen->used_region(),
5114                       &modUnionClosure);
5115     }
5116     // Having transferred these marks into the modUnionTable, we just need
5117     // to rescan the marked objects on the dirty cards in the modUnionTable.
5118     // The initial marking may have been done during an asynchronous
5119     // collection so there may be dirty bits in the mod-union table.
5120     const int alignment =
5121       CardTableModRefBS::card_size * BitsPerWord;
5122     {
5123       // ... First handle dirty cards in CMS gen
5124       markFromDirtyCardsClosure.set_space(_cmsGen->cmsSpace());
5125       MemRegion ur = _cmsGen->used_region();
5126       HeapWord* lb = ur.start();
5127       HeapWord* ub = (HeapWord*)round_to((intptr_t)ur.end(), alignment);
5128       MemRegion cms_span(lb, ub);
5129       _modUnionTable.dirty_range_iterate_clear(cms_span,
5130                                                &markFromDirtyCardsClosure);
5131       verify_work_stacks_empty();
5132       if (PrintCMSStatistics != 0) {
5133         gclog_or_tty->print(" (re-scanned " SIZE_FORMAT " dirty cards in cms gen) ",
5134           markFromDirtyCardsClosure.num_dirty_cards());
5135       }
5136     }
5137   }
5138   if (VerifyDuringGC &&
5139       GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) {
5140     HandleMark hm;  // Discard invalid handles created during verification
5141     Universe::verify();
5142   }
5143   {
5144     GCTraceTime t("root rescan", PrintGCDetails, false, _gc_timer_cm);
5145 
5146     verify_work_stacks_empty();
5147 
5148     gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel.
5149     StrongRootsScope srs(1);
5150 
5151     gch->gen_process_roots(&srs,
5152                            GenCollectedHeap::OldGen,
5153                            true,  // young gen as roots
5154                            GenCollectedHeap::ScanningOption(roots_scanning_options()),
5155                            should_unload_classes(),
5156                            &mrias_cl,
5157                            NULL,
5158                            NULL); // The dirty klasses will be handled below
5159 
5160     assert(should_unload_classes()
5161            || (roots_scanning_options() & GenCollectedHeap::SO_AllCodeCache),
5162            "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops");
5163   }
5164 
5165   {
5166     GCTraceTime t("visit unhandled CLDs", PrintGCDetails, false, _gc_timer_cm);
5167 
5168     verify_work_stacks_empty();
5169 
5170     // Scan all class loader data objects that might have been introduced
5171     // during concurrent marking.
5172     ResourceMark rm;
5173     GrowableArray<ClassLoaderData*>* array = ClassLoaderDataGraph::new_clds();
5174     for (int i = 0; i < array->length(); i++) {
5175       mrias_cl.do_cld_nv(array->at(i));
5176     }
5177 
5178     // We don't need to keep track of new CLDs anymore.
5179     ClassLoaderDataGraph::remember_new_clds(false);
5180 
5181     verify_work_stacks_empty();
5182   }
5183 
5184   {
5185     GCTraceTime t("dirty klass scan", PrintGCDetails, false, _gc_timer_cm);
5186 
5187     verify_work_stacks_empty();
5188 
5189     RemarkKlassClosure remark_klass_closure(&mrias_cl);
5190     ClassLoaderDataGraph::classes_do(&remark_klass_closure);
5191 
5192     verify_work_stacks_empty();
5193   }
5194 
5195   // We might have added oops to ClassLoaderData::_handles during the
5196   // concurrent marking phase. These oops point to newly allocated objects
5197   // that are guaranteed to be kept alive. Either by the direct allocation
5198   // code, or when the young collector processes the roots. Hence,
5199   // we don't have to revisit the _handles block during the remark phase.
5200 
5201   verify_work_stacks_empty();
5202   // Restore evacuated mark words, if any, used for overflow list links
5203   restore_preserved_marks_if_any();
5204 
5205   verify_overflow_empty();
5206 }
5207 
5208 ////////////////////////////////////////////////////////
5209 // Parallel Reference Processing Task Proxy Class
5210 ////////////////////////////////////////////////////////
5211 class AbstractGangTaskWOopQueues : public AbstractGangTask {
5212   OopTaskQueueSet*       _queues;
5213   ParallelTaskTerminator _terminator;
5214  public:
5215   AbstractGangTaskWOopQueues(const char* name, OopTaskQueueSet* queues, uint n_threads) :
5216     AbstractGangTask(name), _queues(queues), _terminator(n_threads, _queues) {}
5217   ParallelTaskTerminator* terminator() { return &_terminator; }
5218   OopTaskQueueSet* queues() { return _queues; }
5219 };
5220 
5221 class CMSRefProcTaskProxy: public AbstractGangTaskWOopQueues {
5222   typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;
5223   CMSCollector*          _collector;
5224   CMSBitMap*             _mark_bit_map;
5225   const MemRegion        _span;
5226   ProcessTask&           _task;
5227 
5228 public:
5229   CMSRefProcTaskProxy(ProcessTask&     task,
5230                       CMSCollector*    collector,
5231                       const MemRegion& span,
5232                       CMSBitMap*       mark_bit_map,
5233                       AbstractWorkGang* workers,
5234                       OopTaskQueueSet* task_queues):
5235     AbstractGangTaskWOopQueues("Process referents by policy in parallel",
5236       task_queues,
5237       workers->active_workers()),
5238     _task(task),
5239     _collector(collector), _span(span), _mark_bit_map(mark_bit_map)
5240   {
5241     assert(_collector->_span.equals(_span) && !_span.is_empty(),
5242            "Inconsistency in _span");
5243   }
5244 
5245   OopTaskQueueSet* task_queues() { return queues(); }
5246 
5247   OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); }
5248 
5249   void do_work_steal(int i,
5250                      CMSParDrainMarkingStackClosure* drain,
5251                      CMSParKeepAliveClosure* keep_alive,
5252                      int* seed);
5253 
5254   virtual void work(uint worker_id);
5255 };
5256 
5257 void CMSRefProcTaskProxy::work(uint worker_id) {
5258   ResourceMark rm;
5259   HandleMark hm;
5260   assert(_collector->_span.equals(_span), "Inconsistency in _span");
5261   CMSParKeepAliveClosure par_keep_alive(_collector, _span,
5262                                         _mark_bit_map,
5263                                         work_queue(worker_id));
5264   CMSParDrainMarkingStackClosure par_drain_stack(_collector, _span,
5265                                                  _mark_bit_map,
5266                                                  work_queue(worker_id));
5267   CMSIsAliveClosure is_alive_closure(_span, _mark_bit_map);
5268   _task.work(worker_id, is_alive_closure, par_keep_alive, par_drain_stack);
5269   if (_task.marks_oops_alive()) {
5270     do_work_steal(worker_id, &par_drain_stack, &par_keep_alive,
5271                   _collector->hash_seed(worker_id));
5272   }
5273   assert(work_queue(worker_id)->size() == 0, "work_queue should be empty");
5274   assert(_collector->_overflow_list == NULL, "non-empty _overflow_list");
5275 }
5276 
5277 class CMSRefEnqueueTaskProxy: public AbstractGangTask {
5278   typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;
5279   EnqueueTask& _task;
5280 
5281 public:
5282   CMSRefEnqueueTaskProxy(EnqueueTask& task)
5283     : AbstractGangTask("Enqueue reference objects in parallel"),
5284       _task(task)
5285   { }
5286 
5287   virtual void work(uint worker_id)
5288   {
5289     _task.work(worker_id);
5290   }
5291 };
5292 
5293 CMSParKeepAliveClosure::CMSParKeepAliveClosure(CMSCollector* collector,
5294   MemRegion span, CMSBitMap* bit_map, OopTaskQueue* work_queue):
5295    _span(span),
5296    _bit_map(bit_map),
5297    _work_queue(work_queue),
5298    _mark_and_push(collector, span, bit_map, work_queue),
5299    _low_water_mark(MIN2((work_queue->max_elems()/4),
5300                         ((uint)CMSWorkQueueDrainThreshold * ParallelGCThreads)))
5301 { }
5302 
5303 // . see if we can share work_queues with ParNew? XXX
5304 void CMSRefProcTaskProxy::do_work_steal(int i,
5305   CMSParDrainMarkingStackClosure* drain,
5306   CMSParKeepAliveClosure* keep_alive,
5307   int* seed) {
5308   OopTaskQueue* work_q = work_queue(i);
5309   NOT_PRODUCT(int num_steals = 0;)
5310   oop obj_to_scan;
5311 
5312   while (true) {
5313     // Completely finish any left over work from (an) earlier round(s)
5314     drain->trim_queue(0);
5315     size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,
5316                                          (size_t)ParGCDesiredObjsFromOverflowList);
5317     // Now check if there's any work in the overflow list
5318     // Passing ParallelGCThreads as the third parameter, no_of_gc_threads,
5319     // only affects the number of attempts made to get work from the
5320     // overflow list and does not affect the number of workers.  Just
5321     // pass ParallelGCThreads so this behavior is unchanged.
5322     if (_collector->par_take_from_overflow_list(num_from_overflow_list,
5323                                                 work_q,
5324                                                 ParallelGCThreads)) {
5325       // Found something in global overflow list;
5326       // not yet ready to go stealing work from others.
5327       // We'd like to assert(work_q->size() != 0, ...)
5328       // because we just took work from the overflow list,
5329       // but of course we can't, since all of that might have
5330       // been already stolen from us.
5331       continue;
5332     }
5333     // Verify that we have no work before we resort to stealing
5334     assert(work_q->size() == 0, "Have work, shouldn't steal");
5335     // Try to steal from other queues that have work
5336     if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) {
5337       NOT_PRODUCT(num_steals++;)
5338       assert(obj_to_scan->is_oop(), "Oops, not an oop!");
5339       assert(_mark_bit_map->isMarked((HeapWord*)obj_to_scan), "Stole an unmarked oop?");
5340       // Do scanning work
5341       obj_to_scan->oop_iterate(keep_alive);
5342       // Loop around, finish this work, and try to steal some more
5343     } else if (terminator()->offer_termination()) {
5344       break;  // nirvana from the infinite cycle
5345     }
5346   }
5347   NOT_PRODUCT(
5348     if (PrintCMSStatistics != 0) {
5349       gclog_or_tty->print("\n\t(%d: stole %d oops)", i, num_steals);
5350     }
5351   )
5352 }
5353 
5354 void CMSRefProcTaskExecutor::execute(ProcessTask& task)
5355 {
5356   GenCollectedHeap* gch = GenCollectedHeap::heap();
5357   WorkGang* workers = gch->workers();
5358   assert(workers != NULL, "Need parallel worker threads.");
5359   CMSRefProcTaskProxy rp_task(task, &_collector,
5360                               _collector.ref_processor()->span(),
5361                               _collector.markBitMap(),
5362                               workers, _collector.task_queues());
5363   workers->run_task(&rp_task);
5364 }
5365 
5366 void CMSRefProcTaskExecutor::execute(EnqueueTask& task)
5367 {
5368 
5369   GenCollectedHeap* gch = GenCollectedHeap::heap();
5370   WorkGang* workers = gch->workers();
5371   assert(workers != NULL, "Need parallel worker threads.");
5372   CMSRefEnqueueTaskProxy enq_task(task);
5373   workers->run_task(&enq_task);
5374 }
5375 
5376 void CMSCollector::refProcessingWork() {
5377   ResourceMark rm;
5378   HandleMark   hm;
5379 
5380   ReferenceProcessor* rp = ref_processor();
5381   assert(rp->span().equals(_span), "Spans should be equal");
5382   assert(!rp->enqueuing_is_done(), "Enqueuing should not be complete");
5383   // Process weak references.
5384   rp->setup_policy(false);
5385   verify_work_stacks_empty();
5386 
5387   CMSKeepAliveClosure cmsKeepAliveClosure(this, _span, &_markBitMap,
5388                                           &_markStack, false /* !preclean */);
5389   CMSDrainMarkingStackClosure cmsDrainMarkingStackClosure(this,
5390                                 _span, &_markBitMap, &_markStack,
5391                                 &cmsKeepAliveClosure, false /* !preclean */);
5392   {
5393     GCTraceTime t("weak refs processing", PrintGCDetails, false, _gc_timer_cm);
5394 
5395     ReferenceProcessorStats stats;
5396     if (rp->processing_is_mt()) {
5397       // Set the degree of MT here.  If the discovery is done MT, there
5398       // may have been a different number of threads doing the discovery
5399       // and a different number of discovered lists may have Ref objects.
5400       // That is OK as long as the Reference lists are balanced (see
5401       // balance_all_queues() and balance_queues()).
5402       GenCollectedHeap* gch = GenCollectedHeap::heap();
5403       uint active_workers = ParallelGCThreads;
5404       WorkGang* workers = gch->workers();
5405       if (workers != NULL) {
5406         active_workers = workers->active_workers();
5407         // The expectation is that active_workers will have already
5408         // been set to a reasonable value.  If it has not been set,
5409         // investigate.
5410         assert(active_workers > 0, "Should have been set during scavenge");
5411       }
5412       rp->set_active_mt_degree(active_workers);
5413       CMSRefProcTaskExecutor task_executor(*this);
5414       stats = rp->process_discovered_references(&_is_alive_closure,
5415                                         &cmsKeepAliveClosure,
5416                                         &cmsDrainMarkingStackClosure,
5417                                         &task_executor,
5418                                         _gc_timer_cm);
5419     } else {
5420       stats = rp->process_discovered_references(&_is_alive_closure,
5421                                         &cmsKeepAliveClosure,
5422                                         &cmsDrainMarkingStackClosure,
5423                                         NULL,
5424                                         _gc_timer_cm);
5425     }
5426     _gc_tracer_cm->report_gc_reference_stats(stats);
5427 
5428   }
5429 
5430   // This is the point where the entire marking should have completed.
5431   verify_work_stacks_empty();
5432 
5433   if (should_unload_classes()) {
5434     {
5435       GCTraceTime t("class unloading", PrintGCDetails, false, _gc_timer_cm);
5436 
5437       // Unload classes and purge the SystemDictionary.
5438       bool purged_class = SystemDictionary::do_unloading(&_is_alive_closure);
5439 
5440       // Unload nmethods.
5441       CodeCache::do_unloading(&_is_alive_closure, purged_class);
5442 
5443       // Prune dead klasses from subklass/sibling/implementor lists.
5444       Klass::clean_weak_klass_links(&_is_alive_closure);
5445     }
5446 
5447     {
5448       GCTraceTime t("scrub symbol table", PrintGCDetails, false, _gc_timer_cm);
5449       // Clean up unreferenced symbols in symbol table.
5450       SymbolTable::unlink();
5451     }
5452 
5453     {
5454       GCTraceTime t("scrub string table", PrintGCDetails, false, _gc_timer_cm);
5455       // Delete entries for dead interned strings.
5456       StringTable::unlink(&_is_alive_closure);
5457     }
5458   }
5459 
5460 
5461   // Restore any preserved marks as a result of mark stack or
5462   // work queue overflow
5463   restore_preserved_marks_if_any();  // done single-threaded for now
5464 
5465   rp->set_enqueuing_is_done(true);
5466   if (rp->processing_is_mt()) {
5467     rp->balance_all_queues();
5468     CMSRefProcTaskExecutor task_executor(*this);
5469     rp->enqueue_discovered_references(&task_executor);
5470   } else {
5471     rp->enqueue_discovered_references(NULL);
5472   }
5473   rp->verify_no_references_recorded();
5474   assert(!rp->discovery_enabled(), "should have been disabled");
5475 }
5476 
5477 #ifndef PRODUCT
5478 void CMSCollector::check_correct_thread_executing() {
5479   Thread* t = Thread::current();
5480   // Only the VM thread or the CMS thread should be here.
5481   assert(t->is_ConcurrentGC_thread() || t->is_VM_thread(),
5482          "Unexpected thread type");
5483   // If this is the vm thread, the foreground process
5484   // should not be waiting.  Note that _foregroundGCIsActive is
5485   // true while the foreground collector is waiting.
5486   if (_foregroundGCShouldWait) {
5487     // We cannot be the VM thread
5488     assert(t->is_ConcurrentGC_thread(),
5489            "Should be CMS thread");
5490   } else {
5491     // We can be the CMS thread only if we are in a stop-world
5492     // phase of CMS collection.
5493     if (t->is_ConcurrentGC_thread()) {
5494       assert(_collectorState == InitialMarking ||
5495              _collectorState == FinalMarking,
5496              "Should be a stop-world phase");
5497       // The CMS thread should be holding the CMS_token.
5498       assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
5499              "Potential interference with concurrently "
5500              "executing VM thread");
5501     }
5502   }
5503 }
5504 #endif
5505 
5506 void CMSCollector::sweep() {
5507   assert(_collectorState == Sweeping, "just checking");
5508   check_correct_thread_executing();
5509   verify_work_stacks_empty();
5510   verify_overflow_empty();
5511   increment_sweep_count();
5512   TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause());
5513 
5514   _inter_sweep_timer.stop();
5515   _inter_sweep_estimate.sample(_inter_sweep_timer.seconds());
5516 
5517   assert(!_intra_sweep_timer.is_active(), "Should not be active");
5518   _intra_sweep_timer.reset();
5519   _intra_sweep_timer.start();
5520   {
5521     TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
5522     CMSPhaseAccounting pa(this, "sweep", !PrintGCDetails);
5523     // First sweep the old gen
5524     {
5525       CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock(),
5526                                bitMapLock());
5527       sweepWork(_cmsGen);
5528     }
5529 
5530     // Update Universe::_heap_*_at_gc figures.
5531     // We need all the free list locks to make the abstract state
5532     // transition from Sweeping to Resetting. See detailed note
5533     // further below.
5534     {
5535       CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock());
5536       // Update heap occupancy information which is used as
5537       // input to soft ref clearing policy at the next gc.
5538       Universe::update_heap_info_at_gc();
5539       _collectorState = Resizing;
5540     }
5541   }
5542   verify_work_stacks_empty();
5543   verify_overflow_empty();
5544 
5545   if (should_unload_classes()) {
5546     // Delay purge to the beginning of the next safepoint.  Metaspace::contains
5547     // requires that the virtual spaces are stable and not deleted.
5548     ClassLoaderDataGraph::set_should_purge(true);
5549   }
5550 
5551   _intra_sweep_timer.stop();
5552   _intra_sweep_estimate.sample(_intra_sweep_timer.seconds());
5553 
5554   _inter_sweep_timer.reset();
5555   _inter_sweep_timer.start();
5556 
5557   // We need to use a monotonically non-decreasing time in ms
5558   // or we will see time-warp warnings and os::javaTimeMillis()
5559   // does not guarantee monotonicity.
5560   jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;
5561   update_time_of_last_gc(now);
5562 
5563   // NOTE on abstract state transitions:
5564   // Mutators allocate-live and/or mark the mod-union table dirty
5565   // based on the state of the collection.  The former is done in
5566   // the interval [Marking, Sweeping] and the latter in the interval
5567   // [Marking, Sweeping).  Thus the transitions into the Marking state
5568   // and out of the Sweeping state must be synchronously visible
5569   // globally to the mutators.
5570   // The transition into the Marking state happens with the world
5571   // stopped so the mutators will globally see it.  Sweeping is
5572   // done asynchronously by the background collector so the transition
5573   // from the Sweeping state to the Resizing state must be done
5574   // under the freelistLock (as is the check for whether to
5575   // allocate-live and whether to dirty the mod-union table).
5576   assert(_collectorState == Resizing, "Change of collector state to"
5577     " Resizing must be done under the freelistLocks (plural)");
5578 
5579   // Now that sweeping has been completed, we clear
5580   // the incremental_collection_failed flag,
5581   // thus inviting a younger gen collection to promote into
5582   // this generation. If such a promotion may still fail,
5583   // the flag will be set again when a young collection is
5584   // attempted.
5585   GenCollectedHeap* gch = GenCollectedHeap::heap();
5586   gch->clear_incremental_collection_failed();  // Worth retrying as fresh space may have been freed up
5587   gch->update_full_collections_completed(_collection_count_start);
5588 }
5589 
5590 // FIX ME!!! Looks like this belongs in CFLSpace, with
5591 // CMSGen merely delegating to it.
5592 void ConcurrentMarkSweepGeneration::setNearLargestChunk() {
5593   double nearLargestPercent = FLSLargestBlockCoalesceProximity;
5594   HeapWord*  minAddr        = _cmsSpace->bottom();
5595   HeapWord*  largestAddr    =
5596     (HeapWord*) _cmsSpace->dictionary()->find_largest_dict();
5597   if (largestAddr == NULL) {
5598     // The dictionary appears to be empty.  In this case
5599     // try to coalesce at the end of the heap.
5600     largestAddr = _cmsSpace->end();
5601   }
5602   size_t largestOffset     = pointer_delta(largestAddr, minAddr);
5603   size_t nearLargestOffset =
5604     (size_t)((double)largestOffset * nearLargestPercent) - MinChunkSize;
5605   if (PrintFLSStatistics != 0) {
5606     gclog_or_tty->print_cr(
5607       "CMS: Large Block: " PTR_FORMAT ";"
5608       " Proximity: " PTR_FORMAT " -> " PTR_FORMAT,
5609       p2i(largestAddr),
5610       p2i(_cmsSpace->nearLargestChunk()), p2i(minAddr + nearLargestOffset));
5611   }
5612   _cmsSpace->set_nearLargestChunk(minAddr + nearLargestOffset);
5613 }
5614 
5615 bool ConcurrentMarkSweepGeneration::isNearLargestChunk(HeapWord* addr) {
5616   return addr >= _cmsSpace->nearLargestChunk();
5617 }
5618 
5619 FreeChunk* ConcurrentMarkSweepGeneration::find_chunk_at_end() {
5620   return _cmsSpace->find_chunk_at_end();
5621 }
5622 
5623 void ConcurrentMarkSweepGeneration::update_gc_stats(Generation* current_generation,
5624                                                     bool full) {
5625   // If the young generation has been collected, gather any statistics
5626   // that are of interest at this point.
5627   bool current_is_young = GenCollectedHeap::heap()->is_young_gen(current_generation);
5628   if (!full && current_is_young) {
5629     // Gather statistics on the young generation collection.
5630     collector()->stats().record_gc0_end(used());
5631   }
5632 }
5633 
5634 void CMSCollector::sweepWork(ConcurrentMarkSweepGeneration* old_gen) {
5635   // We iterate over the space(s) underlying this generation,
5636   // checking the mark bit map to see if the bits corresponding
5637   // to specific blocks are marked or not. Blocks that are
5638   // marked are live and are not swept up. All remaining blocks
5639   // are swept up, with coalescing on-the-fly as we sweep up
5640   // contiguous free and/or garbage blocks:
5641   // We need to ensure that the sweeper synchronizes with allocators
5642   // and stop-the-world collectors. In particular, the following
5643   // locks are used:
5644   // . CMS token: if this is held, a stop the world collection cannot occur
5645   // . freelistLock: if this is held no allocation can occur from this
5646   //                 generation by another thread
5647   // . bitMapLock: if this is held, no other thread can access or update
5648   //
5649 
5650   // Note that we need to hold the freelistLock if we use
5651   // block iterate below; else the iterator might go awry if
5652   // a mutator (or promotion) causes block contents to change
5653   // (for instance if the allocator divvies up a block).
5654   // If we hold the free list lock, for all practical purposes
5655   // young generation GC's can't occur (they'll usually need to
5656   // promote), so we might as well prevent all young generation
5657   // GC's while we do a sweeping step. For the same reason, we might
5658   // as well take the bit map lock for the entire duration
5659 
5660   // check that we hold the requisite locks
5661   assert(have_cms_token(), "Should hold cms token");
5662   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), "Should possess CMS token to sweep");
5663   assert_lock_strong(old_gen->freelistLock());
5664   assert_lock_strong(bitMapLock());
5665 
5666   assert(!_inter_sweep_timer.is_active(), "Was switched off in an outer context");
5667   assert(_intra_sweep_timer.is_active(),  "Was switched on  in an outer context");
5668   old_gen->cmsSpace()->beginSweepFLCensus((float)(_inter_sweep_timer.seconds()),
5669                                           _inter_sweep_estimate.padded_average(),
5670                                           _intra_sweep_estimate.padded_average());
5671   old_gen->setNearLargestChunk();
5672 
5673   {
5674     SweepClosure sweepClosure(this, old_gen, &_markBitMap, CMSYield);
5675     old_gen->cmsSpace()->blk_iterate_careful(&sweepClosure);
5676     // We need to free-up/coalesce garbage/blocks from a
5677     // co-terminal free run. This is done in the SweepClosure
5678     // destructor; so, do not remove this scope, else the
5679     // end-of-sweep-census below will be off by a little bit.
5680   }
5681   old_gen->cmsSpace()->sweep_completed();
5682   old_gen->cmsSpace()->endSweepFLCensus(sweep_count());
5683   if (should_unload_classes()) {                // unloaded classes this cycle,
5684     _concurrent_cycles_since_last_unload = 0;   // ... reset count
5685   } else {                                      // did not unload classes,
5686     _concurrent_cycles_since_last_unload++;     // ... increment count
5687   }
5688 }
5689 
5690 // Reset CMS data structures (for now just the marking bit map)
5691 // preparatory for the next cycle.
5692 void CMSCollector::reset_concurrent() {
5693   CMSTokenSyncWithLocks ts(true, bitMapLock());
5694 
5695   // If the state is not "Resetting", the foreground  thread
5696   // has done a collection and the resetting.
5697   if (_collectorState != Resetting) {
5698     assert(_collectorState == Idling, "The state should only change"
5699       " because the foreground collector has finished the collection");
5700     return;
5701   }
5702 
5703   // Clear the mark bitmap (no grey objects to start with)
5704   // for the next cycle.
5705   TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
5706   CMSPhaseAccounting cmspa(this, "reset", !PrintGCDetails);
5707 
5708   HeapWord* curAddr = _markBitMap.startWord();
5709   while (curAddr < _markBitMap.endWord()) {
5710     size_t remaining  = pointer_delta(_markBitMap.endWord(), curAddr);
5711     MemRegion chunk(curAddr, MIN2(CMSBitMapYieldQuantum, remaining));
5712     _markBitMap.clear_large_range(chunk);
5713     if (ConcurrentMarkSweepThread::should_yield() &&
5714         !foregroundGCIsActive() &&
5715         CMSYield) {
5716       assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
5717              "CMS thread should hold CMS token");
5718       assert_lock_strong(bitMapLock());
5719       bitMapLock()->unlock();
5720       ConcurrentMarkSweepThread::desynchronize(true);
5721       stopTimer();
5722       if (PrintCMSStatistics != 0) {
5723         incrementYields();
5724       }
5725 
5726       // See the comment in coordinator_yield()
5727       for (unsigned i = 0; i < CMSYieldSleepCount &&
5728                        ConcurrentMarkSweepThread::should_yield() &&
5729                        !CMSCollector::foregroundGCIsActive(); ++i) {
5730         os::sleep(Thread::current(), 1, false);
5731       }
5732 
5733       ConcurrentMarkSweepThread::synchronize(true);
5734       bitMapLock()->lock_without_safepoint_check();
5735       startTimer();
5736     }
5737     curAddr = chunk.end();
5738   }
5739   // A successful mostly concurrent collection has been done.
5740   // Because only the full (i.e., concurrent mode failure) collections
5741   // are being measured for gc overhead limits, clean the "near" flag
5742   // and count.
5743   size_policy()->reset_gc_overhead_limit_count();
5744   _collectorState = Idling;
5745 
5746   register_gc_end();
5747 }
5748 
5749 // Same as above but for STW paths
5750 void CMSCollector::reset_stw() {
5751   // already have the lock
5752   assert(_collectorState == Resetting, "just checking");
5753   assert_lock_strong(bitMapLock());
5754   GCIdMarkAndRestore gc_id_mark(_cmsThread->gc_id());
5755   _markBitMap.clear_all();
5756   _collectorState = Idling;
5757   register_gc_end();
5758 }
5759 
5760 void CMSCollector::do_CMS_operation(CMS_op_type op, GCCause::Cause gc_cause) {
5761   TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);
5762   GCTraceTime t(GCCauseString("GC", gc_cause), PrintGC, !PrintGCDetails, NULL);
5763   TraceCollectorStats tcs(counters());
5764 
5765   switch (op) {
5766     case CMS_op_checkpointRootsInitial: {
5767       SvcGCMarker sgcm(SvcGCMarker::OTHER);
5768       checkpointRootsInitial();
5769       if (PrintGC) {
5770         _cmsGen->printOccupancy("initial-mark");
5771       }
5772       break;
5773     }
5774     case CMS_op_checkpointRootsFinal: {
5775       SvcGCMarker sgcm(SvcGCMarker::OTHER);
5776       checkpointRootsFinal();
5777       if (PrintGC) {
5778         _cmsGen->printOccupancy("remark");
5779       }
5780       break;
5781     }
5782     default:
5783       fatal("No such CMS_op");
5784   }
5785 }
5786 
5787 #ifndef PRODUCT
5788 size_t const CMSCollector::skip_header_HeapWords() {
5789   return FreeChunk::header_size();
5790 }
5791 
5792 // Try and collect here conditions that should hold when
5793 // CMS thread is exiting. The idea is that the foreground GC
5794 // thread should not be blocked if it wants to terminate
5795 // the CMS thread and yet continue to run the VM for a while
5796 // after that.
5797 void CMSCollector::verify_ok_to_terminate() const {
5798   assert(Thread::current()->is_ConcurrentGC_thread(),
5799          "should be called by CMS thread");
5800   assert(!_foregroundGCShouldWait, "should be false");
5801   // We could check here that all the various low-level locks
5802   // are not held by the CMS thread, but that is overkill; see
5803   // also CMSThread::verify_ok_to_terminate() where the CGC_lock
5804   // is checked.
5805 }
5806 #endif
5807 
5808 size_t CMSCollector::block_size_using_printezis_bits(HeapWord* addr) const {
5809    assert(_markBitMap.isMarked(addr) && _markBitMap.isMarked(addr + 1),
5810           "missing Printezis mark?");
5811   HeapWord* nextOneAddr = _markBitMap.getNextMarkedWordAddress(addr + 2);
5812   size_t size = pointer_delta(nextOneAddr + 1, addr);
5813   assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
5814          "alignment problem");
5815   assert(size >= 3, "Necessary for Printezis marks to work");
5816   return size;
5817 }
5818 
5819 // A variant of the above (block_size_using_printezis_bits()) except
5820 // that we return 0 if the P-bits are not yet set.
5821 size_t CMSCollector::block_size_if_printezis_bits(HeapWord* addr) const {
5822   if (_markBitMap.isMarked(addr + 1)) {
5823     assert(_markBitMap.isMarked(addr), "P-bit can be set only for marked objects");
5824     HeapWord* nextOneAddr = _markBitMap.getNextMarkedWordAddress(addr + 2);
5825     size_t size = pointer_delta(nextOneAddr + 1, addr);
5826     assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
5827            "alignment problem");
5828     assert(size >= 3, "Necessary for Printezis marks to work");
5829     return size;
5830   }
5831   return 0;
5832 }
5833 
5834 HeapWord* CMSCollector::next_card_start_after_block(HeapWord* addr) const {
5835   size_t sz = 0;
5836   oop p = (oop)addr;
5837   if (p->klass_or_null() != NULL) {
5838     sz = CompactibleFreeListSpace::adjustObjectSize(p->size());
5839   } else {
5840     sz = block_size_using_printezis_bits(addr);
5841   }
5842   assert(sz > 0, "size must be nonzero");
5843   HeapWord* next_block = addr + sz;
5844   HeapWord* next_card  = (HeapWord*)round_to((uintptr_t)next_block,
5845                                              CardTableModRefBS::card_size);
5846   assert(round_down((uintptr_t)addr,      CardTableModRefBS::card_size) <
5847          round_down((uintptr_t)next_card, CardTableModRefBS::card_size),
5848          "must be different cards");
5849   return next_card;
5850 }
5851 
5852 
5853 // CMS Bit Map Wrapper /////////////////////////////////////////
5854 
5855 // Construct a CMS bit map infrastructure, but don't create the
5856 // bit vector itself. That is done by a separate call CMSBitMap::allocate()
5857 // further below.
5858 CMSBitMap::CMSBitMap(int shifter, int mutex_rank, const char* mutex_name):
5859   _bm(),
5860   _shifter(shifter),
5861   _lock(mutex_rank >= 0 ? new Mutex(mutex_rank, mutex_name, true,
5862                                     Monitor::_safepoint_check_sometimes) : NULL)
5863 {
5864   _bmStartWord = 0;
5865   _bmWordSize  = 0;
5866 }
5867 
5868 bool CMSBitMap::allocate(MemRegion mr) {
5869   _bmStartWord = mr.start();
5870   _bmWordSize  = mr.word_size();
5871   ReservedSpace brs(ReservedSpace::allocation_align_size_up(
5872                      (_bmWordSize >> (_shifter + LogBitsPerByte)) + 1));
5873   if (!brs.is_reserved()) {
5874     warning("CMS bit map allocation failure");
5875     return false;
5876   }
5877   // For now we'll just commit all of the bit map up front.
5878   // Later on we'll try to be more parsimonious with swap.
5879   if (!_virtual_space.initialize(brs, brs.size())) {
5880     warning("CMS bit map backing store failure");
5881     return false;
5882   }
5883   assert(_virtual_space.committed_size() == brs.size(),
5884          "didn't reserve backing store for all of CMS bit map?");
5885   _bm.set_map((BitMap::bm_word_t*)_virtual_space.low());
5886   assert(_virtual_space.committed_size() << (_shifter + LogBitsPerByte) >=
5887          _bmWordSize, "inconsistency in bit map sizing");
5888   _bm.set_size(_bmWordSize >> _shifter);
5889 
5890   // bm.clear(); // can we rely on getting zero'd memory? verify below
5891   assert(isAllClear(),
5892          "Expected zero'd memory from ReservedSpace constructor");
5893   assert(_bm.size() == heapWordDiffToOffsetDiff(sizeInWords()),
5894          "consistency check");
5895   return true;
5896 }
5897 
5898 void CMSBitMap::dirty_range_iterate_clear(MemRegion mr, MemRegionClosure* cl) {
5899   HeapWord *next_addr, *end_addr, *last_addr;
5900   assert_locked();
5901   assert(covers(mr), "out-of-range error");
5902   // XXX assert that start and end are appropriately aligned
5903   for (next_addr = mr.start(), end_addr = mr.end();
5904        next_addr < end_addr; next_addr = last_addr) {
5905     MemRegion dirty_region = getAndClearMarkedRegion(next_addr, end_addr);
5906     last_addr = dirty_region.end();
5907     if (!dirty_region.is_empty()) {
5908       cl->do_MemRegion(dirty_region);
5909     } else {
5910       assert(last_addr == end_addr, "program logic");
5911       return;
5912     }
5913   }
5914 }
5915 
5916 void CMSBitMap::print_on_error(outputStream* st, const char* prefix) const {
5917   _bm.print_on_error(st, prefix);
5918 }
5919 
5920 #ifndef PRODUCT
5921 void CMSBitMap::assert_locked() const {
5922   CMSLockVerifier::assert_locked(lock());
5923 }
5924 
5925 bool CMSBitMap::covers(MemRegion mr) const {
5926   // assert(_bm.map() == _virtual_space.low(), "map inconsistency");
5927   assert((size_t)_bm.size() == (_bmWordSize >> _shifter),
5928          "size inconsistency");
5929   return (mr.start() >= _bmStartWord) &&
5930          (mr.end()   <= endWord());
5931 }
5932 
5933 bool CMSBitMap::covers(HeapWord* start, size_t size) const {
5934     return (start >= _bmStartWord && (start + size) <= endWord());
5935 }
5936 
5937 void CMSBitMap::verifyNoOneBitsInRange(HeapWord* left, HeapWord* right) {
5938   // verify that there are no 1 bits in the interval [left, right)
5939   FalseBitMapClosure falseBitMapClosure;
5940   iterate(&falseBitMapClosure, left, right);
5941 }
5942 
5943 void CMSBitMap::region_invariant(MemRegion mr)
5944 {
5945   assert_locked();
5946   // mr = mr.intersection(MemRegion(_bmStartWord, _bmWordSize));
5947   assert(!mr.is_empty(), "unexpected empty region");
5948   assert(covers(mr), "mr should be covered by bit map");
5949   // convert address range into offset range
5950   size_t start_ofs = heapWordToOffset(mr.start());
5951   // Make sure that end() is appropriately aligned
5952   assert(mr.end() == (HeapWord*)round_to((intptr_t)mr.end(),
5953                         (1 << (_shifter+LogHeapWordSize))),
5954          "Misaligned mr.end()");
5955   size_t end_ofs   = heapWordToOffset(mr.end());
5956   assert(end_ofs > start_ofs, "Should mark at least one bit");
5957 }
5958 
5959 #endif
5960 
5961 bool CMSMarkStack::allocate(size_t size) {
5962   // allocate a stack of the requisite depth
5963   ReservedSpace rs(ReservedSpace::allocation_align_size_up(
5964                    size * sizeof(oop)));
5965   if (!rs.is_reserved()) {
5966     warning("CMSMarkStack allocation failure");
5967     return false;
5968   }
5969   if (!_virtual_space.initialize(rs, rs.size())) {
5970     warning("CMSMarkStack backing store failure");
5971     return false;
5972   }
5973   assert(_virtual_space.committed_size() == rs.size(),
5974          "didn't reserve backing store for all of CMS stack?");
5975   _base = (oop*)(_virtual_space.low());
5976   _index = 0;
5977   _capacity = size;
5978   NOT_PRODUCT(_max_depth = 0);
5979   return true;
5980 }
5981 
5982 // XXX FIX ME !!! In the MT case we come in here holding a
5983 // leaf lock. For printing we need to take a further lock
5984 // which has lower rank. We need to recalibrate the two
5985 // lock-ranks involved in order to be able to print the
5986 // messages below. (Or defer the printing to the caller.
5987 // For now we take the expedient path of just disabling the
5988 // messages for the problematic case.)
5989 void CMSMarkStack::expand() {
5990   assert(_capacity <= MarkStackSizeMax, "stack bigger than permitted");
5991   if (_capacity == MarkStackSizeMax) {
5992     if (_hit_limit++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) {
5993       // We print a warning message only once per CMS cycle.
5994       gclog_or_tty->print_cr(" (benign) Hit CMSMarkStack max size limit");
5995     }
5996     return;
5997   }
5998   // Double capacity if possible
5999   size_t new_capacity = MIN2(_capacity*2, MarkStackSizeMax);
6000   // Do not give up existing stack until we have managed to
6001   // get the double capacity that we desired.
6002   ReservedSpace rs(ReservedSpace::allocation_align_size_up(
6003                    new_capacity * sizeof(oop)));
6004   if (rs.is_reserved()) {
6005     // Release the backing store associated with old stack
6006     _virtual_space.release();
6007     // Reinitialize virtual space for new stack
6008     if (!_virtual_space.initialize(rs, rs.size())) {
6009       fatal("Not enough swap for expanded marking stack");
6010     }
6011     _base = (oop*)(_virtual_space.low());
6012     _index = 0;
6013     _capacity = new_capacity;
6014   } else if (_failed_double++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) {
6015     // Failed to double capacity, continue;
6016     // we print a detail message only once per CMS cycle.
6017     gclog_or_tty->print(" (benign) Failed to expand marking stack from " SIZE_FORMAT "K to "
6018             SIZE_FORMAT "K",
6019             _capacity / K, new_capacity / K);
6020   }
6021 }
6022 
6023 
6024 // Closures
6025 // XXX: there seems to be a lot of code  duplication here;
6026 // should refactor and consolidate common code.
6027 
6028 // This closure is used to mark refs into the CMS generation in
6029 // the CMS bit map. Called at the first checkpoint. This closure
6030 // assumes that we do not need to re-mark dirty cards; if the CMS
6031 // generation on which this is used is not an oldest
6032 // generation then this will lose younger_gen cards!
6033 
6034 MarkRefsIntoClosure::MarkRefsIntoClosure(
6035   MemRegion span, CMSBitMap* bitMap):
6036     _span(span),
6037     _bitMap(bitMap)
6038 {
6039   assert(ref_processor() == NULL, "deliberately left NULL");
6040   assert(_bitMap->covers(_span), "_bitMap/_span mismatch");
6041 }
6042 
6043 void MarkRefsIntoClosure::do_oop(oop obj) {
6044   // if p points into _span, then mark corresponding bit in _markBitMap
6045   assert(obj->is_oop(), "expected an oop");
6046   HeapWord* addr = (HeapWord*)obj;
6047   if (_span.contains(addr)) {
6048     // this should be made more efficient
6049     _bitMap->mark(addr);
6050   }
6051 }
6052 
6053 void MarkRefsIntoClosure::do_oop(oop* p)       { MarkRefsIntoClosure::do_oop_work(p); }
6054 void MarkRefsIntoClosure::do_oop(narrowOop* p) { MarkRefsIntoClosure::do_oop_work(p); }
6055 
6056 Par_MarkRefsIntoClosure::Par_MarkRefsIntoClosure(
6057   MemRegion span, CMSBitMap* bitMap):
6058     _span(span),
6059     _bitMap(bitMap)
6060 {
6061   assert(ref_processor() == NULL, "deliberately left NULL");
6062   assert(_bitMap->covers(_span), "_bitMap/_span mismatch");
6063 }
6064 
6065 void Par_MarkRefsIntoClosure::do_oop(oop obj) {
6066   // if p points into _span, then mark corresponding bit in _markBitMap
6067   assert(obj->is_oop(), "expected an oop");
6068   HeapWord* addr = (HeapWord*)obj;
6069   if (_span.contains(addr)) {
6070     // this should be made more efficient
6071     _bitMap->par_mark(addr);
6072   }
6073 }
6074 
6075 void Par_MarkRefsIntoClosure::do_oop(oop* p)       { Par_MarkRefsIntoClosure::do_oop_work(p); }
6076 void Par_MarkRefsIntoClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoClosure::do_oop_work(p); }
6077 
6078 // A variant of the above, used for CMS marking verification.
6079 MarkRefsIntoVerifyClosure::MarkRefsIntoVerifyClosure(
6080   MemRegion span, CMSBitMap* verification_bm, CMSBitMap* cms_bm):
6081     _span(span),
6082     _verification_bm(verification_bm),
6083     _cms_bm(cms_bm)
6084 {
6085   assert(ref_processor() == NULL, "deliberately left NULL");
6086   assert(_verification_bm->covers(_span), "_verification_bm/_span mismatch");
6087 }
6088 
6089 void MarkRefsIntoVerifyClosure::do_oop(oop obj) {
6090   // if p points into _span, then mark corresponding bit in _markBitMap
6091   assert(obj->is_oop(), "expected an oop");
6092   HeapWord* addr = (HeapWord*)obj;
6093   if (_span.contains(addr)) {
6094     _verification_bm->mark(addr);
6095     if (!_cms_bm->isMarked(addr)) {
6096       oop(addr)->print();
6097       gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)", p2i(addr));
6098       fatal("... aborting");
6099     }
6100   }
6101 }
6102 
6103 void MarkRefsIntoVerifyClosure::do_oop(oop* p)       { MarkRefsIntoVerifyClosure::do_oop_work(p); }
6104 void MarkRefsIntoVerifyClosure::do_oop(narrowOop* p) { MarkRefsIntoVerifyClosure::do_oop_work(p); }
6105 
6106 //////////////////////////////////////////////////
6107 // MarkRefsIntoAndScanClosure
6108 //////////////////////////////////////////////////
6109 
6110 MarkRefsIntoAndScanClosure::MarkRefsIntoAndScanClosure(MemRegion span,
6111                                                        ReferenceProcessor* rp,
6112                                                        CMSBitMap* bit_map,
6113                                                        CMSBitMap* mod_union_table,
6114                                                        CMSMarkStack*  mark_stack,
6115                                                        CMSCollector* collector,
6116                                                        bool should_yield,
6117                                                        bool concurrent_precleaning):
6118   _collector(collector),
6119   _span(span),
6120   _bit_map(bit_map),
6121   _mark_stack(mark_stack),
6122   _pushAndMarkClosure(collector, span, rp, bit_map, mod_union_table,
6123                       mark_stack, concurrent_precleaning),
6124   _yield(should_yield),
6125   _concurrent_precleaning(concurrent_precleaning),
6126   _freelistLock(NULL)
6127 {
6128   // FIXME: Should initialize in base class constructor.
6129   assert(rp != NULL, "ref_processor shouldn't be NULL");
6130   set_ref_processor_internal(rp);
6131 }
6132 
6133 // This closure is used to mark refs into the CMS generation at the
6134 // second (final) checkpoint, and to scan and transitively follow
6135 // the unmarked oops. It is also used during the concurrent precleaning
6136 // phase while scanning objects on dirty cards in the CMS generation.
6137 // The marks are made in the marking bit map and the marking stack is
6138 // used for keeping the (newly) grey objects during the scan.
6139 // The parallel version (Par_...) appears further below.
6140 void MarkRefsIntoAndScanClosure::do_oop(oop obj) {
6141   if (obj != NULL) {
6142     assert(obj->is_oop(), "expected an oop");
6143     HeapWord* addr = (HeapWord*)obj;
6144     assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)");
6145     assert(_collector->overflow_list_is_empty(),
6146            "overflow list should be empty");
6147     if (_span.contains(addr) &&
6148         !_bit_map->isMarked(addr)) {
6149       // mark bit map (object is now grey)
6150       _bit_map->mark(addr);
6151       // push on marking stack (stack should be empty), and drain the
6152       // stack by applying this closure to the oops in the oops popped
6153       // from the stack (i.e. blacken the grey objects)
6154       bool res = _mark_stack->push(obj);
6155       assert(res, "Should have space to push on empty stack");
6156       do {
6157         oop new_oop = _mark_stack->pop();
6158         assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop");
6159         assert(_bit_map->isMarked((HeapWord*)new_oop),
6160                "only grey objects on this stack");
6161         // iterate over the oops in this oop, marking and pushing
6162         // the ones in CMS heap (i.e. in _span).
6163         new_oop->oop_iterate(&_pushAndMarkClosure);
6164         // check if it's time to yield
6165         do_yield_check();
6166       } while (!_mark_stack->isEmpty() ||
6167                (!_concurrent_precleaning && take_from_overflow_list()));
6168         // if marking stack is empty, and we are not doing this
6169         // during precleaning, then check the overflow list
6170     }
6171     assert(_mark_stack->isEmpty(), "post-condition (eager drainage)");
6172     assert(_collector->overflow_list_is_empty(),
6173            "overflow list was drained above");
6174 
6175     assert(_collector->no_preserved_marks(),
6176            "All preserved marks should have been restored above");
6177   }
6178 }
6179 
6180 void MarkRefsIntoAndScanClosure::do_oop(oop* p)       { MarkRefsIntoAndScanClosure::do_oop_work(p); }
6181 void MarkRefsIntoAndScanClosure::do_oop(narrowOop* p) { MarkRefsIntoAndScanClosure::do_oop_work(p); }
6182 
6183 void MarkRefsIntoAndScanClosure::do_yield_work() {
6184   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
6185          "CMS thread should hold CMS token");
6186   assert_lock_strong(_freelistLock);
6187   assert_lock_strong(_bit_map->lock());
6188   // relinquish the free_list_lock and bitMaplock()
6189   _bit_map->lock()->unlock();
6190   _freelistLock->unlock();
6191   ConcurrentMarkSweepThread::desynchronize(true);
6192   _collector->stopTimer();
6193   if (PrintCMSStatistics != 0) {
6194     _collector->incrementYields();
6195   }
6196 
6197   // See the comment in coordinator_yield()
6198   for (unsigned i = 0;
6199        i < CMSYieldSleepCount &&
6200        ConcurrentMarkSweepThread::should_yield() &&
6201        !CMSCollector::foregroundGCIsActive();
6202        ++i) {
6203     os::sleep(Thread::current(), 1, false);
6204   }
6205 
6206   ConcurrentMarkSweepThread::synchronize(true);
6207   _freelistLock->lock_without_safepoint_check();
6208   _bit_map->lock()->lock_without_safepoint_check();
6209   _collector->startTimer();
6210 }
6211 
6212 ///////////////////////////////////////////////////////////
6213 // Par_MarkRefsIntoAndScanClosure: a parallel version of
6214 //                                 MarkRefsIntoAndScanClosure
6215 ///////////////////////////////////////////////////////////
6216 Par_MarkRefsIntoAndScanClosure::Par_MarkRefsIntoAndScanClosure(
6217   CMSCollector* collector, MemRegion span, ReferenceProcessor* rp,
6218   CMSBitMap* bit_map, OopTaskQueue* work_queue):
6219   _span(span),
6220   _bit_map(bit_map),
6221   _work_queue(work_queue),
6222   _low_water_mark(MIN2((work_queue->max_elems()/4),
6223                        ((uint)CMSWorkQueueDrainThreshold * ParallelGCThreads))),
6224   _par_pushAndMarkClosure(collector, span, rp, bit_map, work_queue)
6225 {
6226   // FIXME: Should initialize in base class constructor.
6227   assert(rp != NULL, "ref_processor shouldn't be NULL");
6228   set_ref_processor_internal(rp);
6229 }
6230 
6231 // This closure is used to mark refs into the CMS generation at the
6232 // second (final) checkpoint, and to scan and transitively follow
6233 // the unmarked oops. The marks are made in the marking bit map and
6234 // the work_queue is used for keeping the (newly) grey objects during
6235 // the scan phase whence they are also available for stealing by parallel
6236 // threads. Since the marking bit map is shared, updates are
6237 // synchronized (via CAS).
6238 void Par_MarkRefsIntoAndScanClosure::do_oop(oop obj) {
6239   if (obj != NULL) {
6240     // Ignore mark word because this could be an already marked oop
6241     // that may be chained at the end of the overflow list.
6242     assert(obj->is_oop(true), "expected an oop");
6243     HeapWord* addr = (HeapWord*)obj;
6244     if (_span.contains(addr) &&
6245         !_bit_map->isMarked(addr)) {
6246       // mark bit map (object will become grey):
6247       // It is possible for several threads to be
6248       // trying to "claim" this object concurrently;
6249       // the unique thread that succeeds in marking the
6250       // object first will do the subsequent push on
6251       // to the work queue (or overflow list).
6252       if (_bit_map->par_mark(addr)) {
6253         // push on work_queue (which may not be empty), and trim the
6254         // queue to an appropriate length by applying this closure to
6255         // the oops in the oops popped from the stack (i.e. blacken the
6256         // grey objects)
6257         bool res = _work_queue->push(obj);
6258         assert(res, "Low water mark should be less than capacity?");
6259         trim_queue(_low_water_mark);
6260       } // Else, another thread claimed the object
6261     }
6262   }
6263 }
6264 
6265 void Par_MarkRefsIntoAndScanClosure::do_oop(oop* p)       { Par_MarkRefsIntoAndScanClosure::do_oop_work(p); }
6266 void Par_MarkRefsIntoAndScanClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoAndScanClosure::do_oop_work(p); }
6267 
6268 // This closure is used to rescan the marked objects on the dirty cards
6269 // in the mod union table and the card table proper.
6270 size_t ScanMarkedObjectsAgainCarefullyClosure::do_object_careful_m(
6271   oop p, MemRegion mr) {
6272 
6273   size_t size = 0;
6274   HeapWord* addr = (HeapWord*)p;
6275   DEBUG_ONLY(_collector->verify_work_stacks_empty();)
6276   assert(_span.contains(addr), "we are scanning the CMS generation");
6277   // check if it's time to yield
6278   if (do_yield_check()) {
6279     // We yielded for some foreground stop-world work,
6280     // and we have been asked to abort this ongoing preclean cycle.
6281     return 0;
6282   }
6283   if (_bitMap->isMarked(addr)) {
6284     // it's marked; is it potentially uninitialized?
6285     if (p->klass_or_null() != NULL) {
6286         // an initialized object; ignore mark word in verification below
6287         // since we are running concurrent with mutators
6288         assert(p->is_oop(true), "should be an oop");
6289         if (p->is_objArray()) {
6290           // objArrays are precisely marked; restrict scanning
6291           // to dirty cards only.
6292           size = CompactibleFreeListSpace::adjustObjectSize(
6293                    p->oop_iterate_size(_scanningClosure, mr));
6294         } else {
6295           // A non-array may have been imprecisely marked; we need
6296           // to scan object in its entirety.
6297           size = CompactibleFreeListSpace::adjustObjectSize(
6298                    p->oop_iterate_size(_scanningClosure));
6299         }
6300         #ifdef ASSERT
6301           size_t direct_size =
6302             CompactibleFreeListSpace::adjustObjectSize(p->size());
6303           assert(size == direct_size, "Inconsistency in size");
6304           assert(size >= 3, "Necessary for Printezis marks to work");
6305           if (!_bitMap->isMarked(addr+1)) {
6306             _bitMap->verifyNoOneBitsInRange(addr+2, addr+size);
6307           } else {
6308             _bitMap->verifyNoOneBitsInRange(addr+2, addr+size-1);
6309             assert(_bitMap->isMarked(addr+size-1),
6310                    "inconsistent Printezis mark");
6311           }
6312         #endif // ASSERT
6313     } else {
6314       // An uninitialized object.
6315       assert(_bitMap->isMarked(addr+1), "missing Printezis mark?");
6316       HeapWord* nextOneAddr = _bitMap->getNextMarkedWordAddress(addr + 2);
6317       size = pointer_delta(nextOneAddr + 1, addr);
6318       assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
6319              "alignment problem");
6320       // Note that pre-cleaning needn't redirty the card. OopDesc::set_klass()
6321       // will dirty the card when the klass pointer is installed in the
6322       // object (signaling the completion of initialization).
6323     }
6324   } else {
6325     // Either a not yet marked object or an uninitialized object
6326     if (p->klass_or_null() == NULL) {
6327       // An uninitialized object, skip to the next card, since
6328       // we may not be able to read its P-bits yet.
6329       assert(size == 0, "Initial value");
6330     } else {
6331       // An object not (yet) reached by marking: we merely need to
6332       // compute its size so as to go look at the next block.
6333       assert(p->is_oop(true), "should be an oop");
6334       size = CompactibleFreeListSpace::adjustObjectSize(p->size());
6335     }
6336   }
6337   DEBUG_ONLY(_collector->verify_work_stacks_empty();)
6338   return size;
6339 }
6340 
6341 void ScanMarkedObjectsAgainCarefullyClosure::do_yield_work() {
6342   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
6343          "CMS thread should hold CMS token");
6344   assert_lock_strong(_freelistLock);
6345   assert_lock_strong(_bitMap->lock());
6346   // relinquish the free_list_lock and bitMaplock()
6347   _bitMap->lock()->unlock();
6348   _freelistLock->unlock();
6349   ConcurrentMarkSweepThread::desynchronize(true);
6350   _collector->stopTimer();
6351   if (PrintCMSStatistics != 0) {
6352     _collector->incrementYields();
6353   }
6354 
6355   // See the comment in coordinator_yield()
6356   for (unsigned i = 0; i < CMSYieldSleepCount &&
6357                    ConcurrentMarkSweepThread::should_yield() &&
6358                    !CMSCollector::foregroundGCIsActive(); ++i) {
6359     os::sleep(Thread::current(), 1, false);
6360   }
6361 
6362   ConcurrentMarkSweepThread::synchronize(true);
6363   _freelistLock->lock_without_safepoint_check();
6364   _bitMap->lock()->lock_without_safepoint_check();
6365   _collector->startTimer();
6366 }
6367 
6368 
6369 //////////////////////////////////////////////////////////////////
6370 // SurvivorSpacePrecleanClosure
6371 //////////////////////////////////////////////////////////////////
6372 // This (single-threaded) closure is used to preclean the oops in
6373 // the survivor spaces.
6374 size_t SurvivorSpacePrecleanClosure::do_object_careful(oop p) {
6375 
6376   HeapWord* addr = (HeapWord*)p;
6377   DEBUG_ONLY(_collector->verify_work_stacks_empty();)
6378   assert(!_span.contains(addr), "we are scanning the survivor spaces");
6379   assert(p->klass_or_null() != NULL, "object should be initialized");
6380   // an initialized object; ignore mark word in verification below
6381   // since we are running concurrent with mutators
6382   assert(p->is_oop(true), "should be an oop");
6383   // Note that we do not yield while we iterate over
6384   // the interior oops of p, pushing the relevant ones
6385   // on our marking stack.
6386   size_t size = p->oop_iterate_size(_scanning_closure);
6387   do_yield_check();
6388   // Observe that below, we do not abandon the preclean
6389   // phase as soon as we should; rather we empty the
6390   // marking stack before returning. This is to satisfy
6391   // some existing assertions. In general, it may be a
6392   // good idea to abort immediately and complete the marking
6393   // from the grey objects at a later time.
6394   while (!_mark_stack->isEmpty()) {
6395     oop new_oop = _mark_stack->pop();
6396     assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop");
6397     assert(_bit_map->isMarked((HeapWord*)new_oop),
6398            "only grey objects on this stack");
6399     // iterate over the oops in this oop, marking and pushing
6400     // the ones in CMS heap (i.e. in _span).
6401     new_oop->oop_iterate(_scanning_closure);
6402     // check if it's time to yield
6403     do_yield_check();
6404   }
6405   unsigned int after_count =
6406     GenCollectedHeap::heap()->total_collections();
6407   bool abort = (_before_count != after_count) ||
6408                _collector->should_abort_preclean();
6409   return abort ? 0 : size;
6410 }
6411 
6412 void SurvivorSpacePrecleanClosure::do_yield_work() {
6413   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
6414          "CMS thread should hold CMS token");
6415   assert_lock_strong(_bit_map->lock());
6416   // Relinquish the bit map lock
6417   _bit_map->lock()->unlock();
6418   ConcurrentMarkSweepThread::desynchronize(true);
6419   _collector->stopTimer();
6420   if (PrintCMSStatistics != 0) {
6421     _collector->incrementYields();
6422   }
6423 
6424   // See the comment in coordinator_yield()
6425   for (unsigned i = 0; i < CMSYieldSleepCount &&
6426                        ConcurrentMarkSweepThread::should_yield() &&
6427                        !CMSCollector::foregroundGCIsActive(); ++i) {
6428     os::sleep(Thread::current(), 1, false);
6429   }
6430 
6431   ConcurrentMarkSweepThread::synchronize(true);
6432   _bit_map->lock()->lock_without_safepoint_check();
6433   _collector->startTimer();
6434 }
6435 
6436 // This closure is used to rescan the marked objects on the dirty cards
6437 // in the mod union table and the card table proper. In the parallel
6438 // case, although the bitMap is shared, we do a single read so the
6439 // isMarked() query is "safe".
6440 bool ScanMarkedObjectsAgainClosure::do_object_bm(oop p, MemRegion mr) {
6441   // Ignore mark word because we are running concurrent with mutators
6442   assert(p->is_oop_or_null(true), "Expected an oop or NULL at " PTR_FORMAT, p2i(p));
6443   HeapWord* addr = (HeapWord*)p;
6444   assert(_span.contains(addr), "we are scanning the CMS generation");
6445   bool is_obj_array = false;
6446   #ifdef ASSERT
6447     if (!_parallel) {
6448       assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)");
6449       assert(_collector->overflow_list_is_empty(),
6450              "overflow list should be empty");
6451 
6452     }
6453   #endif // ASSERT
6454   if (_bit_map->isMarked(addr)) {
6455     // Obj arrays are precisely marked, non-arrays are not;
6456     // so we scan objArrays precisely and non-arrays in their
6457     // entirety.
6458     if (p->is_objArray()) {
6459       is_obj_array = true;
6460       if (_parallel) {
6461         p->oop_iterate(_par_scan_closure, mr);
6462       } else {
6463         p->oop_iterate(_scan_closure, mr);
6464       }
6465     } else {
6466       if (_parallel) {
6467         p->oop_iterate(_par_scan_closure);
6468       } else {
6469         p->oop_iterate(_scan_closure);
6470       }
6471     }
6472   }
6473   #ifdef ASSERT
6474     if (!_parallel) {
6475       assert(_mark_stack->isEmpty(), "post-condition (eager drainage)");
6476       assert(_collector->overflow_list_is_empty(),
6477              "overflow list should be empty");
6478 
6479     }
6480   #endif // ASSERT
6481   return is_obj_array;
6482 }
6483 
6484 MarkFromRootsClosure::MarkFromRootsClosure(CMSCollector* collector,
6485                         MemRegion span,
6486                         CMSBitMap* bitMap, CMSMarkStack*  markStack,
6487                         bool should_yield, bool verifying):
6488   _collector(collector),
6489   _span(span),
6490   _bitMap(bitMap),
6491   _mut(&collector->_modUnionTable),
6492   _markStack(markStack),
6493   _yield(should_yield),
6494   _skipBits(0)
6495 {
6496   assert(_markStack->isEmpty(), "stack should be empty");
6497   _finger = _bitMap->startWord();
6498   _threshold = _finger;
6499   assert(_collector->_restart_addr == NULL, "Sanity check");
6500   assert(_span.contains(_finger), "Out of bounds _finger?");
6501   DEBUG_ONLY(_verifying = verifying;)
6502 }
6503 
6504 void MarkFromRootsClosure::reset(HeapWord* addr) {
6505   assert(_markStack->isEmpty(), "would cause duplicates on stack");
6506   assert(_span.contains(addr), "Out of bounds _finger?");
6507   _finger = addr;
6508   _threshold = (HeapWord*)round_to(
6509                  (intptr_t)_finger, CardTableModRefBS::card_size);
6510 }
6511 
6512 // Should revisit to see if this should be restructured for
6513 // greater efficiency.
6514 bool MarkFromRootsClosure::do_bit(size_t offset) {
6515   if (_skipBits > 0) {
6516     _skipBits--;
6517     return true;
6518   }
6519   // convert offset into a HeapWord*
6520   HeapWord* addr = _bitMap->startWord() + offset;
6521   assert(_bitMap->endWord() && addr < _bitMap->endWord(),
6522          "address out of range");
6523   assert(_bitMap->isMarked(addr), "tautology");
6524   if (_bitMap->isMarked(addr+1)) {
6525     // this is an allocated but not yet initialized object
6526     assert(_skipBits == 0, "tautology");
6527     _skipBits = 2;  // skip next two marked bits ("Printezis-marks")
6528     oop p = oop(addr);
6529     if (p->klass_or_null() == NULL) {
6530       DEBUG_ONLY(if (!_verifying) {)
6531         // We re-dirty the cards on which this object lies and increase
6532         // the _threshold so that we'll come back to scan this object
6533         // during the preclean or remark phase. (CMSCleanOnEnter)
6534         if (CMSCleanOnEnter) {
6535           size_t sz = _collector->block_size_using_printezis_bits(addr);
6536           HeapWord* end_card_addr   = (HeapWord*)round_to(
6537                                          (intptr_t)(addr+sz), CardTableModRefBS::card_size);
6538           MemRegion redirty_range = MemRegion(addr, end_card_addr);
6539           assert(!redirty_range.is_empty(), "Arithmetical tautology");
6540           // Bump _threshold to end_card_addr; note that
6541           // _threshold cannot possibly exceed end_card_addr, anyhow.
6542           // This prevents future clearing of the card as the scan proceeds
6543           // to the right.
6544           assert(_threshold <= end_card_addr,
6545                  "Because we are just scanning into this object");
6546           if (_threshold < end_card_addr) {
6547             _threshold = end_card_addr;
6548           }
6549           if (p->klass_or_null() != NULL) {
6550             // Redirty the range of cards...
6551             _mut->mark_range(redirty_range);
6552           } // ...else the setting of klass will dirty the card anyway.
6553         }
6554       DEBUG_ONLY(})
6555       return true;
6556     }
6557   }
6558   scanOopsInOop(addr);
6559   return true;
6560 }
6561 
6562 // We take a break if we've been at this for a while,
6563 // so as to avoid monopolizing the locks involved.
6564 void MarkFromRootsClosure::do_yield_work() {
6565   // First give up the locks, then yield, then re-lock
6566   // We should probably use a constructor/destructor idiom to
6567   // do this unlock/lock or modify the MutexUnlocker class to
6568   // serve our purpose. XXX
6569   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
6570          "CMS thread should hold CMS token");
6571   assert_lock_strong(_bitMap->lock());
6572   _bitMap->lock()->unlock();
6573   ConcurrentMarkSweepThread::desynchronize(true);
6574   _collector->stopTimer();
6575   if (PrintCMSStatistics != 0) {
6576     _collector->incrementYields();
6577   }
6578 
6579   // See the comment in coordinator_yield()
6580   for (unsigned i = 0; i < CMSYieldSleepCount &&
6581                        ConcurrentMarkSweepThread::should_yield() &&
6582                        !CMSCollector::foregroundGCIsActive(); ++i) {
6583     os::sleep(Thread::current(), 1, false);
6584   }
6585 
6586   ConcurrentMarkSweepThread::synchronize(true);
6587   _bitMap->lock()->lock_without_safepoint_check();
6588   _collector->startTimer();
6589 }
6590 
6591 void MarkFromRootsClosure::scanOopsInOop(HeapWord* ptr) {
6592   assert(_bitMap->isMarked(ptr), "expected bit to be set");
6593   assert(_markStack->isEmpty(),
6594          "should drain stack to limit stack usage");
6595   // convert ptr to an oop preparatory to scanning
6596   oop obj = oop(ptr);
6597   // Ignore mark word in verification below, since we
6598   // may be running concurrent with mutators.
6599   assert(obj->is_oop(true), "should be an oop");
6600   assert(_finger <= ptr, "_finger runneth ahead");
6601   // advance the finger to right end of this object
6602   _finger = ptr + obj->size();
6603   assert(_finger > ptr, "we just incremented it above");
6604   // On large heaps, it may take us some time to get through
6605   // the marking phase. During
6606   // this time it's possible that a lot of mutations have
6607   // accumulated in the card table and the mod union table --
6608   // these mutation records are redundant until we have
6609   // actually traced into the corresponding card.
6610   // Here, we check whether advancing the finger would make
6611   // us cross into a new card, and if so clear corresponding
6612   // cards in the MUT (preclean them in the card-table in the
6613   // future).
6614 
6615   DEBUG_ONLY(if (!_verifying) {)
6616     // The clean-on-enter optimization is disabled by default,
6617     // until we fix 6178663.
6618     if (CMSCleanOnEnter && (_finger > _threshold)) {
6619       // [_threshold, _finger) represents the interval
6620       // of cards to be cleared  in MUT (or precleaned in card table).
6621       // The set of cards to be cleared is all those that overlap
6622       // with the interval [_threshold, _finger); note that
6623       // _threshold is always kept card-aligned but _finger isn't
6624       // always card-aligned.
6625       HeapWord* old_threshold = _threshold;
6626       assert(old_threshold == (HeapWord*)round_to(
6627               (intptr_t)old_threshold, CardTableModRefBS::card_size),
6628              "_threshold should always be card-aligned");
6629       _threshold = (HeapWord*)round_to(
6630                      (intptr_t)_finger, CardTableModRefBS::card_size);
6631       MemRegion mr(old_threshold, _threshold);
6632       assert(!mr.is_empty(), "Control point invariant");
6633       assert(_span.contains(mr), "Should clear within span");
6634       _mut->clear_range(mr);
6635     }
6636   DEBUG_ONLY(})
6637   // Note: the finger doesn't advance while we drain
6638   // the stack below.
6639   PushOrMarkClosure pushOrMarkClosure(_collector,
6640                                       _span, _bitMap, _markStack,
6641                                       _finger, this);
6642   bool res = _markStack->push(obj);
6643   assert(res, "Empty non-zero size stack should have space for single push");
6644   while (!_markStack->isEmpty()) {
6645     oop new_oop = _markStack->pop();
6646     // Skip verifying header mark word below because we are
6647     // running concurrent with mutators.
6648     assert(new_oop->is_oop(true), "Oops! expected to pop an oop");
6649     // now scan this oop's oops
6650     new_oop->oop_iterate(&pushOrMarkClosure);
6651     do_yield_check();
6652   }
6653   assert(_markStack->isEmpty(), "tautology, emphasizing post-condition");
6654 }
6655 
6656 Par_MarkFromRootsClosure::Par_MarkFromRootsClosure(CMSConcMarkingTask* task,
6657                        CMSCollector* collector, MemRegion span,
6658                        CMSBitMap* bit_map,
6659                        OopTaskQueue* work_queue,
6660                        CMSMarkStack*  overflow_stack):
6661   _collector(collector),
6662   _whole_span(collector->_span),
6663   _span(span),
6664   _bit_map(bit_map),
6665   _mut(&collector->_modUnionTable),
6666   _work_queue(work_queue),
6667   _overflow_stack(overflow_stack),
6668   _skip_bits(0),
6669   _task(task)
6670 {
6671   assert(_work_queue->size() == 0, "work_queue should be empty");
6672   _finger = span.start();
6673   _threshold = _finger;     // XXX Defer clear-on-enter optimization for now
6674   assert(_span.contains(_finger), "Out of bounds _finger?");
6675 }
6676 
6677 // Should revisit to see if this should be restructured for
6678 // greater efficiency.
6679 bool Par_MarkFromRootsClosure::do_bit(size_t offset) {
6680   if (_skip_bits > 0) {
6681     _skip_bits--;
6682     return true;
6683   }
6684   // convert offset into a HeapWord*
6685   HeapWord* addr = _bit_map->startWord() + offset;
6686   assert(_bit_map->endWord() && addr < _bit_map->endWord(),
6687          "address out of range");
6688   assert(_bit_map->isMarked(addr), "tautology");
6689   if (_bit_map->isMarked(addr+1)) {
6690     // this is an allocated object that might not yet be initialized
6691     assert(_skip_bits == 0, "tautology");
6692     _skip_bits = 2;  // skip next two marked bits ("Printezis-marks")
6693     oop p = oop(addr);
6694     if (p->klass_or_null() == NULL) {
6695       // in the case of Clean-on-Enter optimization, redirty card
6696       // and avoid clearing card by increasing  the threshold.
6697       return true;
6698     }
6699   }
6700   scan_oops_in_oop(addr);
6701   return true;
6702 }
6703 
6704 void Par_MarkFromRootsClosure::scan_oops_in_oop(HeapWord* ptr) {
6705   assert(_bit_map->isMarked(ptr), "expected bit to be set");
6706   // Should we assert that our work queue is empty or
6707   // below some drain limit?
6708   assert(_work_queue->size() == 0,
6709          "should drain stack to limit stack usage");
6710   // convert ptr to an oop preparatory to scanning
6711   oop obj = oop(ptr);
6712   // Ignore mark word in verification below, since we
6713   // may be running concurrent with mutators.
6714   assert(obj->is_oop(true), "should be an oop");
6715   assert(_finger <= ptr, "_finger runneth ahead");
6716   // advance the finger to right end of this object
6717   _finger = ptr + obj->size();
6718   assert(_finger > ptr, "we just incremented it above");
6719   // On large heaps, it may take us some time to get through
6720   // the marking phase. During
6721   // this time it's possible that a lot of mutations have
6722   // accumulated in the card table and the mod union table --
6723   // these mutation records are redundant until we have
6724   // actually traced into the corresponding card.
6725   // Here, we check whether advancing the finger would make
6726   // us cross into a new card, and if so clear corresponding
6727   // cards in the MUT (preclean them in the card-table in the
6728   // future).
6729 
6730   // The clean-on-enter optimization is disabled by default,
6731   // until we fix 6178663.
6732   if (CMSCleanOnEnter && (_finger > _threshold)) {
6733     // [_threshold, _finger) represents the interval
6734     // of cards to be cleared  in MUT (or precleaned in card table).
6735     // The set of cards to be cleared is all those that overlap
6736     // with the interval [_threshold, _finger); note that
6737     // _threshold is always kept card-aligned but _finger isn't
6738     // always card-aligned.
6739     HeapWord* old_threshold = _threshold;
6740     assert(old_threshold == (HeapWord*)round_to(
6741             (intptr_t)old_threshold, CardTableModRefBS::card_size),
6742            "_threshold should always be card-aligned");
6743     _threshold = (HeapWord*)round_to(
6744                    (intptr_t)_finger, CardTableModRefBS::card_size);
6745     MemRegion mr(old_threshold, _threshold);
6746     assert(!mr.is_empty(), "Control point invariant");
6747     assert(_span.contains(mr), "Should clear within span"); // _whole_span ??
6748     _mut->clear_range(mr);
6749   }
6750 
6751   // Note: the local finger doesn't advance while we drain
6752   // the stack below, but the global finger sure can and will.
6753   HeapWord** gfa = _task->global_finger_addr();
6754   Par_PushOrMarkClosure pushOrMarkClosure(_collector,
6755                                       _span, _bit_map,
6756                                       _work_queue,
6757                                       _overflow_stack,
6758                                       _finger,
6759                                       gfa, this);
6760   bool res = _work_queue->push(obj);   // overflow could occur here
6761   assert(res, "Will hold once we use workqueues");
6762   while (true) {
6763     oop new_oop;
6764     if (!_work_queue->pop_local(new_oop)) {
6765       // We emptied our work_queue; check if there's stuff that can
6766       // be gotten from the overflow stack.
6767       if (CMSConcMarkingTask::get_work_from_overflow_stack(
6768             _overflow_stack, _work_queue)) {
6769         do_yield_check();
6770         continue;
6771       } else {  // done
6772         break;
6773       }
6774     }
6775     // Skip verifying header mark word below because we are
6776     // running concurrent with mutators.
6777     assert(new_oop->is_oop(true), "Oops! expected to pop an oop");
6778     // now scan this oop's oops
6779     new_oop->oop_iterate(&pushOrMarkClosure);
6780     do_yield_check();
6781   }
6782   assert(_work_queue->size() == 0, "tautology, emphasizing post-condition");
6783 }
6784 
6785 // Yield in response to a request from VM Thread or
6786 // from mutators.
6787 void Par_MarkFromRootsClosure::do_yield_work() {
6788   assert(_task != NULL, "sanity");
6789   _task->yield();
6790 }
6791 
6792 // A variant of the above used for verifying CMS marking work.
6793 MarkFromRootsVerifyClosure::MarkFromRootsVerifyClosure(CMSCollector* collector,
6794                         MemRegion span,
6795                         CMSBitMap* verification_bm, CMSBitMap* cms_bm,
6796                         CMSMarkStack*  mark_stack):
6797   _collector(collector),
6798   _span(span),
6799   _verification_bm(verification_bm),
6800   _cms_bm(cms_bm),
6801   _mark_stack(mark_stack),
6802   _pam_verify_closure(collector, span, verification_bm, cms_bm,
6803                       mark_stack)
6804 {
6805   assert(_mark_stack->isEmpty(), "stack should be empty");
6806   _finger = _verification_bm->startWord();
6807   assert(_collector->_restart_addr == NULL, "Sanity check");
6808   assert(_span.contains(_finger), "Out of bounds _finger?");
6809 }
6810 
6811 void MarkFromRootsVerifyClosure::reset(HeapWord* addr) {
6812   assert(_mark_stack->isEmpty(), "would cause duplicates on stack");
6813   assert(_span.contains(addr), "Out of bounds _finger?");
6814   _finger = addr;
6815 }
6816 
6817 // Should revisit to see if this should be restructured for
6818 // greater efficiency.
6819 bool MarkFromRootsVerifyClosure::do_bit(size_t offset) {
6820   // convert offset into a HeapWord*
6821   HeapWord* addr = _verification_bm->startWord() + offset;
6822   assert(_verification_bm->endWord() && addr < _verification_bm->endWord(),
6823          "address out of range");
6824   assert(_verification_bm->isMarked(addr), "tautology");
6825   assert(_cms_bm->isMarked(addr), "tautology");
6826 
6827   assert(_mark_stack->isEmpty(),
6828          "should drain stack to limit stack usage");
6829   // convert addr to an oop preparatory to scanning
6830   oop obj = oop(addr);
6831   assert(obj->is_oop(), "should be an oop");
6832   assert(_finger <= addr, "_finger runneth ahead");
6833   // advance the finger to right end of this object
6834   _finger = addr + obj->size();
6835   assert(_finger > addr, "we just incremented it above");
6836   // Note: the finger doesn't advance while we drain
6837   // the stack below.
6838   bool res = _mark_stack->push(obj);
6839   assert(res, "Empty non-zero size stack should have space for single push");
6840   while (!_mark_stack->isEmpty()) {
6841     oop new_oop = _mark_stack->pop();
6842     assert(new_oop->is_oop(), "Oops! expected to pop an oop");
6843     // now scan this oop's oops
6844     new_oop->oop_iterate(&_pam_verify_closure);
6845   }
6846   assert(_mark_stack->isEmpty(), "tautology, emphasizing post-condition");
6847   return true;
6848 }
6849 
6850 PushAndMarkVerifyClosure::PushAndMarkVerifyClosure(
6851   CMSCollector* collector, MemRegion span,
6852   CMSBitMap* verification_bm, CMSBitMap* cms_bm,
6853   CMSMarkStack*  mark_stack):
6854   MetadataAwareOopClosure(collector->ref_processor()),
6855   _collector(collector),
6856   _span(span),
6857   _verification_bm(verification_bm),
6858   _cms_bm(cms_bm),
6859   _mark_stack(mark_stack)
6860 { }
6861 
6862 void PushAndMarkVerifyClosure::do_oop(oop* p)       { PushAndMarkVerifyClosure::do_oop_work(p); }
6863 void PushAndMarkVerifyClosure::do_oop(narrowOop* p) { PushAndMarkVerifyClosure::do_oop_work(p); }
6864 
6865 // Upon stack overflow, we discard (part of) the stack,
6866 // remembering the least address amongst those discarded
6867 // in CMSCollector's _restart_address.
6868 void PushAndMarkVerifyClosure::handle_stack_overflow(HeapWord* lost) {
6869   // Remember the least grey address discarded
6870   HeapWord* ra = (HeapWord*)_mark_stack->least_value(lost);
6871   _collector->lower_restart_addr(ra);
6872   _mark_stack->reset();  // discard stack contents
6873   _mark_stack->expand(); // expand the stack if possible
6874 }
6875 
6876 void PushAndMarkVerifyClosure::do_oop(oop obj) {
6877   assert(obj->is_oop_or_null(), "Expected an oop or NULL at " PTR_FORMAT, p2i(obj));
6878   HeapWord* addr = (HeapWord*)obj;
6879   if (_span.contains(addr) && !_verification_bm->isMarked(addr)) {
6880     // Oop lies in _span and isn't yet grey or black
6881     _verification_bm->mark(addr);            // now grey
6882     if (!_cms_bm->isMarked(addr)) {
6883       oop(addr)->print();
6884       gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)",
6885                              p2i(addr));
6886       fatal("... aborting");
6887     }
6888 
6889     if (!_mark_stack->push(obj)) { // stack overflow
6890       if (PrintCMSStatistics != 0) {
6891         gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
6892                                SIZE_FORMAT, _mark_stack->capacity());
6893       }
6894       assert(_mark_stack->isFull(), "Else push should have succeeded");
6895       handle_stack_overflow(addr);
6896     }
6897     // anything including and to the right of _finger
6898     // will be scanned as we iterate over the remainder of the
6899     // bit map
6900   }
6901 }
6902 
6903 PushOrMarkClosure::PushOrMarkClosure(CMSCollector* collector,
6904                      MemRegion span,
6905                      CMSBitMap* bitMap, CMSMarkStack*  markStack,
6906                      HeapWord* finger, MarkFromRootsClosure* parent) :
6907   MetadataAwareOopClosure(collector->ref_processor()),
6908   _collector(collector),
6909   _span(span),
6910   _bitMap(bitMap),
6911   _markStack(markStack),
6912   _finger(finger),
6913   _parent(parent)
6914 { }
6915 
6916 Par_PushOrMarkClosure::Par_PushOrMarkClosure(CMSCollector* collector,
6917                      MemRegion span,
6918                      CMSBitMap* bit_map,
6919                      OopTaskQueue* work_queue,
6920                      CMSMarkStack*  overflow_stack,
6921                      HeapWord* finger,
6922                      HeapWord** global_finger_addr,
6923                      Par_MarkFromRootsClosure* parent) :
6924   MetadataAwareOopClosure(collector->ref_processor()),
6925   _collector(collector),
6926   _whole_span(collector->_span),
6927   _span(span),
6928   _bit_map(bit_map),
6929   _work_queue(work_queue),
6930   _overflow_stack(overflow_stack),
6931   _finger(finger),
6932   _global_finger_addr(global_finger_addr),
6933   _parent(parent)
6934 { }
6935 
6936 // Assumes thread-safe access by callers, who are
6937 // responsible for mutual exclusion.
6938 void CMSCollector::lower_restart_addr(HeapWord* low) {
6939   assert(_span.contains(low), "Out of bounds addr");
6940   if (_restart_addr == NULL) {
6941     _restart_addr = low;
6942   } else {
6943     _restart_addr = MIN2(_restart_addr, low);
6944   }
6945 }
6946 
6947 // Upon stack overflow, we discard (part of) the stack,
6948 // remembering the least address amongst those discarded
6949 // in CMSCollector's _restart_address.
6950 void PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) {
6951   // Remember the least grey address discarded
6952   HeapWord* ra = (HeapWord*)_markStack->least_value(lost);
6953   _collector->lower_restart_addr(ra);
6954   _markStack->reset();  // discard stack contents
6955   _markStack->expand(); // expand the stack if possible
6956 }
6957 
6958 // Upon stack overflow, we discard (part of) the stack,
6959 // remembering the least address amongst those discarded
6960 // in CMSCollector's _restart_address.
6961 void Par_PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) {
6962   // We need to do this under a mutex to prevent other
6963   // workers from interfering with the work done below.
6964   MutexLockerEx ml(_overflow_stack->par_lock(),
6965                    Mutex::_no_safepoint_check_flag);
6966   // Remember the least grey address discarded
6967   HeapWord* ra = (HeapWord*)_overflow_stack->least_value(lost);
6968   _collector->lower_restart_addr(ra);
6969   _overflow_stack->reset();  // discard stack contents
6970   _overflow_stack->expand(); // expand the stack if possible
6971 }
6972 
6973 void PushOrMarkClosure::do_oop(oop obj) {
6974   // Ignore mark word because we are running concurrent with mutators.
6975   assert(obj->is_oop_or_null(true), "Expected an oop or NULL at " PTR_FORMAT, p2i(obj));
6976   HeapWord* addr = (HeapWord*)obj;
6977   if (_span.contains(addr) && !_bitMap->isMarked(addr)) {
6978     // Oop lies in _span and isn't yet grey or black
6979     _bitMap->mark(addr);            // now grey
6980     if (addr < _finger) {
6981       // the bit map iteration has already either passed, or
6982       // sampled, this bit in the bit map; we'll need to
6983       // use the marking stack to scan this oop's oops.
6984       bool simulate_overflow = false;
6985       NOT_PRODUCT(
6986         if (CMSMarkStackOverflowALot &&
6987             _collector->simulate_overflow()) {
6988           // simulate a stack overflow
6989           simulate_overflow = true;
6990         }
6991       )
6992       if (simulate_overflow || !_markStack->push(obj)) { // stack overflow
6993         if (PrintCMSStatistics != 0) {
6994           gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
6995                                  SIZE_FORMAT, _markStack->capacity());
6996         }
6997         assert(simulate_overflow || _markStack->isFull(), "Else push should have succeeded");
6998         handle_stack_overflow(addr);
6999       }
7000     }
7001     // anything including and to the right of _finger
7002     // will be scanned as we iterate over the remainder of the
7003     // bit map
7004     do_yield_check();
7005   }
7006 }
7007 
7008 void PushOrMarkClosure::do_oop(oop* p)       { PushOrMarkClosure::do_oop_work(p); }
7009 void PushOrMarkClosure::do_oop(narrowOop* p) { PushOrMarkClosure::do_oop_work(p); }
7010 
7011 void Par_PushOrMarkClosure::do_oop(oop obj) {
7012   // Ignore mark word because we are running concurrent with mutators.
7013   assert(obj->is_oop_or_null(true), "Expected an oop or NULL at " PTR_FORMAT, p2i(obj));
7014   HeapWord* addr = (HeapWord*)obj;
7015   if (_whole_span.contains(addr) && !_bit_map->isMarked(addr)) {
7016     // Oop lies in _span and isn't yet grey or black
7017     // We read the global_finger (volatile read) strictly after marking oop
7018     bool res = _bit_map->par_mark(addr);    // now grey
7019     volatile HeapWord** gfa = (volatile HeapWord**)_global_finger_addr;
7020     // Should we push this marked oop on our stack?
7021     // -- if someone else marked it, nothing to do
7022     // -- if target oop is above global finger nothing to do
7023     // -- if target oop is in chunk and above local finger
7024     //      then nothing to do
7025     // -- else push on work queue
7026     if (   !res       // someone else marked it, they will deal with it
7027         || (addr >= *gfa)  // will be scanned in a later task
7028         || (_span.contains(addr) && addr >= _finger)) { // later in this chunk
7029       return;
7030     }
7031     // the bit map iteration has already either passed, or
7032     // sampled, this bit in the bit map; we'll need to
7033     // use the marking stack to scan this oop's oops.
7034     bool simulate_overflow = false;
7035     NOT_PRODUCT(
7036       if (CMSMarkStackOverflowALot &&
7037           _collector->simulate_overflow()) {
7038         // simulate a stack overflow
7039         simulate_overflow = true;
7040       }
7041     )
7042     if (simulate_overflow ||
7043         !(_work_queue->push(obj) || _overflow_stack->par_push(obj))) {
7044       // stack overflow
7045       if (PrintCMSStatistics != 0) {
7046         gclog_or_tty->print_cr("CMS marking stack overflow (benign) at "
7047                                SIZE_FORMAT, _overflow_stack->capacity());
7048       }
7049       // We cannot assert that the overflow stack is full because
7050       // it may have been emptied since.
7051       assert(simulate_overflow ||
7052              _work_queue->size() == _work_queue->max_elems(),
7053             "Else push should have succeeded");
7054       handle_stack_overflow(addr);
7055     }
7056     do_yield_check();
7057   }
7058 }
7059 
7060 void Par_PushOrMarkClosure::do_oop(oop* p)       { Par_PushOrMarkClosure::do_oop_work(p); }
7061 void Par_PushOrMarkClosure::do_oop(narrowOop* p) { Par_PushOrMarkClosure::do_oop_work(p); }
7062 
7063 PushAndMarkClosure::PushAndMarkClosure(CMSCollector* collector,
7064                                        MemRegion span,
7065                                        ReferenceProcessor* rp,
7066                                        CMSBitMap* bit_map,
7067                                        CMSBitMap* mod_union_table,
7068                                        CMSMarkStack*  mark_stack,
7069                                        bool           concurrent_precleaning):
7070   MetadataAwareOopClosure(rp),
7071   _collector(collector),
7072   _span(span),
7073   _bit_map(bit_map),
7074   _mod_union_table(mod_union_table),
7075   _mark_stack(mark_stack),
7076   _concurrent_precleaning(concurrent_precleaning)
7077 {
7078   assert(ref_processor() != NULL, "ref_processor shouldn't be NULL");
7079 }
7080 
7081 // Grey object rescan during pre-cleaning and second checkpoint phases --
7082 // the non-parallel version (the parallel version appears further below.)
7083 void PushAndMarkClosure::do_oop(oop obj) {
7084   // Ignore mark word verification. If during concurrent precleaning,
7085   // the object monitor may be locked. If during the checkpoint
7086   // phases, the object may already have been reached by a  different
7087   // path and may be at the end of the global overflow list (so
7088   // the mark word may be NULL).
7089   assert(obj->is_oop_or_null(true /* ignore mark word */),
7090          "Expected an oop or NULL at " PTR_FORMAT, p2i(obj));
7091   HeapWord* addr = (HeapWord*)obj;
7092   // Check if oop points into the CMS generation
7093   // and is not marked
7094   if (_span.contains(addr) && !_bit_map->isMarked(addr)) {
7095     // a white object ...
7096     _bit_map->mark(addr);         // ... now grey
7097     // push on the marking stack (grey set)
7098     bool simulate_overflow = false;
7099     NOT_PRODUCT(
7100       if (CMSMarkStackOverflowALot &&
7101           _collector->simulate_overflow()) {
7102         // simulate a stack overflow
7103         simulate_overflow = true;
7104       }
7105     )
7106     if (simulate_overflow || !_mark_stack->push(obj)) {
7107       if (_concurrent_precleaning) {
7108          // During precleaning we can just dirty the appropriate card(s)
7109          // in the mod union table, thus ensuring that the object remains
7110          // in the grey set  and continue. In the case of object arrays
7111          // we need to dirty all of the cards that the object spans,
7112          // since the rescan of object arrays will be limited to the
7113          // dirty cards.
7114          // Note that no one can be interfering with us in this action
7115          // of dirtying the mod union table, so no locking or atomics
7116          // are required.
7117          if (obj->is_objArray()) {
7118            size_t sz = obj->size();
7119            HeapWord* end_card_addr = (HeapWord*)round_to(
7120                                         (intptr_t)(addr+sz), CardTableModRefBS::card_size);
7121            MemRegion redirty_range = MemRegion(addr, end_card_addr);
7122            assert(!redirty_range.is_empty(), "Arithmetical tautology");
7123            _mod_union_table->mark_range(redirty_range);
7124          } else {
7125            _mod_union_table->mark(addr);
7126          }
7127          _collector->_ser_pmc_preclean_ovflw++;
7128       } else {
7129          // During the remark phase, we need to remember this oop
7130          // in the overflow list.
7131          _collector->push_on_overflow_list(obj);
7132          _collector->_ser_pmc_remark_ovflw++;
7133       }
7134     }
7135   }
7136 }
7137 
7138 Par_PushAndMarkClosure::Par_PushAndMarkClosure(CMSCollector* collector,
7139                                                MemRegion span,
7140                                                ReferenceProcessor* rp,
7141                                                CMSBitMap* bit_map,
7142                                                OopTaskQueue* work_queue):
7143   MetadataAwareOopClosure(rp),
7144   _collector(collector),
7145   _span(span),
7146   _bit_map(bit_map),
7147   _work_queue(work_queue)
7148 {
7149   assert(ref_processor() != NULL, "ref_processor shouldn't be NULL");
7150 }
7151 
7152 void PushAndMarkClosure::do_oop(oop* p)       { PushAndMarkClosure::do_oop_work(p); }
7153 void PushAndMarkClosure::do_oop(narrowOop* p) { PushAndMarkClosure::do_oop_work(p); }
7154 
7155 // Grey object rescan during second checkpoint phase --
7156 // the parallel version.
7157 void Par_PushAndMarkClosure::do_oop(oop obj) {
7158   // In the assert below, we ignore the mark word because
7159   // this oop may point to an already visited object that is
7160   // on the overflow stack (in which case the mark word has
7161   // been hijacked for chaining into the overflow stack --
7162   // if this is the last object in the overflow stack then
7163   // its mark word will be NULL). Because this object may
7164   // have been subsequently popped off the global overflow
7165   // stack, and the mark word possibly restored to the prototypical
7166   // value, by the time we get to examined this failing assert in
7167   // the debugger, is_oop_or_null(false) may subsequently start
7168   // to hold.
7169   assert(obj->is_oop_or_null(true),
7170          "Expected an oop or NULL at " PTR_FORMAT, p2i(obj));
7171   HeapWord* addr = (HeapWord*)obj;
7172   // Check if oop points into the CMS generation
7173   // and is not marked
7174   if (_span.contains(addr) && !_bit_map->isMarked(addr)) {
7175     // a white object ...
7176     // If we manage to "claim" the object, by being the
7177     // first thread to mark it, then we push it on our
7178     // marking stack
7179     if (_bit_map->par_mark(addr)) {     // ... now grey
7180       // push on work queue (grey set)
7181       bool simulate_overflow = false;
7182       NOT_PRODUCT(
7183         if (CMSMarkStackOverflowALot &&
7184             _collector->par_simulate_overflow()) {
7185           // simulate a stack overflow
7186           simulate_overflow = true;
7187         }
7188       )
7189       if (simulate_overflow || !_work_queue->push(obj)) {
7190         _collector->par_push_on_overflow_list(obj);
7191         _collector->_par_pmc_remark_ovflw++; //  imprecise OK: no need to CAS
7192       }
7193     } // Else, some other thread got there first
7194   }
7195 }
7196 
7197 void Par_PushAndMarkClosure::do_oop(oop* p)       { Par_PushAndMarkClosure::do_oop_work(p); }
7198 void Par_PushAndMarkClosure::do_oop(narrowOop* p) { Par_PushAndMarkClosure::do_oop_work(p); }
7199 
7200 void CMSPrecleanRefsYieldClosure::do_yield_work() {
7201   Mutex* bml = _collector->bitMapLock();
7202   assert_lock_strong(bml);
7203   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
7204          "CMS thread should hold CMS token");
7205 
7206   bml->unlock();
7207   ConcurrentMarkSweepThread::desynchronize(true);
7208 
7209   _collector->stopTimer();
7210   if (PrintCMSStatistics != 0) {
7211     _collector->incrementYields();
7212   }
7213 
7214   // See the comment in coordinator_yield()
7215   for (unsigned i = 0; i < CMSYieldSleepCount &&
7216                        ConcurrentMarkSweepThread::should_yield() &&
7217                        !CMSCollector::foregroundGCIsActive(); ++i) {
7218     os::sleep(Thread::current(), 1, false);
7219   }
7220 
7221   ConcurrentMarkSweepThread::synchronize(true);
7222   bml->lock();
7223 
7224   _collector->startTimer();
7225 }
7226 
7227 bool CMSPrecleanRefsYieldClosure::should_return() {
7228   if (ConcurrentMarkSweepThread::should_yield()) {
7229     do_yield_work();
7230   }
7231   return _collector->foregroundGCIsActive();
7232 }
7233 
7234 void MarkFromDirtyCardsClosure::do_MemRegion(MemRegion mr) {
7235   assert(((size_t)mr.start())%CardTableModRefBS::card_size_in_words == 0,
7236          "mr should be aligned to start at a card boundary");
7237   // We'd like to assert:
7238   // assert(mr.word_size()%CardTableModRefBS::card_size_in_words == 0,
7239   //        "mr should be a range of cards");
7240   // However, that would be too strong in one case -- the last
7241   // partition ends at _unallocated_block which, in general, can be
7242   // an arbitrary boundary, not necessarily card aligned.
7243   if (PrintCMSStatistics != 0) {
7244     _num_dirty_cards +=
7245          mr.word_size()/CardTableModRefBS::card_size_in_words;
7246   }
7247   _space->object_iterate_mem(mr, &_scan_cl);
7248 }
7249 
7250 SweepClosure::SweepClosure(CMSCollector* collector,
7251                            ConcurrentMarkSweepGeneration* g,
7252                            CMSBitMap* bitMap, bool should_yield) :
7253   _collector(collector),
7254   _g(g),
7255   _sp(g->cmsSpace()),
7256   _limit(_sp->sweep_limit()),
7257   _freelistLock(_sp->freelistLock()),
7258   _bitMap(bitMap),
7259   _yield(should_yield),
7260   _inFreeRange(false),           // No free range at beginning of sweep
7261   _freeRangeInFreeLists(false),  // No free range at beginning of sweep
7262   _lastFreeRangeCoalesced(false),
7263   _freeFinger(g->used_region().start())
7264 {
7265   NOT_PRODUCT(
7266     _numObjectsFreed = 0;
7267     _numWordsFreed   = 0;
7268     _numObjectsLive = 0;
7269     _numWordsLive = 0;
7270     _numObjectsAlreadyFree = 0;
7271     _numWordsAlreadyFree = 0;
7272     _last_fc = NULL;
7273 
7274     _sp->initializeIndexedFreeListArrayReturnedBytes();
7275     _sp->dictionary()->initialize_dict_returned_bytes();
7276   )
7277   assert(_limit >= _sp->bottom() && _limit <= _sp->end(),
7278          "sweep _limit out of bounds");
7279   if (CMSTraceSweeper) {
7280     gclog_or_tty->print_cr("\n====================\nStarting new sweep with limit " PTR_FORMAT,
7281                         p2i(_limit));
7282   }
7283 }
7284 
7285 void SweepClosure::print_on(outputStream* st) const {
7286   tty->print_cr("_sp = [" PTR_FORMAT "," PTR_FORMAT ")",
7287                 p2i(_sp->bottom()), p2i(_sp->end()));
7288   tty->print_cr("_limit = " PTR_FORMAT, p2i(_limit));
7289   tty->print_cr("_freeFinger = " PTR_FORMAT, p2i(_freeFinger));
7290   NOT_PRODUCT(tty->print_cr("_last_fc = " PTR_FORMAT, p2i(_last_fc));)
7291   tty->print_cr("_inFreeRange = %d, _freeRangeInFreeLists = %d, _lastFreeRangeCoalesced = %d",
7292                 _inFreeRange, _freeRangeInFreeLists, _lastFreeRangeCoalesced);
7293 }
7294 
7295 #ifndef PRODUCT
7296 // Assertion checking only:  no useful work in product mode --
7297 // however, if any of the flags below become product flags,
7298 // you may need to review this code to see if it needs to be
7299 // enabled in product mode.
7300 SweepClosure::~SweepClosure() {
7301   assert_lock_strong(_freelistLock);
7302   assert(_limit >= _sp->bottom() && _limit <= _sp->end(),
7303          "sweep _limit out of bounds");
7304   if (inFreeRange()) {
7305     warning("inFreeRange() should have been reset; dumping state of SweepClosure");
7306     print();
7307     ShouldNotReachHere();
7308   }
7309   if (Verbose && PrintGC) {
7310     gclog_or_tty->print("Collected " SIZE_FORMAT " objects, " SIZE_FORMAT " bytes",
7311                         _numObjectsFreed, _numWordsFreed*sizeof(HeapWord));
7312     gclog_or_tty->print_cr("\nLive " SIZE_FORMAT " objects,  "
7313                            SIZE_FORMAT " bytes  "
7314       "Already free " SIZE_FORMAT " objects, " SIZE_FORMAT " bytes",
7315       _numObjectsLive, _numWordsLive*sizeof(HeapWord),
7316       _numObjectsAlreadyFree, _numWordsAlreadyFree*sizeof(HeapWord));
7317     size_t totalBytes = (_numWordsFreed + _numWordsLive + _numWordsAlreadyFree)
7318                         * sizeof(HeapWord);
7319     gclog_or_tty->print_cr("Total sweep: " SIZE_FORMAT " bytes", totalBytes);
7320 
7321     if (PrintCMSStatistics && CMSVerifyReturnedBytes) {
7322       size_t indexListReturnedBytes = _sp->sumIndexedFreeListArrayReturnedBytes();
7323       size_t dict_returned_bytes = _sp->dictionary()->sum_dict_returned_bytes();
7324       size_t returned_bytes = indexListReturnedBytes + dict_returned_bytes;
7325       gclog_or_tty->print("Returned " SIZE_FORMAT " bytes", returned_bytes);
7326       gclog_or_tty->print("   Indexed List Returned " SIZE_FORMAT " bytes",
7327         indexListReturnedBytes);
7328       gclog_or_tty->print_cr("        Dictionary Returned " SIZE_FORMAT " bytes",
7329         dict_returned_bytes);
7330     }
7331   }
7332   if (CMSTraceSweeper) {
7333     gclog_or_tty->print_cr("end of sweep with _limit = " PTR_FORMAT "\n================",
7334                            p2i(_limit));
7335   }
7336 }
7337 #endif  // PRODUCT
7338 
7339 void SweepClosure::initialize_free_range(HeapWord* freeFinger,
7340     bool freeRangeInFreeLists) {
7341   if (CMSTraceSweeper) {
7342     gclog_or_tty->print("---- Start free range at " PTR_FORMAT " with free block (%d)\n",
7343                p2i(freeFinger), freeRangeInFreeLists);
7344   }
7345   assert(!inFreeRange(), "Trampling existing free range");
7346   set_inFreeRange(true);
7347   set_lastFreeRangeCoalesced(false);
7348 
7349   set_freeFinger(freeFinger);
7350   set_freeRangeInFreeLists(freeRangeInFreeLists);
7351   if (CMSTestInFreeList) {
7352     if (freeRangeInFreeLists) {
7353       FreeChunk* fc = (FreeChunk*) freeFinger;
7354       assert(fc->is_free(), "A chunk on the free list should be free.");
7355       assert(fc->size() > 0, "Free range should have a size");
7356       assert(_sp->verify_chunk_in_free_list(fc), "Chunk is not in free lists");
7357     }
7358   }
7359 }
7360 
7361 // Note that the sweeper runs concurrently with mutators. Thus,
7362 // it is possible for direct allocation in this generation to happen
7363 // in the middle of the sweep. Note that the sweeper also coalesces
7364 // contiguous free blocks. Thus, unless the sweeper and the allocator
7365 // synchronize appropriately freshly allocated blocks may get swept up.
7366 // This is accomplished by the sweeper locking the free lists while
7367 // it is sweeping. Thus blocks that are determined to be free are
7368 // indeed free. There is however one additional complication:
7369 // blocks that have been allocated since the final checkpoint and
7370 // mark, will not have been marked and so would be treated as
7371 // unreachable and swept up. To prevent this, the allocator marks
7372 // the bit map when allocating during the sweep phase. This leads,
7373 // however, to a further complication -- objects may have been allocated
7374 // but not yet initialized -- in the sense that the header isn't yet
7375 // installed. The sweeper can not then determine the size of the block
7376 // in order to skip over it. To deal with this case, we use a technique
7377 // (due to Printezis) to encode such uninitialized block sizes in the
7378 // bit map. Since the bit map uses a bit per every HeapWord, but the
7379 // CMS generation has a minimum object size of 3 HeapWords, it follows
7380 // that "normal marks" won't be adjacent in the bit map (there will
7381 // always be at least two 0 bits between successive 1 bits). We make use
7382 // of these "unused" bits to represent uninitialized blocks -- the bit
7383 // corresponding to the start of the uninitialized object and the next
7384 // bit are both set. Finally, a 1 bit marks the end of the object that
7385 // started with the two consecutive 1 bits to indicate its potentially
7386 // uninitialized state.
7387 
7388 size_t SweepClosure::do_blk_careful(HeapWord* addr) {
7389   FreeChunk* fc = (FreeChunk*)addr;
7390   size_t res;
7391 
7392   // Check if we are done sweeping. Below we check "addr >= _limit" rather
7393   // than "addr == _limit" because although _limit was a block boundary when
7394   // we started the sweep, it may no longer be one because heap expansion
7395   // may have caused us to coalesce the block ending at the address _limit
7396   // with a newly expanded chunk (this happens when _limit was set to the
7397   // previous _end of the space), so we may have stepped past _limit:
7398   // see the following Zeno-like trail of CRs 6977970, 7008136, 7042740.
7399   if (addr >= _limit) { // we have swept up to or past the limit: finish up
7400     assert(_limit >= _sp->bottom() && _limit <= _sp->end(),
7401            "sweep _limit out of bounds");
7402     assert(addr < _sp->end(), "addr out of bounds");
7403     // Flush any free range we might be holding as a single
7404     // coalesced chunk to the appropriate free list.
7405     if (inFreeRange()) {
7406       assert(freeFinger() >= _sp->bottom() && freeFinger() < _limit,
7407              "freeFinger() " PTR_FORMAT " is out-of-bounds", p2i(freeFinger()));
7408       flush_cur_free_chunk(freeFinger(),
7409                            pointer_delta(addr, freeFinger()));
7410       if (CMSTraceSweeper) {
7411         gclog_or_tty->print("Sweep: last chunk: ");
7412         gclog_or_tty->print("put_free_blk " PTR_FORMAT " (" SIZE_FORMAT ") "
7413                    "[coalesced:%d]\n",
7414                    p2i(freeFinger()), pointer_delta(addr, freeFinger()),
7415                    lastFreeRangeCoalesced() ? 1 : 0);
7416       }
7417     }
7418 
7419     // help the iterator loop finish
7420     return pointer_delta(_sp->end(), addr);
7421   }
7422 
7423   assert(addr < _limit, "sweep invariant");
7424   // check if we should yield
7425   do_yield_check(addr);
7426   if (fc->is_free()) {
7427     // Chunk that is already free
7428     res = fc->size();
7429     do_already_free_chunk(fc);
7430     debug_only(_sp->verifyFreeLists());
7431     // If we flush the chunk at hand in lookahead_and_flush()
7432     // and it's coalesced with a preceding chunk, then the
7433     // process of "mangling" the payload of the coalesced block
7434     // will cause erasure of the size information from the
7435     // (erstwhile) header of all the coalesced blocks but the
7436     // first, so the first disjunct in the assert will not hold
7437     // in that specific case (in which case the second disjunct
7438     // will hold).
7439     assert(res == fc->size() || ((HeapWord*)fc) + res >= _limit,
7440            "Otherwise the size info doesn't change at this step");
7441     NOT_PRODUCT(
7442       _numObjectsAlreadyFree++;
7443       _numWordsAlreadyFree += res;
7444     )
7445     NOT_PRODUCT(_last_fc = fc;)
7446   } else if (!_bitMap->isMarked(addr)) {
7447     // Chunk is fresh garbage
7448     res = do_garbage_chunk(fc);
7449     debug_only(_sp->verifyFreeLists());
7450     NOT_PRODUCT(
7451       _numObjectsFreed++;
7452       _numWordsFreed += res;
7453     )
7454   } else {
7455     // Chunk that is alive.
7456     res = do_live_chunk(fc);
7457     debug_only(_sp->verifyFreeLists());
7458     NOT_PRODUCT(
7459         _numObjectsLive++;
7460         _numWordsLive += res;
7461     )
7462   }
7463   return res;
7464 }
7465 
7466 // For the smart allocation, record following
7467 //  split deaths - a free chunk is removed from its free list because
7468 //      it is being split into two or more chunks.
7469 //  split birth - a free chunk is being added to its free list because
7470 //      a larger free chunk has been split and resulted in this free chunk.
7471 //  coal death - a free chunk is being removed from its free list because
7472 //      it is being coalesced into a large free chunk.
7473 //  coal birth - a free chunk is being added to its free list because
7474 //      it was created when two or more free chunks where coalesced into
7475 //      this free chunk.
7476 //
7477 // These statistics are used to determine the desired number of free
7478 // chunks of a given size.  The desired number is chosen to be relative
7479 // to the end of a CMS sweep.  The desired number at the end of a sweep
7480 // is the
7481 //      count-at-end-of-previous-sweep (an amount that was enough)
7482 //              - count-at-beginning-of-current-sweep  (the excess)
7483 //              + split-births  (gains in this size during interval)
7484 //              - split-deaths  (demands on this size during interval)
7485 // where the interval is from the end of one sweep to the end of the
7486 // next.
7487 //
7488 // When sweeping the sweeper maintains an accumulated chunk which is
7489 // the chunk that is made up of chunks that have been coalesced.  That
7490 // will be termed the left-hand chunk.  A new chunk of garbage that
7491 // is being considered for coalescing will be referred to as the
7492 // right-hand chunk.
7493 //
7494 // When making a decision on whether to coalesce a right-hand chunk with
7495 // the current left-hand chunk, the current count vs. the desired count
7496 // of the left-hand chunk is considered.  Also if the right-hand chunk
7497 // is near the large chunk at the end of the heap (see
7498 // ConcurrentMarkSweepGeneration::isNearLargestChunk()), then the
7499 // left-hand chunk is coalesced.
7500 //
7501 // When making a decision about whether to split a chunk, the desired count
7502 // vs. the current count of the candidate to be split is also considered.
7503 // If the candidate is underpopulated (currently fewer chunks than desired)
7504 // a chunk of an overpopulated (currently more chunks than desired) size may
7505 // be chosen.  The "hint" associated with a free list, if non-null, points
7506 // to a free list which may be overpopulated.
7507 //
7508 
7509 void SweepClosure::do_already_free_chunk(FreeChunk* fc) {
7510   const size_t size = fc->size();
7511   // Chunks that cannot be coalesced are not in the
7512   // free lists.
7513   if (CMSTestInFreeList && !fc->cantCoalesce()) {
7514     assert(_sp->verify_chunk_in_free_list(fc),
7515            "free chunk should be in free lists");
7516   }
7517   // a chunk that is already free, should not have been
7518   // marked in the bit map
7519   HeapWord* const addr = (HeapWord*) fc;
7520   assert(!_bitMap->isMarked(addr), "free chunk should be unmarked");
7521   // Verify that the bit map has no bits marked between
7522   // addr and purported end of this block.
7523   _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size);
7524 
7525   // Some chunks cannot be coalesced under any circumstances.
7526   // See the definition of cantCoalesce().
7527   if (!fc->cantCoalesce()) {
7528     // This chunk can potentially be coalesced.
7529     // All the work is done in
7530     do_post_free_or_garbage_chunk(fc, size);
7531     // Note that if the chunk is not coalescable (the else arm
7532     // below), we unconditionally flush, without needing to do
7533     // a "lookahead," as we do below.
7534     if (inFreeRange()) lookahead_and_flush(fc, size);
7535   } else {
7536     // Code path common to both original and adaptive free lists.
7537 
7538     // cant coalesce with previous block; this should be treated
7539     // as the end of a free run if any
7540     if (inFreeRange()) {
7541       // we kicked some butt; time to pick up the garbage
7542       assert(freeFinger() < addr, "freeFinger points too high");
7543       flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger()));
7544     }
7545     // else, nothing to do, just continue
7546   }
7547 }
7548 
7549 size_t SweepClosure::do_garbage_chunk(FreeChunk* fc) {
7550   // This is a chunk of garbage.  It is not in any free list.
7551   // Add it to a free list or let it possibly be coalesced into
7552   // a larger chunk.
7553   HeapWord* const addr = (HeapWord*) fc;
7554   const size_t size = CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size());
7555 
7556   // Verify that the bit map has no bits marked between
7557   // addr and purported end of just dead object.
7558   _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size);
7559   do_post_free_or_garbage_chunk(fc, size);
7560 
7561   assert(_limit >= addr + size,
7562          "A freshly garbage chunk can't possibly straddle over _limit");
7563   if (inFreeRange()) lookahead_and_flush(fc, size);
7564   return size;
7565 }
7566 
7567 size_t SweepClosure::do_live_chunk(FreeChunk* fc) {
7568   HeapWord* addr = (HeapWord*) fc;
7569   // The sweeper has just found a live object. Return any accumulated
7570   // left hand chunk to the free lists.
7571   if (inFreeRange()) {
7572     assert(freeFinger() < addr, "freeFinger points too high");
7573     flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger()));
7574   }
7575 
7576   // This object is live: we'd normally expect this to be
7577   // an oop, and like to assert the following:
7578   // assert(oop(addr)->is_oop(), "live block should be an oop");
7579   // However, as we commented above, this may be an object whose
7580   // header hasn't yet been initialized.
7581   size_t size;
7582   assert(_bitMap->isMarked(addr), "Tautology for this control point");
7583   if (_bitMap->isMarked(addr + 1)) {
7584     // Determine the size from the bit map, rather than trying to
7585     // compute it from the object header.
7586     HeapWord* nextOneAddr = _bitMap->getNextMarkedWordAddress(addr + 2);
7587     size = pointer_delta(nextOneAddr + 1, addr);
7588     assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
7589            "alignment problem");
7590 
7591 #ifdef ASSERT
7592       if (oop(addr)->klass_or_null() != NULL) {
7593         // Ignore mark word because we are running concurrent with mutators
7594         assert(oop(addr)->is_oop(true), "live block should be an oop");
7595         assert(size ==
7596                CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size()),
7597                "P-mark and computed size do not agree");
7598       }
7599 #endif
7600 
7601   } else {
7602     // This should be an initialized object that's alive.
7603     assert(oop(addr)->klass_or_null() != NULL,
7604            "Should be an initialized object");
7605     // Ignore mark word because we are running concurrent with mutators
7606     assert(oop(addr)->is_oop(true), "live block should be an oop");
7607     // Verify that the bit map has no bits marked between
7608     // addr and purported end of this block.
7609     size = CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size());
7610     assert(size >= 3, "Necessary for Printezis marks to work");
7611     assert(!_bitMap->isMarked(addr+1), "Tautology for this control point");
7612     DEBUG_ONLY(_bitMap->verifyNoOneBitsInRange(addr+2, addr+size);)
7613   }
7614   return size;
7615 }
7616 
7617 void SweepClosure::do_post_free_or_garbage_chunk(FreeChunk* fc,
7618                                                  size_t chunkSize) {
7619   // do_post_free_or_garbage_chunk() should only be called in the case
7620   // of the adaptive free list allocator.
7621   const bool fcInFreeLists = fc->is_free();
7622   assert((HeapWord*)fc <= _limit, "sweep invariant");
7623   if (CMSTestInFreeList && fcInFreeLists) {
7624     assert(_sp->verify_chunk_in_free_list(fc), "free chunk is not in free lists");
7625   }
7626 
7627   if (CMSTraceSweeper) {
7628     gclog_or_tty->print_cr("  -- pick up another chunk at " PTR_FORMAT " (" SIZE_FORMAT ")", p2i(fc), chunkSize);
7629   }
7630 
7631   HeapWord* const fc_addr = (HeapWord*) fc;
7632 
7633   bool coalesce = false;
7634   const size_t left  = pointer_delta(fc_addr, freeFinger());
7635   const size_t right = chunkSize;
7636   switch (FLSCoalescePolicy) {
7637     // numeric value forms a coalition aggressiveness metric
7638     case 0:  { // never coalesce
7639       coalesce = false;
7640       break;
7641     }
7642     case 1: { // coalesce if left & right chunks on overpopulated lists
7643       coalesce = _sp->coalOverPopulated(left) &&
7644                  _sp->coalOverPopulated(right);
7645       break;
7646     }
7647     case 2: { // coalesce if left chunk on overpopulated list (default)
7648       coalesce = _sp->coalOverPopulated(left);
7649       break;
7650     }
7651     case 3: { // coalesce if left OR right chunk on overpopulated list
7652       coalesce = _sp->coalOverPopulated(left) ||
7653                  _sp->coalOverPopulated(right);
7654       break;
7655     }
7656     case 4: { // always coalesce
7657       coalesce = true;
7658       break;
7659     }
7660     default:
7661      ShouldNotReachHere();
7662   }
7663 
7664   // Should the current free range be coalesced?
7665   // If the chunk is in a free range and either we decided to coalesce above
7666   // or the chunk is near the large block at the end of the heap
7667   // (isNearLargestChunk() returns true), then coalesce this chunk.
7668   const bool doCoalesce = inFreeRange()
7669                           && (coalesce || _g->isNearLargestChunk(fc_addr));
7670   if (doCoalesce) {
7671     // Coalesce the current free range on the left with the new
7672     // chunk on the right.  If either is on a free list,
7673     // it must be removed from the list and stashed in the closure.
7674     if (freeRangeInFreeLists()) {
7675       FreeChunk* const ffc = (FreeChunk*)freeFinger();
7676       assert(ffc->size() == pointer_delta(fc_addr, freeFinger()),
7677              "Size of free range is inconsistent with chunk size.");
7678       if (CMSTestInFreeList) {
7679         assert(_sp->verify_chunk_in_free_list(ffc),
7680                "Chunk is not in free lists");
7681       }
7682       _sp->coalDeath(ffc->size());
7683       _sp->removeFreeChunkFromFreeLists(ffc);
7684       set_freeRangeInFreeLists(false);
7685     }
7686     if (fcInFreeLists) {
7687       _sp->coalDeath(chunkSize);
7688       assert(fc->size() == chunkSize,
7689         "The chunk has the wrong size or is not in the free lists");
7690       _sp->removeFreeChunkFromFreeLists(fc);
7691     }
7692     set_lastFreeRangeCoalesced(true);
7693     print_free_block_coalesced(fc);
7694   } else {  // not in a free range and/or should not coalesce
7695     // Return the current free range and start a new one.
7696     if (inFreeRange()) {
7697       // In a free range but cannot coalesce with the right hand chunk.
7698       // Put the current free range into the free lists.
7699       flush_cur_free_chunk(freeFinger(),
7700                            pointer_delta(fc_addr, freeFinger()));
7701     }
7702     // Set up for new free range.  Pass along whether the right hand
7703     // chunk is in the free lists.
7704     initialize_free_range((HeapWord*)fc, fcInFreeLists);
7705   }
7706 }
7707 
7708 // Lookahead flush:
7709 // If we are tracking a free range, and this is the last chunk that
7710 // we'll look at because its end crosses past _limit, we'll preemptively
7711 // flush it along with any free range we may be holding on to. Note that
7712 // this can be the case only for an already free or freshly garbage
7713 // chunk. If this block is an object, it can never straddle
7714 // over _limit. The "straddling" occurs when _limit is set at
7715 // the previous end of the space when this cycle started, and
7716 // a subsequent heap expansion caused the previously co-terminal
7717 // free block to be coalesced with the newly expanded portion,
7718 // thus rendering _limit a non-block-boundary making it dangerous
7719 // for the sweeper to step over and examine.
7720 void SweepClosure::lookahead_and_flush(FreeChunk* fc, size_t chunk_size) {
7721   assert(inFreeRange(), "Should only be called if currently in a free range.");
7722   HeapWord* const eob = ((HeapWord*)fc) + chunk_size;
7723   assert(_sp->used_region().contains(eob - 1),
7724          "eob = " PTR_FORMAT " eob-1 = " PTR_FORMAT " _limit = " PTR_FORMAT
7725          " out of bounds wrt _sp = [" PTR_FORMAT "," PTR_FORMAT ")"
7726          " when examining fc = " PTR_FORMAT "(" SIZE_FORMAT ")",
7727          p2i(eob), p2i(eob-1), p2i(_limit), p2i(_sp->bottom()), p2i(_sp->end()), p2i(fc), chunk_size);
7728   if (eob >= _limit) {
7729     assert(eob == _limit || fc->is_free(), "Only a free chunk should allow us to cross over the limit");
7730     if (CMSTraceSweeper) {
7731       gclog_or_tty->print_cr("_limit " PTR_FORMAT " reached or crossed by block "
7732                              "[" PTR_FORMAT "," PTR_FORMAT ") in space "
7733                              "[" PTR_FORMAT "," PTR_FORMAT ")",
7734                              p2i(_limit), p2i(fc), p2i(eob), p2i(_sp->bottom()), p2i(_sp->end()));
7735     }
7736     // Return the storage we are tracking back into the free lists.
7737     if (CMSTraceSweeper) {
7738       gclog_or_tty->print_cr("Flushing ... ");
7739     }
7740     assert(freeFinger() < eob, "Error");
7741     flush_cur_free_chunk( freeFinger(), pointer_delta(eob, freeFinger()));
7742   }
7743 }
7744 
7745 void SweepClosure::flush_cur_free_chunk(HeapWord* chunk, size_t size) {
7746   assert(inFreeRange(), "Should only be called if currently in a free range.");
7747   assert(size > 0,
7748     "A zero sized chunk cannot be added to the free lists.");
7749   if (!freeRangeInFreeLists()) {
7750     if (CMSTestInFreeList) {
7751       FreeChunk* fc = (FreeChunk*) chunk;
7752       fc->set_size(size);
7753       assert(!_sp->verify_chunk_in_free_list(fc),
7754              "chunk should not be in free lists yet");
7755     }
7756     if (CMSTraceSweeper) {
7757       gclog_or_tty->print_cr(" -- add free block " PTR_FORMAT " (" SIZE_FORMAT ") to free lists",
7758                     p2i(chunk), size);
7759     }
7760     // A new free range is going to be starting.  The current
7761     // free range has not been added to the free lists yet or
7762     // was removed so add it back.
7763     // If the current free range was coalesced, then the death
7764     // of the free range was recorded.  Record a birth now.
7765     if (lastFreeRangeCoalesced()) {
7766       _sp->coalBirth(size);
7767     }
7768     _sp->addChunkAndRepairOffsetTable(chunk, size,
7769             lastFreeRangeCoalesced());
7770   } else if (CMSTraceSweeper) {
7771     gclog_or_tty->print_cr("Already in free list: nothing to flush");
7772   }
7773   set_inFreeRange(false);
7774   set_freeRangeInFreeLists(false);
7775 }
7776 
7777 // We take a break if we've been at this for a while,
7778 // so as to avoid monopolizing the locks involved.
7779 void SweepClosure::do_yield_work(HeapWord* addr) {
7780   // Return current free chunk being used for coalescing (if any)
7781   // to the appropriate freelist.  After yielding, the next
7782   // free block encountered will start a coalescing range of
7783   // free blocks.  If the next free block is adjacent to the
7784   // chunk just flushed, they will need to wait for the next
7785   // sweep to be coalesced.
7786   if (inFreeRange()) {
7787     flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger()));
7788   }
7789 
7790   // First give up the locks, then yield, then re-lock.
7791   // We should probably use a constructor/destructor idiom to
7792   // do this unlock/lock or modify the MutexUnlocker class to
7793   // serve our purpose. XXX
7794   assert_lock_strong(_bitMap->lock());
7795   assert_lock_strong(_freelistLock);
7796   assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(),
7797          "CMS thread should hold CMS token");
7798   _bitMap->lock()->unlock();
7799   _freelistLock->unlock();
7800   ConcurrentMarkSweepThread::desynchronize(true);
7801   _collector->stopTimer();
7802   if (PrintCMSStatistics != 0) {
7803     _collector->incrementYields();
7804   }
7805 
7806   // See the comment in coordinator_yield()
7807   for (unsigned i = 0; i < CMSYieldSleepCount &&
7808                        ConcurrentMarkSweepThread::should_yield() &&
7809                        !CMSCollector::foregroundGCIsActive(); ++i) {
7810     os::sleep(Thread::current(), 1, false);
7811   }
7812 
7813   ConcurrentMarkSweepThread::synchronize(true);
7814   _freelistLock->lock();
7815   _bitMap->lock()->lock_without_safepoint_check();
7816   _collector->startTimer();
7817 }
7818 
7819 #ifndef PRODUCT
7820 // This is actually very useful in a product build if it can
7821 // be called from the debugger.  Compile it into the product
7822 // as needed.
7823 bool debug_verify_chunk_in_free_list(FreeChunk* fc) {
7824   return debug_cms_space->verify_chunk_in_free_list(fc);
7825 }
7826 #endif
7827 
7828 void SweepClosure::print_free_block_coalesced(FreeChunk* fc) const {
7829   if (CMSTraceSweeper) {
7830     gclog_or_tty->print_cr("Sweep:coal_free_blk " PTR_FORMAT " (" SIZE_FORMAT ")",
7831                            p2i(fc), fc->size());
7832   }
7833 }
7834 
7835 // CMSIsAliveClosure
7836 bool CMSIsAliveClosure::do_object_b(oop obj) {
7837   HeapWord* addr = (HeapWord*)obj;
7838   return addr != NULL &&
7839          (!_span.contains(addr) || _bit_map->isMarked(addr));
7840 }
7841 
7842 
7843 CMSKeepAliveClosure::CMSKeepAliveClosure( CMSCollector* collector,
7844                       MemRegion span,
7845                       CMSBitMap* bit_map, CMSMarkStack* mark_stack,
7846                       bool cpc):
7847   _collector(collector),
7848   _span(span),
7849   _bit_map(bit_map),
7850   _mark_stack(mark_stack),
7851   _concurrent_precleaning(cpc) {
7852   assert(!_span.is_empty(), "Empty span could spell trouble");
7853 }
7854 
7855 
7856 // CMSKeepAliveClosure: the serial version
7857 void CMSKeepAliveClosure::do_oop(oop obj) {
7858   HeapWord* addr = (HeapWord*)obj;
7859   if (_span.contains(addr) &&
7860       !_bit_map->isMarked(addr)) {
7861     _bit_map->mark(addr);
7862     bool simulate_overflow = false;
7863     NOT_PRODUCT(
7864       if (CMSMarkStackOverflowALot &&
7865           _collector->simulate_overflow()) {
7866         // simulate a stack overflow
7867         simulate_overflow = true;
7868       }
7869     )
7870     if (simulate_overflow || !_mark_stack->push(obj)) {
7871       if (_concurrent_precleaning) {
7872         // We dirty the overflown object and let the remark
7873         // phase deal with it.
7874         assert(_collector->overflow_list_is_empty(), "Error");
7875         // In the case of object arrays, we need to dirty all of
7876         // the cards that the object spans. No locking or atomics
7877         // are needed since no one else can be mutating the mod union
7878         // table.
7879         if (obj->is_objArray()) {
7880           size_t sz = obj->size();
7881           HeapWord* end_card_addr =
7882             (HeapWord*)round_to((intptr_t)(addr+sz), CardTableModRefBS::card_size);
7883           MemRegion redirty_range = MemRegion(addr, end_card_addr);
7884           assert(!redirty_range.is_empty(), "Arithmetical tautology");
7885           _collector->_modUnionTable.mark_range(redirty_range);
7886         } else {
7887           _collector->_modUnionTable.mark(addr);
7888         }
7889         _collector->_ser_kac_preclean_ovflw++;
7890       } else {
7891         _collector->push_on_overflow_list(obj);
7892         _collector->_ser_kac_ovflw++;
7893       }
7894     }
7895   }
7896 }
7897 
7898 void CMSKeepAliveClosure::do_oop(oop* p)       { CMSKeepAliveClosure::do_oop_work(p); }
7899 void CMSKeepAliveClosure::do_oop(narrowOop* p) { CMSKeepAliveClosure::do_oop_work(p); }
7900 
7901 // CMSParKeepAliveClosure: a parallel version of the above.
7902 // The work queues are private to each closure (thread),
7903 // but (may be) available for stealing by other threads.
7904 void CMSParKeepAliveClosure::do_oop(oop obj) {
7905   HeapWord* addr = (HeapWord*)obj;
7906   if (_span.contains(addr) &&
7907       !_bit_map->isMarked(addr)) {
7908     // In general, during recursive tracing, several threads
7909     // may be concurrently getting here; the first one to
7910     // "tag" it, claims it.
7911     if (_bit_map->par_mark(addr)) {
7912       bool res = _work_queue->push(obj);
7913       assert(res, "Low water mark should be much less than capacity");
7914       // Do a recursive trim in the hope that this will keep
7915       // stack usage lower, but leave some oops for potential stealers
7916       trim_queue(_low_water_mark);
7917     } // Else, another thread got there first
7918   }
7919 }
7920 
7921 void CMSParKeepAliveClosure::do_oop(oop* p)       { CMSParKeepAliveClosure::do_oop_work(p); }
7922 void CMSParKeepAliveClosure::do_oop(narrowOop* p) { CMSParKeepAliveClosure::do_oop_work(p); }
7923 
7924 void CMSParKeepAliveClosure::trim_queue(uint max) {
7925   while (_work_queue->size() > max) {
7926     oop new_oop;
7927     if (_work_queue->pop_local(new_oop)) {
7928       assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop");
7929       assert(_bit_map->isMarked((HeapWord*)new_oop),
7930              "no white objects on this stack!");
7931       assert(_span.contains((HeapWord*)new_oop), "Out of bounds oop");
7932       // iterate over the oops in this oop, marking and pushing
7933       // the ones in CMS heap (i.e. in _span).
7934       new_oop->oop_iterate(&_mark_and_push);
7935     }
7936   }
7937 }
7938 
7939 CMSInnerParMarkAndPushClosure::CMSInnerParMarkAndPushClosure(
7940                                 CMSCollector* collector,
7941                                 MemRegion span, CMSBitMap* bit_map,
7942                                 OopTaskQueue* work_queue):
7943   _collector(collector),
7944   _span(span),
7945   _bit_map(bit_map),
7946   _work_queue(work_queue) { }
7947 
7948 void CMSInnerParMarkAndPushClosure::do_oop(oop obj) {
7949   HeapWord* addr = (HeapWord*)obj;
7950   if (_span.contains(addr) &&
7951       !_bit_map->isMarked(addr)) {
7952     if (_bit_map->par_mark(addr)) {
7953       bool simulate_overflow = false;
7954       NOT_PRODUCT(
7955         if (CMSMarkStackOverflowALot &&
7956             _collector->par_simulate_overflow()) {
7957           // simulate a stack overflow
7958           simulate_overflow = true;
7959         }
7960       )
7961       if (simulate_overflow || !_work_queue->push(obj)) {
7962         _collector->par_push_on_overflow_list(obj);
7963         _collector->_par_kac_ovflw++;
7964       }
7965     } // Else another thread got there already
7966   }
7967 }
7968 
7969 void CMSInnerParMarkAndPushClosure::do_oop(oop* p)       { CMSInnerParMarkAndPushClosure::do_oop_work(p); }
7970 void CMSInnerParMarkAndPushClosure::do_oop(narrowOop* p) { CMSInnerParMarkAndPushClosure::do_oop_work(p); }
7971 
7972 //////////////////////////////////////////////////////////////////
7973 //  CMSExpansionCause                /////////////////////////////
7974 //////////////////////////////////////////////////////////////////
7975 const char* CMSExpansionCause::to_string(CMSExpansionCause::Cause cause) {
7976   switch (cause) {
7977     case _no_expansion:
7978       return "No expansion";
7979     case _satisfy_free_ratio:
7980       return "Free ratio";
7981     case _satisfy_promotion:
7982       return "Satisfy promotion";
7983     case _satisfy_allocation:
7984       return "allocation";
7985     case _allocate_par_lab:
7986       return "Par LAB";
7987     case _allocate_par_spooling_space:
7988       return "Par Spooling Space";
7989     case _adaptive_size_policy:
7990       return "Ergonomics";
7991     default:
7992       return "unknown";
7993   }
7994 }
7995 
7996 void CMSDrainMarkingStackClosure::do_void() {
7997   // the max number to take from overflow list at a time
7998   const size_t num = _mark_stack->capacity()/4;
7999   assert(!_concurrent_precleaning || _collector->overflow_list_is_empty(),
8000          "Overflow list should be NULL during concurrent phases");
8001   while (!_mark_stack->isEmpty() ||
8002          // if stack is empty, check the overflow list
8003          _collector->take_from_overflow_list(num, _mark_stack)) {
8004     oop obj = _mark_stack->pop();
8005     HeapWord* addr = (HeapWord*)obj;
8006     assert(_span.contains(addr), "Should be within span");
8007     assert(_bit_map->isMarked(addr), "Should be marked");
8008     assert(obj->is_oop(), "Should be an oop");
8009     obj->oop_iterate(_keep_alive);
8010   }
8011 }
8012 
8013 void CMSParDrainMarkingStackClosure::do_void() {
8014   // drain queue
8015   trim_queue(0);
8016 }
8017 
8018 // Trim our work_queue so its length is below max at return
8019 void CMSParDrainMarkingStackClosure::trim_queue(uint max) {
8020   while (_work_queue->size() > max) {
8021     oop new_oop;
8022     if (_work_queue->pop_local(new_oop)) {
8023       assert(new_oop->is_oop(), "Expected an oop");
8024       assert(_bit_map->isMarked((HeapWord*)new_oop),
8025              "no white objects on this stack!");
8026       assert(_span.contains((HeapWord*)new_oop), "Out of bounds oop");
8027       // iterate over the oops in this oop, marking and pushing
8028       // the ones in CMS heap (i.e. in _span).
8029       new_oop->oop_iterate(&_mark_and_push);
8030     }
8031   }
8032 }
8033 
8034 ////////////////////////////////////////////////////////////////////
8035 // Support for Marking Stack Overflow list handling and related code
8036 ////////////////////////////////////////////////////////////////////
8037 // Much of the following code is similar in shape and spirit to the
8038 // code used in ParNewGC. We should try and share that code
8039 // as much as possible in the future.
8040 
8041 #ifndef PRODUCT
8042 // Debugging support for CMSStackOverflowALot
8043 
8044 // It's OK to call this multi-threaded;  the worst thing
8045 // that can happen is that we'll get a bunch of closely
8046 // spaced simulated overflows, but that's OK, in fact
8047 // probably good as it would exercise the overflow code
8048 // under contention.
8049 bool CMSCollector::simulate_overflow() {
8050   if (_overflow_counter-- <= 0) { // just being defensive
8051     _overflow_counter = CMSMarkStackOverflowInterval;
8052     return true;
8053   } else {
8054     return false;
8055   }
8056 }
8057 
8058 bool CMSCollector::par_simulate_overflow() {
8059   return simulate_overflow();
8060 }
8061 #endif
8062 
8063 // Single-threaded
8064 bool CMSCollector::take_from_overflow_list(size_t num, CMSMarkStack* stack) {
8065   assert(stack->isEmpty(), "Expected precondition");
8066   assert(stack->capacity() > num, "Shouldn't bite more than can chew");
8067   size_t i = num;
8068   oop  cur = _overflow_list;
8069   const markOop proto = markOopDesc::prototype();
8070   NOT_PRODUCT(ssize_t n = 0;)
8071   for (oop next; i > 0 && cur != NULL; cur = next, i--) {
8072     next = oop(cur->mark());
8073     cur->set_mark(proto);   // until proven otherwise
8074     assert(cur->is_oop(), "Should be an oop");
8075     bool res = stack->push(cur);
8076     assert(res, "Bit off more than can chew?");
8077     NOT_PRODUCT(n++;)
8078   }
8079   _overflow_list = cur;
8080 #ifndef PRODUCT
8081   assert(_num_par_pushes >= n, "Too many pops?");
8082   _num_par_pushes -=n;
8083 #endif
8084   return !stack->isEmpty();
8085 }
8086 
8087 #define BUSY  (cast_to_oop<intptr_t>(0x1aff1aff))
8088 // (MT-safe) Get a prefix of at most "num" from the list.
8089 // The overflow list is chained through the mark word of
8090 // each object in the list. We fetch the entire list,
8091 // break off a prefix of the right size and return the
8092 // remainder. If other threads try to take objects from
8093 // the overflow list at that time, they will wait for
8094 // some time to see if data becomes available. If (and
8095 // only if) another thread places one or more object(s)
8096 // on the global list before we have returned the suffix
8097 // to the global list, we will walk down our local list
8098 // to find its end and append the global list to
8099 // our suffix before returning it. This suffix walk can
8100 // prove to be expensive (quadratic in the amount of traffic)
8101 // when there are many objects in the overflow list and
8102 // there is much producer-consumer contention on the list.
8103 // *NOTE*: The overflow list manipulation code here and
8104 // in ParNewGeneration:: are very similar in shape,
8105 // except that in the ParNew case we use the old (from/eden)
8106 // copy of the object to thread the list via its klass word.
8107 // Because of the common code, if you make any changes in
8108 // the code below, please check the ParNew version to see if
8109 // similar changes might be needed.
8110 // CR 6797058 has been filed to consolidate the common code.
8111 bool CMSCollector::par_take_from_overflow_list(size_t num,
8112                                                OopTaskQueue* work_q,
8113                                                int no_of_gc_threads) {
8114   assert(work_q->size() == 0, "First empty local work queue");
8115   assert(num < work_q->max_elems(), "Can't bite more than we can chew");
8116   if (_overflow_list == NULL) {
8117     return false;
8118   }
8119   // Grab the entire list; we'll put back a suffix
8120   oop prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list));
8121   Thread* tid = Thread::current();
8122   // Before "no_of_gc_threads" was introduced CMSOverflowSpinCount was
8123   // set to ParallelGCThreads.
8124   size_t CMSOverflowSpinCount = (size_t) no_of_gc_threads; // was ParallelGCThreads;
8125   size_t sleep_time_millis = MAX2((size_t)1, num/100);
8126   // If the list is busy, we spin for a short while,
8127   // sleeping between attempts to get the list.
8128   for (size_t spin = 0; prefix == BUSY && spin < CMSOverflowSpinCount; spin++) {
8129     os::sleep(tid, sleep_time_millis, false);
8130     if (_overflow_list == NULL) {
8131       // Nothing left to take
8132       return false;
8133     } else if (_overflow_list != BUSY) {
8134       // Try and grab the prefix
8135       prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list));
8136     }
8137   }
8138   // If the list was found to be empty, or we spun long
8139   // enough, we give up and return empty-handed. If we leave
8140   // the list in the BUSY state below, it must be the case that
8141   // some other thread holds the overflow list and will set it
8142   // to a non-BUSY state in the future.
8143   if (prefix == NULL || prefix == BUSY) {
8144      // Nothing to take or waited long enough
8145      if (prefix == NULL) {
8146        // Write back the NULL in case we overwrote it with BUSY above
8147        // and it is still the same value.
8148        (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY);
8149      }
8150      return false;
8151   }
8152   assert(prefix != NULL && prefix != BUSY, "Error");
8153   size_t i = num;
8154   oop cur = prefix;
8155   // Walk down the first "num" objects, unless we reach the end.
8156   for (; i > 1 && cur->mark() != NULL; cur = oop(cur->mark()), i--);
8157   if (cur->mark() == NULL) {
8158     // We have "num" or fewer elements in the list, so there
8159     // is nothing to return to the global list.
8160     // Write back the NULL in lieu of the BUSY we wrote
8161     // above, if it is still the same value.
8162     if (_overflow_list == BUSY) {
8163       (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY);
8164     }
8165   } else {
8166     // Chop off the suffix and return it to the global list.
8167     assert(cur->mark() != BUSY, "Error");
8168     oop suffix_head = cur->mark(); // suffix will be put back on global list
8169     cur->set_mark(NULL);           // break off suffix
8170     // It's possible that the list is still in the empty(busy) state
8171     // we left it in a short while ago; in that case we may be
8172     // able to place back the suffix without incurring the cost
8173     // of a walk down the list.
8174     oop observed_overflow_list = _overflow_list;
8175     oop cur_overflow_list = observed_overflow_list;
8176     bool attached = false;
8177     while (observed_overflow_list == BUSY || observed_overflow_list == NULL) {
8178       observed_overflow_list =
8179         (oop) Atomic::cmpxchg_ptr(suffix_head, &_overflow_list, cur_overflow_list);
8180       if (cur_overflow_list == observed_overflow_list) {
8181         attached = true;
8182         break;
8183       } else cur_overflow_list = observed_overflow_list;
8184     }
8185     if (!attached) {
8186       // Too bad, someone else sneaked in (at least) an element; we'll need
8187       // to do a splice. Find tail of suffix so we can prepend suffix to global
8188       // list.
8189       for (cur = suffix_head; cur->mark() != NULL; cur = (oop)(cur->mark()));
8190       oop suffix_tail = cur;
8191       assert(suffix_tail != NULL && suffix_tail->mark() == NULL,
8192              "Tautology");
8193       observed_overflow_list = _overflow_list;
8194       do {
8195         cur_overflow_list = observed_overflow_list;
8196         if (cur_overflow_list != BUSY) {
8197           // Do the splice ...
8198           suffix_tail->set_mark(markOop(cur_overflow_list));
8199         } else { // cur_overflow_list == BUSY
8200           suffix_tail->set_mark(NULL);
8201         }
8202         // ... and try to place spliced list back on overflow_list ...
8203         observed_overflow_list =
8204           (oop) Atomic::cmpxchg_ptr(suffix_head, &_overflow_list, cur_overflow_list);
8205       } while (cur_overflow_list != observed_overflow_list);
8206       // ... until we have succeeded in doing so.
8207     }
8208   }
8209 
8210   // Push the prefix elements on work_q
8211   assert(prefix != NULL, "control point invariant");
8212   const markOop proto = markOopDesc::prototype();
8213   oop next;
8214   NOT_PRODUCT(ssize_t n = 0;)
8215   for (cur = prefix; cur != NULL; cur = next) {
8216     next = oop(cur->mark());
8217     cur->set_mark(proto);   // until proven otherwise
8218     assert(cur->is_oop(), "Should be an oop");
8219     bool res = work_q->push(cur);
8220     assert(res, "Bit off more than we can chew?");
8221     NOT_PRODUCT(n++;)
8222   }
8223 #ifndef PRODUCT
8224   assert(_num_par_pushes >= n, "Too many pops?");
8225   Atomic::add_ptr(-(intptr_t)n, &_num_par_pushes);
8226 #endif
8227   return true;
8228 }
8229 
8230 // Single-threaded
8231 void CMSCollector::push_on_overflow_list(oop p) {
8232   NOT_PRODUCT(_num_par_pushes++;)
8233   assert(p->is_oop(), "Not an oop");
8234   preserve_mark_if_necessary(p);
8235   p->set_mark((markOop)_overflow_list);
8236   _overflow_list = p;
8237 }
8238 
8239 // Multi-threaded; use CAS to prepend to overflow list
8240 void CMSCollector::par_push_on_overflow_list(oop p) {
8241   NOT_PRODUCT(Atomic::inc_ptr(&_num_par_pushes);)
8242   assert(p->is_oop(), "Not an oop");
8243   par_preserve_mark_if_necessary(p);
8244   oop observed_overflow_list = _overflow_list;
8245   oop cur_overflow_list;
8246   do {
8247     cur_overflow_list = observed_overflow_list;
8248     if (cur_overflow_list != BUSY) {
8249       p->set_mark(markOop(cur_overflow_list));
8250     } else {
8251       p->set_mark(NULL);
8252     }
8253     observed_overflow_list =
8254       (oop) Atomic::cmpxchg_ptr(p, &_overflow_list, cur_overflow_list);
8255   } while (cur_overflow_list != observed_overflow_list);
8256 }
8257 #undef BUSY
8258 
8259 // Single threaded
8260 // General Note on GrowableArray: pushes may silently fail
8261 // because we are (temporarily) out of C-heap for expanding
8262 // the stack. The problem is quite ubiquitous and affects
8263 // a lot of code in the JVM. The prudent thing for GrowableArray
8264 // to do (for now) is to exit with an error. However, that may
8265 // be too draconian in some cases because the caller may be
8266 // able to recover without much harm. For such cases, we
8267 // should probably introduce a "soft_push" method which returns
8268 // an indication of success or failure with the assumption that
8269 // the caller may be able to recover from a failure; code in
8270 // the VM can then be changed, incrementally, to deal with such
8271 // failures where possible, thus, incrementally hardening the VM
8272 // in such low resource situations.
8273 void CMSCollector::preserve_mark_work(oop p, markOop m) {
8274   _preserved_oop_stack.push(p);
8275   _preserved_mark_stack.push(m);
8276   assert(m == p->mark(), "Mark word changed");
8277   assert(_preserved_oop_stack.size() == _preserved_mark_stack.size(),
8278          "bijection");
8279 }
8280 
8281 // Single threaded
8282 void CMSCollector::preserve_mark_if_necessary(oop p) {
8283   markOop m = p->mark();
8284   if (m->must_be_preserved(p)) {
8285     preserve_mark_work(p, m);
8286   }
8287 }
8288 
8289 void CMSCollector::par_preserve_mark_if_necessary(oop p) {
8290   markOop m = p->mark();
8291   if (m->must_be_preserved(p)) {
8292     MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag);
8293     // Even though we read the mark word without holding
8294     // the lock, we are assured that it will not change
8295     // because we "own" this oop, so no other thread can
8296     // be trying to push it on the overflow list; see
8297     // the assertion in preserve_mark_work() that checks
8298     // that m == p->mark().
8299     preserve_mark_work(p, m);
8300   }
8301 }
8302 
8303 // We should be able to do this multi-threaded,
8304 // a chunk of stack being a task (this is
8305 // correct because each oop only ever appears
8306 // once in the overflow list. However, it's
8307 // not very easy to completely overlap this with
8308 // other operations, so will generally not be done
8309 // until all work's been completed. Because we
8310 // expect the preserved oop stack (set) to be small,
8311 // it's probably fine to do this single-threaded.
8312 // We can explore cleverer concurrent/overlapped/parallel
8313 // processing of preserved marks if we feel the
8314 // need for this in the future. Stack overflow should
8315 // be so rare in practice and, when it happens, its
8316 // effect on performance so great that this will
8317 // likely just be in the noise anyway.
8318 void CMSCollector::restore_preserved_marks_if_any() {
8319   assert(SafepointSynchronize::is_at_safepoint(),
8320          "world should be stopped");
8321   assert(Thread::current()->is_ConcurrentGC_thread() ||
8322          Thread::current()->is_VM_thread(),
8323          "should be single-threaded");
8324   assert(_preserved_oop_stack.size() == _preserved_mark_stack.size(),
8325          "bijection");
8326 
8327   while (!_preserved_oop_stack.is_empty()) {
8328     oop p = _preserved_oop_stack.pop();
8329     assert(p->is_oop(), "Should be an oop");
8330     assert(_span.contains(p), "oop should be in _span");
8331     assert(p->mark() == markOopDesc::prototype(),
8332            "Set when taken from overflow list");
8333     markOop m = _preserved_mark_stack.pop();
8334     p->set_mark(m);
8335   }
8336   assert(_preserved_mark_stack.is_empty() && _preserved_oop_stack.is_empty(),
8337          "stacks were cleared above");
8338 }
8339 
8340 #ifndef PRODUCT
8341 bool CMSCollector::no_preserved_marks() const {
8342   return _preserved_mark_stack.is_empty() && _preserved_oop_stack.is_empty();
8343 }
8344 #endif
8345 
8346 // Transfer some number of overflown objects to usual marking
8347 // stack. Return true if some objects were transferred.
8348 bool MarkRefsIntoAndScanClosure::take_from_overflow_list() {
8349   size_t num = MIN2((size_t)(_mark_stack->capacity() - _mark_stack->length())/4,
8350                     (size_t)ParGCDesiredObjsFromOverflowList);
8351 
8352   bool res = _collector->take_from_overflow_list(num, _mark_stack);
8353   assert(_collector->overflow_list_is_empty() || res,
8354          "If list is not empty, we should have taken something");
8355   assert(!res || !_mark_stack->isEmpty(),
8356          "If we took something, it should now be on our stack");
8357   return res;
8358 }
8359 
8360 size_t MarkDeadObjectsClosure::do_blk(HeapWord* addr) {
8361   size_t res = _sp->block_size_no_stall(addr, _collector);
8362   if (_sp->block_is_obj(addr)) {
8363     if (_live_bit_map->isMarked(addr)) {
8364       // It can't have been dead in a previous cycle
8365       guarantee(!_dead_bit_map->isMarked(addr), "No resurrection!");
8366     } else {
8367       _dead_bit_map->mark(addr);      // mark the dead object
8368     }
8369   }
8370   // Could be 0, if the block size could not be computed without stalling.
8371   return res;
8372 }
8373 
8374 TraceCMSMemoryManagerStats::TraceCMSMemoryManagerStats(CMSCollector::CollectorState phase, GCCause::Cause cause): TraceMemoryManagerStats() {
8375 
8376   switch (phase) {
8377     case CMSCollector::InitialMarking:
8378       initialize(true  /* fullGC */ ,
8379                  cause /* cause of the GC */,
8380                  true  /* recordGCBeginTime */,
8381                  true  /* recordPreGCUsage */,
8382                  false /* recordPeakUsage */,
8383                  false /* recordPostGCusage */,
8384                  true  /* recordAccumulatedGCTime */,
8385                  false /* recordGCEndTime */,
8386                  false /* countCollection */  );
8387       break;
8388 
8389     case CMSCollector::FinalMarking:
8390       initialize(true  /* fullGC */ ,
8391                  cause /* cause of the GC */,
8392                  false /* recordGCBeginTime */,
8393                  false /* recordPreGCUsage */,
8394                  false /* recordPeakUsage */,
8395                  false /* recordPostGCusage */,
8396                  true  /* recordAccumulatedGCTime */,
8397                  false /* recordGCEndTime */,
8398                  false /* countCollection */  );
8399       break;
8400 
8401     case CMSCollector::Sweeping:
8402       initialize(true  /* fullGC */ ,
8403                  cause /* cause of the GC */,
8404                  false /* recordGCBeginTime */,
8405                  false /* recordPreGCUsage */,
8406                  true  /* recordPeakUsage */,
8407                  true  /* recordPostGCusage */,
8408                  false /* recordAccumulatedGCTime */,
8409                  true  /* recordGCEndTime */,
8410                  true  /* countCollection */  );
8411       break;
8412 
8413     default:
8414       ShouldNotReachHere();
8415   }
8416 }