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