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