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