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