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