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