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