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