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