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