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