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