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