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