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