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