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