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