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