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