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