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