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->get_gen(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 ResourceMark rm; 5991 HandleMark hm; 5992 assert(_collector->_span.equals(_span), "Inconsistency in _span"); 5993 CMSParKeepAliveClosure par_keep_alive(_collector, _span, 5994 _mark_bit_map, 5995 work_queue(worker_id)); 5996 CMSParDrainMarkingStackClosure par_drain_stack(_collector, _span, 5997 _mark_bit_map, 5998 work_queue(worker_id)); 5999 CMSIsAliveClosure is_alive_closure(_span, _mark_bit_map); 6000 _task.work(worker_id, is_alive_closure, par_keep_alive, par_drain_stack); 6001 if (_task.marks_oops_alive()) { 6002 do_work_steal(worker_id, &par_drain_stack, &par_keep_alive, 6003 _collector->hash_seed(worker_id)); 6004 } 6005 assert(work_queue(worker_id)->size() == 0, "work_queue should be empty"); 6006 assert(_collector->_overflow_list == NULL, "non-empty _overflow_list"); 6007 } 6008 6009 class CMSRefEnqueueTaskProxy: public AbstractGangTask { 6010 typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask; 6011 EnqueueTask& _task; 6012 6013 public: 6014 CMSRefEnqueueTaskProxy(EnqueueTask& task) 6015 : AbstractGangTask("Enqueue reference objects in parallel"), 6016 _task(task) 6017 { } 6018 6019 virtual void work(uint worker_id) 6020 { 6021 _task.work(worker_id); 6022 } 6023 }; 6024 6025 CMSParKeepAliveClosure::CMSParKeepAliveClosure(CMSCollector* collector, 6026 MemRegion span, CMSBitMap* bit_map, OopTaskQueue* work_queue): 6027 _span(span), 6028 _bit_map(bit_map), 6029 _work_queue(work_queue), 6030 _mark_and_push(collector, span, bit_map, work_queue), 6031 _low_water_mark(MIN2((uint)(work_queue->max_elems()/4), 6032 (uint)(CMSWorkQueueDrainThreshold * ParallelGCThreads))) 6033 { } 6034 6035 // . see if we can share work_queues with ParNew? XXX 6036 void CMSRefProcTaskProxy::do_work_steal(int i, 6037 CMSParDrainMarkingStackClosure* drain, 6038 CMSParKeepAliveClosure* keep_alive, 6039 int* seed) { 6040 OopTaskQueue* work_q = work_queue(i); 6041 NOT_PRODUCT(int num_steals = 0;) 6042 oop obj_to_scan; 6043 6044 while (true) { 6045 // Completely finish any left over work from (an) earlier round(s) 6046 drain->trim_queue(0); 6047 size_t num_from_overflow_list = MIN2((size_t)(work_q->max_elems() - work_q->size())/4, 6048 (size_t)ParGCDesiredObjsFromOverflowList); 6049 // Now check if there's any work in the overflow list 6050 // Passing ParallelGCThreads as the third parameter, no_of_gc_threads, 6051 // only affects the number of attempts made to get work from the 6052 // overflow list and does not affect the number of workers. Just 6053 // pass ParallelGCThreads so this behavior is unchanged. 6054 if (_collector->par_take_from_overflow_list(num_from_overflow_list, 6055 work_q, 6056 ParallelGCThreads)) { 6057 // Found something in global overflow list; 6058 // not yet ready to go stealing work from others. 6059 // We'd like to assert(work_q->size() != 0, ...) 6060 // because we just took work from the overflow list, 6061 // but of course we can't, since all of that might have 6062 // been already stolen from us. 6063 continue; 6064 } 6065 // Verify that we have no work before we resort to stealing 6066 assert(work_q->size() == 0, "Have work, shouldn't steal"); 6067 // Try to steal from other queues that have work 6068 if (task_queues()->steal(i, seed, /* reference */ obj_to_scan)) { 6069 NOT_PRODUCT(num_steals++;) 6070 assert(obj_to_scan->is_oop(), "Oops, not an oop!"); 6071 assert(_mark_bit_map->isMarked((HeapWord*)obj_to_scan), "Stole an unmarked oop?"); 6072 // Do scanning work 6073 obj_to_scan->oop_iterate(keep_alive); 6074 // Loop around, finish this work, and try to steal some more 6075 } else if (terminator()->offer_termination()) { 6076 break; // nirvana from the infinite cycle 6077 } 6078 } 6079 NOT_PRODUCT( 6080 if (PrintCMSStatistics != 0) { 6081 gclog_or_tty->print("\n\t(%d: stole %d oops)", i, num_steals); 6082 } 6083 ) 6084 } 6085 6086 void CMSRefProcTaskExecutor::execute(ProcessTask& task) 6087 { 6088 GenCollectedHeap* gch = GenCollectedHeap::heap(); 6089 FlexibleWorkGang* workers = gch->workers(); 6090 assert(workers != NULL, "Need parallel worker threads."); 6091 CMSRefProcTaskProxy rp_task(task, &_collector, 6092 _collector.ref_processor()->span(), 6093 _collector.markBitMap(), 6094 workers, _collector.task_queues()); 6095 workers->run_task(&rp_task); 6096 } 6097 6098 void CMSRefProcTaskExecutor::execute(EnqueueTask& task) 6099 { 6100 6101 GenCollectedHeap* gch = GenCollectedHeap::heap(); 6102 FlexibleWorkGang* workers = gch->workers(); 6103 assert(workers != NULL, "Need parallel worker threads."); 6104 CMSRefEnqueueTaskProxy enq_task(task); 6105 workers->run_task(&enq_task); 6106 } 6107 6108 void CMSCollector::refProcessingWork(bool asynch, bool clear_all_soft_refs) { 6109 6110 ResourceMark rm; 6111 HandleMark hm; 6112 6113 ReferenceProcessor* rp = ref_processor(); 6114 assert(rp->span().equals(_span), "Spans should be equal"); 6115 assert(!rp->enqueuing_is_done(), "Enqueuing should not be complete"); 6116 // Process weak references. 6117 rp->setup_policy(clear_all_soft_refs); 6118 verify_work_stacks_empty(); 6119 6120 CMSKeepAliveClosure cmsKeepAliveClosure(this, _span, &_markBitMap, 6121 &_markStack, false /* !preclean */); 6122 CMSDrainMarkingStackClosure cmsDrainMarkingStackClosure(this, 6123 _span, &_markBitMap, &_markStack, 6124 &cmsKeepAliveClosure, false /* !preclean */); 6125 { 6126 GCTraceTime t("weak refs processing", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 6127 6128 ReferenceProcessorStats stats; 6129 if (rp->processing_is_mt()) { 6130 // Set the degree of MT here. If the discovery is done MT, there 6131 // may have been a different number of threads doing the discovery 6132 // and a different number of discovered lists may have Ref objects. 6133 // That is OK as long as the Reference lists are balanced (see 6134 // balance_all_queues() and balance_queues()). 6135 GenCollectedHeap* gch = GenCollectedHeap::heap(); 6136 int active_workers = ParallelGCThreads; 6137 FlexibleWorkGang* workers = gch->workers(); 6138 if (workers != NULL) { 6139 active_workers = workers->active_workers(); 6140 // The expectation is that active_workers will have already 6141 // been set to a reasonable value. If it has not been set, 6142 // investigate. 6143 assert(active_workers > 0, "Should have been set during scavenge"); 6144 } 6145 rp->set_active_mt_degree(active_workers); 6146 CMSRefProcTaskExecutor task_executor(*this); 6147 stats = rp->process_discovered_references(&_is_alive_closure, 6148 &cmsKeepAliveClosure, 6149 &cmsDrainMarkingStackClosure, 6150 &task_executor, 6151 _gc_timer_cm, 6152 _gc_tracer_cm->gc_id()); 6153 } else { 6154 stats = rp->process_discovered_references(&_is_alive_closure, 6155 &cmsKeepAliveClosure, 6156 &cmsDrainMarkingStackClosure, 6157 NULL, 6158 _gc_timer_cm, 6159 _gc_tracer_cm->gc_id()); 6160 } 6161 _gc_tracer_cm->report_gc_reference_stats(stats); 6162 6163 } 6164 6165 // This is the point where the entire marking should have completed. 6166 verify_work_stacks_empty(); 6167 6168 if (should_unload_classes()) { 6169 { 6170 GCTraceTime t("class unloading", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 6171 6172 // Unload classes and purge the SystemDictionary. 6173 bool purged_class = SystemDictionary::do_unloading(&_is_alive_closure); 6174 6175 // Unload nmethods. 6176 CodeCache::do_unloading(&_is_alive_closure, purged_class); 6177 6178 // Prune dead klasses from subklass/sibling/implementor lists. 6179 Klass::clean_weak_klass_links(&_is_alive_closure); 6180 } 6181 6182 { 6183 GCTraceTime t("scrub symbol table", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 6184 // Clean up unreferenced symbols in symbol table. 6185 SymbolTable::unlink(); 6186 } 6187 6188 { 6189 GCTraceTime t("scrub string table", PrintGCDetails, false, _gc_timer_cm, _gc_tracer_cm->gc_id()); 6190 // Delete entries for dead interned strings. 6191 StringTable::unlink(&_is_alive_closure); 6192 } 6193 } 6194 6195 6196 // Restore any preserved marks as a result of mark stack or 6197 // work queue overflow 6198 restore_preserved_marks_if_any(); // done single-threaded for now 6199 6200 rp->set_enqueuing_is_done(true); 6201 if (rp->processing_is_mt()) { 6202 rp->balance_all_queues(); 6203 CMSRefProcTaskExecutor task_executor(*this); 6204 rp->enqueue_discovered_references(&task_executor); 6205 } else { 6206 rp->enqueue_discovered_references(NULL); 6207 } 6208 rp->verify_no_references_recorded(); 6209 assert(!rp->discovery_enabled(), "should have been disabled"); 6210 } 6211 6212 #ifndef PRODUCT 6213 void CMSCollector::check_correct_thread_executing() { 6214 Thread* t = Thread::current(); 6215 // Only the VM thread or the CMS thread should be here. 6216 assert(t->is_ConcurrentGC_thread() || t->is_VM_thread(), 6217 "Unexpected thread type"); 6218 // If this is the vm thread, the foreground process 6219 // should not be waiting. Note that _foregroundGCIsActive is 6220 // true while the foreground collector is waiting. 6221 if (_foregroundGCShouldWait) { 6222 // We cannot be the VM thread 6223 assert(t->is_ConcurrentGC_thread(), 6224 "Should be CMS thread"); 6225 } else { 6226 // We can be the CMS thread only if we are in a stop-world 6227 // phase of CMS collection. 6228 if (t->is_ConcurrentGC_thread()) { 6229 assert(_collectorState == InitialMarking || 6230 _collectorState == FinalMarking, 6231 "Should be a stop-world phase"); 6232 // The CMS thread should be holding the CMS_token. 6233 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 6234 "Potential interference with concurrently " 6235 "executing VM thread"); 6236 } 6237 } 6238 } 6239 #endif 6240 6241 void CMSCollector::sweep(bool asynch) { 6242 assert(_collectorState == Sweeping, "just checking"); 6243 check_correct_thread_executing(); 6244 verify_work_stacks_empty(); 6245 verify_overflow_empty(); 6246 increment_sweep_count(); 6247 TraceCMSMemoryManagerStats tms(_collectorState,GenCollectedHeap::heap()->gc_cause()); 6248 6249 _inter_sweep_timer.stop(); 6250 _inter_sweep_estimate.sample(_inter_sweep_timer.seconds()); 6251 6252 assert(!_intra_sweep_timer.is_active(), "Should not be active"); 6253 _intra_sweep_timer.reset(); 6254 _intra_sweep_timer.start(); 6255 if (asynch) { 6256 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); 6257 CMSPhaseAccounting pa(this, "sweep", _gc_tracer_cm->gc_id(), !PrintGCDetails); 6258 // First sweep the old gen 6259 { 6260 CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock(), 6261 bitMapLock()); 6262 sweepWork(_cmsGen, asynch); 6263 } 6264 6265 // Update Universe::_heap_*_at_gc figures. 6266 // We need all the free list locks to make the abstract state 6267 // transition from Sweeping to Resetting. See detailed note 6268 // further below. 6269 { 6270 CMSTokenSyncWithLocks ts(true, _cmsGen->freelistLock()); 6271 // Update heap occupancy information which is used as 6272 // input to soft ref clearing policy at the next gc. 6273 Universe::update_heap_info_at_gc(); 6274 _collectorState = Resizing; 6275 } 6276 } else { 6277 // already have needed locks 6278 sweepWork(_cmsGen, asynch); 6279 // Update heap occupancy information which is used as 6280 // input to soft ref clearing policy at the next gc. 6281 Universe::update_heap_info_at_gc(); 6282 _collectorState = Resizing; 6283 } 6284 verify_work_stacks_empty(); 6285 verify_overflow_empty(); 6286 6287 if (should_unload_classes()) { 6288 // Delay purge to the beginning of the next safepoint. Metaspace::contains 6289 // requires that the virtual spaces are stable and not deleted. 6290 ClassLoaderDataGraph::set_should_purge(true); 6291 } 6292 6293 _intra_sweep_timer.stop(); 6294 _intra_sweep_estimate.sample(_intra_sweep_timer.seconds()); 6295 6296 _inter_sweep_timer.reset(); 6297 _inter_sweep_timer.start(); 6298 6299 // We need to use a monotonically non-decreasing time in ms 6300 // or we will see time-warp warnings and os::javaTimeMillis() 6301 // does not guarantee monotonicity. 6302 jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC; 6303 update_time_of_last_gc(now); 6304 6305 // NOTE on abstract state transitions: 6306 // Mutators allocate-live and/or mark the mod-union table dirty 6307 // based on the state of the collection. The former is done in 6308 // the interval [Marking, Sweeping] and the latter in the interval 6309 // [Marking, Sweeping). Thus the transitions into the Marking state 6310 // and out of the Sweeping state must be synchronously visible 6311 // globally to the mutators. 6312 // The transition into the Marking state happens with the world 6313 // stopped so the mutators will globally see it. Sweeping is 6314 // done asynchronously by the background collector so the transition 6315 // from the Sweeping state to the Resizing state must be done 6316 // under the freelistLock (as is the check for whether to 6317 // allocate-live and whether to dirty the mod-union table). 6318 assert(_collectorState == Resizing, "Change of collector state to" 6319 " Resizing must be done under the freelistLocks (plural)"); 6320 6321 // Now that sweeping has been completed, we clear 6322 // the incremental_collection_failed flag, 6323 // thus inviting a younger gen collection to promote into 6324 // this generation. If such a promotion may still fail, 6325 // the flag will be set again when a young collection is 6326 // attempted. 6327 GenCollectedHeap* gch = GenCollectedHeap::heap(); 6328 gch->clear_incremental_collection_failed(); // Worth retrying as fresh space may have been freed up 6329 gch->update_full_collections_completed(_collection_count_start); 6330 } 6331 6332 // FIX ME!!! Looks like this belongs in CFLSpace, with 6333 // CMSGen merely delegating to it. 6334 void ConcurrentMarkSweepGeneration::setNearLargestChunk() { 6335 double nearLargestPercent = FLSLargestBlockCoalesceProximity; 6336 HeapWord* minAddr = _cmsSpace->bottom(); 6337 HeapWord* largestAddr = 6338 (HeapWord*) _cmsSpace->dictionary()->find_largest_dict(); 6339 if (largestAddr == NULL) { 6340 // The dictionary appears to be empty. In this case 6341 // try to coalesce at the end of the heap. 6342 largestAddr = _cmsSpace->end(); 6343 } 6344 size_t largestOffset = pointer_delta(largestAddr, minAddr); 6345 size_t nearLargestOffset = 6346 (size_t)((double)largestOffset * nearLargestPercent) - MinChunkSize; 6347 if (PrintFLSStatistics != 0) { 6348 gclog_or_tty->print_cr( 6349 "CMS: Large Block: " PTR_FORMAT ";" 6350 " Proximity: " PTR_FORMAT " -> " PTR_FORMAT, 6351 largestAddr, 6352 _cmsSpace->nearLargestChunk(), minAddr + nearLargestOffset); 6353 } 6354 _cmsSpace->set_nearLargestChunk(minAddr + nearLargestOffset); 6355 } 6356 6357 bool ConcurrentMarkSweepGeneration::isNearLargestChunk(HeapWord* addr) { 6358 return addr >= _cmsSpace->nearLargestChunk(); 6359 } 6360 6361 FreeChunk* ConcurrentMarkSweepGeneration::find_chunk_at_end() { 6362 return _cmsSpace->find_chunk_at_end(); 6363 } 6364 6365 void ConcurrentMarkSweepGeneration::update_gc_stats(int current_level, 6366 bool full) { 6367 // The next lower level has been collected. Gather any statistics 6368 // that are of interest at this point. 6369 if (!full && (current_level + 1) == level()) { 6370 // Gather statistics on the young generation collection. 6371 collector()->stats().record_gc0_end(used()); 6372 } 6373 } 6374 6375 void ConcurrentMarkSweepGeneration::rotate_debug_collection_type() { 6376 if (PrintGCDetails && Verbose) { 6377 gclog_or_tty->print("Rotate from %d ", _debug_collection_type); 6378 } 6379 _debug_collection_type = (CollectionTypes) (_debug_collection_type + 1); 6380 _debug_collection_type = 6381 (CollectionTypes) (_debug_collection_type % Unknown_collection_type); 6382 if (PrintGCDetails && Verbose) { 6383 gclog_or_tty->print_cr("to %d ", _debug_collection_type); 6384 } 6385 } 6386 6387 void CMSCollector::sweepWork(ConcurrentMarkSweepGeneration* gen, 6388 bool asynch) { 6389 // We iterate over the space(s) underlying this generation, 6390 // checking the mark bit map to see if the bits corresponding 6391 // to specific blocks are marked or not. Blocks that are 6392 // marked are live and are not swept up. All remaining blocks 6393 // are swept up, with coalescing on-the-fly as we sweep up 6394 // contiguous free and/or garbage blocks: 6395 // We need to ensure that the sweeper synchronizes with allocators 6396 // and stop-the-world collectors. In particular, the following 6397 // locks are used: 6398 // . CMS token: if this is held, a stop the world collection cannot occur 6399 // . freelistLock: if this is held no allocation can occur from this 6400 // generation by another thread 6401 // . bitMapLock: if this is held, no other thread can access or update 6402 // 6403 6404 // Note that we need to hold the freelistLock if we use 6405 // block iterate below; else the iterator might go awry if 6406 // a mutator (or promotion) causes block contents to change 6407 // (for instance if the allocator divvies up a block). 6408 // If we hold the free list lock, for all practical purposes 6409 // young generation GC's can't occur (they'll usually need to 6410 // promote), so we might as well prevent all young generation 6411 // GC's while we do a sweeping step. For the same reason, we might 6412 // as well take the bit map lock for the entire duration 6413 6414 // check that we hold the requisite locks 6415 assert(have_cms_token(), "Should hold cms token"); 6416 assert( (asynch && ConcurrentMarkSweepThread::cms_thread_has_cms_token()) 6417 || (!asynch && ConcurrentMarkSweepThread::vm_thread_has_cms_token()), 6418 "Should possess CMS token to sweep"); 6419 assert_lock_strong(gen->freelistLock()); 6420 assert_lock_strong(bitMapLock()); 6421 6422 assert(!_inter_sweep_timer.is_active(), "Was switched off in an outer context"); 6423 assert(_intra_sweep_timer.is_active(), "Was switched on in an outer context"); 6424 gen->cmsSpace()->beginSweepFLCensus((float)(_inter_sweep_timer.seconds()), 6425 _inter_sweep_estimate.padded_average(), 6426 _intra_sweep_estimate.padded_average()); 6427 gen->setNearLargestChunk(); 6428 6429 { 6430 SweepClosure sweepClosure(this, gen, &_markBitMap, 6431 CMSYield && asynch); 6432 gen->cmsSpace()->blk_iterate_careful(&sweepClosure); 6433 // We need to free-up/coalesce garbage/blocks from a 6434 // co-terminal free run. This is done in the SweepClosure 6435 // destructor; so, do not remove this scope, else the 6436 // end-of-sweep-census below will be off by a little bit. 6437 } 6438 gen->cmsSpace()->sweep_completed(); 6439 gen->cmsSpace()->endSweepFLCensus(sweep_count()); 6440 if (should_unload_classes()) { // unloaded classes this cycle, 6441 _concurrent_cycles_since_last_unload = 0; // ... reset count 6442 } else { // did not unload classes, 6443 _concurrent_cycles_since_last_unload++; // ... increment count 6444 } 6445 } 6446 6447 // Reset CMS data structures (for now just the marking bit map) 6448 // preparatory for the next cycle. 6449 void CMSCollector::reset(bool asynch) { 6450 if (asynch) { 6451 CMSTokenSyncWithLocks ts(true, bitMapLock()); 6452 6453 // If the state is not "Resetting", the foreground thread 6454 // has done a collection and the resetting. 6455 if (_collectorState != Resetting) { 6456 assert(_collectorState == Idling, "The state should only change" 6457 " because the foreground collector has finished the collection"); 6458 return; 6459 } 6460 6461 // Clear the mark bitmap (no grey objects to start with) 6462 // for the next cycle. 6463 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); 6464 CMSPhaseAccounting cmspa(this, "reset", _gc_tracer_cm->gc_id(), !PrintGCDetails); 6465 6466 HeapWord* curAddr = _markBitMap.startWord(); 6467 while (curAddr < _markBitMap.endWord()) { 6468 size_t remaining = pointer_delta(_markBitMap.endWord(), curAddr); 6469 MemRegion chunk(curAddr, MIN2(CMSBitMapYieldQuantum, remaining)); 6470 _markBitMap.clear_large_range(chunk); 6471 if (ConcurrentMarkSweepThread::should_yield() && 6472 !foregroundGCIsActive() && 6473 CMSYield) { 6474 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 6475 "CMS thread should hold CMS token"); 6476 assert_lock_strong(bitMapLock()); 6477 bitMapLock()->unlock(); 6478 ConcurrentMarkSweepThread::desynchronize(true); 6479 ConcurrentMarkSweepThread::acknowledge_yield_request(); 6480 stopTimer(); 6481 if (PrintCMSStatistics != 0) { 6482 incrementYields(); 6483 } 6484 icms_wait(); 6485 6486 // See the comment in coordinator_yield() 6487 for (unsigned i = 0; i < CMSYieldSleepCount && 6488 ConcurrentMarkSweepThread::should_yield() && 6489 !CMSCollector::foregroundGCIsActive(); ++i) { 6490 os::sleep(Thread::current(), 1, false); 6491 ConcurrentMarkSweepThread::acknowledge_yield_request(); 6492 } 6493 6494 ConcurrentMarkSweepThread::synchronize(true); 6495 bitMapLock()->lock_without_safepoint_check(); 6496 startTimer(); 6497 } 6498 curAddr = chunk.end(); 6499 } 6500 // A successful mostly concurrent collection has been done. 6501 // Because only the full (i.e., concurrent mode failure) collections 6502 // are being measured for gc overhead limits, clean the "near" flag 6503 // and count. 6504 size_policy()->reset_gc_overhead_limit_count(); 6505 _collectorState = Idling; 6506 } else { 6507 // already have the lock 6508 assert(_collectorState == Resetting, "just checking"); 6509 assert_lock_strong(bitMapLock()); 6510 _markBitMap.clear_all(); 6511 _collectorState = Idling; 6512 } 6513 6514 // Stop incremental mode after a cycle completes, so that any future cycles 6515 // are triggered by allocation. 6516 stop_icms(); 6517 6518 NOT_PRODUCT( 6519 if (RotateCMSCollectionTypes) { 6520 _cmsGen->rotate_debug_collection_type(); 6521 } 6522 ) 6523 6524 register_gc_end(); 6525 } 6526 6527 void CMSCollector::do_CMS_operation(CMS_op_type op, GCCause::Cause gc_cause) { 6528 gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps); 6529 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); 6530 GCTraceTime t(GCCauseString("GC", gc_cause), PrintGC, !PrintGCDetails, NULL, _gc_tracer_cm->gc_id()); 6531 TraceCollectorStats tcs(counters()); 6532 6533 switch (op) { 6534 case CMS_op_checkpointRootsInitial: { 6535 SvcGCMarker sgcm(SvcGCMarker::OTHER); 6536 checkpointRootsInitial(true); // asynch 6537 if (PrintGC) { 6538 _cmsGen->printOccupancy("initial-mark"); 6539 } 6540 break; 6541 } 6542 case CMS_op_checkpointRootsFinal: { 6543 SvcGCMarker sgcm(SvcGCMarker::OTHER); 6544 checkpointRootsFinal(true, // asynch 6545 false, // !clear_all_soft_refs 6546 false); // !init_mark_was_synchronous 6547 if (PrintGC) { 6548 _cmsGen->printOccupancy("remark"); 6549 } 6550 break; 6551 } 6552 default: 6553 fatal("No such CMS_op"); 6554 } 6555 } 6556 6557 #ifndef PRODUCT 6558 size_t const CMSCollector::skip_header_HeapWords() { 6559 return FreeChunk::header_size(); 6560 } 6561 6562 // Try and collect here conditions that should hold when 6563 // CMS thread is exiting. The idea is that the foreground GC 6564 // thread should not be blocked if it wants to terminate 6565 // the CMS thread and yet continue to run the VM for a while 6566 // after that. 6567 void CMSCollector::verify_ok_to_terminate() const { 6568 assert(Thread::current()->is_ConcurrentGC_thread(), 6569 "should be called by CMS thread"); 6570 assert(!_foregroundGCShouldWait, "should be false"); 6571 // We could check here that all the various low-level locks 6572 // are not held by the CMS thread, but that is overkill; see 6573 // also CMSThread::verify_ok_to_terminate() where the CGC_lock 6574 // is checked. 6575 } 6576 #endif 6577 6578 size_t CMSCollector::block_size_using_printezis_bits(HeapWord* addr) const { 6579 assert(_markBitMap.isMarked(addr) && _markBitMap.isMarked(addr + 1), 6580 "missing Printezis mark?"); 6581 HeapWord* nextOneAddr = _markBitMap.getNextMarkedWordAddress(addr + 2); 6582 size_t size = pointer_delta(nextOneAddr + 1, addr); 6583 assert(size == CompactibleFreeListSpace::adjustObjectSize(size), 6584 "alignment problem"); 6585 assert(size >= 3, "Necessary for Printezis marks to work"); 6586 return size; 6587 } 6588 6589 // A variant of the above (block_size_using_printezis_bits()) except 6590 // that we return 0 if the P-bits are not yet set. 6591 size_t CMSCollector::block_size_if_printezis_bits(HeapWord* addr) const { 6592 if (_markBitMap.isMarked(addr + 1)) { 6593 assert(_markBitMap.isMarked(addr), "P-bit can be set only for marked objects"); 6594 HeapWord* nextOneAddr = _markBitMap.getNextMarkedWordAddress(addr + 2); 6595 size_t size = pointer_delta(nextOneAddr + 1, addr); 6596 assert(size == CompactibleFreeListSpace::adjustObjectSize(size), 6597 "alignment problem"); 6598 assert(size >= 3, "Necessary for Printezis marks to work"); 6599 return size; 6600 } 6601 return 0; 6602 } 6603 6604 HeapWord* CMSCollector::next_card_start_after_block(HeapWord* addr) const { 6605 size_t sz = 0; 6606 oop p = (oop)addr; 6607 if (p->klass_or_null() != NULL) { 6608 sz = CompactibleFreeListSpace::adjustObjectSize(p->size()); 6609 } else { 6610 sz = block_size_using_printezis_bits(addr); 6611 } 6612 assert(sz > 0, "size must be nonzero"); 6613 HeapWord* next_block = addr + sz; 6614 HeapWord* next_card = (HeapWord*)round_to((uintptr_t)next_block, 6615 CardTableModRefBS::card_size); 6616 assert(round_down((uintptr_t)addr, CardTableModRefBS::card_size) < 6617 round_down((uintptr_t)next_card, CardTableModRefBS::card_size), 6618 "must be different cards"); 6619 return next_card; 6620 } 6621 6622 6623 // CMS Bit Map Wrapper ///////////////////////////////////////// 6624 6625 // Construct a CMS bit map infrastructure, but don't create the 6626 // bit vector itself. That is done by a separate call CMSBitMap::allocate() 6627 // further below. 6628 CMSBitMap::CMSBitMap(int shifter, int mutex_rank, const char* mutex_name): 6629 _bm(), 6630 _shifter(shifter), 6631 _lock(mutex_rank >= 0 ? new Mutex(mutex_rank, mutex_name, true) : NULL) 6632 { 6633 _bmStartWord = 0; 6634 _bmWordSize = 0; 6635 } 6636 6637 bool CMSBitMap::allocate(MemRegion mr) { 6638 _bmStartWord = mr.start(); 6639 _bmWordSize = mr.word_size(); 6640 ReservedSpace brs(ReservedSpace::allocation_align_size_up( 6641 (_bmWordSize >> (_shifter + LogBitsPerByte)) + 1)); 6642 if (!brs.is_reserved()) { 6643 warning("CMS bit map allocation failure"); 6644 return false; 6645 } 6646 // For now we'll just commit all of the bit map up front. 6647 // Later on we'll try to be more parsimonious with swap. 6648 if (!_virtual_space.initialize(brs, brs.size())) { 6649 warning("CMS bit map backing store failure"); 6650 return false; 6651 } 6652 assert(_virtual_space.committed_size() == brs.size(), 6653 "didn't reserve backing store for all of CMS bit map?"); 6654 _bm.set_map((BitMap::bm_word_t*)_virtual_space.low()); 6655 assert(_virtual_space.committed_size() << (_shifter + LogBitsPerByte) >= 6656 _bmWordSize, "inconsistency in bit map sizing"); 6657 _bm.set_size(_bmWordSize >> _shifter); 6658 6659 // bm.clear(); // can we rely on getting zero'd memory? verify below 6660 assert(isAllClear(), 6661 "Expected zero'd memory from ReservedSpace constructor"); 6662 assert(_bm.size() == heapWordDiffToOffsetDiff(sizeInWords()), 6663 "consistency check"); 6664 return true; 6665 } 6666 6667 void CMSBitMap::dirty_range_iterate_clear(MemRegion mr, MemRegionClosure* cl) { 6668 HeapWord *next_addr, *end_addr, *last_addr; 6669 assert_locked(); 6670 assert(covers(mr), "out-of-range error"); 6671 // XXX assert that start and end are appropriately aligned 6672 for (next_addr = mr.start(), end_addr = mr.end(); 6673 next_addr < end_addr; next_addr = last_addr) { 6674 MemRegion dirty_region = getAndClearMarkedRegion(next_addr, end_addr); 6675 last_addr = dirty_region.end(); 6676 if (!dirty_region.is_empty()) { 6677 cl->do_MemRegion(dirty_region); 6678 } else { 6679 assert(last_addr == end_addr, "program logic"); 6680 return; 6681 } 6682 } 6683 } 6684 6685 void CMSBitMap::print_on_error(outputStream* st, const char* prefix) const { 6686 _bm.print_on_error(st, prefix); 6687 } 6688 6689 #ifndef PRODUCT 6690 void CMSBitMap::assert_locked() const { 6691 CMSLockVerifier::assert_locked(lock()); 6692 } 6693 6694 bool CMSBitMap::covers(MemRegion mr) const { 6695 // assert(_bm.map() == _virtual_space.low(), "map inconsistency"); 6696 assert((size_t)_bm.size() == (_bmWordSize >> _shifter), 6697 "size inconsistency"); 6698 return (mr.start() >= _bmStartWord) && 6699 (mr.end() <= endWord()); 6700 } 6701 6702 bool CMSBitMap::covers(HeapWord* start, size_t size) const { 6703 return (start >= _bmStartWord && (start + size) <= endWord()); 6704 } 6705 6706 void CMSBitMap::verifyNoOneBitsInRange(HeapWord* left, HeapWord* right) { 6707 // verify that there are no 1 bits in the interval [left, right) 6708 FalseBitMapClosure falseBitMapClosure; 6709 iterate(&falseBitMapClosure, left, right); 6710 } 6711 6712 void CMSBitMap::region_invariant(MemRegion mr) 6713 { 6714 assert_locked(); 6715 // mr = mr.intersection(MemRegion(_bmStartWord, _bmWordSize)); 6716 assert(!mr.is_empty(), "unexpected empty region"); 6717 assert(covers(mr), "mr should be covered by bit map"); 6718 // convert address range into offset range 6719 size_t start_ofs = heapWordToOffset(mr.start()); 6720 // Make sure that end() is appropriately aligned 6721 assert(mr.end() == (HeapWord*)round_to((intptr_t)mr.end(), 6722 (1 << (_shifter+LogHeapWordSize))), 6723 "Misaligned mr.end()"); 6724 size_t end_ofs = heapWordToOffset(mr.end()); 6725 assert(end_ofs > start_ofs, "Should mark at least one bit"); 6726 } 6727 6728 #endif 6729 6730 bool CMSMarkStack::allocate(size_t size) { 6731 // allocate a stack of the requisite depth 6732 ReservedSpace rs(ReservedSpace::allocation_align_size_up( 6733 size * sizeof(oop))); 6734 if (!rs.is_reserved()) { 6735 warning("CMSMarkStack allocation failure"); 6736 return false; 6737 } 6738 if (!_virtual_space.initialize(rs, rs.size())) { 6739 warning("CMSMarkStack backing store failure"); 6740 return false; 6741 } 6742 assert(_virtual_space.committed_size() == rs.size(), 6743 "didn't reserve backing store for all of CMS stack?"); 6744 _base = (oop*)(_virtual_space.low()); 6745 _index = 0; 6746 _capacity = size; 6747 NOT_PRODUCT(_max_depth = 0); 6748 return true; 6749 } 6750 6751 // XXX FIX ME !!! In the MT case we come in here holding a 6752 // leaf lock. For printing we need to take a further lock 6753 // which has lower rank. We need to recalibrate the two 6754 // lock-ranks involved in order to be able to print the 6755 // messages below. (Or defer the printing to the caller. 6756 // For now we take the expedient path of just disabling the 6757 // messages for the problematic case.) 6758 void CMSMarkStack::expand() { 6759 assert(_capacity <= MarkStackSizeMax, "stack bigger than permitted"); 6760 if (_capacity == MarkStackSizeMax) { 6761 if (_hit_limit++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) { 6762 // We print a warning message only once per CMS cycle. 6763 gclog_or_tty->print_cr(" (benign) Hit CMSMarkStack max size limit"); 6764 } 6765 return; 6766 } 6767 // Double capacity if possible 6768 size_t new_capacity = MIN2(_capacity*2, MarkStackSizeMax); 6769 // Do not give up existing stack until we have managed to 6770 // get the double capacity that we desired. 6771 ReservedSpace rs(ReservedSpace::allocation_align_size_up( 6772 new_capacity * sizeof(oop))); 6773 if (rs.is_reserved()) { 6774 // Release the backing store associated with old stack 6775 _virtual_space.release(); 6776 // Reinitialize virtual space for new stack 6777 if (!_virtual_space.initialize(rs, rs.size())) { 6778 fatal("Not enough swap for expanded marking stack"); 6779 } 6780 _base = (oop*)(_virtual_space.low()); 6781 _index = 0; 6782 _capacity = new_capacity; 6783 } else if (_failed_double++ == 0 && !CMSConcurrentMTEnabled && PrintGCDetails) { 6784 // Failed to double capacity, continue; 6785 // we print a detail message only once per CMS cycle. 6786 gclog_or_tty->print(" (benign) Failed to expand marking stack from "SIZE_FORMAT"K to " 6787 SIZE_FORMAT"K", 6788 _capacity / K, new_capacity / K); 6789 } 6790 } 6791 6792 6793 // Closures 6794 // XXX: there seems to be a lot of code duplication here; 6795 // should refactor and consolidate common code. 6796 6797 // This closure is used to mark refs into the CMS generation in 6798 // the CMS bit map. Called at the first checkpoint. This closure 6799 // assumes that we do not need to re-mark dirty cards; if the CMS 6800 // generation on which this is used is not an oldest 6801 // generation then this will lose younger_gen cards! 6802 6803 MarkRefsIntoClosure::MarkRefsIntoClosure( 6804 MemRegion span, CMSBitMap* bitMap): 6805 _span(span), 6806 _bitMap(bitMap) 6807 { 6808 assert(_ref_processor == NULL, "deliberately left NULL"); 6809 assert(_bitMap->covers(_span), "_bitMap/_span mismatch"); 6810 } 6811 6812 void MarkRefsIntoClosure::do_oop(oop obj) { 6813 // if p points into _span, then mark corresponding bit in _markBitMap 6814 assert(obj->is_oop(), "expected an oop"); 6815 HeapWord* addr = (HeapWord*)obj; 6816 if (_span.contains(addr)) { 6817 // this should be made more efficient 6818 _bitMap->mark(addr); 6819 } 6820 } 6821 6822 void MarkRefsIntoClosure::do_oop(oop* p) { MarkRefsIntoClosure::do_oop_work(p); } 6823 void MarkRefsIntoClosure::do_oop(narrowOop* p) { MarkRefsIntoClosure::do_oop_work(p); } 6824 6825 Par_MarkRefsIntoClosure::Par_MarkRefsIntoClosure( 6826 MemRegion span, CMSBitMap* bitMap): 6827 _span(span), 6828 _bitMap(bitMap) 6829 { 6830 assert(_ref_processor == NULL, "deliberately left NULL"); 6831 assert(_bitMap->covers(_span), "_bitMap/_span mismatch"); 6832 } 6833 6834 void Par_MarkRefsIntoClosure::do_oop(oop obj) { 6835 // if p points into _span, then mark corresponding bit in _markBitMap 6836 assert(obj->is_oop(), "expected an oop"); 6837 HeapWord* addr = (HeapWord*)obj; 6838 if (_span.contains(addr)) { 6839 // this should be made more efficient 6840 _bitMap->par_mark(addr); 6841 } 6842 } 6843 6844 void Par_MarkRefsIntoClosure::do_oop(oop* p) { Par_MarkRefsIntoClosure::do_oop_work(p); } 6845 void Par_MarkRefsIntoClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoClosure::do_oop_work(p); } 6846 6847 // A variant of the above, used for CMS marking verification. 6848 MarkRefsIntoVerifyClosure::MarkRefsIntoVerifyClosure( 6849 MemRegion span, CMSBitMap* verification_bm, CMSBitMap* cms_bm): 6850 _span(span), 6851 _verification_bm(verification_bm), 6852 _cms_bm(cms_bm) 6853 { 6854 assert(_ref_processor == NULL, "deliberately left NULL"); 6855 assert(_verification_bm->covers(_span), "_verification_bm/_span mismatch"); 6856 } 6857 6858 void MarkRefsIntoVerifyClosure::do_oop(oop obj) { 6859 // if p points into _span, then mark corresponding bit in _markBitMap 6860 assert(obj->is_oop(), "expected an oop"); 6861 HeapWord* addr = (HeapWord*)obj; 6862 if (_span.contains(addr)) { 6863 _verification_bm->mark(addr); 6864 if (!_cms_bm->isMarked(addr)) { 6865 oop(addr)->print(); 6866 gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)", addr); 6867 fatal("... aborting"); 6868 } 6869 } 6870 } 6871 6872 void MarkRefsIntoVerifyClosure::do_oop(oop* p) { MarkRefsIntoVerifyClosure::do_oop_work(p); } 6873 void MarkRefsIntoVerifyClosure::do_oop(narrowOop* p) { MarkRefsIntoVerifyClosure::do_oop_work(p); } 6874 6875 ////////////////////////////////////////////////// 6876 // MarkRefsIntoAndScanClosure 6877 ////////////////////////////////////////////////// 6878 6879 MarkRefsIntoAndScanClosure::MarkRefsIntoAndScanClosure(MemRegion span, 6880 ReferenceProcessor* rp, 6881 CMSBitMap* bit_map, 6882 CMSBitMap* mod_union_table, 6883 CMSMarkStack* mark_stack, 6884 CMSCollector* collector, 6885 bool should_yield, 6886 bool concurrent_precleaning): 6887 _collector(collector), 6888 _span(span), 6889 _bit_map(bit_map), 6890 _mark_stack(mark_stack), 6891 _pushAndMarkClosure(collector, span, rp, bit_map, mod_union_table, 6892 mark_stack, concurrent_precleaning), 6893 _yield(should_yield), 6894 _concurrent_precleaning(concurrent_precleaning), 6895 _freelistLock(NULL) 6896 { 6897 _ref_processor = rp; 6898 assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL"); 6899 } 6900 6901 // This closure is used to mark refs into the CMS generation at the 6902 // second (final) checkpoint, and to scan and transitively follow 6903 // the unmarked oops. It is also used during the concurrent precleaning 6904 // phase while scanning objects on dirty cards in the CMS generation. 6905 // The marks are made in the marking bit map and the marking stack is 6906 // used for keeping the (newly) grey objects during the scan. 6907 // The parallel version (Par_...) appears further below. 6908 void MarkRefsIntoAndScanClosure::do_oop(oop obj) { 6909 if (obj != NULL) { 6910 assert(obj->is_oop(), "expected an oop"); 6911 HeapWord* addr = (HeapWord*)obj; 6912 assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)"); 6913 assert(_collector->overflow_list_is_empty(), 6914 "overflow list should be empty"); 6915 if (_span.contains(addr) && 6916 !_bit_map->isMarked(addr)) { 6917 // mark bit map (object is now grey) 6918 _bit_map->mark(addr); 6919 // push on marking stack (stack should be empty), and drain the 6920 // stack by applying this closure to the oops in the oops popped 6921 // from the stack (i.e. blacken the grey objects) 6922 bool res = _mark_stack->push(obj); 6923 assert(res, "Should have space to push on empty stack"); 6924 do { 6925 oop new_oop = _mark_stack->pop(); 6926 assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop"); 6927 assert(_bit_map->isMarked((HeapWord*)new_oop), 6928 "only grey objects on this stack"); 6929 // iterate over the oops in this oop, marking and pushing 6930 // the ones in CMS heap (i.e. in _span). 6931 new_oop->oop_iterate(&_pushAndMarkClosure); 6932 // check if it's time to yield 6933 do_yield_check(); 6934 } while (!_mark_stack->isEmpty() || 6935 (!_concurrent_precleaning && take_from_overflow_list())); 6936 // if marking stack is empty, and we are not doing this 6937 // during precleaning, then check the overflow list 6938 } 6939 assert(_mark_stack->isEmpty(), "post-condition (eager drainage)"); 6940 assert(_collector->overflow_list_is_empty(), 6941 "overflow list was drained above"); 6942 // We could restore evacuated mark words, if any, used for 6943 // overflow list links here because the overflow list is 6944 // provably empty here. That would reduce the maximum 6945 // size requirements for preserved_{oop,mark}_stack. 6946 // But we'll just postpone it until we are all done 6947 // so we can just stream through. 6948 if (!_concurrent_precleaning && CMSOverflowEarlyRestoration) { 6949 _collector->restore_preserved_marks_if_any(); 6950 assert(_collector->no_preserved_marks(), "No preserved marks"); 6951 } 6952 assert(!CMSOverflowEarlyRestoration || _collector->no_preserved_marks(), 6953 "All preserved marks should have been restored above"); 6954 } 6955 } 6956 6957 void MarkRefsIntoAndScanClosure::do_oop(oop* p) { MarkRefsIntoAndScanClosure::do_oop_work(p); } 6958 void MarkRefsIntoAndScanClosure::do_oop(narrowOop* p) { MarkRefsIntoAndScanClosure::do_oop_work(p); } 6959 6960 void MarkRefsIntoAndScanClosure::do_yield_work() { 6961 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 6962 "CMS thread should hold CMS token"); 6963 assert_lock_strong(_freelistLock); 6964 assert_lock_strong(_bit_map->lock()); 6965 // relinquish the free_list_lock and bitMaplock() 6966 _bit_map->lock()->unlock(); 6967 _freelistLock->unlock(); 6968 ConcurrentMarkSweepThread::desynchronize(true); 6969 ConcurrentMarkSweepThread::acknowledge_yield_request(); 6970 _collector->stopTimer(); 6971 if (PrintCMSStatistics != 0) { 6972 _collector->incrementYields(); 6973 } 6974 _collector->icms_wait(); 6975 6976 // See the comment in coordinator_yield() 6977 for (unsigned i = 0; 6978 i < CMSYieldSleepCount && 6979 ConcurrentMarkSweepThread::should_yield() && 6980 !CMSCollector::foregroundGCIsActive(); 6981 ++i) { 6982 os::sleep(Thread::current(), 1, false); 6983 ConcurrentMarkSweepThread::acknowledge_yield_request(); 6984 } 6985 6986 ConcurrentMarkSweepThread::synchronize(true); 6987 _freelistLock->lock_without_safepoint_check(); 6988 _bit_map->lock()->lock_without_safepoint_check(); 6989 _collector->startTimer(); 6990 } 6991 6992 /////////////////////////////////////////////////////////// 6993 // Par_MarkRefsIntoAndScanClosure: a parallel version of 6994 // MarkRefsIntoAndScanClosure 6995 /////////////////////////////////////////////////////////// 6996 Par_MarkRefsIntoAndScanClosure::Par_MarkRefsIntoAndScanClosure( 6997 CMSCollector* collector, MemRegion span, ReferenceProcessor* rp, 6998 CMSBitMap* bit_map, OopTaskQueue* work_queue): 6999 _span(span), 7000 _bit_map(bit_map), 7001 _work_queue(work_queue), 7002 _low_water_mark(MIN2((uint)(work_queue->max_elems()/4), 7003 (uint)(CMSWorkQueueDrainThreshold * ParallelGCThreads))), 7004 _par_pushAndMarkClosure(collector, span, rp, bit_map, work_queue) 7005 { 7006 _ref_processor = rp; 7007 assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL"); 7008 } 7009 7010 // This closure is used to mark refs into the CMS generation at the 7011 // second (final) checkpoint, and to scan and transitively follow 7012 // the unmarked oops. The marks are made in the marking bit map and 7013 // the work_queue is used for keeping the (newly) grey objects during 7014 // the scan phase whence they are also available for stealing by parallel 7015 // threads. Since the marking bit map is shared, updates are 7016 // synchronized (via CAS). 7017 void Par_MarkRefsIntoAndScanClosure::do_oop(oop obj) { 7018 if (obj != NULL) { 7019 // Ignore mark word because this could be an already marked oop 7020 // that may be chained at the end of the overflow list. 7021 assert(obj->is_oop(true), "expected an oop"); 7022 HeapWord* addr = (HeapWord*)obj; 7023 if (_span.contains(addr) && 7024 !_bit_map->isMarked(addr)) { 7025 // mark bit map (object will become grey): 7026 // It is possible for several threads to be 7027 // trying to "claim" this object concurrently; 7028 // the unique thread that succeeds in marking the 7029 // object first will do the subsequent push on 7030 // to the work queue (or overflow list). 7031 if (_bit_map->par_mark(addr)) { 7032 // push on work_queue (which may not be empty), and trim the 7033 // queue to an appropriate length by applying this closure to 7034 // the oops in the oops popped from the stack (i.e. blacken the 7035 // grey objects) 7036 bool res = _work_queue->push(obj); 7037 assert(res, "Low water mark should be less than capacity?"); 7038 trim_queue(_low_water_mark); 7039 } // Else, another thread claimed the object 7040 } 7041 } 7042 } 7043 7044 void Par_MarkRefsIntoAndScanClosure::do_oop(oop* p) { Par_MarkRefsIntoAndScanClosure::do_oop_work(p); } 7045 void Par_MarkRefsIntoAndScanClosure::do_oop(narrowOop* p) { Par_MarkRefsIntoAndScanClosure::do_oop_work(p); } 7046 7047 // This closure is used to rescan the marked objects on the dirty cards 7048 // in the mod union table and the card table proper. 7049 size_t ScanMarkedObjectsAgainCarefullyClosure::do_object_careful_m( 7050 oop p, MemRegion mr) { 7051 7052 size_t size = 0; 7053 HeapWord* addr = (HeapWord*)p; 7054 DEBUG_ONLY(_collector->verify_work_stacks_empty();) 7055 assert(_span.contains(addr), "we are scanning the CMS generation"); 7056 // check if it's time to yield 7057 if (do_yield_check()) { 7058 // We yielded for some foreground stop-world work, 7059 // and we have been asked to abort this ongoing preclean cycle. 7060 return 0; 7061 } 7062 if (_bitMap->isMarked(addr)) { 7063 // it's marked; is it potentially uninitialized? 7064 if (p->klass_or_null() != NULL) { 7065 // an initialized object; ignore mark word in verification below 7066 // since we are running concurrent with mutators 7067 assert(p->is_oop(true), "should be an oop"); 7068 if (p->is_objArray()) { 7069 // objArrays are precisely marked; restrict scanning 7070 // to dirty cards only. 7071 size = CompactibleFreeListSpace::adjustObjectSize( 7072 p->oop_iterate(_scanningClosure, mr)); 7073 } else { 7074 // A non-array may have been imprecisely marked; we need 7075 // to scan object in its entirety. 7076 size = CompactibleFreeListSpace::adjustObjectSize( 7077 p->oop_iterate(_scanningClosure)); 7078 } 7079 #ifdef ASSERT 7080 size_t direct_size = 7081 CompactibleFreeListSpace::adjustObjectSize(p->size()); 7082 assert(size == direct_size, "Inconsistency in size"); 7083 assert(size >= 3, "Necessary for Printezis marks to work"); 7084 if (!_bitMap->isMarked(addr+1)) { 7085 _bitMap->verifyNoOneBitsInRange(addr+2, addr+size); 7086 } else { 7087 _bitMap->verifyNoOneBitsInRange(addr+2, addr+size-1); 7088 assert(_bitMap->isMarked(addr+size-1), 7089 "inconsistent Printezis mark"); 7090 } 7091 #endif // ASSERT 7092 } else { 7093 // An uninitialized object. 7094 assert(_bitMap->isMarked(addr+1), "missing Printezis mark?"); 7095 HeapWord* nextOneAddr = _bitMap->getNextMarkedWordAddress(addr + 2); 7096 size = pointer_delta(nextOneAddr + 1, addr); 7097 assert(size == CompactibleFreeListSpace::adjustObjectSize(size), 7098 "alignment problem"); 7099 // Note that pre-cleaning needn't redirty the card. OopDesc::set_klass() 7100 // will dirty the card when the klass pointer is installed in the 7101 // object (signaling the completion of initialization). 7102 } 7103 } else { 7104 // Either a not yet marked object or an uninitialized object 7105 if (p->klass_or_null() == NULL) { 7106 // An uninitialized object, skip to the next card, since 7107 // we may not be able to read its P-bits yet. 7108 assert(size == 0, "Initial value"); 7109 } else { 7110 // An object not (yet) reached by marking: we merely need to 7111 // compute its size so as to go look at the next block. 7112 assert(p->is_oop(true), "should be an oop"); 7113 size = CompactibleFreeListSpace::adjustObjectSize(p->size()); 7114 } 7115 } 7116 DEBUG_ONLY(_collector->verify_work_stacks_empty();) 7117 return size; 7118 } 7119 7120 void ScanMarkedObjectsAgainCarefullyClosure::do_yield_work() { 7121 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 7122 "CMS thread should hold CMS token"); 7123 assert_lock_strong(_freelistLock); 7124 assert_lock_strong(_bitMap->lock()); 7125 // relinquish the free_list_lock and bitMaplock() 7126 _bitMap->lock()->unlock(); 7127 _freelistLock->unlock(); 7128 ConcurrentMarkSweepThread::desynchronize(true); 7129 ConcurrentMarkSweepThread::acknowledge_yield_request(); 7130 _collector->stopTimer(); 7131 if (PrintCMSStatistics != 0) { 7132 _collector->incrementYields(); 7133 } 7134 _collector->icms_wait(); 7135 7136 // See the comment in coordinator_yield() 7137 for (unsigned i = 0; i < CMSYieldSleepCount && 7138 ConcurrentMarkSweepThread::should_yield() && 7139 !CMSCollector::foregroundGCIsActive(); ++i) { 7140 os::sleep(Thread::current(), 1, false); 7141 ConcurrentMarkSweepThread::acknowledge_yield_request(); 7142 } 7143 7144 ConcurrentMarkSweepThread::synchronize(true); 7145 _freelistLock->lock_without_safepoint_check(); 7146 _bitMap->lock()->lock_without_safepoint_check(); 7147 _collector->startTimer(); 7148 } 7149 7150 7151 ////////////////////////////////////////////////////////////////// 7152 // SurvivorSpacePrecleanClosure 7153 ////////////////////////////////////////////////////////////////// 7154 // This (single-threaded) closure is used to preclean the oops in 7155 // the survivor spaces. 7156 size_t SurvivorSpacePrecleanClosure::do_object_careful(oop p) { 7157 7158 HeapWord* addr = (HeapWord*)p; 7159 DEBUG_ONLY(_collector->verify_work_stacks_empty();) 7160 assert(!_span.contains(addr), "we are scanning the survivor spaces"); 7161 assert(p->klass_or_null() != NULL, "object should be initialized"); 7162 // an initialized object; ignore mark word in verification below 7163 // since we are running concurrent with mutators 7164 assert(p->is_oop(true), "should be an oop"); 7165 // Note that we do not yield while we iterate over 7166 // the interior oops of p, pushing the relevant ones 7167 // on our marking stack. 7168 size_t size = p->oop_iterate(_scanning_closure); 7169 do_yield_check(); 7170 // Observe that below, we do not abandon the preclean 7171 // phase as soon as we should; rather we empty the 7172 // marking stack before returning. This is to satisfy 7173 // some existing assertions. In general, it may be a 7174 // good idea to abort immediately and complete the marking 7175 // from the grey objects at a later time. 7176 while (!_mark_stack->isEmpty()) { 7177 oop new_oop = _mark_stack->pop(); 7178 assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop"); 7179 assert(_bit_map->isMarked((HeapWord*)new_oop), 7180 "only grey objects on this stack"); 7181 // iterate over the oops in this oop, marking and pushing 7182 // the ones in CMS heap (i.e. in _span). 7183 new_oop->oop_iterate(_scanning_closure); 7184 // check if it's time to yield 7185 do_yield_check(); 7186 } 7187 unsigned int after_count = 7188 GenCollectedHeap::heap()->total_collections(); 7189 bool abort = (_before_count != after_count) || 7190 _collector->should_abort_preclean(); 7191 return abort ? 0 : size; 7192 } 7193 7194 void SurvivorSpacePrecleanClosure::do_yield_work() { 7195 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 7196 "CMS thread should hold CMS token"); 7197 assert_lock_strong(_bit_map->lock()); 7198 // Relinquish the bit map lock 7199 _bit_map->lock()->unlock(); 7200 ConcurrentMarkSweepThread::desynchronize(true); 7201 ConcurrentMarkSweepThread::acknowledge_yield_request(); 7202 _collector->stopTimer(); 7203 if (PrintCMSStatistics != 0) { 7204 _collector->incrementYields(); 7205 } 7206 _collector->icms_wait(); 7207 7208 // See the comment in coordinator_yield() 7209 for (unsigned i = 0; i < CMSYieldSleepCount && 7210 ConcurrentMarkSweepThread::should_yield() && 7211 !CMSCollector::foregroundGCIsActive(); ++i) { 7212 os::sleep(Thread::current(), 1, false); 7213 ConcurrentMarkSweepThread::acknowledge_yield_request(); 7214 } 7215 7216 ConcurrentMarkSweepThread::synchronize(true); 7217 _bit_map->lock()->lock_without_safepoint_check(); 7218 _collector->startTimer(); 7219 } 7220 7221 // This closure is used to rescan the marked objects on the dirty cards 7222 // in the mod union table and the card table proper. In the parallel 7223 // case, although the bitMap is shared, we do a single read so the 7224 // isMarked() query is "safe". 7225 bool ScanMarkedObjectsAgainClosure::do_object_bm(oop p, MemRegion mr) { 7226 // Ignore mark word because we are running concurrent with mutators 7227 assert(p->is_oop_or_null(true), "expected an oop or null"); 7228 HeapWord* addr = (HeapWord*)p; 7229 assert(_span.contains(addr), "we are scanning the CMS generation"); 7230 bool is_obj_array = false; 7231 #ifdef ASSERT 7232 if (!_parallel) { 7233 assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)"); 7234 assert(_collector->overflow_list_is_empty(), 7235 "overflow list should be empty"); 7236 7237 } 7238 #endif // ASSERT 7239 if (_bit_map->isMarked(addr)) { 7240 // Obj arrays are precisely marked, non-arrays are not; 7241 // so we scan objArrays precisely and non-arrays in their 7242 // entirety. 7243 if (p->is_objArray()) { 7244 is_obj_array = true; 7245 if (_parallel) { 7246 p->oop_iterate(_par_scan_closure, mr); 7247 } else { 7248 p->oop_iterate(_scan_closure, mr); 7249 } 7250 } else { 7251 if (_parallel) { 7252 p->oop_iterate(_par_scan_closure); 7253 } else { 7254 p->oop_iterate(_scan_closure); 7255 } 7256 } 7257 } 7258 #ifdef ASSERT 7259 if (!_parallel) { 7260 assert(_mark_stack->isEmpty(), "post-condition (eager drainage)"); 7261 assert(_collector->overflow_list_is_empty(), 7262 "overflow list should be empty"); 7263 7264 } 7265 #endif // ASSERT 7266 return is_obj_array; 7267 } 7268 7269 MarkFromRootsClosure::MarkFromRootsClosure(CMSCollector* collector, 7270 MemRegion span, 7271 CMSBitMap* bitMap, CMSMarkStack* markStack, 7272 bool should_yield, bool verifying): 7273 _collector(collector), 7274 _span(span), 7275 _bitMap(bitMap), 7276 _mut(&collector->_modUnionTable), 7277 _markStack(markStack), 7278 _yield(should_yield), 7279 _skipBits(0) 7280 { 7281 assert(_markStack->isEmpty(), "stack should be empty"); 7282 _finger = _bitMap->startWord(); 7283 _threshold = _finger; 7284 assert(_collector->_restart_addr == NULL, "Sanity check"); 7285 assert(_span.contains(_finger), "Out of bounds _finger?"); 7286 DEBUG_ONLY(_verifying = verifying;) 7287 } 7288 7289 void MarkFromRootsClosure::reset(HeapWord* addr) { 7290 assert(_markStack->isEmpty(), "would cause duplicates on stack"); 7291 assert(_span.contains(addr), "Out of bounds _finger?"); 7292 _finger = addr; 7293 _threshold = (HeapWord*)round_to( 7294 (intptr_t)_finger, CardTableModRefBS::card_size); 7295 } 7296 7297 // Should revisit to see if this should be restructured for 7298 // greater efficiency. 7299 bool MarkFromRootsClosure::do_bit(size_t offset) { 7300 if (_skipBits > 0) { 7301 _skipBits--; 7302 return true; 7303 } 7304 // convert offset into a HeapWord* 7305 HeapWord* addr = _bitMap->startWord() + offset; 7306 assert(_bitMap->endWord() && addr < _bitMap->endWord(), 7307 "address out of range"); 7308 assert(_bitMap->isMarked(addr), "tautology"); 7309 if (_bitMap->isMarked(addr+1)) { 7310 // this is an allocated but not yet initialized object 7311 assert(_skipBits == 0, "tautology"); 7312 _skipBits = 2; // skip next two marked bits ("Printezis-marks") 7313 oop p = oop(addr); 7314 if (p->klass_or_null() == NULL) { 7315 DEBUG_ONLY(if (!_verifying) {) 7316 // We re-dirty the cards on which this object lies and increase 7317 // the _threshold so that we'll come back to scan this object 7318 // during the preclean or remark phase. (CMSCleanOnEnter) 7319 if (CMSCleanOnEnter) { 7320 size_t sz = _collector->block_size_using_printezis_bits(addr); 7321 HeapWord* end_card_addr = (HeapWord*)round_to( 7322 (intptr_t)(addr+sz), CardTableModRefBS::card_size); 7323 MemRegion redirty_range = MemRegion(addr, end_card_addr); 7324 assert(!redirty_range.is_empty(), "Arithmetical tautology"); 7325 // Bump _threshold to end_card_addr; note that 7326 // _threshold cannot possibly exceed end_card_addr, anyhow. 7327 // This prevents future clearing of the card as the scan proceeds 7328 // to the right. 7329 assert(_threshold <= end_card_addr, 7330 "Because we are just scanning into this object"); 7331 if (_threshold < end_card_addr) { 7332 _threshold = end_card_addr; 7333 } 7334 if (p->klass_or_null() != NULL) { 7335 // Redirty the range of cards... 7336 _mut->mark_range(redirty_range); 7337 } // ...else the setting of klass will dirty the card anyway. 7338 } 7339 DEBUG_ONLY(}) 7340 return true; 7341 } 7342 } 7343 scanOopsInOop(addr); 7344 return true; 7345 } 7346 7347 // We take a break if we've been at this for a while, 7348 // so as to avoid monopolizing the locks involved. 7349 void MarkFromRootsClosure::do_yield_work() { 7350 // First give up the locks, then yield, then re-lock 7351 // We should probably use a constructor/destructor idiom to 7352 // do this unlock/lock or modify the MutexUnlocker class to 7353 // serve our purpose. XXX 7354 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 7355 "CMS thread should hold CMS token"); 7356 assert_lock_strong(_bitMap->lock()); 7357 _bitMap->lock()->unlock(); 7358 ConcurrentMarkSweepThread::desynchronize(true); 7359 ConcurrentMarkSweepThread::acknowledge_yield_request(); 7360 _collector->stopTimer(); 7361 if (PrintCMSStatistics != 0) { 7362 _collector->incrementYields(); 7363 } 7364 _collector->icms_wait(); 7365 7366 // See the comment in coordinator_yield() 7367 for (unsigned i = 0; i < CMSYieldSleepCount && 7368 ConcurrentMarkSweepThread::should_yield() && 7369 !CMSCollector::foregroundGCIsActive(); ++i) { 7370 os::sleep(Thread::current(), 1, false); 7371 ConcurrentMarkSweepThread::acknowledge_yield_request(); 7372 } 7373 7374 ConcurrentMarkSweepThread::synchronize(true); 7375 _bitMap->lock()->lock_without_safepoint_check(); 7376 _collector->startTimer(); 7377 } 7378 7379 void MarkFromRootsClosure::scanOopsInOop(HeapWord* ptr) { 7380 assert(_bitMap->isMarked(ptr), "expected bit to be set"); 7381 assert(_markStack->isEmpty(), 7382 "should drain stack to limit stack usage"); 7383 // convert ptr to an oop preparatory to scanning 7384 oop obj = oop(ptr); 7385 // Ignore mark word in verification below, since we 7386 // may be running concurrent with mutators. 7387 assert(obj->is_oop(true), "should be an oop"); 7388 assert(_finger <= ptr, "_finger runneth ahead"); 7389 // advance the finger to right end of this object 7390 _finger = ptr + obj->size(); 7391 assert(_finger > ptr, "we just incremented it above"); 7392 // On large heaps, it may take us some time to get through 7393 // the marking phase (especially if running iCMS). During 7394 // this time it's possible that a lot of mutations have 7395 // accumulated in the card table and the mod union table -- 7396 // these mutation records are redundant until we have 7397 // actually traced into the corresponding card. 7398 // Here, we check whether advancing the finger would make 7399 // us cross into a new card, and if so clear corresponding 7400 // cards in the MUT (preclean them in the card-table in the 7401 // future). 7402 7403 DEBUG_ONLY(if (!_verifying) {) 7404 // The clean-on-enter optimization is disabled by default, 7405 // until we fix 6178663. 7406 if (CMSCleanOnEnter && (_finger > _threshold)) { 7407 // [_threshold, _finger) represents the interval 7408 // of cards to be cleared in MUT (or precleaned in card table). 7409 // The set of cards to be cleared is all those that overlap 7410 // with the interval [_threshold, _finger); note that 7411 // _threshold is always kept card-aligned but _finger isn't 7412 // always card-aligned. 7413 HeapWord* old_threshold = _threshold; 7414 assert(old_threshold == (HeapWord*)round_to( 7415 (intptr_t)old_threshold, CardTableModRefBS::card_size), 7416 "_threshold should always be card-aligned"); 7417 _threshold = (HeapWord*)round_to( 7418 (intptr_t)_finger, CardTableModRefBS::card_size); 7419 MemRegion mr(old_threshold, _threshold); 7420 assert(!mr.is_empty(), "Control point invariant"); 7421 assert(_span.contains(mr), "Should clear within span"); 7422 _mut->clear_range(mr); 7423 } 7424 DEBUG_ONLY(}) 7425 // Note: the finger doesn't advance while we drain 7426 // the stack below. 7427 PushOrMarkClosure pushOrMarkClosure(_collector, 7428 _span, _bitMap, _markStack, 7429 _finger, this); 7430 bool res = _markStack->push(obj); 7431 assert(res, "Empty non-zero size stack should have space for single push"); 7432 while (!_markStack->isEmpty()) { 7433 oop new_oop = _markStack->pop(); 7434 // Skip verifying header mark word below because we are 7435 // running concurrent with mutators. 7436 assert(new_oop->is_oop(true), "Oops! expected to pop an oop"); 7437 // now scan this oop's oops 7438 new_oop->oop_iterate(&pushOrMarkClosure); 7439 do_yield_check(); 7440 } 7441 assert(_markStack->isEmpty(), "tautology, emphasizing post-condition"); 7442 } 7443 7444 Par_MarkFromRootsClosure::Par_MarkFromRootsClosure(CMSConcMarkingTask* task, 7445 CMSCollector* collector, MemRegion span, 7446 CMSBitMap* bit_map, 7447 OopTaskQueue* work_queue, 7448 CMSMarkStack* overflow_stack, 7449 bool should_yield): 7450 _collector(collector), 7451 _whole_span(collector->_span), 7452 _span(span), 7453 _bit_map(bit_map), 7454 _mut(&collector->_modUnionTable), 7455 _work_queue(work_queue), 7456 _overflow_stack(overflow_stack), 7457 _yield(should_yield), 7458 _skip_bits(0), 7459 _task(task) 7460 { 7461 assert(_work_queue->size() == 0, "work_queue should be empty"); 7462 _finger = span.start(); 7463 _threshold = _finger; // XXX Defer clear-on-enter optimization for now 7464 assert(_span.contains(_finger), "Out of bounds _finger?"); 7465 } 7466 7467 // Should revisit to see if this should be restructured for 7468 // greater efficiency. 7469 bool Par_MarkFromRootsClosure::do_bit(size_t offset) { 7470 if (_skip_bits > 0) { 7471 _skip_bits--; 7472 return true; 7473 } 7474 // convert offset into a HeapWord* 7475 HeapWord* addr = _bit_map->startWord() + offset; 7476 assert(_bit_map->endWord() && addr < _bit_map->endWord(), 7477 "address out of range"); 7478 assert(_bit_map->isMarked(addr), "tautology"); 7479 if (_bit_map->isMarked(addr+1)) { 7480 // this is an allocated object that might not yet be initialized 7481 assert(_skip_bits == 0, "tautology"); 7482 _skip_bits = 2; // skip next two marked bits ("Printezis-marks") 7483 oop p = oop(addr); 7484 if (p->klass_or_null() == NULL) { 7485 // in the case of Clean-on-Enter optimization, redirty card 7486 // and avoid clearing card by increasing the threshold. 7487 return true; 7488 } 7489 } 7490 scan_oops_in_oop(addr); 7491 return true; 7492 } 7493 7494 void Par_MarkFromRootsClosure::scan_oops_in_oop(HeapWord* ptr) { 7495 assert(_bit_map->isMarked(ptr), "expected bit to be set"); 7496 // Should we assert that our work queue is empty or 7497 // below some drain limit? 7498 assert(_work_queue->size() == 0, 7499 "should drain stack to limit stack usage"); 7500 // convert ptr to an oop preparatory to scanning 7501 oop obj = oop(ptr); 7502 // Ignore mark word in verification below, since we 7503 // may be running concurrent with mutators. 7504 assert(obj->is_oop(true), "should be an oop"); 7505 assert(_finger <= ptr, "_finger runneth ahead"); 7506 // advance the finger to right end of this object 7507 _finger = ptr + obj->size(); 7508 assert(_finger > ptr, "we just incremented it above"); 7509 // On large heaps, it may take us some time to get through 7510 // the marking phase (especially if running iCMS). During 7511 // this time it's possible that a lot of mutations have 7512 // accumulated in the card table and the mod union table -- 7513 // these mutation records are redundant until we have 7514 // actually traced into the corresponding card. 7515 // Here, we check whether advancing the finger would make 7516 // us cross into a new card, and if so clear corresponding 7517 // cards in the MUT (preclean them in the card-table in the 7518 // future). 7519 7520 // The clean-on-enter optimization is disabled by default, 7521 // until we fix 6178663. 7522 if (CMSCleanOnEnter && (_finger > _threshold)) { 7523 // [_threshold, _finger) represents the interval 7524 // of cards to be cleared in MUT (or precleaned in card table). 7525 // The set of cards to be cleared is all those that overlap 7526 // with the interval [_threshold, _finger); note that 7527 // _threshold is always kept card-aligned but _finger isn't 7528 // always card-aligned. 7529 HeapWord* old_threshold = _threshold; 7530 assert(old_threshold == (HeapWord*)round_to( 7531 (intptr_t)old_threshold, CardTableModRefBS::card_size), 7532 "_threshold should always be card-aligned"); 7533 _threshold = (HeapWord*)round_to( 7534 (intptr_t)_finger, CardTableModRefBS::card_size); 7535 MemRegion mr(old_threshold, _threshold); 7536 assert(!mr.is_empty(), "Control point invariant"); 7537 assert(_span.contains(mr), "Should clear within span"); // _whole_span ?? 7538 _mut->clear_range(mr); 7539 } 7540 7541 // Note: the local finger doesn't advance while we drain 7542 // the stack below, but the global finger sure can and will. 7543 HeapWord** gfa = _task->global_finger_addr(); 7544 Par_PushOrMarkClosure pushOrMarkClosure(_collector, 7545 _span, _bit_map, 7546 _work_queue, 7547 _overflow_stack, 7548 _finger, 7549 gfa, this); 7550 bool res = _work_queue->push(obj); // overflow could occur here 7551 assert(res, "Will hold once we use workqueues"); 7552 while (true) { 7553 oop new_oop; 7554 if (!_work_queue->pop_local(new_oop)) { 7555 // We emptied our work_queue; check if there's stuff that can 7556 // be gotten from the overflow stack. 7557 if (CMSConcMarkingTask::get_work_from_overflow_stack( 7558 _overflow_stack, _work_queue)) { 7559 do_yield_check(); 7560 continue; 7561 } else { // done 7562 break; 7563 } 7564 } 7565 // Skip verifying header mark word below because we are 7566 // running concurrent with mutators. 7567 assert(new_oop->is_oop(true), "Oops! expected to pop an oop"); 7568 // now scan this oop's oops 7569 new_oop->oop_iterate(&pushOrMarkClosure); 7570 do_yield_check(); 7571 } 7572 assert(_work_queue->size() == 0, "tautology, emphasizing post-condition"); 7573 } 7574 7575 // Yield in response to a request from VM Thread or 7576 // from mutators. 7577 void Par_MarkFromRootsClosure::do_yield_work() { 7578 assert(_task != NULL, "sanity"); 7579 _task->yield(); 7580 } 7581 7582 // A variant of the above used for verifying CMS marking work. 7583 MarkFromRootsVerifyClosure::MarkFromRootsVerifyClosure(CMSCollector* collector, 7584 MemRegion span, 7585 CMSBitMap* verification_bm, CMSBitMap* cms_bm, 7586 CMSMarkStack* mark_stack): 7587 _collector(collector), 7588 _span(span), 7589 _verification_bm(verification_bm), 7590 _cms_bm(cms_bm), 7591 _mark_stack(mark_stack), 7592 _pam_verify_closure(collector, span, verification_bm, cms_bm, 7593 mark_stack) 7594 { 7595 assert(_mark_stack->isEmpty(), "stack should be empty"); 7596 _finger = _verification_bm->startWord(); 7597 assert(_collector->_restart_addr == NULL, "Sanity check"); 7598 assert(_span.contains(_finger), "Out of bounds _finger?"); 7599 } 7600 7601 void MarkFromRootsVerifyClosure::reset(HeapWord* addr) { 7602 assert(_mark_stack->isEmpty(), "would cause duplicates on stack"); 7603 assert(_span.contains(addr), "Out of bounds _finger?"); 7604 _finger = addr; 7605 } 7606 7607 // Should revisit to see if this should be restructured for 7608 // greater efficiency. 7609 bool MarkFromRootsVerifyClosure::do_bit(size_t offset) { 7610 // convert offset into a HeapWord* 7611 HeapWord* addr = _verification_bm->startWord() + offset; 7612 assert(_verification_bm->endWord() && addr < _verification_bm->endWord(), 7613 "address out of range"); 7614 assert(_verification_bm->isMarked(addr), "tautology"); 7615 assert(_cms_bm->isMarked(addr), "tautology"); 7616 7617 assert(_mark_stack->isEmpty(), 7618 "should drain stack to limit stack usage"); 7619 // convert addr to an oop preparatory to scanning 7620 oop obj = oop(addr); 7621 assert(obj->is_oop(), "should be an oop"); 7622 assert(_finger <= addr, "_finger runneth ahead"); 7623 // advance the finger to right end of this object 7624 _finger = addr + obj->size(); 7625 assert(_finger > addr, "we just incremented it above"); 7626 // Note: the finger doesn't advance while we drain 7627 // the stack below. 7628 bool res = _mark_stack->push(obj); 7629 assert(res, "Empty non-zero size stack should have space for single push"); 7630 while (!_mark_stack->isEmpty()) { 7631 oop new_oop = _mark_stack->pop(); 7632 assert(new_oop->is_oop(), "Oops! expected to pop an oop"); 7633 // now scan this oop's oops 7634 new_oop->oop_iterate(&_pam_verify_closure); 7635 } 7636 assert(_mark_stack->isEmpty(), "tautology, emphasizing post-condition"); 7637 return true; 7638 } 7639 7640 PushAndMarkVerifyClosure::PushAndMarkVerifyClosure( 7641 CMSCollector* collector, MemRegion span, 7642 CMSBitMap* verification_bm, CMSBitMap* cms_bm, 7643 CMSMarkStack* mark_stack): 7644 MetadataAwareOopClosure(collector->ref_processor()), 7645 _collector(collector), 7646 _span(span), 7647 _verification_bm(verification_bm), 7648 _cms_bm(cms_bm), 7649 _mark_stack(mark_stack) 7650 { } 7651 7652 void PushAndMarkVerifyClosure::do_oop(oop* p) { PushAndMarkVerifyClosure::do_oop_work(p); } 7653 void PushAndMarkVerifyClosure::do_oop(narrowOop* p) { PushAndMarkVerifyClosure::do_oop_work(p); } 7654 7655 // Upon stack overflow, we discard (part of) the stack, 7656 // remembering the least address amongst those discarded 7657 // in CMSCollector's _restart_address. 7658 void PushAndMarkVerifyClosure::handle_stack_overflow(HeapWord* lost) { 7659 // Remember the least grey address discarded 7660 HeapWord* ra = (HeapWord*)_mark_stack->least_value(lost); 7661 _collector->lower_restart_addr(ra); 7662 _mark_stack->reset(); // discard stack contents 7663 _mark_stack->expand(); // expand the stack if possible 7664 } 7665 7666 void PushAndMarkVerifyClosure::do_oop(oop obj) { 7667 assert(obj->is_oop_or_null(), "expected an oop or NULL"); 7668 HeapWord* addr = (HeapWord*)obj; 7669 if (_span.contains(addr) && !_verification_bm->isMarked(addr)) { 7670 // Oop lies in _span and isn't yet grey or black 7671 _verification_bm->mark(addr); // now grey 7672 if (!_cms_bm->isMarked(addr)) { 7673 oop(addr)->print(); 7674 gclog_or_tty->print_cr(" (" INTPTR_FORMAT " should have been marked)", 7675 addr); 7676 fatal("... aborting"); 7677 } 7678 7679 if (!_mark_stack->push(obj)) { // stack overflow 7680 if (PrintCMSStatistics != 0) { 7681 gclog_or_tty->print_cr("CMS marking stack overflow (benign) at " 7682 SIZE_FORMAT, _mark_stack->capacity()); 7683 } 7684 assert(_mark_stack->isFull(), "Else push should have succeeded"); 7685 handle_stack_overflow(addr); 7686 } 7687 // anything including and to the right of _finger 7688 // will be scanned as we iterate over the remainder of the 7689 // bit map 7690 } 7691 } 7692 7693 PushOrMarkClosure::PushOrMarkClosure(CMSCollector* collector, 7694 MemRegion span, 7695 CMSBitMap* bitMap, CMSMarkStack* markStack, 7696 HeapWord* finger, MarkFromRootsClosure* parent) : 7697 MetadataAwareOopClosure(collector->ref_processor()), 7698 _collector(collector), 7699 _span(span), 7700 _bitMap(bitMap), 7701 _markStack(markStack), 7702 _finger(finger), 7703 _parent(parent) 7704 { } 7705 7706 Par_PushOrMarkClosure::Par_PushOrMarkClosure(CMSCollector* collector, 7707 MemRegion span, 7708 CMSBitMap* bit_map, 7709 OopTaskQueue* work_queue, 7710 CMSMarkStack* overflow_stack, 7711 HeapWord* finger, 7712 HeapWord** global_finger_addr, 7713 Par_MarkFromRootsClosure* parent) : 7714 MetadataAwareOopClosure(collector->ref_processor()), 7715 _collector(collector), 7716 _whole_span(collector->_span), 7717 _span(span), 7718 _bit_map(bit_map), 7719 _work_queue(work_queue), 7720 _overflow_stack(overflow_stack), 7721 _finger(finger), 7722 _global_finger_addr(global_finger_addr), 7723 _parent(parent) 7724 { } 7725 7726 // Assumes thread-safe access by callers, who are 7727 // responsible for mutual exclusion. 7728 void CMSCollector::lower_restart_addr(HeapWord* low) { 7729 assert(_span.contains(low), "Out of bounds addr"); 7730 if (_restart_addr == NULL) { 7731 _restart_addr = low; 7732 } else { 7733 _restart_addr = MIN2(_restart_addr, low); 7734 } 7735 } 7736 7737 // Upon stack overflow, we discard (part of) the stack, 7738 // remembering the least address amongst those discarded 7739 // in CMSCollector's _restart_address. 7740 void PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) { 7741 // Remember the least grey address discarded 7742 HeapWord* ra = (HeapWord*)_markStack->least_value(lost); 7743 _collector->lower_restart_addr(ra); 7744 _markStack->reset(); // discard stack contents 7745 _markStack->expand(); // expand the stack if possible 7746 } 7747 7748 // Upon stack overflow, we discard (part of) the stack, 7749 // remembering the least address amongst those discarded 7750 // in CMSCollector's _restart_address. 7751 void Par_PushOrMarkClosure::handle_stack_overflow(HeapWord* lost) { 7752 // We need to do this under a mutex to prevent other 7753 // workers from interfering with the work done below. 7754 MutexLockerEx ml(_overflow_stack->par_lock(), 7755 Mutex::_no_safepoint_check_flag); 7756 // Remember the least grey address discarded 7757 HeapWord* ra = (HeapWord*)_overflow_stack->least_value(lost); 7758 _collector->lower_restart_addr(ra); 7759 _overflow_stack->reset(); // discard stack contents 7760 _overflow_stack->expand(); // expand the stack if possible 7761 } 7762 7763 void PushOrMarkClosure::do_oop(oop obj) { 7764 // Ignore mark word because we are running concurrent with mutators. 7765 assert(obj->is_oop_or_null(true), "expected an oop or NULL"); 7766 HeapWord* addr = (HeapWord*)obj; 7767 if (_span.contains(addr) && !_bitMap->isMarked(addr)) { 7768 // Oop lies in _span and isn't yet grey or black 7769 _bitMap->mark(addr); // now grey 7770 if (addr < _finger) { 7771 // the bit map iteration has already either passed, or 7772 // sampled, this bit in the bit map; we'll need to 7773 // use the marking stack to scan this oop's oops. 7774 bool simulate_overflow = false; 7775 NOT_PRODUCT( 7776 if (CMSMarkStackOverflowALot && 7777 _collector->simulate_overflow()) { 7778 // simulate a stack overflow 7779 simulate_overflow = true; 7780 } 7781 ) 7782 if (simulate_overflow || !_markStack->push(obj)) { // stack overflow 7783 if (PrintCMSStatistics != 0) { 7784 gclog_or_tty->print_cr("CMS marking stack overflow (benign) at " 7785 SIZE_FORMAT, _markStack->capacity()); 7786 } 7787 assert(simulate_overflow || _markStack->isFull(), "Else push should have succeeded"); 7788 handle_stack_overflow(addr); 7789 } 7790 } 7791 // anything including and to the right of _finger 7792 // will be scanned as we iterate over the remainder of the 7793 // bit map 7794 do_yield_check(); 7795 } 7796 } 7797 7798 void PushOrMarkClosure::do_oop(oop* p) { PushOrMarkClosure::do_oop_work(p); } 7799 void PushOrMarkClosure::do_oop(narrowOop* p) { PushOrMarkClosure::do_oop_work(p); } 7800 7801 void Par_PushOrMarkClosure::do_oop(oop obj) { 7802 // Ignore mark word because we are running concurrent with mutators. 7803 assert(obj->is_oop_or_null(true), "expected an oop or NULL"); 7804 HeapWord* addr = (HeapWord*)obj; 7805 if (_whole_span.contains(addr) && !_bit_map->isMarked(addr)) { 7806 // Oop lies in _span and isn't yet grey or black 7807 // We read the global_finger (volatile read) strictly after marking oop 7808 bool res = _bit_map->par_mark(addr); // now grey 7809 volatile HeapWord** gfa = (volatile HeapWord**)_global_finger_addr; 7810 // Should we push this marked oop on our stack? 7811 // -- if someone else marked it, nothing to do 7812 // -- if target oop is above global finger nothing to do 7813 // -- if target oop is in chunk and above local finger 7814 // then nothing to do 7815 // -- else push on work queue 7816 if ( !res // someone else marked it, they will deal with it 7817 || (addr >= *gfa) // will be scanned in a later task 7818 || (_span.contains(addr) && addr >= _finger)) { // later in this chunk 7819 return; 7820 } 7821 // the bit map iteration has already either passed, or 7822 // sampled, this bit in the bit map; we'll need to 7823 // use the marking stack to scan this oop's oops. 7824 bool simulate_overflow = false; 7825 NOT_PRODUCT( 7826 if (CMSMarkStackOverflowALot && 7827 _collector->simulate_overflow()) { 7828 // simulate a stack overflow 7829 simulate_overflow = true; 7830 } 7831 ) 7832 if (simulate_overflow || 7833 !(_work_queue->push(obj) || _overflow_stack->par_push(obj))) { 7834 // stack overflow 7835 if (PrintCMSStatistics != 0) { 7836 gclog_or_tty->print_cr("CMS marking stack overflow (benign) at " 7837 SIZE_FORMAT, _overflow_stack->capacity()); 7838 } 7839 // We cannot assert that the overflow stack is full because 7840 // it may have been emptied since. 7841 assert(simulate_overflow || 7842 _work_queue->size() == _work_queue->max_elems(), 7843 "Else push should have succeeded"); 7844 handle_stack_overflow(addr); 7845 } 7846 do_yield_check(); 7847 } 7848 } 7849 7850 void Par_PushOrMarkClosure::do_oop(oop* p) { Par_PushOrMarkClosure::do_oop_work(p); } 7851 void Par_PushOrMarkClosure::do_oop(narrowOop* p) { Par_PushOrMarkClosure::do_oop_work(p); } 7852 7853 PushAndMarkClosure::PushAndMarkClosure(CMSCollector* collector, 7854 MemRegion span, 7855 ReferenceProcessor* rp, 7856 CMSBitMap* bit_map, 7857 CMSBitMap* mod_union_table, 7858 CMSMarkStack* mark_stack, 7859 bool concurrent_precleaning): 7860 MetadataAwareOopClosure(rp), 7861 _collector(collector), 7862 _span(span), 7863 _bit_map(bit_map), 7864 _mod_union_table(mod_union_table), 7865 _mark_stack(mark_stack), 7866 _concurrent_precleaning(concurrent_precleaning) 7867 { 7868 assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL"); 7869 } 7870 7871 // Grey object rescan during pre-cleaning and second checkpoint phases -- 7872 // the non-parallel version (the parallel version appears further below.) 7873 void PushAndMarkClosure::do_oop(oop obj) { 7874 // Ignore mark word verification. If during concurrent precleaning, 7875 // the object monitor may be locked. If during the checkpoint 7876 // phases, the object may already have been reached by a different 7877 // path and may be at the end of the global overflow list (so 7878 // the mark word may be NULL). 7879 assert(obj->is_oop_or_null(true /* ignore mark word */), 7880 "expected an oop or NULL"); 7881 HeapWord* addr = (HeapWord*)obj; 7882 // Check if oop points into the CMS generation 7883 // and is not marked 7884 if (_span.contains(addr) && !_bit_map->isMarked(addr)) { 7885 // a white object ... 7886 _bit_map->mark(addr); // ... now grey 7887 // push on the marking stack (grey set) 7888 bool simulate_overflow = false; 7889 NOT_PRODUCT( 7890 if (CMSMarkStackOverflowALot && 7891 _collector->simulate_overflow()) { 7892 // simulate a stack overflow 7893 simulate_overflow = true; 7894 } 7895 ) 7896 if (simulate_overflow || !_mark_stack->push(obj)) { 7897 if (_concurrent_precleaning) { 7898 // During precleaning we can just dirty the appropriate card(s) 7899 // in the mod union table, thus ensuring that the object remains 7900 // in the grey set and continue. In the case of object arrays 7901 // we need to dirty all of the cards that the object spans, 7902 // since the rescan of object arrays will be limited to the 7903 // dirty cards. 7904 // Note that no one can be interfering with us in this action 7905 // of dirtying the mod union table, so no locking or atomics 7906 // are required. 7907 if (obj->is_objArray()) { 7908 size_t sz = obj->size(); 7909 HeapWord* end_card_addr = (HeapWord*)round_to( 7910 (intptr_t)(addr+sz), CardTableModRefBS::card_size); 7911 MemRegion redirty_range = MemRegion(addr, end_card_addr); 7912 assert(!redirty_range.is_empty(), "Arithmetical tautology"); 7913 _mod_union_table->mark_range(redirty_range); 7914 } else { 7915 _mod_union_table->mark(addr); 7916 } 7917 _collector->_ser_pmc_preclean_ovflw++; 7918 } else { 7919 // During the remark phase, we need to remember this oop 7920 // in the overflow list. 7921 _collector->push_on_overflow_list(obj); 7922 _collector->_ser_pmc_remark_ovflw++; 7923 } 7924 } 7925 } 7926 } 7927 7928 Par_PushAndMarkClosure::Par_PushAndMarkClosure(CMSCollector* collector, 7929 MemRegion span, 7930 ReferenceProcessor* rp, 7931 CMSBitMap* bit_map, 7932 OopTaskQueue* work_queue): 7933 MetadataAwareOopClosure(rp), 7934 _collector(collector), 7935 _span(span), 7936 _bit_map(bit_map), 7937 _work_queue(work_queue) 7938 { 7939 assert(_ref_processor != NULL, "_ref_processor shouldn't be NULL"); 7940 } 7941 7942 void PushAndMarkClosure::do_oop(oop* p) { PushAndMarkClosure::do_oop_work(p); } 7943 void PushAndMarkClosure::do_oop(narrowOop* p) { PushAndMarkClosure::do_oop_work(p); } 7944 7945 // Grey object rescan during second checkpoint phase -- 7946 // the parallel version. 7947 void Par_PushAndMarkClosure::do_oop(oop obj) { 7948 // In the assert below, we ignore the mark word because 7949 // this oop may point to an already visited object that is 7950 // on the overflow stack (in which case the mark word has 7951 // been hijacked for chaining into the overflow stack -- 7952 // if this is the last object in the overflow stack then 7953 // its mark word will be NULL). Because this object may 7954 // have been subsequently popped off the global overflow 7955 // stack, and the mark word possibly restored to the prototypical 7956 // value, by the time we get to examined this failing assert in 7957 // the debugger, is_oop_or_null(false) may subsequently start 7958 // to hold. 7959 assert(obj->is_oop_or_null(true), 7960 "expected an oop or NULL"); 7961 HeapWord* addr = (HeapWord*)obj; 7962 // Check if oop points into the CMS generation 7963 // and is not marked 7964 if (_span.contains(addr) && !_bit_map->isMarked(addr)) { 7965 // a white object ... 7966 // If we manage to "claim" the object, by being the 7967 // first thread to mark it, then we push it on our 7968 // marking stack 7969 if (_bit_map->par_mark(addr)) { // ... now grey 7970 // push on work queue (grey set) 7971 bool simulate_overflow = false; 7972 NOT_PRODUCT( 7973 if (CMSMarkStackOverflowALot && 7974 _collector->par_simulate_overflow()) { 7975 // simulate a stack overflow 7976 simulate_overflow = true; 7977 } 7978 ) 7979 if (simulate_overflow || !_work_queue->push(obj)) { 7980 _collector->par_push_on_overflow_list(obj); 7981 _collector->_par_pmc_remark_ovflw++; // imprecise OK: no need to CAS 7982 } 7983 } // Else, some other thread got there first 7984 } 7985 } 7986 7987 void Par_PushAndMarkClosure::do_oop(oop* p) { Par_PushAndMarkClosure::do_oop_work(p); } 7988 void Par_PushAndMarkClosure::do_oop(narrowOop* p) { Par_PushAndMarkClosure::do_oop_work(p); } 7989 7990 void CMSPrecleanRefsYieldClosure::do_yield_work() { 7991 Mutex* bml = _collector->bitMapLock(); 7992 assert_lock_strong(bml); 7993 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 7994 "CMS thread should hold CMS token"); 7995 7996 bml->unlock(); 7997 ConcurrentMarkSweepThread::desynchronize(true); 7998 7999 ConcurrentMarkSweepThread::acknowledge_yield_request(); 8000 8001 _collector->stopTimer(); 8002 if (PrintCMSStatistics != 0) { 8003 _collector->incrementYields(); 8004 } 8005 _collector->icms_wait(); 8006 8007 // See the comment in coordinator_yield() 8008 for (unsigned i = 0; i < CMSYieldSleepCount && 8009 ConcurrentMarkSweepThread::should_yield() && 8010 !CMSCollector::foregroundGCIsActive(); ++i) { 8011 os::sleep(Thread::current(), 1, false); 8012 ConcurrentMarkSweepThread::acknowledge_yield_request(); 8013 } 8014 8015 ConcurrentMarkSweepThread::synchronize(true); 8016 bml->lock(); 8017 8018 _collector->startTimer(); 8019 } 8020 8021 bool CMSPrecleanRefsYieldClosure::should_return() { 8022 if (ConcurrentMarkSweepThread::should_yield()) { 8023 do_yield_work(); 8024 } 8025 return _collector->foregroundGCIsActive(); 8026 } 8027 8028 void MarkFromDirtyCardsClosure::do_MemRegion(MemRegion mr) { 8029 assert(((size_t)mr.start())%CardTableModRefBS::card_size_in_words == 0, 8030 "mr should be aligned to start at a card boundary"); 8031 // We'd like to assert: 8032 // assert(mr.word_size()%CardTableModRefBS::card_size_in_words == 0, 8033 // "mr should be a range of cards"); 8034 // However, that would be too strong in one case -- the last 8035 // partition ends at _unallocated_block which, in general, can be 8036 // an arbitrary boundary, not necessarily card aligned. 8037 if (PrintCMSStatistics != 0) { 8038 _num_dirty_cards += 8039 mr.word_size()/CardTableModRefBS::card_size_in_words; 8040 } 8041 _space->object_iterate_mem(mr, &_scan_cl); 8042 } 8043 8044 SweepClosure::SweepClosure(CMSCollector* collector, 8045 ConcurrentMarkSweepGeneration* g, 8046 CMSBitMap* bitMap, bool should_yield) : 8047 _collector(collector), 8048 _g(g), 8049 _sp(g->cmsSpace()), 8050 _limit(_sp->sweep_limit()), 8051 _freelistLock(_sp->freelistLock()), 8052 _bitMap(bitMap), 8053 _yield(should_yield), 8054 _inFreeRange(false), // No free range at beginning of sweep 8055 _freeRangeInFreeLists(false), // No free range at beginning of sweep 8056 _lastFreeRangeCoalesced(false), 8057 _freeFinger(g->used_region().start()) 8058 { 8059 NOT_PRODUCT( 8060 _numObjectsFreed = 0; 8061 _numWordsFreed = 0; 8062 _numObjectsLive = 0; 8063 _numWordsLive = 0; 8064 _numObjectsAlreadyFree = 0; 8065 _numWordsAlreadyFree = 0; 8066 _last_fc = NULL; 8067 8068 _sp->initializeIndexedFreeListArrayReturnedBytes(); 8069 _sp->dictionary()->initialize_dict_returned_bytes(); 8070 ) 8071 assert(_limit >= _sp->bottom() && _limit <= _sp->end(), 8072 "sweep _limit out of bounds"); 8073 if (CMSTraceSweeper) { 8074 gclog_or_tty->print_cr("\n====================\nStarting new sweep with limit " PTR_FORMAT, 8075 _limit); 8076 } 8077 } 8078 8079 void SweepClosure::print_on(outputStream* st) const { 8080 tty->print_cr("_sp = [" PTR_FORMAT "," PTR_FORMAT ")", 8081 _sp->bottom(), _sp->end()); 8082 tty->print_cr("_limit = " PTR_FORMAT, _limit); 8083 tty->print_cr("_freeFinger = " PTR_FORMAT, _freeFinger); 8084 NOT_PRODUCT(tty->print_cr("_last_fc = " PTR_FORMAT, _last_fc);) 8085 tty->print_cr("_inFreeRange = %d, _freeRangeInFreeLists = %d, _lastFreeRangeCoalesced = %d", 8086 _inFreeRange, _freeRangeInFreeLists, _lastFreeRangeCoalesced); 8087 } 8088 8089 #ifndef PRODUCT 8090 // Assertion checking only: no useful work in product mode -- 8091 // however, if any of the flags below become product flags, 8092 // you may need to review this code to see if it needs to be 8093 // enabled in product mode. 8094 SweepClosure::~SweepClosure() { 8095 assert_lock_strong(_freelistLock); 8096 assert(_limit >= _sp->bottom() && _limit <= _sp->end(), 8097 "sweep _limit out of bounds"); 8098 if (inFreeRange()) { 8099 warning("inFreeRange() should have been reset; dumping state of SweepClosure"); 8100 print(); 8101 ShouldNotReachHere(); 8102 } 8103 if (Verbose && PrintGC) { 8104 gclog_or_tty->print("Collected "SIZE_FORMAT" objects, " SIZE_FORMAT " bytes", 8105 _numObjectsFreed, _numWordsFreed*sizeof(HeapWord)); 8106 gclog_or_tty->print_cr("\nLive "SIZE_FORMAT" objects, " 8107 SIZE_FORMAT" bytes " 8108 "Already free "SIZE_FORMAT" objects, "SIZE_FORMAT" bytes", 8109 _numObjectsLive, _numWordsLive*sizeof(HeapWord), 8110 _numObjectsAlreadyFree, _numWordsAlreadyFree*sizeof(HeapWord)); 8111 size_t totalBytes = (_numWordsFreed + _numWordsLive + _numWordsAlreadyFree) 8112 * sizeof(HeapWord); 8113 gclog_or_tty->print_cr("Total sweep: "SIZE_FORMAT" bytes", totalBytes); 8114 8115 if (PrintCMSStatistics && CMSVerifyReturnedBytes) { 8116 size_t indexListReturnedBytes = _sp->sumIndexedFreeListArrayReturnedBytes(); 8117 size_t dict_returned_bytes = _sp->dictionary()->sum_dict_returned_bytes(); 8118 size_t returned_bytes = indexListReturnedBytes + dict_returned_bytes; 8119 gclog_or_tty->print("Returned "SIZE_FORMAT" bytes", returned_bytes); 8120 gclog_or_tty->print(" Indexed List Returned "SIZE_FORMAT" bytes", 8121 indexListReturnedBytes); 8122 gclog_or_tty->print_cr(" Dictionary Returned "SIZE_FORMAT" bytes", 8123 dict_returned_bytes); 8124 } 8125 } 8126 if (CMSTraceSweeper) { 8127 gclog_or_tty->print_cr("end of sweep with _limit = " PTR_FORMAT "\n================", 8128 _limit); 8129 } 8130 } 8131 #endif // PRODUCT 8132 8133 void SweepClosure::initialize_free_range(HeapWord* freeFinger, 8134 bool freeRangeInFreeLists) { 8135 if (CMSTraceSweeper) { 8136 gclog_or_tty->print("---- Start free range at " PTR_FORMAT " with free block (%d)\n", 8137 freeFinger, freeRangeInFreeLists); 8138 } 8139 assert(!inFreeRange(), "Trampling existing free range"); 8140 set_inFreeRange(true); 8141 set_lastFreeRangeCoalesced(false); 8142 8143 set_freeFinger(freeFinger); 8144 set_freeRangeInFreeLists(freeRangeInFreeLists); 8145 if (CMSTestInFreeList) { 8146 if (freeRangeInFreeLists) { 8147 FreeChunk* fc = (FreeChunk*) freeFinger; 8148 assert(fc->is_free(), "A chunk on the free list should be free."); 8149 assert(fc->size() > 0, "Free range should have a size"); 8150 assert(_sp->verify_chunk_in_free_list(fc), "Chunk is not in free lists"); 8151 } 8152 } 8153 } 8154 8155 // Note that the sweeper runs concurrently with mutators. Thus, 8156 // it is possible for direct allocation in this generation to happen 8157 // in the middle of the sweep. Note that the sweeper also coalesces 8158 // contiguous free blocks. Thus, unless the sweeper and the allocator 8159 // synchronize appropriately freshly allocated blocks may get swept up. 8160 // This is accomplished by the sweeper locking the free lists while 8161 // it is sweeping. Thus blocks that are determined to be free are 8162 // indeed free. There is however one additional complication: 8163 // blocks that have been allocated since the final checkpoint and 8164 // mark, will not have been marked and so would be treated as 8165 // unreachable and swept up. To prevent this, the allocator marks 8166 // the bit map when allocating during the sweep phase. This leads, 8167 // however, to a further complication -- objects may have been allocated 8168 // but not yet initialized -- in the sense that the header isn't yet 8169 // installed. The sweeper can not then determine the size of the block 8170 // in order to skip over it. To deal with this case, we use a technique 8171 // (due to Printezis) to encode such uninitialized block sizes in the 8172 // bit map. Since the bit map uses a bit per every HeapWord, but the 8173 // CMS generation has a minimum object size of 3 HeapWords, it follows 8174 // that "normal marks" won't be adjacent in the bit map (there will 8175 // always be at least two 0 bits between successive 1 bits). We make use 8176 // of these "unused" bits to represent uninitialized blocks -- the bit 8177 // corresponding to the start of the uninitialized object and the next 8178 // bit are both set. Finally, a 1 bit marks the end of the object that 8179 // started with the two consecutive 1 bits to indicate its potentially 8180 // uninitialized state. 8181 8182 size_t SweepClosure::do_blk_careful(HeapWord* addr) { 8183 FreeChunk* fc = (FreeChunk*)addr; 8184 size_t res; 8185 8186 // Check if we are done sweeping. Below we check "addr >= _limit" rather 8187 // than "addr == _limit" because although _limit was a block boundary when 8188 // we started the sweep, it may no longer be one because heap expansion 8189 // may have caused us to coalesce the block ending at the address _limit 8190 // with a newly expanded chunk (this happens when _limit was set to the 8191 // previous _end of the space), so we may have stepped past _limit: 8192 // see the following Zeno-like trail of CRs 6977970, 7008136, 7042740. 8193 if (addr >= _limit) { // we have swept up to or past the limit: finish up 8194 assert(_limit >= _sp->bottom() && _limit <= _sp->end(), 8195 "sweep _limit out of bounds"); 8196 assert(addr < _sp->end(), "addr out of bounds"); 8197 // Flush any free range we might be holding as a single 8198 // coalesced chunk to the appropriate free list. 8199 if (inFreeRange()) { 8200 assert(freeFinger() >= _sp->bottom() && freeFinger() < _limit, 8201 err_msg("freeFinger() " PTR_FORMAT" is out-of-bounds", freeFinger())); 8202 flush_cur_free_chunk(freeFinger(), 8203 pointer_delta(addr, freeFinger())); 8204 if (CMSTraceSweeper) { 8205 gclog_or_tty->print("Sweep: last chunk: "); 8206 gclog_or_tty->print("put_free_blk " PTR_FORMAT " ("SIZE_FORMAT") " 8207 "[coalesced:%d]\n", 8208 freeFinger(), pointer_delta(addr, freeFinger()), 8209 lastFreeRangeCoalesced() ? 1 : 0); 8210 } 8211 } 8212 8213 // help the iterator loop finish 8214 return pointer_delta(_sp->end(), addr); 8215 } 8216 8217 assert(addr < _limit, "sweep invariant"); 8218 // check if we should yield 8219 do_yield_check(addr); 8220 if (fc->is_free()) { 8221 // Chunk that is already free 8222 res = fc->size(); 8223 do_already_free_chunk(fc); 8224 debug_only(_sp->verifyFreeLists()); 8225 // If we flush the chunk at hand in lookahead_and_flush() 8226 // and it's coalesced with a preceding chunk, then the 8227 // process of "mangling" the payload of the coalesced block 8228 // will cause erasure of the size information from the 8229 // (erstwhile) header of all the coalesced blocks but the 8230 // first, so the first disjunct in the assert will not hold 8231 // in that specific case (in which case the second disjunct 8232 // will hold). 8233 assert(res == fc->size() || ((HeapWord*)fc) + res >= _limit, 8234 "Otherwise the size info doesn't change at this step"); 8235 NOT_PRODUCT( 8236 _numObjectsAlreadyFree++; 8237 _numWordsAlreadyFree += res; 8238 ) 8239 NOT_PRODUCT(_last_fc = fc;) 8240 } else if (!_bitMap->isMarked(addr)) { 8241 // Chunk is fresh garbage 8242 res = do_garbage_chunk(fc); 8243 debug_only(_sp->verifyFreeLists()); 8244 NOT_PRODUCT( 8245 _numObjectsFreed++; 8246 _numWordsFreed += res; 8247 ) 8248 } else { 8249 // Chunk that is alive. 8250 res = do_live_chunk(fc); 8251 debug_only(_sp->verifyFreeLists()); 8252 NOT_PRODUCT( 8253 _numObjectsLive++; 8254 _numWordsLive += res; 8255 ) 8256 } 8257 return res; 8258 } 8259 8260 // For the smart allocation, record following 8261 // split deaths - a free chunk is removed from its free list because 8262 // it is being split into two or more chunks. 8263 // split birth - a free chunk is being added to its free list because 8264 // a larger free chunk has been split and resulted in this free chunk. 8265 // coal death - a free chunk is being removed from its free list because 8266 // it is being coalesced into a large free chunk. 8267 // coal birth - a free chunk is being added to its free list because 8268 // it was created when two or more free chunks where coalesced into 8269 // this free chunk. 8270 // 8271 // These statistics are used to determine the desired number of free 8272 // chunks of a given size. The desired number is chosen to be relative 8273 // to the end of a CMS sweep. The desired number at the end of a sweep 8274 // is the 8275 // count-at-end-of-previous-sweep (an amount that was enough) 8276 // - count-at-beginning-of-current-sweep (the excess) 8277 // + split-births (gains in this size during interval) 8278 // - split-deaths (demands on this size during interval) 8279 // where the interval is from the end of one sweep to the end of the 8280 // next. 8281 // 8282 // When sweeping the sweeper maintains an accumulated chunk which is 8283 // the chunk that is made up of chunks that have been coalesced. That 8284 // will be termed the left-hand chunk. A new chunk of garbage that 8285 // is being considered for coalescing will be referred to as the 8286 // right-hand chunk. 8287 // 8288 // When making a decision on whether to coalesce a right-hand chunk with 8289 // the current left-hand chunk, the current count vs. the desired count 8290 // of the left-hand chunk is considered. Also if the right-hand chunk 8291 // is near the large chunk at the end of the heap (see 8292 // ConcurrentMarkSweepGeneration::isNearLargestChunk()), then the 8293 // left-hand chunk is coalesced. 8294 // 8295 // When making a decision about whether to split a chunk, the desired count 8296 // vs. the current count of the candidate to be split is also considered. 8297 // If the candidate is underpopulated (currently fewer chunks than desired) 8298 // a chunk of an overpopulated (currently more chunks than desired) size may 8299 // be chosen. The "hint" associated with a free list, if non-null, points 8300 // to a free list which may be overpopulated. 8301 // 8302 8303 void SweepClosure::do_already_free_chunk(FreeChunk* fc) { 8304 const size_t size = fc->size(); 8305 // Chunks that cannot be coalesced are not in the 8306 // free lists. 8307 if (CMSTestInFreeList && !fc->cantCoalesce()) { 8308 assert(_sp->verify_chunk_in_free_list(fc), 8309 "free chunk should be in free lists"); 8310 } 8311 // a chunk that is already free, should not have been 8312 // marked in the bit map 8313 HeapWord* const addr = (HeapWord*) fc; 8314 assert(!_bitMap->isMarked(addr), "free chunk should be unmarked"); 8315 // Verify that the bit map has no bits marked between 8316 // addr and purported end of this block. 8317 _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size); 8318 8319 // Some chunks cannot be coalesced under any circumstances. 8320 // See the definition of cantCoalesce(). 8321 if (!fc->cantCoalesce()) { 8322 // This chunk can potentially be coalesced. 8323 if (_sp->adaptive_freelists()) { 8324 // All the work is done in 8325 do_post_free_or_garbage_chunk(fc, size); 8326 } else { // Not adaptive free lists 8327 // this is a free chunk that can potentially be coalesced by the sweeper; 8328 if (!inFreeRange()) { 8329 // if the next chunk is a free block that can't be coalesced 8330 // it doesn't make sense to remove this chunk from the free lists 8331 FreeChunk* nextChunk = (FreeChunk*)(addr + size); 8332 assert((HeapWord*)nextChunk <= _sp->end(), "Chunk size out of bounds?"); 8333 if ((HeapWord*)nextChunk < _sp->end() && // There is another free chunk to the right ... 8334 nextChunk->is_free() && // ... which is free... 8335 nextChunk->cantCoalesce()) { // ... but can't be coalesced 8336 // nothing to do 8337 } else { 8338 // Potentially the start of a new free range: 8339 // Don't eagerly remove it from the free lists. 8340 // No need to remove it if it will just be put 8341 // back again. (Also from a pragmatic point of view 8342 // if it is a free block in a region that is beyond 8343 // any allocated blocks, an assertion will fail) 8344 // Remember the start of a free run. 8345 initialize_free_range(addr, true); 8346 // end - can coalesce with next chunk 8347 } 8348 } else { 8349 // the midst of a free range, we are coalescing 8350 print_free_block_coalesced(fc); 8351 if (CMSTraceSweeper) { 8352 gclog_or_tty->print(" -- pick up free block " PTR_FORMAT " (" SIZE_FORMAT ")\n", fc, size); 8353 } 8354 // remove it from the free lists 8355 _sp->removeFreeChunkFromFreeLists(fc); 8356 set_lastFreeRangeCoalesced(true); 8357 // If the chunk is being coalesced and the current free range is 8358 // in the free lists, remove the current free range so that it 8359 // will be returned to the free lists in its entirety - all 8360 // the coalesced pieces included. 8361 if (freeRangeInFreeLists()) { 8362 FreeChunk* ffc = (FreeChunk*) freeFinger(); 8363 assert(ffc->size() == pointer_delta(addr, freeFinger()), 8364 "Size of free range is inconsistent with chunk size."); 8365 if (CMSTestInFreeList) { 8366 assert(_sp->verify_chunk_in_free_list(ffc), 8367 "free range is not in free lists"); 8368 } 8369 _sp->removeFreeChunkFromFreeLists(ffc); 8370 set_freeRangeInFreeLists(false); 8371 } 8372 } 8373 } 8374 // Note that if the chunk is not coalescable (the else arm 8375 // below), we unconditionally flush, without needing to do 8376 // a "lookahead," as we do below. 8377 if (inFreeRange()) lookahead_and_flush(fc, size); 8378 } else { 8379 // Code path common to both original and adaptive free lists. 8380 8381 // cant coalesce with previous block; this should be treated 8382 // as the end of a free run if any 8383 if (inFreeRange()) { 8384 // we kicked some butt; time to pick up the garbage 8385 assert(freeFinger() < addr, "freeFinger points too high"); 8386 flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger())); 8387 } 8388 // else, nothing to do, just continue 8389 } 8390 } 8391 8392 size_t SweepClosure::do_garbage_chunk(FreeChunk* fc) { 8393 // This is a chunk of garbage. It is not in any free list. 8394 // Add it to a free list or let it possibly be coalesced into 8395 // a larger chunk. 8396 HeapWord* const addr = (HeapWord*) fc; 8397 const size_t size = CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size()); 8398 8399 if (_sp->adaptive_freelists()) { 8400 // Verify that the bit map has no bits marked between 8401 // addr and purported end of just dead object. 8402 _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size); 8403 8404 do_post_free_or_garbage_chunk(fc, size); 8405 } else { 8406 if (!inFreeRange()) { 8407 // start of a new free range 8408 assert(size > 0, "A free range should have a size"); 8409 initialize_free_range(addr, false); 8410 } else { 8411 // this will be swept up when we hit the end of the 8412 // free range 8413 if (CMSTraceSweeper) { 8414 gclog_or_tty->print(" -- pick up garbage " PTR_FORMAT " (" SIZE_FORMAT ")\n", fc, size); 8415 } 8416 // If the chunk is being coalesced and the current free range is 8417 // in the free lists, remove the current free range so that it 8418 // will be returned to the free lists in its entirety - all 8419 // the coalesced pieces included. 8420 if (freeRangeInFreeLists()) { 8421 FreeChunk* ffc = (FreeChunk*)freeFinger(); 8422 assert(ffc->size() == pointer_delta(addr, freeFinger()), 8423 "Size of free range is inconsistent with chunk size."); 8424 if (CMSTestInFreeList) { 8425 assert(_sp->verify_chunk_in_free_list(ffc), 8426 "free range is not in free lists"); 8427 } 8428 _sp->removeFreeChunkFromFreeLists(ffc); 8429 set_freeRangeInFreeLists(false); 8430 } 8431 set_lastFreeRangeCoalesced(true); 8432 } 8433 // this will be swept up when we hit the end of the free range 8434 8435 // Verify that the bit map has no bits marked between 8436 // addr and purported end of just dead object. 8437 _bitMap->verifyNoOneBitsInRange(addr + 1, addr + size); 8438 } 8439 assert(_limit >= addr + size, 8440 "A freshly garbage chunk can't possibly straddle over _limit"); 8441 if (inFreeRange()) lookahead_and_flush(fc, size); 8442 return size; 8443 } 8444 8445 size_t SweepClosure::do_live_chunk(FreeChunk* fc) { 8446 HeapWord* addr = (HeapWord*) fc; 8447 // The sweeper has just found a live object. Return any accumulated 8448 // left hand chunk to the free lists. 8449 if (inFreeRange()) { 8450 assert(freeFinger() < addr, "freeFinger points too high"); 8451 flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger())); 8452 } 8453 8454 // This object is live: we'd normally expect this to be 8455 // an oop, and like to assert the following: 8456 // assert(oop(addr)->is_oop(), "live block should be an oop"); 8457 // However, as we commented above, this may be an object whose 8458 // header hasn't yet been initialized. 8459 size_t size; 8460 assert(_bitMap->isMarked(addr), "Tautology for this control point"); 8461 if (_bitMap->isMarked(addr + 1)) { 8462 // Determine the size from the bit map, rather than trying to 8463 // compute it from the object header. 8464 HeapWord* nextOneAddr = _bitMap->getNextMarkedWordAddress(addr + 2); 8465 size = pointer_delta(nextOneAddr + 1, addr); 8466 assert(size == CompactibleFreeListSpace::adjustObjectSize(size), 8467 "alignment problem"); 8468 8469 #ifdef ASSERT 8470 if (oop(addr)->klass_or_null() != NULL) { 8471 // Ignore mark word because we are running concurrent with mutators 8472 assert(oop(addr)->is_oop(true), "live block should be an oop"); 8473 assert(size == 8474 CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size()), 8475 "P-mark and computed size do not agree"); 8476 } 8477 #endif 8478 8479 } else { 8480 // This should be an initialized object that's alive. 8481 assert(oop(addr)->klass_or_null() != NULL, 8482 "Should be an initialized object"); 8483 // Ignore mark word because we are running concurrent with mutators 8484 assert(oop(addr)->is_oop(true), "live block should be an oop"); 8485 // Verify that the bit map has no bits marked between 8486 // addr and purported end of this block. 8487 size = CompactibleFreeListSpace::adjustObjectSize(oop(addr)->size()); 8488 assert(size >= 3, "Necessary for Printezis marks to work"); 8489 assert(!_bitMap->isMarked(addr+1), "Tautology for this control point"); 8490 DEBUG_ONLY(_bitMap->verifyNoOneBitsInRange(addr+2, addr+size);) 8491 } 8492 return size; 8493 } 8494 8495 void SweepClosure::do_post_free_or_garbage_chunk(FreeChunk* fc, 8496 size_t chunkSize) { 8497 // do_post_free_or_garbage_chunk() should only be called in the case 8498 // of the adaptive free list allocator. 8499 const bool fcInFreeLists = fc->is_free(); 8500 assert(_sp->adaptive_freelists(), "Should only be used in this case."); 8501 assert((HeapWord*)fc <= _limit, "sweep invariant"); 8502 if (CMSTestInFreeList && fcInFreeLists) { 8503 assert(_sp->verify_chunk_in_free_list(fc), "free chunk is not in free lists"); 8504 } 8505 8506 if (CMSTraceSweeper) { 8507 gclog_or_tty->print_cr(" -- pick up another chunk at " PTR_FORMAT " (" SIZE_FORMAT ")", fc, chunkSize); 8508 } 8509 8510 HeapWord* const fc_addr = (HeapWord*) fc; 8511 8512 bool coalesce; 8513 const size_t left = pointer_delta(fc_addr, freeFinger()); 8514 const size_t right = chunkSize; 8515 switch (FLSCoalescePolicy) { 8516 // numeric value forms a coalition aggressiveness metric 8517 case 0: { // never coalesce 8518 coalesce = false; 8519 break; 8520 } 8521 case 1: { // coalesce if left & right chunks on overpopulated lists 8522 coalesce = _sp->coalOverPopulated(left) && 8523 _sp->coalOverPopulated(right); 8524 break; 8525 } 8526 case 2: { // coalesce if left chunk on overpopulated list (default) 8527 coalesce = _sp->coalOverPopulated(left); 8528 break; 8529 } 8530 case 3: { // coalesce if left OR right chunk on overpopulated list 8531 coalesce = _sp->coalOverPopulated(left) || 8532 _sp->coalOverPopulated(right); 8533 break; 8534 } 8535 case 4: { // always coalesce 8536 coalesce = true; 8537 break; 8538 } 8539 default: 8540 ShouldNotReachHere(); 8541 } 8542 8543 // Should the current free range be coalesced? 8544 // If the chunk is in a free range and either we decided to coalesce above 8545 // or the chunk is near the large block at the end of the heap 8546 // (isNearLargestChunk() returns true), then coalesce this chunk. 8547 const bool doCoalesce = inFreeRange() 8548 && (coalesce || _g->isNearLargestChunk(fc_addr)); 8549 if (doCoalesce) { 8550 // Coalesce the current free range on the left with the new 8551 // chunk on the right. If either is on a free list, 8552 // it must be removed from the list and stashed in the closure. 8553 if (freeRangeInFreeLists()) { 8554 FreeChunk* const ffc = (FreeChunk*)freeFinger(); 8555 assert(ffc->size() == pointer_delta(fc_addr, freeFinger()), 8556 "Size of free range is inconsistent with chunk size."); 8557 if (CMSTestInFreeList) { 8558 assert(_sp->verify_chunk_in_free_list(ffc), 8559 "Chunk is not in free lists"); 8560 } 8561 _sp->coalDeath(ffc->size()); 8562 _sp->removeFreeChunkFromFreeLists(ffc); 8563 set_freeRangeInFreeLists(false); 8564 } 8565 if (fcInFreeLists) { 8566 _sp->coalDeath(chunkSize); 8567 assert(fc->size() == chunkSize, 8568 "The chunk has the wrong size or is not in the free lists"); 8569 _sp->removeFreeChunkFromFreeLists(fc); 8570 } 8571 set_lastFreeRangeCoalesced(true); 8572 print_free_block_coalesced(fc); 8573 } else { // not in a free range and/or should not coalesce 8574 // Return the current free range and start a new one. 8575 if (inFreeRange()) { 8576 // In a free range but cannot coalesce with the right hand chunk. 8577 // Put the current free range into the free lists. 8578 flush_cur_free_chunk(freeFinger(), 8579 pointer_delta(fc_addr, freeFinger())); 8580 } 8581 // Set up for new free range. Pass along whether the right hand 8582 // chunk is in the free lists. 8583 initialize_free_range((HeapWord*)fc, fcInFreeLists); 8584 } 8585 } 8586 8587 // Lookahead flush: 8588 // If we are tracking a free range, and this is the last chunk that 8589 // we'll look at because its end crosses past _limit, we'll preemptively 8590 // flush it along with any free range we may be holding on to. Note that 8591 // this can be the case only for an already free or freshly garbage 8592 // chunk. If this block is an object, it can never straddle 8593 // over _limit. The "straddling" occurs when _limit is set at 8594 // the previous end of the space when this cycle started, and 8595 // a subsequent heap expansion caused the previously co-terminal 8596 // free block to be coalesced with the newly expanded portion, 8597 // thus rendering _limit a non-block-boundary making it dangerous 8598 // for the sweeper to step over and examine. 8599 void SweepClosure::lookahead_and_flush(FreeChunk* fc, size_t chunk_size) { 8600 assert(inFreeRange(), "Should only be called if currently in a free range."); 8601 HeapWord* const eob = ((HeapWord*)fc) + chunk_size; 8602 assert(_sp->used_region().contains(eob - 1), 8603 err_msg("eob = " PTR_FORMAT " eob-1 = " PTR_FORMAT " _limit = " PTR_FORMAT 8604 " out of bounds wrt _sp = [" PTR_FORMAT "," PTR_FORMAT ")" 8605 " when examining fc = " PTR_FORMAT "(" SIZE_FORMAT ")", 8606 eob, eob-1, _limit, _sp->bottom(), _sp->end(), fc, chunk_size)); 8607 if (eob >= _limit) { 8608 assert(eob == _limit || fc->is_free(), "Only a free chunk should allow us to cross over the limit"); 8609 if (CMSTraceSweeper) { 8610 gclog_or_tty->print_cr("_limit " PTR_FORMAT " reached or crossed by block " 8611 "[" PTR_FORMAT "," PTR_FORMAT ") in space " 8612 "[" PTR_FORMAT "," PTR_FORMAT ")", 8613 _limit, fc, eob, _sp->bottom(), _sp->end()); 8614 } 8615 // Return the storage we are tracking back into the free lists. 8616 if (CMSTraceSweeper) { 8617 gclog_or_tty->print_cr("Flushing ... "); 8618 } 8619 assert(freeFinger() < eob, "Error"); 8620 flush_cur_free_chunk( freeFinger(), pointer_delta(eob, freeFinger())); 8621 } 8622 } 8623 8624 void SweepClosure::flush_cur_free_chunk(HeapWord* chunk, size_t size) { 8625 assert(inFreeRange(), "Should only be called if currently in a free range."); 8626 assert(size > 0, 8627 "A zero sized chunk cannot be added to the free lists."); 8628 if (!freeRangeInFreeLists()) { 8629 if (CMSTestInFreeList) { 8630 FreeChunk* fc = (FreeChunk*) chunk; 8631 fc->set_size(size); 8632 assert(!_sp->verify_chunk_in_free_list(fc), 8633 "chunk should not be in free lists yet"); 8634 } 8635 if (CMSTraceSweeper) { 8636 gclog_or_tty->print_cr(" -- add free block " PTR_FORMAT " (" SIZE_FORMAT ") to free lists", 8637 chunk, size); 8638 } 8639 // A new free range is going to be starting. The current 8640 // free range has not been added to the free lists yet or 8641 // was removed so add it back. 8642 // If the current free range was coalesced, then the death 8643 // of the free range was recorded. Record a birth now. 8644 if (lastFreeRangeCoalesced()) { 8645 _sp->coalBirth(size); 8646 } 8647 _sp->addChunkAndRepairOffsetTable(chunk, size, 8648 lastFreeRangeCoalesced()); 8649 } else if (CMSTraceSweeper) { 8650 gclog_or_tty->print_cr("Already in free list: nothing to flush"); 8651 } 8652 set_inFreeRange(false); 8653 set_freeRangeInFreeLists(false); 8654 } 8655 8656 // We take a break if we've been at this for a while, 8657 // so as to avoid monopolizing the locks involved. 8658 void SweepClosure::do_yield_work(HeapWord* addr) { 8659 // Return current free chunk being used for coalescing (if any) 8660 // to the appropriate freelist. After yielding, the next 8661 // free block encountered will start a coalescing range of 8662 // free blocks. If the next free block is adjacent to the 8663 // chunk just flushed, they will need to wait for the next 8664 // sweep to be coalesced. 8665 if (inFreeRange()) { 8666 flush_cur_free_chunk(freeFinger(), pointer_delta(addr, freeFinger())); 8667 } 8668 8669 // First give up the locks, then yield, then re-lock. 8670 // We should probably use a constructor/destructor idiom to 8671 // do this unlock/lock or modify the MutexUnlocker class to 8672 // serve our purpose. XXX 8673 assert_lock_strong(_bitMap->lock()); 8674 assert_lock_strong(_freelistLock); 8675 assert(ConcurrentMarkSweepThread::cms_thread_has_cms_token(), 8676 "CMS thread should hold CMS token"); 8677 _bitMap->lock()->unlock(); 8678 _freelistLock->unlock(); 8679 ConcurrentMarkSweepThread::desynchronize(true); 8680 ConcurrentMarkSweepThread::acknowledge_yield_request(); 8681 _collector->stopTimer(); 8682 if (PrintCMSStatistics != 0) { 8683 _collector->incrementYields(); 8684 } 8685 _collector->icms_wait(); 8686 8687 // See the comment in coordinator_yield() 8688 for (unsigned i = 0; i < CMSYieldSleepCount && 8689 ConcurrentMarkSweepThread::should_yield() && 8690 !CMSCollector::foregroundGCIsActive(); ++i) { 8691 os::sleep(Thread::current(), 1, false); 8692 ConcurrentMarkSweepThread::acknowledge_yield_request(); 8693 } 8694 8695 ConcurrentMarkSweepThread::synchronize(true); 8696 _freelistLock->lock(); 8697 _bitMap->lock()->lock_without_safepoint_check(); 8698 _collector->startTimer(); 8699 } 8700 8701 #ifndef PRODUCT 8702 // This is actually very useful in a product build if it can 8703 // be called from the debugger. Compile it into the product 8704 // as needed. 8705 bool debug_verify_chunk_in_free_list(FreeChunk* fc) { 8706 return debug_cms_space->verify_chunk_in_free_list(fc); 8707 } 8708 #endif 8709 8710 void SweepClosure::print_free_block_coalesced(FreeChunk* fc) const { 8711 if (CMSTraceSweeper) { 8712 gclog_or_tty->print_cr("Sweep:coal_free_blk " PTR_FORMAT " (" SIZE_FORMAT ")", 8713 fc, fc->size()); 8714 } 8715 } 8716 8717 // CMSIsAliveClosure 8718 bool CMSIsAliveClosure::do_object_b(oop obj) { 8719 HeapWord* addr = (HeapWord*)obj; 8720 return addr != NULL && 8721 (!_span.contains(addr) || _bit_map->isMarked(addr)); 8722 } 8723 8724 8725 CMSKeepAliveClosure::CMSKeepAliveClosure( CMSCollector* collector, 8726 MemRegion span, 8727 CMSBitMap* bit_map, CMSMarkStack* mark_stack, 8728 bool cpc): 8729 _collector(collector), 8730 _span(span), 8731 _bit_map(bit_map), 8732 _mark_stack(mark_stack), 8733 _concurrent_precleaning(cpc) { 8734 assert(!_span.is_empty(), "Empty span could spell trouble"); 8735 } 8736 8737 8738 // CMSKeepAliveClosure: the serial version 8739 void CMSKeepAliveClosure::do_oop(oop obj) { 8740 HeapWord* addr = (HeapWord*)obj; 8741 if (_span.contains(addr) && 8742 !_bit_map->isMarked(addr)) { 8743 _bit_map->mark(addr); 8744 bool simulate_overflow = false; 8745 NOT_PRODUCT( 8746 if (CMSMarkStackOverflowALot && 8747 _collector->simulate_overflow()) { 8748 // simulate a stack overflow 8749 simulate_overflow = true; 8750 } 8751 ) 8752 if (simulate_overflow || !_mark_stack->push(obj)) { 8753 if (_concurrent_precleaning) { 8754 // We dirty the overflown object and let the remark 8755 // phase deal with it. 8756 assert(_collector->overflow_list_is_empty(), "Error"); 8757 // In the case of object arrays, we need to dirty all of 8758 // the cards that the object spans. No locking or atomics 8759 // are needed since no one else can be mutating the mod union 8760 // table. 8761 if (obj->is_objArray()) { 8762 size_t sz = obj->size(); 8763 HeapWord* end_card_addr = 8764 (HeapWord*)round_to((intptr_t)(addr+sz), CardTableModRefBS::card_size); 8765 MemRegion redirty_range = MemRegion(addr, end_card_addr); 8766 assert(!redirty_range.is_empty(), "Arithmetical tautology"); 8767 _collector->_modUnionTable.mark_range(redirty_range); 8768 } else { 8769 _collector->_modUnionTable.mark(addr); 8770 } 8771 _collector->_ser_kac_preclean_ovflw++; 8772 } else { 8773 _collector->push_on_overflow_list(obj); 8774 _collector->_ser_kac_ovflw++; 8775 } 8776 } 8777 } 8778 } 8779 8780 void CMSKeepAliveClosure::do_oop(oop* p) { CMSKeepAliveClosure::do_oop_work(p); } 8781 void CMSKeepAliveClosure::do_oop(narrowOop* p) { CMSKeepAliveClosure::do_oop_work(p); } 8782 8783 // CMSParKeepAliveClosure: a parallel version of the above. 8784 // The work queues are private to each closure (thread), 8785 // but (may be) available for stealing by other threads. 8786 void CMSParKeepAliveClosure::do_oop(oop obj) { 8787 HeapWord* addr = (HeapWord*)obj; 8788 if (_span.contains(addr) && 8789 !_bit_map->isMarked(addr)) { 8790 // In general, during recursive tracing, several threads 8791 // may be concurrently getting here; the first one to 8792 // "tag" it, claims it. 8793 if (_bit_map->par_mark(addr)) { 8794 bool res = _work_queue->push(obj); 8795 assert(res, "Low water mark should be much less than capacity"); 8796 // Do a recursive trim in the hope that this will keep 8797 // stack usage lower, but leave some oops for potential stealers 8798 trim_queue(_low_water_mark); 8799 } // Else, another thread got there first 8800 } 8801 } 8802 8803 void CMSParKeepAliveClosure::do_oop(oop* p) { CMSParKeepAliveClosure::do_oop_work(p); } 8804 void CMSParKeepAliveClosure::do_oop(narrowOop* p) { CMSParKeepAliveClosure::do_oop_work(p); } 8805 8806 void CMSParKeepAliveClosure::trim_queue(uint max) { 8807 while (_work_queue->size() > max) { 8808 oop new_oop; 8809 if (_work_queue->pop_local(new_oop)) { 8810 assert(new_oop != NULL && new_oop->is_oop(), "Expected an oop"); 8811 assert(_bit_map->isMarked((HeapWord*)new_oop), 8812 "no white objects on this stack!"); 8813 assert(_span.contains((HeapWord*)new_oop), "Out of bounds oop"); 8814 // iterate over the oops in this oop, marking and pushing 8815 // the ones in CMS heap (i.e. in _span). 8816 new_oop->oop_iterate(&_mark_and_push); 8817 } 8818 } 8819 } 8820 8821 CMSInnerParMarkAndPushClosure::CMSInnerParMarkAndPushClosure( 8822 CMSCollector* collector, 8823 MemRegion span, CMSBitMap* bit_map, 8824 OopTaskQueue* work_queue): 8825 _collector(collector), 8826 _span(span), 8827 _bit_map(bit_map), 8828 _work_queue(work_queue) { } 8829 8830 void CMSInnerParMarkAndPushClosure::do_oop(oop obj) { 8831 HeapWord* addr = (HeapWord*)obj; 8832 if (_span.contains(addr) && 8833 !_bit_map->isMarked(addr)) { 8834 if (_bit_map->par_mark(addr)) { 8835 bool simulate_overflow = false; 8836 NOT_PRODUCT( 8837 if (CMSMarkStackOverflowALot && 8838 _collector->par_simulate_overflow()) { 8839 // simulate a stack overflow 8840 simulate_overflow = true; 8841 } 8842 ) 8843 if (simulate_overflow || !_work_queue->push(obj)) { 8844 _collector->par_push_on_overflow_list(obj); 8845 _collector->_par_kac_ovflw++; 8846 } 8847 } // Else another thread got there already 8848 } 8849 } 8850 8851 void CMSInnerParMarkAndPushClosure::do_oop(oop* p) { CMSInnerParMarkAndPushClosure::do_oop_work(p); } 8852 void CMSInnerParMarkAndPushClosure::do_oop(narrowOop* p) { CMSInnerParMarkAndPushClosure::do_oop_work(p); } 8853 8854 ////////////////////////////////////////////////////////////////// 8855 // CMSExpansionCause ///////////////////////////// 8856 ////////////////////////////////////////////////////////////////// 8857 const char* CMSExpansionCause::to_string(CMSExpansionCause::Cause cause) { 8858 switch (cause) { 8859 case _no_expansion: 8860 return "No expansion"; 8861 case _satisfy_free_ratio: 8862 return "Free ratio"; 8863 case _satisfy_promotion: 8864 return "Satisfy promotion"; 8865 case _satisfy_allocation: 8866 return "allocation"; 8867 case _allocate_par_lab: 8868 return "Par LAB"; 8869 case _allocate_par_spooling_space: 8870 return "Par Spooling Space"; 8871 case _adaptive_size_policy: 8872 return "Ergonomics"; 8873 default: 8874 return "unknown"; 8875 } 8876 } 8877 8878 void CMSDrainMarkingStackClosure::do_void() { 8879 // the max number to take from overflow list at a time 8880 const size_t num = _mark_stack->capacity()/4; 8881 assert(!_concurrent_precleaning || _collector->overflow_list_is_empty(), 8882 "Overflow list should be NULL during concurrent phases"); 8883 while (!_mark_stack->isEmpty() || 8884 // if stack is empty, check the overflow list 8885 _collector->take_from_overflow_list(num, _mark_stack)) { 8886 oop obj = _mark_stack->pop(); 8887 HeapWord* addr = (HeapWord*)obj; 8888 assert(_span.contains(addr), "Should be within span"); 8889 assert(_bit_map->isMarked(addr), "Should be marked"); 8890 assert(obj->is_oop(), "Should be an oop"); 8891 obj->oop_iterate(_keep_alive); 8892 } 8893 } 8894 8895 void CMSParDrainMarkingStackClosure::do_void() { 8896 // drain queue 8897 trim_queue(0); 8898 } 8899 8900 // Trim our work_queue so its length is below max at return 8901 void CMSParDrainMarkingStackClosure::trim_queue(uint max) { 8902 while (_work_queue->size() > max) { 8903 oop new_oop; 8904 if (_work_queue->pop_local(new_oop)) { 8905 assert(new_oop->is_oop(), "Expected an oop"); 8906 assert(_bit_map->isMarked((HeapWord*)new_oop), 8907 "no white objects on this stack!"); 8908 assert(_span.contains((HeapWord*)new_oop), "Out of bounds oop"); 8909 // iterate over the oops in this oop, marking and pushing 8910 // the ones in CMS heap (i.e. in _span). 8911 new_oop->oop_iterate(&_mark_and_push); 8912 } 8913 } 8914 } 8915 8916 //////////////////////////////////////////////////////////////////// 8917 // Support for Marking Stack Overflow list handling and related code 8918 //////////////////////////////////////////////////////////////////// 8919 // Much of the following code is similar in shape and spirit to the 8920 // code used in ParNewGC. We should try and share that code 8921 // as much as possible in the future. 8922 8923 #ifndef PRODUCT 8924 // Debugging support for CMSStackOverflowALot 8925 8926 // It's OK to call this multi-threaded; the worst thing 8927 // that can happen is that we'll get a bunch of closely 8928 // spaced simulated overflows, but that's OK, in fact 8929 // probably good as it would exercise the overflow code 8930 // under contention. 8931 bool CMSCollector::simulate_overflow() { 8932 if (_overflow_counter-- <= 0) { // just being defensive 8933 _overflow_counter = CMSMarkStackOverflowInterval; 8934 return true; 8935 } else { 8936 return false; 8937 } 8938 } 8939 8940 bool CMSCollector::par_simulate_overflow() { 8941 return simulate_overflow(); 8942 } 8943 #endif 8944 8945 // Single-threaded 8946 bool CMSCollector::take_from_overflow_list(size_t num, CMSMarkStack* stack) { 8947 assert(stack->isEmpty(), "Expected precondition"); 8948 assert(stack->capacity() > num, "Shouldn't bite more than can chew"); 8949 size_t i = num; 8950 oop cur = _overflow_list; 8951 const markOop proto = markOopDesc::prototype(); 8952 NOT_PRODUCT(ssize_t n = 0;) 8953 for (oop next; i > 0 && cur != NULL; cur = next, i--) { 8954 next = oop(cur->mark()); 8955 cur->set_mark(proto); // until proven otherwise 8956 assert(cur->is_oop(), "Should be an oop"); 8957 bool res = stack->push(cur); 8958 assert(res, "Bit off more than can chew?"); 8959 NOT_PRODUCT(n++;) 8960 } 8961 _overflow_list = cur; 8962 #ifndef PRODUCT 8963 assert(_num_par_pushes >= n, "Too many pops?"); 8964 _num_par_pushes -=n; 8965 #endif 8966 return !stack->isEmpty(); 8967 } 8968 8969 #define BUSY (cast_to_oop<intptr_t>(0x1aff1aff)) 8970 // (MT-safe) Get a prefix of at most "num" from the list. 8971 // The overflow list is chained through the mark word of 8972 // each object in the list. We fetch the entire list, 8973 // break off a prefix of the right size and return the 8974 // remainder. If other threads try to take objects from 8975 // the overflow list at that time, they will wait for 8976 // some time to see if data becomes available. If (and 8977 // only if) another thread places one or more object(s) 8978 // on the global list before we have returned the suffix 8979 // to the global list, we will walk down our local list 8980 // to find its end and append the global list to 8981 // our suffix before returning it. This suffix walk can 8982 // prove to be expensive (quadratic in the amount of traffic) 8983 // when there are many objects in the overflow list and 8984 // there is much producer-consumer contention on the list. 8985 // *NOTE*: The overflow list manipulation code here and 8986 // in ParNewGeneration:: are very similar in shape, 8987 // except that in the ParNew case we use the old (from/eden) 8988 // copy of the object to thread the list via its klass word. 8989 // Because of the common code, if you make any changes in 8990 // the code below, please check the ParNew version to see if 8991 // similar changes might be needed. 8992 // CR 6797058 has been filed to consolidate the common code. 8993 bool CMSCollector::par_take_from_overflow_list(size_t num, 8994 OopTaskQueue* work_q, 8995 int no_of_gc_threads) { 8996 assert(work_q->size() == 0, "First empty local work queue"); 8997 assert(num < work_q->max_elems(), "Can't bite more than we can chew"); 8998 if (_overflow_list == NULL) { 8999 return false; 9000 } 9001 // Grab the entire list; we'll put back a suffix 9002 oop prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list)); 9003 Thread* tid = Thread::current(); 9004 // Before "no_of_gc_threads" was introduced CMSOverflowSpinCount was 9005 // set to ParallelGCThreads. 9006 size_t CMSOverflowSpinCount = (size_t) no_of_gc_threads; // was ParallelGCThreads; 9007 size_t sleep_time_millis = MAX2((size_t)1, num/100); 9008 // If the list is busy, we spin for a short while, 9009 // sleeping between attempts to get the list. 9010 for (size_t spin = 0; prefix == BUSY && spin < CMSOverflowSpinCount; spin++) { 9011 os::sleep(tid, sleep_time_millis, false); 9012 if (_overflow_list == NULL) { 9013 // Nothing left to take 9014 return false; 9015 } else if (_overflow_list != BUSY) { 9016 // Try and grab the prefix 9017 prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list)); 9018 } 9019 } 9020 // If the list was found to be empty, or we spun long 9021 // enough, we give up and return empty-handed. If we leave 9022 // the list in the BUSY state below, it must be the case that 9023 // some other thread holds the overflow list and will set it 9024 // to a non-BUSY state in the future. 9025 if (prefix == NULL || prefix == BUSY) { 9026 // Nothing to take or waited long enough 9027 if (prefix == NULL) { 9028 // Write back the NULL in case we overwrote it with BUSY above 9029 // and it is still the same value. 9030 (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY); 9031 } 9032 return false; 9033 } 9034 assert(prefix != NULL && prefix != BUSY, "Error"); 9035 size_t i = num; 9036 oop cur = prefix; 9037 // Walk down the first "num" objects, unless we reach the end. 9038 for (; i > 1 && cur->mark() != NULL; cur = oop(cur->mark()), i--); 9039 if (cur->mark() == NULL) { 9040 // We have "num" or fewer elements in the list, so there 9041 // is nothing to return to the global list. 9042 // Write back the NULL in lieu of the BUSY we wrote 9043 // above, if it is still the same value. 9044 if (_overflow_list == BUSY) { 9045 (void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY); 9046 } 9047 } else { 9048 // Chop off the suffix and return it to the global list. 9049 assert(cur->mark() != BUSY, "Error"); 9050 oop suffix_head = cur->mark(); // suffix will be put back on global list 9051 cur->set_mark(NULL); // break off suffix 9052 // It's possible that the list is still in the empty(busy) state 9053 // we left it in a short while ago; in that case we may be 9054 // able to place back the suffix without incurring the cost 9055 // of a walk down the list. 9056 oop observed_overflow_list = _overflow_list; 9057 oop cur_overflow_list = observed_overflow_list; 9058 bool attached = false; 9059 while (observed_overflow_list == BUSY || observed_overflow_list == NULL) { 9060 observed_overflow_list = 9061 (oop) Atomic::cmpxchg_ptr(suffix_head, &_overflow_list, cur_overflow_list); 9062 if (cur_overflow_list == observed_overflow_list) { 9063 attached = true; 9064 break; 9065 } else cur_overflow_list = observed_overflow_list; 9066 } 9067 if (!attached) { 9068 // Too bad, someone else sneaked in (at least) an element; we'll need 9069 // to do a splice. Find tail of suffix so we can prepend suffix to global 9070 // list. 9071 for (cur = suffix_head; cur->mark() != NULL; cur = (oop)(cur->mark())); 9072 oop suffix_tail = cur; 9073 assert(suffix_tail != NULL && suffix_tail->mark() == NULL, 9074 "Tautology"); 9075 observed_overflow_list = _overflow_list; 9076 do { 9077 cur_overflow_list = observed_overflow_list; 9078 if (cur_overflow_list != BUSY) { 9079 // Do the splice ... 9080 suffix_tail->set_mark(markOop(cur_overflow_list)); 9081 } else { // cur_overflow_list == BUSY 9082 suffix_tail->set_mark(NULL); 9083 } 9084 // ... and try to place spliced list back on overflow_list ... 9085 observed_overflow_list = 9086 (oop) Atomic::cmpxchg_ptr(suffix_head, &_overflow_list, cur_overflow_list); 9087 } while (cur_overflow_list != observed_overflow_list); 9088 // ... until we have succeeded in doing so. 9089 } 9090 } 9091 9092 // Push the prefix elements on work_q 9093 assert(prefix != NULL, "control point invariant"); 9094 const markOop proto = markOopDesc::prototype(); 9095 oop next; 9096 NOT_PRODUCT(ssize_t n = 0;) 9097 for (cur = prefix; cur != NULL; cur = next) { 9098 next = oop(cur->mark()); 9099 cur->set_mark(proto); // until proven otherwise 9100 assert(cur->is_oop(), "Should be an oop"); 9101 bool res = work_q->push(cur); 9102 assert(res, "Bit off more than we can chew?"); 9103 NOT_PRODUCT(n++;) 9104 } 9105 #ifndef PRODUCT 9106 assert(_num_par_pushes >= n, "Too many pops?"); 9107 Atomic::add_ptr(-(intptr_t)n, &_num_par_pushes); 9108 #endif 9109 return true; 9110 } 9111 9112 // Single-threaded 9113 void CMSCollector::push_on_overflow_list(oop p) { 9114 NOT_PRODUCT(_num_par_pushes++;) 9115 assert(p->is_oop(), "Not an oop"); 9116 preserve_mark_if_necessary(p); 9117 p->set_mark((markOop)_overflow_list); 9118 _overflow_list = p; 9119 } 9120 9121 // Multi-threaded; use CAS to prepend to overflow list 9122 void CMSCollector::par_push_on_overflow_list(oop p) { 9123 NOT_PRODUCT(Atomic::inc_ptr(&_num_par_pushes);) 9124 assert(p->is_oop(), "Not an oop"); 9125 par_preserve_mark_if_necessary(p); 9126 oop observed_overflow_list = _overflow_list; 9127 oop cur_overflow_list; 9128 do { 9129 cur_overflow_list = observed_overflow_list; 9130 if (cur_overflow_list != BUSY) { 9131 p->set_mark(markOop(cur_overflow_list)); 9132 } else { 9133 p->set_mark(NULL); 9134 } 9135 observed_overflow_list = 9136 (oop) Atomic::cmpxchg_ptr(p, &_overflow_list, cur_overflow_list); 9137 } while (cur_overflow_list != observed_overflow_list); 9138 } 9139 #undef BUSY 9140 9141 // Single threaded 9142 // General Note on GrowableArray: pushes may silently fail 9143 // because we are (temporarily) out of C-heap for expanding 9144 // the stack. The problem is quite ubiquitous and affects 9145 // a lot of code in the JVM. The prudent thing for GrowableArray 9146 // to do (for now) is to exit with an error. However, that may 9147 // be too draconian in some cases because the caller may be 9148 // able to recover without much harm. For such cases, we 9149 // should probably introduce a "soft_push" method which returns 9150 // an indication of success or failure with the assumption that 9151 // the caller may be able to recover from a failure; code in 9152 // the VM can then be changed, incrementally, to deal with such 9153 // failures where possible, thus, incrementally hardening the VM 9154 // in such low resource situations. 9155 void CMSCollector::preserve_mark_work(oop p, markOop m) { 9156 _preserved_oop_stack.push(p); 9157 _preserved_mark_stack.push(m); 9158 assert(m == p->mark(), "Mark word changed"); 9159 assert(_preserved_oop_stack.size() == _preserved_mark_stack.size(), 9160 "bijection"); 9161 } 9162 9163 // Single threaded 9164 void CMSCollector::preserve_mark_if_necessary(oop p) { 9165 markOop m = p->mark(); 9166 if (m->must_be_preserved(p)) { 9167 preserve_mark_work(p, m); 9168 } 9169 } 9170 9171 void CMSCollector::par_preserve_mark_if_necessary(oop p) { 9172 markOop m = p->mark(); 9173 if (m->must_be_preserved(p)) { 9174 MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag); 9175 // Even though we read the mark word without holding 9176 // the lock, we are assured that it will not change 9177 // because we "own" this oop, so no other thread can 9178 // be trying to push it on the overflow list; see 9179 // the assertion in preserve_mark_work() that checks 9180 // that m == p->mark(). 9181 preserve_mark_work(p, m); 9182 } 9183 } 9184 9185 // We should be able to do this multi-threaded, 9186 // a chunk of stack being a task (this is 9187 // correct because each oop only ever appears 9188 // once in the overflow list. However, it's 9189 // not very easy to completely overlap this with 9190 // other operations, so will generally not be done 9191 // until all work's been completed. Because we 9192 // expect the preserved oop stack (set) to be small, 9193 // it's probably fine to do this single-threaded. 9194 // We can explore cleverer concurrent/overlapped/parallel 9195 // processing of preserved marks if we feel the 9196 // need for this in the future. Stack overflow should 9197 // be so rare in practice and, when it happens, its 9198 // effect on performance so great that this will 9199 // likely just be in the noise anyway. 9200 void CMSCollector::restore_preserved_marks_if_any() { 9201 assert(SafepointSynchronize::is_at_safepoint(), 9202 "world should be stopped"); 9203 assert(Thread::current()->is_ConcurrentGC_thread() || 9204 Thread::current()->is_VM_thread(), 9205 "should be single-threaded"); 9206 assert(_preserved_oop_stack.size() == _preserved_mark_stack.size(), 9207 "bijection"); 9208 9209 while (!_preserved_oop_stack.is_empty()) { 9210 oop p = _preserved_oop_stack.pop(); 9211 assert(p->is_oop(), "Should be an oop"); 9212 assert(_span.contains(p), "oop should be in _span"); 9213 assert(p->mark() == markOopDesc::prototype(), 9214 "Set when taken from overflow list"); 9215 markOop m = _preserved_mark_stack.pop(); 9216 p->set_mark(m); 9217 } 9218 assert(_preserved_mark_stack.is_empty() && _preserved_oop_stack.is_empty(), 9219 "stacks were cleared above"); 9220 } 9221 9222 #ifndef PRODUCT 9223 bool CMSCollector::no_preserved_marks() const { 9224 return _preserved_mark_stack.is_empty() && _preserved_oop_stack.is_empty(); 9225 } 9226 #endif 9227 9228 // Transfer some number of overflown objects to usual marking 9229 // stack. Return true if some objects were transferred. 9230 bool MarkRefsIntoAndScanClosure::take_from_overflow_list() { 9231 size_t num = MIN2((size_t)(_mark_stack->capacity() - _mark_stack->length())/4, 9232 (size_t)ParGCDesiredObjsFromOverflowList); 9233 9234 bool res = _collector->take_from_overflow_list(num, _mark_stack); 9235 assert(_collector->overflow_list_is_empty() || res, 9236 "If list is not empty, we should have taken something"); 9237 assert(!res || !_mark_stack->isEmpty(), 9238 "If we took something, it should now be on our stack"); 9239 return res; 9240 } 9241 9242 size_t MarkDeadObjectsClosure::do_blk(HeapWord* addr) { 9243 size_t res = _sp->block_size_no_stall(addr, _collector); 9244 if (_sp->block_is_obj(addr)) { 9245 if (_live_bit_map->isMarked(addr)) { 9246 // It can't have been dead in a previous cycle 9247 guarantee(!_dead_bit_map->isMarked(addr), "No resurrection!"); 9248 } else { 9249 _dead_bit_map->mark(addr); // mark the dead object 9250 } 9251 } 9252 // Could be 0, if the block size could not be computed without stalling. 9253 return res; 9254 } 9255 9256 TraceCMSMemoryManagerStats::TraceCMSMemoryManagerStats(CMSCollector::CollectorState phase, GCCause::Cause cause): TraceMemoryManagerStats() { 9257 9258 switch (phase) { 9259 case CMSCollector::InitialMarking: 9260 initialize(true /* fullGC */ , 9261 cause /* cause of the GC */, 9262 true /* recordGCBeginTime */, 9263 true /* recordPreGCUsage */, 9264 false /* recordPeakUsage */, 9265 false /* recordPostGCusage */, 9266 true /* recordAccumulatedGCTime */, 9267 false /* recordGCEndTime */, 9268 false /* countCollection */ ); 9269 break; 9270 9271 case CMSCollector::FinalMarking: 9272 initialize(true /* fullGC */ , 9273 cause /* cause of the GC */, 9274 false /* recordGCBeginTime */, 9275 false /* recordPreGCUsage */, 9276 false /* recordPeakUsage */, 9277 false /* recordPostGCusage */, 9278 true /* recordAccumulatedGCTime */, 9279 false /* recordGCEndTime */, 9280 false /* countCollection */ ); 9281 break; 9282 9283 case CMSCollector::Sweeping: 9284 initialize(true /* fullGC */ , 9285 cause /* cause of the GC */, 9286 false /* recordGCBeginTime */, 9287 false /* recordPreGCUsage */, 9288 true /* recordPeakUsage */, 9289 true /* recordPostGCusage */, 9290 false /* recordAccumulatedGCTime */, 9291 true /* recordGCEndTime */, 9292 true /* countCollection */ ); 9293 break; 9294 9295 default: 9296 ShouldNotReachHere(); 9297 } 9298 }