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