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