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