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