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 { 208 HeapWord* bottom = (HeapWord*) _virtual_space.low(); 209 HeapWord* end = (HeapWord*) _virtual_space.high(); 210 211 _direct_allocated_words = 0; 212 NOT_PRODUCT( 213 _numObjectsPromoted = 0; 214 _numWordsPromoted = 0; 215 _numObjectsAllocated = 0; 216 _numWordsAllocated = 0; 217 ) 218 219 _cmsSpace = new CompactibleFreeListSpace(_bts, MemRegion(bottom, end), 220 use_adaptive_freelists, 221 dictionaryChoice); 222 NOT_PRODUCT(debug_cms_space = _cmsSpace;) 223 if (_cmsSpace == NULL) { 224 vm_exit_during_initialization( 225 "CompactibleFreeListSpace allocation failure"); 226 } 227 _cmsSpace->_gen = this; 228 229 _gc_stats = new CMSGCStats(); 230 231 // Verify the assumption that FreeChunk::_prev and OopDesc::_klass 232 // offsets match. The ability to tell free chunks from objects 233 // depends on this property. 234 debug_only( 235 FreeChunk* junk = NULL; 236 assert(UseCompressedClassPointers || 237 junk->prev_addr() == (void*)(oop(junk)->klass_addr()), 238 "Offset of FreeChunk::_prev within FreeChunk must match" 239 " that of OopDesc::_klass within OopDesc"); 240 ) 241 if (CollectedHeap::use_parallel_gc_threads()) { 242 typedef CMSParGCThreadState* CMSParGCThreadStatePtr; 243 _par_gc_thread_states = 244 NEW_C_HEAP_ARRAY(CMSParGCThreadStatePtr, ParallelGCThreads, mtGC); 245 if (_par_gc_thread_states == NULL) { 246 vm_exit_during_initialization("Could not allocate par gc structs"); 247 } 248 for (uint i = 0; i < ParallelGCThreads; i++) { 249 _par_gc_thread_states[i] = new CMSParGCThreadState(cmsSpace()); 250 if (_par_gc_thread_states[i] == NULL) { 251 vm_exit_during_initialization("Could not allocate par gc structs"); 252 } 253 } 254 } else { 255 _par_gc_thread_states = NULL; 256 } 257 _incremental_collection_failed = false; 258 // The "dilatation_factor" is the expansion that can occur on 259 // account of the fact that the minimum object size in the CMS 260 // generation may be larger than that in, say, a contiguous young 261 // generation. 262 // Ideally, in the calculation below, we'd compute the dilatation 263 // factor as: MinChunkSize/(promoting_gen's min object size) 264 // Since we do not have such a general query interface for the 265 // promoting generation, we'll instead just use the minimum 266 // object size (which today is a header's worth of space); 267 // note that all arithmetic is in units of HeapWords. 268 assert(MinChunkSize >= CollectedHeap::min_fill_size(), "just checking"); 269 assert(_dilatation_factor >= 1.0, "from previous assert"); 270 271 // Support for CMSFastPromotionFailure 272 reset_promotion_failed(); 273 } 274 275 276 // The field "_initiating_occupancy" represents the occupancy percentage 277 // at which we trigger a new collection cycle. Unless explicitly specified 278 // via CMSInitiatingOccupancyFraction (argument "io" below), it 279 // is calculated by: 280 // 281 // Let "f" be MinHeapFreeRatio in 282 // 283 // _initiating_occupancy = 100-f + 284 // f * (CMSTriggerRatio/100) 285 // where CMSTriggerRatio is the argument "tr" below. 286 // 287 // That is, if we assume the heap is at its desired maximum occupancy at the 288 // end of a collection, we let CMSTriggerRatio of the (purported) free 289 // space be allocated before initiating a new collection cycle. 290 // 291 void ConcurrentMarkSweepGeneration::init_initiating_occupancy(intx io, uintx tr) { 292 assert(io <= 100 && tr <= 100, "Check the arguments"); 293 if (io >= 0) { 294 _initiating_occupancy = (double)io / 100.0; 295 } else { 296 _initiating_occupancy = ((100 - MinHeapFreeRatio) + 297 (double)(tr * MinHeapFreeRatio) / 100.0) 298 / 100.0; 299 } 300 } 301 302 void ConcurrentMarkSweepGeneration::ref_processor_init() { 303 assert(collector() != NULL, "no collector"); 304 collector()->ref_processor_init(); 305 } 306 307 void CMSCollector::ref_processor_init() { 308 if (_ref_processor == NULL) { 309 // Allocate and initialize a reference processor 310 _ref_processor = 311 new ReferenceProcessor(_span, // span 312 (ParallelGCThreads > 1) && ParallelRefProcEnabled, // mt processing 313 (int) ParallelGCThreads, // mt processing degree 314 _cmsGen->refs_discovery_is_mt(), // mt discovery 315 (int) MAX2(ConcGCThreads, ParallelGCThreads), // mt discovery degree 316 _cmsGen->refs_discovery_is_atomic(), // discovery is not atomic 317 &_is_alive_closure); // closure for liveness info 318 // Initialize the _ref_processor field of CMSGen 319 _cmsGen->set_ref_processor(_ref_processor); 320 321 } 322 } 323 324 AdaptiveSizePolicy* CMSCollector::size_policy() { 325 GenCollectedHeap* gch = GenCollectedHeap::heap(); 326 assert(gch->kind() == CollectedHeap::GenCollectedHeap, 327 "Wrong type of heap"); 328 return gch->gen_policy()->size_policy(); 329 } 330 331 void ConcurrentMarkSweepGeneration::initialize_performance_counters() { 332 333 const char* gen_name = "old"; 334 GenCollectorPolicy* gcp = (GenCollectorPolicy*) GenCollectedHeap::heap()->collector_policy(); 335 336 // Generation Counters - generation 1, 1 subspace 337 _gen_counters = new GenerationCounters(gen_name, 1, 1, 338 gcp->min_old_size(), gcp->max_old_size(), &_virtual_space); 339 340 _space_counters = new GSpaceCounters(gen_name, 0, 341 _virtual_space.reserved_size(), 342 this, _gen_counters); 343 } 344 345 CMSStats::CMSStats(ConcurrentMarkSweepGeneration* cms_gen, unsigned int alpha): 346 _cms_gen(cms_gen) 347 { 348 assert(alpha <= 100, "bad value"); 349 _saved_alpha = alpha; 350 351 // Initialize the alphas to the bootstrap value of 100. 352 _gc0_alpha = _cms_alpha = 100; 353 354 _cms_begin_time.update(); 355 _cms_end_time.update(); 356 357 _gc0_duration = 0.0; 358 _gc0_period = 0.0; 359 _gc0_promoted = 0; 360 361 _cms_duration = 0.0; 362 _cms_period = 0.0; 363 _cms_allocated = 0; 364 365 _cms_used_at_gc0_begin = 0; 366 _cms_used_at_gc0_end = 0; 367 _allow_duty_cycle_reduction = false; 368 _valid_bits = 0; 369 _icms_duty_cycle = CMSIncrementalDutyCycle; 370 } 371 372 double CMSStats::cms_free_adjustment_factor(size_t free) const { 373 // TBD: CR 6909490 374 return 1.0; 375 } 376 377 void CMSStats::adjust_cms_free_adjustment_factor(bool fail, size_t free) { 378 } 379 380 // If promotion failure handling is on use 381 // the padded average size of the promotion for each 382 // young generation collection. 383 double CMSStats::time_until_cms_gen_full() const { 384 size_t cms_free = _cms_gen->cmsSpace()->free(); 385 GenCollectedHeap* gch = GenCollectedHeap::heap(); 386 size_t expected_promotion = MIN2(gch->get_gen(0)->capacity(), 387 (size_t) _cms_gen->gc_stats()->avg_promoted()->padded_average()); 388 if (cms_free > expected_promotion) { 389 // Start a cms collection if there isn't enough space to promote 390 // for the next minor collection. Use the padded average as 391 // a safety factor. 392 cms_free -= expected_promotion; 393 394 // Adjust by the safety factor. 395 double cms_free_dbl = (double)cms_free; 396 double cms_adjustment = (100.0 - CMSIncrementalSafetyFactor)/100.0; 397 // Apply a further correction factor which tries to adjust 398 // for recent occurance of concurrent mode failures. 399 cms_adjustment = cms_adjustment * cms_free_adjustment_factor(cms_free); 400 cms_free_dbl = cms_free_dbl * cms_adjustment; 401 402 if (PrintGCDetails && Verbose) { 403 gclog_or_tty->print_cr("CMSStats::time_until_cms_gen_full: cms_free " 404 SIZE_FORMAT " expected_promotion " SIZE_FORMAT, 405 cms_free, expected_promotion); 406 gclog_or_tty->print_cr(" cms_free_dbl %f cms_consumption_rate %f", 407 cms_free_dbl, cms_consumption_rate() + 1.0); 408 } 409 // Add 1 in case the consumption rate goes to zero. 410 return cms_free_dbl / (cms_consumption_rate() + 1.0); 411 } 412 return 0.0; 413 } 414 415 // Compare the duration of the cms collection to the 416 // time remaining before the cms generation is empty. 417 // Note that the time from the start of the cms collection 418 // to the start of the cms sweep (less than the total 419 // duration of the cms collection) can be used. This 420 // has been tried and some applications experienced 421 // promotion failures early in execution. This was 422 // possibly because the averages were not accurate 423 // enough at the beginning. 424 double CMSStats::time_until_cms_start() const { 425 // We add "gc0_period" to the "work" calculation 426 // below because this query is done (mostly) at the 427 // end of a scavenge, so we need to conservatively 428 // account for that much possible delay 429 // in the query so as to avoid concurrent mode failures 430 // due to starting the collection just a wee bit too 431 // late. 432 double work = cms_duration() + gc0_period(); 433 double deadline = time_until_cms_gen_full(); 434 // If a concurrent mode failure occurred recently, we want to be 435 // more conservative and halve our expected time_until_cms_gen_full() 436 if (work > deadline) { 437 if (Verbose && PrintGCDetails) { 438 gclog_or_tty->print( 439 " CMSCollector: collect because of anticipated promotion " 440 "before full %3.7f + %3.7f > %3.7f ", cms_duration(), 441 gc0_period(), time_until_cms_gen_full()); 442 } 443 return 0.0; 444 } 445 return work - deadline; 446 } 447 448 // Return a duty cycle based on old_duty_cycle and new_duty_cycle, limiting the 449 // amount of change to prevent wild oscillation. 450 unsigned int CMSStats::icms_damped_duty_cycle(unsigned int old_duty_cycle, 451 unsigned int new_duty_cycle) { 452 assert(old_duty_cycle <= 100, "bad input value"); 453 assert(new_duty_cycle <= 100, "bad input value"); 454 455 // Note: use subtraction with caution since it may underflow (values are 456 // unsigned). Addition is safe since we're in the range 0-100. 457 unsigned int damped_duty_cycle = new_duty_cycle; 458 if (new_duty_cycle < old_duty_cycle) { 459 const unsigned int largest_delta = MAX2(old_duty_cycle / 4, 5U); 460 if (new_duty_cycle + largest_delta < old_duty_cycle) { 461 damped_duty_cycle = old_duty_cycle - largest_delta; 462 } 463 } else if (new_duty_cycle > old_duty_cycle) { 464 const unsigned int largest_delta = MAX2(old_duty_cycle / 4, 15U); 465 if (new_duty_cycle > old_duty_cycle + largest_delta) { 466 damped_duty_cycle = MIN2(old_duty_cycle + largest_delta, 100U); 467 } 468 } 469 assert(damped_duty_cycle <= 100, "invalid duty cycle computed"); 470 471 if (CMSTraceIncrementalPacing) { 472 gclog_or_tty->print(" [icms_damped_duty_cycle(%d,%d) = %d] ", 473 old_duty_cycle, new_duty_cycle, damped_duty_cycle); 474 } 475 return damped_duty_cycle; 476 } 477 478 unsigned int CMSStats::icms_update_duty_cycle_impl() { 479 assert(CMSIncrementalPacing && valid(), 480 "should be handled in icms_update_duty_cycle()"); 481 482 double cms_time_so_far = cms_timer().seconds(); 483 double scaled_duration = cms_duration_per_mb() * _cms_used_at_gc0_end / M; 484 double scaled_duration_remaining = fabsd(scaled_duration - cms_time_so_far); 485 486 // Avoid division by 0. 487 double time_until_full = MAX2(time_until_cms_gen_full(), 0.01); 488 double duty_cycle_dbl = 100.0 * scaled_duration_remaining / time_until_full; 489 490 unsigned int new_duty_cycle = MIN2((unsigned int)duty_cycle_dbl, 100U); 491 if (new_duty_cycle > _icms_duty_cycle) { 492 // Avoid very small duty cycles (1 or 2); 0 is allowed. 493 if (new_duty_cycle > 2) { 494 _icms_duty_cycle = icms_damped_duty_cycle(_icms_duty_cycle, 495 new_duty_cycle); 496 } 497 } else if (_allow_duty_cycle_reduction) { 498 // The duty cycle is reduced only once per cms cycle (see record_cms_end()). 499 new_duty_cycle = icms_damped_duty_cycle(_icms_duty_cycle, new_duty_cycle); 500 // Respect the minimum duty cycle. 501 unsigned int min_duty_cycle = (unsigned int)CMSIncrementalDutyCycleMin; 502 _icms_duty_cycle = MAX2(new_duty_cycle, min_duty_cycle); 503 } 504 505 if (PrintGCDetails || CMSTraceIncrementalPacing) { 506 gclog_or_tty->print(" icms_dc=%d ", _icms_duty_cycle); 507 } 508 509 _allow_duty_cycle_reduction = false; 510 return _icms_duty_cycle; 511 } 512 513 #ifndef PRODUCT 514 void CMSStats::print_on(outputStream *st) const { 515 st->print(" gc0_alpha=%d,cms_alpha=%d", _gc0_alpha, _cms_alpha); 516 st->print(",gc0_dur=%g,gc0_per=%g,gc0_promo=" SIZE_FORMAT, 517 gc0_duration(), gc0_period(), gc0_promoted()); 518 st->print(",cms_dur=%g,cms_dur_per_mb=%g,cms_per=%g,cms_alloc=" SIZE_FORMAT, 519 cms_duration(), cms_duration_per_mb(), 520 cms_period(), cms_allocated()); 521 st->print(",cms_since_beg=%g,cms_since_end=%g", 522 cms_time_since_begin(), cms_time_since_end()); 523 st->print(",cms_used_beg=" SIZE_FORMAT ",cms_used_end=" SIZE_FORMAT, 524 _cms_used_at_gc0_begin, _cms_used_at_gc0_end); 525 if (CMSIncrementalMode) { 526 st->print(",dc=%d", icms_duty_cycle()); 527 } 528 529 if (valid()) { 530 st->print(",promo_rate=%g,cms_alloc_rate=%g", 531 promotion_rate(), cms_allocation_rate()); 532 st->print(",cms_consumption_rate=%g,time_until_full=%g", 533 cms_consumption_rate(), time_until_cms_gen_full()); 534 } 535 st->print(" "); 536 } 537 #endif // #ifndef PRODUCT 538 539 CMSCollector::CollectorState CMSCollector::_collectorState = 540 CMSCollector::Idling; 541 bool CMSCollector::_foregroundGCIsActive = false; 542 bool CMSCollector::_foregroundGCShouldWait = false; 543 544 CMSCollector::CMSCollector(ConcurrentMarkSweepGeneration* cmsGen, 545 CardTableRS* ct, 546 ConcurrentMarkSweepPolicy* cp): 547 _cmsGen(cmsGen), 548 _ct(ct), 549 _ref_processor(NULL), // will be set later 550 _conc_workers(NULL), // may be set later 551 _abort_preclean(false), 552 _start_sampling(false), 553 _between_prologue_and_epilogue(false), 554 _markBitMap(0, Mutex::leaf + 1, "CMS_markBitMap_lock"), 555 _modUnionTable((CardTableModRefBS::card_shift - LogHeapWordSize), 556 -1 /* lock-free */, "No_lock" /* dummy */), 557 _modUnionClosure(&_modUnionTable), 558 _modUnionClosurePar(&_modUnionTable), 559 // Adjust my span to cover old (cms) gen 560 _span(cmsGen->reserved()), 561 // Construct the is_alive_closure with _span & markBitMap 562 _is_alive_closure(_span, &_markBitMap), 563 _restart_addr(NULL), 564 _overflow_list(NULL), 565 _stats(cmsGen), 566 _eden_chunk_lock(new Mutex(Mutex::leaf + 1, "CMS_eden_chunk_lock", true)), 567 _eden_chunk_array(NULL), // may be set in ctor body 568 _eden_chunk_capacity(0), // -- ditto -- 569 _eden_chunk_index(0), // -- ditto -- 570 _survivor_plab_array(NULL), // -- ditto -- 571 _survivor_chunk_array(NULL), // -- ditto -- 572 _survivor_chunk_capacity(0), // -- ditto -- 573 _survivor_chunk_index(0), // -- ditto -- 574 _ser_pmc_preclean_ovflw(0), 575 _ser_kac_preclean_ovflw(0), 576 _ser_pmc_remark_ovflw(0), 577 _par_pmc_remark_ovflw(0), 578 _ser_kac_ovflw(0), 579 _par_kac_ovflw(0), 580 #ifndef PRODUCT 581 _num_par_pushes(0), 582 #endif 583 _collection_count_start(0), 584 _verifying(false), 585 _icms_start_limit(NULL), 586 _icms_stop_limit(NULL), 587 _verification_mark_bm(0, Mutex::leaf + 1, "CMS_verification_mark_bm_lock"), 588 _completed_initialization(false), 589 _collector_policy(cp), 590 _should_unload_classes(CMSClassUnloadingEnabled), 591 _concurrent_cycles_since_last_unload(0), 592 _roots_scanning_options(SharedHeap::SO_None), 593 _inter_sweep_estimate(CMS_SweepWeight, CMS_SweepPadding), 594 _intra_sweep_estimate(CMS_SweepWeight, CMS_SweepPadding), 595 _gc_tracer_cm(new (ResourceObj::C_HEAP, mtGC) CMSTracer()), 596 _gc_timer_cm(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()), 597 _cms_start_registered(false) 598 { 599 if (ExplicitGCInvokesConcurrentAndUnloadsClasses) { 600 ExplicitGCInvokesConcurrent = true; 601 } 602 // Now expand the span and allocate the collection support structures 603 // (MUT, marking bit map etc.) to cover both generations subject to 604 // collection. 605 606 // For use by dirty card to oop closures. 607 _cmsGen->cmsSpace()->set_collector(this); 608 609 // Allocate MUT and marking bit map 610 { 611 MutexLockerEx x(_markBitMap.lock(), Mutex::_no_safepoint_check_flag); 612 if (!_markBitMap.allocate(_span)) { 613 warning("Failed to allocate CMS Bit Map"); 614 return; 615 } 616 assert(_markBitMap.covers(_span), "_markBitMap inconsistency?"); 617 } 618 { 619 _modUnionTable.allocate(_span); 620 assert(_modUnionTable.covers(_span), "_modUnionTable inconsistency?"); 621 } 622 623 if (!_markStack.allocate(MarkStackSize)) { 624 warning("Failed to allocate CMS Marking Stack"); 625 return; 626 } 627 628 // Support for multi-threaded concurrent phases 629 if (CMSConcurrentMTEnabled) { 630 if (FLAG_IS_DEFAULT(ConcGCThreads)) { 631 // just for now 632 FLAG_SET_DEFAULT(ConcGCThreads, (ParallelGCThreads + 3)/4); 633 } 634 if (ConcGCThreads > 1) { 635 _conc_workers = new YieldingFlexibleWorkGang("Parallel CMS Threads", 636 ConcGCThreads, true); 637 if (_conc_workers == NULL) { 638 warning("GC/CMS: _conc_workers allocation failure: " 639 "forcing -CMSConcurrentMTEnabled"); 640 CMSConcurrentMTEnabled = false; 641 } else { 642 _conc_workers->initialize_workers(); 643 } 644 } else { 645 CMSConcurrentMTEnabled = false; 646 } 647 } 648 if (!CMSConcurrentMTEnabled) { 649 ConcGCThreads = 0; 650 } else { 651 // Turn off CMSCleanOnEnter optimization temporarily for 652 // the MT case where it's not fixed yet; see 6178663. 653 CMSCleanOnEnter = false; 654 } 655 assert((_conc_workers != NULL) == (ConcGCThreads > 1), 656 "Inconsistency"); 657 658 // Parallel task queues; these are shared for the 659 // concurrent and stop-world phases of CMS, but 660 // are not shared with parallel scavenge (ParNew). 661 { 662 uint i; 663 uint num_queues = (uint) MAX2(ParallelGCThreads, ConcGCThreads); 664 665 if ((CMSParallelRemarkEnabled || CMSConcurrentMTEnabled 666 || ParallelRefProcEnabled) 667 && num_queues > 0) { 668 _task_queues = new OopTaskQueueSet(num_queues); 669 if (_task_queues == NULL) { 670 warning("task_queues allocation failure."); 671 return; 672 } 673 _hash_seed = NEW_C_HEAP_ARRAY(int, num_queues, mtGC); 674 if (_hash_seed == NULL) { 675 warning("_hash_seed array allocation failure"); 676 return; 677 } 678 679 typedef Padded<OopTaskQueue> PaddedOopTaskQueue; 680 for (i = 0; i < num_queues; i++) { 681 PaddedOopTaskQueue *q = new PaddedOopTaskQueue(); 682 if (q == NULL) { 683 warning("work_queue allocation failure."); 684 return; 685 } 686 _task_queues->register_queue(i, q); 687 } 688 for (i = 0; i < num_queues; i++) { 689 _task_queues->queue(i)->initialize(); 690 _hash_seed[i] = 17; // copied from ParNew 691 } 692 } 693 } 694 695 _cmsGen ->init_initiating_occupancy(CMSInitiatingOccupancyFraction, CMSTriggerRatio); 696 697 // Clip CMSBootstrapOccupancy between 0 and 100. 698 _bootstrap_occupancy = ((double)CMSBootstrapOccupancy)/(double)100; 699 700 _full_gcs_since_conc_gc = 0; 701 702 // Now tell CMS generations the identity of their collector 703 ConcurrentMarkSweepGeneration::set_collector(this); 704 705 // Create & start a CMS thread for this CMS collector 706 _cmsThread = ConcurrentMarkSweepThread::start(this); 707 assert(cmsThread() != NULL, "CMS Thread should have been created"); 708 assert(cmsThread()->collector() == this, 709 "CMS Thread should refer to this gen"); 710 assert(CGC_lock != NULL, "Where's the CGC_lock?"); 711 712 // Support for parallelizing young gen rescan 713 GenCollectedHeap* gch = GenCollectedHeap::heap(); 714 _young_gen = gch->prev_gen(_cmsGen); 715 if (gch->supports_inline_contig_alloc()) { 716 _top_addr = gch->top_addr(); 717 _end_addr = gch->end_addr(); 718 assert(_young_gen != NULL, "no _young_gen"); 719 _eden_chunk_index = 0; 720 _eden_chunk_capacity = (_young_gen->max_capacity()+CMSSamplingGrain)/CMSSamplingGrain; 721 _eden_chunk_array = NEW_C_HEAP_ARRAY(HeapWord*, _eden_chunk_capacity, mtGC); 722 if (_eden_chunk_array == NULL) { 723 _eden_chunk_capacity = 0; 724 warning("GC/CMS: _eden_chunk_array allocation failure"); 725 } 726 } 727 assert(_eden_chunk_array != NULL || _eden_chunk_capacity == 0, "Error"); 728 729 // Support for parallelizing survivor space rescan 730 if ((CMSParallelRemarkEnabled && CMSParallelSurvivorRemarkEnabled) || CMSParallelInitialMarkEnabled) { 731 const size_t max_plab_samples = 732 ((DefNewGeneration*)_young_gen)->max_survivor_size()/MinTLABSize; 733 734 _survivor_plab_array = NEW_C_HEAP_ARRAY(ChunkArray, ParallelGCThreads, mtGC); 735 _survivor_chunk_array = NEW_C_HEAP_ARRAY(HeapWord*, 2*max_plab_samples, mtGC); 736 _cursor = NEW_C_HEAP_ARRAY(size_t, ParallelGCThreads, mtGC); 737 if (_survivor_plab_array == NULL || _survivor_chunk_array == NULL 738 || _cursor == NULL) { 739 warning("Failed to allocate survivor plab/chunk array"); 740 if (_survivor_plab_array != NULL) { 741 FREE_C_HEAP_ARRAY(ChunkArray, _survivor_plab_array, mtGC); 742 _survivor_plab_array = NULL; 743 } 744 if (_survivor_chunk_array != NULL) { 745 FREE_C_HEAP_ARRAY(HeapWord*, _survivor_chunk_array, mtGC); 746 _survivor_chunk_array = NULL; 747 } 748 if (_cursor != NULL) { 749 FREE_C_HEAP_ARRAY(size_t, _cursor, mtGC); 750 _cursor = NULL; 751 } 752 } else { 753 _survivor_chunk_capacity = 2*max_plab_samples; 754 for (uint i = 0; i < ParallelGCThreads; i++) { 755 HeapWord** vec = NEW_C_HEAP_ARRAY(HeapWord*, max_plab_samples, mtGC); 756 if (vec == NULL) { 757 warning("Failed to allocate survivor plab array"); 758 for (int j = i; j > 0; j--) { 759 FREE_C_HEAP_ARRAY(HeapWord*, _survivor_plab_array[j-1].array(), mtGC); 760 } 761 FREE_C_HEAP_ARRAY(ChunkArray, _survivor_plab_array, mtGC); 762 FREE_C_HEAP_ARRAY(HeapWord*, _survivor_chunk_array, mtGC); 763 _survivor_plab_array = NULL; 764 _survivor_chunk_array = NULL; 765 _survivor_chunk_capacity = 0; 766 break; 767 } else { 768 ChunkArray* cur = 769 ::new (&_survivor_plab_array[i]) ChunkArray(vec, 770 max_plab_samples); 771 assert(cur->end() == 0, "Should be 0"); 772 assert(cur->array() == vec, "Should be vec"); 773 assert(cur->capacity() == max_plab_samples, "Error"); 774 } 775 } 776 } 777 } 778 assert( ( _survivor_plab_array != NULL 779 && _survivor_chunk_array != NULL) 780 || ( _survivor_chunk_capacity == 0 781 && _survivor_chunk_index == 0), 782 "Error"); 783 784 NOT_PRODUCT(_overflow_counter = CMSMarkStackOverflowInterval;) 785 _gc_counters = new CollectorCounters("CMS", 1); 786 _completed_initialization = true; 787 _inter_sweep_timer.start(); // start of time 788 } 789 790 const char* ConcurrentMarkSweepGeneration::name() const { 791 return "concurrent mark-sweep generation"; 792 } 793 void ConcurrentMarkSweepGeneration::update_counters() { 794 if (UsePerfData) { 795 _space_counters->update_all(); 796 _gen_counters->update_all(); 797 } 798 } 799 800 // this is an optimized version of update_counters(). it takes the 801 // used value as a parameter rather than computing it. 802 // 803 void ConcurrentMarkSweepGeneration::update_counters(size_t used) { 804 if (UsePerfData) { 805 _space_counters->update_used(used); 806 _space_counters->update_capacity(); 807 _gen_counters->update_all(); 808 } 809 } 810 811 void ConcurrentMarkSweepGeneration::print() const { 812 Generation::print(); 813 cmsSpace()->print(); 814 } 815 816 #ifndef PRODUCT 817 void ConcurrentMarkSweepGeneration::print_statistics() { 818 cmsSpace()->printFLCensus(0); 819 } 820 #endif 821 822 void ConcurrentMarkSweepGeneration::printOccupancy(const char *s) { 823 GenCollectedHeap* gch = GenCollectedHeap::heap(); 824 if (PrintGCDetails) { 825 if (Verbose) { 826 gclog_or_tty->print("[%d %s-%s: "SIZE_FORMAT"("SIZE_FORMAT")]", 827 level(), short_name(), s, used(), capacity()); 828 } else { 829 gclog_or_tty->print("[%d %s-%s: "SIZE_FORMAT"K("SIZE_FORMAT"K)]", 830 level(), short_name(), s, used() / K, capacity() / K); 831 } 832 } 833 if (Verbose) { 834 gclog_or_tty->print(" "SIZE_FORMAT"("SIZE_FORMAT")", 835 gch->used(), gch->capacity()); 836 } else { 837 gclog_or_tty->print(" "SIZE_FORMAT"K("SIZE_FORMAT"K)", 838 gch->used() / K, gch->capacity() / K); 839 } 840 } 841 842 size_t 843 ConcurrentMarkSweepGeneration::contiguous_available() const { 844 // dld proposes an improvement in precision here. If the committed 845 // part of the space ends in a free block we should add that to 846 // uncommitted size in the calculation below. Will make this 847 // change later, staying with the approximation below for the 848 // time being. -- ysr. 849 return MAX2(_virtual_space.uncommitted_size(), unsafe_max_alloc_nogc()); 850 } 851 852 size_t 853 ConcurrentMarkSweepGeneration::unsafe_max_alloc_nogc() const { 854 return _cmsSpace->max_alloc_in_words() * HeapWordSize; 855 } 856 857 size_t ConcurrentMarkSweepGeneration::max_available() const { 858 return free() + _virtual_space.uncommitted_size(); 859 } 860 861 bool ConcurrentMarkSweepGeneration::promotion_attempt_is_safe(size_t max_promotion_in_bytes) const { 862 size_t available = max_available(); 863 size_t av_promo = (size_t)gc_stats()->avg_promoted()->padded_average(); 864 bool res = (available >= av_promo) || (available >= max_promotion_in_bytes); 865 if (Verbose && PrintGCDetails) { 866 gclog_or_tty->print_cr( 867 "CMS: promo attempt is%s safe: available("SIZE_FORMAT") %s av_promo("SIZE_FORMAT")," 868 "max_promo("SIZE_FORMAT")", 869 res? "":" not", available, res? ">=":"<", 870 av_promo, max_promotion_in_bytes); 871 } 872 return res; 873 } 874 875 // At a promotion failure dump information on block layout in heap 876 // (cms old generation). 877 void ConcurrentMarkSweepGeneration::promotion_failure_occurred() { 878 if (CMSDumpAtPromotionFailure) { 879 cmsSpace()->dump_at_safepoint_with_locks(collector(), gclog_or_tty); 880 } 881 if (CMSFastPromotionFailure) { 882 reset_promotion_failed(); 883 } 884 } 885 886 CompactibleSpace* 887 ConcurrentMarkSweepGeneration::first_compaction_space() const { 888 return _cmsSpace; 889 } 890 891 void ConcurrentMarkSweepGeneration::reset_after_compaction() { 892 // Clear the promotion information. These pointers can be adjusted 893 // along with all the other pointers into the heap but 894 // compaction is expected to be a rare event with 895 // a heap using cms so don't do it without seeing the need. 896 if (CollectedHeap::use_parallel_gc_threads()) { 897 for (uint i = 0; i < ParallelGCThreads; i++) { 898 _par_gc_thread_states[i]->promo.reset(); 899 } 900 } 901 } 902 903 void ConcurrentMarkSweepGeneration::space_iterate(SpaceClosure* blk, bool usedOnly) { 904 blk->do_space(_cmsSpace); 905 } 906 907 void ConcurrentMarkSweepGeneration::compute_new_size() { 908 assert_locked_or_safepoint(Heap_lock); 909 910 // If incremental collection failed, we just want to expand 911 // to the limit. 912 if (incremental_collection_failed()) { 913 clear_incremental_collection_failed(); 914 grow_to_reserved(); 915 return; 916 } 917 918 // The heap has been compacted but not reset yet. 919 // Any metric such as free() or used() will be incorrect. 920 921 CardGeneration::compute_new_size(); 922 923 // Reset again after a possible resizing 924 if (did_compact()) { 925 cmsSpace()->reset_after_compaction(); 926 } 927 } 928 929 void ConcurrentMarkSweepGeneration::compute_new_size_free_list() { 930 assert_locked_or_safepoint(Heap_lock); 931 932 // If incremental collection failed, we just want to expand 933 // to the limit. 934 if (incremental_collection_failed()) { 935 clear_incremental_collection_failed(); 936 grow_to_reserved(); 937 return; 938 } 939 940 double free_percentage = ((double) free()) / capacity(); 941 double desired_free_percentage = (double) MinHeapFreeRatio / 100; 942 double maximum_free_percentage = (double) MaxHeapFreeRatio / 100; 943 944 // compute expansion delta needed for reaching desired free percentage 945 if (free_percentage < desired_free_percentage) { 946 size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage)); 947 assert(desired_capacity >= capacity(), "invalid expansion size"); 948 size_t expand_bytes = MAX2(desired_capacity - capacity(), MinHeapDeltaBytes); 949 if (PrintGCDetails && Verbose) { 950 size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage)); 951 gclog_or_tty->print_cr("\nFrom compute_new_size: "); 952 gclog_or_tty->print_cr(" Free fraction %f", free_percentage); 953 gclog_or_tty->print_cr(" Desired free fraction %f", 954 desired_free_percentage); 955 gclog_or_tty->print_cr(" Maximum free fraction %f", 956 maximum_free_percentage); 957 gclog_or_tty->print_cr(" Capacity "SIZE_FORMAT, capacity()/1000); 958 gclog_or_tty->print_cr(" Desired capacity "SIZE_FORMAT, 959 desired_capacity/1000); 960 int prev_level = level() - 1; 961 if (prev_level >= 0) { 962 size_t prev_size = 0; 963 GenCollectedHeap* gch = GenCollectedHeap::heap(); 964 Generation* prev_gen = gch->_gens[prev_level]; 965 prev_size = prev_gen->capacity(); 966 gclog_or_tty->print_cr(" Younger gen size "SIZE_FORMAT, 967 prev_size/1000); 968 } 969 gclog_or_tty->print_cr(" unsafe_max_alloc_nogc "SIZE_FORMAT, 970 unsafe_max_alloc_nogc()/1000); 971 gclog_or_tty->print_cr(" contiguous available "SIZE_FORMAT, 972 contiguous_available()/1000); 973 gclog_or_tty->print_cr(" Expand by "SIZE_FORMAT" (bytes)", 974 expand_bytes); 975 } 976 // safe if expansion fails 977 expand(expand_bytes, 0, CMSExpansionCause::_satisfy_free_ratio); 978 if (PrintGCDetails && Verbose) { 979 gclog_or_tty->print_cr(" Expanded free fraction %f", 980 ((double) free()) / capacity()); 981 } 982 } else { 983 size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage)); 984 assert(desired_capacity <= capacity(), "invalid expansion size"); 985 size_t shrink_bytes = capacity() - desired_capacity; 986 // Don't shrink unless the delta is greater than the minimum shrink we want 987 if (shrink_bytes >= MinHeapDeltaBytes) { 988 shrink_free_list_by(shrink_bytes); 989 } 990 } 991 } 992 993 Mutex* ConcurrentMarkSweepGeneration::freelistLock() const { 994 return cmsSpace()->freelistLock(); 995 } 996 997 HeapWord* ConcurrentMarkSweepGeneration::allocate(size_t size, 998 bool tlab) { 999 CMSSynchronousYieldRequest yr; 1000 MutexLockerEx x(freelistLock(), 1001 Mutex::_no_safepoint_check_flag); 1002 return have_lock_and_allocate(size, tlab); 1003 } 1004 1005 HeapWord* ConcurrentMarkSweepGeneration::have_lock_and_allocate(size_t size, 1006 bool tlab /* ignored */) { 1007 assert_lock_strong(freelistLock()); 1008 size_t adjustedSize = CompactibleFreeListSpace::adjustObjectSize(size); 1009 HeapWord* res = cmsSpace()->allocate(adjustedSize); 1010 // Allocate the object live (grey) if the background collector has 1011 // started marking. This is necessary because the marker may 1012 // have passed this address and consequently this object will 1013 // not otherwise be greyed and would be incorrectly swept up. 1014 // Note that if this object contains references, the writing 1015 // of those references will dirty the card containing this object 1016 // allowing the object to be blackened (and its references scanned) 1017 // either during a preclean phase or at the final checkpoint. 1018 if (res != NULL) { 1019 // We may block here with an uninitialized object with 1020 // its mark-bit or P-bits not yet set. Such objects need 1021 // to be safely navigable by block_start(). 1022 assert(oop(res)->klass_or_null() == NULL, "Object should be uninitialized here."); 1023 assert(!((FreeChunk*)res)->is_free(), "Error, block will look free but show wrong size"); 1024 collector()->direct_allocated(res, adjustedSize); 1025 _direct_allocated_words += adjustedSize; 1026 // allocation counters 1027 NOT_PRODUCT( 1028 _numObjectsAllocated++; 1029 _numWordsAllocated += (int)adjustedSize; 1030 ) 1031 } 1032 return res; 1033 } 1034 1035 // In the case of direct allocation by mutators in a generation that 1036 // is being concurrently collected, the object must be allocated 1037 // live (grey) if the background collector has started marking. 1038 // This is necessary because the marker may 1039 // have passed this address and consequently this object will 1040 // not otherwise be greyed and would be incorrectly swept up. 1041 // Note that if this object contains references, the writing 1042 // of those references will dirty the card containing this object 1043 // allowing the object to be blackened (and its references scanned) 1044 // either during a preclean phase or at the final checkpoint. 1045 void CMSCollector::direct_allocated(HeapWord* start, size_t size) { 1046 assert(_markBitMap.covers(start, size), "Out of bounds"); 1047 if (_collectorState >= Marking) { 1048 MutexLockerEx y(_markBitMap.lock(), 1049 Mutex::_no_safepoint_check_flag); 1050 // [see comments preceding SweepClosure::do_blk() below for details] 1051 // 1052 // Can the P-bits be deleted now? JJJ 1053 // 1054 // 1. need to mark the object as live so it isn't collected 1055 // 2. need to mark the 2nd bit to indicate the object may be uninitialized 1056 // 3. need to mark the end of the object so marking, precleaning or sweeping 1057 // can skip over uninitialized or unparsable objects. An allocated 1058 // object is considered uninitialized for our purposes as long as 1059 // its klass word is NULL. All old gen objects are parsable 1060 // as soon as they are initialized.) 1061 _markBitMap.mark(start); // object is live 1062 _markBitMap.mark(start + 1); // object is potentially uninitialized? 1063 _markBitMap.mark(start + size - 1); 1064 // mark end of object 1065 } 1066 // check that oop looks uninitialized 1067 assert(oop(start)->klass_or_null() == NULL, "_klass should be NULL"); 1068 } 1069 1070 void CMSCollector::promoted(bool par, HeapWord* start, 1071 bool is_obj_array, size_t obj_size) { 1072 assert(_markBitMap.covers(start), "Out of bounds"); 1073 // See comment in direct_allocated() about when objects should 1074 // be allocated live. 1075 if (_collectorState >= Marking) { 1076 // we already hold the marking bit map lock, taken in 1077 // the prologue 1078 if (par) { 1079 _markBitMap.par_mark(start); 1080 } else { 1081 _markBitMap.mark(start); 1082 } 1083 // We don't need to mark the object as uninitialized (as 1084 // in direct_allocated above) because this is being done with the 1085 // world stopped and the object will be initialized by the 1086 // time the marking, precleaning or sweeping get to look at it. 1087 // But see the code for copying objects into the CMS generation, 1088 // where we need to ensure that concurrent readers of the 1089 // block offset table are able to safely navigate a block that 1090 // is in flux from being free to being allocated (and in 1091 // transition while being copied into) and subsequently 1092 // becoming a bona-fide object when the copy/promotion is complete. 1093 assert(SafepointSynchronize::is_at_safepoint(), 1094 "expect promotion only at safepoints"); 1095 1096 if (_collectorState < Sweeping) { 1097 // Mark the appropriate cards in the modUnionTable, so that 1098 // this object gets scanned before the sweep. If this is 1099 // not done, CMS generation references in the object might 1100 // not get marked. 1101 // For the case of arrays, which are otherwise precisely 1102 // marked, we need to dirty the entire array, not just its head. 1103 if (is_obj_array) { 1104 // The [par_]mark_range() method expects mr.end() below to 1105 // be aligned to the granularity of a bit's representation 1106 // in the heap. In the case of the MUT below, that's a 1107 // card size. 1108 MemRegion mr(start, 1109 (HeapWord*)round_to((intptr_t)(start + obj_size), 1110 CardTableModRefBS::card_size /* bytes */)); 1111 if (par) { 1112 _modUnionTable.par_mark_range(mr); 1113 } else { 1114 _modUnionTable.mark_range(mr); 1115 } 1116 } else { // not an obj array; we can just mark the head 1117 if (par) { 1118 _modUnionTable.par_mark(start); 1119 } else { 1120 _modUnionTable.mark(start); 1121 } 1122 } 1123 } 1124 } 1125 } 1126 1127 static inline size_t percent_of_space(Space* space, HeapWord* addr) 1128 { 1129 size_t delta = pointer_delta(addr, space->bottom()); 1130 return (size_t)(delta * 100.0 / (space->capacity() / HeapWordSize)); 1131 } 1132 1133 void CMSCollector::icms_update_allocation_limits() 1134 { 1135 Generation* young = GenCollectedHeap::heap()->get_gen(0); 1136 EdenSpace* eden = young->as_DefNewGeneration()->eden(); 1137 1138 const unsigned int duty_cycle = stats().icms_update_duty_cycle(); 1139 if (CMSTraceIncrementalPacing) { 1140 stats().print(); 1141 } 1142 1143 assert(duty_cycle <= 100, "invalid duty cycle"); 1144 if (duty_cycle != 0) { 1145 // The duty_cycle is a percentage between 0 and 100; convert to words and 1146 // then compute the offset from the endpoints of the space. 1147 size_t free_words = eden->free() / HeapWordSize; 1148 double free_words_dbl = (double)free_words; 1149 size_t duty_cycle_words = (size_t)(free_words_dbl * duty_cycle / 100.0); 1150 size_t offset_words = (free_words - duty_cycle_words) / 2; 1151 1152 _icms_start_limit = eden->top() + offset_words; 1153 _icms_stop_limit = eden->end() - offset_words; 1154 1155 // The limits may be adjusted (shifted to the right) by 1156 // CMSIncrementalOffset, to allow the application more mutator time after a 1157 // young gen gc (when all mutators were stopped) and before CMS starts and 1158 // takes away one or more cpus. 1159 if (CMSIncrementalOffset != 0) { 1160 double adjustment_dbl = free_words_dbl * CMSIncrementalOffset / 100.0; 1161 size_t adjustment = (size_t)adjustment_dbl; 1162 HeapWord* tmp_stop = _icms_stop_limit + adjustment; 1163 if (tmp_stop > _icms_stop_limit && tmp_stop < eden->end()) { 1164 _icms_start_limit += adjustment; 1165 _icms_stop_limit = tmp_stop; 1166 } 1167 } 1168 } 1169 if (duty_cycle == 0 || (_icms_start_limit == _icms_stop_limit)) { 1170 _icms_start_limit = _icms_stop_limit = eden->end(); 1171 } 1172 1173 // Install the new start limit. 1174 eden->set_soft_end(_icms_start_limit); 1175 1176 if (CMSTraceIncrementalMode) { 1177 gclog_or_tty->print(" icms alloc limits: " 1178 PTR_FORMAT "," PTR_FORMAT 1179 " (" SIZE_FORMAT "%%," SIZE_FORMAT "%%) ", 1180 p2i(_icms_start_limit), p2i(_icms_stop_limit), 1181 percent_of_space(eden, _icms_start_limit), 1182 percent_of_space(eden, _icms_stop_limit)); 1183 if (Verbose) { 1184 gclog_or_tty->print("eden: "); 1185 eden->print_on(gclog_or_tty); 1186 } 1187 } 1188 } 1189 1190 // Any changes here should try to maintain the invariant 1191 // that if this method is called with _icms_start_limit 1192 // and _icms_stop_limit both NULL, then it should return NULL 1193 // and not notify the icms thread. 1194 HeapWord* 1195 CMSCollector::allocation_limit_reached(Space* space, HeapWord* top, 1196 size_t word_size) 1197 { 1198 // A start_limit equal to end() means the duty cycle is 0, so treat that as a 1199 // nop. 1200 if (CMSIncrementalMode && _icms_start_limit != space->end()) { 1201 if (top <= _icms_start_limit) { 1202 if (CMSTraceIncrementalMode) { 1203 space->print_on(gclog_or_tty); 1204 gclog_or_tty->stamp(); 1205 gclog_or_tty->print_cr(" start limit top=" PTR_FORMAT 1206 ", new limit=" PTR_FORMAT 1207 " (" SIZE_FORMAT "%%)", 1208 p2i(top), p2i(_icms_stop_limit), 1209 percent_of_space(space, _icms_stop_limit)); 1210 } 1211 ConcurrentMarkSweepThread::start_icms(); 1212 assert(top < _icms_stop_limit, "Tautology"); 1213 if (word_size < pointer_delta(_icms_stop_limit, top)) { 1214 return _icms_stop_limit; 1215 } 1216 1217 // The allocation will cross both the _start and _stop limits, so do the 1218 // stop notification also and return end(). 1219 if (CMSTraceIncrementalMode) { 1220 space->print_on(gclog_or_tty); 1221 gclog_or_tty->stamp(); 1222 gclog_or_tty->print_cr(" +stop limit top=" PTR_FORMAT 1223 ", new limit=" PTR_FORMAT 1224 " (" SIZE_FORMAT "%%)", 1225 p2i(top), p2i(space->end()), 1226 percent_of_space(space, space->end())); 1227 } 1228 ConcurrentMarkSweepThread::stop_icms(); 1229 return space->end(); 1230 } 1231 1232 if (top <= _icms_stop_limit) { 1233 if (CMSTraceIncrementalMode) { 1234 space->print_on(gclog_or_tty); 1235 gclog_or_tty->stamp(); 1236 gclog_or_tty->print_cr(" stop limit top=" PTR_FORMAT 1237 ", new limit=" PTR_FORMAT 1238 " (" SIZE_FORMAT "%%)", 1239 top, space->end(), 1240 percent_of_space(space, space->end())); 1241 } 1242 ConcurrentMarkSweepThread::stop_icms(); 1243 return space->end(); 1244 } 1245 1246 if (CMSTraceIncrementalMode) { 1247 space->print_on(gclog_or_tty); 1248 gclog_or_tty->stamp(); 1249 gclog_or_tty->print_cr(" end limit top=" PTR_FORMAT 1250 ", new limit=" PTR_FORMAT, 1251 top, NULL); 1252 } 1253 } 1254 1255 return NULL; 1256 } 1257 1258 oop ConcurrentMarkSweepGeneration::promote(oop obj, size_t obj_size) { 1259 assert(obj_size == (size_t)obj->size(), "bad obj_size passed in"); 1260 // allocate, copy and if necessary update promoinfo -- 1261 // delegate to underlying space. 1262 assert_lock_strong(freelistLock()); 1263 1264 #ifndef PRODUCT 1265 if (Universe::heap()->promotion_should_fail()) { 1266 return NULL; 1267 } 1268 #endif // #ifndef PRODUCT 1269 1270 oop res = _cmsSpace->promote(obj, obj_size); 1271 if (res == NULL) { 1272 // expand and retry 1273 size_t s = _cmsSpace->expansionSpaceRequired(obj_size); // HeapWords 1274 expand(s*HeapWordSize, MinHeapDeltaBytes, 1275 CMSExpansionCause::_satisfy_promotion); 1276 // Since there's currently no next generation, we don't try to promote 1277 // into a more senior generation. 1278 assert(next_gen() == NULL, "assumption, based upon which no attempt " 1279 "is made to pass on a possibly failing " 1280 "promotion to next generation"); 1281 res = _cmsSpace->promote(obj, obj_size); 1282 } 1283 if (res != NULL) { 1284 // See comment in allocate() about when objects should 1285 // be allocated live. 1286 assert(obj->is_oop(), "Will dereference klass pointer below"); 1287 collector()->promoted(false, // Not parallel 1288 (HeapWord*)res, obj->is_objArray(), obj_size); 1289 // promotion counters 1290 NOT_PRODUCT( 1291 _numObjectsPromoted++; 1292 _numWordsPromoted += 1293 (int)(CompactibleFreeListSpace::adjustObjectSize(obj->size())); 1294 ) 1295 } 1296 return res; 1297 } 1298 1299 1300 HeapWord* 1301 ConcurrentMarkSweepGeneration::allocation_limit_reached(Space* space, 1302 HeapWord* top, 1303 size_t word_sz) 1304 { 1305 return collector()->allocation_limit_reached(space, top, word_sz); 1306 } 1307 1308 // IMPORTANT: Notes on object size recognition in CMS. 1309 // --------------------------------------------------- 1310 // A block of storage in the CMS generation is always in 1311 // one of three states. A free block (FREE), an allocated 1312 // object (OBJECT) whose size() method reports the correct size, 1313 // and an intermediate state (TRANSIENT) in which its size cannot 1314 // be accurately determined. 1315 // STATE IDENTIFICATION: (32 bit and 64 bit w/o COOPS) 1316 // ----------------------------------------------------- 1317 // FREE: klass_word & 1 == 1; mark_word holds block size 1318 // 1319 // OBJECT: klass_word installed; klass_word != 0 && klass_word & 1 == 0; 1320 // obj->size() computes correct size 1321 // 1322 // TRANSIENT: klass_word == 0; size is indeterminate until we become an OBJECT 1323 // 1324 // STATE IDENTIFICATION: (64 bit+COOPS) 1325 // ------------------------------------ 1326 // FREE: mark_word & CMS_FREE_BIT == 1; mark_word & ~CMS_FREE_BIT gives block_size 1327 // 1328 // OBJECT: klass_word installed; klass_word != 0; 1329 // obj->size() computes correct size 1330 // 1331 // TRANSIENT: klass_word == 0; size is indeterminate until we become an OBJECT 1332 // 1333 // 1334 // STATE TRANSITION DIAGRAM 1335 // 1336 // mut / parnew mut / parnew 1337 // FREE --------------------> TRANSIENT ---------------------> OBJECT --| 1338 // ^ | 1339 // |------------------------ DEAD <------------------------------------| 1340 // sweep mut 1341 // 1342 // While a block is in TRANSIENT state its size cannot be determined 1343 // so readers will either need to come back later or stall until 1344 // the size can be determined. Note that for the case of direct 1345 // allocation, P-bits, when available, may be used to determine the 1346 // size of an object that may not yet have been initialized. 1347 1348 // Things to support parallel young-gen collection. 1349 oop 1350 ConcurrentMarkSweepGeneration::par_promote(int thread_num, 1351 oop old, markOop m, 1352 size_t word_sz) { 1353 #ifndef PRODUCT 1354 if (Universe::heap()->promotion_should_fail()) { 1355 return NULL; 1356 } 1357 #endif // #ifndef PRODUCT 1358 if (CMSFastPromotionFailure && has_promotion_failed()) { 1359 return NULL; 1360 } 1361 1362 CMSParGCThreadState* ps = _par_gc_thread_states[thread_num]; 1363 PromotionInfo* promoInfo = &ps->promo; 1364 // if we are tracking promotions, then first ensure space for 1365 // promotion (including spooling space for saving header if necessary). 1366 // then allocate and copy, then track promoted info if needed. 1367 // When tracking (see PromotionInfo::track()), the mark word may 1368 // be displaced and in this case restoration of the mark word 1369 // occurs in the (oop_since_save_marks_)iterate phase. 1370 if (promoInfo->tracking() && !promoInfo->ensure_spooling_space()) { 1371 // Out of space for allocating spooling buffers; 1372 // try expanding and allocating spooling buffers. 1373 if (!expand_and_ensure_spooling_space(promoInfo)) { 1374 return NULL; 1375 } 1376 } 1377 assert(promoInfo->has_spooling_space(), "Control point invariant"); 1378 const size_t alloc_sz = CompactibleFreeListSpace::adjustObjectSize(word_sz); 1379 HeapWord* obj_ptr = ps->lab.alloc(alloc_sz); 1380 if (obj_ptr == NULL) { 1381 if (CMSFastPromotionFailure && has_promotion_failed()) { 1382 return NULL; 1383 } 1384 obj_ptr = expand_and_par_lab_allocate(ps, alloc_sz); 1385 if (obj_ptr == NULL) { 1386 return NULL; 1387 } 1388 } 1389 oop obj = oop(obj_ptr); 1390 OrderAccess::storestore(); 1391 assert(obj->klass_or_null() == NULL, "Object should be uninitialized here."); 1392 assert(!((FreeChunk*)obj_ptr)->is_free(), "Error, block will look free but show wrong size"); 1393 // IMPORTANT: See note on object initialization for CMS above. 1394 // Otherwise, copy the object. Here we must be careful to insert the 1395 // klass pointer last, since this marks the block as an allocated object. 1396 // Except with compressed oops it's the mark word. 1397 HeapWord* old_ptr = (HeapWord*)old; 1398 // Restore the mark word copied above. 1399 obj->set_mark(m); 1400 assert(obj->klass_or_null() == NULL, "Object should be uninitialized here."); 1401 assert(!((FreeChunk*)obj_ptr)->is_free(), "Error, block will look free but show wrong size"); 1402 OrderAccess::storestore(); 1403 1404 if (UseCompressedClassPointers) { 1405 // Copy gap missed by (aligned) header size calculation below 1406 obj->set_klass_gap(old->klass_gap()); 1407 } 1408 if (word_sz > (size_t)oopDesc::header_size()) { 1409 Copy::aligned_disjoint_words(old_ptr + oopDesc::header_size(), 1410 obj_ptr + oopDesc::header_size(), 1411 word_sz - oopDesc::header_size()); 1412 } 1413 1414 // Now we can track the promoted object, if necessary. We take care 1415 // to delay the transition from uninitialized to full object 1416 // (i.e., insertion of klass pointer) until after, so that it 1417 // atomically becomes a promoted object. 1418 if (promoInfo->tracking()) { 1419 promoInfo->track((PromotedObject*)obj, old->klass()); 1420 } 1421 assert(obj->klass_or_null() == NULL, "Object should be uninitialized here."); 1422 assert(!((FreeChunk*)obj_ptr)->is_free(), "Error, block will look free but show wrong size"); 1423 assert(old->is_oop(), "Will use and dereference old klass ptr below"); 1424 1425 // Finally, install the klass pointer (this should be volatile). 1426 OrderAccess::storestore(); 1427 obj->set_klass(old->klass()); 1428 // We should now be able to calculate the right size for this object 1429 assert(obj->is_oop() && obj->size() == (int)word_sz, "Error, incorrect size computed for promoted object"); 1430 1431 collector()->promoted(true, // parallel 1432 obj_ptr, old->is_objArray(), word_sz); 1433 1434 NOT_PRODUCT( 1435 Atomic::inc_ptr(&_numObjectsPromoted); 1436 Atomic::add_ptr(alloc_sz, &_numWordsPromoted); 1437 ) 1438 1439 return obj; 1440 } 1441 1442 void 1443 ConcurrentMarkSweepGeneration:: 1444 par_promote_alloc_undo(int thread_num, 1445 HeapWord* obj, size_t word_sz) { 1446 // CMS does not support promotion undo. 1447 ShouldNotReachHere(); 1448 } 1449 1450 void 1451 ConcurrentMarkSweepGeneration:: 1452 par_promote_alloc_done(int thread_num) { 1453 CMSParGCThreadState* ps = _par_gc_thread_states[thread_num]; 1454 ps->lab.retire(thread_num); 1455 } 1456 1457 void 1458 ConcurrentMarkSweepGeneration:: 1459 par_oop_since_save_marks_iterate_done(int thread_num) { 1460 CMSParGCThreadState* ps = _par_gc_thread_states[thread_num]; 1461 ParScanWithoutBarrierClosure* dummy_cl = NULL; 1462 ps->promo.promoted_oops_iterate_nv(dummy_cl); 1463 } 1464 1465 bool ConcurrentMarkSweepGeneration::should_collect(bool full, 1466 size_t size, 1467 bool tlab) 1468 { 1469 // We allow a STW collection only if a full 1470 // collection was requested. 1471 return full || should_allocate(size, tlab); // FIX ME !!! 1472 // This and promotion failure handling are connected at the 1473 // hip and should be fixed by untying them. 1474 } 1475 1476 bool CMSCollector::shouldConcurrentCollect() { 1477 if (_full_gc_requested) { 1478 if (Verbose && PrintGCDetails) { 1479 gclog_or_tty->print_cr("CMSCollector: collect because of explicit " 1480 " gc request (or gc_locker)"); 1481 } 1482 return true; 1483 } 1484 1485 // For debugging purposes, change the type of collection. 1486 // If the rotation is not on the concurrent collection 1487 // type, don't start a concurrent collection. 1488 NOT_PRODUCT( 1489 if (RotateCMSCollectionTypes && 1490 (_cmsGen->debug_collection_type() != 1491 ConcurrentMarkSweepGeneration::Concurrent_collection_type)) { 1492 assert(_cmsGen->debug_collection_type() != 1493 ConcurrentMarkSweepGeneration::Unknown_collection_type, 1494 "Bad cms collection type"); 1495 return false; 1496 } 1497 ) 1498 1499 FreelistLocker x(this); 1500 // ------------------------------------------------------------------ 1501 // Print out lots of information which affects the initiation of 1502 // a collection. 1503 if (PrintCMSInitiationStatistics && stats().valid()) { 1504 gclog_or_tty->print("CMSCollector shouldConcurrentCollect: "); 1505 gclog_or_tty->stamp(); 1506 gclog_or_tty->cr(); 1507 stats().print_on(gclog_or_tty); 1508 gclog_or_tty->print_cr("time_until_cms_gen_full %3.7f", 1509 stats().time_until_cms_gen_full()); 1510 gclog_or_tty->print_cr("free="SIZE_FORMAT, _cmsGen->free()); 1511 gclog_or_tty->print_cr("contiguous_available="SIZE_FORMAT, 1512 _cmsGen->contiguous_available()); 1513 gclog_or_tty->print_cr("promotion_rate=%g", stats().promotion_rate()); 1514 gclog_or_tty->print_cr("cms_allocation_rate=%g", stats().cms_allocation_rate()); 1515 gclog_or_tty->print_cr("occupancy=%3.7f", _cmsGen->occupancy()); 1516 gclog_or_tty->print_cr("initiatingOccupancy=%3.7f", _cmsGen->initiating_occupancy()); 1517 gclog_or_tty->print_cr("cms_time_since_begin=%3.7f", stats().cms_time_since_begin()); 1518 gclog_or_tty->print_cr("cms_time_since_end=%3.7f", stats().cms_time_since_end()); 1519 gclog_or_tty->print_cr("metadata initialized %d", 1520 MetaspaceGC::should_concurrent_collect()); 1521 } 1522 // ------------------------------------------------------------------ 1523 1524 // If the estimated time to complete a cms collection (cms_duration()) 1525 // is less than the estimated time remaining until the cms generation 1526 // is full, start a collection. 1527 if (!UseCMSInitiatingOccupancyOnly) { 1528 if (stats().valid()) { 1529 if (stats().time_until_cms_start() == 0.0) { 1530 return true; 1531 } 1532 } else { 1533 // We want to conservatively collect somewhat early in order 1534 // to try and "bootstrap" our CMS/promotion statistics; 1535 // this branch will not fire after the first successful CMS 1536 // collection because the stats should then be valid. 1537 if (_cmsGen->occupancy() >= _bootstrap_occupancy) { 1538 if (Verbose && PrintGCDetails) { 1539 gclog_or_tty->print_cr( 1540 " CMSCollector: collect for bootstrapping statistics:" 1541 " occupancy = %f, boot occupancy = %f", _cmsGen->occupancy(), 1542 _bootstrap_occupancy); 1543 } 1544 return true; 1545 } 1546 } 1547 } 1548 1549 // Otherwise, we start a collection cycle if 1550 // old gen want a collection cycle started. Each may use 1551 // an appropriate criterion for making this decision. 1552 // XXX We need to make sure that the gen expansion 1553 // criterion dovetails well with this. XXX NEED TO FIX THIS 1554 if (_cmsGen->should_concurrent_collect()) { 1555 if (Verbose && PrintGCDetails) { 1556 gclog_or_tty->print_cr("CMS old gen initiated"); 1557 } 1558 return true; 1559 } 1560 1561 // We start a collection if we believe an incremental collection may fail; 1562 // this is not likely to be productive in practice because it's probably too 1563 // late anyway. 1564 GenCollectedHeap* gch = GenCollectedHeap::heap(); 1565 assert(gch->collector_policy()->is_generation_policy(), 1566 "You may want to check the correctness of the following"); 1567 if (gch->incremental_collection_will_fail(true /* consult_young */)) { 1568 if (Verbose && PrintGCDetails) { 1569 gclog_or_tty->print("CMSCollector: collect because incremental collection will fail "); 1570 } 1571 return true; 1572 } 1573 1574 if (MetaspaceGC::should_concurrent_collect()) { 1575 if (Verbose && PrintGCDetails) { 1576 gclog_or_tty->print("CMSCollector: collect for metadata allocation "); 1577 } 1578 return true; 1579 } 1580 1581 // CMSTriggerInterval starts a CMS cycle if enough time has passed. 1582 if (CMSTriggerInterval >= 0) { 1583 if (CMSTriggerInterval == 0) { 1584 // Trigger always 1585 return true; 1586 } 1587 1588 // Check the CMS time since begin (we do not check the stats validity 1589 // as we want to be able to trigger the first CMS cycle as well) 1590 if (stats().cms_time_since_begin() >= (CMSTriggerInterval / ((double) MILLIUNITS))) { 1591 if (Verbose && PrintGCDetails) { 1592 if (stats().valid()) { 1593 gclog_or_tty->print_cr("CMSCollector: collect because of trigger interval (time since last begin %3.7f secs)", 1594 stats().cms_time_since_begin()); 1595 } else { 1596 gclog_or_tty->print_cr("CMSCollector: collect because of trigger interval (first collection)"); 1597 } 1598 } 1599 return true; 1600 } 1601 } 1602 1603 return false; 1604 } 1605 1606 void CMSCollector::set_did_compact(bool v) { _cmsGen->set_did_compact(v); } 1607 1608 // Clear _expansion_cause fields of constituent generations 1609 void CMSCollector::clear_expansion_cause() { 1610 _cmsGen->clear_expansion_cause(); 1611 } 1612 1613 // We should be conservative in starting a collection cycle. To 1614 // start too eagerly runs the risk of collecting too often in the 1615 // extreme. To collect too rarely falls back on full collections, 1616 // which works, even if not optimum in terms of concurrent work. 1617 // As a work around for too eagerly collecting, use the flag 1618 // UseCMSInitiatingOccupancyOnly. This also has the advantage of 1619 // giving the user an easily understandable way of controlling the 1620 // collections. 1621 // We want to start a new collection cycle if any of the following 1622 // conditions hold: 1623 // . our current occupancy exceeds the configured initiating occupancy 1624 // for this generation, or 1625 // . we recently needed to expand this space and have not, since that 1626 // expansion, done a collection of this generation, or 1627 // . the underlying space believes that it may be a good idea to initiate 1628 // a concurrent collection (this may be based on criteria such as the 1629 // following: the space uses linear allocation and linear allocation is 1630 // going to fail, or there is believed to be excessive fragmentation in 1631 // the generation, etc... or ... 1632 // [.(currently done by CMSCollector::shouldConcurrentCollect() only for 1633 // the case of the old generation; see CR 6543076): 1634 // we may be approaching a point at which allocation requests may fail because 1635 // we will be out of sufficient free space given allocation rate estimates.] 1636 bool ConcurrentMarkSweepGeneration::should_concurrent_collect() const { 1637 1638 assert_lock_strong(freelistLock()); 1639 if (occupancy() > initiating_occupancy()) { 1640 if (PrintGCDetails && Verbose) { 1641 gclog_or_tty->print(" %s: collect because of occupancy %f / %f ", 1642 short_name(), occupancy(), initiating_occupancy()); 1643 } 1644 return true; 1645 } 1646 if (UseCMSInitiatingOccupancyOnly) { 1647 return false; 1648 } 1649 if (expansion_cause() == CMSExpansionCause::_satisfy_allocation) { 1650 if (PrintGCDetails && Verbose) { 1651 gclog_or_tty->print(" %s: collect because expanded for allocation ", 1652 short_name()); 1653 } 1654 return true; 1655 } 1656 if (_cmsSpace->should_concurrent_collect()) { 1657 if (PrintGCDetails && Verbose) { 1658 gclog_or_tty->print(" %s: collect because cmsSpace says so ", 1659 short_name()); 1660 } 1661 return true; 1662 } 1663 return false; 1664 } 1665 1666 void ConcurrentMarkSweepGeneration::collect(bool full, 1667 bool clear_all_soft_refs, 1668 size_t size, 1669 bool tlab) 1670 { 1671 collector()->collect(full, clear_all_soft_refs, size, tlab); 1672 } 1673 1674 void CMSCollector::collect(bool full, 1675 bool clear_all_soft_refs, 1676 size_t size, 1677 bool tlab) 1678 { 1679 if (!UseCMSCollectionPassing && _collectorState > Idling) { 1680 // For debugging purposes skip the collection if the state 1681 // is not currently idle 1682 if (TraceCMSState) { 1683 gclog_or_tty->print_cr("Thread " INTPTR_FORMAT " skipped full:%d CMS state %d", 1684 Thread::current(), full, _collectorState); 1685 } 1686 return; 1687 } 1688 1689 // The following "if" branch is present for defensive reasons. 1690 // In the current uses of this interface, it can be replaced with: 1691 // assert(!GC_locker.is_active(), "Can't be called otherwise"); 1692 // But I am not placing that assert here to allow future 1693 // generality in invoking this interface. 1694 if (GC_locker::is_active()) { 1695 // A consistency test for GC_locker 1696 assert(GC_locker::needs_gc(), "Should have been set already"); 1697 // Skip this foreground collection, instead 1698 // expanding the heap if necessary. 1699 // Need the free list locks for the call to free() in compute_new_size() 1700 compute_new_size(); 1701 return; 1702 } 1703 acquire_control_and_collect(full, clear_all_soft_refs); 1704 _full_gcs_since_conc_gc++; 1705 } 1706 1707 void CMSCollector::request_full_gc(unsigned int full_gc_count, GCCause::Cause cause) { 1708 GenCollectedHeap* gch = GenCollectedHeap::heap(); 1709 unsigned int gc_count = gch->total_full_collections(); 1710 if (gc_count == full_gc_count) { 1711 MutexLockerEx y(CGC_lock, Mutex::_no_safepoint_check_flag); 1712 _full_gc_requested = true; 1713 _full_gc_cause = cause; 1714 CGC_lock->notify(); // nudge CMS thread 1715 } else { 1716 assert(gc_count > full_gc_count, "Error: causal loop"); 1717 } 1718 } 1719 1720 bool CMSCollector::is_external_interruption() { 1721 GCCause::Cause cause = GenCollectedHeap::heap()->gc_cause(); 1722 return GCCause::is_user_requested_gc(cause) || 1723 GCCause::is_serviceability_requested_gc(cause); 1724 } 1725 1726 void CMSCollector::report_concurrent_mode_interruption() { 1727 if (is_external_interruption()) { 1728 if (PrintGCDetails) { 1729 gclog_or_tty->print(" (concurrent mode interrupted)"); 1730 } 1731 } else { 1732 if (PrintGCDetails) { 1733 gclog_or_tty->print(" (concurrent mode failure)"); 1734 } 1735 _gc_tracer_cm->report_concurrent_mode_failure(); 1736 } 1737 } 1738 1739 1740 // The foreground and background collectors need to coordinate in order 1741 // to make sure that they do not mutually interfere with CMS collections. 1742 // When a background collection is active, 1743 // the foreground collector may need to take over (preempt) and 1744 // synchronously complete an ongoing collection. Depending on the 1745 // frequency of the background collections and the heap usage 1746 // of the application, this preemption can be seldom or frequent. 1747 // There are only certain 1748 // points in the background collection that the "collection-baton" 1749 // can be passed to the foreground collector. 1750 // 1751 // The foreground collector will wait for the baton before 1752 // starting any part of the collection. The foreground collector 1753 // will only wait at one location. 1754 // 1755 // The background collector will yield the baton before starting a new 1756 // phase of the collection (e.g., before initial marking, marking from roots, 1757 // precleaning, final re-mark, sweep etc.) This is normally done at the head 1758 // of the loop which switches the phases. The background collector does some 1759 // of the phases (initial mark, final re-mark) with the world stopped. 1760 // Because of locking involved in stopping the world, 1761 // the foreground collector should not block waiting for the background 1762 // collector when it is doing a stop-the-world phase. The background 1763 // collector will yield the baton at an additional point just before 1764 // it enters a stop-the-world phase. Once the world is stopped, the 1765 // background collector checks the phase of the collection. If the 1766 // phase has not changed, it proceeds with the collection. If the 1767 // phase has changed, it skips that phase of the collection. See 1768 // the comments on the use of the Heap_lock in collect_in_background(). 1769 // 1770 // Variable used in baton passing. 1771 // _foregroundGCIsActive - Set to true by the foreground collector when 1772 // it wants the baton. The foreground clears it when it has finished 1773 // the collection. 1774 // _foregroundGCShouldWait - Set to true by the background collector 1775 // when it is running. The foreground collector waits while 1776 // _foregroundGCShouldWait is true. 1777 // CGC_lock - monitor used to protect access to the above variables 1778 // and to notify the foreground and background collectors. 1779 // _collectorState - current state of the CMS collection. 1780 // 1781 // The foreground collector 1782 // acquires the CGC_lock 1783 // sets _foregroundGCIsActive 1784 // waits on the CGC_lock for _foregroundGCShouldWait to be false 1785 // various locks acquired in preparation for the collection 1786 // are released so as not to block the background collector 1787 // that is in the midst of a collection 1788 // proceeds with the collection 1789 // clears _foregroundGCIsActive 1790 // returns 1791 // 1792 // The background collector in a loop iterating on the phases of the 1793 // collection 1794 // acquires the CGC_lock 1795 // sets _foregroundGCShouldWait 1796 // if _foregroundGCIsActive is set 1797 // clears _foregroundGCShouldWait, notifies _CGC_lock 1798 // waits on _CGC_lock for _foregroundGCIsActive to become false 1799 // and exits the loop. 1800 // otherwise 1801 // proceed with that phase of the collection 1802 // if the phase is a stop-the-world phase, 1803 // yield the baton once more just before enqueueing 1804 // the stop-world CMS operation (executed by the VM thread). 1805 // returns after all phases of the collection are done 1806 // 1807 1808 void CMSCollector::acquire_control_and_collect(bool full, 1809 bool clear_all_soft_refs) { 1810 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint"); 1811 assert(!Thread::current()->is_ConcurrentGC_thread(), 1812 "shouldn't try to acquire control from self!"); 1813 1814 // Start the protocol for acquiring control of the 1815 // collection from the background collector (aka CMS thread). 1816 assert(ConcurrentMarkSweepThread::vm_thread_has_cms_token(), 1817 "VM thread should have CMS token"); 1818 // Remember the possibly interrupted state of an ongoing 1819 // concurrent collection 1820 CollectorState first_state = _collectorState; 1821 1822 // Signal to a possibly ongoing concurrent collection that 1823 // we want to do a foreground collection. 1824 _foregroundGCIsActive = true; 1825 1826 // Disable incremental mode during a foreground collection. 1827 ICMSDisabler icms_disabler; 1828 1829 // release locks and wait for a notify from the background collector 1830 // releasing the locks in only necessary for phases which 1831 // do yields to improve the granularity of the collection. 1832 assert_lock_strong(bitMapLock()); 1833 // We need to lock the Free list lock for the space that we are 1834 // currently collecting. 1835 assert(haveFreelistLocks(), "Must be holding free list locks"); 1836 bitMapLock()->unlock(); 1837 releaseFreelistLocks(); 1838 { 1839 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag); 1840 if (_foregroundGCShouldWait) { 1841 // We are going to be waiting for action for the CMS thread; 1842 // it had better not be gone (for instance at shutdown)! 1843 assert(ConcurrentMarkSweepThread::cmst() != NULL, 1844 "CMS thread must be running"); 1845 // Wait here until the background collector gives us the go-ahead 1846 ConcurrentMarkSweepThread::clear_CMS_flag( 1847 ConcurrentMarkSweepThread::CMS_vm_has_token); // release token 1848 // Get a possibly blocked CMS thread going: 1849 // Note that we set _foregroundGCIsActive true above, 1850 // without protection of the CGC_lock. 1851 CGC_lock->notify(); 1852 assert(!ConcurrentMarkSweepThread::vm_thread_wants_cms_token(), 1853 "Possible deadlock"); 1854 while (_foregroundGCShouldWait) { 1855 // wait for notification 1856 CGC_lock->wait(Mutex::_no_safepoint_check_flag); 1857 // Possibility of delay/starvation here, since CMS token does 1858 // not know to give priority to VM thread? Actually, i think 1859 // there wouldn't be any delay/starvation, but the proof of 1860 // that "fact" (?) appears non-trivial. XXX 20011219YSR 1861 } 1862 ConcurrentMarkSweepThread::set_CMS_flag( 1863 ConcurrentMarkSweepThread::CMS_vm_has_token); 1864 } 1865 } 1866 // The CMS_token is already held. Get back the other locks. 1867 assert(ConcurrentMarkSweepThread::vm_thread_has_cms_token(), 1868 "VM thread should have CMS token"); 1869 getFreelistLocks(); 1870 bitMapLock()->lock_without_safepoint_check(); 1871 if (TraceCMSState) { 1872 gclog_or_tty->print_cr("CMS foreground collector has asked for control " 1873 INTPTR_FORMAT " with first state %d", Thread::current(), first_state); 1874 gclog_or_tty->print_cr(" gets control with state %d", _collectorState); 1875 } 1876 1877 // Check if we need to do a compaction, or if not, whether 1878 // we need to start the mark-sweep from scratch. 1879 bool should_compact = false; 1880 bool should_start_over = false; 1881 decide_foreground_collection_type(clear_all_soft_refs, 1882 &should_compact, &should_start_over); 1883 1884 NOT_PRODUCT( 1885 if (RotateCMSCollectionTypes) { 1886 if (_cmsGen->debug_collection_type() == 1887 ConcurrentMarkSweepGeneration::MSC_foreground_collection_type) { 1888 should_compact = true; 1889 } else if (_cmsGen->debug_collection_type() == 1890 ConcurrentMarkSweepGeneration::MS_foreground_collection_type) { 1891 should_compact = false; 1892 } 1893 } 1894 ) 1895 1896 if (first_state > Idling) { 1897 report_concurrent_mode_interruption(); 1898 } 1899 1900 set_did_compact(should_compact); 1901 if (should_compact) { 1902 // If the collection is being acquired from the background 1903 // collector, there may be references on the discovered 1904 // references lists that have NULL referents (being those 1905 // that were concurrently cleared by a mutator) or 1906 // that are no longer active (having been enqueued concurrently 1907 // by the mutator). 1908 // Scrub the list of those references because Mark-Sweep-Compact 1909 // code assumes referents are not NULL and that all discovered 1910 // Reference objects are active. 1911 ref_processor()->clean_up_discovered_references(); 1912 1913 if (first_state > Idling) { 1914 save_heap_summary(); 1915 } 1916 1917 do_compaction_work(clear_all_soft_refs); 1918 1919 // Has the GC time limit been exceeded? 1920 DefNewGeneration* young_gen = _young_gen->as_DefNewGeneration(); 1921 size_t max_eden_size = young_gen->max_capacity() - 1922 young_gen->to()->capacity() - 1923 young_gen->from()->capacity(); 1924 GenCollectedHeap* gch = GenCollectedHeap::heap(); 1925 GCCause::Cause gc_cause = gch->gc_cause(); 1926 size_policy()->check_gc_overhead_limit(_young_gen->used(), 1927 young_gen->eden()->used(), 1928 _cmsGen->max_capacity(), 1929 max_eden_size, 1930 full, 1931 gc_cause, 1932 gch->collector_policy()); 1933 } else { 1934 do_mark_sweep_work(clear_all_soft_refs, first_state, 1935 should_start_over); 1936 } 1937 // Reset the expansion cause, now that we just completed 1938 // a collection cycle. 1939 clear_expansion_cause(); 1940 _foregroundGCIsActive = false; 1941 return; 1942 } 1943 1944 // Resize the tenured generation 1945 // after obtaining the free list locks for the 1946 // two generations. 1947 void CMSCollector::compute_new_size() { 1948 assert_locked_or_safepoint(Heap_lock); 1949 FreelistLocker z(this); 1950 MetaspaceGC::compute_new_size(); 1951 _cmsGen->compute_new_size_free_list(); 1952 } 1953 1954 // A work method used by foreground collection to determine 1955 // what type of collection (compacting or not, continuing or fresh) 1956 // it should do. 1957 // NOTE: the intent is to make UseCMSCompactAtFullCollection 1958 // and CMSCompactWhenClearAllSoftRefs the default in the future 1959 // and do away with the flags after a suitable period. 1960 void CMSCollector::decide_foreground_collection_type( 1961 bool clear_all_soft_refs, bool* should_compact, 1962 bool* should_start_over) { 1963 // Normally, we'll compact only if the UseCMSCompactAtFullCollection 1964 // flag is set, and we have either requested a System.gc() or 1965 // the number of full gc's since the last concurrent cycle 1966 // has exceeded the threshold set by CMSFullGCsBeforeCompaction, 1967 // or if an incremental collection has failed 1968 GenCollectedHeap* gch = GenCollectedHeap::heap(); 1969 assert(gch->collector_policy()->is_generation_policy(), 1970 "You may want to check the correctness of the following"); 1971 // Inform cms gen if this was due to partial collection failing. 1972 // The CMS gen may use this fact to determine its expansion policy. 1973 if (gch->incremental_collection_will_fail(false /* don't consult_young */)) { 1974 assert(!_cmsGen->incremental_collection_failed(), 1975 "Should have been noticed, reacted to and cleared"); 1976 _cmsGen->set_incremental_collection_failed(); 1977 } 1978 *should_compact = 1979 UseCMSCompactAtFullCollection && 1980 ((_full_gcs_since_conc_gc >= CMSFullGCsBeforeCompaction) || 1981 GCCause::is_user_requested_gc(gch->gc_cause()) || 1982 gch->incremental_collection_will_fail(true /* consult_young */)); 1983 *should_start_over = false; 1984 if (clear_all_soft_refs && !*should_compact) { 1985 // We are about to do a last ditch collection attempt 1986 // so it would normally make sense to do a compaction 1987 // to reclaim as much space as possible. 1988 if (CMSCompactWhenClearAllSoftRefs) { 1989 // Default: The rationale is that in this case either 1990 // we are past the final marking phase, in which case 1991 // we'd have to start over, or so little has been done 1992 // that there's little point in saving that work. Compaction 1993 // appears to be the sensible choice in either case. 1994 *should_compact = true; 1995 } else { 1996 // We have been asked to clear all soft refs, but not to 1997 // compact. Make sure that we aren't past the final checkpoint 1998 // phase, for that is where we process soft refs. If we are already 1999 // past that phase, we'll need to redo the refs discovery phase and 2000 // if necessary clear soft refs that weren't previously 2001 // cleared. We do so by remembering the phase in which 2002 // we came in, and if we are past the refs processing 2003 // phase, we'll choose to just redo the mark-sweep 2004 // collection from scratch. 2005 if (_collectorState > FinalMarking) { 2006 // We are past the refs processing phase; 2007 // start over and do a fresh synchronous CMS cycle 2008 _collectorState = Resetting; // skip to reset to start new cycle 2009 reset(false /* == !asynch */); 2010 *should_start_over = true; 2011 } // else we can continue a possibly ongoing current cycle 2012 } 2013 } 2014 } 2015 2016 // A work method used by the foreground collector to do 2017 // a mark-sweep-compact. 2018 void CMSCollector::do_compaction_work(bool clear_all_soft_refs) { 2019 GenCollectedHeap* gch = GenCollectedHeap::heap(); 2020 2021 STWGCTimer* gc_timer = GenMarkSweep::gc_timer(); 2022 gc_timer->register_gc_start(); 2023 2024 SerialOldTracer* gc_tracer = GenMarkSweep::gc_tracer(); 2025 gc_tracer->report_gc_start(gch->gc_cause(), gc_timer->gc_start()); 2026 2027 GCTraceTime t("CMS:MSC ", PrintGCDetails && Verbose, true, NULL, gc_tracer->gc_id()); 2028 if (PrintGC && Verbose && !(GCCause::is_user_requested_gc(gch->gc_cause()))) { 2029 gclog_or_tty->print_cr("Compact ConcurrentMarkSweepGeneration after %d " 2030 "collections passed to foreground collector", _full_gcs_since_conc_gc); 2031 } 2032 2033 // Temporarily widen the span of the weak reference processing to 2034 // the entire heap. 2035 MemRegion new_span(GenCollectedHeap::heap()->reserved_region()); 2036 ReferenceProcessorSpanMutator rp_mut_span(ref_processor(), new_span); 2037 // Temporarily, clear the "is_alive_non_header" field of the 2038 // reference processor. 2039 ReferenceProcessorIsAliveMutator rp_mut_closure(ref_processor(), NULL); 2040 // Temporarily make reference _processing_ single threaded (non-MT). 2041 ReferenceProcessorMTProcMutator rp_mut_mt_processing(ref_processor(), false); 2042 // Temporarily make refs discovery atomic 2043 ReferenceProcessorAtomicMutator rp_mut_atomic(ref_processor(), true); 2044 // Temporarily make reference _discovery_ single threaded (non-MT) 2045 ReferenceProcessorMTDiscoveryMutator rp_mut_discovery(ref_processor(), false); 2046 2047 ref_processor()->set_enqueuing_is_done(false); 2048 ref_processor()->enable_discovery(false /*verify_disabled*/, false /*check_no_refs*/); 2049 ref_processor()->setup_policy(clear_all_soft_refs); 2050 // If an asynchronous collection finishes, the _modUnionTable is 2051 // all clear. If we are assuming the collection from an asynchronous 2052 // collection, clear the _modUnionTable. 2053 assert(_collectorState != Idling || _modUnionTable.isAllClear(), 2054 "_modUnionTable should be clear if the baton was not passed"); 2055 _modUnionTable.clear_all(); 2056 assert(_collectorState != Idling || _ct->klass_rem_set()->mod_union_is_clear(), 2057 "mod union for klasses should be clear if the baton was passed"); 2058 _ct->klass_rem_set()->clear_mod_union(); 2059 2060 // We must adjust the allocation statistics being maintained 2061 // in the free list space. We do so by reading and clearing 2062 // the sweep timer and updating the block flux rate estimates below. 2063 assert(!_intra_sweep_timer.is_active(), "_intra_sweep_timer should be inactive"); 2064 if (_inter_sweep_timer.is_active()) { 2065 _inter_sweep_timer.stop(); 2066 // Note that we do not use this sample to update the _inter_sweep_estimate. 2067 _cmsGen->cmsSpace()->beginSweepFLCensus((float)(_inter_sweep_timer.seconds()), 2068 _inter_sweep_estimate.padded_average(), 2069 _intra_sweep_estimate.padded_average()); 2070 } 2071 2072 GenMarkSweep::invoke_at_safepoint(_cmsGen->level(), 2073 ref_processor(), clear_all_soft_refs); 2074 #ifdef ASSERT 2075 CompactibleFreeListSpace* cms_space = _cmsGen->cmsSpace(); 2076 size_t free_size = cms_space->free(); 2077 assert(free_size == 2078 pointer_delta(cms_space->end(), cms_space->compaction_top()) 2079 * HeapWordSize, 2080 "All the free space should be compacted into one chunk at top"); 2081 assert(cms_space->dictionary()->total_chunk_size( 2082 debug_only(cms_space->freelistLock())) == 0 || 2083 cms_space->totalSizeInIndexedFreeLists() == 0, 2084 "All the free space should be in a single chunk"); 2085 size_t num = cms_space->totalCount(); 2086 assert((free_size == 0 && num == 0) || 2087 (free_size > 0 && (num == 1 || num == 2)), 2088 "There should be at most 2 free chunks after compaction"); 2089 #endif // ASSERT 2090 _collectorState = Resetting; 2091 assert(_restart_addr == NULL, 2092 "Should have been NULL'd before baton was passed"); 2093 reset(false /* == !asynch */); 2094 _cmsGen->reset_after_compaction(); 2095 _concurrent_cycles_since_last_unload = 0; 2096 2097 // Clear any data recorded in the PLAB chunk arrays. 2098 if (_survivor_plab_array != NULL) { 2099 reset_survivor_plab_arrays(); 2100 } 2101 2102 // Adjust the per-size allocation stats for the next epoch. 2103 _cmsGen->cmsSpace()->endSweepFLCensus(sweep_count() /* fake */); 2104 // Restart the "inter sweep timer" for the next epoch. 2105 _inter_sweep_timer.reset(); 2106 _inter_sweep_timer.start(); 2107 2108 gc_timer->register_gc_end(); 2109 2110 gc_tracer->report_gc_end(gc_timer->gc_end(), gc_timer->time_partitions()); 2111 2112 // For a mark-sweep-compact, compute_new_size() will be called 2113 // in the heap's do_collection() method. 2114 } 2115 2116 // A work method used by the foreground collector to do 2117 // a mark-sweep, after taking over from a possibly on-going 2118 // concurrent mark-sweep collection. 2119 void CMSCollector::do_mark_sweep_work(bool clear_all_soft_refs, 2120 CollectorState first_state, bool should_start_over) { 2121 if (PrintGC && Verbose) { 2122 gclog_or_tty->print_cr("Pass concurrent collection to foreground " 2123 "collector with count %d", 2124 _full_gcs_since_conc_gc); 2125 } 2126 switch (_collectorState) { 2127 case Idling: 2128 if (first_state == Idling || should_start_over) { 2129 // The background GC was not active, or should 2130 // restarted from scratch; start the cycle. 2131 _collectorState = InitialMarking; 2132 } 2133 // If first_state was not Idling, then a background GC 2134 // was in progress and has now finished. No need to do it 2135 // again. Leave the state as Idling. 2136 break; 2137 case Precleaning: 2138 // In the foreground case don't do the precleaning since 2139 // it is not done concurrently and there is extra work 2140 // required. 2141 _collectorState = FinalMarking; 2142 } 2143 collect_in_foreground(clear_all_soft_refs, GenCollectedHeap::heap()->gc_cause()); 2144 2145 // For a mark-sweep, compute_new_size() will be called 2146 // in the heap's do_collection() method. 2147 } 2148 2149 2150 void CMSCollector::print_eden_and_survivor_chunk_arrays() { 2151 DefNewGeneration* dng = _young_gen->as_DefNewGeneration(); 2152 EdenSpace* eden_space = dng->eden(); 2153 ContiguousSpace* from_space = dng->from(); 2154 ContiguousSpace* to_space = dng->to(); 2155 // Eden 2156 if (_eden_chunk_array != NULL) { 2157 gclog_or_tty->print_cr("eden " PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "(" SIZE_FORMAT ")", 2158 eden_space->bottom(), eden_space->top(), 2159 eden_space->end(), eden_space->capacity()); 2160 gclog_or_tty->print_cr("_eden_chunk_index=" SIZE_FORMAT ", " 2161 "_eden_chunk_capacity=" SIZE_FORMAT, 2162 _eden_chunk_index, _eden_chunk_capacity); 2163 for (size_t i = 0; i < _eden_chunk_index; i++) { 2164 gclog_or_tty->print_cr("_eden_chunk_array[" SIZE_FORMAT "]=" PTR_FORMAT, 2165 i, _eden_chunk_array[i]); 2166 } 2167 } 2168 // Survivor 2169 if (_survivor_chunk_array != NULL) { 2170 gclog_or_tty->print_cr("survivor " PTR_FORMAT "-" PTR_FORMAT "-" PTR_FORMAT "(" SIZE_FORMAT ")", 2171 from_space->bottom(), from_space->top(), 2172 from_space->end(), from_space->capacity()); 2173 gclog_or_tty->print_cr("_survivor_chunk_index=" SIZE_FORMAT ", " 2174 "_survivor_chunk_capacity=" SIZE_FORMAT, 2175 _survivor_chunk_index, _survivor_chunk_capacity); 2176 for (size_t i = 0; i < _survivor_chunk_index; i++) { 2177 gclog_or_tty->print_cr("_survivor_chunk_array[" SIZE_FORMAT "]=" PTR_FORMAT, 2178 i, _survivor_chunk_array[i]); 2179 } 2180 } 2181 } 2182 2183 void CMSCollector::getFreelistLocks() const { 2184 // Get locks for all free lists in all generations that this 2185 // collector is responsible for 2186 _cmsGen->freelistLock()->lock_without_safepoint_check(); 2187 } 2188 2189 void CMSCollector::releaseFreelistLocks() const { 2190 // Release locks for all free lists in all generations that this 2191 // collector is responsible for 2192 _cmsGen->freelistLock()->unlock(); 2193 } 2194 2195 bool CMSCollector::haveFreelistLocks() const { 2196 // Check locks for all free lists in all generations that this 2197 // collector is responsible for 2198 assert_lock_strong(_cmsGen->freelistLock()); 2199 PRODUCT_ONLY(ShouldNotReachHere()); 2200 return true; 2201 } 2202 2203 // A utility class that is used by the CMS collector to 2204 // temporarily "release" the foreground collector from its 2205 // usual obligation to wait for the background collector to 2206 // complete an ongoing phase before proceeding. 2207 class ReleaseForegroundGC: public StackObj { 2208 private: 2209 CMSCollector* _c; 2210 public: 2211 ReleaseForegroundGC(CMSCollector* c) : _c(c) { 2212 assert(_c->_foregroundGCShouldWait, "Else should not need to call"); 2213 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag); 2214 // allow a potentially blocked foreground collector to proceed 2215 _c->_foregroundGCShouldWait = false; 2216 if (_c->_foregroundGCIsActive) { 2217 CGC_lock->notify(); 2218 } 2219 assert(!ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 2220 "Possible deadlock"); 2221 } 2222 2223 ~ReleaseForegroundGC() { 2224 assert(!_c->_foregroundGCShouldWait, "Usage protocol violation?"); 2225 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag); 2226 _c->_foregroundGCShouldWait = true; 2227 } 2228 }; 2229 2230 // There are separate collect_in_background and collect_in_foreground because of 2231 // the different locking requirements of the background collector and the 2232 // foreground collector. There was originally an attempt to share 2233 // one "collect" method between the background collector and the foreground 2234 // collector but the if-then-else required made it cleaner to have 2235 // separate methods. 2236 void CMSCollector::collect_in_background(bool clear_all_soft_refs, GCCause::Cause cause) { 2237 assert(Thread::current()->is_ConcurrentGC_thread(), 2238 "A CMS asynchronous collection is only allowed on a CMS thread."); 2239 2240 GenCollectedHeap* gch = GenCollectedHeap::heap(); 2241 { 2242 bool safepoint_check = Mutex::_no_safepoint_check_flag; 2243 MutexLockerEx hl(Heap_lock, safepoint_check); 2244 FreelistLocker fll(this); 2245 MutexLockerEx x(CGC_lock, safepoint_check); 2246 if (_foregroundGCIsActive || !UseAsyncConcMarkSweepGC) { 2247 // The foreground collector is active or we're 2248 // not using asynchronous collections. Skip this 2249 // background collection. 2250 assert(!_foregroundGCShouldWait, "Should be clear"); 2251 return; 2252 } else { 2253 assert(_collectorState == Idling, "Should be idling before start."); 2254 _collectorState = InitialMarking; 2255 register_gc_start(cause); 2256 // Reset the expansion cause, now that we are about to begin 2257 // a new cycle. 2258 clear_expansion_cause(); 2259 2260 // Clear the MetaspaceGC flag since a concurrent collection 2261 // is starting but also clear it after the collection. 2262 MetaspaceGC::set_should_concurrent_collect(false); 2263 } 2264 // Decide if we want to enable class unloading as part of the 2265 // ensuing concurrent GC cycle. 2266 update_should_unload_classes(); 2267 _full_gc_requested = false; // acks all outstanding full gc requests 2268 _full_gc_cause = GCCause::_no_gc; 2269 // Signal that we are about to start a collection 2270 gch->increment_total_full_collections(); // ... starting a collection cycle 2271 _collection_count_start = gch->total_full_collections(); 2272 } 2273 2274 // Used for PrintGC 2275 size_t prev_used; 2276 if (PrintGC && Verbose) { 2277 prev_used = _cmsGen->used(); // XXXPERM 2278 } 2279 2280 // The change of the collection state is normally done at this level; 2281 // the exceptions are phases that are executed while the world is 2282 // stopped. For those phases the change of state is done while the 2283 // world is stopped. For baton passing purposes this allows the 2284 // background collector to finish the phase and change state atomically. 2285 // The foreground collector cannot wait on a phase that is done 2286 // while the world is stopped because the foreground collector already 2287 // has the world stopped and would deadlock. 2288 while (_collectorState != Idling) { 2289 if (TraceCMSState) { 2290 gclog_or_tty->print_cr("Thread " INTPTR_FORMAT " in CMS state %d", 2291 Thread::current(), _collectorState); 2292 } 2293 // The foreground collector 2294 // holds the Heap_lock throughout its collection. 2295 // holds the CMS token (but not the lock) 2296 // except while it is waiting for the background collector to yield. 2297 // 2298 // The foreground collector should be blocked (not for long) 2299 // if the background collector is about to start a phase 2300 // executed with world stopped. If the background 2301 // collector has already started such a phase, the 2302 // foreground collector is blocked waiting for the 2303 // Heap_lock. The stop-world phases (InitialMarking and FinalMarking) 2304 // are executed in the VM thread. 2305 // 2306 // The locking order is 2307 // PendingListLock (PLL) -- if applicable (FinalMarking) 2308 // Heap_lock (both this & PLL locked in VM_CMS_Operation::prologue()) 2309 // CMS token (claimed in 2310 // stop_world_and_do() --> 2311 // safepoint_synchronize() --> 2312 // CMSThread::synchronize()) 2313 2314 { 2315 // Check if the FG collector wants us to yield. 2316 CMSTokenSync x(true); // is cms thread 2317 if (waitForForegroundGC()) { 2318 // We yielded to a foreground GC, nothing more to be 2319 // done this round. 2320 assert(_foregroundGCShouldWait == false, "We set it to false in " 2321 "waitForForegroundGC()"); 2322 if (TraceCMSState) { 2323 gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT 2324 " exiting collection CMS state %d", 2325 Thread::current(), _collectorState); 2326 } 2327 return; 2328 } else { 2329 // The background collector can run but check to see if the 2330 // foreground collector has done a collection while the 2331 // background collector was waiting to get the CGC_lock 2332 // above. If yes, break so that _foregroundGCShouldWait 2333 // is cleared before returning. 2334 if (_collectorState == Idling) { 2335 break; 2336 } 2337 } 2338 } 2339 2340 assert(_foregroundGCShouldWait, "Foreground collector, if active, " 2341 "should be waiting"); 2342 2343 switch (_collectorState) { 2344 case InitialMarking: 2345 { 2346 ReleaseForegroundGC x(this); 2347 stats().record_cms_begin(); 2348 VM_CMS_Initial_Mark initial_mark_op(this); 2349 VMThread::execute(&initial_mark_op); 2350 } 2351 // The collector state may be any legal state at this point 2352 // since the background collector may have yielded to the 2353 // foreground collector. 2354 break; 2355 case Marking: 2356 // initial marking in checkpointRootsInitialWork has been completed 2357 if (markFromRoots(true)) { // we were successful 2358 assert(_collectorState == Precleaning, "Collector state should " 2359 "have changed"); 2360 } else { 2361 assert(_foregroundGCIsActive, "Internal state inconsistency"); 2362 } 2363 break; 2364 case Precleaning: 2365 // marking from roots in markFromRoots has been completed 2366 preclean(); 2367 assert(_collectorState == AbortablePreclean || 2368 _collectorState == FinalMarking, 2369 "Collector state should have changed"); 2370 break; 2371 case AbortablePreclean: 2372 abortable_preclean(); 2373 assert(_collectorState == FinalMarking, "Collector state should " 2374 "have changed"); 2375 break; 2376 case FinalMarking: 2377 { 2378 ReleaseForegroundGC x(this); 2379 2380 VM_CMS_Final_Remark final_remark_op(this); 2381 VMThread::execute(&final_remark_op); 2382 } 2383 assert(_foregroundGCShouldWait, "block post-condition"); 2384 break; 2385 case Sweeping: 2386 // final marking in checkpointRootsFinal has been completed 2387 sweep(true); 2388 assert(_collectorState == Resizing, "Collector state change " 2389 "to Resizing must be done under the free_list_lock"); 2390 _full_gcs_since_conc_gc = 0; 2391 2392 case Resizing: { 2393 // Sweeping has been completed... 2394 // At this point the background collection has completed. 2395 // Don't move the call to compute_new_size() down 2396 // into code that might be executed if the background 2397 // collection was preempted. 2398 { 2399 ReleaseForegroundGC x(this); // unblock FG collection 2400 MutexLockerEx y(Heap_lock, Mutex::_no_safepoint_check_flag); 2401 CMSTokenSync z(true); // not strictly needed. 2402 if (_collectorState == Resizing) { 2403 compute_new_size(); 2404 save_heap_summary(); 2405 _collectorState = Resetting; 2406 } else { 2407 assert(_collectorState == Idling, "The state should only change" 2408 " because the foreground collector has finished the collection"); 2409 } 2410 } 2411 break; 2412 } 2413 case Resetting: 2414 // CMS heap resizing has been completed 2415 reset(true); 2416 assert(_collectorState == Idling, "Collector state should " 2417 "have changed"); 2418 2419 MetaspaceGC::set_should_concurrent_collect(false); 2420 2421 stats().record_cms_end(); 2422 // Don't move the concurrent_phases_end() and compute_new_size() 2423 // calls to here because a preempted background collection 2424 // has it's state set to "Resetting". 2425 break; 2426 case Idling: 2427 default: 2428 ShouldNotReachHere(); 2429 break; 2430 } 2431 if (TraceCMSState) { 2432 gclog_or_tty->print_cr(" Thread " INTPTR_FORMAT " done - next CMS state %d", 2433 Thread::current(), _collectorState); 2434 } 2435 assert(_foregroundGCShouldWait, "block post-condition"); 2436 } 2437 2438 // Should this be in gc_epilogue? 2439 collector_policy()->counters()->update_counters(); 2440 2441 { 2442 // Clear _foregroundGCShouldWait and, in the event that the 2443 // foreground collector is waiting, notify it, before 2444 // returning. 2445 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag); 2446 _foregroundGCShouldWait = false; 2447 if (_foregroundGCIsActive) { 2448 CGC_lock->notify(); 2449 } 2450 assert(!ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 2451 "Possible deadlock"); 2452 } 2453 if (TraceCMSState) { 2454 gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT 2455 " exiting collection CMS state %d", 2456 Thread::current(), _collectorState); 2457 } 2458 if (PrintGC && Verbose) { 2459 _cmsGen->print_heap_change(prev_used); 2460 } 2461 } 2462 2463 void CMSCollector::register_foreground_gc_start(GCCause::Cause cause) { 2464 if (!_cms_start_registered) { 2465 register_gc_start(cause); 2466 } 2467 } 2468 2469 void CMSCollector::register_gc_start(GCCause::Cause cause) { 2470 _cms_start_registered = true; 2471 _gc_timer_cm->register_gc_start(); 2472 _gc_tracer_cm->report_gc_start(cause, _gc_timer_cm->gc_start()); 2473 } 2474 2475 void CMSCollector::register_gc_end() { 2476 if (_cms_start_registered) { 2477 report_heap_summary(GCWhen::AfterGC); 2478 2479 _gc_timer_cm->register_gc_end(); 2480 _gc_tracer_cm->report_gc_end(_gc_timer_cm->gc_end(), _gc_timer_cm->time_partitions()); 2481 _cms_start_registered = false; 2482 } 2483 } 2484 2485 void CMSCollector::save_heap_summary() { 2486 GenCollectedHeap* gch = GenCollectedHeap::heap(); 2487 _last_heap_summary = gch->create_heap_summary(); 2488 _last_metaspace_summary = gch->create_metaspace_summary(); 2489 } 2490 2491 void CMSCollector::report_heap_summary(GCWhen::Type when) { 2492 _gc_tracer_cm->report_gc_heap_summary(when, _last_heap_summary); 2493 _gc_tracer_cm->report_metaspace_summary(when, _last_metaspace_summary); 2494 } 2495 2496 void CMSCollector::collect_in_foreground(bool clear_all_soft_refs, GCCause::Cause cause) { 2497 assert(_foregroundGCIsActive && !_foregroundGCShouldWait, 2498 "Foreground collector should be waiting, not executing"); 2499 assert(Thread::current()->is_VM_thread(), "A foreground collection" 2500 "may only be done by the VM Thread with the world stopped"); 2501 assert(ConcurrentMarkSweepThread::vm_thread_has_cms_token(), 2502 "VM thread should have CMS token"); 2503 2504 // The gc id is created in register_foreground_gc_start if this collection is synchronous 2505 const GCId gc_id = _collectorState == InitialMarking ? GCId::peek() : _gc_tracer_cm->gc_id(); 2506 NOT_PRODUCT(GCTraceTime t("CMS:MS (foreground) ", PrintGCDetails && Verbose, 2507 true, NULL, gc_id);) 2508 COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact); 2509 2510 HandleMark hm; // Discard invalid handles created during verification 2511 2512 if (VerifyBeforeGC && 2513 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) { 2514 Universe::verify(); 2515 } 2516 2517 // Snapshot the soft reference policy to be used in this collection cycle. 2518 ref_processor()->setup_policy(clear_all_soft_refs); 2519 2520 // Decide if class unloading should be done 2521 update_should_unload_classes(); 2522 2523 bool init_mark_was_synchronous = false; // until proven otherwise 2524 while (_collectorState != Idling) { 2525 if (TraceCMSState) { 2526 gclog_or_tty->print_cr("Thread " INTPTR_FORMAT " in CMS state %d", 2527 Thread::current(), _collectorState); 2528 } 2529 switch (_collectorState) { 2530 case InitialMarking: 2531 register_foreground_gc_start(cause); 2532 init_mark_was_synchronous = true; // fact to be exploited in re-mark 2533 checkpointRootsInitial(false); 2534 assert(_collectorState == Marking, "Collector state should have changed" 2535 " within checkpointRootsInitial()"); 2536 break; 2537 case Marking: 2538 // initial marking in checkpointRootsInitialWork has been completed 2539 if (VerifyDuringGC && 2540 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) { 2541 Universe::verify("Verify before initial mark: "); 2542 } 2543 { 2544 bool res = markFromRoots(false); 2545 assert(res && _collectorState == FinalMarking, "Collector state should " 2546 "have changed"); 2547 break; 2548 } 2549 case FinalMarking: 2550 if (VerifyDuringGC && 2551 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) { 2552 Universe::verify("Verify before re-mark: "); 2553 } 2554 checkpointRootsFinal(false, clear_all_soft_refs, 2555 init_mark_was_synchronous); 2556 assert(_collectorState == Sweeping, "Collector state should not " 2557 "have changed within checkpointRootsFinal()"); 2558 break; 2559 case Sweeping: 2560 // final marking in checkpointRootsFinal has been completed 2561 if (VerifyDuringGC && 2562 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) { 2563 Universe::verify("Verify before sweep: "); 2564 } 2565 sweep(false); 2566 assert(_collectorState == Resizing, "Incorrect state"); 2567 break; 2568 case Resizing: { 2569 // Sweeping has been completed; the actual resize in this case 2570 // is done separately; nothing to be done in this state. 2571 _collectorState = Resetting; 2572 break; 2573 } 2574 case Resetting: 2575 // The heap has been resized. 2576 if (VerifyDuringGC && 2577 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) { 2578 Universe::verify("Verify before reset: "); 2579 } 2580 save_heap_summary(); 2581 reset(false); 2582 assert(_collectorState == Idling, "Collector state should " 2583 "have changed"); 2584 break; 2585 case Precleaning: 2586 case AbortablePreclean: 2587 // Elide the preclean phase 2588 _collectorState = FinalMarking; 2589 break; 2590 default: 2591 ShouldNotReachHere(); 2592 } 2593 if (TraceCMSState) { 2594 gclog_or_tty->print_cr(" Thread " INTPTR_FORMAT " done - next CMS state %d", 2595 Thread::current(), _collectorState); 2596 } 2597 } 2598 2599 if (VerifyAfterGC && 2600 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) { 2601 Universe::verify(); 2602 } 2603 if (TraceCMSState) { 2604 gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT 2605 " exiting collection CMS state %d", 2606 Thread::current(), _collectorState); 2607 } 2608 } 2609 2610 bool CMSCollector::waitForForegroundGC() { 2611 bool res = false; 2612 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 2613 "CMS thread should have CMS token"); 2614 // Block the foreground collector until the 2615 // background collectors decides whether to 2616 // yield. 2617 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag); 2618 _foregroundGCShouldWait = true; 2619 if (_foregroundGCIsActive) { 2620 // The background collector yields to the 2621 // foreground collector and returns a value 2622 // indicating that it has yielded. The foreground 2623 // collector can proceed. 2624 res = true; 2625 _foregroundGCShouldWait = false; 2626 ConcurrentMarkSweepThread::clear_CMS_flag( 2627 ConcurrentMarkSweepThread::CMS_cms_has_token); 2628 ConcurrentMarkSweepThread::set_CMS_flag( 2629 ConcurrentMarkSweepThread::CMS_cms_wants_token); 2630 // Get a possibly blocked foreground thread going 2631 CGC_lock->notify(); 2632 if (TraceCMSState) { 2633 gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT " waiting at CMS state %d", 2634 Thread::current(), _collectorState); 2635 } 2636 while (_foregroundGCIsActive) { 2637 CGC_lock->wait(Mutex::_no_safepoint_check_flag); 2638 } 2639 ConcurrentMarkSweepThread::set_CMS_flag( 2640 ConcurrentMarkSweepThread::CMS_cms_has_token); 2641 ConcurrentMarkSweepThread::clear_CMS_flag( 2642 ConcurrentMarkSweepThread::CMS_cms_wants_token); 2643 } 2644 if (TraceCMSState) { 2645 gclog_or_tty->print_cr("CMS Thread " INTPTR_FORMAT " continuing at CMS state %d", 2646 Thread::current(), _collectorState); 2647 } 2648 return res; 2649 } 2650 2651 // Because of the need to lock the free lists and other structures in 2652 // the collector, common to all the generations that the collector is 2653 // collecting, we need the gc_prologues of individual CMS generations 2654 // delegate to their collector. It may have been simpler had the 2655 // current infrastructure allowed one to call a prologue on a 2656 // collector. In the absence of that we have the generation's 2657 // prologue delegate to the collector, which delegates back 2658 // some "local" work to a worker method in the individual generations 2659 // that it's responsible for collecting, while itself doing any 2660 // work common to all generations it's responsible for. A similar 2661 // comment applies to the gc_epilogue()'s. 2662 // The role of the variable _between_prologue_and_epilogue is to 2663 // enforce the invocation protocol. 2664 void CMSCollector::gc_prologue(bool full) { 2665 // Call gc_prologue_work() for the CMSGen 2666 // we are responsible for. 2667 2668 // The following locking discipline assumes that we are only called 2669 // when the world is stopped. 2670 assert(SafepointSynchronize::is_at_safepoint(), "world is stopped assumption"); 2671 2672 // The CMSCollector prologue must call the gc_prologues for the 2673 // "generations" that it's responsible 2674 // for. 2675 2676 assert( Thread::current()->is_VM_thread() 2677 || ( CMSScavengeBeforeRemark 2678 && Thread::current()->is_ConcurrentGC_thread()), 2679 "Incorrect thread type for prologue execution"); 2680 2681 if (_between_prologue_and_epilogue) { 2682 // We have already been invoked; this is a gc_prologue delegation 2683 // from yet another CMS generation that we are responsible for, just 2684 // ignore it since all relevant work has already been done. 2685 return; 2686 } 2687 2688 // set a bit saying prologue has been called; cleared in epilogue 2689 _between_prologue_and_epilogue = true; 2690 // Claim locks for common data structures, then call gc_prologue_work() 2691 // for each CMSGen. 2692 2693 getFreelistLocks(); // gets free list locks on constituent spaces 2694 bitMapLock()->lock_without_safepoint_check(); 2695 2696 // Should call gc_prologue_work() for all cms gens we are responsible for 2697 bool duringMarking = _collectorState >= Marking 2698 && _collectorState < Sweeping; 2699 2700 // The young collections clear the modified oops state, which tells if 2701 // there are any modified oops in the class. The remark phase also needs 2702 // that information. Tell the young collection to save the union of all 2703 // modified klasses. 2704 if (duringMarking) { 2705 _ct->klass_rem_set()->set_accumulate_modified_oops(true); 2706 } 2707 2708 bool registerClosure = duringMarking; 2709 2710 ModUnionClosure* muc = CollectedHeap::use_parallel_gc_threads() ? 2711 &_modUnionClosurePar 2712 : &_modUnionClosure; 2713 _cmsGen->gc_prologue_work(full, registerClosure, muc); 2714 2715 if (!full) { 2716 stats().record_gc0_begin(); 2717 } 2718 } 2719 2720 void ConcurrentMarkSweepGeneration::gc_prologue(bool full) { 2721 2722 _capacity_at_prologue = capacity(); 2723 _used_at_prologue = used(); 2724 2725 // Delegate to CMScollector which knows how to coordinate between 2726 // this and any other CMS generations that it is responsible for 2727 // collecting. 2728 collector()->gc_prologue(full); 2729 } 2730 2731 // This is a "private" interface for use by this generation's CMSCollector. 2732 // Not to be called directly by any other entity (for instance, 2733 // GenCollectedHeap, which calls the "public" gc_prologue method above). 2734 void ConcurrentMarkSweepGeneration::gc_prologue_work(bool full, 2735 bool registerClosure, ModUnionClosure* modUnionClosure) { 2736 assert(!incremental_collection_failed(), "Shouldn't be set yet"); 2737 assert(cmsSpace()->preconsumptionDirtyCardClosure() == NULL, 2738 "Should be NULL"); 2739 if (registerClosure) { 2740 cmsSpace()->setPreconsumptionDirtyCardClosure(modUnionClosure); 2741 } 2742 cmsSpace()->gc_prologue(); 2743 // Clear stat counters 2744 NOT_PRODUCT( 2745 assert(_numObjectsPromoted == 0, "check"); 2746 assert(_numWordsPromoted == 0, "check"); 2747 if (Verbose && PrintGC) { 2748 gclog_or_tty->print("Allocated "SIZE_FORMAT" objects, " 2749 SIZE_FORMAT" bytes concurrently", 2750 _numObjectsAllocated, _numWordsAllocated*sizeof(HeapWord)); 2751 } 2752 _numObjectsAllocated = 0; 2753 _numWordsAllocated = 0; 2754 ) 2755 } 2756 2757 void CMSCollector::gc_epilogue(bool full) { 2758 // The following locking discipline assumes that we are only called 2759 // when the world is stopped. 2760 assert(SafepointSynchronize::is_at_safepoint(), 2761 "world is stopped assumption"); 2762 2763 // Currently the CMS epilogue (see CompactibleFreeListSpace) merely checks 2764 // if linear allocation blocks need to be appropriately marked to allow the 2765 // the blocks to be parsable. We also check here whether we need to nudge the 2766 // CMS collector thread to start a new cycle (if it's not already active). 2767 assert( Thread::current()->is_VM_thread() 2768 || ( CMSScavengeBeforeRemark 2769 && Thread::current()->is_ConcurrentGC_thread()), 2770 "Incorrect thread type for epilogue execution"); 2771 2772 if (!_between_prologue_and_epilogue) { 2773 // We have already been invoked; this is a gc_epilogue delegation 2774 // from yet another CMS generation that we are responsible for, just 2775 // ignore it since all relevant work has already been done. 2776 return; 2777 } 2778 assert(haveFreelistLocks(), "must have freelist locks"); 2779 assert_lock_strong(bitMapLock()); 2780 2781 _ct->klass_rem_set()->set_accumulate_modified_oops(false); 2782 2783 _cmsGen->gc_epilogue_work(full); 2784 2785 if (_collectorState == AbortablePreclean || _collectorState == Precleaning) { 2786 // in case sampling was not already enabled, enable it 2787 _start_sampling = true; 2788 } 2789 // reset _eden_chunk_array so sampling starts afresh 2790 _eden_chunk_index = 0; 2791 2792 size_t cms_used = _cmsGen->cmsSpace()->used(); 2793 2794 // update performance counters - this uses a special version of 2795 // update_counters() that allows the utilization to be passed as a 2796 // parameter, avoiding multiple calls to used(). 2797 // 2798 _cmsGen->update_counters(cms_used); 2799 2800 if (CMSIncrementalMode) { 2801 icms_update_allocation_limits(); 2802 } 2803 2804 bitMapLock()->unlock(); 2805 releaseFreelistLocks(); 2806 2807 if (!CleanChunkPoolAsync) { 2808 Chunk::clean_chunk_pool(); 2809 } 2810 2811 set_did_compact(false); 2812 _between_prologue_and_epilogue = false; // ready for next cycle 2813 } 2814 2815 void ConcurrentMarkSweepGeneration::gc_epilogue(bool full) { 2816 collector()->gc_epilogue(full); 2817 2818 // Also reset promotion tracking in par gc thread states. 2819 if (CollectedHeap::use_parallel_gc_threads()) { 2820 for (uint i = 0; i < ParallelGCThreads; i++) { 2821 _par_gc_thread_states[i]->promo.stopTrackingPromotions(i); 2822 } 2823 } 2824 } 2825 2826 void ConcurrentMarkSweepGeneration::gc_epilogue_work(bool full) { 2827 assert(!incremental_collection_failed(), "Should have been cleared"); 2828 cmsSpace()->setPreconsumptionDirtyCardClosure(NULL); 2829 cmsSpace()->gc_epilogue(); 2830 // Print stat counters 2831 NOT_PRODUCT( 2832 assert(_numObjectsAllocated == 0, "check"); 2833 assert(_numWordsAllocated == 0, "check"); 2834 if (Verbose && PrintGC) { 2835 gclog_or_tty->print("Promoted "SIZE_FORMAT" objects, " 2836 SIZE_FORMAT" bytes", 2837 _numObjectsPromoted, _numWordsPromoted*sizeof(HeapWord)); 2838 } 2839 _numObjectsPromoted = 0; 2840 _numWordsPromoted = 0; 2841 ) 2842 2843 if (PrintGC && Verbose) { 2844 // Call down the chain in contiguous_available needs the freelistLock 2845 // so print this out before releasing the freeListLock. 2846 gclog_or_tty->print(" Contiguous available "SIZE_FORMAT" bytes ", 2847 contiguous_available()); 2848 } 2849 } 2850 2851 #ifndef PRODUCT 2852 bool CMSCollector::have_cms_token() { 2853 Thread* thr = Thread::current(); 2854 if (thr->is_VM_thread()) { 2855 return ConcurrentMarkSweepThread::vm_thread_has_cms_token(); 2856 } else if (thr->is_ConcurrentGC_thread()) { 2857 return ConcurrentMarkSweepThread::cms_thread_has_cms_token(); 2858 } else if (thr->is_GC_task_thread()) { 2859 return ConcurrentMarkSweepThread::vm_thread_has_cms_token() && 2860 ParGCRareEvent_lock->owned_by_self(); 2861 } 2862 return false; 2863 } 2864 #endif 2865 2866 // Check reachability of the given heap address in CMS generation, 2867 // treating all other generations as roots. 2868 bool CMSCollector::is_cms_reachable(HeapWord* addr) { 2869 // We could "guarantee" below, rather than assert, but I'll 2870 // leave these as "asserts" so that an adventurous debugger 2871 // could try this in the product build provided some subset of 2872 // the conditions were met, provided they were interested in the 2873 // results and knew that the computation below wouldn't interfere 2874 // with other concurrent computations mutating the structures 2875 // being read or written. 2876 assert(SafepointSynchronize::is_at_safepoint(), 2877 "Else mutations in object graph will make answer suspect"); 2878 assert(have_cms_token(), "Should hold cms token"); 2879 assert(haveFreelistLocks(), "must hold free list locks"); 2880 assert_lock_strong(bitMapLock()); 2881 2882 // Clear the marking bit map array before starting, but, just 2883 // for kicks, first report if the given address is already marked 2884 gclog_or_tty->print_cr("Start: Address " PTR_FORMAT " is%s marked", addr, 2885 _markBitMap.isMarked(addr) ? "" : " not"); 2886 2887 if (verify_after_remark()) { 2888 MutexLockerEx x(verification_mark_bm()->lock(), Mutex::_no_safepoint_check_flag); 2889 bool result = verification_mark_bm()->isMarked(addr); 2890 gclog_or_tty->print_cr("TransitiveMark: Address " PTR_FORMAT " %s marked", addr, 2891 result ? "IS" : "is NOT"); 2892 return result; 2893 } else { 2894 gclog_or_tty->print_cr("Could not compute result"); 2895 return false; 2896 } 2897 } 2898 2899 2900 void 2901 CMSCollector::print_on_error(outputStream* st) { 2902 CMSCollector* collector = ConcurrentMarkSweepGeneration::_collector; 2903 if (collector != NULL) { 2904 CMSBitMap* bitmap = &collector->_markBitMap; 2905 st->print_cr("Marking Bits: (CMSBitMap*) " PTR_FORMAT, bitmap); 2906 bitmap->print_on_error(st, " Bits: "); 2907 2908 st->cr(); 2909 2910 CMSBitMap* mut_bitmap = &collector->_modUnionTable; 2911 st->print_cr("Mod Union Table: (CMSBitMap*) " PTR_FORMAT, mut_bitmap); 2912 mut_bitmap->print_on_error(st, " Bits: "); 2913 } 2914 } 2915 2916 //////////////////////////////////////////////////////// 2917 // CMS Verification Support 2918 //////////////////////////////////////////////////////// 2919 // Following the remark phase, the following invariant 2920 // should hold -- each object in the CMS heap which is 2921 // marked in markBitMap() should be marked in the verification_mark_bm(). 2922 2923 class VerifyMarkedClosure: public BitMapClosure { 2924 CMSBitMap* _marks; 2925 bool _failed; 2926 2927 public: 2928 VerifyMarkedClosure(CMSBitMap* bm): _marks(bm), _failed(false) {} 2929 2930 bool do_bit(size_t offset) { 2931 HeapWord* addr = _marks->offsetToHeapWord(offset); 2932 if (!_marks->isMarked(addr)) { 2933 oop(addr)->print_on(gclog_or_tty); 2934 gclog_or_tty->print_cr(" ("INTPTR_FORMAT" should have been marked)", addr); 2935 _failed = true; 2936 } 2937 return true; 2938 } 2939 2940 bool failed() { return _failed; } 2941 }; 2942 2943 bool CMSCollector::verify_after_remark(bool silent) { 2944 if (!silent) gclog_or_tty->print(" [Verifying CMS Marking... "); 2945 MutexLockerEx ml(verification_mark_bm()->lock(), Mutex::_no_safepoint_check_flag); 2946 static bool init = false; 2947 2948 assert(SafepointSynchronize::is_at_safepoint(), 2949 "Else mutations in object graph will make answer suspect"); 2950 assert(have_cms_token(), 2951 "Else there may be mutual interference in use of " 2952 " verification data structures"); 2953 assert(_collectorState > Marking && _collectorState <= Sweeping, 2954 "Else marking info checked here may be obsolete"); 2955 assert(haveFreelistLocks(), "must hold free list locks"); 2956 assert_lock_strong(bitMapLock()); 2957 2958 2959 // Allocate marking bit map if not already allocated 2960 if (!init) { // first time 2961 if (!verification_mark_bm()->allocate(_span)) { 2962 return false; 2963 } 2964 init = true; 2965 } 2966 2967 assert(verification_mark_stack()->isEmpty(), "Should be empty"); 2968 2969 // Turn off refs discovery -- so we will be tracing through refs. 2970 // This is as intended, because by this time 2971 // GC must already have cleared any refs that need to be cleared, 2972 // and traced those that need to be marked; moreover, 2973 // the marking done here is not going to interfere in any 2974 // way with the marking information used by GC. 2975 NoRefDiscovery no_discovery(ref_processor()); 2976 2977 COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;) 2978 2979 // Clear any marks from a previous round 2980 verification_mark_bm()->clear_all(); 2981 assert(verification_mark_stack()->isEmpty(), "markStack should be empty"); 2982 verify_work_stacks_empty(); 2983 2984 GenCollectedHeap* gch = GenCollectedHeap::heap(); 2985 gch->ensure_parsability(false); // fill TLABs, but no need to retire them 2986 // Update the saved marks which may affect the root scans. 2987 gch->save_marks(); 2988 2989 if (CMSRemarkVerifyVariant == 1) { 2990 // In this first variant of verification, we complete 2991 // all marking, then check if the new marks-vector is 2992 // a subset of the CMS marks-vector. 2993 verify_after_remark_work_1(); 2994 } else if (CMSRemarkVerifyVariant == 2) { 2995 // In this second variant of verification, we flag an error 2996 // (i.e. an object reachable in the new marks-vector not reachable 2997 // in the CMS marks-vector) immediately, also indicating the 2998 // identify of an object (A) that references the unmarked object (B) -- 2999 // presumably, a mutation to A failed to be picked up by preclean/remark? 3000 verify_after_remark_work_2(); 3001 } else { 3002 warning("Unrecognized value %d for CMSRemarkVerifyVariant", 3003 CMSRemarkVerifyVariant); 3004 } 3005 if (!silent) gclog_or_tty->print(" done] "); 3006 return true; 3007 } 3008 3009 void CMSCollector::verify_after_remark_work_1() { 3010 ResourceMark rm; 3011 HandleMark hm; 3012 GenCollectedHeap* gch = GenCollectedHeap::heap(); 3013 3014 // Get a clear set of claim bits for the roots processing to work with. 3015 ClassLoaderDataGraph::clear_claimed_marks(); 3016 3017 // Mark from roots one level into CMS 3018 MarkRefsIntoClosure notOlder(_span, verification_mark_bm()); 3019 gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel. 3020 3021 gch->gen_process_roots(_cmsGen->level(), 3022 true, // younger gens are roots 3023 true, // activate StrongRootsScope 3024 SharedHeap::ScanningOption(roots_scanning_options()), 3025 should_unload_classes(), 3026 ¬Older, 3027 NULL, 3028 NULL); // SSS: Provide correct closure 3029 3030 // Now mark from the roots 3031 MarkFromRootsClosure markFromRootsClosure(this, _span, 3032 verification_mark_bm(), verification_mark_stack(), 3033 false /* don't yield */, true /* verifying */); 3034 assert(_restart_addr == NULL, "Expected pre-condition"); 3035 verification_mark_bm()->iterate(&markFromRootsClosure); 3036 while (_restart_addr != NULL) { 3037 // Deal with stack overflow: by restarting at the indicated 3038 // address. 3039 HeapWord* ra = _restart_addr; 3040 markFromRootsClosure.reset(ra); 3041 _restart_addr = NULL; 3042 verification_mark_bm()->iterate(&markFromRootsClosure, ra, _span.end()); 3043 } 3044 assert(verification_mark_stack()->isEmpty(), "Should have been drained"); 3045 verify_work_stacks_empty(); 3046 3047 // Marking completed -- now verify that each bit marked in 3048 // verification_mark_bm() is also marked in markBitMap(); flag all 3049 // errors by printing corresponding objects. 3050 VerifyMarkedClosure vcl(markBitMap()); 3051 verification_mark_bm()->iterate(&vcl); 3052 if (vcl.failed()) { 3053 gclog_or_tty->print("Verification failed"); 3054 Universe::heap()->print_on(gclog_or_tty); 3055 fatal("CMS: failed marking verification after remark"); 3056 } 3057 } 3058 3059 class VerifyKlassOopsKlassClosure : public KlassClosure { 3060 class VerifyKlassOopsClosure : public OopClosure { 3061 CMSBitMap* _bitmap; 3062 public: 3063 VerifyKlassOopsClosure(CMSBitMap* bitmap) : _bitmap(bitmap) { } 3064 void do_oop(oop* p) { guarantee(*p == NULL || _bitmap->isMarked((HeapWord*) *p), "Should be marked"); } 3065 void do_oop(narrowOop* p) { ShouldNotReachHere(); } 3066 } _oop_closure; 3067 public: 3068 VerifyKlassOopsKlassClosure(CMSBitMap* bitmap) : _oop_closure(bitmap) {} 3069 void do_klass(Klass* k) { 3070 k->oops_do(&_oop_closure); 3071 } 3072 }; 3073 3074 void CMSCollector::verify_after_remark_work_2() { 3075 ResourceMark rm; 3076 HandleMark hm; 3077 GenCollectedHeap* gch = GenCollectedHeap::heap(); 3078 3079 // Get a clear set of claim bits for the roots processing to work with. 3080 ClassLoaderDataGraph::clear_claimed_marks(); 3081 3082 // Mark from roots one level into CMS 3083 MarkRefsIntoVerifyClosure notOlder(_span, verification_mark_bm(), 3084 markBitMap()); 3085 CLDToOopClosure cld_closure(¬Older, true); 3086 3087 gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel. 3088 3089 gch->gen_process_roots(_cmsGen->level(), 3090 true, // younger gens are roots 3091 true, // activate StrongRootsScope 3092 SharedHeap::ScanningOption(roots_scanning_options()), 3093 should_unload_classes(), 3094 ¬Older, 3095 NULL, 3096 &cld_closure); 3097 3098 // Now mark from the roots 3099 MarkFromRootsVerifyClosure markFromRootsClosure(this, _span, 3100 verification_mark_bm(), markBitMap(), verification_mark_stack()); 3101 assert(_restart_addr == NULL, "Expected pre-condition"); 3102 verification_mark_bm()->iterate(&markFromRootsClosure); 3103 while (_restart_addr != NULL) { 3104 // Deal with stack overflow: by restarting at the indicated 3105 // address. 3106 HeapWord* ra = _restart_addr; 3107 markFromRootsClosure.reset(ra); 3108 _restart_addr = NULL; 3109 verification_mark_bm()->iterate(&markFromRootsClosure, ra, _span.end()); 3110 } 3111 assert(verification_mark_stack()->isEmpty(), "Should have been drained"); 3112 verify_work_stacks_empty(); 3113 3114 VerifyKlassOopsKlassClosure verify_klass_oops(verification_mark_bm()); 3115 ClassLoaderDataGraph::classes_do(&verify_klass_oops); 3116 3117 // Marking completed -- now verify that each bit marked in 3118 // verification_mark_bm() is also marked in markBitMap(); flag all 3119 // errors by printing corresponding objects. 3120 VerifyMarkedClosure vcl(markBitMap()); 3121 verification_mark_bm()->iterate(&vcl); 3122 assert(!vcl.failed(), "Else verification above should not have succeeded"); 3123 } 3124 3125 void ConcurrentMarkSweepGeneration::save_marks() { 3126 // delegate to CMS space 3127 cmsSpace()->save_marks(); 3128 for (uint i = 0; i < ParallelGCThreads; i++) { 3129 _par_gc_thread_states[i]->promo.startTrackingPromotions(); 3130 } 3131 } 3132 3133 bool ConcurrentMarkSweepGeneration::no_allocs_since_save_marks() { 3134 return cmsSpace()->no_allocs_since_save_marks(); 3135 } 3136 3137 #define CMS_SINCE_SAVE_MARKS_DEFN(OopClosureType, nv_suffix) \ 3138 \ 3139 void ConcurrentMarkSweepGeneration:: \ 3140 oop_since_save_marks_iterate##nv_suffix(OopClosureType* cl) { \ 3141 cl->set_generation(this); \ 3142 cmsSpace()->oop_since_save_marks_iterate##nv_suffix(cl); \ 3143 cl->reset_generation(); \ 3144 save_marks(); \ 3145 } 3146 3147 ALL_SINCE_SAVE_MARKS_CLOSURES(CMS_SINCE_SAVE_MARKS_DEFN) 3148 3149 void 3150 ConcurrentMarkSweepGeneration::younger_refs_iterate(OopsInGenClosure* cl) { 3151 cl->set_generation(this); 3152 younger_refs_in_space_iterate(_cmsSpace, cl); 3153 cl->reset_generation(); 3154 } 3155 3156 void 3157 ConcurrentMarkSweepGeneration::oop_iterate(ExtendedOopClosure* cl) { 3158 if (freelistLock()->owned_by_self()) { 3159 Generation::oop_iterate(cl); 3160 } else { 3161 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag); 3162 Generation::oop_iterate(cl); 3163 } 3164 } 3165 3166 void 3167 ConcurrentMarkSweepGeneration::object_iterate(ObjectClosure* cl) { 3168 if (freelistLock()->owned_by_self()) { 3169 Generation::object_iterate(cl); 3170 } else { 3171 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag); 3172 Generation::object_iterate(cl); 3173 } 3174 } 3175 3176 void 3177 ConcurrentMarkSweepGeneration::safe_object_iterate(ObjectClosure* cl) { 3178 if (freelistLock()->owned_by_self()) { 3179 Generation::safe_object_iterate(cl); 3180 } else { 3181 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag); 3182 Generation::safe_object_iterate(cl); 3183 } 3184 } 3185 3186 void 3187 ConcurrentMarkSweepGeneration::post_compact() { 3188 } 3189 3190 void 3191 ConcurrentMarkSweepGeneration::prepare_for_verify() { 3192 // Fix the linear allocation blocks to look like free blocks. 3193 3194 // Locks are normally acquired/released in gc_prologue/gc_epilogue, but those 3195 // are not called when the heap is verified during universe initialization and 3196 // at vm shutdown. 3197 if (freelistLock()->owned_by_self()) { 3198 cmsSpace()->prepare_for_verify(); 3199 } else { 3200 MutexLockerEx fll(freelistLock(), Mutex::_no_safepoint_check_flag); 3201 cmsSpace()->prepare_for_verify(); 3202 } 3203 } 3204 3205 void 3206 ConcurrentMarkSweepGeneration::verify() { 3207 // Locks are normally acquired/released in gc_prologue/gc_epilogue, but those 3208 // are not called when the heap is verified during universe initialization and 3209 // at vm shutdown. 3210 if (freelistLock()->owned_by_self()) { 3211 cmsSpace()->verify(); 3212 } else { 3213 MutexLockerEx fll(freelistLock(), Mutex::_no_safepoint_check_flag); 3214 cmsSpace()->verify(); 3215 } 3216 } 3217 3218 void CMSCollector::verify() { 3219 _cmsGen->verify(); 3220 } 3221 3222 #ifndef PRODUCT 3223 bool CMSCollector::overflow_list_is_empty() const { 3224 assert(_num_par_pushes >= 0, "Inconsistency"); 3225 if (_overflow_list == NULL) { 3226 assert(_num_par_pushes == 0, "Inconsistency"); 3227 } 3228 return _overflow_list == NULL; 3229 } 3230 3231 // The methods verify_work_stacks_empty() and verify_overflow_empty() 3232 // merely consolidate assertion checks that appear to occur together frequently. 3233 void CMSCollector::verify_work_stacks_empty() const { 3234 assert(_markStack.isEmpty(), "Marking stack should be empty"); 3235 assert(overflow_list_is_empty(), "Overflow list should be empty"); 3236 } 3237 3238 void CMSCollector::verify_overflow_empty() const { 3239 assert(overflow_list_is_empty(), "Overflow list should be empty"); 3240 assert(no_preserved_marks(), "No preserved marks"); 3241 } 3242 #endif // PRODUCT 3243 3244 // Decide if we want to enable class unloading as part of the 3245 // ensuing concurrent GC cycle. We will collect and 3246 // unload classes if it's the case that: 3247 // (1) an explicit gc request has been made and the flag 3248 // ExplicitGCInvokesConcurrentAndUnloadsClasses is set, OR 3249 // (2) (a) class unloading is enabled at the command line, and 3250 // (b) old gen is getting really full 3251 // NOTE: Provided there is no change in the state of the heap between 3252 // calls to this method, it should have idempotent results. Moreover, 3253 // its results should be monotonically increasing (i.e. going from 0 to 1, 3254 // but not 1 to 0) between successive calls between which the heap was 3255 // not collected. For the implementation below, it must thus rely on 3256 // the property that concurrent_cycles_since_last_unload() 3257 // will not decrease unless a collection cycle happened and that 3258 // _cmsGen->is_too_full() are 3259 // themselves also monotonic in that sense. See check_monotonicity() 3260 // below. 3261 void CMSCollector::update_should_unload_classes() { 3262 _should_unload_classes = false; 3263 // Condition 1 above 3264 if (_full_gc_requested && ExplicitGCInvokesConcurrentAndUnloadsClasses) { 3265 _should_unload_classes = true; 3266 } else if (CMSClassUnloadingEnabled) { // Condition 2.a above 3267 // Disjuncts 2.b.(i,ii,iii) above 3268 _should_unload_classes = (concurrent_cycles_since_last_unload() >= 3269 CMSClassUnloadingMaxInterval) 3270 || _cmsGen->is_too_full(); 3271 } 3272 } 3273 3274 bool ConcurrentMarkSweepGeneration::is_too_full() const { 3275 bool res = should_concurrent_collect(); 3276 res = res && (occupancy() > (double)CMSIsTooFullPercentage/100.0); 3277 return res; 3278 } 3279 3280 void CMSCollector::setup_cms_unloading_and_verification_state() { 3281 const bool should_verify = VerifyBeforeGC || VerifyAfterGC || VerifyDuringGC 3282 || VerifyBeforeExit; 3283 const int rso = SharedHeap::SO_AllCodeCache; 3284 3285 // We set the proper root for this CMS cycle here. 3286 if (should_unload_classes()) { // Should unload classes this cycle 3287 remove_root_scanning_option(rso); // Shrink the root set appropriately 3288 set_verifying(should_verify); // Set verification state for this cycle 3289 return; // Nothing else needs to be done at this time 3290 } 3291 3292 // Not unloading classes this cycle 3293 assert(!should_unload_classes(), "Inconsistency!"); 3294 3295 if ((!verifying() || unloaded_classes_last_cycle()) && should_verify) { 3296 // Include symbols, strings and code cache elements to prevent their resurrection. 3297 add_root_scanning_option(rso); 3298 set_verifying(true); 3299 } else if (verifying() && !should_verify) { 3300 // We were verifying, but some verification flags got disabled. 3301 set_verifying(false); 3302 // Exclude symbols, strings and code cache elements from root scanning to 3303 // reduce IM and RM pauses. 3304 remove_root_scanning_option(rso); 3305 } 3306 } 3307 3308 3309 #ifndef PRODUCT 3310 HeapWord* CMSCollector::block_start(const void* p) const { 3311 const HeapWord* addr = (HeapWord*)p; 3312 if (_span.contains(p)) { 3313 if (_cmsGen->cmsSpace()->is_in_reserved(addr)) { 3314 return _cmsGen->cmsSpace()->block_start(p); 3315 } 3316 } 3317 return NULL; 3318 } 3319 #endif 3320 3321 HeapWord* 3322 ConcurrentMarkSweepGeneration::expand_and_allocate(size_t word_size, 3323 bool tlab, 3324 bool parallel) { 3325 CMSSynchronousYieldRequest yr; 3326 assert(!tlab, "Can't deal with TLAB allocation"); 3327 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag); 3328 expand(word_size*HeapWordSize, MinHeapDeltaBytes, 3329 CMSExpansionCause::_satisfy_allocation); 3330 if (GCExpandToAllocateDelayMillis > 0) { 3331 os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false); 3332 } 3333 return have_lock_and_allocate(word_size, tlab); 3334 } 3335 3336 // YSR: All of this generation expansion/shrinking stuff is an exact copy of 3337 // OneContigSpaceCardGeneration, which makes me wonder if we should move this 3338 // to CardGeneration and share it... 3339 bool ConcurrentMarkSweepGeneration::expand(size_t bytes, size_t expand_bytes) { 3340 return CardGeneration::expand(bytes, expand_bytes); 3341 } 3342 3343 void ConcurrentMarkSweepGeneration::expand(size_t bytes, size_t expand_bytes, 3344 CMSExpansionCause::Cause cause) 3345 { 3346 3347 bool success = expand(bytes, expand_bytes); 3348 3349 // remember why we expanded; this information is used 3350 // by shouldConcurrentCollect() when making decisions on whether to start 3351 // a new CMS cycle. 3352 if (success) { 3353 set_expansion_cause(cause); 3354 if (PrintGCDetails && Verbose) { 3355 gclog_or_tty->print_cr("Expanded CMS gen for %s", 3356 CMSExpansionCause::to_string(cause)); 3357 } 3358 } 3359 } 3360 3361 HeapWord* ConcurrentMarkSweepGeneration::expand_and_par_lab_allocate(CMSParGCThreadState* ps, size_t word_sz) { 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(¬Older, 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 ¬Older, 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 }