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