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