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