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