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 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_roots(_cmsGen->level(), 3008 true, // younger gens are roots 3009 true, // activate StrongRootsScope 3010 SharedHeap::ScanningOption(roots_scanning_options()), 3011 should_unload_classes(), 3012 ¬Older, 3013 NULL, 3014 NULL); // SSS: Provide correct closure 3015 3016 // Now mark from the roots 3017 MarkFromRootsClosure markFromRootsClosure(this, _span, 3018 verification_mark_bm(), verification_mark_stack(), 3019 false /* don't yield */, true /* verifying */); 3020 assert(_restart_addr == NULL, "Expected pre-condition"); 3021 verification_mark_bm()->iterate(&markFromRootsClosure); 3022 while (_restart_addr != NULL) { 3023 // Deal with stack overflow: by restarting at the indicated 3024 // address. 3025 HeapWord* ra = _restart_addr; 3026 markFromRootsClosure.reset(ra); 3027 _restart_addr = NULL; 3028 verification_mark_bm()->iterate(&markFromRootsClosure, ra, _span.end()); 3029 } 3030 assert(verification_mark_stack()->isEmpty(), "Should have been drained"); 3031 verify_work_stacks_empty(); 3032 3033 // Marking completed -- now verify that each bit marked in 3034 // verification_mark_bm() is also marked in markBitMap(); flag all 3035 // errors by printing corresponding objects. 3036 VerifyMarkedClosure vcl(markBitMap()); 3037 verification_mark_bm()->iterate(&vcl); 3038 if (vcl.failed()) { 3039 gclog_or_tty->print("Verification failed"); 3040 Universe::heap()->print_on(gclog_or_tty); 3041 fatal("CMS: failed marking verification after remark"); 3042 } 3043 } 3044 3045 class VerifyKlassOopsKlassClosure : public KlassClosure { 3046 class VerifyKlassOopsClosure : public OopClosure { 3047 CMSBitMap* _bitmap; 3048 public: 3049 VerifyKlassOopsClosure(CMSBitMap* bitmap) : _bitmap(bitmap) { } 3050 void do_oop(oop* p) { guarantee(*p == NULL || _bitmap->isMarked((HeapWord*) *p), "Should be marked"); } 3051 void do_oop(narrowOop* p) { ShouldNotReachHere(); } 3052 } _oop_closure; 3053 public: 3054 VerifyKlassOopsKlassClosure(CMSBitMap* bitmap) : _oop_closure(bitmap) {} 3055 void do_klass(Klass* k) { 3056 k->oops_do(&_oop_closure); 3057 } 3058 }; 3059 3060 void CMSCollector::verify_after_remark_work_2() { 3061 ResourceMark rm; 3062 HandleMark hm; 3063 GenCollectedHeap* gch = GenCollectedHeap::heap(); 3064 3065 // Get a clear set of claim bits for the roots processing to work with. 3066 ClassLoaderDataGraph::clear_claimed_marks(); 3067 3068 // Mark from roots one level into CMS 3069 MarkRefsIntoVerifyClosure notOlder(_span, verification_mark_bm(), 3070 markBitMap()); 3071 CLDToOopClosure cld_closure(¬Older, true); 3072 3073 gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel. 3074 3075 gch->gen_process_roots(_cmsGen->level(), 3076 true, // younger gens are roots 3077 true, // activate StrongRootsScope 3078 SharedHeap::ScanningOption(roots_scanning_options()), 3079 should_unload_classes(), 3080 ¬Older, 3081 NULL, 3082 &cld_closure); 3083 3084 // Now mark from the roots 3085 MarkFromRootsVerifyClosure markFromRootsClosure(this, _span, 3086 verification_mark_bm(), markBitMap(), verification_mark_stack()); 3087 assert(_restart_addr == NULL, "Expected pre-condition"); 3088 verification_mark_bm()->iterate(&markFromRootsClosure); 3089 while (_restart_addr != NULL) { 3090 // Deal with stack overflow: by restarting at the indicated 3091 // address. 3092 HeapWord* ra = _restart_addr; 3093 markFromRootsClosure.reset(ra); 3094 _restart_addr = NULL; 3095 verification_mark_bm()->iterate(&markFromRootsClosure, ra, _span.end()); 3096 } 3097 assert(verification_mark_stack()->isEmpty(), "Should have been drained"); 3098 verify_work_stacks_empty(); 3099 3100 VerifyKlassOopsKlassClosure verify_klass_oops(verification_mark_bm()); 3101 ClassLoaderDataGraph::classes_do(&verify_klass_oops); 3102 3103 // Marking completed -- now verify that each bit marked in 3104 // verification_mark_bm() is also marked in markBitMap(); flag all 3105 // errors by printing corresponding objects. 3106 VerifyMarkedClosure vcl(markBitMap()); 3107 verification_mark_bm()->iterate(&vcl); 3108 assert(!vcl.failed(), "Else verification above should not have succeeded"); 3109 } 3110 3111 void ConcurrentMarkSweepGeneration::save_marks() { 3112 // delegate to CMS space 3113 cmsSpace()->save_marks(); 3114 for (uint i = 0; i < ParallelGCThreads; i++) { 3115 _par_gc_thread_states[i]->promo.startTrackingPromotions(); 3116 } 3117 } 3118 3119 bool ConcurrentMarkSweepGeneration::no_allocs_since_save_marks() { 3120 return cmsSpace()->no_allocs_since_save_marks(); 3121 } 3122 3123 #define CMS_SINCE_SAVE_MARKS_DEFN(OopClosureType, nv_suffix) \ 3124 \ 3125 void ConcurrentMarkSweepGeneration:: \ 3126 oop_since_save_marks_iterate##nv_suffix(OopClosureType* cl) { \ 3127 cl->set_generation(this); \ 3128 cmsSpace()->oop_since_save_marks_iterate##nv_suffix(cl); \ 3129 cl->reset_generation(); \ 3130 save_marks(); \ 3131 } 3132 3133 ALL_SINCE_SAVE_MARKS_CLOSURES(CMS_SINCE_SAVE_MARKS_DEFN) 3134 3135 void 3136 ConcurrentMarkSweepGeneration::younger_refs_iterate(OopsInGenClosure* cl) { 3137 cl->set_generation(this); 3138 younger_refs_in_space_iterate(_cmsSpace, cl); 3139 cl->reset_generation(); 3140 } 3141 3142 void 3143 ConcurrentMarkSweepGeneration::oop_iterate(ExtendedOopClosure* cl) { 3144 if (freelistLock()->owned_by_self()) { 3145 Generation::oop_iterate(cl); 3146 } else { 3147 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag); 3148 Generation::oop_iterate(cl); 3149 } 3150 } 3151 3152 void 3153 ConcurrentMarkSweepGeneration::object_iterate(ObjectClosure* cl) { 3154 if (freelistLock()->owned_by_self()) { 3155 Generation::object_iterate(cl); 3156 } else { 3157 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag); 3158 Generation::object_iterate(cl); 3159 } 3160 } 3161 3162 void 3163 ConcurrentMarkSweepGeneration::safe_object_iterate(ObjectClosure* cl) { 3164 if (freelistLock()->owned_by_self()) { 3165 Generation::safe_object_iterate(cl); 3166 } else { 3167 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag); 3168 Generation::safe_object_iterate(cl); 3169 } 3170 } 3171 3172 void 3173 ConcurrentMarkSweepGeneration::post_compact() { 3174 } 3175 3176 void 3177 ConcurrentMarkSweepGeneration::prepare_for_verify() { 3178 // Fix the linear allocation blocks to look like free blocks. 3179 3180 // Locks are normally acquired/released in gc_prologue/gc_epilogue, but those 3181 // are not called when the heap is verified during universe initialization and 3182 // at vm shutdown. 3183 if (freelistLock()->owned_by_self()) { 3184 cmsSpace()->prepare_for_verify(); 3185 } else { 3186 MutexLockerEx fll(freelistLock(), Mutex::_no_safepoint_check_flag); 3187 cmsSpace()->prepare_for_verify(); 3188 } 3189 } 3190 3191 void 3192 ConcurrentMarkSweepGeneration::verify() { 3193 // Locks are normally acquired/released in gc_prologue/gc_epilogue, but those 3194 // are not called when the heap is verified during universe initialization and 3195 // at vm shutdown. 3196 if (freelistLock()->owned_by_self()) { 3197 cmsSpace()->verify(); 3198 } else { 3199 MutexLockerEx fll(freelistLock(), Mutex::_no_safepoint_check_flag); 3200 cmsSpace()->verify(); 3201 } 3202 } 3203 3204 void CMSCollector::verify() { 3205 _cmsGen->verify(); 3206 } 3207 3208 #ifndef PRODUCT 3209 bool CMSCollector::overflow_list_is_empty() const { 3210 assert(_num_par_pushes >= 0, "Inconsistency"); 3211 if (_overflow_list == NULL) { 3212 assert(_num_par_pushes == 0, "Inconsistency"); 3213 } 3214 return _overflow_list == NULL; 3215 } 3216 3217 // The methods verify_work_stacks_empty() and verify_overflow_empty() 3218 // merely consolidate assertion checks that appear to occur together frequently. 3219 void CMSCollector::verify_work_stacks_empty() const { 3220 assert(_markStack.isEmpty(), "Marking stack should be empty"); 3221 assert(overflow_list_is_empty(), "Overflow list should be empty"); 3222 } 3223 3224 void CMSCollector::verify_overflow_empty() const { 3225 assert(overflow_list_is_empty(), "Overflow list should be empty"); 3226 assert(no_preserved_marks(), "No preserved marks"); 3227 } 3228 #endif // PRODUCT 3229 3230 // Decide if we want to enable class unloading as part of the 3231 // ensuing concurrent GC cycle. We will collect and 3232 // unload classes if it's the case that: 3233 // (1) an explicit gc request has been made and the flag 3234 // ExplicitGCInvokesConcurrentAndUnloadsClasses is set, OR 3235 // (2) (a) class unloading is enabled at the command line, and 3236 // (b) old gen is getting really full 3237 // NOTE: Provided there is no change in the state of the heap between 3238 // calls to this method, it should have idempotent results. Moreover, 3239 // its results should be monotonically increasing (i.e. going from 0 to 1, 3240 // but not 1 to 0) between successive calls between which the heap was 3241 // not collected. For the implementation below, it must thus rely on 3242 // the property that concurrent_cycles_since_last_unload() 3243 // will not decrease unless a collection cycle happened and that 3244 // _cmsGen->is_too_full() are 3245 // themselves also monotonic in that sense. See check_monotonicity() 3246 // below. 3247 void CMSCollector::update_should_unload_classes() { 3248 _should_unload_classes = false; 3249 // Condition 1 above 3250 if (_full_gc_requested && ExplicitGCInvokesConcurrentAndUnloadsClasses) { 3251 _should_unload_classes = true; 3252 } else if (CMSClassUnloadingEnabled) { // Condition 2.a above 3253 // Disjuncts 2.b.(i,ii,iii) above 3254 _should_unload_classes = (concurrent_cycles_since_last_unload() >= 3255 CMSClassUnloadingMaxInterval) 3256 || _cmsGen->is_too_full(); 3257 } 3258 } 3259 3260 bool ConcurrentMarkSweepGeneration::is_too_full() const { 3261 bool res = should_concurrent_collect(); 3262 res = res && (occupancy() > (double)CMSIsTooFullPercentage/100.0); 3263 return res; 3264 } 3265 3266 void CMSCollector::setup_cms_unloading_and_verification_state() { 3267 const bool should_verify = VerifyBeforeGC || VerifyAfterGC || VerifyDuringGC 3268 || VerifyBeforeExit; 3269 const int rso = SharedHeap::SO_AllCodeCache; 3270 3271 // We set the proper root for this CMS cycle here. 3272 if (should_unload_classes()) { // Should unload classes this cycle 3273 remove_root_scanning_option(rso); // Shrink the root set appropriately 3274 set_verifying(should_verify); // Set verification state for this cycle 3275 return; // Nothing else needs to be done at this time 3276 } 3277 3278 // Not unloading classes this cycle 3279 assert(!should_unload_classes(), "Inconsistency!"); 3280 3281 if ((!verifying() || unloaded_classes_last_cycle()) && should_verify) { 3282 // Include symbols, strings and code cache elements to prevent their resurrection. 3283 add_root_scanning_option(rso); 3284 set_verifying(true); 3285 } else if (verifying() && !should_verify) { 3286 // We were verifying, but some verification flags got disabled. 3287 set_verifying(false); 3288 // Exclude symbols, strings and code cache elements from root scanning to 3289 // reduce IM and RM pauses. 3290 remove_root_scanning_option(rso); 3291 } 3292 } 3293 3294 3295 #ifndef PRODUCT 3296 HeapWord* CMSCollector::block_start(const void* p) const { 3297 const HeapWord* addr = (HeapWord*)p; 3298 if (_span.contains(p)) { 3299 if (_cmsGen->cmsSpace()->is_in_reserved(addr)) { 3300 return _cmsGen->cmsSpace()->block_start(p); 3301 } 3302 } 3303 return NULL; 3304 } 3305 #endif 3306 3307 HeapWord* 3308 ConcurrentMarkSweepGeneration::expand_and_allocate(size_t word_size, 3309 bool tlab, 3310 bool parallel) { 3311 CMSSynchronousYieldRequest yr; 3312 assert(!tlab, "Can't deal with TLAB allocation"); 3313 MutexLockerEx x(freelistLock(), Mutex::_no_safepoint_check_flag); 3314 expand(word_size*HeapWordSize, MinHeapDeltaBytes, 3315 CMSExpansionCause::_satisfy_allocation); 3316 if (GCExpandToAllocateDelayMillis > 0) { 3317 os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false); 3318 } 3319 return have_lock_and_allocate(word_size, tlab); 3320 } 3321 3322 // YSR: All of this generation expansion/shrinking stuff is an exact copy of 3323 // OneContigSpaceCardGeneration, which makes me wonder if we should move this 3324 // to CardGeneration and share it... 3325 bool ConcurrentMarkSweepGeneration::expand(size_t bytes, size_t expand_bytes) { 3326 return CardGeneration::expand(bytes, expand_bytes); 3327 } 3328 3329 void ConcurrentMarkSweepGeneration::expand(size_t bytes, size_t expand_bytes, 3330 CMSExpansionCause::Cause cause) 3331 { 3332 3333 bool success = expand(bytes, expand_bytes); 3334 3335 // remember why we expanded; this information is used 3336 // by shouldConcurrentCollect() when making decisions on whether to start 3337 // a new CMS cycle. 3338 if (success) { 3339 set_expansion_cause(cause); 3340 if (PrintGCDetails && Verbose) { 3341 gclog_or_tty->print_cr("Expanded CMS gen for %s", 3342 CMSExpansionCause::to_string(cause)); 3343 } 3344 } 3345 } 3346 3347 HeapWord* ConcurrentMarkSweepGeneration::expand_and_par_lab_allocate(CMSParGCThreadState* ps, size_t word_sz) { 3348 HeapWord* res = NULL; 3349 MutexLocker x(ParGCRareEvent_lock); 3350 while (true) { 3351 // Expansion by some other thread might make alloc OK now: 3352 res = ps->lab.alloc(word_sz); 3353 if (res != NULL) return res; 3354 // If there's not enough expansion space available, give up. 3355 if (_virtual_space.uncommitted_size() < (word_sz * HeapWordSize)) { 3356 return NULL; 3357 } 3358 // Otherwise, we try expansion. 3359 expand(word_sz*HeapWordSize, MinHeapDeltaBytes, 3360 CMSExpansionCause::_allocate_par_lab); 3361 // Now go around the loop and try alloc again; 3362 // A competing par_promote might beat us to the expansion space, 3363 // so we may go around the loop again if promotion fails again. 3364 if (GCExpandToAllocateDelayMillis > 0) { 3365 os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false); 3366 } 3367 } 3368 } 3369 3370 3371 bool ConcurrentMarkSweepGeneration::expand_and_ensure_spooling_space( 3372 PromotionInfo* promo) { 3373 MutexLocker x(ParGCRareEvent_lock); 3374 size_t refill_size_bytes = promo->refillSize() * HeapWordSize; 3375 while (true) { 3376 // Expansion by some other thread might make alloc OK now: 3377 if (promo->ensure_spooling_space()) { 3378 assert(promo->has_spooling_space(), 3379 "Post-condition of successful ensure_spooling_space()"); 3380 return true; 3381 } 3382 // If there's not enough expansion space available, give up. 3383 if (_virtual_space.uncommitted_size() < refill_size_bytes) { 3384 return false; 3385 } 3386 // Otherwise, we try expansion. 3387 expand(refill_size_bytes, MinHeapDeltaBytes, 3388 CMSExpansionCause::_allocate_par_spooling_space); 3389 // Now go around the loop and try alloc again; 3390 // A competing allocation might beat us to the expansion space, 3391 // so we may go around the loop again if allocation fails again. 3392 if (GCExpandToAllocateDelayMillis > 0) { 3393 os::sleep(Thread::current(), GCExpandToAllocateDelayMillis, false); 3394 } 3395 } 3396 } 3397 3398 3399 void ConcurrentMarkSweepGeneration::shrink_by(size_t bytes) { 3400 assert_locked_or_safepoint(ExpandHeap_lock); 3401 // Shrink committed space 3402 _virtual_space.shrink_by(bytes); 3403 // Shrink space; this also shrinks the space's BOT 3404 _cmsSpace->set_end((HeapWord*) _virtual_space.high()); 3405 size_t new_word_size = heap_word_size(_cmsSpace->capacity()); 3406 // Shrink the shared block offset array 3407 _bts->resize(new_word_size); 3408 MemRegion mr(_cmsSpace->bottom(), new_word_size); 3409 // Shrink the card table 3410 Universe::heap()->barrier_set()->resize_covered_region(mr); 3411 3412 if (Verbose && PrintGC) { 3413 size_t new_mem_size = _virtual_space.committed_size(); 3414 size_t old_mem_size = new_mem_size + bytes; 3415 gclog_or_tty->print_cr("Shrinking %s from " SIZE_FORMAT "K to " SIZE_FORMAT "K", 3416 name(), old_mem_size/K, new_mem_size/K); 3417 } 3418 } 3419 3420 void ConcurrentMarkSweepGeneration::shrink(size_t bytes) { 3421 assert_locked_or_safepoint(Heap_lock); 3422 size_t size = ReservedSpace::page_align_size_down(bytes); 3423 // Only shrink if a compaction was done so that all the free space 3424 // in the generation is in a contiguous block at the end. 3425 if (size > 0 && did_compact()) { 3426 shrink_by(size); 3427 } 3428 } 3429 3430 bool ConcurrentMarkSweepGeneration::grow_by(size_t bytes) { 3431 assert_locked_or_safepoint(Heap_lock); 3432 bool result = _virtual_space.expand_by(bytes); 3433 if (result) { 3434 size_t new_word_size = 3435 heap_word_size(_virtual_space.committed_size()); 3436 MemRegion mr(_cmsSpace->bottom(), new_word_size); 3437 _bts->resize(new_word_size); // resize the block offset shared array 3438 Universe::heap()->barrier_set()->resize_covered_region(mr); 3439 // Hmmmm... why doesn't CFLS::set_end verify locking? 3440 // This is quite ugly; FIX ME XXX 3441 _cmsSpace->assert_locked(freelistLock()); 3442 _cmsSpace->set_end((HeapWord*)_virtual_space.high()); 3443 3444 // update the space and generation capacity counters 3445 if (UsePerfData) { 3446 _space_counters->update_capacity(); 3447 _gen_counters->update_all(); 3448 } 3449 3450 if (Verbose && PrintGC) { 3451 size_t new_mem_size = _virtual_space.committed_size(); 3452 size_t old_mem_size = new_mem_size - bytes; 3453 gclog_or_tty->print_cr("Expanding %s from " SIZE_FORMAT "K by " SIZE_FORMAT "K to " SIZE_FORMAT "K", 3454 name(), old_mem_size/K, bytes/K, new_mem_size/K); 3455 } 3456 } 3457 return result; 3458 } 3459 3460 bool ConcurrentMarkSweepGeneration::grow_to_reserved() { 3461 assert_locked_or_safepoint(Heap_lock); 3462 bool success = true; 3463 const size_t remaining_bytes = _virtual_space.uncommitted_size(); 3464 if (remaining_bytes > 0) { 3465 success = grow_by(remaining_bytes); 3466 DEBUG_ONLY(if (!success) warning("grow to reserved failed");) 3467 } 3468 return success; 3469 } 3470 3471 void ConcurrentMarkSweepGeneration::shrink_free_list_by(size_t bytes) { 3472 assert_locked_or_safepoint(Heap_lock); 3473 assert_lock_strong(freelistLock()); 3474 if (PrintGCDetails && Verbose) { 3475 warning("Shrinking of CMS not yet implemented"); 3476 } 3477 return; 3478 } 3479 3480 3481 // Simple ctor/dtor wrapper for accounting & timer chores around concurrent 3482 // phases. 3483 class CMSPhaseAccounting: public StackObj { 3484 public: 3485 CMSPhaseAccounting(CMSCollector *collector, 3486 const char *phase, 3487 const GCId gc_id, 3488 bool print_cr = true); 3489 ~CMSPhaseAccounting(); 3490 3491 private: 3492 CMSCollector *_collector; 3493 const char *_phase; 3494 elapsedTimer _wallclock; 3495 bool _print_cr; 3496 const GCId _gc_id; 3497 3498 public: 3499 // Not MT-safe; so do not pass around these StackObj's 3500 // where they may be accessed by other threads. 3501 jlong wallclock_millis() { 3502 assert(_wallclock.is_active(), "Wall clock should not stop"); 3503 _wallclock.stop(); // to record time 3504 jlong ret = _wallclock.milliseconds(); 3505 _wallclock.start(); // restart 3506 return ret; 3507 } 3508 }; 3509 3510 CMSPhaseAccounting::CMSPhaseAccounting(CMSCollector *collector, 3511 const char *phase, 3512 const GCId gc_id, 3513 bool print_cr) : 3514 _collector(collector), _phase(phase), _print_cr(print_cr), _gc_id(gc_id) { 3515 3516 if (PrintCMSStatistics != 0) { 3517 _collector->resetYields(); 3518 } 3519 if (PrintGCDetails) { 3520 gclog_or_tty->gclog_stamp(_gc_id); 3521 gclog_or_tty->print_cr("[%s-concurrent-%s-start]", 3522 _collector->cmsGen()->short_name(), _phase); 3523 } 3524 _collector->resetTimer(); 3525 _wallclock.start(); 3526 _collector->startTimer(); 3527 } 3528 3529 CMSPhaseAccounting::~CMSPhaseAccounting() { 3530 assert(_wallclock.is_active(), "Wall clock should not have stopped"); 3531 _collector->stopTimer(); 3532 _wallclock.stop(); 3533 if (PrintGCDetails) { 3534 gclog_or_tty->gclog_stamp(_gc_id); 3535 gclog_or_tty->print("[%s-concurrent-%s: %3.3f/%3.3f secs]", 3536 _collector->cmsGen()->short_name(), 3537 _phase, _collector->timerValue(), _wallclock.seconds()); 3538 if (_print_cr) { 3539 gclog_or_tty->cr(); 3540 } 3541 if (PrintCMSStatistics != 0) { 3542 gclog_or_tty->print_cr(" (CMS-concurrent-%s yielded %d times)", _phase, 3543 _collector->yields()); 3544 } 3545 } 3546 } 3547 3548 // CMS work 3549 3550 // The common parts of CMSParInitialMarkTask and CMSParRemarkTask. 3551 class CMSParMarkTask : public AbstractGangTask { 3552 protected: 3553 CMSCollector* _collector; 3554 int _n_workers; 3555 CMSParMarkTask(const char* name, CMSCollector* collector, int n_workers) : 3556 AbstractGangTask(name), 3557 _collector(collector), 3558 _n_workers(n_workers) {} 3559 // Work method in support of parallel rescan ... of young gen spaces 3560 void do_young_space_rescan(uint worker_id, OopsInGenClosure* cl, 3561 ContiguousSpace* space, 3562 HeapWord** chunk_array, size_t chunk_top); 3563 void work_on_young_gen_roots(uint worker_id, OopsInGenClosure* cl); 3564 }; 3565 3566 // Parallel initial mark task 3567 class CMSParInitialMarkTask: public CMSParMarkTask { 3568 public: 3569 CMSParInitialMarkTask(CMSCollector* collector, int n_workers) : 3570 CMSParMarkTask("Scan roots and young gen for initial mark in parallel", 3571 collector, n_workers) {} 3572 void work(uint worker_id); 3573 }; 3574 3575 // Checkpoint the roots into this generation from outside 3576 // this generation. [Note this initial checkpoint need only 3577 // be approximate -- we'll do a catch up phase subsequently.] 3578 void CMSCollector::checkpointRootsInitial(bool asynch) { 3579 assert(_collectorState == InitialMarking, "Wrong collector state"); 3580 check_correct_thread_executing(); 3581 TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause()); 3582 3583 save_heap_summary(); 3584 report_heap_summary(GCWhen::BeforeGC); 3585 3586 ReferenceProcessor* rp = ref_processor(); 3587 SpecializationStats::clear(); 3588 assert(_restart_addr == NULL, "Control point invariant"); 3589 if (asynch) { 3590 // acquire locks for subsequent manipulations 3591 MutexLockerEx x(bitMapLock(), 3592 Mutex::_no_safepoint_check_flag); 3593 checkpointRootsInitialWork(asynch); 3594 // enable ("weak") refs discovery 3595 rp->enable_discovery(true /*verify_disabled*/, true /*check_no_refs*/); 3596 _collectorState = Marking; 3597 } else { 3598 // (Weak) Refs discovery: this is controlled from genCollectedHeap::do_collection 3599 // which recognizes if we are a CMS generation, and doesn't try to turn on 3600 // discovery; verify that they aren't meddling. 3601 assert(!rp->discovery_is_atomic(), 3602 "incorrect setting of discovery predicate"); 3603 assert(!rp->discovery_enabled(), "genCollectedHeap shouldn't control " 3604 "ref discovery for this generation kind"); 3605 // already have locks 3606 checkpointRootsInitialWork(asynch); 3607 // now enable ("weak") refs discovery 3608 rp->enable_discovery(true /*verify_disabled*/, false /*verify_no_refs*/); 3609 _collectorState = Marking; 3610 } 3611 SpecializationStats::print(); 3612 } 3613 3614 void CMSCollector::checkpointRootsInitialWork(bool asynch) { 3615 assert(SafepointSynchronize::is_at_safepoint(), "world should be stopped"); 3616 assert(_collectorState == InitialMarking, "just checking"); 3617 3618 // If there has not been a GC[n-1] since last GC[n] cycle completed, 3619 // precede our marking with a collection of all 3620 // younger generations to keep floating garbage to a minimum. 3621 // XXX: we won't do this for now -- it's an optimization to be done later. 3622 3623 // already have locks 3624 assert_lock_strong(bitMapLock()); 3625 assert(_markBitMap.isAllClear(), "was reset at end of previous cycle"); 3626 3627 // Setup the verification and class unloading state for this 3628 // CMS collection cycle. 3629 setup_cms_unloading_and_verification_state(); 3630 3631 NOT_PRODUCT(GCTraceTime t("\ncheckpointRootsInitialWork", 3632 PrintGCDetails && Verbose, true, _gc_timer_cm, _gc_tracer_cm->gc_id());) 3633 3634 // Reset all the PLAB chunk arrays if necessary. 3635 if (_survivor_plab_array != NULL && !CMSPLABRecordAlways) { 3636 reset_survivor_plab_arrays(); 3637 } 3638 3639 ResourceMark rm; 3640 HandleMark hm; 3641 3642 MarkRefsIntoClosure notOlder(_span, &_markBitMap); 3643 GenCollectedHeap* gch = GenCollectedHeap::heap(); 3644 3645 verify_work_stacks_empty(); 3646 verify_overflow_empty(); 3647 3648 gch->ensure_parsability(false); // fill TLABs, but no need to retire them 3649 // Update the saved marks which may affect the root scans. 3650 gch->save_marks(); 3651 3652 // weak reference processing has not started yet. 3653 ref_processor()->set_enqueuing_is_done(false); 3654 3655 // Need to remember all newly created CLDs, 3656 // so that we can guarantee that the remark finds them. 3657 ClassLoaderDataGraph::remember_new_clds(true); 3658 3659 // Whenever a CLD is found, it will be claimed before proceeding to mark 3660 // the klasses. The claimed marks need to be cleared before marking starts. 3661 ClassLoaderDataGraph::clear_claimed_marks(); 3662 3663 if (CMSPrintEdenSurvivorChunks) { 3664 print_eden_and_survivor_chunk_arrays(); 3665 } 3666 3667 { 3668 COMPILER2_PRESENT(DerivedPointerTableDeactivate dpt_deact;) 3669 if (CMSParallelInitialMarkEnabled && CollectedHeap::use_parallel_gc_threads()) { 3670 // The parallel version. 3671 FlexibleWorkGang* workers = gch->workers(); 3672 assert(workers != NULL, "Need parallel worker threads."); 3673 int n_workers = workers->active_workers(); 3674 CMSParInitialMarkTask tsk(this, n_workers); 3675 gch->set_par_threads(n_workers); 3676 initialize_sequential_subtasks_for_young_gen_rescan(n_workers); 3677 if (n_workers > 1) { 3678 GenCollectedHeap::StrongRootsScope srs(gch); 3679 workers->run_task(&tsk); 3680 } else { 3681 GenCollectedHeap::StrongRootsScope srs(gch); 3682 tsk.work(0); 3683 } 3684 gch->set_par_threads(0); 3685 } else { 3686 // The serial version. 3687 CLDToOopClosure cld_closure(¬Older, true); 3688 gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel. 3689 gch->gen_process_roots(_cmsGen->level(), 3690 true, // younger gens are roots 3691 true, // activate StrongRootsScope 3692 SharedHeap::ScanningOption(roots_scanning_options()), 3693 should_unload_classes(), 3694 ¬Older, 3695 NULL, 3696 &cld_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 5143 // ---------- young gen roots -------------- 5144 { 5145 work_on_young_gen_roots(worker_id, &par_mri_cl); 5146 _timer.stop(); 5147 if (PrintCMSStatistics != 0) { 5148 gclog_or_tty->print_cr( 5149 "Finished young gen initial mark scan work in %dth thread: %3.3f sec", 5150 worker_id, _timer.seconds()); 5151 } 5152 } 5153 5154 // ---------- remaining roots -------------- 5155 _timer.reset(); 5156 _timer.start(); 5157 5158 CLDToOopClosure cld_closure(&par_mri_cl, true); 5159 5160 gch->gen_process_roots(_collector->_cmsGen->level(), 5161 false, // yg was scanned above 5162 false, // this is parallel code 5163 SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()), 5164 _collector->should_unload_classes(), 5165 &par_mri_cl, 5166 NULL, 5167 &cld_closure); 5168 assert(_collector->should_unload_classes() 5169 || (_collector->CMSCollector::roots_scanning_options() & SharedHeap::SO_AllCodeCache), 5170 "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops"); 5171 _timer.stop(); 5172 if (PrintCMSStatistics != 0) { 5173 gclog_or_tty->print_cr( 5174 "Finished remaining root initial mark scan work in %dth thread: %3.3f sec", 5175 worker_id, _timer.seconds()); 5176 } 5177 } 5178 5179 // Parallel remark task 5180 class CMSParRemarkTask: public CMSParMarkTask { 5181 CompactibleFreeListSpace* _cms_space; 5182 5183 // The per-thread work queues, available here for stealing. 5184 OopTaskQueueSet* _task_queues; 5185 ParallelTaskTerminator _term; 5186 5187 public: 5188 // A value of 0 passed to n_workers will cause the number of 5189 // workers to be taken from the active workers in the work gang. 5190 CMSParRemarkTask(CMSCollector* collector, 5191 CompactibleFreeListSpace* cms_space, 5192 int n_workers, FlexibleWorkGang* workers, 5193 OopTaskQueueSet* task_queues): 5194 CMSParMarkTask("Rescan roots and grey objects in parallel", 5195 collector, n_workers), 5196 _cms_space(cms_space), 5197 _task_queues(task_queues), 5198 _term(n_workers, task_queues) { } 5199 5200 OopTaskQueueSet* task_queues() { return _task_queues; } 5201 5202 OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); } 5203 5204 ParallelTaskTerminator* terminator() { return &_term; } 5205 int n_workers() { return _n_workers; } 5206 5207 void work(uint worker_id); 5208 5209 private: 5210 // ... of dirty cards in old space 5211 void do_dirty_card_rescan_tasks(CompactibleFreeListSpace* sp, int i, 5212 Par_MarkRefsIntoAndScanClosure* cl); 5213 5214 // ... work stealing for the above 5215 void do_work_steal(int i, Par_MarkRefsIntoAndScanClosure* cl, int* seed); 5216 }; 5217 5218 class RemarkKlassClosure : public KlassClosure { 5219 KlassToOopClosure _cm_klass_closure; 5220 public: 5221 RemarkKlassClosure(OopClosure* oop_closure) : _cm_klass_closure(oop_closure) {} 5222 void do_klass(Klass* k) { 5223 // Check if we have modified any oops in the Klass during the concurrent marking. 5224 if (k->has_accumulated_modified_oops()) { 5225 k->clear_accumulated_modified_oops(); 5226 5227 // We could have transfered the current modified marks to the accumulated marks, 5228 // like we do with the Card Table to Mod Union Table. But it's not really necessary. 5229 } else if (k->has_modified_oops()) { 5230 // Don't clear anything, this info is needed by the next young collection. 5231 } else { 5232 // No modified oops in the Klass. 5233 return; 5234 } 5235 5236 // The klass has modified fields, need to scan the klass. 5237 _cm_klass_closure.do_klass(k); 5238 } 5239 }; 5240 5241 void CMSParMarkTask::work_on_young_gen_roots(uint worker_id, OopsInGenClosure* cl) { 5242 DefNewGeneration* dng = _collector->_young_gen->as_DefNewGeneration(); 5243 EdenSpace* eden_space = dng->eden(); 5244 ContiguousSpace* from_space = dng->from(); 5245 ContiguousSpace* to_space = dng->to(); 5246 5247 HeapWord** eca = _collector->_eden_chunk_array; 5248 size_t ect = _collector->_eden_chunk_index; 5249 HeapWord** sca = _collector->_survivor_chunk_array; 5250 size_t sct = _collector->_survivor_chunk_index; 5251 5252 assert(ect <= _collector->_eden_chunk_capacity, "out of bounds"); 5253 assert(sct <= _collector->_survivor_chunk_capacity, "out of bounds"); 5254 5255 do_young_space_rescan(worker_id, cl, to_space, NULL, 0); 5256 do_young_space_rescan(worker_id, cl, from_space, sca, sct); 5257 do_young_space_rescan(worker_id, cl, eden_space, eca, ect); 5258 } 5259 5260 // work_queue(i) is passed to the closure 5261 // Par_MarkRefsIntoAndScanClosure. The "i" parameter 5262 // also is passed to do_dirty_card_rescan_tasks() and to 5263 // do_work_steal() to select the i-th task_queue. 5264 5265 void CMSParRemarkTask::work(uint worker_id) { 5266 elapsedTimer _timer; 5267 ResourceMark rm; 5268 HandleMark hm; 5269 5270 // ---------- rescan from roots -------------- 5271 _timer.start(); 5272 GenCollectedHeap* gch = GenCollectedHeap::heap(); 5273 Par_MarkRefsIntoAndScanClosure par_mrias_cl(_collector, 5274 _collector->_span, _collector->ref_processor(), 5275 &(_collector->_markBitMap), 5276 work_queue(worker_id)); 5277 5278 // Rescan young gen roots first since these are likely 5279 // coarsely partitioned and may, on that account, constitute 5280 // the critical path; thus, it's best to start off that 5281 // work first. 5282 // ---------- young gen roots -------------- 5283 { 5284 work_on_young_gen_roots(worker_id, &par_mrias_cl); 5285 _timer.stop(); 5286 if (PrintCMSStatistics != 0) { 5287 gclog_or_tty->print_cr( 5288 "Finished young gen rescan work in %dth thread: %3.3f sec", 5289 worker_id, _timer.seconds()); 5290 } 5291 } 5292 5293 // ---------- remaining roots -------------- 5294 _timer.reset(); 5295 _timer.start(); 5296 gch->gen_process_roots(_collector->_cmsGen->level(), 5297 false, // yg was scanned above 5298 false, // this is parallel code 5299 SharedHeap::ScanningOption(_collector->CMSCollector::roots_scanning_options()), 5300 _collector->should_unload_classes(), 5301 &par_mrias_cl, 5302 NULL, 5303 NULL); // The dirty klasses will be handled below 5304 5305 assert(_collector->should_unload_classes() 5306 || (_collector->CMSCollector::roots_scanning_options() & SharedHeap::SO_AllCodeCache), 5307 "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops"); 5308 _timer.stop(); 5309 if (PrintCMSStatistics != 0) { 5310 gclog_or_tty->print_cr( 5311 "Finished remaining root rescan work in %dth thread: %3.3f sec", 5312 worker_id, _timer.seconds()); 5313 } 5314 5315 // ---------- unhandled CLD scanning ---------- 5316 if (worker_id == 0) { // Single threaded at the moment. 5317 _timer.reset(); 5318 _timer.start(); 5319 5320 // Scan all new class loader data objects and new dependencies that were 5321 // introduced during concurrent marking. 5322 ResourceMark rm; 5323 GrowableArray<ClassLoaderData*>* array = ClassLoaderDataGraph::new_clds(); 5324 for (int i = 0; i < array->length(); i++) { 5325 par_mrias_cl.do_class_loader_data(array->at(i)); 5326 } 5327 5328 // We don't need to keep track of new CLDs anymore. 5329 ClassLoaderDataGraph::remember_new_clds(false); 5330 5331 _timer.stop(); 5332 if (PrintCMSStatistics != 0) { 5333 gclog_or_tty->print_cr( 5334 "Finished unhandled CLD scanning work in %dth thread: %3.3f sec", 5335 worker_id, _timer.seconds()); 5336 } 5337 } 5338 5339 // ---------- dirty klass scanning ---------- 5340 if (worker_id == 0) { // Single threaded at the moment. 5341 _timer.reset(); 5342 _timer.start(); 5343 5344 // Scan all classes that was dirtied during the concurrent marking phase. 5345 RemarkKlassClosure remark_klass_closure(&par_mrias_cl); 5346 ClassLoaderDataGraph::classes_do(&remark_klass_closure); 5347 5348 _timer.stop(); 5349 if (PrintCMSStatistics != 0) { 5350 gclog_or_tty->print_cr( 5351 "Finished dirty klass scanning work in %dth thread: %3.3f sec", 5352 worker_id, _timer.seconds()); 5353 } 5354 } 5355 5356 // We might have added oops to ClassLoaderData::_handles during the 5357 // concurrent marking phase. These oops point to newly allocated objects 5358 // that are guaranteed to be kept alive. Either by the direct allocation 5359 // code, or when the young collector processes the roots. Hence, 5360 // we don't have to revisit the _handles block during the remark phase. 5361 5362 // ---------- rescan dirty cards ------------ 5363 _timer.reset(); 5364 _timer.start(); 5365 5366 // Do the rescan tasks for each of the two spaces 5367 // (cms_space) in turn. 5368 // "worker_id" is passed to select the task_queue for "worker_id" 5369 do_dirty_card_rescan_tasks(_cms_space, worker_id, &par_mrias_cl); 5370 _timer.stop(); 5371 if (PrintCMSStatistics != 0) { 5372 gclog_or_tty->print_cr( 5373 "Finished dirty card rescan work in %dth thread: %3.3f sec", 5374 worker_id, _timer.seconds()); 5375 } 5376 5377 // ---------- steal work from other threads ... 5378 // ---------- ... and drain overflow list. 5379 _timer.reset(); 5380 _timer.start(); 5381 do_work_steal(worker_id, &par_mrias_cl, _collector->hash_seed(worker_id)); 5382 _timer.stop(); 5383 if (PrintCMSStatistics != 0) { 5384 gclog_or_tty->print_cr( 5385 "Finished work stealing in %dth thread: %3.3f sec", 5386 worker_id, _timer.seconds()); 5387 } 5388 } 5389 5390 // Note that parameter "i" is not used. 5391 void 5392 CMSParMarkTask::do_young_space_rescan(uint worker_id, 5393 OopsInGenClosure* cl, ContiguousSpace* space, 5394 HeapWord** chunk_array, size_t chunk_top) { 5395 // Until all tasks completed: 5396 // . claim an unclaimed task 5397 // . compute region boundaries corresponding to task claimed 5398 // using chunk_array 5399 // . par_oop_iterate(cl) over that region 5400 5401 ResourceMark rm; 5402 HandleMark hm; 5403 5404 SequentialSubTasksDone* pst = space->par_seq_tasks(); 5405 5406 uint nth_task = 0; 5407 uint n_tasks = pst->n_tasks(); 5408 5409 if (n_tasks > 0) { 5410 assert(pst->valid(), "Uninitialized use?"); 5411 HeapWord *start, *end; 5412 while (!pst->is_task_claimed(/* reference */ nth_task)) { 5413 // We claimed task # nth_task; compute its boundaries. 5414 if (chunk_top == 0) { // no samples were taken 5415 assert(nth_task == 0 && n_tasks == 1, "Can have only 1 EdenSpace task"); 5416 start = space->bottom(); 5417 end = space->top(); 5418 } else if (nth_task == 0) { 5419 start = space->bottom(); 5420 end = chunk_array[nth_task]; 5421 } else if (nth_task < (uint)chunk_top) { 5422 assert(nth_task >= 1, "Control point invariant"); 5423 start = chunk_array[nth_task - 1]; 5424 end = chunk_array[nth_task]; 5425 } else { 5426 assert(nth_task == (uint)chunk_top, "Control point invariant"); 5427 start = chunk_array[chunk_top - 1]; 5428 end = space->top(); 5429 } 5430 MemRegion mr(start, end); 5431 // Verify that mr is in space 5432 assert(mr.is_empty() || space->used_region().contains(mr), 5433 "Should be in space"); 5434 // Verify that "start" is an object boundary 5435 assert(mr.is_empty() || oop(mr.start())->is_oop(), 5436 "Should be an oop"); 5437 space->par_oop_iterate(mr, cl); 5438 } 5439 pst->all_tasks_completed(); 5440 } 5441 } 5442 5443 void 5444 CMSParRemarkTask::do_dirty_card_rescan_tasks( 5445 CompactibleFreeListSpace* sp, int i, 5446 Par_MarkRefsIntoAndScanClosure* cl) { 5447 // Until all tasks completed: 5448 // . claim an unclaimed task 5449 // . compute region boundaries corresponding to task claimed 5450 // . transfer dirty bits ct->mut for that region 5451 // . apply rescanclosure to dirty mut bits for that region 5452 5453 ResourceMark rm; 5454 HandleMark hm; 5455 5456 OopTaskQueue* work_q = work_queue(i); 5457 ModUnionClosure modUnionClosure(&(_collector->_modUnionTable)); 5458 // CAUTION! CAUTION! CAUTION! CAUTION! CAUTION! CAUTION! CAUTION! 5459 // CAUTION: This closure has state that persists across calls to 5460 // the work method dirty_range_iterate_clear() in that it has 5461 // embedded in it a (subtype of) UpwardsObjectClosure. The 5462 // use of that state in the embedded UpwardsObjectClosure instance 5463 // assumes that the cards are always iterated (even if in parallel 5464 // by several threads) in monotonically increasing order per each 5465 // thread. This is true of the implementation below which picks 5466 // card ranges (chunks) in monotonically increasing order globally 5467 // and, a-fortiori, in monotonically increasing order per thread 5468 // (the latter order being a subsequence of the former). 5469 // If the work code below is ever reorganized into a more chaotic 5470 // work-partitioning form than the current "sequential tasks" 5471 // paradigm, the use of that persistent state will have to be 5472 // revisited and modified appropriately. See also related 5473 // bug 4756801 work on which should examine this code to make 5474 // sure that the changes there do not run counter to the 5475 // assumptions made here and necessary for correctness and 5476 // efficiency. Note also that this code might yield inefficient 5477 // behavior in the case of very large objects that span one or 5478 // more work chunks. Such objects would potentially be scanned 5479 // several times redundantly. Work on 4756801 should try and 5480 // address that performance anomaly if at all possible. XXX 5481 MemRegion full_span = _collector->_span; 5482 CMSBitMap* bm = &(_collector->_markBitMap); // shared 5483 MarkFromDirtyCardsClosure 5484 greyRescanClosure(_collector, full_span, // entire span of interest 5485 sp, bm, work_q, cl); 5486 5487 SequentialSubTasksDone* pst = sp->conc_par_seq_tasks(); 5488 assert(pst->valid(), "Uninitialized use?"); 5489 uint nth_task = 0; 5490 const int alignment = CardTableModRefBS::card_size * BitsPerWord; 5491 MemRegion span = sp->used_region(); 5492 HeapWord* start_addr = span.start(); 5493 HeapWord* end_addr = (HeapWord*)round_to((intptr_t)span.end(), 5494 alignment); 5495 const size_t chunk_size = sp->rescan_task_size(); // in HeapWord units 5496 assert((HeapWord*)round_to((intptr_t)start_addr, alignment) == 5497 start_addr, "Check alignment"); 5498 assert((size_t)round_to((intptr_t)chunk_size, alignment) == 5499 chunk_size, "Check alignment"); 5500 5501 while (!pst->is_task_claimed(/* reference */ nth_task)) { 5502 // Having claimed the nth_task, compute corresponding mem-region, 5503 // which is a-fortiori aligned correctly (i.e. at a MUT boundary). 5504 // The alignment restriction ensures that we do not need any 5505 // synchronization with other gang-workers while setting or 5506 // clearing bits in thus chunk of the MUT. 5507 MemRegion this_span = MemRegion(start_addr + nth_task*chunk_size, 5508 start_addr + (nth_task+1)*chunk_size); 5509 // The last chunk's end might be way beyond end of the 5510 // used region. In that case pull back appropriately. 5511 if (this_span.end() > end_addr) { 5512 this_span.set_end(end_addr); 5513 assert(!this_span.is_empty(), "Program logic (calculation of n_tasks)"); 5514 } 5515 // Iterate over the dirty cards covering this chunk, marking them 5516 // precleaned, and setting the corresponding bits in the mod union 5517 // table. Since we have been careful to partition at Card and MUT-word 5518 // boundaries no synchronization is needed between parallel threads. 5519 _collector->_ct->ct_bs()->dirty_card_iterate(this_span, 5520 &modUnionClosure); 5521 5522 // Having transferred these marks into the modUnionTable, 5523 // rescan the marked objects on the dirty cards in the modUnionTable. 5524 // Even if this is at a synchronous collection, the initial marking 5525 // may have been done during an asynchronous collection so there 5526 // may be dirty bits in the mod-union table. 5527 _collector->_modUnionTable.dirty_range_iterate_clear( 5528 this_span, &greyRescanClosure); 5529 _collector->_modUnionTable.verifyNoOneBitsInRange( 5530 this_span.start(), 5531 this_span.end()); 5532 } 5533 pst->all_tasks_completed(); // declare that i am done 5534 } 5535 5536 // . see if we can share work_queues with ParNew? XXX 5537 void 5538 CMSParRemarkTask::do_work_steal(int i, Par_MarkRefsIntoAndScanClosure* cl, 5539 int* seed) { 5540 OopTaskQueue* work_q = work_queue(i); 5541 NOT_PRODUCT(int num_steals = 0;) 5542 oop obj_to_scan; 5543 CMSBitMap* bm = &(_collector->_markBitMap); 5544 5545 while (true) { 5546 // Completely finish any left over work from (an) earlier round(s) 5547 cl->trim_queue(0); 5548 size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4, 5549 (size_t)ParGCDesiredObjsFromOverflowList); 5550 // Now check if there's any work in the overflow list 5551 // Passing ParallelGCThreads as the third parameter, no_of_gc_threads, 5552 // only affects the number of attempts made to get work from the 5553 // overflow list and does not affect the number of workers. Just 5554 // pass ParallelGCThreads so this behavior is unchanged. 5555 if (_collector->par_take_from_overflow_list(num_from_overflow_list, 5556 work_q, 5557 ParallelGCThreads)) { 5558 // found something in global overflow list; 5559 // not yet ready to go stealing work from others. 5560 // We'd like to assert(work_q->size() != 0, ...) 5561 // because we just took work from the overflow list, 5562 // but of course we can't since all of that could have 5563 // been already stolen from us. 5564 // "He giveth and He taketh away." 5565 continue; 5566 } 5567 // Verify that we have no work before we resort to stealing 5568 assert(work_q->size() == 0, "Have work, shouldn't steal"); 5569 // Try to steal from other queues that have work 5570 if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) { 5571 NOT_PRODUCT(num_steals++;) 5572 assert(obj_to_scan->is_oop(), "Oops, not an oop!"); 5573 assert(bm->isMarked((HeapWord*)obj_to_scan), "Stole an unmarked oop?"); 5574 // Do scanning work 5575 obj_to_scan->oop_iterate(cl); 5576 // Loop around, finish this work, and try to steal some more 5577 } else if (terminator()->offer_termination()) { 5578 break; // nirvana from the infinite cycle 5579 } 5580 } 5581 NOT_PRODUCT( 5582 if (PrintCMSStatistics != 0) { 5583 gclog_or_tty->print("\n\t(%d: stole %d oops)", i, num_steals); 5584 } 5585 ) 5586 assert(work_q->size() == 0 && _collector->overflow_list_is_empty(), 5587 "Else our work is not yet done"); 5588 } 5589 5590 // Record object boundaries in _eden_chunk_array by sampling the eden 5591 // top in the slow-path eden object allocation code path and record 5592 // the boundaries, if CMSEdenChunksRecordAlways is true. If 5593 // CMSEdenChunksRecordAlways is false, we use the other asynchronous 5594 // sampling in sample_eden() that activates during the part of the 5595 // preclean phase. 5596 void CMSCollector::sample_eden_chunk() { 5597 if (CMSEdenChunksRecordAlways && _eden_chunk_array != NULL) { 5598 if (_eden_chunk_lock->try_lock()) { 5599 // Record a sample. This is the critical section. The contents 5600 // of the _eden_chunk_array have to be non-decreasing in the 5601 // address order. 5602 _eden_chunk_array[_eden_chunk_index] = *_top_addr; 5603 assert(_eden_chunk_array[_eden_chunk_index] <= *_end_addr, 5604 "Unexpected state of Eden"); 5605 if (_eden_chunk_index == 0 || 5606 ((_eden_chunk_array[_eden_chunk_index] > _eden_chunk_array[_eden_chunk_index-1]) && 5607 (pointer_delta(_eden_chunk_array[_eden_chunk_index], 5608 _eden_chunk_array[_eden_chunk_index-1]) >= CMSSamplingGrain))) { 5609 _eden_chunk_index++; // commit sample 5610 } 5611 _eden_chunk_lock->unlock(); 5612 } 5613 } 5614 } 5615 5616 // Return a thread-local PLAB recording array, as appropriate. 5617 void* CMSCollector::get_data_recorder(int thr_num) { 5618 if (_survivor_plab_array != NULL && 5619 (CMSPLABRecordAlways || 5620 (_collectorState > Marking && _collectorState < FinalMarking))) { 5621 assert(thr_num < (int)ParallelGCThreads, "thr_num is out of bounds"); 5622 ChunkArray* ca = &_survivor_plab_array[thr_num]; 5623 ca->reset(); // clear it so that fresh data is recorded 5624 return (void*) ca; 5625 } else { 5626 return NULL; 5627 } 5628 } 5629 5630 // Reset all the thread-local PLAB recording arrays 5631 void CMSCollector::reset_survivor_plab_arrays() { 5632 for (uint i = 0; i < ParallelGCThreads; i++) { 5633 _survivor_plab_array[i].reset(); 5634 } 5635 } 5636 5637 // Merge the per-thread plab arrays into the global survivor chunk 5638 // array which will provide the partitioning of the survivor space 5639 // for CMS initial scan and rescan. 5640 void CMSCollector::merge_survivor_plab_arrays(ContiguousSpace* surv, 5641 int no_of_gc_threads) { 5642 assert(_survivor_plab_array != NULL, "Error"); 5643 assert(_survivor_chunk_array != NULL, "Error"); 5644 assert(_collectorState == FinalMarking || 5645 (CMSParallelInitialMarkEnabled && _collectorState == InitialMarking), "Error"); 5646 for (int j = 0; j < no_of_gc_threads; j++) { 5647 _cursor[j] = 0; 5648 } 5649 HeapWord* top = surv->top(); 5650 size_t i; 5651 for (i = 0; i < _survivor_chunk_capacity; i++) { // all sca entries 5652 HeapWord* min_val = top; // Higher than any PLAB address 5653 uint min_tid = 0; // position of min_val this round 5654 for (int j = 0; j < no_of_gc_threads; j++) { 5655 ChunkArray* cur_sca = &_survivor_plab_array[j]; 5656 if (_cursor[j] == cur_sca->end()) { 5657 continue; 5658 } 5659 assert(_cursor[j] < cur_sca->end(), "ctl pt invariant"); 5660 HeapWord* cur_val = cur_sca->nth(_cursor[j]); 5661 assert(surv->used_region().contains(cur_val), "Out of bounds value"); 5662 if (cur_val < min_val) { 5663 min_tid = j; 5664 min_val = cur_val; 5665 } else { 5666 assert(cur_val < top, "All recorded addresses should be less"); 5667 } 5668 } 5669 // At this point min_val and min_tid are respectively 5670 // the least address in _survivor_plab_array[j]->nth(_cursor[j]) 5671 // and the thread (j) that witnesses that address. 5672 // We record this address in the _survivor_chunk_array[i] 5673 // and increment _cursor[min_tid] prior to the next round i. 5674 if (min_val == top) { 5675 break; 5676 } 5677 _survivor_chunk_array[i] = min_val; 5678 _cursor[min_tid]++; 5679 } 5680 // We are all done; record the size of the _survivor_chunk_array 5681 _survivor_chunk_index = i; // exclusive: [0, i) 5682 if (PrintCMSStatistics > 0) { 5683 gclog_or_tty->print(" (Survivor:" SIZE_FORMAT "chunks) ", i); 5684 } 5685 // Verify that we used up all the recorded entries 5686 #ifdef ASSERT 5687 size_t total = 0; 5688 for (int j = 0; j < no_of_gc_threads; j++) { 5689 assert(_cursor[j] == _survivor_plab_array[j].end(), "Ctl pt invariant"); 5690 total += _cursor[j]; 5691 } 5692 assert(total == _survivor_chunk_index, "Ctl Pt Invariant"); 5693 // Check that the merged array is in sorted order 5694 if (total > 0) { 5695 for (size_t i = 0; i < total - 1; i++) { 5696 if (PrintCMSStatistics > 0) { 5697 gclog_or_tty->print(" (chunk" SIZE_FORMAT ":" INTPTR_FORMAT ") ", 5698 i, _survivor_chunk_array[i]); 5699 } 5700 assert(_survivor_chunk_array[i] < _survivor_chunk_array[i+1], 5701 "Not sorted"); 5702 } 5703 } 5704 #endif // ASSERT 5705 } 5706 5707 // Set up the space's par_seq_tasks structure for work claiming 5708 // for parallel initial scan and rescan of young gen. 5709 // See ParRescanTask where this is currently used. 5710 void 5711 CMSCollector:: 5712 initialize_sequential_subtasks_for_young_gen_rescan(int n_threads) { 5713 assert(n_threads > 0, "Unexpected n_threads argument"); 5714 DefNewGeneration* dng = (DefNewGeneration*)_young_gen; 5715 5716 // Eden space 5717 if (!dng->eden()->is_empty()) { 5718 SequentialSubTasksDone* pst = dng->eden()->par_seq_tasks(); 5719 assert(!pst->valid(), "Clobbering existing data?"); 5720 // Each valid entry in [0, _eden_chunk_index) represents a task. 5721 size_t n_tasks = _eden_chunk_index + 1; 5722 assert(n_tasks == 1 || _eden_chunk_array != NULL, "Error"); 5723 // Sets the condition for completion of the subtask (how many threads 5724 // need to finish in order to be done). 5725 pst->set_n_threads(n_threads); 5726 pst->set_n_tasks((int)n_tasks); 5727 } 5728 5729 // Merge the survivor plab arrays into _survivor_chunk_array 5730 if (_survivor_plab_array != NULL) { 5731 merge_survivor_plab_arrays(dng->from(), n_threads); 5732 } else { 5733 assert(_survivor_chunk_index == 0, "Error"); 5734 } 5735 5736 // To space 5737 { 5738 SequentialSubTasksDone* pst = dng->to()->par_seq_tasks(); 5739 assert(!pst->valid(), "Clobbering existing data?"); 5740 // Sets the condition for completion of the subtask (how many threads 5741 // need to finish in order to be done). 5742 pst->set_n_threads(n_threads); 5743 pst->set_n_tasks(1); 5744 assert(pst->valid(), "Error"); 5745 } 5746 5747 // From space 5748 { 5749 SequentialSubTasksDone* pst = dng->from()->par_seq_tasks(); 5750 assert(!pst->valid(), "Clobbering existing data?"); 5751 size_t n_tasks = _survivor_chunk_index + 1; 5752 assert(n_tasks == 1 || _survivor_chunk_array != NULL, "Error"); 5753 // Sets the condition for completion of the subtask (how many threads 5754 // need to finish in order to be done). 5755 pst->set_n_threads(n_threads); 5756 pst->set_n_tasks((int)n_tasks); 5757 assert(pst->valid(), "Error"); 5758 } 5759 } 5760 5761 // Parallel version of remark 5762 void CMSCollector::do_remark_parallel() { 5763 GenCollectedHeap* gch = GenCollectedHeap::heap(); 5764 FlexibleWorkGang* workers = gch->workers(); 5765 assert(workers != NULL, "Need parallel worker threads."); 5766 // Choose to use the number of GC workers most recently set 5767 // into "active_workers". If active_workers is not set, set it 5768 // to ParallelGCThreads. 5769 int n_workers = workers->active_workers(); 5770 if (n_workers == 0) { 5771 assert(n_workers > 0, "Should have been set during scavenge"); 5772 n_workers = ParallelGCThreads; 5773 workers->set_active_workers(n_workers); 5774 } 5775 CompactibleFreeListSpace* cms_space = _cmsGen->cmsSpace(); 5776 5777 CMSParRemarkTask tsk(this, 5778 cms_space, 5779 n_workers, workers, task_queues()); 5780 5781 // Set up for parallel process_roots work. 5782 gch->set_par_threads(n_workers); 5783 // We won't be iterating over the cards in the card table updating 5784 // the younger_gen cards, so we shouldn't call the following else 5785 // the verification code as well as subsequent younger_refs_iterate 5786 // code would get confused. XXX 5787 // gch->rem_set()->prepare_for_younger_refs_iterate(true); // parallel 5788 5789 // The young gen rescan work will not be done as part of 5790 // process_roots (which currently doesn't know how to 5791 // parallelize such a scan), but rather will be broken up into 5792 // a set of parallel tasks (via the sampling that the [abortable] 5793 // preclean phase did of EdenSpace, plus the [two] tasks of 5794 // scanning the [two] survivor spaces. Further fine-grain 5795 // parallelization of the scanning of the survivor spaces 5796 // themselves, and of precleaning of the younger gen itself 5797 // is deferred to the future. 5798 initialize_sequential_subtasks_for_young_gen_rescan(n_workers); 5799 5800 // The dirty card rescan work is broken up into a "sequence" 5801 // of parallel tasks (per constituent space) that are dynamically 5802 // claimed by the parallel threads. 5803 cms_space->initialize_sequential_subtasks_for_rescan(n_workers); 5804 5805 // It turns out that even when we're using 1 thread, doing the work in a 5806 // separate thread causes wide variance in run times. We can't help this 5807 // in the multi-threaded case, but we special-case n=1 here to get 5808 // repeatable measurements of the 1-thread overhead of the parallel code. 5809 if (n_workers > 1) { 5810 // Make refs discovery MT-safe, if it isn't already: it may not 5811 // necessarily be so, since it's possible that we are doing 5812 // ST marking. 5813 ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), true); 5814 GenCollectedHeap::StrongRootsScope srs(gch); 5815 workers->run_task(&tsk); 5816 } else { 5817 ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), false); 5818 GenCollectedHeap::StrongRootsScope srs(gch); 5819 tsk.work(0); 5820 } 5821 5822 gch->set_par_threads(0); // 0 ==> non-parallel. 5823 // restore, single-threaded for now, any preserved marks 5824 // as a result of work_q overflow 5825 restore_preserved_marks_if_any(); 5826 } 5827 5828 // Non-parallel version of remark 5829 void CMSCollector::do_remark_non_parallel() { 5830 ResourceMark rm; 5831 HandleMark hm; 5832 GenCollectedHeap* gch = GenCollectedHeap::heap(); 5833 ReferenceProcessorMTDiscoveryMutator mt(ref_processor(), false); 5834 5835 MarkRefsIntoAndScanClosure 5836 mrias_cl(_span, ref_processor(), &_markBitMap, NULL /* not precleaning */, 5837 &_markStack, this, 5838 false /* should_yield */, false /* not precleaning */); 5839 MarkFromDirtyCardsClosure 5840 markFromDirtyCardsClosure(this, _span, 5841 NULL, // space is set further below 5842 &_markBitMap, &_markStack, &mrias_cl); 5843 { 5844 GCTraceTime t("grey object rescan", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 5845 // Iterate over the dirty cards, setting the corresponding bits in the 5846 // mod union table. 5847 { 5848 ModUnionClosure modUnionClosure(&_modUnionTable); 5849 _ct->ct_bs()->dirty_card_iterate( 5850 _cmsGen->used_region(), 5851 &modUnionClosure); 5852 } 5853 // Having transferred these marks into the modUnionTable, we just need 5854 // to rescan the marked objects on the dirty cards in the modUnionTable. 5855 // The initial marking may have been done during an asynchronous 5856 // collection so there may be dirty bits in the mod-union table. 5857 const int alignment = 5858 CardTableModRefBS::card_size * BitsPerWord; 5859 { 5860 // ... First handle dirty cards in CMS gen 5861 markFromDirtyCardsClosure.set_space(_cmsGen->cmsSpace()); 5862 MemRegion ur = _cmsGen->used_region(); 5863 HeapWord* lb = ur.start(); 5864 HeapWord* ub = (HeapWord*)round_to((intptr_t)ur.end(), alignment); 5865 MemRegion cms_span(lb, ub); 5866 _modUnionTable.dirty_range_iterate_clear(cms_span, 5867 &markFromDirtyCardsClosure); 5868 verify_work_stacks_empty(); 5869 if (PrintCMSStatistics != 0) { 5870 gclog_or_tty->print(" (re-scanned "SIZE_FORMAT" dirty cards in cms gen) ", 5871 markFromDirtyCardsClosure.num_dirty_cards()); 5872 } 5873 } 5874 } 5875 if (VerifyDuringGC && 5876 GenCollectedHeap::heap()->total_collections() >= VerifyGCStartAt) { 5877 HandleMark hm; // Discard invalid handles created during verification 5878 Universe::verify(); 5879 } 5880 { 5881 GCTraceTime t("root rescan", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 5882 5883 verify_work_stacks_empty(); 5884 5885 gch->rem_set()->prepare_for_younger_refs_iterate(false); // Not parallel. 5886 GenCollectedHeap::StrongRootsScope srs(gch); 5887 5888 gch->gen_process_roots(_cmsGen->level(), 5889 true, // younger gens as roots 5890 false, // use the local StrongRootsScope 5891 SharedHeap::ScanningOption(roots_scanning_options()), 5892 should_unload_classes(), 5893 &mrias_cl, 5894 NULL, 5895 NULL); // The dirty klasses will be handled below 5896 5897 assert(should_unload_classes() 5898 || (roots_scanning_options() & SharedHeap::SO_AllCodeCache), 5899 "if we didn't scan the code cache, we have to be ready to drop nmethods with expired weak oops"); 5900 } 5901 5902 { 5903 GCTraceTime t("visit unhandled CLDs", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 5904 5905 verify_work_stacks_empty(); 5906 5907 // Scan all class loader data objects that might have been introduced 5908 // during concurrent marking. 5909 ResourceMark rm; 5910 GrowableArray<ClassLoaderData*>* array = ClassLoaderDataGraph::new_clds(); 5911 for (int i = 0; i < array->length(); i++) { 5912 mrias_cl.do_class_loader_data(array->at(i)); 5913 } 5914 5915 // We don't need to keep track of new CLDs anymore. 5916 ClassLoaderDataGraph::remember_new_clds(false); 5917 5918 verify_work_stacks_empty(); 5919 } 5920 5921 { 5922 GCTraceTime t("dirty klass scan", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 5923 5924 verify_work_stacks_empty(); 5925 5926 RemarkKlassClosure remark_klass_closure(&mrias_cl); 5927 ClassLoaderDataGraph::classes_do(&remark_klass_closure); 5928 5929 verify_work_stacks_empty(); 5930 } 5931 5932 // We might have added oops to ClassLoaderData::_handles during the 5933 // concurrent marking phase. These oops point to newly allocated objects 5934 // that are guaranteed to be kept alive. Either by the direct allocation 5935 // code, or when the young collector processes the roots. Hence, 5936 // we don't have to revisit the _handles block during the remark phase. 5937 5938 verify_work_stacks_empty(); 5939 // Restore evacuated mark words, if any, used for overflow list links 5940 if (!CMSOverflowEarlyRestoration) { 5941 restore_preserved_marks_if_any(); 5942 } 5943 verify_overflow_empty(); 5944 } 5945 5946 //////////////////////////////////////////////////////// 5947 // Parallel Reference Processing Task Proxy Class 5948 //////////////////////////////////////////////////////// 5949 class CMSRefProcTaskProxy: public AbstractGangTaskWOopQueues { 5950 typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask; 5951 CMSCollector* _collector; 5952 CMSBitMap* _mark_bit_map; 5953 const MemRegion _span; 5954 ProcessTask& _task; 5955 5956 public: 5957 CMSRefProcTaskProxy(ProcessTask& task, 5958 CMSCollector* collector, 5959 const MemRegion& span, 5960 CMSBitMap* mark_bit_map, 5961 AbstractWorkGang* workers, 5962 OopTaskQueueSet* task_queues): 5963 // XXX Should superclass AGTWOQ also know about AWG since it knows 5964 // about the task_queues used by the AWG? Then it could initialize 5965 // the terminator() object. See 6984287. The set_for_termination() 5966 // below is a temporary band-aid for the regression in 6984287. 5967 AbstractGangTaskWOopQueues("Process referents by policy in parallel", 5968 task_queues), 5969 _task(task), 5970 _collector(collector), _span(span), _mark_bit_map(mark_bit_map) 5971 { 5972 assert(_collector->_span.equals(_span) && !_span.is_empty(), 5973 "Inconsistency in _span"); 5974 set_for_termination(workers->active_workers()); 5975 } 5976 5977 OopTaskQueueSet* task_queues() { return queues(); } 5978 5979 OopTaskQueue* work_queue(int i) { return task_queues()->queue(i); } 5980 5981 void do_work_steal(int i, 5982 CMSParDrainMarkingStackClosure* drain, 5983 CMSParKeepAliveClosure* keep_alive, 5984 int* seed); 5985 5986 virtual void work(uint worker_id); 5987 }; 5988 5989 void CMSRefProcTaskProxy::work(uint worker_id) { 5990 assert(_collector->_span.equals(_span), "Inconsistency in _span"); 5991 CMSParKeepAliveClosure par_keep_alive(_collector, _span, 5992 _mark_bit_map, 5993 work_queue(worker_id)); 5994 CMSParDrainMarkingStackClosure par_drain_stack(_collector, _span, 5995 _mark_bit_map, 5996 work_queue(worker_id)); 5997 CMSIsAliveClosure is_alive_closure(_span, _mark_bit_map); 5998 _task.work(worker_id, is_alive_closure, par_keep_alive, par_drain_stack); 5999 if (_task.marks_oops_alive()) { 6000 do_work_steal(worker_id, &par_drain_stack, &par_keep_alive, 6001 _collector->hash_seed(worker_id)); 6002 } 6003 assert(work_queue(worker_id)->size() == 0, "work_queue should be empty"); 6004 assert(_collector->_overflow_list == NULL, "non-empty _overflow_list"); 6005 } 6006 6007 class CMSRefEnqueueTaskProxy: public AbstractGangTask { 6008 typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask; 6009 EnqueueTask& _task; 6010 6011 public: 6012 CMSRefEnqueueTaskProxy(EnqueueTask& task) 6013 : AbstractGangTask("Enqueue reference objects in parallel"), 6014 _task(task) 6015 { } 6016 6017 virtual void work(uint worker_id) 6018 { 6019 _task.work(worker_id); 6020 } 6021 }; 6022 6023 CMSParKeepAliveClosure::CMSParKeepAliveClosure(CMSCollector* collector, 6024 MemRegion span, CMSBitMap* bit_map, OopTaskQueue* work_queue): 6025 _span(span), 6026 _bit_map(bit_map), 6027 _work_queue(work_queue), 6028 _mark_and_push(collector, span, bit_map, work_queue), 6029 _low_water_mark(MIN2((uint)(work_queue->max_elems()/4), 6030 (uint)(CMSWorkQueueDrainThreshold * ParallelGCThreads))) 6031 { } 6032 6033 // . see if we can share work_queues with ParNew? XXX 6034 void CMSRefProcTaskProxy::do_work_steal(int i, 6035 CMSParDrainMarkingStackClosure* drain, 6036 CMSParKeepAliveClosure* keep_alive, 6037 int* seed) { 6038 OopTaskQueue* work_q = work_queue(i); 6039 NOT_PRODUCT(int num_steals = 0;) 6040 oop obj_to_scan; 6041 6042 while (true) { 6043 // Completely finish any left over work from (an) earlier round(s) 6044 drain->trim_queue(0); 6045 size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4, 6046 (size_t)ParGCDesiredObjsFromOverflowList); 6047 // Now check if there's any work in the overflow list 6048 // Passing ParallelGCThreads as the third parameter, no_of_gc_threads, 6049 // only affects the number of attempts made to get work from the 6050 // overflow list and does not affect the number of workers. Just 6051 // pass ParallelGCThreads so this behavior is unchanged. 6052 if (_collector->par_take_from_overflow_list(num_from_overflow_list, 6053 work_q, 6054 ParallelGCThreads)) { 6055 // Found something in global overflow list; 6056 // not yet ready to go stealing work from others. 6057 // We'd like to assert(work_q->size() != 0, ...) 6058 // because we just took work from the overflow list, 6059 // but of course we can't, since all of that might have 6060 // been already stolen from us. 6061 continue; 6062 } 6063 // Verify that we have no work before we resort to stealing 6064 assert(work_q->size() == 0, "Have work, shouldn't steal"); 6065 // Try to steal from other queues that have work 6066 if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) { 6067 NOT_PRODUCT(num_steals++;) 6068 assert(obj_to_scan->is_oop(), "Oops, not an oop!"); 6069 assert(_mark_bit_map->isMarked((HeapWord*)obj_to_scan), "Stole an unmarked oop?"); 6070 // Do scanning work 6071 obj_to_scan->oop_iterate(keep_alive); 6072 // Loop around, finish this work, and try to steal some more 6073 } else if (terminator()->offer_termination()) { 6074 break; // nirvana from the infinite cycle 6075 } 6076 } 6077 NOT_PRODUCT( 6078 if (PrintCMSStatistics != 0) { 6079 gclog_or_tty->print("\n\t(%d: stole %d oops)", i, num_steals); 6080 } 6081 ) 6082 } 6083 6084 void CMSRefProcTaskExecutor::execute(ProcessTask& task) 6085 { 6086 GenCollectedHeap* gch = GenCollectedHeap::heap(); 6087 FlexibleWorkGang* workers = gch->workers(); 6088 assert(workers != NULL, "Need parallel worker threads."); 6089 CMSRefProcTaskProxy rp_task(task, &_collector, 6090 _collector.ref_processor()->span(), 6091 _collector.markBitMap(), 6092 workers, _collector.task_queues()); 6093 workers->run_task(&rp_task); 6094 } 6095 6096 void CMSRefProcTaskExecutor::execute(EnqueueTask& task) 6097 { 6098 6099 GenCollectedHeap* gch = GenCollectedHeap::heap(); 6100 FlexibleWorkGang* workers = gch->workers(); 6101 assert(workers != NULL, "Need parallel worker threads."); 6102 CMSRefEnqueueTaskProxy enq_task(task); 6103 workers->run_task(&enq_task); 6104 } 6105 6106 void CMSCollector::refProcessingWork(bool asynch, bool clear_all_soft_refs) { 6107 6108 ResourceMark rm; 6109 HandleMark hm; 6110 6111 ReferenceProcessor* rp = ref_processor(); 6112 assert(rp->span().equals(_span), "Spans should be equal"); 6113 assert(!rp->enqueuing_is_done(), "Enqueuing should not be complete"); 6114 // Process weak references. 6115 rp->setup_policy(clear_all_soft_refs); 6116 verify_work_stacks_empty(); 6117 6118 CMSKeepAliveClosure cmsKeepAliveClosure(this, _span, &_markBitMap, 6119 &_markStack, false /* !preclean */); 6120 CMSDrainMarkingStackClosure cmsDrainMarkingStackClosure(this, 6121 _span, &_markBitMap, &_markStack, 6122 &cmsKeepAliveClosure, false /* !preclean */); 6123 { 6124 GCTraceTime t("weak refs processing", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 6125 6126 ReferenceProcessorStats stats; 6127 if (rp->processing_is_mt()) { 6128 // Set the degree of MT here. If the discovery is done MT, there 6129 // may have been a different number of threads doing the discovery 6130 // and a different number of discovered lists may have Ref objects. 6131 // That is OK as long as the Reference lists are balanced (see 6132 // balance_all_queues() and balance_queues()). 6133 GenCollectedHeap* gch = GenCollectedHeap::heap(); 6134 int active_workers = ParallelGCThreads; 6135 FlexibleWorkGang* workers = gch->workers(); 6136 if (workers != NULL) { 6137 active_workers = workers->active_workers(); 6138 // The expectation is that active_workers will have already 6139 // been set to a reasonable value. If it has not been set, 6140 // investigate. 6141 assert(active_workers > 0, "Should have been set during scavenge"); 6142 } 6143 rp->set_active_mt_degree(active_workers); 6144 CMSRefProcTaskExecutor task_executor(*this); 6145 stats = rp->process_discovered_references(&_is_alive_closure, 6146 &cmsKeepAliveClosure, 6147 &cmsDrainMarkingStackClosure, 6148 &task_executor, 6149 _gc_timer_cm, 6150 _gc_tracer_cm->gc_id()); 6151 } else { 6152 stats = rp->process_discovered_references(&_is_alive_closure, 6153 &cmsKeepAliveClosure, 6154 &cmsDrainMarkingStackClosure, 6155 NULL, 6156 _gc_timer_cm, 6157 _gc_tracer_cm->gc_id()); 6158 } 6159 _gc_tracer_cm->report_gc_reference_stats(stats); 6160 6161 } 6162 6163 // This is the point where the entire marking should have completed. 6164 verify_work_stacks_empty(); 6165 6166 if (should_unload_classes()) { 6167 { 6168 GCTraceTime t("class unloading", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 6169 6170 // Unload classes and purge the SystemDictionary. 6171 bool purged_class = SystemDictionary::do_unloading(&_is_alive_closure); 6172 6173 // Unload nmethods. 6174 CodeCache::do_unloading(&_is_alive_closure, purged_class); 6175 6176 // Prune dead klasses from subklass/sibling/implementor lists. 6177 Klass::clean_weak_klass_links(&_is_alive_closure); 6178 } 6179 6180 { 6181 GCTraceTime t("scrub symbol table", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 6182 // Clean up unreferenced symbols in symbol table. 6183 SymbolTable::unlink(); 6184 } 6185 6186 { 6187 GCTraceTime t("scrub string table", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 6188 // Delete entries for dead interned strings. 6189 StringTable::unlink(&_is_alive_closure); 6190 } 6191 } 6192 6193 6194 // Restore any preserved marks as a result of mark stack or 6195 // work queue overflow 6196 restore_preserved_marks_if_any(); // done single-threaded for now 6197 6198 rp->set_enqueuing_is_done(true); 6199 if (rp->processing_is_mt()) { 6200 rp->balance_all_queues(); 6201 CMSRefProcTaskExecutor task_executor(*this); 6202 rp->enqueue_discovered_references(&task_executor); 6203 } else { 6204 rp->enqueue_discovered_references(NULL); 6205 } 6206 rp->verify_no_references_recorded(); 6207 assert(!rp->discovery_enabled(), "should have been disabled"); 6208 } 6209 6210 #ifndef PRODUCT 6211 void CMSCollector::check_correct_thread_executing() { 6212 Thread* t = Thread::current(); 6213 // Only the VM thread or the CMS thread should be here. 6214 assert(t->is_ConcurrentGC_thread() || t->is_VM_thread(), 6215 "Unexpected thread type"); 6216 // If this is the vm thread, the foreground process 6217 // should not be waiting. Note that _foregroundGCIsActive is 6218 // true while the foreground collector is waiting. 6219 if (_foregroundGCShouldWait) { 6220 // We cannot be the VM thread 6221 assert(t->is_ConcurrentGC_thread(), 6222 "Should be CMS thread"); 6223 } else { 6224 // We can be the CMS thread only if we are in a stop-world 6225 // phase of CMS collection. 6226 if (t->is_ConcurrentGC_thread()) { 6227 assert(_collectorState == InitialMarking || 6228 _collectorState == FinalMarking, 6229 "Should be a stop-world phase"); 6230 // The CMS thread should be holding the CMS_token. 6231 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 6232 "Potential interference with concurrently " 6233 "executing VM thread"); 6234 } 6235 } 6236 } 6237 #endif 6238 6239 void CMSCollector::sweep(bool asynch) { 6240 assert(_collectorState == Sweeping, "just checking"); 6241 check_correct_thread_executing(); 6242 verify_work_stacks_empty(); 6243 verify_overflow_empty(); 6244 increment_sweep_count(); 6245 TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause()); 6246 6247 _inter_sweep_timer.stop(); 6248 _inter_sweep_estimate.sample(_inter_sweep_timer.seconds()); 6249 6250 assert(!_intra_sweep_timer.is_active(), "Should not be active"); 6251 _intra_sweep_timer.reset(); 6252 _intra_sweep_timer.start(); 6253 if (asynch) { 6254 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); 6255 CMSPhaseAccounting pa(this, "sweep", _gc_tracer_cm->gc_id(), !PrintGCDetails); 6256 // First sweep the old gen 6257 { 6258 CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock(), 6259 bitMapLock()); 6260 sweepWork(_cmsGen, asynch); 6261 } 6262 6263 // Update Universe::_heap_*_at_gc figures. 6264 // We need all the free list locks to make the abstract state 6265 // transition from Sweeping to Resetting. See detailed note 6266 // further below. 6267 { 6268 CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock()); 6269 // Update heap occupancy information which is used as 6270 // input to soft ref clearing policy at the next gc. 6271 Universe::update_heap_info_at_gc(); 6272 _collectorState = Resizing; 6273 } 6274 } else { 6275 // already have needed locks 6276 sweepWork(_cmsGen, asynch); 6277 // Update heap occupancy information which is used as 6278 // input to soft ref clearing policy at the next gc. 6279 Universe::update_heap_info_at_gc(); 6280 _collectorState = Resizing; 6281 } 6282 verify_work_stacks_empty(); 6283 verify_overflow_empty(); 6284 6285 if (should_unload_classes()) { 6286 // Delay purge to the beginning of the next safepoint. Metaspace::contains 6287 // requires that the virtual spaces are stable and not deleted. 6288 ClassLoaderDataGraph::set_should_purge(true); 6289 } 6290 6291 _intra_sweep_timer.stop(); 6292 _intra_sweep_estimate.sample(_intra_sweep_timer.seconds()); 6293 6294 _inter_sweep_timer.reset(); 6295 _inter_sweep_timer.start(); 6296 6297 // We need to use a monotonically non-decreasing time in ms 6298 // or we will see time-warp warnings and os::javaTimeMillis() 6299 // does not guarantee monotonicity. 6300 jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC; 6301 update_time_of_last_gc(now); 6302 6303 // NOTE on abstract state transitions: 6304 // Mutators allocate-live and/or mark the mod-union table dirty 6305 // based on the state of the collection. The former is done in 6306 // the interval [Marking, Sweeping] and the latter in the interval 6307 // [Marking, Sweeping). Thus the transitions into the Marking state 6308 // and out of the Sweeping state must be synchronously visible 6309 // globally to the mutators. 6310 // The transition into the Marking state happens with the world 6311 // stopped so the mutators will globally see it. Sweeping is 6312 // done asynchronously by the background collector so the transition 6313 // from the Sweeping state to the Resizing state must be done 6314 // under the freelistLock (as is the check for whether to 6315 // allocate-live and whether to dirty the mod-union table). 6316 assert(_collectorState == Resizing, "Change of collector state to" 6317 " Resizing must be done under the freelistLocks (plural)"); 6318 6319 // Now that sweeping has been completed, we clear 6320 // the incremental_collection_failed flag, 6321 // thus inviting a younger gen collection to promote into 6322 // this generation. If such a promotion may still fail, 6323 // the flag will be set again when a young collection is 6324 // attempted. 6325 GenCollectedHeap* gch = GenCollectedHeap::heap(); 6326 gch->clear_incremental_collection_failed(); // Worth retrying as fresh space may have been freed up 6327 gch->update_full_collections_completed(_collection_count_start); 6328 } 6329 6330 // FIX ME!!! Looks like this belongs in CFLSpace, with 6331 // CMSGen merely delegating to it. 6332 void ConcurrentMarkSweepGeneration::setNearLargestChunk() { 6333 double nearLargestPercent = FLSLargestBlockCoalesceProximity; 6334 HeapWord* minAddr = _cmsSpace->bottom(); 6335 HeapWord* largestAddr = 6336 (HeapWord*) _cmsSpace->dictionary()->find_largest_dict(); 6337 if (largestAddr == NULL) { 6338 // The dictionary appears to be empty. In this case 6339 // try to coalesce at the end of the heap. 6340 largestAddr = _cmsSpace->end(); 6341 } 6342 size_t largestOffset = pointer_delta(largestAddr, minAddr); 6343 size_t nearLargestOffset = 6344 (size_t)((double)largestOffset * nearLargestPercent) - MinChunkSize; 6345 if (PrintFLSStatistics != 0) { 6346 gclog_or_tty->print_cr( 6347 "CMS: Large Block: " PTR_FORMAT ";" 6348 " Proximity: " PTR_FORMAT " -> " PTR_FORMAT, 6349 largestAddr, 6350 _cmsSpace->nearLargestChunk(), minAddr + nearLargestOffset); 6351 } 6352 _cmsSpace->set_nearLargestChunk(minAddr + nearLargestOffset); 6353 } 6354 6355 bool ConcurrentMarkSweepGeneration::isNearLargestChunk(HeapWord* addr) { 6356 return addr >= _cmsSpace->nearLargestChunk(); 6357 } 6358 6359 FreeChunk* ConcurrentMarkSweepGeneration::find_chunk_at_end() { 6360 return _cmsSpace->find_chunk_at_end(); 6361 } 6362 6363 void ConcurrentMarkSweepGeneration::update_gc_stats(int current_level, 6364 bool full) { 6365 // The next lower level has been collected. Gather any statistics 6366 // that are of interest at this point. 6367 if (!full && (current_level + 1) == level()) { 6368 // Gather statistics on the young generation collection. 6369 collector()->stats().record_gc0_end(used()); 6370 } 6371 } 6372 6373 void ConcurrentMarkSweepGeneration::rotate_debug_collection_type() { 6374 if (PrintGCDetails && Verbose) { 6375 gclog_or_tty->print("Rotate from %d ", _debug_collection_type); 6376 } 6377 _debug_collection_type = (CollectionTypes) (_debug_collection_type + 1); 6378 _debug_collection_type = 6379 (CollectionTypes) (_debug_collection_type % Unknown_collection_type); 6380 if (PrintGCDetails && Verbose) { 6381 gclog_or_tty->print_cr("to %d ", _debug_collection_type); 6382 } 6383 } 6384 6385 void CMSCollector::sweepWork(ConcurrentMarkSweepGeneration* gen, 6386 bool asynch) { 6387 // We iterate over the space(s) underlying this generation, 6388 // checking the mark bit map to see if the bits corresponding 6389 // to specific blocks are marked or not. Blocks that are 6390 // marked are live and are not swept up. All remaining blocks 6391 // are swept up, with coalescing on-the-fly as we sweep up 6392 // contiguous free and/or garbage blocks: 6393 // We need to ensure that the sweeper synchronizes with allocators 6394 // and stop-the-world collectors. In particular, the following 6395 // locks are used: 6396 // . CMS token: if this is held, a stop the world collection cannot occur 6397 // . freelistLock: if this is held no allocation can occur from this 6398 // generation by another thread 6399 // . bitMapLock: if this is held, no other thread can access or update 6400 // 6401 6402 // Note that we need to hold the freelistLock if we use 6403 // block iterate below; else the iterator might go awry if 6404 // a mutator (or promotion) causes block contents to change 6405 // (for instance if the allocator divvies up a block). 6406 // If we hold the free list lock, for all practical purposes 6407 // young generation GC's can't occur (they'll usually need to 6408 // promote), so we might as well prevent all young generation 6409 // GC's while we do a sweeping step. For the same reason, we might 6410 // as well take the bit map lock for the entire duration 6411 6412 // check that we hold the requisite locks 6413 assert(have_cms_token(), "Should hold cms token"); 6414 assert( (asynch && ConcurrentMarkSweepThread::cms_thread_has_cms_token()) 6415 || (!asynch && ConcurrentMarkSweepThread::vm_thread_has_cms_token()), 6416 "Should possess CMS token to sweep"); 6417 assert_lock_strong(gen->freelistLock()); 6418 assert_lock_strong(bitMapLock()); 6419 6420 assert(!_inter_sweep_timer.is_active(), "Was switched off in an outer context"); 6421 assert(_intra_sweep_timer.is_active(), "Was switched on in an outer context"); 6422 gen->cmsSpace()->beginSweepFLCensus((float)(_inter_sweep_timer.seconds()), 6423 _inter_sweep_estimate.padded_average(), 6424 _intra_sweep_estimate.padded_average()); 6425 gen->setNearLargestChunk(); 6426 6427 { 6428 SweepClosure sweepClosure(this, gen, &_markBitMap, 6429 CMSYield && asynch); 6430 gen->cmsSpace()->blk_iterate_careful(&sweepClosure); 6431 // We need to free-up/coalesce garbage/blocks from a 6432 // co-terminal free run. This is done in the SweepClosure 6433 // destructor; so, do not remove this scope, else the 6434 // end-of-sweep-census below will be off by a little bit. 6435 } 6436 gen->cmsSpace()->sweep_completed(); 6437 gen->cmsSpace()->endSweepFLCensus(sweep_count()); 6438 if (should_unload_classes()) { // unloaded classes this cycle, 6439 _concurrent_cycles_since_last_unload = 0; // ... reset count 6440 } else { // did not unload classes, 6441 _concurrent_cycles_since_last_unload++; // ... increment count 6442 } 6443 } 6444 6445 // Reset CMS data structures (for now just the marking bit map) 6446 // preparatory for the next cycle. 6447 void CMSCollector::reset(bool asynch) { 6448 if (asynch) { 6449 CMSTokenSyncWithLocks ts(true, bitMapLock()); 6450 6451 // If the state is not "Resetting", the foreground thread 6452 // has done a collection and the resetting. 6453 if (_collectorState != Resetting) { 6454 assert(_collectorState == Idling, "The state should only change" 6455 " because the foreground collector has finished the collection"); 6456 return; 6457 } 6458 6459 // Clear the mark bitmap (no grey objects to start with) 6460 // for the next cycle. 6461 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); 6462 CMSPhaseAccounting cmspa(this, "reset", _gc_tracer_cm->gc_id(), !PrintGCDetails); 6463 6464 HeapWord* curAddr = _markBitMap.startWord(); 6465 while (curAddr < _markBitMap.endWord()) { 6466 size_t remaining = pointer_delta(_markBitMap.endWord(), curAddr); 6467 MemRegion chunk(curAddr, MIN2(CMSBitMapYieldQuantum, remaining)); 6468 _markBitMap.clear_large_range(chunk); 6469 if (ConcurrentMarkSweepThread::should_yield() && 6470 !foregroundGCIsActive() && 6471 CMSYield) { 6472 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 6473 "CMS thread should hold CMS token"); 6474 assert_lock_strong(bitMapLock()); 6475 bitMapLock()->unlock(); 6476 ConcurrentMarkSweepThread::desynchronize(true); 6477 ConcurrentMarkSweepThread::acknowledge_yield_request(); 6478 stopTimer(); 6479 if (PrintCMSStatistics != 0) { 6480 incrementYields(); 6481 } 6482 icms_wait(); 6483 6484 // See the comment in coordinator_yield() 6485 for (unsigned i = 0; i < CMSYieldSleepCount && 6486 ConcurrentMarkSweepThread::should_yield() && 6487 !CMSCollector::foregroundGCIsActive(); ++i) { 6488 os::sleep(Thread::current(), 1, false); 6489 ConcurrentMarkSweepThread::acknowledge_yield_request(); 6490 } 6491 6492 ConcurrentMarkSweepThread::synchronize(true); 6493 bitMapLock()->lock_without_safepoint_check(); 6494 startTimer(); 6495 } 6496 curAddr = chunk.end(); 6497 } 6498 // A successful mostly concurrent collection has been done. 6499 // Because only the full (i.e., concurrent mode failure) collections 6500 // are being measured for gc overhead limits, clean the "near" flag 6501 // and count. 6502 size_policy()->reset_gc_overhead_limit_count(); 6503 _collectorState = Idling; 6504 } else { 6505 // already have the lock 6506 assert(_collectorState == Resetting, "just checking"); 6507 assert_lock_strong(bitMapLock()); 6508 _markBitMap.clear_all(); 6509 _collectorState = Idling; 6510 } 6511 6512 // Stop incremental mode after a cycle completes, so that any future cycles 6513 // are triggered by allocation. 6514 stop_icms(); 6515 6516 NOT_PRODUCT( 6517 if (RotateCMSCollectionTypes) { 6518 _cmsGen->rotate_debug_collection_type(); 6519 } 6520 ) 6521 6522 register_gc_end(); 6523 } 6524 6525 void CMSCollector::do_CMS_operation(CMS_op_type op, GCCause::Cause gc_cause) { 6526 gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps); 6527 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); 6528 GCTraceTime t(GCCauseString("GC", gc_cause), PrintGC, !PrintGCDetails, NULL, _gc_tracer_cm->gc_id()); 6529 TraceCollectorStats tcs(counters()); 6530 6531 switch (op) { 6532 case CMS_op_checkpointRootsInitial: { 6533 SvcGCMarker sgcm(SvcGCMarker::OTHER); 6534 checkpointRootsInitial(true); // asynch 6535 if (PrintGC) { 6536 _cmsGen->printOccupancy("initial-mark"); 6537 } 6538 break; 6539 } 6540 case CMS_op_checkpointRootsFinal: { 6541 SvcGCMarker sgcm(SvcGCMarker::OTHER); 6542 checkpointRootsFinal(true, // asynch 6543 false, // !clear_all_soft_refs 6544 false); // !init_mark_was_synchronous 6545 if (PrintGC) { 6546 _cmsGen->printOccupancy("remark"); 6547 } 6548 break; 6549 } 6550 default: 6551 fatal("No such CMS_op"); 6552 } 6553 } 6554 6555 #ifndef PRODUCT 6556 size_t const CMSCollector::skip_header_HeapWords() { 6557 return FreeChunk::header_size(); 6558 } 6559 6560 // Try and collect here conditions that should hold when 6561 // CMS thread is exiting. The idea is that the foreground GC 6562 // thread should not be blocked if it wants to terminate 6563 // the CMS thread and yet continue to run the VM for a while 6564 // after that. 6565 void CMSCollector::verify_ok_to_terminate() const { 6566 assert(Thread::current()->is_ConcurrentGC_thread(), 6567 "should be called by CMS thread"); 6568 assert(!_foregroundGCShouldWait, "should be false"); 6569 // We could check here that all the various low-level locks 6570 // are not held by the CMS thread, but that is overkill; see 6571 // also CMSThread::verify_ok_to_terminate() where the CGC_lock 6572 // is checked. 6573 } 6574 #endif 6575 6576 size_t CMSCollector::block_size_using_printezis_bits(HeapWord* addr) const { 6577 assert(_markBitMap.isMarked(addr) && _markBitMap.isMarked(addr + 1), 6578 "missing Printezis mark?"); 6579 HeapWord* nextOneAddr = _markBitMap.getNextMarkedWordAddress(addr + 2); 6580 size_t size = pointer_delta(nextOneAddr + 1, addr); 6581 assert(size == CompactibleFreeListSpace::adjustObjectSize(size), 6582 "alignment problem"); 6583 assert(size >= 3, "Necessary for Printezis marks to work"); 6584 return size; 6585 } 6586 6587 // A variant of the above (block_size_using_printezis_bits()) except 6588 // that we return 0 if the P-bits are not yet set. 6589 size_t CMSCollector::block_size_if_printezis_bits(HeapWord* addr) const { 6590 if (_markBitMap.isMarked(addr + 1)) { 6591 assert(_markBitMap.isMarked(addr), "P-bit can be set only for marked objects"); 6592 HeapWord* nextOneAddr = _markBitMap.getNextMarkedWordAddress(addr + 2); 6593 size_t size = pointer_delta(nextOneAddr + 1, addr); 6594 assert(size == CompactibleFreeListSpace::adjustObjectSize(size), 6595 "alignment problem"); 6596 assert(size >= 3, "Necessary for Printezis marks to work"); 6597 return size; 6598 } 6599 return 0; 6600 } 6601 6602 HeapWord* CMSCollector::next_card_start_after_block(HeapWord* addr) const { 6603 size_t sz = 0; 6604 oop p = (oop)addr; 6605 if (p->klass_or_null() != NULL) { 6606 sz = CompactibleFreeListSpace::adjustObjectSize(p->size()); 6607 } else { 6608 sz = block_size_using_printezis_bits(addr); 6609 } 6610 assert(sz > 0, "size must be nonzero"); 6611 HeapWord* next_block = addr + sz; 6612 HeapWord* next_card = (HeapWord*)round_to((uintptr_t)next_block, 6613 CardTableModRefBS::card_size); 6614 assert(round_down((uintptr_t)addr, CardTableModRefBS::card_size) < 6615 round_down((uintptr_t)next_card, CardTableModRefBS::card_size), 6616 "must be different cards"); 6617 return next_card; 6618 } 6619 6620 6621 // CMS Bit Map Wrapper ///////////////////////////////////////// 6622 6623 // Construct a CMS bit map infrastructure, but don't create the 6624 // bit vector itself. That is done by a separate call CMSBitMap::allocate() 6625 // further below. 6626 CMSBitMap::CMSBitMap(int shifter, int mutex_rank, const char* mutex_name): 6627 _bm(), 6628 _shifter(shifter), 6629 _lock(mutex_rank >= 0 ? new Mutex(mutex_rank, mutex_name, true) : NULL) 6630 { 6631 _bmStartWord = 0; 6632 _bmWordSize = 0; 6633 } 6634 6635 bool CMSBitMap::allocate(MemRegion mr) { 6636 _bmStartWord = mr.start(); 6637 _bmWordSize = mr.word_size(); 6638 ReservedSpace brs(ReservedSpace::allocation_align_size_up( 6639 (_bmWordSize >> (_shifter + LogBitsPerByte)) + 1)); 6640 if (!brs.is_reserved()) { 6641 warning("CMS bit map allocation failure"); 6642 return false; 6643 } 6644 // For now we'll just commit all of the bit map up front. 6645 // Later on we'll try to be more parsimonious with swap. 6646 if (!_virtual_space.initialize(brs, brs.size())) { 6647 warning("CMS bit map backing store failure"); 6648 return false; 6649 } 6650 assert(_virtual_space.committed_size() == brs.size(), 6651 "didn't reserve backing store for all of CMS bit map?"); 6652 _bm.set_map((BitMap::bm_word_t*)_virtual_space.low()); 6653 assert(_virtual_space.committed_size() << (_shifter + LogBitsPerByte) >= 6654 _bmWordSize, "inconsistency in bit map sizing"); 6655 _bm.set_size(_bmWordSize >> _shifter); 6656 6657 // bm.clear(); // can we rely on getting zero'd memory? verify below 6658 assert(isAllClear(), 6659 "Expected zero'd memory from ReservedSpace constructor"); 6660 assert(_bm.size() == heapWordDiffToOffsetDiff(sizeInWords()), 6661 "consistency check"); 6662 return true; 6663 } 6664 6665 void CMSBitMap::dirty_range_iterate_clear(MemRegion mr, MemRegionClosure* cl) { 6666 HeapWord *next_addr, *end_addr, *last_addr; 6667 assert_locked(); 6668 assert(covers(mr), "out-of-range error"); 6669 // XXX assert that start and end are appropriately aligned 6670 for (next_addr = mr.start(), end_addr = mr.end(); 6671 next_addr < end_addr; next_addr = last_addr) { 6672 MemRegion dirty_region = getAndClearMarkedRegion(next_addr, end_addr); 6673 last_addr = dirty_region.end(); 6674 if (!dirty_region.is_empty()) { 6675 cl->do_MemRegion(dirty_region); 6676 } else { 6677 assert(last_addr == end_addr, "program logic"); 6678 return; 6679 } 6680 } 6681 } 6682 6683 void CMSBitMap::print_on_error(outputStream* st, const char* prefix) const { 6684 _bm.print_on_error(st, prefix); 6685 } 6686 6687 #ifndef PRODUCT 6688 void CMSBitMap::assert_locked() const { 6689 CMSLockVerifier::assert_locked(lock()); 6690 } 6691 6692 bool CMSBitMap::covers(MemRegion mr) const { 6693 // assert(_bm.map() == _virtual_space.low(), "map inconsistency"); 6694 assert((size_t)_bm.size() == (_bmWordSize >> _shifter), 6695 "size inconsistency"); 6696 return (mr.start() >= _bmStartWord) && 6697 (mr.end() <= endWord()); 6698 } 6699 6700 bool CMSBitMap::covers(HeapWord* start, size_t size) const { 6701 return (start >= _bmStartWord && (start + size) <= endWord()); 6702 } 6703 6704 void CMSBitMap::verifyNoOneBitsInRange(HeapWord* left, HeapWord* right) { 6705 // verify that there are no 1 bits in the interval [left, right) 6706 FalseBitMapClosure falseBitMapClosure; 6707 iterate(&falseBitMapClosure, left, right); 6708 } 6709 6710 void CMSBitMap::region_invariant(MemRegion mr) 6711 { 6712 assert_locked(); 6713 // mr = mr.intersection(MemRegion(_bmStartWord, _bmWordSize)); 6714 assert(!mr.is_empty(), "unexpected empty region"); 6715 assert(covers(mr), "mr should be covered by bit map"); 6716 // convert address range into offset range 6717 size_t start_ofs = heapWordToOffset(mr.start()); 6718 // Make sure that end() is appropriately aligned 6719 assert(mr.end() == (HeapWord*)round_to((intptr_t)mr.end(), 6720 (1 << (_shifter+LogHeapWordSize))), 6721 "Misaligned mr.end()"); 6722 size_t end_ofs = heapWordToOffset(mr.end()); 6723 assert(end_ofs > start_ofs, "Should mark at least one bit"); 6724 } 6725 6726 #endif 6727 6728 bool CMSMarkStack::allocate(size_t size) { 6729 // allocate a stack of the requisite depth 6730 ReservedSpace rs(ReservedSpace::allocation_align_size_up( 6731 size * sizeof(oop))); 6732 if (!rs.is_reserved()) { 6733 warning("CMSMarkStack allocation failure"); 6734 return false; 6735 } 6736 if (!_virtual_space.initialize(rs, rs.size())) { 6737 warning("CMSMarkStack backing store failure"); 6738 return false; 6739 } 6740 assert(_virtual_space.committed_size() == rs.size(), 6741 "didn't reserve backing store for all of CMS stack?"); 6742 _base = (oop*)(_virtual_space.low()); 6743 _index = 0; 6744 _capacity = size; 6745 NOT_PRODUCT(_max_depth = 0); 6746 return true; 6747 } 6748 6749 // XXX FIX ME !!! In the MT case we come in here holding a 6750 // leaf lock. For printing we need to take a further lock 6751 // which has lower rank. We need to recalibrate the two 6752 // lock-ranks involved in order to be able to print the 6753 // messages below. (Or defer the printing to the caller. 6754 // For now we take the expedient path of just disabling the 6755 // messages for the problematic case.) 6756 void CMSMarkStack::expand() { 6757 assert(_capacity <= MarkStackSizeMax, "stack bigger than permitted"); 6758 if (_capacity == MarkStackSizeMax) { 6759 if (_hit_limit++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) { 6760 // We print a warning message only once per CMS cycle. 6761 gclog_or_tty->print_cr(" (benign) Hit CMSMarkStack max size limit"); 6762 } 6763 return; 6764 } 6765 // Double capacity if possible 6766 size_t new_capacity = MIN2(_capacity*2, MarkStackSizeMax); 6767 // Do not give up existing stack until we have managed to 6768 // get the double capacity that we desired. 6769 ReservedSpace rs(ReservedSpace::allocation_align_size_up( 6770 new_capacity * sizeof(oop))); 6771 if (rs.is_reserved()) { 6772 // Release the backing store associated with old stack 6773 _virtual_space.release(); 6774 // Reinitialize virtual space for new stack 6775 if (!_virtual_space.initialize(rs, rs.size())) { 6776 fatal("Not enough swap for expanded marking stack"); 6777 } 6778 _base = (oop*)(_virtual_space.low()); 6779 _index = 0; 6780 _capacity = new_capacity; 6781 } else if (_failed_double++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) { 6782 // Failed to double capacity, continue; 6783 // we print a detail message only once per CMS cycle. 6784 gclog_or_tty->print(" (benign) Failed to expand marking stack from "SIZE_FORMAT"K to " 6785 SIZE_FORMAT"K", 6786 _capacity / K, new_capacity / K); 6787 } 6788 } 6789 6790 6791 // Closures 6792 // XXX: there seems to be a lot of code duplication here; 6793 // should refactor and consolidate common code. 6794 6795 // This closure is used to mark refs into the CMS generation in 6796 // the CMS bit map. Called at the first checkpoint. This closure 6797 // assumes that we do not need to re-mark dirty cards; if the CMS 6798 // generation on which this is used is not an oldest 6799 // generation then this will lose younger_gen cards! 6800 6801 MarkRefsIntoClosure::MarkRefsIntoClosure( 6802 MemRegion span, CMSBitMap* bitMap): 6803 _span(span), 6804 _bitMap(bitMap) 6805 { 6806 assert(_ref_processor == NULL, "deliberately left NULL"); 6807 assert(_bitMap->covers(_span), "_bitMap/_span mismatch"); 6808 } 6809 6810 void MarkRefsIntoClosure::do_oop(oop obj) { 6811 // if p points into _span, then mark corresponding bit in _markBitMap 6812 assert(obj->is_oop(), "expected an oop"); 6813 HeapWord* addr = (HeapWord*)obj; 6814 if (_span.contains(addr)) { 6815 // this should be made more efficient 6816 _bitMap->mark(addr); 6817 } 6818 } 6819 6820 void MarkRefsIntoClosure::do_oop(oop* p) { MarkRefsIntoClosure::do_oop_work(p); } 6821 void MarkRefsIntoClosure::do_oop(narrowOop* p) { MarkRefsIntoClosure::do_oop_work(p); } 6822 6823 Par_MarkRefsIntoClosure::Par_MarkRefsIntoClosure( 6824 MemRegion span, CMSBitMap* bitMap): 6825 _span(span), 6826 _bitMap(bitMap) 6827 { 6828 assert(_ref_processor == NULL, "deliberately left NULL"); 6829 assert(_bitMap->covers(_span), "_bitMap/_span mismatch"); 6830 } 6831 6832 void Par_MarkRefsIntoClosure::do_oop(oop obj) { 6833 // if p points into _span, then mark corresponding bit in _markBitMap 6834 assert(obj->is_oop(), "expected an oop"); 6835 HeapWord* addr = (HeapWord*)obj; 6836 if (_span.contains(addr)) { 6837 // this should be made more efficient 6838 _bitMap->par_mark(addr); 6839 } 6840 } 6841 6842 void Par_MarkRefsIntoClosure::do_oop(oop* p) { Par_MarkRefsIntoClosure::do_oop_work(p); } 6843 void Par_MarkRefsIntoClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoClosure::do_oop_work(p); } 6844 6845 // A variant of the above, used for CMS marking verification. 6846 MarkRefsIntoVerifyClosure::MarkRefsIntoVerifyClosure( 6847 MemRegion span, CMSBitMap* verification_bm, CMSBitMap* cms_bm): 6848 _span(span), 6849 _verification_bm(verification_bm), 6850 _cms_bm(cms_bm) 6851 { 6852 assert(_ref_processor == NULL, "deliberately left NULL"); 6853 assert(_verification_bm->covers(_span), "_verification_bm/_span mismatch"); 6854 } 6855 6856 void MarkRefsIntoVerifyClosure::do_oop(oop obj) { 6857 // if p points into _span, then mark corresponding bit in _markBitMap 6858 assert(obj->is_oop(), "expected an oop"); 6859 HeapWord* addr = (HeapWord*)obj; 6860 if (_span.contains(addr)) { 6861 _verification_bm->mark(addr); 6862 if (!_cms_bm->isMarked(addr)) { 6863 oop(addr)->print(); 6864 gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)", addr); 6865 fatal("... aborting"); 6866 } 6867 } 6868 } 6869 6870 void MarkRefsIntoVerifyClosure::do_oop(oop* p) { MarkRefsIntoVerifyClosure::do_oop_work(p); } 6871 void MarkRefsIntoVerifyClosure::do_oop(narrowOop* p) { MarkRefsIntoVerifyClosure::do_oop_work(p); } 6872 6873 ////////////////////////////////////////////////// 6874 // MarkRefsIntoAndScanClosure 6875 ////////////////////////////////////////////////// 6876 6877 MarkRefsIntoAndScanClosure::MarkRefsIntoAndScanClosure(MemRegion span, 6878 ReferenceProcessor* rp, 6879 CMSBitMap* bit_map, 6880 CMSBitMap* mod_union_table, 6881 CMSMarkStack* mark_stack, 6882 CMSCollector* collector, 6883 bool should_yield, 6884 bool concurrent_precleaning): 6885 _collector(collector), 6886 _span(span), 6887 _bit_map(bit_map), 6888 _mark_stack(mark_stack), 6889 _pushAndMarkClosure(collector, span, rp, bit_map, mod_union_table, 6890 mark_stack, concurrent_precleaning), 6891 _yield(should_yield), 6892 _concurrent_precleaning(concurrent_precleaning), 6893 _freelistLock(NULL) 6894 { 6895 _ref_processor = rp; 6896 assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL"); 6897 } 6898 6899 // This closure is used to mark refs into the CMS generation at the 6900 // second (final) checkpoint, and to scan and transitively follow 6901 // the unmarked oops. It is also used during the concurrent precleaning 6902 // phase while scanning objects on dirty cards in the CMS generation. 6903 // The marks are made in the marking bit map and the marking stack is 6904 // used for keeping the (newly) grey objects during the scan. 6905 // The parallel version (Par_...) appears further below. 6906 void MarkRefsIntoAndScanClosure::do_oop(oop obj) { 6907 if (obj != NULL) { 6908 assert(obj->is_oop(), "expected an oop"); 6909 HeapWord* addr = (HeapWord*)obj; 6910 assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)"); 6911 assert(_collector->overflow_list_is_empty(), 6912 "overflow list should be empty"); 6913 if (_span.contains(addr) && 6914 !_bit_map->isMarked(addr)) { 6915 // mark bit map (object is now grey) 6916 _bit_map->mark(addr); 6917 // push on marking stack (stack should be empty), and drain the 6918 // stack by applying this closure to the oops in the oops popped 6919 // from the stack (i.e. blacken the grey objects) 6920 bool res = _mark_stack->push(obj); 6921 assert(res, "Should have space to push on empty stack"); 6922 do { 6923 oop new_oop = _mark_stack->pop(); 6924 assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop"); 6925 assert(_bit_map->isMarked((HeapWord*)new_oop), 6926 "only grey objects on this stack"); 6927 // iterate over the oops in this oop, marking and pushing 6928 // the ones in CMS heap (i.e. in _span). 6929 new_oop->oop_iterate(&_pushAndMarkClosure); 6930 // check if it's time to yield 6931 do_yield_check(); 6932 } while (!_mark_stack->isEmpty() || 6933 (!_concurrent_precleaning && take_from_overflow_list())); 6934 // if marking stack is empty, and we are not doing this 6935 // during precleaning, then check the overflow list 6936 } 6937 assert(_mark_stack->isEmpty(), "post-condition (eager drainage)"); 6938 assert(_collector->overflow_list_is_empty(), 6939 "overflow list was drained above"); 6940 // We could restore evacuated mark words, if any, used for 6941 // overflow list links here because the overflow list is 6942 // provably empty here. That would reduce the maximum 6943 // size requirements for preserved_{oop,mark}_stack. 6944 // But we'll just postpone it until we are all done 6945 // so we can just stream through. 6946 if (!_concurrent_precleaning && CMSOverflowEarlyRestoration) { 6947 _collector->restore_preserved_marks_if_any(); 6948 assert(_collector->no_preserved_marks(), "No preserved marks"); 6949 } 6950 assert(!CMSOverflowEarlyRestoration || _collector->no_preserved_marks(), 6951 "All preserved marks should have been restored above"); 6952 } 6953 } 6954 6955 void MarkRefsIntoAndScanClosure::do_oop(oop* p) { MarkRefsIntoAndScanClosure::do_oop_work(p); } 6956 void MarkRefsIntoAndScanClosure::do_oop(narrowOop* p) { MarkRefsIntoAndScanClosure::do_oop_work(p); } 6957 6958 void MarkRefsIntoAndScanClosure::do_yield_work() { 6959 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 6960 "CMS thread should hold CMS token"); 6961 assert_lock_strong(_freelistLock); 6962 assert_lock_strong(_bit_map->lock()); 6963 // relinquish the free_list_lock and bitMaplock() 6964 _bit_map->lock()->unlock(); 6965 _freelistLock->unlock(); 6966 ConcurrentMarkSweepThread::desynchronize(true); 6967 ConcurrentMarkSweepThread::acknowledge_yield_request(); 6968 _collector->stopTimer(); 6969 if (PrintCMSStatistics != 0) { 6970 _collector->incrementYields(); 6971 } 6972 _collector->icms_wait(); 6973 6974 // See the comment in coordinator_yield() 6975 for (unsigned i = 0; 6976 i < CMSYieldSleepCount && 6977 ConcurrentMarkSweepThread::should_yield() && 6978 !CMSCollector::foregroundGCIsActive(); 6979 ++i) { 6980 os::sleep(Thread::current(), 1, false); 6981 ConcurrentMarkSweepThread::acknowledge_yield_request(); 6982 } 6983 6984 ConcurrentMarkSweepThread::synchronize(true); 6985 _freelistLock->lock_without_safepoint_check(); 6986 _bit_map->lock()->lock_without_safepoint_check(); 6987 _collector->startTimer(); 6988 } 6989 6990 /////////////////////////////////////////////////////////// 6991 // Par_MarkRefsIntoAndScanClosure: a parallel version of 6992 // MarkRefsIntoAndScanClosure 6993 /////////////////////////////////////////////////////////// 6994 Par_MarkRefsIntoAndScanClosure::Par_MarkRefsIntoAndScanClosure( 6995 CMSCollector* collector, MemRegion span, ReferenceProcessor* rp, 6996 CMSBitMap* bit_map, OopTaskQueue* work_queue): 6997 _span(span), 6998 _bit_map(bit_map), 6999 _work_queue(work_queue), 7000 _low_water_mark(MIN2((uint)(work_queue->max_elems()/4), 7001 (uint)(CMSWorkQueueDrainThreshold * ParallelGCThreads))), 7002 _par_pushAndMarkClosure(collector, span, rp, bit_map, work_queue) 7003 { 7004 _ref_processor = rp; 7005 assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL"); 7006 } 7007 7008 // This closure is used to mark refs into the CMS generation at the 7009 // second (final) checkpoint, and to scan and transitively follow 7010 // the unmarked oops. The marks are made in the marking bit map and 7011 // the work_queue is used for keeping the (newly) grey objects during 7012 // the scan phase whence they are also available for stealing by parallel 7013 // threads. Since the marking bit map is shared, updates are 7014 // synchronized (via CAS). 7015 void Par_MarkRefsIntoAndScanClosure::do_oop(oop obj) { 7016 if (obj != NULL) { 7017 // Ignore mark word because this could be an already marked oop 7018 // that may be chained at the end of the overflow list. 7019 assert(obj->is_oop(true), "expected an oop"); 7020 HeapWord* addr = (HeapWord*)obj; 7021 if (_span.contains(addr) && 7022 !_bit_map->isMarked(addr)) { 7023 // mark bit map (object will become grey): 7024 // It is possible for several threads to be 7025 // trying to "claim" this object concurrently; 7026 // the unique thread that succeeds in marking the 7027 // object first will do the subsequent push on 7028 // to the work queue (or overflow list). 7029 if (_bit_map->par_mark(addr)) { 7030 // push on work_queue (which may not be empty), and trim the 7031 // queue to an appropriate length by applying this closure to 7032 // the oops in the oops popped from the stack (i.e. blacken the 7033 // grey objects) 7034 bool res = _work_queue->push(obj); 7035 assert(res, "Low water mark should be less than capacity?"); 7036 trim_queue(_low_water_mark); 7037 } // Else, another thread claimed the object 7038 } 7039 } 7040 } 7041 7042 void Par_MarkRefsIntoAndScanClosure::do_oop(oop* p) { Par_MarkRefsIntoAndScanClosure::do_oop_work(p); } 7043 void Par_MarkRefsIntoAndScanClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoAndScanClosure::do_oop_work(p); } 7044 7045 // This closure is used to rescan the marked objects on the dirty cards 7046 // in the mod union table and the card table proper. 7047 size_t ScanMarkedObjectsAgainCarefullyClosure::do_object_careful_m( 7048 oop p, MemRegion mr) { 7049 7050 size_t size = 0; 7051 HeapWord* addr = (HeapWord*)p; 7052 DEBUG_ONLY(_collector->verify_work_stacks_empty();) 7053 assert(_span.contains(addr), "we are scanning the CMS generation"); 7054 // check if it's time to yield 7055 if (do_yield_check()) { 7056 // We yielded for some foreground stop-world work, 7057 // and we have been asked to abort this ongoing preclean cycle. 7058 return 0; 7059 } 7060 if (_bitMap->isMarked(addr)) { 7061 // it's marked; is it potentially uninitialized? 7062 if (p->klass_or_null() != NULL) { 7063 // an initialized object; ignore mark word in verification below 7064 // since we are running concurrent with mutators 7065 assert(p->is_oop(true), "should be an oop"); 7066 if (p->is_objArray()) { 7067 // objArrays are precisely marked; restrict scanning 7068 // to dirty cards only. 7069 size = CompactibleFreeListSpace::adjustObjectSize( 7070 p->oop_iterate(_scanningClosure, mr)); 7071 } else { 7072 // A non-array may have been imprecisely marked; we need 7073 // to scan object in its entirety. 7074 size = CompactibleFreeListSpace::adjustObjectSize( 7075 p->oop_iterate(_scanningClosure)); 7076 } 7077 #ifdef ASSERT 7078 size_t direct_size = 7079 CompactibleFreeListSpace::adjustObjectSize(p->size()); 7080 assert(size == direct_size, "Inconsistency in size"); 7081 assert(size >= 3, "Necessary for Printezis marks to work"); 7082 if (!_bitMap->isMarked(addr+1)) { 7083 _bitMap->verifyNoOneBitsInRange(addr+2, addr+size); 7084 } else { 7085 _bitMap->verifyNoOneBitsInRange(addr+2, addr+size-1); 7086 assert(_bitMap->isMarked(addr+size-1), 7087 "inconsistent Printezis mark"); 7088 } 7089 #endif // ASSERT 7090 } else { 7091 // An uninitialized object. 7092 assert(_bitMap->isMarked(addr+1), "missing Printezis mark?"); 7093 HeapWord* nextOneAddr = _bitMap->getNextMarkedWordAddress(addr + 2); 7094 size = pointer_delta(nextOneAddr + 1, addr); 7095 assert(size == CompactibleFreeListSpace::adjustObjectSize(size), 7096 "alignment problem"); 7097 // Note that pre-cleaning needn't redirty the card. OopDesc::set_klass() 7098 // will dirty the card when the klass pointer is installed in the 7099 // object (signaling the completion of initialization). 7100 } 7101 } else { 7102 // Either a not yet marked object or an uninitialized object 7103 if (p->klass_or_null() == NULL) { 7104 // An uninitialized object, skip to the next card, since 7105 // we may not be able to read its P-bits yet. 7106 assert(size == 0, "Initial value"); 7107 } else { 7108 // An object not (yet) reached by marking: we merely need to 7109 // compute its size so as to go look at the next block. 7110 assert(p->is_oop(true), "should be an oop"); 7111 size = CompactibleFreeListSpace::adjustObjectSize(p->size()); 7112 } 7113 } 7114 DEBUG_ONLY(_collector->verify_work_stacks_empty();) 7115 return size; 7116 } 7117 7118 void ScanMarkedObjectsAgainCarefullyClosure::do_yield_work() { 7119 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 7120 "CMS thread should hold CMS token"); 7121 assert_lock_strong(_freelistLock); 7122 assert_lock_strong(_bitMap->lock()); 7123 // relinquish the free_list_lock and bitMaplock() 7124 _bitMap->lock()->unlock(); 7125 _freelistLock->unlock(); 7126 ConcurrentMarkSweepThread::desynchronize(true); 7127 ConcurrentMarkSweepThread::acknowledge_yield_request(); 7128 _collector->stopTimer(); 7129 if (PrintCMSStatistics != 0) { 7130 _collector->incrementYields(); 7131 } 7132 _collector->icms_wait(); 7133 7134 // See the comment in coordinator_yield() 7135 for (unsigned i = 0; i < CMSYieldSleepCount && 7136 ConcurrentMarkSweepThread::should_yield() && 7137 !CMSCollector::foregroundGCIsActive(); ++i) { 7138 os::sleep(Thread::current(), 1, false); 7139 ConcurrentMarkSweepThread::acknowledge_yield_request(); 7140 } 7141 7142 ConcurrentMarkSweepThread::synchronize(true); 7143 _freelistLock->lock_without_safepoint_check(); 7144 _bitMap->lock()->lock_without_safepoint_check(); 7145 _collector->startTimer(); 7146 } 7147 7148 7149 ////////////////////////////////////////////////////////////////// 7150 // SurvivorSpacePrecleanClosure 7151 ////////////////////////////////////////////////////////////////// 7152 // This (single-threaded) closure is used to preclean the oops in 7153 // the survivor spaces. 7154 size_t SurvivorSpacePrecleanClosure::do_object_careful(oop p) { 7155 7156 HeapWord* addr = (HeapWord*)p; 7157 DEBUG_ONLY(_collector->verify_work_stacks_empty();) 7158 assert(!_span.contains(addr), "we are scanning the survivor spaces"); 7159 assert(p->klass_or_null() != NULL, "object should be initialized"); 7160 // an initialized object; ignore mark word in verification below 7161 // since we are running concurrent with mutators 7162 assert(p->is_oop(true), "should be an oop"); 7163 // Note that we do not yield while we iterate over 7164 // the interior oops of p, pushing the relevant ones 7165 // on our marking stack. 7166 size_t size = p->oop_iterate(_scanning_closure); 7167 do_yield_check(); 7168 // Observe that below, we do not abandon the preclean 7169 // phase as soon as we should; rather we empty the 7170 // marking stack before returning. This is to satisfy 7171 // some existing assertions. In general, it may be a 7172 // good idea to abort immediately and complete the marking 7173 // from the grey objects at a later time. 7174 while (!_mark_stack->isEmpty()) { 7175 oop new_oop = _mark_stack->pop(); 7176 assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop"); 7177 assert(_bit_map->isMarked((HeapWord*)new_oop), 7178 "only grey objects on this stack"); 7179 // iterate over the oops in this oop, marking and pushing 7180 // the ones in CMS heap (i.e. in _span). 7181 new_oop->oop_iterate(_scanning_closure); 7182 // check if it's time to yield 7183 do_yield_check(); 7184 } 7185 unsigned int after_count = 7186 GenCollectedHeap::heap()->total_collections(); 7187 bool abort = (_before_count != after_count) || 7188 _collector->should_abort_preclean(); 7189 return abort ? 0 : size; 7190 } 7191 7192 void SurvivorSpacePrecleanClosure::do_yield_work() { 7193 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 7194 "CMS thread should hold CMS token"); 7195 assert_lock_strong(_bit_map->lock()); 7196 // Relinquish the bit map lock 7197 _bit_map->lock()->unlock(); 7198 ConcurrentMarkSweepThread::desynchronize(true); 7199 ConcurrentMarkSweepThread::acknowledge_yield_request(); 7200 _collector->stopTimer(); 7201 if (PrintCMSStatistics != 0) { 7202 _collector->incrementYields(); 7203 } 7204 _collector->icms_wait(); 7205 7206 // See the comment in coordinator_yield() 7207 for (unsigned i = 0; i < CMSYieldSleepCount && 7208 ConcurrentMarkSweepThread::should_yield() && 7209 !CMSCollector::foregroundGCIsActive(); ++i) { 7210 os::sleep(Thread::current(), 1, false); 7211 ConcurrentMarkSweepThread::acknowledge_yield_request(); 7212 } 7213 7214 ConcurrentMarkSweepThread::synchronize(true); 7215 _bit_map->lock()->lock_without_safepoint_check(); 7216 _collector->startTimer(); 7217 } 7218 7219 // This closure is used to rescan the marked objects on the dirty cards 7220 // in the mod union table and the card table proper. In the parallel 7221 // case, although the bitMap is shared, we do a single read so the 7222 // isMarked() query is "safe". 7223 bool ScanMarkedObjectsAgainClosure::do_object_bm(oop p, MemRegion mr) { 7224 // Ignore mark word because we are running concurrent with mutators 7225 assert(p->is_oop_or_null(true), "expected an oop or null"); 7226 HeapWord* addr = (HeapWord*)p; 7227 assert(_span.contains(addr), "we are scanning the CMS generation"); 7228 bool is_obj_array = false; 7229 #ifdef ASSERT 7230 if (!_parallel) { 7231 assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)"); 7232 assert(_collector->overflow_list_is_empty(), 7233 "overflow list should be empty"); 7234 7235 } 7236 #endif // ASSERT 7237 if (_bit_map->isMarked(addr)) { 7238 // Obj arrays are precisely marked, non-arrays are not; 7239 // so we scan objArrays precisely and non-arrays in their 7240 // entirety. 7241 if (p->is_objArray()) { 7242 is_obj_array = true; 7243 if (_parallel) { 7244 p->oop_iterate(_par_scan_closure, mr); 7245 } else { 7246 p->oop_iterate(_scan_closure, mr); 7247 } 7248 } else { 7249 if (_parallel) { 7250 p->oop_iterate(_par_scan_closure); 7251 } else { 7252 p->oop_iterate(_scan_closure); 7253 } 7254 } 7255 } 7256 #ifdef ASSERT 7257 if (!_parallel) { 7258 assert(_mark_stack->isEmpty(), "post-condition (eager drainage)"); 7259 assert(_collector->overflow_list_is_empty(), 7260 "overflow list should be empty"); 7261 7262 } 7263 #endif // ASSERT 7264 return is_obj_array; 7265 } 7266 7267 MarkFromRootsClosure::MarkFromRootsClosure(CMSCollector* collector, 7268 MemRegion span, 7269 CMSBitMap* bitMap, CMSMarkStack* markStack, 7270 bool should_yield, bool verifying): 7271 _collector(collector), 7272 _span(span), 7273 _bitMap(bitMap), 7274 _mut(&collector->_modUnionTable), 7275 _markStack(markStack), 7276 _yield(should_yield), 7277 _skipBits(0) 7278 { 7279 assert(_markStack->isEmpty(), "stack should be empty"); 7280 _finger = _bitMap->startWord(); 7281 _threshold = _finger; 7282 assert(_collector->_restart_addr == NULL, "Sanity check"); 7283 assert(_span.contains(_finger), "Out of bounds _finger?"); 7284 DEBUG_ONLY(_verifying = verifying;) 7285 } 7286 7287 void MarkFromRootsClosure::reset(HeapWord* addr) { 7288 assert(_markStack->isEmpty(), "would cause duplicates on stack"); 7289 assert(_span.contains(addr), "Out of bounds _finger?"); 7290 _finger = addr; 7291 _threshold = (HeapWord*)round_to( 7292 (intptr_t)_finger, CardTableModRefBS::card_size); 7293 } 7294 7295 // Should revisit to see if this should be restructured for 7296 // greater efficiency. 7297 bool MarkFromRootsClosure::do_bit(size_t offset) { 7298 if (_skipBits > 0) { 7299 _skipBits--; 7300 return true; 7301 } 7302 // convert offset into a HeapWord* 7303 HeapWord* addr = _bitMap->startWord() + offset; 7304 assert(_bitMap->endWord() && addr < _bitMap->endWord(), 7305 "address out of range"); 7306 assert(_bitMap->isMarked(addr), "tautology"); 7307 if (_bitMap->isMarked(addr+1)) { 7308 // this is an allocated but not yet initialized object 7309 assert(_skipBits == 0, "tautology"); 7310 _skipBits = 2; // skip next two marked bits ("Printezis-marks") 7311 oop p = oop(addr); 7312 if (p->klass_or_null() == NULL) { 7313 DEBUG_ONLY(if (!_verifying) {) 7314 // We re-dirty the cards on which this object lies and increase 7315 // the _threshold so that we'll come back to scan this object 7316 // during the preclean or remark phase. (CMSCleanOnEnter) 7317 if (CMSCleanOnEnter) { 7318 size_t sz = _collector->block_size_using_printezis_bits(addr); 7319 HeapWord* end_card_addr = (HeapWord*)round_to( 7320 (intptr_t)(addr+sz), CardTableModRefBS::card_size); 7321 MemRegion redirty_range = MemRegion(addr, end_card_addr); 7322 assert(!redirty_range.is_empty(), "Arithmetical tautology"); 7323 // Bump _threshold to end_card_addr; note that 7324 // _threshold cannot possibly exceed end_card_addr, anyhow. 7325 // This prevents future clearing of the card as the scan proceeds 7326 // to the right. 7327 assert(_threshold <= end_card_addr, 7328 "Because we are just scanning into this object"); 7329 if (_threshold < end_card_addr) { 7330 _threshold = end_card_addr; 7331 } 7332 if (p->klass_or_null() != NULL) { 7333 // Redirty the range of cards... 7334 _mut->mark_range(redirty_range); 7335 } // ...else the setting of klass will dirty the card anyway. 7336 } 7337 DEBUG_ONLY(}) 7338 return true; 7339 } 7340 } 7341 scanOopsInOop(addr); 7342 return true; 7343 } 7344 7345 // We take a break if we've been at this for a while, 7346 // so as to avoid monopolizing the locks involved. 7347 void MarkFromRootsClosure::do_yield_work() { 7348 // First give up the locks, then yield, then re-lock 7349 // We should probably use a constructor/destructor idiom to 7350 // do this unlock/lock or modify the MutexUnlocker class to 7351 // serve our purpose. XXX 7352 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 7353 "CMS thread should hold CMS token"); 7354 assert_lock_strong(_bitMap->lock()); 7355 _bitMap->lock()->unlock(); 7356 ConcurrentMarkSweepThread::desynchronize(true); 7357 ConcurrentMarkSweepThread::acknowledge_yield_request(); 7358 _collector->stopTimer(); 7359 if (PrintCMSStatistics != 0) { 7360 _collector->incrementYields(); 7361 } 7362 _collector->icms_wait(); 7363 7364 // See the comment in coordinator_yield() 7365 for (unsigned i = 0; i < CMSYieldSleepCount && 7366 ConcurrentMarkSweepThread::should_yield() && 7367 !CMSCollector::foregroundGCIsActive(); ++i) { 7368 os::sleep(Thread::current(), 1, false); 7369 ConcurrentMarkSweepThread::acknowledge_yield_request(); 7370 } 7371 7372 ConcurrentMarkSweepThread::synchronize(true); 7373 _bitMap->lock()->lock_without_safepoint_check(); 7374 _collector->startTimer(); 7375 } 7376 7377 void MarkFromRootsClosure::scanOopsInOop(HeapWord* ptr) { 7378 assert(_bitMap->isMarked(ptr), "expected bit to be set"); 7379 assert(_markStack->isEmpty(), 7380 "should drain stack to limit stack usage"); 7381 // convert ptr to an oop preparatory to scanning 7382 oop obj = oop(ptr); 7383 // Ignore mark word in verification below, since we 7384 // may be running concurrent with mutators. 7385 assert(obj->is_oop(true), "should be an oop"); 7386 assert(_finger <= ptr, "_finger runneth ahead"); 7387 // advance the finger to right end of this object 7388 _finger = ptr + obj->size(); 7389 assert(_finger > ptr, "we just incremented it above"); 7390 // On large heaps, it may take us some time to get through 7391 // the marking phase (especially if running iCMS). During 7392 // this time it's possible that a lot of mutations have 7393 // accumulated in the card table and the mod union table -- 7394 // these mutation records are redundant until we have 7395 // actually traced into the corresponding card. 7396 // Here, we check whether advancing the finger would make 7397 // us cross into a new card, and if so clear corresponding 7398 // cards in the MUT (preclean them in the card-table in the 7399 // future). 7400 7401 DEBUG_ONLY(if (!_verifying) {) 7402 // The clean-on-enter optimization is disabled by default, 7403 // until we fix 6178663. 7404 if (CMSCleanOnEnter && (_finger > _threshold)) { 7405 // [_threshold, _finger) represents the interval 7406 // of cards to be cleared in MUT (or precleaned in card table). 7407 // The set of cards to be cleared is all those that overlap 7408 // with the interval [_threshold, _finger); note that 7409 // _threshold is always kept card-aligned but _finger isn't 7410 // always card-aligned. 7411 HeapWord* old_threshold = _threshold; 7412 assert(old_threshold == (HeapWord*)round_to( 7413 (intptr_t)old_threshold, CardTableModRefBS::card_size), 7414 "_threshold should always be card-aligned"); 7415 _threshold = (HeapWord*)round_to( 7416 (intptr_t)_finger, CardTableModRefBS::card_size); 7417 MemRegion mr(old_threshold, _threshold); 7418 assert(!mr.is_empty(), "Control point invariant"); 7419 assert(_span.contains(mr), "Should clear within span"); 7420 _mut->clear_range(mr); 7421 } 7422 DEBUG_ONLY(}) 7423 // Note: the finger doesn't advance while we drain 7424 // the stack below. 7425 PushOrMarkClosure pushOrMarkClosure(_collector, 7426 _span, _bitMap, _markStack, 7427 _finger, this); 7428 bool res = _markStack->push(obj); 7429 assert(res, "Empty non-zero size stack should have space for single push"); 7430 while (!_markStack->isEmpty()) { 7431 oop new_oop = _markStack->pop(); 7432 // Skip verifying header mark word below because we are 7433 // running concurrent with mutators. 7434 assert(new_oop->is_oop(true), "Oops! expected to pop an oop"); 7435 // now scan this oop's oops 7436 new_oop->oop_iterate(&pushOrMarkClosure); 7437 do_yield_check(); 7438 } 7439 assert(_markStack->isEmpty(), "tautology, emphasizing post-condition"); 7440 } 7441 7442 Par_MarkFromRootsClosure::Par_MarkFromRootsClosure(CMSConcMarkingTask* task, 7443 CMSCollector* collector, MemRegion span, 7444 CMSBitMap* bit_map, 7445 OopTaskQueue* work_queue, 7446 CMSMarkStack* overflow_stack, 7447 bool should_yield): 7448 _collector(collector), 7449 _whole_span(collector->_span), 7450 _span(span), 7451 _bit_map(bit_map), 7452 _mut(&collector->_modUnionTable), 7453 _work_queue(work_queue), 7454 _overflow_stack(overflow_stack), 7455 _yield(should_yield), 7456 _skip_bits(0), 7457 _task(task) 7458 { 7459 assert(_work_queue->size() == 0, "work_queue should be empty"); 7460 _finger = span.start(); 7461 _threshold = _finger; // XXX Defer clear-on-enter optimization for now 7462 assert(_span.contains(_finger), "Out of bounds _finger?"); 7463 } 7464 7465 // Should revisit to see if this should be restructured for 7466 // greater efficiency. 7467 bool Par_MarkFromRootsClosure::do_bit(size_t offset) { 7468 if (_skip_bits > 0) { 7469 _skip_bits--; 7470 return true; 7471 } 7472 // convert offset into a HeapWord* 7473 HeapWord* addr = _bit_map->startWord() + offset; 7474 assert(_bit_map->endWord() && addr < _bit_map->endWord(), 7475 "address out of range"); 7476 assert(_bit_map->isMarked(addr), "tautology"); 7477 if (_bit_map->isMarked(addr+1)) { 7478 // this is an allocated object that might not yet be initialized 7479 assert(_skip_bits == 0, "tautology"); 7480 _skip_bits = 2; // skip next two marked bits ("Printezis-marks") 7481 oop p = oop(addr); 7482 if (p->klass_or_null() == NULL) { 7483 // in the case of Clean-on-Enter optimization, redirty card 7484 // and avoid clearing card by increasing the threshold. 7485 return true; 7486 } 7487 } 7488 scan_oops_in_oop(addr); 7489 return true; 7490 } 7491 7492 void Par_MarkFromRootsClosure::scan_oops_in_oop(HeapWord* ptr) { 7493 assert(_bit_map->isMarked(ptr), "expected bit to be set"); 7494 // Should we assert that our work queue is empty or 7495 // below some drain limit? 7496 assert(_work_queue->size() == 0, 7497 "should drain stack to limit stack usage"); 7498 // convert ptr to an oop preparatory to scanning 7499 oop obj = oop(ptr); 7500 // Ignore mark word in verification below, since we 7501 // may be running concurrent with mutators. 7502 assert(obj->is_oop(true), "should be an oop"); 7503 assert(_finger <= ptr, "_finger runneth ahead"); 7504 // advance the finger to right end of this object 7505 _finger = ptr + obj->size(); 7506 assert(_finger > ptr, "we just incremented it above"); 7507 // On large heaps, it may take us some time to get through 7508 // the marking phase (especially if running iCMS). During 7509 // this time it's possible that a lot of mutations have 7510 // accumulated in the card table and the mod union table -- 7511 // these mutation records are redundant until we have 7512 // actually traced into the corresponding card. 7513 // Here, we check whether advancing the finger would make 7514 // us cross into a new card, and if so clear corresponding 7515 // cards in the MUT (preclean them in the card-table in the 7516 // future). 7517 7518 // The clean-on-enter optimization is disabled by default, 7519 // until we fix 6178663. 7520 if (CMSCleanOnEnter && (_finger > _threshold)) { 7521 // [_threshold, _finger) represents the interval 7522 // of cards to be cleared in MUT (or precleaned in card table). 7523 // The set of cards to be cleared is all those that overlap 7524 // with the interval [_threshold, _finger); note that 7525 // _threshold is always kept card-aligned but _finger isn't 7526 // always card-aligned. 7527 HeapWord* old_threshold = _threshold; 7528 assert(old_threshold == (HeapWord*)round_to( 7529 (intptr_t)old_threshold, CardTableModRefBS::card_size), 7530 "_threshold should always be card-aligned"); 7531 _threshold = (HeapWord*)round_to( 7532 (intptr_t)_finger, CardTableModRefBS::card_size); 7533 MemRegion mr(old_threshold, _threshold); 7534 assert(!mr.is_empty(), "Control point invariant"); 7535 assert(_span.contains(mr), "Should clear within span"); // _whole_span ?? 7536 _mut->clear_range(mr); 7537 } 7538 7539 // Note: the local finger doesn't advance while we drain 7540 // the stack below, but the global finger sure can and will. 7541 HeapWord** gfa = _task->global_finger_addr(); 7542 Par_PushOrMarkClosure pushOrMarkClosure(_collector, 7543 _span, _bit_map, 7544 _work_queue, 7545 _overflow_stack, 7546 _finger, 7547 gfa, this); 7548 bool res = _work_queue->push(obj); // overflow could occur here 7549 assert(res, "Will hold once we use workqueues"); 7550 while (true) { 7551 oop new_oop; 7552 if (!_work_queue->pop_local(new_oop)) { 7553 // We emptied our work_queue; check if there's stuff that can 7554 // be gotten from the overflow stack. 7555 if (CMSConcMarkingTask::get_work_from_overflow_stack( 7556 _overflow_stack, _work_queue)) { 7557 do_yield_check(); 7558 continue; 7559 } else { // done 7560 break; 7561 } 7562 } 7563 // Skip verifying header mark word below because we are 7564 // running concurrent with mutators. 7565 assert(new_oop->is_oop(true), "Oops! expected to pop an oop"); 7566 // now scan this oop's oops 7567 new_oop->oop_iterate(&pushOrMarkClosure); 7568 do_yield_check(); 7569 } 7570 assert(_work_queue->size() == 0, "tautology, emphasizing post-condition"); 7571 } 7572 7573 // Yield in response to a request from VM Thread or 7574 // from mutators. 7575 void Par_MarkFromRootsClosure::do_yield_work() { 7576 assert(_task != NULL, "sanity"); 7577 _task->yield(); 7578 } 7579 7580 // A variant of the above used for verifying CMS marking work. 7581 MarkFromRootsVerifyClosure::MarkFromRootsVerifyClosure(CMSCollector* collector, 7582 MemRegion span, 7583 CMSBitMap* verification_bm, CMSBitMap* cms_bm, 7584 CMSMarkStack* mark_stack): 7585 _collector(collector), 7586 _span(span), 7587 _verification_bm(verification_bm), 7588 _cms_bm(cms_bm), 7589 _mark_stack(mark_stack), 7590 _pam_verify_closure(collector, span, verification_bm, cms_bm, 7591 mark_stack) 7592 { 7593 assert(_mark_stack->isEmpty(), "stack should be empty"); 7594 _finger = _verification_bm->startWord(); 7595 assert(_collector->_restart_addr == NULL, "Sanity check"); 7596 assert(_span.contains(_finger), "Out of bounds _finger?"); 7597 } 7598 7599 void MarkFromRootsVerifyClosure::reset(HeapWord* addr) { 7600 assert(_mark_stack->isEmpty(), "would cause duplicates on stack"); 7601 assert(_span.contains(addr), "Out of bounds _finger?"); 7602 _finger = addr; 7603 } 7604 7605 // Should revisit to see if this should be restructured for 7606 // greater efficiency. 7607 bool MarkFromRootsVerifyClosure::do_bit(size_t offset) { 7608 // convert offset into a HeapWord* 7609 HeapWord* addr = _verification_bm->startWord() + offset; 7610 assert(_verification_bm->endWord() && addr < _verification_bm->endWord(), 7611 "address out of range"); 7612 assert(_verification_bm->isMarked(addr), "tautology"); 7613 assert(_cms_bm->isMarked(addr), "tautology"); 7614 7615 assert(_mark_stack->isEmpty(), 7616 "should drain stack to limit stack usage"); 7617 // convert addr to an oop preparatory to scanning 7618 oop obj = oop(addr); 7619 assert(obj->is_oop(), "should be an oop"); 7620 assert(_finger <= addr, "_finger runneth ahead"); 7621 // advance the finger to right end of this object 7622 _finger = addr + obj->size(); 7623 assert(_finger > addr, "we just incremented it above"); 7624 // Note: the finger doesn't advance while we drain 7625 // the stack below. 7626 bool res = _mark_stack->push(obj); 7627 assert(res, "Empty non-zero size stack should have space for single push"); 7628 while (!_mark_stack->isEmpty()) { 7629 oop new_oop = _mark_stack->pop(); 7630 assert(new_oop->is_oop(), "Oops! expected to pop an oop"); 7631 // now scan this oop's oops 7632 new_oop->oop_iterate(&_pam_verify_closure); 7633 } 7634 assert(_mark_stack->isEmpty(), "tautology, emphasizing post-condition"); 7635 return true; 7636 } 7637 7638 PushAndMarkVerifyClosure::PushAndMarkVerifyClosure( 7639 CMSCollector* collector, MemRegion span, 7640 CMSBitMap* verification_bm, CMSBitMap* cms_bm, 7641 CMSMarkStack* mark_stack): 7642 MetadataAwareOopClosure(collector->ref_processor()), 7643 _collector(collector), 7644 _span(span), 7645 _verification_bm(verification_bm), 7646 _cms_bm(cms_bm), 7647 _mark_stack(mark_stack) 7648 { } 7649 7650 void PushAndMarkVerifyClosure::do_oop(oop* p) { PushAndMarkVerifyClosure::do_oop_work(p); } 7651 void PushAndMarkVerifyClosure::do_oop(narrowOop* p) { PushAndMarkVerifyClosure::do_oop_work(p); } 7652 7653 // Upon stack overflow, we discard (part of) the stack, 7654 // remembering the least address amongst those discarded 7655 // in CMSCollector's _restart_address. 7656 void PushAndMarkVerifyClosure::handle_stack_overflow(HeapWord* lost) { 7657 // Remember the least grey address discarded 7658 HeapWord* ra = (HeapWord*)_mark_stack->least_value(lost); 7659 _collector->lower_restart_addr(ra); 7660 _mark_stack->reset(); // discard stack contents 7661 _mark_stack->expand(); // expand the stack if possible 7662 } 7663 7664 void PushAndMarkVerifyClosure::do_oop(oop obj) { 7665 assert(obj->is_oop_or_null(), "expected an oop or NULL"); 7666 HeapWord* addr = (HeapWord*)obj; 7667 if (_span.contains(addr) && !_verification_bm->isMarked(addr)) { 7668 // Oop lies in _span and isn't yet grey or black 7669 _verification_bm->mark(addr); // now grey 7670 if (!_cms_bm->isMarked(addr)) { 7671 oop(addr)->print(); 7672 gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)", 7673 addr); 7674 fatal("... aborting"); 7675 } 7676 7677 if (!_mark_stack->push(obj)) { // stack overflow 7678 if (PrintCMSStatistics != 0) { 7679 gclog_or_tty->print_cr("CMS marking stack overflow (benign) at " 7680 SIZE_FORMAT, _mark_stack->capacity()); 7681 } 7682 assert(_mark_stack->isFull(), "Else push should have succeeded"); 7683 handle_stack_overflow(addr); 7684 } 7685 // anything including and to the right of _finger 7686 // will be scanned as we iterate over the remainder of the 7687 // bit map 7688 } 7689 } 7690 7691 PushOrMarkClosure::PushOrMarkClosure(CMSCollector* collector, 7692 MemRegion span, 7693 CMSBitMap* bitMap, CMSMarkStack* markStack, 7694 HeapWord* finger, MarkFromRootsClosure* parent) : 7695 MetadataAwareOopClosure(collector->ref_processor()), 7696 _collector(collector), 7697 _span(span), 7698 _bitMap(bitMap), 7699 _markStack(markStack), 7700 _finger(finger), 7701 _parent(parent) 7702 { } 7703 7704 Par_PushOrMarkClosure::Par_PushOrMarkClosure(CMSCollector* collector, 7705 MemRegion span, 7706 CMSBitMap* bit_map, 7707 OopTaskQueue* work_queue, 7708 CMSMarkStack* overflow_stack, 7709 HeapWord* finger, 7710 HeapWord** global_finger_addr, 7711 Par_MarkFromRootsClosure* parent) : 7712 MetadataAwareOopClosure(collector->ref_processor()), 7713 _collector(collector), 7714 _whole_span(collector->_span), 7715 _span(span), 7716 _bit_map(bit_map), 7717 _work_queue(work_queue), 7718 _overflow_stack(overflow_stack), 7719 _finger(finger), 7720 _global_finger_addr(global_finger_addr), 7721 _parent(parent) 7722 { } 7723 7724 // Assumes thread-safe access by callers, who are 7725 // responsible for mutual exclusion. 7726 void CMSCollector::lower_restart_addr(HeapWord* low) { 7727 assert(_span.contains(low), "Out of bounds addr"); 7728 if (_restart_addr == NULL) { 7729 _restart_addr = low; 7730 } else { 7731 _restart_addr = MIN2(_restart_addr, low); 7732 } 7733 } 7734 7735 // Upon stack overflow, we discard (part of) the stack, 7736 // remembering the least address amongst those discarded 7737 // in CMSCollector's _restart_address. 7738 void PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) { 7739 // Remember the least grey address discarded 7740 HeapWord* ra = (HeapWord*)_markStack->least_value(lost); 7741 _collector->lower_restart_addr(ra); 7742 _markStack->reset(); // discard stack contents 7743 _markStack->expand(); // expand the stack if possible 7744 } 7745 7746 // Upon stack overflow, we discard (part of) the stack, 7747 // remembering the least address amongst those discarded 7748 // in CMSCollector's _restart_address. 7749 void Par_PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) { 7750 // We need to do this under a mutex to prevent other 7751 // workers from interfering with the work done below. 7752 MutexLockerEx ml(_overflow_stack->par_lock(), 7753 Mutex::_no_safepoint_check_flag); 7754 // Remember the least grey address discarded 7755 HeapWord* ra = (HeapWord*)_overflow_stack->least_value(lost); 7756 _collector->lower_restart_addr(ra); 7757 _overflow_stack->reset(); // discard stack contents 7758 _overflow_stack->expand(); // expand the stack if possible 7759 } 7760 7761 void PushOrMarkClosure::do_oop(oop obj) { 7762 // Ignore mark word because we are running concurrent with mutators. 7763 assert(obj->is_oop_or_null(true), "expected an oop or NULL"); 7764 HeapWord* addr = (HeapWord*)obj; 7765 if (_span.contains(addr) && !_bitMap->isMarked(addr)) { 7766 // Oop lies in _span and isn't yet grey or black 7767 _bitMap->mark(addr); // now grey 7768 if (addr < _finger) { 7769 // the bit map iteration has already either passed, or 7770 // sampled, this bit in the bit map; we'll need to 7771 // use the marking stack to scan this oop's oops. 7772 bool simulate_overflow = false; 7773 NOT_PRODUCT( 7774 if (CMSMarkStackOverflowALot && 7775 _collector->simulate_overflow()) { 7776 // simulate a stack overflow 7777 simulate_overflow = true; 7778 } 7779 ) 7780 if (simulate_overflow || !_markStack->push(obj)) { // stack overflow 7781 if (PrintCMSStatistics != 0) { 7782 gclog_or_tty->print_cr("CMS marking stack overflow (benign) at " 7783 SIZE_FORMAT, _markStack->capacity()); 7784 } 7785 assert(simulate_overflow || _markStack->isFull(), "Else push should have succeeded"); 7786 handle_stack_overflow(addr); 7787 } 7788 } 7789 // anything including and to the right of _finger 7790 // will be scanned as we iterate over the remainder of the 7791 // bit map 7792 do_yield_check(); 7793 } 7794 } 7795 7796 void PushOrMarkClosure::do_oop(oop* p) { PushOrMarkClosure::do_oop_work(p); } 7797 void PushOrMarkClosure::do_oop(narrowOop* p) { PushOrMarkClosure::do_oop_work(p); } 7798 7799 void Par_PushOrMarkClosure::do_oop(oop obj) { 7800 // Ignore mark word because we are running concurrent with mutators. 7801 assert(obj->is_oop_or_null(true), "expected an oop or NULL"); 7802 HeapWord* addr = (HeapWord*)obj; 7803 if (_whole_span.contains(addr) && !_bit_map->isMarked(addr)) { 7804 // Oop lies in _span and isn't yet grey or black 7805 // We read the global_finger (volatile read) strictly after marking oop 7806 bool res = _bit_map->par_mark(addr); // now grey 7807 volatile HeapWord** gfa = (volatile HeapWord**)_global_finger_addr; 7808 // Should we push this marked oop on our stack? 7809 // -- if someone else marked it, nothing to do 7810 // -- if target oop is above global finger nothing to do 7811 // -- if target oop is in chunk and above local finger 7812 // then nothing to do 7813 // -- else push on work queue 7814 if ( !res // someone else marked it, they will deal with it 7815 || (addr >= *gfa) // will be scanned in a later task 7816 || (_span.contains(addr) && addr >= _finger)) { // later in this chunk 7817 return; 7818 } 7819 // the bit map iteration has already either passed, or 7820 // sampled, this bit in the bit map; we'll need to 7821 // use the marking stack to scan this oop's oops. 7822 bool simulate_overflow = false; 7823 NOT_PRODUCT( 7824 if (CMSMarkStackOverflowALot && 7825 _collector->simulate_overflow()) { 7826 // simulate a stack overflow 7827 simulate_overflow = true; 7828 } 7829 ) 7830 if (simulate_overflow || 7831 !(_work_queue->push(obj) || _overflow_stack->par_push(obj))) { 7832 // stack overflow 7833 if (PrintCMSStatistics != 0) { 7834 gclog_or_tty->print_cr("CMS marking stack overflow (benign) at " 7835 SIZE_FORMAT, _overflow_stack->capacity()); 7836 } 7837 // We cannot assert that the overflow stack is full because 7838 // it may have been emptied since. 7839 assert(simulate_overflow || 7840 _work_queue->size() == _work_queue->max_elems(), 7841 "Else push should have succeeded"); 7842 handle_stack_overflow(addr); 7843 } 7844 do_yield_check(); 7845 } 7846 } 7847 7848 void Par_PushOrMarkClosure::do_oop(oop* p) { Par_PushOrMarkClosure::do_oop_work(p); } 7849 void Par_PushOrMarkClosure::do_oop(narrowOop* p) { Par_PushOrMarkClosure::do_oop_work(p); } 7850 7851 PushAndMarkClosure::PushAndMarkClosure(CMSCollector* collector, 7852 MemRegion span, 7853 ReferenceProcessor* rp, 7854 CMSBitMap* bit_map, 7855 CMSBitMap* mod_union_table, 7856 CMSMarkStack* mark_stack, 7857 bool concurrent_precleaning): 7858 MetadataAwareOopClosure(rp), 7859 _collector(collector), 7860 _span(span), 7861 _bit_map(bit_map), 7862 _mod_union_table(mod_union_table), 7863 _mark_stack(mark_stack), 7864 _concurrent_precleaning(concurrent_precleaning) 7865 { 7866 assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL"); 7867 } 7868 7869 // Grey object rescan during pre-cleaning and second checkpoint phases -- 7870 // the non-parallel version (the parallel version appears further below.) 7871 void PushAndMarkClosure::do_oop(oop obj) { 7872 // Ignore mark word verification. If during concurrent precleaning, 7873 // the object monitor may be locked. If during the checkpoint 7874 // phases, the object may already have been reached by a different 7875 // path and may be at the end of the global overflow list (so 7876 // the mark word may be NULL). 7877 assert(obj->is_oop_or_null(true /* ignore mark word */), 7878 "expected an oop or NULL"); 7879 HeapWord* addr = (HeapWord*)obj; 7880 // Check if oop points into the CMS generation 7881 // and is not marked 7882 if (_span.contains(addr) && !_bit_map->isMarked(addr)) { 7883 // a white object ... 7884 _bit_map->mark(addr); // ... now grey 7885 // push on the marking stack (grey set) 7886 bool simulate_overflow = false; 7887 NOT_PRODUCT( 7888 if (CMSMarkStackOverflowALot && 7889 _collector->simulate_overflow()) { 7890 // simulate a stack overflow 7891 simulate_overflow = true; 7892 } 7893 ) 7894 if (simulate_overflow || !_mark_stack->push(obj)) { 7895 if (_concurrent_precleaning) { 7896 // During precleaning we can just dirty the appropriate card(s) 7897 // in the mod union table, thus ensuring that the object remains 7898 // in the grey set and continue. In the case of object arrays 7899 // we need to dirty all of the cards that the object spans, 7900 // since the rescan of object arrays will be limited to the 7901 // dirty cards. 7902 // Note that no one can be interfering with us in this action 7903 // of dirtying the mod union table, so no locking or atomics 7904 // are required. 7905 if (obj->is_objArray()) { 7906 size_t sz = obj->size(); 7907 HeapWord* end_card_addr = (HeapWord*)round_to( 7908 (intptr_t)(addr+sz), CardTableModRefBS::card_size); 7909 MemRegion redirty_range = MemRegion(addr, end_card_addr); 7910 assert(!redirty_range.is_empty(), "Arithmetical tautology"); 7911 _mod_union_table->mark_range(redirty_range); 7912 } else { 7913 _mod_union_table->mark(addr); 7914 } 7915 _collector->_ser_pmc_preclean_ovflw++; 7916 } else { 7917 // During the remark phase, we need to remember this oop 7918 // in the overflow list. 7919 _collector->push_on_overflow_list(obj); 7920 _collector->_ser_pmc_remark_ovflw++; 7921 } 7922 } 7923 } 7924 } 7925 7926 Par_PushAndMarkClosure::Par_PushAndMarkClosure(CMSCollector* collector, 7927 MemRegion span, 7928 ReferenceProcessor* rp, 7929 CMSBitMap* bit_map, 7930 OopTaskQueue* work_queue): 7931 MetadataAwareOopClosure(rp), 7932 _collector(collector), 7933 _span(span), 7934 _bit_map(bit_map), 7935 _work_queue(work_queue) 7936 { 7937 assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL"); 7938 } 7939 7940 void PushAndMarkClosure::do_oop(oop* p) { PushAndMarkClosure::do_oop_work(p); } 7941 void PushAndMarkClosure::do_oop(narrowOop* p) { PushAndMarkClosure::do_oop_work(p); } 7942 7943 // Grey object rescan during second checkpoint phase -- 7944 // the parallel version. 7945 void Par_PushAndMarkClosure::do_oop(oop obj) { 7946 // In the assert below, we ignore the mark word because 7947 // this oop may point to an already visited object that is 7948 // on the overflow stack (in which case the mark word has 7949 // been hijacked for chaining into the overflow stack -- 7950 // if this is the last object in the overflow stack then 7951 // its mark word will be NULL). Because this object may 7952 // have been subsequently popped off the global overflow 7953 // stack, and the mark word possibly restored to the prototypical 7954 // value, by the time we get to examined this failing assert in 7955 // the debugger, is_oop_or_null(false) may subsequently start 7956 // to hold. 7957 assert(obj->is_oop_or_null(true), 7958 "expected an oop or NULL"); 7959 HeapWord* addr = (HeapWord*)obj; 7960 // Check if oop points into the CMS generation 7961 // and is not marked 7962 if (_span.contains(addr) && !_bit_map->isMarked(addr)) { 7963 // a white object ... 7964 // If we manage to "claim" the object, by being the 7965 // first thread to mark it, then we push it on our 7966 // marking stack 7967 if (_bit_map->par_mark(addr)) { // ... now grey 7968 // push on work queue (grey set) 7969 bool simulate_overflow = false; 7970 NOT_PRODUCT( 7971 if (CMSMarkStackOverflowALot && 7972 _collector->par_simulate_overflow()) { 7973 // simulate a stack overflow 7974 simulate_overflow = true; 7975 } 7976 ) 7977 if (simulate_overflow || !_work_queue->push(obj)) { 7978 _collector->par_push_on_overflow_list(obj); 7979 _collector->_par_pmc_remark_ovflw++; // imprecise OK: no need to CAS 7980 } 7981 } // Else, some other thread got there first 7982 } 7983 } 7984 7985 void Par_PushAndMarkClosure::do_oop(oop* p) { Par_PushAndMarkClosure::do_oop_work(p); } 7986 void Par_PushAndMarkClosure::do_oop(narrowOop* p) { Par_PushAndMarkClosure::do_oop_work(p); } 7987 7988 void CMSPrecleanRefsYieldClosure::do_yield_work() { 7989 Mutex* bml = _collector->bitMapLock(); 7990 assert_lock_strong(bml); 7991 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 7992 "CMS thread should hold CMS token"); 7993 7994 bml->unlock(); 7995 ConcurrentMarkSweepThread::desynchronize(true); 7996 7997 ConcurrentMarkSweepThread::acknowledge_yield_request(); 7998 7999 _collector->stopTimer(); 8000 if (PrintCMSStatistics != 0) { 8001 _collector->incrementYields(); 8002 } 8003 _collector->icms_wait(); 8004 8005 // See the comment in coordinator_yield() 8006 for (unsigned i = 0; i < CMSYieldSleepCount && 8007 ConcurrentMarkSweepThread::should_yield() && 8008 !CMSCollector::foregroundGCIsActive(); ++i) { 8009 os::sleep(Thread::current(), 1, false); 8010 ConcurrentMarkSweepThread::acknowledge_yield_request(); 8011 } 8012 8013 ConcurrentMarkSweepThread::synchronize(true); 8014 bml->lock(); 8015 8016 _collector->startTimer(); 8017 } 8018 8019 bool CMSPrecleanRefsYieldClosure::should_return() { 8020 if (ConcurrentMarkSweepThread::should_yield()) { 8021 do_yield_work(); 8022 } 8023 return _collector->foregroundGCIsActive(); 8024 } 8025 8026 void MarkFromDirtyCardsClosure::do_MemRegion(MemRegion mr) { 8027 assert(((size_t)mr.start())%CardTableModRefBS::card_size_in_words == 0, 8028 "mr should be aligned to start at a card boundary"); 8029 // We'd like to assert: 8030 // assert(mr.word_size()%CardTableModRefBS::card_size_in_words == 0, 8031 // "mr should be a range of cards"); 8032 // However, that would be too strong in one case -- the last 8033 // partition ends at _unallocated_block which, in general, can be 8034 // an arbitrary boundary, not necessarily card aligned. 8035 if (PrintCMSStatistics != 0) { 8036 _num_dirty_cards += 8037 mr.word_size()/CardTableModRefBS::card_size_in_words; 8038 } 8039 _space->object_iterate_mem(mr, &_scan_cl); 8040 } 8041 8042 SweepClosure::SweepClosure(CMSCollector* collector, 8043 ConcurrentMarkSweepGeneration* g, 8044 CMSBitMap* bitMap, bool should_yield) : 8045 _collector(collector), 8046 _g(g), 8047 _sp(g->cmsSpace()), 8048 _limit(_sp->sweep_limit()), 8049 _freelistLock(_sp->freelistLock()), 8050 _bitMap(bitMap), 8051 _yield(should_yield), 8052 _inFreeRange(false), // No free range at beginning of sweep 8053 _freeRangeInFreeLists(false), // No free range at beginning of sweep 8054 _lastFreeRangeCoalesced(false), 8055 _freeFinger(g->used_region().start()) 8056 { 8057 NOT_PRODUCT( 8058 _numObjectsFreed = 0; 8059 _numWordsFreed = 0; 8060 _numObjectsLive = 0; 8061 _numWordsLive = 0; 8062 _numObjectsAlreadyFree = 0; 8063 _numWordsAlreadyFree = 0; 8064 _last_fc = NULL; 8065 8066 _sp->initializeIndexedFreeListArrayReturnedBytes(); 8067 _sp->dictionary()->initialize_dict_returned_bytes(); 8068 ) 8069 assert(_limit >= _sp->bottom() && _limit <= _sp->end(), 8070 "sweep _limit out of bounds"); 8071 if (CMSTraceSweeper) { 8072 gclog_or_tty->print_cr("\n====================\nStarting new sweep with limit " PTR_FORMAT, 8073 _limit); 8074 } 8075 } 8076 8077 void SweepClosure::print_on(outputStream* st) const { 8078 tty->print_cr("_sp = [" PTR_FORMAT "," PTR_FORMAT ")", 8079 _sp->bottom(), _sp->end()); 8080 tty->print_cr("_limit = " PTR_FORMAT, _limit); 8081 tty->print_cr("_freeFinger = " PTR_FORMAT, _freeFinger); 8082 NOT_PRODUCT(tty->print_cr("_last_fc = " PTR_FORMAT, _last_fc);) 8083 tty->print_cr("_inFreeRange = %d, _freeRangeInFreeLists = %d, _lastFreeRangeCoalesced = %d", 8084 _inFreeRange, _freeRangeInFreeLists, _lastFreeRangeCoalesced); 8085 } 8086 8087 #ifndef PRODUCT 8088 // Assertion checking only: no useful work in product mode -- 8089 // however, if any of the flags below become product flags, 8090 // you may need to review this code to see if it needs to be 8091 // enabled in product mode. 8092 SweepClosure::~SweepClosure() { 8093 assert_lock_strong(_freelistLock); 8094 assert(_limit >= _sp->bottom() && _limit <= _sp->end(), 8095 "sweep _limit out of bounds"); 8096 if (inFreeRange()) { 8097 warning("inFreeRange() should have been reset; dumping state of SweepClosure"); 8098 print(); 8099 ShouldNotReachHere(); 8100 } 8101 if (Verbose && PrintGC) { 8102 gclog_or_tty->print("Collected "SIZE_FORMAT" objects, " SIZE_FORMAT " bytes", 8103 _numObjectsFreed, _numWordsFreed*sizeof(HeapWord)); 8104 gclog_or_tty->print_cr("\nLive "SIZE_FORMAT" objects, " 8105 SIZE_FORMAT" bytes " 8106 "Already free "SIZE_FORMAT" objects, "SIZE_FORMAT" bytes", 8107 _numObjectsLive, _numWordsLive*sizeof(HeapWord), 8108 _numObjectsAlreadyFree, _numWordsAlreadyFree*sizeof(HeapWord)); 8109 size_t totalBytes = (_numWordsFreed + _numWordsLive + _numWordsAlreadyFree) 8110 * sizeof(HeapWord); 8111 gclog_or_tty->print_cr("Total sweep: "SIZE_FORMAT" bytes", totalBytes); 8112 8113 if (PrintCMSStatistics && CMSVerifyReturnedBytes) { 8114 size_t indexListReturnedBytes = _sp->sumIndexedFreeListArrayReturnedBytes(); 8115 size_t dict_returned_bytes = _sp->dictionary()->sum_dict_returned_bytes(); 8116 size_t returned_bytes = indexListReturnedBytes + dict_returned_bytes; 8117 gclog_or_tty->print("Returned "SIZE_FORMAT" bytes", returned_bytes); 8118 gclog_or_tty->print(" Indexed List Returned "SIZE_FORMAT" bytes", 8119 indexListReturnedBytes); 8120 gclog_or_tty->print_cr(" Dictionary Returned "SIZE_FORMAT" bytes", 8121 dict_returned_bytes); 8122 } 8123 } 8124 if (CMSTraceSweeper) { 8125 gclog_or_tty->print_cr("end of sweep with _limit = " PTR_FORMAT "\n================", 8126 _limit); 8127 } 8128 } 8129 #endif // PRODUCT 8130 8131 void SweepClosure::initialize_free_range(HeapWord* freeFinger, 8132 bool freeRangeInFreeLists) { 8133 if (CMSTraceSweeper) { 8134 gclog_or_tty->print("---- Start free range at " PTR_FORMAT " with free block (%d)\n", 8135 freeFinger, freeRangeInFreeLists); 8136 } 8137 assert(!inFreeRange(), "Trampling existing free range"); 8138 set_inFreeRange(true); 8139 set_lastFreeRangeCoalesced(false); 8140 8141 set_freeFinger(freeFinger); 8142 set_freeRangeInFreeLists(freeRangeInFreeLists); 8143 if (CMSTestInFreeList) { 8144 if (freeRangeInFreeLists) { 8145 FreeChunk* fc = (FreeChunk*) freeFinger; 8146 assert(fc->is_free(), "A chunk on the free list should be free."); 8147 assert(fc->size() > 0, "Free range should have a size"); 8148 assert(_sp->verify_chunk_in_free_list(fc), "Chunk is not in free lists"); 8149 } 8150 } 8151 } 8152 8153 // Note that the sweeper runs concurrently with mutators. Thus, 8154 // it is possible for direct allocation in this generation to happen 8155 // in the middle of the sweep. Note that the sweeper also coalesces 8156 // contiguous free blocks. Thus, unless the sweeper and the allocator 8157 // synchronize appropriately freshly allocated blocks may get swept up. 8158 // This is accomplished by the sweeper locking the free lists while 8159 // it is sweeping. Thus blocks that are determined to be free are 8160 // indeed free. There is however one additional complication: 8161 // blocks that have been allocated since the final checkpoint and 8162 // mark, will not have been marked and so would be treated as 8163 // unreachable and swept up. To prevent this, the allocator marks 8164 // the bit map when allocating during the sweep phase. This leads, 8165 // however, to a further complication -- objects may have been allocated 8166 // but not yet initialized -- in the sense that the header isn't yet 8167 // installed. The sweeper can not then determine the size of the block 8168 // in order to skip over it. To deal with this case, we use a technique 8169 // (due to Printezis) to encode such uninitialized block sizes in the 8170 // bit map. Since the bit map uses a bit per every HeapWord, but the 8171 // CMS generation has a minimum object size of 3 HeapWords, it follows 8172 // that "normal marks" won't be adjacent in the bit map (there will 8173 // always be at least two 0 bits between successive 1 bits). We make use 8174 // of these "unused" bits to represent uninitialized blocks -- the bit 8175 // corresponding to the start of the uninitialized object and the next 8176 // bit are both set. Finally, a 1 bit marks the end of the object that 8177 // started with the two consecutive 1 bits to indicate its potentially 8178 // uninitialized state. 8179 8180 size_t SweepClosure::do_blk_careful(HeapWord* addr) { 8181 FreeChunk* fc = (FreeChunk*)addr; 8182 size_t res; 8183 8184 // Check if we are done sweeping. Below we check "addr >= _limit" rather 8185 // than "addr == _limit" because although _limit was a block boundary when 8186 // we started the sweep, it may no longer be one because heap expansion 8187 // may have caused us to coalesce the block ending at the address _limit 8188 // with a newly expanded chunk (this happens when _limit was set to the 8189 // previous _end of the space), so we may have stepped past _limit: 8190 // see the following Zeno-like trail of CRs 6977970, 7008136, 7042740. 8191 if (addr >= _limit) { // we have swept up to or past the limit: finish up 8192 assert(_limit >= _sp->bottom() && _limit <= _sp->end(), 8193 "sweep _limit out of bounds"); 8194 assert(addr < _sp->end(), "addr out of bounds"); 8195 // Flush any free range we might be holding as a single 8196 // coalesced chunk to the appropriate free list. 8197 if (inFreeRange()) { 8198 assert(freeFinger() >= _sp->bottom() && freeFinger() < _limit, 8199 err_msg("freeFinger() " PTR_FORMAT" is out-of-bounds", freeFinger())); 8200 flush_cur_free_chunk(freeFinger(), 8201 pointer_delta(addr, freeFinger())); 8202 if (CMSTraceSweeper) { 8203 gclog_or_tty->print("Sweep: last chunk: "); 8204 gclog_or_tty->print("put_free_blk " PTR_FORMAT " ("SIZE_FORMAT") " 8205 "[coalesced:%d]\n", 8206 freeFinger(), pointer_delta(addr, freeFinger()), 8207 lastFreeRangeCoalesced() ? 1 : 0); 8208 } 8209 } 8210 8211 // help the iterator loop finish 8212 return pointer_delta(_sp->end(), addr); 8213 } 8214 8215 assert(addr < _limit, "sweep invariant"); 8216 // check if we should yield 8217 do_yield_check(addr); 8218 if (fc->is_free()) { 8219 // Chunk that is already free 8220 res = fc->size(); 8221 do_already_free_chunk(fc); 8222 debug_only(_sp->verifyFreeLists()); 8223 // If we flush the chunk at hand in lookahead_and_flush() 8224 // and it's coalesced with a preceding chunk, then the 8225 // process of "mangling" the payload of the coalesced block 8226 // will cause erasure of the size information from the 8227 // (erstwhile) header of all the coalesced blocks but the 8228 // first, so the first disjunct in the assert will not hold 8229 // in that specific case (in which case the second disjunct 8230 // will hold). 8231 assert(res == fc->size() || ((HeapWord*)fc) + res >= _limit, 8232 "Otherwise the size info doesn't change at this step"); 8233 NOT_PRODUCT( 8234 _numObjectsAlreadyFree++; 8235 _numWordsAlreadyFree += res; 8236 ) 8237 NOT_PRODUCT(_last_fc = fc;) 8238 } else if (!_bitMap->isMarked(addr)) { 8239 // Chunk is fresh garbage 8240 res = do_garbage_chunk(fc); 8241 debug_only(_sp->verifyFreeLists()); 8242 NOT_PRODUCT( 8243 _numObjectsFreed++; 8244 _numWordsFreed += res; 8245 ) 8246 } else { 8247 // Chunk that is alive. 8248 res = do_live_chunk(fc); 8249 debug_only(_sp->verifyFreeLists()); 8250 NOT_PRODUCT( 8251 _numObjectsLive++; 8252 _numWordsLive += res; 8253 ) 8254 } 8255 return res; 8256 } 8257 8258 // For the smart allocation, record following 8259 // split deaths - a free chunk is removed from its free list because 8260 // it is being split into two or more chunks. 8261 // split birth - a free chunk is being added to its free list because 8262 // a larger free chunk has been split and resulted in this free chunk. 8263 // coal death - a free chunk is being removed from its free list because 8264 // it is being coalesced into a large free chunk. 8265 // coal birth - a free chunk is being added to its free list because 8266 // it was created when two or more free chunks where coalesced into 8267 // this free chunk. 8268 // 8269 // These statistics are used to determine the desired number of free 8270 // chunks of a given size. The desired number is chosen to be relative 8271 // to the end of a CMS sweep. The desired number at the end of a sweep 8272 // is the 8273 // count-at-end-of-previous-sweep (an amount that was enough) 8274 // - count-at-beginning-of-current-sweep (the excess) 8275 // + split-births (gains in this size during interval) 8276 // - split-deaths (demands on this size during interval) 8277 // where the interval is from the end of one sweep to the end of the 8278 // next. 8279 // 8280 // When sweeping the sweeper maintains an accumulated chunk which is 8281 // the chunk that is made up of chunks that have been coalesced. That 8282 // will be termed the left-hand chunk. A new chunk of garbage that 8283 // is being considered for coalescing will be referred to as the 8284 // right-hand chunk. 8285 // 8286 // When making a decision on whether to coalesce a right-hand chunk with 8287 // the current left-hand chunk, the current count vs. the desired count 8288 // of the left-hand chunk is considered. Also if the right-hand chunk 8289 // is near the large chunk at the end of the heap (see 8290 // ConcurrentMarkSweepGeneration::isNearLargestChunk()), then the 8291 // left-hand chunk is coalesced. 8292 // 8293 // When making a decision about whether to split a chunk, the desired count 8294 // vs. the current count of the candidate to be split is also considered. 8295 // If the candidate is underpopulated (currently fewer chunks than desired) 8296 // a chunk of an overpopulated (currently more chunks than desired) size may 8297 // be chosen. The "hint" associated with a free list, if non-null, points 8298 // to a free list which may be overpopulated. 8299 // 8300 8301 void SweepClosure::do_already_free_chunk(FreeChunk* fc) { 8302 const size_t size = fc->size(); 8303 // Chunks that cannot be coalesced are not in the 8304 // free lists. 8305 if (CMSTestInFreeList && !fc->cantCoalesce()) { 8306 assert(_sp->verify_chunk_in_free_list(fc), 8307 "free chunk should be in free lists"); 8308 } 8309 // a chunk that is already free, should not have been 8310 // marked in the bit map 8311 HeapWord* const addr = (HeapWord*) fc; 8312 assert(!_bitMap->isMarked(addr), "free chunk should be unmarked"); 8313 // Verify that the bit map has no bits marked between 8314 // addr and purported end of this block. 8315 _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size); 8316 8317 // Some chunks cannot be coalesced under any circumstances. 8318 // See the definition of cantCoalesce(). 8319 if (!fc->cantCoalesce()) { 8320 // This chunk can potentially be coalesced. 8321 if (_sp->adaptive_freelists()) { 8322 // All the work is done in 8323 do_post_free_or_garbage_chunk(fc, size); 8324 } else { // Not adaptive free lists 8325 // this is a free chunk that can potentially be coalesced by the sweeper; 8326 if (!inFreeRange()) { 8327 // if the next chunk is a free block that can't be coalesced 8328 // it doesn't make sense to remove this chunk from the free lists 8329 FreeChunk* nextChunk = (FreeChunk*)(addr + size); 8330 assert((HeapWord*)nextChunk <= _sp->end(), "Chunk size out of bounds?"); 8331 if ((HeapWord*)nextChunk < _sp->end() && // There is another free chunk to the right ... 8332 nextChunk->is_free() && // ... which is free... 8333 nextChunk->cantCoalesce()) { // ... but can't be coalesced 8334 // nothing to do 8335 } else { 8336 // Potentially the start of a new free range: 8337 // Don't eagerly remove it from the free lists. 8338 // No need to remove it if it will just be put 8339 // back again. (Also from a pragmatic point of view 8340 // if it is a free block in a region that is beyond 8341 // any allocated blocks, an assertion will fail) 8342 // Remember the start of a free run. 8343 initialize_free_range(addr, true); 8344 // end - can coalesce with next chunk 8345 } 8346 } else { 8347 // the midst of a free range, we are coalescing 8348 print_free_block_coalesced(fc); 8349 if (CMSTraceSweeper) { 8350 gclog_or_tty->print(" -- pick up free block " PTR_FORMAT " (" SIZE_FORMAT ")\n", fc, size); 8351 } 8352 // remove it from the free lists 8353 _sp->removeFreeChunkFromFreeLists(fc); 8354 set_lastFreeRangeCoalesced(true); 8355 // If the chunk is being coalesced and the current free range is 8356 // in the free lists, remove the current free range so that it 8357 // will be returned to the free lists in its entirety - all 8358 // the coalesced pieces included. 8359 if (freeRangeInFreeLists()) { 8360 FreeChunk* ffc = (FreeChunk*) freeFinger(); 8361 assert(ffc->size() == pointer_delta(addr, freeFinger()), 8362 "Size of free range is inconsistent with chunk size."); 8363 if (CMSTestInFreeList) { 8364 assert(_sp->verify_chunk_in_free_list(ffc), 8365 "free range is not in free lists"); 8366 } 8367 _sp->removeFreeChunkFromFreeLists(ffc); 8368 set_freeRangeInFreeLists(false); 8369 } 8370 } 8371 } 8372 // Note that if the chunk is not coalescable (the else arm 8373 // below), we unconditionally flush, without needing to do 8374 // a "lookahead," as we do below. 8375 if (inFreeRange()) lookahead_and_flush(fc, size); 8376 } else { 8377 // Code path common to both original and adaptive free lists. 8378 8379 // cant coalesce with previous block; this should be treated 8380 // as the end of a free run if any 8381 if (inFreeRange()) { 8382 // we kicked some butt; time to pick up the garbage 8383 assert(freeFinger() < addr, "freeFinger points too high"); 8384 flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger())); 8385 } 8386 // else, nothing to do, just continue 8387 } 8388 } 8389 8390 size_t SweepClosure::do_garbage_chunk(FreeChunk* fc) { 8391 // This is a chunk of garbage. It is not in any free list. 8392 // Add it to a free list or let it possibly be coalesced into 8393 // a larger chunk. 8394 HeapWord* const addr = (HeapWord*) fc; 8395 const size_t size = CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size()); 8396 8397 if (_sp->adaptive_freelists()) { 8398 // Verify that the bit map has no bits marked between 8399 // addr and purported end of just dead object. 8400 _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size); 8401 8402 do_post_free_or_garbage_chunk(fc, size); 8403 } else { 8404 if (!inFreeRange()) { 8405 // start of a new free range 8406 assert(size > 0, "A free range should have a size"); 8407 initialize_free_range(addr, false); 8408 } else { 8409 // this will be swept up when we hit the end of the 8410 // free range 8411 if (CMSTraceSweeper) { 8412 gclog_or_tty->print(" -- pick up garbage " PTR_FORMAT " (" SIZE_FORMAT ")\n", fc, size); 8413 } 8414 // If the chunk is being coalesced and the current free range is 8415 // in the free lists, remove the current free range so that it 8416 // will be returned to the free lists in its entirety - all 8417 // the coalesced pieces included. 8418 if (freeRangeInFreeLists()) { 8419 FreeChunk* ffc = (FreeChunk*)freeFinger(); 8420 assert(ffc->size() == pointer_delta(addr, freeFinger()), 8421 "Size of free range is inconsistent with chunk size."); 8422 if (CMSTestInFreeList) { 8423 assert(_sp->verify_chunk_in_free_list(ffc), 8424 "free range is not in free lists"); 8425 } 8426 _sp->removeFreeChunkFromFreeLists(ffc); 8427 set_freeRangeInFreeLists(false); 8428 } 8429 set_lastFreeRangeCoalesced(true); 8430 } 8431 // this will be swept up when we hit the end of the free range 8432 8433 // Verify that the bit map has no bits marked between 8434 // addr and purported end of just dead object. 8435 _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size); 8436 } 8437 assert(_limit >= addr + size, 8438 "A freshly garbage chunk can't possibly straddle over _limit"); 8439 if (inFreeRange()) lookahead_and_flush(fc, size); 8440 return size; 8441 } 8442 8443 size_t SweepClosure::do_live_chunk(FreeChunk* fc) { 8444 HeapWord* addr = (HeapWord*) fc; 8445 // The sweeper has just found a live object. Return any accumulated 8446 // left hand chunk to the free lists. 8447 if (inFreeRange()) { 8448 assert(freeFinger() < addr, "freeFinger points too high"); 8449 flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger())); 8450 } 8451 8452 // This object is live: we'd normally expect this to be 8453 // an oop, and like to assert the following: 8454 // assert(oop(addr)->is_oop(), "live block should be an oop"); 8455 // However, as we commented above, this may be an object whose 8456 // header hasn't yet been initialized. 8457 size_t size; 8458 assert(_bitMap->isMarked(addr), "Tautology for this control point"); 8459 if (_bitMap->isMarked(addr + 1)) { 8460 // Determine the size from the bit map, rather than trying to 8461 // compute it from the object header. 8462 HeapWord* nextOneAddr = _bitMap->getNextMarkedWordAddress(addr + 2); 8463 size = pointer_delta(nextOneAddr + 1, addr); 8464 assert(size == CompactibleFreeListSpace::adjustObjectSize(size), 8465 "alignment problem"); 8466 8467 #ifdef ASSERT 8468 if (oop(addr)->klass_or_null() != NULL) { 8469 // Ignore mark word because we are running concurrent with mutators 8470 assert(oop(addr)->is_oop(true), "live block should be an oop"); 8471 assert(size == 8472 CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size()), 8473 "P-mark and computed size do not agree"); 8474 } 8475 #endif 8476 8477 } else { 8478 // This should be an initialized object that's alive. 8479 assert(oop(addr)->klass_or_null() != NULL, 8480 "Should be an initialized object"); 8481 // Ignore mark word because we are running concurrent with mutators 8482 assert(oop(addr)->is_oop(true), "live block should be an oop"); 8483 // Verify that the bit map has no bits marked between 8484 // addr and purported end of this block. 8485 size = CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size()); 8486 assert(size >= 3, "Necessary for Printezis marks to work"); 8487 assert(!_bitMap->isMarked(addr+1), "Tautology for this control point"); 8488 DEBUG_ONLY(_bitMap->verifyNoOneBitsInRange(addr+2, addr+size);) 8489 } 8490 return size; 8491 } 8492 8493 void SweepClosure::do_post_free_or_garbage_chunk(FreeChunk* fc, 8494 size_t chunkSize) { 8495 // do_post_free_or_garbage_chunk() should only be called in the case 8496 // of the adaptive free list allocator. 8497 const bool fcInFreeLists = fc->is_free(); 8498 assert(_sp->adaptive_freelists(), "Should only be used in this case."); 8499 assert((HeapWord*)fc <= _limit, "sweep invariant"); 8500 if (CMSTestInFreeList && fcInFreeLists) { 8501 assert(_sp->verify_chunk_in_free_list(fc), "free chunk is not in free lists"); 8502 } 8503 8504 if (CMSTraceSweeper) { 8505 gclog_or_tty->print_cr(" -- pick up another chunk at " PTR_FORMAT " (" SIZE_FORMAT ")", fc, chunkSize); 8506 } 8507 8508 HeapWord* const fc_addr = (HeapWord*) fc; 8509 8510 bool coalesce; 8511 const size_t left = pointer_delta(fc_addr, freeFinger()); 8512 const size_t right = chunkSize; 8513 switch (FLSCoalescePolicy) { 8514 // numeric value forms a coalition aggressiveness metric 8515 case 0: { // never coalesce 8516 coalesce = false; 8517 break; 8518 } 8519 case 1: { // coalesce if left & right chunks on overpopulated lists 8520 coalesce = _sp->coalOverPopulated(left) && 8521 _sp->coalOverPopulated(right); 8522 break; 8523 } 8524 case 2: { // coalesce if left chunk on overpopulated list (default) 8525 coalesce = _sp->coalOverPopulated(left); 8526 break; 8527 } 8528 case 3: { // coalesce if left OR right chunk on overpopulated list 8529 coalesce = _sp->coalOverPopulated(left) || 8530 _sp->coalOverPopulated(right); 8531 break; 8532 } 8533 case 4: { // always coalesce 8534 coalesce = true; 8535 break; 8536 } 8537 default: 8538 ShouldNotReachHere(); 8539 } 8540 8541 // Should the current free range be coalesced? 8542 // If the chunk is in a free range and either we decided to coalesce above 8543 // or the chunk is near the large block at the end of the heap 8544 // (isNearLargestChunk() returns true), then coalesce this chunk. 8545 const bool doCoalesce = inFreeRange() 8546 && (coalesce || _g->isNearLargestChunk(fc_addr)); 8547 if (doCoalesce) { 8548 // Coalesce the current free range on the left with the new 8549 // chunk on the right. If either is on a free list, 8550 // it must be removed from the list and stashed in the closure. 8551 if (freeRangeInFreeLists()) { 8552 FreeChunk* const ffc = (FreeChunk*)freeFinger(); 8553 assert(ffc->size() == pointer_delta(fc_addr, freeFinger()), 8554 "Size of free range is inconsistent with chunk size."); 8555 if (CMSTestInFreeList) { 8556 assert(_sp->verify_chunk_in_free_list(ffc), 8557 "Chunk is not in free lists"); 8558 } 8559 _sp->coalDeath(ffc->size()); 8560 _sp->removeFreeChunkFromFreeLists(ffc); 8561 set_freeRangeInFreeLists(false); 8562 } 8563 if (fcInFreeLists) { 8564 _sp->coalDeath(chunkSize); 8565 assert(fc->size() == chunkSize, 8566 "The chunk has the wrong size or is not in the free lists"); 8567 _sp->removeFreeChunkFromFreeLists(fc); 8568 } 8569 set_lastFreeRangeCoalesced(true); 8570 print_free_block_coalesced(fc); 8571 } else { // not in a free range and/or should not coalesce 8572 // Return the current free range and start a new one. 8573 if (inFreeRange()) { 8574 // In a free range but cannot coalesce with the right hand chunk. 8575 // Put the current free range into the free lists. 8576 flush_cur_free_chunk(freeFinger(), 8577 pointer_delta(fc_addr, freeFinger())); 8578 } 8579 // Set up for new free range. Pass along whether the right hand 8580 // chunk is in the free lists. 8581 initialize_free_range((HeapWord*)fc, fcInFreeLists); 8582 } 8583 } 8584 8585 // Lookahead flush: 8586 // If we are tracking a free range, and this is the last chunk that 8587 // we'll look at because its end crosses past _limit, we'll preemptively 8588 // flush it along with any free range we may be holding on to. Note that 8589 // this can be the case only for an already free or freshly garbage 8590 // chunk. If this block is an object, it can never straddle 8591 // over _limit. The "straddling" occurs when _limit is set at 8592 // the previous end of the space when this cycle started, and 8593 // a subsequent heap expansion caused the previously co-terminal 8594 // free block to be coalesced with the newly expanded portion, 8595 // thus rendering _limit a non-block-boundary making it dangerous 8596 // for the sweeper to step over and examine. 8597 void SweepClosure::lookahead_and_flush(FreeChunk* fc, size_t chunk_size) { 8598 assert(inFreeRange(), "Should only be called if currently in a free range."); 8599 HeapWord* const eob = ((HeapWord*)fc) + chunk_size; 8600 assert(_sp->used_region().contains(eob - 1), 8601 err_msg("eob = " PTR_FORMAT " eob-1 = " PTR_FORMAT " _limit = " PTR_FORMAT 8602 " out of bounds wrt _sp = [" PTR_FORMAT "," PTR_FORMAT ")" 8603 " when examining fc = " PTR_FORMAT "(" SIZE_FORMAT ")", 8604 eob, eob-1, _limit, _sp->bottom(), _sp->end(), fc, chunk_size)); 8605 if (eob >= _limit) { 8606 assert(eob == _limit || fc->is_free(), "Only a free chunk should allow us to cross over the limit"); 8607 if (CMSTraceSweeper) { 8608 gclog_or_tty->print_cr("_limit " PTR_FORMAT " reached or crossed by block " 8609 "[" PTR_FORMAT "," PTR_FORMAT ") in space " 8610 "[" PTR_FORMAT "," PTR_FORMAT ")", 8611 _limit, fc, eob, _sp->bottom(), _sp->end()); 8612 } 8613 // Return the storage we are tracking back into the free lists. 8614 if (CMSTraceSweeper) { 8615 gclog_or_tty->print_cr("Flushing ... "); 8616 } 8617 assert(freeFinger() < eob, "Error"); 8618 flush_cur_free_chunk( freeFinger(), pointer_delta(eob, freeFinger())); 8619 } 8620 } 8621 8622 void SweepClosure::flush_cur_free_chunk(HeapWord* chunk, size_t size) { 8623 assert(inFreeRange(), "Should only be called if currently in a free range."); 8624 assert(size > 0, 8625 "A zero sized chunk cannot be added to the free lists."); 8626 if (!freeRangeInFreeLists()) { 8627 if (CMSTestInFreeList) { 8628 FreeChunk* fc = (FreeChunk*) chunk; 8629 fc->set_size(size); 8630 assert(!_sp->verify_chunk_in_free_list(fc), 8631 "chunk should not be in free lists yet"); 8632 } 8633 if (CMSTraceSweeper) { 8634 gclog_or_tty->print_cr(" -- add free block " PTR_FORMAT " (" SIZE_FORMAT ") to free lists", 8635 chunk, size); 8636 } 8637 // A new free range is going to be starting. The current 8638 // free range has not been added to the free lists yet or 8639 // was removed so add it back. 8640 // If the current free range was coalesced, then the death 8641 // of the free range was recorded. Record a birth now. 8642 if (lastFreeRangeCoalesced()) { 8643 _sp->coalBirth(size); 8644 } 8645 _sp->addChunkAndRepairOffsetTable(chunk, size, 8646 lastFreeRangeCoalesced()); 8647 } else if (CMSTraceSweeper) { 8648 gclog_or_tty->print_cr("Already in free list: nothing to flush"); 8649 } 8650 set_inFreeRange(false); 8651 set_freeRangeInFreeLists(false); 8652 } 8653 8654 // We take a break if we've been at this for a while, 8655 // so as to avoid monopolizing the locks involved. 8656 void SweepClosure::do_yield_work(HeapWord* addr) { 8657 // Return current free chunk being used for coalescing (if any) 8658 // to the appropriate freelist. After yielding, the next 8659 // free block encountered will start a coalescing range of 8660 // free blocks. If the next free block is adjacent to the 8661 // chunk just flushed, they will need to wait for the next 8662 // sweep to be coalesced. 8663 if (inFreeRange()) { 8664 flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger())); 8665 } 8666 8667 // First give up the locks, then yield, then re-lock. 8668 // We should probably use a constructor/destructor idiom to 8669 // do this unlock/lock or modify the MutexUnlocker class to 8670 // serve our purpose. XXX 8671 assert_lock_strong(_bitMap->lock()); 8672 assert_lock_strong(_freelistLock); 8673 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 8674 "CMS thread should hold CMS token"); 8675 _bitMap->lock()->unlock(); 8676 _freelistLock->unlock(); 8677 ConcurrentMarkSweepThread::desynchronize(true); 8678 ConcurrentMarkSweepThread::acknowledge_yield_request(); 8679 _collector->stopTimer(); 8680 if (PrintCMSStatistics != 0) { 8681 _collector->incrementYields(); 8682 } 8683 _collector->icms_wait(); 8684 8685 // See the comment in coordinator_yield() 8686 for (unsigned i = 0; i < CMSYieldSleepCount && 8687 ConcurrentMarkSweepThread::should_yield() && 8688 !CMSCollector::foregroundGCIsActive(); ++i) { 8689 os::sleep(Thread::current(), 1, false); 8690 ConcurrentMarkSweepThread::acknowledge_yield_request(); 8691 } 8692 8693 ConcurrentMarkSweepThread::synchronize(true); 8694 _freelistLock->lock(); 8695 _bitMap->lock()->lock_without_safepoint_check(); 8696 _collector->startTimer(); 8697 } 8698 8699 #ifndef PRODUCT 8700 // This is actually very useful in a product build if it can 8701 // be called from the debugger. Compile it into the product 8702 // as needed. 8703 bool debug_verify_chunk_in_free_list(FreeChunk* fc) { 8704 return debug_cms_space->verify_chunk_in_free_list(fc); 8705 } 8706 #endif 8707 8708 void SweepClosure::print_free_block_coalesced(FreeChunk* fc) const { 8709 if (CMSTraceSweeper) { 8710 gclog_or_tty->print_cr("Sweep:coal_free_blk " PTR_FORMAT " (" SIZE_FORMAT ")", 8711 fc, fc->size()); 8712 } 8713 } 8714 8715 // CMSIsAliveClosure 8716 bool CMSIsAliveClosure::do_object_b(oop obj) { 8717 HeapWord* addr = (HeapWord*)obj; 8718 return addr != NULL && 8719 (!_span.contains(addr) || _bit_map->isMarked(addr)); 8720 } 8721 8722 8723 CMSKeepAliveClosure::CMSKeepAliveClosure( CMSCollector* collector, 8724 MemRegion span, 8725 CMSBitMap* bit_map, CMSMarkStack* mark_stack, 8726 bool cpc): 8727 _collector(collector), 8728 _span(span), 8729 _bit_map(bit_map), 8730 _mark_stack(mark_stack), 8731 _concurrent_precleaning(cpc) { 8732 assert(!_span.is_empty(), "Empty span could spell trouble"); 8733 } 8734 8735 8736 // CMSKeepAliveClosure: the serial version 8737 void CMSKeepAliveClosure::do_oop(oop obj) { 8738 HeapWord* addr = (HeapWord*)obj; 8739 if (_span.contains(addr) && 8740 !_bit_map->isMarked(addr)) { 8741 _bit_map->mark(addr); 8742 bool simulate_overflow = false; 8743 NOT_PRODUCT( 8744 if (CMSMarkStackOverflowALot && 8745 _collector->simulate_overflow()) { 8746 // simulate a stack overflow 8747 simulate_overflow = true; 8748 } 8749 ) 8750 if (simulate_overflow || !_mark_stack->push(obj)) { 8751 if (_concurrent_precleaning) { 8752 // We dirty the overflown object and let the remark 8753 // phase deal with it. 8754 assert(_collector->overflow_list_is_empty(), "Error"); 8755 // In the case of object arrays, we need to dirty all of 8756 // the cards that the object spans. No locking or atomics 8757 // are needed since no one else can be mutating the mod union 8758 // table. 8759 if (obj->is_objArray()) { 8760 size_t sz = obj->size(); 8761 HeapWord* end_card_addr = 8762 (HeapWord*)round_to((intptr_t)(addr+sz), CardTableModRefBS::card_size); 8763 MemRegion redirty_range = MemRegion(addr, end_card_addr); 8764 assert(!redirty_range.is_empty(), "Arithmetical tautology"); 8765 _collector->_modUnionTable.mark_range(redirty_range); 8766 } else { 8767 _collector->_modUnionTable.mark(addr); 8768 } 8769 _collector->_ser_kac_preclean_ovflw++; 8770 } else { 8771 _collector->push_on_overflow_list(obj); 8772 _collector->_ser_kac_ovflw++; 8773 } 8774 } 8775 } 8776 } 8777 8778 void CMSKeepAliveClosure::do_oop(oop* p) { CMSKeepAliveClosure::do_oop_work(p); } 8779 void CMSKeepAliveClosure::do_oop(narrowOop* p) { CMSKeepAliveClosure::do_oop_work(p); } 8780 8781 // CMSParKeepAliveClosure: a parallel version of the above. 8782 // The work queues are private to each closure (thread), 8783 // but (may be) available for stealing by other threads. 8784 void CMSParKeepAliveClosure::do_oop(oop obj) { 8785 HeapWord* addr = (HeapWord*)obj; 8786 if (_span.contains(addr) && 8787 !_bit_map->isMarked(addr)) { 8788 // In general, during recursive tracing, several threads 8789 // may be concurrently getting here; the first one to 8790 // "tag" it, claims it. 8791 if (_bit_map->par_mark(addr)) { 8792 bool res = _work_queue->push(obj); 8793 assert(res, "Low water mark should be much less than capacity"); 8794 // Do a recursive trim in the hope that this will keep 8795 // stack usage lower, but leave some oops for potential stealers 8796 trim_queue(_low_water_mark); 8797 } // Else, another thread got there first 8798 } 8799 } 8800 8801 void CMSParKeepAliveClosure::do_oop(oop* p) { CMSParKeepAliveClosure::do_oop_work(p); } 8802 void CMSParKeepAliveClosure::do_oop(narrowOop* p) { CMSParKeepAliveClosure::do_oop_work(p); } 8803 8804 void CMSParKeepAliveClosure::trim_queue(uint max) { 8805 while (_work_queue->size() > max) { 8806 oop new_oop; 8807 if (_work_queue->pop_local(new_oop)) { 8808 assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop"); 8809 assert(_bit_map->isMarked((HeapWord*)new_oop), 8810 "no white objects on this stack!"); 8811 assert(_span.contains((HeapWord*)new_oop), "Out of bounds oop"); 8812 // iterate over the oops in this oop, marking and pushing 8813 // the ones in CMS heap (i.e. in _span). 8814 new_oop->oop_iterate(&_mark_and_push); 8815 } 8816 } 8817 } 8818 8819 CMSInnerParMarkAndPushClosure::CMSInnerParMarkAndPushClosure( 8820 CMSCollector* collector, 8821 MemRegion span, CMSBitMap* bit_map, 8822 OopTaskQueue* work_queue): 8823 _collector(collector), 8824 _span(span), 8825 _bit_map(bit_map), 8826 _work_queue(work_queue) { } 8827 8828 void CMSInnerParMarkAndPushClosure::do_oop(oop obj) { 8829 HeapWord* addr = (HeapWord*)obj; 8830 if (_span.contains(addr) && 8831 !_bit_map->isMarked(addr)) { 8832 if (_bit_map->par_mark(addr)) { 8833 bool simulate_overflow = false; 8834 NOT_PRODUCT( 8835 if (CMSMarkStackOverflowALot && 8836 _collector->par_simulate_overflow()) { 8837 // simulate a stack overflow 8838 simulate_overflow = true; 8839 } 8840 ) 8841 if (simulate_overflow || !_work_queue->push(obj)) { 8842 _collector->par_push_on_overflow_list(obj); 8843 _collector->_par_kac_ovflw++; 8844 } 8845 } // Else another thread got there already 8846 } 8847 } 8848 8849 void CMSInnerParMarkAndPushClosure::do_oop(oop* p) { CMSInnerParMarkAndPushClosure::do_oop_work(p); } 8850 void CMSInnerParMarkAndPushClosure::do_oop(narrowOop* p) { CMSInnerParMarkAndPushClosure::do_oop_work(p); } 8851 8852 ////////////////////////////////////////////////////////////////// 8853 // CMSExpansionCause ///////////////////////////// 8854 ////////////////////////////////////////////////////////////////// 8855 const char* CMSExpansionCause::to_string(CMSExpansionCause::Cause cause) { 8856 switch (cause) { 8857 case _no_expansion: 8858 return "No expansion"; 8859 case _satisfy_free_ratio: 8860 return "Free ratio"; 8861 case _satisfy_promotion: 8862 return "Satisfy promotion"; 8863 case _satisfy_allocation: 8864 return "allocation"; 8865 case _allocate_par_lab: 8866 return "Par LAB"; 8867 case _allocate_par_spooling_space: 8868 return "Par Spooling Space"; 8869 case _adaptive_size_policy: 8870 return "Ergonomics"; 8871 default: 8872 return "unknown"; 8873 } 8874 } 8875 8876 void CMSDrainMarkingStackClosure::do_void() { 8877 // the max number to take from overflow list at a time 8878 const size_t num = _mark_stack->capacity()/4; 8879 assert(!_concurrent_precleaning || _collector->overflow_list_is_empty(), 8880 "Overflow list should be NULL during concurrent phases"); 8881 while (!_mark_stack->isEmpty() || 8882 // if stack is empty, check the overflow list 8883 _collector->take_from_overflow_list(num, _mark_stack)) { 8884 oop obj = _mark_stack->pop(); 8885 HeapWord* addr = (HeapWord*)obj; 8886 assert(_span.contains(addr), "Should be within span"); 8887 assert(_bit_map->isMarked(addr), "Should be marked"); 8888 assert(obj->is_oop(), "Should be an oop"); 8889 obj->oop_iterate(_keep_alive); 8890 } 8891 } 8892 8893 void CMSParDrainMarkingStackClosure::do_void() { 8894 // drain queue 8895 trim_queue(0); 8896 } 8897 8898 // Trim our work_queue so its length is below max at return 8899 void CMSParDrainMarkingStackClosure::trim_queue(uint max) { 8900 while (_work_queue->size() > max) { 8901 oop new_oop; 8902 if (_work_queue->pop_local(new_oop)) { 8903 assert(new_oop->is_oop(), "Expected an oop"); 8904 assert(_bit_map->isMarked((HeapWord*)new_oop), 8905 "no white objects on this stack!"); 8906 assert(_span.contains((HeapWord*)new_oop), "Out of bounds oop"); 8907 // iterate over the oops in this oop, marking and pushing 8908 // the ones in CMS heap (i.e. in _span). 8909 new_oop->oop_iterate(&_mark_and_push); 8910 } 8911 } 8912 } 8913 8914 //////////////////////////////////////////////////////////////////// 8915 // Support for Marking Stack Overflow list handling and related code 8916 //////////////////////////////////////////////////////////////////// 8917 // Much of the following code is similar in shape and spirit to the 8918 // code used in ParNewGC. We should try and share that code 8919 // as much as possible in the future. 8920 8921 #ifndef PRODUCT 8922 // Debugging support for CMSStackOverflowALot 8923 8924 // It's OK to call this multi-threaded; the worst thing 8925 // that can happen is that we'll get a bunch of closely 8926 // spaced simulated overflows, but that's OK, in fact 8927 // probably good as it would exercise the overflow code 8928 // under contention. 8929 bool CMSCollector::simulate_overflow() { 8930 if (_overflow_counter-- <= 0) { // just being defensive 8931 _overflow_counter = CMSMarkStackOverflowInterval; 8932 return true; 8933 } else { 8934 return false; 8935 } 8936 } 8937 8938 bool CMSCollector::par_simulate_overflow() { 8939 return simulate_overflow(); 8940 } 8941 #endif 8942 8943 // Single-threaded 8944 bool CMSCollector::take_from_overflow_list(size_t num, CMSMarkStack* stack) { 8945 assert(stack->isEmpty(), "Expected precondition"); 8946 assert(stack->capacity() > num, "Shouldn't bite more than can chew"); 8947 size_t i = num; 8948 oop cur = _overflow_list; 8949 const markOop proto = markOopDesc::prototype(); 8950 NOT_PRODUCT(ssize_t n = 0;) 8951 for (oop next; i > 0 && cur != NULL; cur = next, i--) { 8952 next = oop(cur->mark()); 8953 cur->set_mark(proto); // until proven otherwise 8954 assert(cur->is_oop(), "Should be an oop"); 8955 bool res = stack->push(cur); 8956 assert(res, "Bit off more than can chew?"); 8957 NOT_PRODUCT(n++;) 8958 } 8959 _overflow_list = cur; 8960 #ifndef PRODUCT 8961 assert(_num_par_pushes >= n, "Too many pops?"); 8962 _num_par_pushes -=n; 8963 #endif 8964 return !stack->isEmpty(); 8965 } 8966 8967 #define BUSY (cast_to_oop<intptr_t>(0x1aff1aff)) 8968 // (MT-safe) Get a prefix of at most "num" from the list. 8969 // The overflow list is chained through the mark word of 8970 // each object in the list. We fetch the entire list, 8971 // break off a prefix of the right size and return the 8972 // remainder. If other threads try to take objects from 8973 // the overflow list at that time, they will wait for 8974 // some time to see if data becomes available. If (and 8975 // only if) another thread places one or more object(s) 8976 // on the global list before we have returned the suffix 8977 // to the global list, we will walk down our local list 8978 // to find its end and append the global list to 8979 // our suffix before returning it. This suffix walk can 8980 // prove to be expensive (quadratic in the amount of traffic) 8981 // when there are many objects in the overflow list and 8982 // there is much producer-consumer contention on the list. 8983 // *NOTE*: The overflow list manipulation code here and 8984 // in ParNewGeneration:: are very similar in shape, 8985 // except that in the ParNew case we use the old (from/eden) 8986 // copy of the object to thread the list via its klass word. 8987 // Because of the common code, if you make any changes in 8988 // the code below, please check the ParNew version to see if 8989 // similar changes might be needed. 8990 // CR 6797058 has been filed to consolidate the common code. 8991 bool CMSCollector::par_take_from_overflow_list(size_t num, 8992 OopTaskQueue* work_q, 8993 int no_of_gc_threads) { 8994 assert(work_q->size() == 0, "First empty local work queue"); 8995 assert(num < work_q->max_elems(), "Can't bite more than we can chew"); 8996 if (_overflow_list == NULL) { 8997 return false; 8998 } 8999 // Grab the entire list; we'll put back a suffix 9000 oop prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list)); 9001 Thread* tid = Thread::current(); 9002 // Before "no_of_gc_threads" was introduced CMSOverflowSpinCount was 9003 // set to ParallelGCThreads. 9004 size_t CMSOverflowSpinCount = (size_t) no_of_gc_threads; // was ParallelGCThreads; 9005 size_t sleep_time_millis = MAX2((size_t)1, num/100); 9006 // If the list is busy, we spin for a short while, 9007 // sleeping between attempts to get the list. 9008 for (size_t spin = 0; prefix == BUSY && spin < CMSOverflowSpinCount; spin++) { 9009 os::sleep(tid, sleep_time_millis, false); 9010 if (_overflow_list == NULL) { 9011 // Nothing left to take 9012 return false; 9013 } else if (_overflow_list != BUSY) { 9014 // Try and grab the prefix 9015 prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list)); 9016 } 9017 } 9018 // If the list was found to be empty, or we spun long 9019 // enough, we give up and return empty-handed. If we leave 9020 // the list in the BUSY state below, it must be the case that 9021 // some other thread holds the overflow list and will set it 9022 // to a non-BUSY state in the future. 9023 if (prefix == NULL || prefix == BUSY) { 9024 // Nothing to take or waited long enough 9025 if (prefix == NULL) { 9026 // Write back the NULL in case we overwrote it with BUSY above 9027 // and it is still the same value. 9028 (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY); 9029 } 9030 return false; 9031 } 9032 assert(prefix != NULL && prefix != BUSY, "Error"); 9033 size_t i = num; 9034 oop cur = prefix; 9035 // Walk down the first "num" objects, unless we reach the end. 9036 for (; i > 1 && cur->mark() != NULL; cur = oop(cur->mark()), i--); 9037 if (cur->mark() == NULL) { 9038 // We have "num" or fewer elements in the list, so there 9039 // is nothing to return to the global list. 9040 // Write back the NULL in lieu of the BUSY we wrote 9041 // above, if it is still the same value. 9042 if (_overflow_list == BUSY) { 9043 (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY); 9044 } 9045 } else { 9046 // Chop off the suffix and return it to the global list. 9047 assert(cur->mark() != BUSY, "Error"); 9048 oop suffix_head = cur->mark(); // suffix will be put back on global list 9049 cur->set_mark(NULL); // break off suffix 9050 // It's possible that the list is still in the empty(busy) state 9051 // we left it in a short while ago; in that case we may be 9052 // able to place back the suffix without incurring the cost 9053 // of a walk down the list. 9054 oop observed_overflow_list = _overflow_list; 9055 oop cur_overflow_list = observed_overflow_list; 9056 bool attached = false; 9057 while (observed_overflow_list == BUSY || observed_overflow_list == NULL) { 9058 observed_overflow_list = 9059 (oop) Atomic::cmpxchg_ptr(suffix_head, &_overflow_list, cur_overflow_list); 9060 if (cur_overflow_list == observed_overflow_list) { 9061 attached = true; 9062 break; 9063 } else cur_overflow_list = observed_overflow_list; 9064 } 9065 if (!attached) { 9066 // Too bad, someone else sneaked in (at least) an element; we'll need 9067 // to do a splice. Find tail of suffix so we can prepend suffix to global 9068 // list. 9069 for (cur = suffix_head; cur->mark() != NULL; cur = (oop)(cur->mark())); 9070 oop suffix_tail = cur; 9071 assert(suffix_tail != NULL && suffix_tail->mark() == NULL, 9072 "Tautology"); 9073 observed_overflow_list = _overflow_list; 9074 do { 9075 cur_overflow_list = observed_overflow_list; 9076 if (cur_overflow_list != BUSY) { 9077 // Do the splice ... 9078 suffix_tail->set_mark(markOop(cur_overflow_list)); 9079 } else { // cur_overflow_list == BUSY 9080 suffix_tail->set_mark(NULL); 9081 } 9082 // ... and try to place spliced list back on overflow_list ... 9083 observed_overflow_list = 9084 (oop) Atomic::cmpxchg_ptr(suffix_head, &_overflow_list, cur_overflow_list); 9085 } while (cur_overflow_list != observed_overflow_list); 9086 // ... until we have succeeded in doing so. 9087 } 9088 } 9089 9090 // Push the prefix elements on work_q 9091 assert(prefix != NULL, "control point invariant"); 9092 const markOop proto = markOopDesc::prototype(); 9093 oop next; 9094 NOT_PRODUCT(ssize_t n = 0;) 9095 for (cur = prefix; cur != NULL; cur = next) { 9096 next = oop(cur->mark()); 9097 cur->set_mark(proto); // until proven otherwise 9098 assert(cur->is_oop(), "Should be an oop"); 9099 bool res = work_q->push(cur); 9100 assert(res, "Bit off more than we can chew?"); 9101 NOT_PRODUCT(n++;) 9102 } 9103 #ifndef PRODUCT 9104 assert(_num_par_pushes >= n, "Too many pops?"); 9105 Atomic::add_ptr(-(intptr_t)n, &_num_par_pushes); 9106 #endif 9107 return true; 9108 } 9109 9110 // Single-threaded 9111 void CMSCollector::push_on_overflow_list(oop p) { 9112 NOT_PRODUCT(_num_par_pushes++;) 9113 assert(p->is_oop(), "Not an oop"); 9114 preserve_mark_if_necessary(p); 9115 p->set_mark((markOop)_overflow_list); 9116 _overflow_list = p; 9117 } 9118 9119 // Multi-threaded; use CAS to prepend to overflow list 9120 void CMSCollector::par_push_on_overflow_list(oop p) { 9121 NOT_PRODUCT(Atomic::inc_ptr(&_num_par_pushes);) 9122 assert(p->is_oop(), "Not an oop"); 9123 par_preserve_mark_if_necessary(p); 9124 oop observed_overflow_list = _overflow_list; 9125 oop cur_overflow_list; 9126 do { 9127 cur_overflow_list = observed_overflow_list; 9128 if (cur_overflow_list != BUSY) { 9129 p->set_mark(markOop(cur_overflow_list)); 9130 } else { 9131 p->set_mark(NULL); 9132 } 9133 observed_overflow_list = 9134 (oop) Atomic::cmpxchg_ptr(p, &_overflow_list, cur_overflow_list); 9135 } while (cur_overflow_list != observed_overflow_list); 9136 } 9137 #undef BUSY 9138 9139 // Single threaded 9140 // General Note on GrowableArray: pushes may silently fail 9141 // because we are (temporarily) out of C-heap for expanding 9142 // the stack. The problem is quite ubiquitous and affects 9143 // a lot of code in the JVM. The prudent thing for GrowableArray 9144 // to do (for now) is to exit with an error. However, that may 9145 // be too draconian in some cases because the caller may be 9146 // able to recover without much harm. For such cases, we 9147 // should probably introduce a "soft_push" method which returns 9148 // an indication of success or failure with the assumption that 9149 // the caller may be able to recover from a failure; code in 9150 // the VM can then be changed, incrementally, to deal with such 9151 // failures where possible, thus, incrementally hardening the VM 9152 // in such low resource situations. 9153 void CMSCollector::preserve_mark_work(oop p, markOop m) { 9154 _preserved_oop_stack.push(p); 9155 _preserved_mark_stack.push(m); 9156 assert(m == p->mark(), "Mark word changed"); 9157 assert(_preserved_oop_stack.size() == _preserved_mark_stack.size(), 9158 "bijection"); 9159 } 9160 9161 // Single threaded 9162 void CMSCollector::preserve_mark_if_necessary(oop p) { 9163 markOop m = p->mark(); 9164 if (m->must_be_preserved(p)) { 9165 preserve_mark_work(p, m); 9166 } 9167 } 9168 9169 void CMSCollector::par_preserve_mark_if_necessary(oop p) { 9170 markOop m = p->mark(); 9171 if (m->must_be_preserved(p)) { 9172 MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag); 9173 // Even though we read the mark word without holding 9174 // the lock, we are assured that it will not change 9175 // because we "own" this oop, so no other thread can 9176 // be trying to push it on the overflow list; see 9177 // the assertion in preserve_mark_work() that checks 9178 // that m == p->mark(). 9179 preserve_mark_work(p, m); 9180 } 9181 } 9182 9183 // We should be able to do this multi-threaded, 9184 // a chunk of stack being a task (this is 9185 // correct because each oop only ever appears 9186 // once in the overflow list. However, it's 9187 // not very easy to completely overlap this with 9188 // other operations, so will generally not be done 9189 // until all work's been completed. Because we 9190 // expect the preserved oop stack (set) to be small, 9191 // it's probably fine to do this single-threaded. 9192 // We can explore cleverer concurrent/overlapped/parallel 9193 // processing of preserved marks if we feel the 9194 // need for this in the future. Stack overflow should 9195 // be so rare in practice and, when it happens, its 9196 // effect on performance so great that this will 9197 // likely just be in the noise anyway. 9198 void CMSCollector::restore_preserved_marks_if_any() { 9199 assert(SafepointSynchronize::is_at_safepoint(), 9200 "world should be stopped"); 9201 assert(Thread::current()->is_ConcurrentGC_thread() || 9202 Thread::current()->is_VM_thread(), 9203 "should be single-threaded"); 9204 assert(_preserved_oop_stack.size() == _preserved_mark_stack.size(), 9205 "bijection"); 9206 9207 while (!_preserved_oop_stack.is_empty()) { 9208 oop p = _preserved_oop_stack.pop(); 9209 assert(p->is_oop(), "Should be an oop"); 9210 assert(_span.contains(p), "oop should be in _span"); 9211 assert(p->mark() == markOopDesc::prototype(), 9212 "Set when taken from overflow list"); 9213 markOop m = _preserved_mark_stack.pop(); 9214 p->set_mark(m); 9215 } 9216 assert(_preserved_mark_stack.is_empty() && _preserved_oop_stack.is_empty(), 9217 "stacks were cleared above"); 9218 } 9219 9220 #ifndef PRODUCT 9221 bool CMSCollector::no_preserved_marks() const { 9222 return _preserved_mark_stack.is_empty() && _preserved_oop_stack.is_empty(); 9223 } 9224 #endif 9225 9226 // Transfer some number of overflown objects to usual marking 9227 // stack. Return true if some objects were transferred. 9228 bool MarkRefsIntoAndScanClosure::take_from_overflow_list() { 9229 size_t num = MIN2((size_t)(_mark_stack->capacity() - _mark_stack->length())/4, 9230 (size_t)ParGCDesiredObjsFromOverflowList); 9231 9232 bool res = _collector->take_from_overflow_list(num, _mark_stack); 9233 assert(_collector->overflow_list_is_empty() || res, 9234 "If list is not empty, we should have taken something"); 9235 assert(!res || !_mark_stack->isEmpty(), 9236 "If we took something, it should now be on our stack"); 9237 return res; 9238 } 9239 9240 size_t MarkDeadObjectsClosure::do_blk(HeapWord* addr) { 9241 size_t res = _sp->block_size_no_stall(addr, _collector); 9242 if (_sp->block_is_obj(addr)) { 9243 if (_live_bit_map->isMarked(addr)) { 9244 // It can't have been dead in a previous cycle 9245 guarantee(!_dead_bit_map->isMarked(addr), "No resurrection!"); 9246 } else { 9247 _dead_bit_map->mark(addr); // mark the dead object 9248 } 9249 } 9250 // Could be 0, if the block size could not be computed without stalling. 9251 return res; 9252 } 9253 9254 TraceCMSMemoryManagerStats::TraceCMSMemoryManagerStats(CMSCollector::CollectorState phase, GCCause::Cause cause): TraceMemoryManagerStats() { 9255 9256 switch (phase) { 9257 case CMSCollector::InitialMarking: 9258 initialize(true /* fullGC */ , 9259 cause /* cause of the GC */, 9260 true /* recordGCBeginTime */, 9261 true /* recordPreGCUsage */, 9262 false /* recordPeakUsage */, 9263 false /* recordPostGCusage */, 9264 true /* recordAccumulatedGCTime */, 9265 false /* recordGCEndTime */, 9266 false /* countCollection */ ); 9267 break; 9268 9269 case CMSCollector::FinalMarking: 9270 initialize(true /* fullGC */ , 9271 cause /* cause of the GC */, 9272 false /* recordGCBeginTime */, 9273 false /* recordPreGCUsage */, 9274 false /* recordPeakUsage */, 9275 false /* recordPostGCusage */, 9276 true /* recordAccumulatedGCTime */, 9277 false /* recordGCEndTime */, 9278 false /* countCollection */ ); 9279 break; 9280 9281 case CMSCollector::Sweeping: 9282 initialize(true /* fullGC */ , 9283 cause /* cause of the GC */, 9284 false /* recordGCBeginTime */, 9285 false /* recordPreGCUsage */, 9286 true /* recordPeakUsage */, 9287 true /* recordPostGCusage */, 9288 false /* recordAccumulatedGCTime */, 9289 true /* recordGCEndTime */, 9290 true /* countCollection */ ); 9291 break; 9292 9293 default: 9294 ShouldNotReachHere(); 9295 } 9296 }