1 /* 2 * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #ifndef SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CONCURRENTMARKSWEEPGENERATION_HPP 26 #define SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CONCURRENTMARKSWEEPGENERATION_HPP 27 28 #include "gc_implementation/shared/gcHeapSummary.hpp" 29 #include "gc_implementation/shared/gSpaceCounters.hpp" 30 #include "gc_implementation/shared/gcStats.hpp" 31 #include "gc_implementation/shared/gcWhen.hpp" 32 #include "gc_implementation/shared/generationCounters.hpp" 33 #include "memory/freeBlockDictionary.hpp" 34 #include "memory/generation.hpp" 35 #include "memory/iterator.hpp" 36 #include "runtime/mutexLocker.hpp" 37 #include "runtime/virtualspace.hpp" 38 #include "services/memoryService.hpp" 39 #include "utilities/bitMap.inline.hpp" 40 #include "utilities/stack.inline.hpp" 41 #include "utilities/taskqueue.hpp" 42 #include "utilities/yieldingWorkgroup.hpp" 43 44 // ConcurrentMarkSweepGeneration is in support of a concurrent 45 // mark-sweep old generation in the Detlefs-Printezis--Boehm-Demers-Schenker 46 // style. We assume, for now, that this generation is always the 47 // seniormost generation and for simplicity 48 // in the first implementation, that this generation is a single compactible 49 // space. Neither of these restrictions appears essential, and will be 50 // relaxed in the future when more time is available to implement the 51 // greater generality (and there's a need for it). 52 // 53 // Concurrent mode failures are currently handled by 54 // means of a sliding mark-compact. 55 56 class AdaptiveSizePolicy; 57 class CMSConcMarkingTask; 58 class CMSGCAdaptivePolicyCounters; 59 class CMSTracer; 60 class ConcurrentGCTimer; 61 class ConcurrentMarkSweepGeneration; 62 class ConcurrentMarkSweepPolicy; 63 class ConcurrentMarkSweepThread; 64 class CompactibleFreeListSpace; 65 class FreeChunk; 66 class PromotionInfo; 67 class ScanMarkedObjectsAgainCarefullyClosure; 68 class TenuredGeneration; 69 class SerialOldTracer; 70 71 // A generic CMS bit map. It's the basis for both the CMS marking bit map 72 // as well as for the mod union table (in each case only a subset of the 73 // methods are used). This is essentially a wrapper around the BitMap class, 74 // with one bit per (1<<_shifter) HeapWords. (i.e. for the marking bit map, 75 // we have _shifter == 0. and for the mod union table we have 76 // shifter == CardTableModRefBS::card_shift - LogHeapWordSize.) 77 // XXX 64-bit issues in BitMap? 78 class CMSBitMap VALUE_OBJ_CLASS_SPEC { 79 friend class VMStructs; 80 81 HeapWord* _bmStartWord; // base address of range covered by map 82 size_t _bmWordSize; // map size (in #HeapWords covered) 83 const int _shifter; // shifts to convert HeapWord to bit position 84 VirtualSpace _virtual_space; // underlying the bit map 85 BitMap _bm; // the bit map itself 86 public: 87 Mutex* const _lock; // mutex protecting _bm; 88 89 public: 90 // constructor 91 CMSBitMap(int shifter, int mutex_rank, const char* mutex_name); 92 93 // allocates the actual storage for the map 94 bool allocate(MemRegion mr); 95 // field getter 96 Mutex* lock() const { return _lock; } 97 // locking verifier convenience function 98 void assert_locked() const PRODUCT_RETURN; 99 100 // inquiries 101 HeapWord* startWord() const { return _bmStartWord; } 102 size_t sizeInWords() const { return _bmWordSize; } 103 size_t sizeInBits() const { return _bm.size(); } 104 // the following is one past the last word in space 105 HeapWord* endWord() const { return _bmStartWord + _bmWordSize; } 106 107 // reading marks 108 bool isMarked(HeapWord* addr) const; 109 bool par_isMarked(HeapWord* addr) const; // do not lock checks 110 bool isUnmarked(HeapWord* addr) const; 111 bool isAllClear() const; 112 113 // writing marks 114 void mark(HeapWord* addr); 115 // For marking by parallel GC threads; 116 // returns true if we did, false if another thread did 117 bool par_mark(HeapWord* addr); 118 119 void mark_range(MemRegion mr); 120 void par_mark_range(MemRegion mr); 121 void mark_large_range(MemRegion mr); 122 void par_mark_large_range(MemRegion mr); 123 void par_clear(HeapWord* addr); // For unmarking by parallel GC threads. 124 void clear_range(MemRegion mr); 125 void par_clear_range(MemRegion mr); 126 void clear_large_range(MemRegion mr); 127 void par_clear_large_range(MemRegion mr); 128 void clear_all(); 129 void clear_all_incrementally(); // Not yet implemented!! 130 131 NOT_PRODUCT( 132 // checks the memory region for validity 133 void region_invariant(MemRegion mr); 134 ) 135 136 // iteration 137 void iterate(BitMapClosure* cl) { 138 _bm.iterate(cl); 139 } 140 void iterate(BitMapClosure* cl, HeapWord* left, HeapWord* right); 141 void dirty_range_iterate_clear(MemRegionClosure* cl); 142 void dirty_range_iterate_clear(MemRegion mr, MemRegionClosure* cl); 143 144 // auxiliary support for iteration 145 HeapWord* getNextMarkedWordAddress(HeapWord* addr) const; 146 HeapWord* getNextMarkedWordAddress(HeapWord* start_addr, 147 HeapWord* end_addr) const; 148 HeapWord* getNextUnmarkedWordAddress(HeapWord* addr) const; 149 HeapWord* getNextUnmarkedWordAddress(HeapWord* start_addr, 150 HeapWord* end_addr) const; 151 MemRegion getAndClearMarkedRegion(HeapWord* addr); 152 MemRegion getAndClearMarkedRegion(HeapWord* start_addr, 153 HeapWord* end_addr); 154 155 // conversion utilities 156 HeapWord* offsetToHeapWord(size_t offset) const; 157 size_t heapWordToOffset(HeapWord* addr) const; 158 size_t heapWordDiffToOffsetDiff(size_t diff) const; 159 160 void print_on_error(outputStream* st, const char* prefix) const; 161 162 // debugging 163 // is this address range covered by the bit-map? 164 NOT_PRODUCT( 165 bool covers(MemRegion mr) const; 166 bool covers(HeapWord* start, size_t size = 0) const; 167 ) 168 void verifyNoOneBitsInRange(HeapWord* left, HeapWord* right) PRODUCT_RETURN; 169 }; 170 171 // Represents a marking stack used by the CMS collector. 172 // Ideally this should be GrowableArray<> just like MSC's marking stack(s). 173 class CMSMarkStack: public CHeapObj<mtGC> { 174 // 175 friend class CMSCollector; // To get at expansion stats further below. 176 // 177 178 VirtualSpace _virtual_space; // Space for the stack 179 oop* _base; // Bottom of stack 180 size_t _index; // One more than last occupied index 181 size_t _capacity; // Max #elements 182 Mutex _par_lock; // An advisory lock used in case of parallel access 183 NOT_PRODUCT(size_t _max_depth;) // Max depth plumbed during run 184 185 protected: 186 size_t _hit_limit; // We hit max stack size limit 187 size_t _failed_double; // We failed expansion before hitting limit 188 189 public: 190 CMSMarkStack(): 191 _par_lock(Mutex::event, "CMSMarkStack._par_lock", true, 192 Monitor::_safepoint_check_never), 193 _hit_limit(0), 194 _failed_double(0) {} 195 196 bool allocate(size_t size); 197 198 size_t capacity() const { return _capacity; } 199 200 oop pop() { 201 if (!isEmpty()) { 202 return _base[--_index] ; 203 } 204 return NULL; 205 } 206 207 bool push(oop ptr) { 208 if (isFull()) { 209 return false; 210 } else { 211 _base[_index++] = ptr; 212 NOT_PRODUCT(_max_depth = MAX2(_max_depth, _index)); 213 return true; 214 } 215 } 216 217 bool isEmpty() const { return _index == 0; } 218 bool isFull() const { 219 assert(_index <= _capacity, "buffer overflow"); 220 return _index == _capacity; 221 } 222 223 size_t length() { return _index; } 224 225 // "Parallel versions" of some of the above 226 oop par_pop() { 227 // lock and pop 228 MutexLockerEx x(&_par_lock, Mutex::_no_safepoint_check_flag); 229 return pop(); 230 } 231 232 bool par_push(oop ptr) { 233 // lock and push 234 MutexLockerEx x(&_par_lock, Mutex::_no_safepoint_check_flag); 235 return push(ptr); 236 } 237 238 // Forcibly reset the stack, losing all of its contents. 239 void reset() { 240 _index = 0; 241 } 242 243 // Expand the stack, typically in response to an overflow condition. 244 void expand(); 245 246 // Compute the least valued stack element. 247 oop least_value(HeapWord* low) { 248 oop least = (oop)low; 249 for (size_t i = 0; i < _index; i++) { 250 least = MIN2(least, _base[i]); 251 } 252 return least; 253 } 254 255 // Exposed here to allow stack expansion in || case. 256 Mutex* par_lock() { return &_par_lock; } 257 }; 258 259 class CardTableRS; 260 class CMSParGCThreadState; 261 262 class ModUnionClosure: public MemRegionClosure { 263 protected: 264 CMSBitMap* _t; 265 public: 266 ModUnionClosure(CMSBitMap* t): _t(t) { } 267 void do_MemRegion(MemRegion mr); 268 }; 269 270 class ModUnionClosurePar: public ModUnionClosure { 271 public: 272 ModUnionClosurePar(CMSBitMap* t): ModUnionClosure(t) { } 273 void do_MemRegion(MemRegion mr); 274 }; 275 276 // Survivor Chunk Array in support of parallelization of 277 // Survivor Space rescan. 278 class ChunkArray: public CHeapObj<mtGC> { 279 size_t _index; 280 size_t _capacity; 281 size_t _overflows; 282 HeapWord** _array; // storage for array 283 284 public: 285 ChunkArray() : _index(0), _capacity(0), _overflows(0), _array(NULL) {} 286 ChunkArray(HeapWord** a, size_t c): 287 _index(0), _capacity(c), _overflows(0), _array(a) {} 288 289 HeapWord** array() { return _array; } 290 void set_array(HeapWord** a) { _array = a; } 291 292 size_t capacity() { return _capacity; } 293 void set_capacity(size_t c) { _capacity = c; } 294 295 size_t end() { 296 assert(_index <= capacity(), 297 err_msg("_index (" SIZE_FORMAT ") > _capacity (" SIZE_FORMAT "): out of bounds", 298 _index, _capacity)); 299 return _index; 300 } // exclusive 301 302 HeapWord* nth(size_t n) { 303 assert(n < end(), "Out of bounds access"); 304 return _array[n]; 305 } 306 307 void reset() { 308 _index = 0; 309 if (_overflows > 0 && PrintCMSStatistics > 1) { 310 warning("CMS: ChunkArray[" SIZE_FORMAT "] overflowed " SIZE_FORMAT " times", 311 _capacity, _overflows); 312 } 313 _overflows = 0; 314 } 315 316 void record_sample(HeapWord* p, size_t sz) { 317 // For now we do not do anything with the size 318 if (_index < _capacity) { 319 _array[_index++] = p; 320 } else { 321 ++_overflows; 322 assert(_index == _capacity, 323 err_msg("_index (" SIZE_FORMAT ") > _capacity (" SIZE_FORMAT 324 "): out of bounds at overflow#" SIZE_FORMAT, 325 _index, _capacity, _overflows)); 326 } 327 } 328 }; 329 330 // 331 // Timing, allocation and promotion statistics for gc scheduling and incremental 332 // mode pacing. Most statistics are exponential averages. 333 // 334 class CMSStats VALUE_OBJ_CLASS_SPEC { 335 private: 336 ConcurrentMarkSweepGeneration* const _cms_gen; // The cms (old) gen. 337 338 // The following are exponential averages with factor alpha: 339 // avg = (100 - alpha) * avg + alpha * cur_sample 340 // 341 // The durations measure: end_time[n] - start_time[n] 342 // The periods measure: start_time[n] - start_time[n-1] 343 // 344 // The cms period and duration include only concurrent collections; time spent 345 // in foreground cms collections due to System.gc() or because of a failure to 346 // keep up are not included. 347 // 348 // There are 3 alphas to "bootstrap" the statistics. The _saved_alpha is the 349 // real value, but is used only after the first period. A value of 100 is 350 // used for the first sample so it gets the entire weight. 351 unsigned int _saved_alpha; // 0-100 352 unsigned int _gc0_alpha; 353 unsigned int _cms_alpha; 354 355 double _gc0_duration; 356 double _gc0_period; 357 size_t _gc0_promoted; // bytes promoted per gc0 358 double _cms_duration; 359 double _cms_duration_pre_sweep; // time from initiation to start of sweep 360 double _cms_period; 361 size_t _cms_allocated; // bytes of direct allocation per gc0 period 362 363 // Timers. 364 elapsedTimer _cms_timer; 365 TimeStamp _gc0_begin_time; 366 TimeStamp _cms_begin_time; 367 TimeStamp _cms_end_time; 368 369 // Snapshots of the amount used in the CMS generation. 370 size_t _cms_used_at_gc0_begin; 371 size_t _cms_used_at_gc0_end; 372 size_t _cms_used_at_cms_begin; 373 374 // Used to prevent the duty cycle from being reduced in the middle of a cms 375 // cycle. 376 bool _allow_duty_cycle_reduction; 377 378 enum { 379 _GC0_VALID = 0x1, 380 _CMS_VALID = 0x2, 381 _ALL_VALID = _GC0_VALID | _CMS_VALID 382 }; 383 384 unsigned int _valid_bits; 385 386 protected: 387 // In support of adjusting of cms trigger ratios based on history 388 // of concurrent mode failure. 389 double cms_free_adjustment_factor(size_t free) const; 390 void adjust_cms_free_adjustment_factor(bool fail, size_t free); 391 392 public: 393 CMSStats(ConcurrentMarkSweepGeneration* cms_gen, 394 unsigned int alpha = CMSExpAvgFactor); 395 396 // Whether or not the statistics contain valid data; higher level statistics 397 // cannot be called until this returns true (they require at least one young 398 // gen and one cms cycle to have completed). 399 bool valid() const; 400 401 // Record statistics. 402 void record_gc0_begin(); 403 void record_gc0_end(size_t cms_gen_bytes_used); 404 void record_cms_begin(); 405 void record_cms_end(); 406 407 // Allow management of the cms timer, which must be stopped/started around 408 // yield points. 409 elapsedTimer& cms_timer() { return _cms_timer; } 410 void start_cms_timer() { _cms_timer.start(); } 411 void stop_cms_timer() { _cms_timer.stop(); } 412 413 // Basic statistics; units are seconds or bytes. 414 double gc0_period() const { return _gc0_period; } 415 double gc0_duration() const { return _gc0_duration; } 416 size_t gc0_promoted() const { return _gc0_promoted; } 417 double cms_period() const { return _cms_period; } 418 double cms_duration() const { return _cms_duration; } 419 size_t cms_allocated() const { return _cms_allocated; } 420 421 size_t cms_used_at_gc0_end() const { return _cms_used_at_gc0_end;} 422 423 // Seconds since the last background cms cycle began or ended. 424 double cms_time_since_begin() const; 425 double cms_time_since_end() const; 426 427 // Higher level statistics--caller must check that valid() returns true before 428 // calling. 429 430 // Returns bytes promoted per second of wall clock time. 431 double promotion_rate() const; 432 433 // Returns bytes directly allocated per second of wall clock time. 434 double cms_allocation_rate() const; 435 436 // Rate at which space in the cms generation is being consumed (sum of the 437 // above two). 438 double cms_consumption_rate() const; 439 440 // Returns an estimate of the number of seconds until the cms generation will 441 // fill up, assuming no collection work is done. 442 double time_until_cms_gen_full() const; 443 444 // Returns an estimate of the number of seconds remaining until 445 // the cms generation collection should start. 446 double time_until_cms_start() const; 447 448 // End of higher level statistics. 449 450 // Debugging. 451 void print_on(outputStream* st) const PRODUCT_RETURN; 452 void print() const { print_on(gclog_or_tty); } 453 }; 454 455 // A closure related to weak references processing which 456 // we embed in the CMSCollector, since we need to pass 457 // it to the reference processor for secondary filtering 458 // of references based on reachability of referent; 459 // see role of _is_alive_non_header closure in the 460 // ReferenceProcessor class. 461 // For objects in the CMS generation, this closure checks 462 // if the object is "live" (reachable). Used in weak 463 // reference processing. 464 class CMSIsAliveClosure: public BoolObjectClosure { 465 const MemRegion _span; 466 const CMSBitMap* _bit_map; 467 468 friend class CMSCollector; 469 public: 470 CMSIsAliveClosure(MemRegion span, 471 CMSBitMap* bit_map): 472 _span(span), 473 _bit_map(bit_map) { 474 assert(!span.is_empty(), "Empty span could spell trouble"); 475 } 476 477 bool do_object_b(oop obj); 478 }; 479 480 481 // Implements AbstractRefProcTaskExecutor for CMS. 482 class CMSRefProcTaskExecutor: public AbstractRefProcTaskExecutor { 483 public: 484 485 CMSRefProcTaskExecutor(CMSCollector& collector) 486 : _collector(collector) 487 { } 488 489 // Executes a task using worker threads. 490 virtual void execute(ProcessTask& task); 491 virtual void execute(EnqueueTask& task); 492 private: 493 CMSCollector& _collector; 494 }; 495 496 497 class CMSCollector: public CHeapObj<mtGC> { 498 friend class VMStructs; 499 friend class ConcurrentMarkSweepThread; 500 friend class ConcurrentMarkSweepGeneration; 501 friend class CompactibleFreeListSpace; 502 friend class CMSParMarkTask; 503 friend class CMSParInitialMarkTask; 504 friend class CMSParRemarkTask; 505 friend class CMSConcMarkingTask; 506 friend class CMSRefProcTaskProxy; 507 friend class CMSRefProcTaskExecutor; 508 friend class ScanMarkedObjectsAgainCarefullyClosure; // for sampling eden 509 friend class SurvivorSpacePrecleanClosure; // --- ditto ------- 510 friend class PushOrMarkClosure; // to access _restart_addr 511 friend class Par_PushOrMarkClosure; // to access _restart_addr 512 friend class MarkFromRootsClosure; // -- ditto -- 513 // ... and for clearing cards 514 friend class Par_MarkFromRootsClosure; // to access _restart_addr 515 // ... and for clearing cards 516 friend class Par_ConcMarkingClosure; // to access _restart_addr etc. 517 friend class MarkFromRootsVerifyClosure; // to access _restart_addr 518 friend class PushAndMarkVerifyClosure; // -- ditto -- 519 friend class MarkRefsIntoAndScanClosure; // to access _overflow_list 520 friend class PushAndMarkClosure; // -- ditto -- 521 friend class Par_PushAndMarkClosure; // -- ditto -- 522 friend class CMSKeepAliveClosure; // -- ditto -- 523 friend class CMSDrainMarkingStackClosure; // -- ditto -- 524 friend class CMSInnerParMarkAndPushClosure; // -- ditto -- 525 NOT_PRODUCT(friend class ScanMarkedObjectsAgainClosure;) // assertion on _overflow_list 526 friend class ReleaseForegroundGC; // to access _foregroundGCShouldWait 527 friend class VM_CMS_Operation; 528 friend class VM_CMS_Initial_Mark; 529 friend class VM_CMS_Final_Remark; 530 friend class TraceCMSMemoryManagerStats; 531 532 private: 533 jlong _time_of_last_gc; 534 void update_time_of_last_gc(jlong now) { 535 _time_of_last_gc = now; 536 } 537 538 OopTaskQueueSet* _task_queues; 539 540 // Overflow list of grey objects, threaded through mark-word 541 // Manipulated with CAS in the parallel/multi-threaded case. 542 oop _overflow_list; 543 // The following array-pair keeps track of mark words 544 // displaced for accommodating overflow list above. 545 // This code will likely be revisited under RFE#4922830. 546 Stack<oop, mtGC> _preserved_oop_stack; 547 Stack<markOop, mtGC> _preserved_mark_stack; 548 549 int* _hash_seed; 550 551 // In support of multi-threaded concurrent phases 552 YieldingFlexibleWorkGang* _conc_workers; 553 554 // Performance Counters 555 CollectorCounters* _gc_counters; 556 557 // Initialization Errors 558 bool _completed_initialization; 559 560 // In support of ExplicitGCInvokesConcurrent 561 static bool _full_gc_requested; 562 static GCCause::Cause _full_gc_cause; 563 unsigned int _collection_count_start; 564 565 // Should we unload classes this concurrent cycle? 566 bool _should_unload_classes; 567 unsigned int _concurrent_cycles_since_last_unload; 568 unsigned int concurrent_cycles_since_last_unload() const { 569 return _concurrent_cycles_since_last_unload; 570 } 571 // Did we (allow) unload classes in the previous concurrent cycle? 572 bool unloaded_classes_last_cycle() const { 573 return concurrent_cycles_since_last_unload() == 0; 574 } 575 // Root scanning options for perm gen 576 int _roots_scanning_options; 577 int roots_scanning_options() const { return _roots_scanning_options; } 578 void add_root_scanning_option(int o) { _roots_scanning_options |= o; } 579 void remove_root_scanning_option(int o) { _roots_scanning_options &= ~o; } 580 581 // Verification support 582 CMSBitMap _verification_mark_bm; 583 void verify_after_remark_work_1(); 584 void verify_after_remark_work_2(); 585 586 // True if any verification flag is on. 587 bool _verifying; 588 bool verifying() const { return _verifying; } 589 void set_verifying(bool v) { _verifying = v; } 590 591 // Collector policy 592 ConcurrentMarkSweepPolicy* _collector_policy; 593 ConcurrentMarkSweepPolicy* collector_policy() { return _collector_policy; } 594 595 void set_did_compact(bool v); 596 597 // XXX Move these to CMSStats ??? FIX ME !!! 598 elapsedTimer _inter_sweep_timer; // Time between sweeps 599 elapsedTimer _intra_sweep_timer; // Time _in_ sweeps 600 // Padded decaying average estimates of the above 601 AdaptivePaddedAverage _inter_sweep_estimate; 602 AdaptivePaddedAverage _intra_sweep_estimate; 603 604 CMSTracer* _gc_tracer_cm; 605 ConcurrentGCTimer* _gc_timer_cm; 606 607 bool _cms_start_registered; 608 609 GCHeapSummary _last_heap_summary; 610 MetaspaceSummary _last_metaspace_summary; 611 612 void register_foreground_gc_start(GCCause::Cause cause); 613 void register_gc_start(GCCause::Cause cause); 614 void register_gc_end(); 615 void save_heap_summary(); 616 void report_heap_summary(GCWhen::Type when); 617 618 protected: 619 ConcurrentMarkSweepGeneration* _cmsGen; // Old gen (CMS) 620 MemRegion _span; // Span covering above two 621 CardTableRS* _ct; // Card table 622 623 // CMS marking support structures 624 CMSBitMap _markBitMap; 625 CMSBitMap _modUnionTable; 626 CMSMarkStack _markStack; 627 628 HeapWord* _restart_addr; // In support of marking stack overflow 629 void lower_restart_addr(HeapWord* low); 630 631 // Counters in support of marking stack / work queue overflow handling: 632 // a non-zero value indicates certain types of overflow events during 633 // the current CMS cycle and could lead to stack resizing efforts at 634 // an opportune future time. 635 size_t _ser_pmc_preclean_ovflw; 636 size_t _ser_pmc_remark_ovflw; 637 size_t _par_pmc_remark_ovflw; 638 size_t _ser_kac_preclean_ovflw; 639 size_t _ser_kac_ovflw; 640 size_t _par_kac_ovflw; 641 NOT_PRODUCT(ssize_t _num_par_pushes;) 642 643 // ("Weak") Reference processing support. 644 ReferenceProcessor* _ref_processor; 645 CMSIsAliveClosure _is_alive_closure; 646 // Keep this textually after _markBitMap and _span; c'tor dependency. 647 648 ConcurrentMarkSweepThread* _cmsThread; // The thread doing the work 649 ModUnionClosure _modUnionClosure; 650 ModUnionClosurePar _modUnionClosurePar; 651 652 // CMS abstract state machine 653 // initial_state: Idling 654 // next_state(Idling) = {Marking} 655 // next_state(Marking) = {Precleaning, Sweeping} 656 // next_state(Precleaning) = {AbortablePreclean, FinalMarking} 657 // next_state(AbortablePreclean) = {FinalMarking} 658 // next_state(FinalMarking) = {Sweeping} 659 // next_state(Sweeping) = {Resizing} 660 // next_state(Resizing) = {Resetting} 661 // next_state(Resetting) = {Idling} 662 // The numeric values below are chosen so that: 663 // . _collectorState <= Idling == post-sweep && pre-mark 664 // . _collectorState in (Idling, Sweeping) == {initial,final}marking || 665 // precleaning || abortablePrecleanb 666 public: 667 enum CollectorState { 668 Resizing = 0, 669 Resetting = 1, 670 Idling = 2, 671 InitialMarking = 3, 672 Marking = 4, 673 Precleaning = 5, 674 AbortablePreclean = 6, 675 FinalMarking = 7, 676 Sweeping = 8 677 }; 678 protected: 679 static CollectorState _collectorState; 680 681 // State related to prologue/epilogue invocation for my generations 682 bool _between_prologue_and_epilogue; 683 684 // Signaling/State related to coordination between fore- and background GC 685 // Note: When the baton has been passed from background GC to foreground GC, 686 // _foregroundGCIsActive is true and _foregroundGCShouldWait is false. 687 static bool _foregroundGCIsActive; // true iff foreground collector is active or 688 // wants to go active 689 static bool _foregroundGCShouldWait; // true iff background GC is active and has not 690 // yet passed the baton to the foreground GC 691 692 // Support for CMSScheduleRemark (abortable preclean) 693 bool _abort_preclean; 694 bool _start_sampling; 695 696 int _numYields; 697 size_t _numDirtyCards; 698 size_t _sweep_count; 699 // Number of full gc's since the last concurrent gc. 700 uint _full_gcs_since_conc_gc; 701 702 // Occupancy used for bootstrapping stats 703 double _bootstrap_occupancy; 704 705 // Timer 706 elapsedTimer _timer; 707 708 // Timing, allocation and promotion statistics, used for scheduling. 709 CMSStats _stats; 710 711 enum CMS_op_type { 712 CMS_op_checkpointRootsInitial, 713 CMS_op_checkpointRootsFinal 714 }; 715 716 void do_CMS_operation(CMS_op_type op, GCCause::Cause gc_cause); 717 bool stop_world_and_do(CMS_op_type op); 718 719 OopTaskQueueSet* task_queues() { return _task_queues; } 720 int* hash_seed(int i) { return &_hash_seed[i]; } 721 YieldingFlexibleWorkGang* conc_workers() { return _conc_workers; } 722 723 // Support for parallelizing Eden rescan in CMS remark phase 724 void sample_eden(); // ... sample Eden space top 725 726 private: 727 // Support for parallelizing young gen rescan in CMS remark phase 728 Generation* _young_gen; // the younger gen 729 HeapWord** _top_addr; // ... Top of Eden 730 HeapWord** _end_addr; // ... End of Eden 731 Mutex* _eden_chunk_lock; 732 HeapWord** _eden_chunk_array; // ... Eden partitioning array 733 size_t _eden_chunk_index; // ... top (exclusive) of array 734 size_t _eden_chunk_capacity; // ... max entries in array 735 736 // Support for parallelizing survivor space rescan 737 HeapWord** _survivor_chunk_array; 738 size_t _survivor_chunk_index; 739 size_t _survivor_chunk_capacity; 740 size_t* _cursor; 741 ChunkArray* _survivor_plab_array; 742 743 // Support for marking stack overflow handling 744 bool take_from_overflow_list(size_t num, CMSMarkStack* to_stack); 745 bool par_take_from_overflow_list(size_t num, 746 OopTaskQueue* to_work_q, 747 int no_of_gc_threads); 748 void push_on_overflow_list(oop p); 749 void par_push_on_overflow_list(oop p); 750 // The following is, obviously, not, in general, "MT-stable" 751 bool overflow_list_is_empty() const; 752 753 void preserve_mark_if_necessary(oop p); 754 void par_preserve_mark_if_necessary(oop p); 755 void preserve_mark_work(oop p, markOop m); 756 void restore_preserved_marks_if_any(); 757 NOT_PRODUCT(bool no_preserved_marks() const;) 758 // In support of testing overflow code 759 NOT_PRODUCT(int _overflow_counter;) 760 NOT_PRODUCT(bool simulate_overflow();) // Sequential 761 NOT_PRODUCT(bool par_simulate_overflow();) // MT version 762 763 // CMS work methods 764 void checkpointRootsInitialWork(bool asynch); // Initial checkpoint work 765 766 // A return value of false indicates failure due to stack overflow 767 bool markFromRootsWork(bool asynch); // Concurrent marking work 768 769 public: // FIX ME!!! only for testing 770 bool do_marking_st(bool asynch); // Single-threaded marking 771 bool do_marking_mt(bool asynch); // Multi-threaded marking 772 773 private: 774 775 // Concurrent precleaning work 776 size_t preclean_mod_union_table(ConcurrentMarkSweepGeneration* gen, 777 ScanMarkedObjectsAgainCarefullyClosure* cl); 778 size_t preclean_card_table(ConcurrentMarkSweepGeneration* gen, 779 ScanMarkedObjectsAgainCarefullyClosure* cl); 780 // Does precleaning work, returning a quantity indicative of 781 // the amount of "useful work" done. 782 size_t preclean_work(bool clean_refs, bool clean_survivors); 783 void preclean_klasses(MarkRefsIntoAndScanClosure* cl, Mutex* freelistLock); 784 void abortable_preclean(); // Preclean while looking for possible abort 785 void initialize_sequential_subtasks_for_young_gen_rescan(int i); 786 // Helper function for above; merge-sorts the per-thread plab samples 787 void merge_survivor_plab_arrays(ContiguousSpace* surv, int no_of_gc_threads); 788 // Resets (i.e. clears) the per-thread plab sample vectors 789 void reset_survivor_plab_arrays(); 790 791 // Final (second) checkpoint work 792 void checkpointRootsFinalWork(bool asynch, bool clear_all_soft_refs, 793 bool init_mark_was_synchronous); 794 // Work routine for parallel version of remark 795 void do_remark_parallel(); 796 // Work routine for non-parallel version of remark 797 void do_remark_non_parallel(); 798 // Reference processing work routine (during second checkpoint) 799 void refProcessingWork(bool asynch, bool clear_all_soft_refs); 800 801 // Concurrent sweeping work 802 void sweepWork(ConcurrentMarkSweepGeneration* gen, bool asynch); 803 804 // (Concurrent) resetting of support data structures 805 void reset(bool asynch); 806 807 // Clear _expansion_cause fields of constituent generations 808 void clear_expansion_cause(); 809 810 // An auxiliary method used to record the ends of 811 // used regions of each generation to limit the extent of sweep 812 void save_sweep_limits(); 813 814 // A work method used by foreground collection to determine 815 // what type of collection (compacting or not, continuing or fresh) 816 // it should do. 817 void decide_foreground_collection_type(bool clear_all_soft_refs, 818 bool* should_compact, bool* should_start_over); 819 820 // A work method used by the foreground collector to do 821 // a mark-sweep-compact. 822 void do_compaction_work(bool clear_all_soft_refs); 823 824 // A work method used by the foreground collector to do 825 // a mark-sweep, after taking over from a possibly on-going 826 // concurrent mark-sweep collection. 827 void do_mark_sweep_work(bool clear_all_soft_refs, 828 CollectorState first_state, bool should_start_over); 829 830 // Work methods for reporting concurrent mode interruption or failure 831 bool is_external_interruption(); 832 void report_concurrent_mode_interruption(); 833 834 // If the background GC is active, acquire control from the background 835 // GC and do the collection. 836 void acquire_control_and_collect(bool full, bool clear_all_soft_refs); 837 838 // For synchronizing passing of control from background to foreground 839 // GC. waitForForegroundGC() is called by the background 840 // collector. It if had to wait for a foreground collection, 841 // it returns true and the background collection should assume 842 // that the collection was finished by the foreground 843 // collector. 844 bool waitForForegroundGC(); 845 846 size_t block_size_using_printezis_bits(HeapWord* addr) const; 847 size_t block_size_if_printezis_bits(HeapWord* addr) const; 848 HeapWord* next_card_start_after_block(HeapWord* addr) const; 849 850 void setup_cms_unloading_and_verification_state(); 851 public: 852 CMSCollector(ConcurrentMarkSweepGeneration* cmsGen, 853 CardTableRS* ct, 854 ConcurrentMarkSweepPolicy* cp); 855 ConcurrentMarkSweepThread* cmsThread() { return _cmsThread; } 856 857 ReferenceProcessor* ref_processor() { return _ref_processor; } 858 void ref_processor_init(); 859 860 Mutex* bitMapLock() const { return _markBitMap.lock(); } 861 static CollectorState abstract_state() { return _collectorState; } 862 863 bool should_abort_preclean() const; // Whether preclean should be aborted. 864 size_t get_eden_used() const; 865 size_t get_eden_capacity() const; 866 867 ConcurrentMarkSweepGeneration* cmsGen() { return _cmsGen; } 868 869 // Locking checks 870 NOT_PRODUCT(static bool have_cms_token();) 871 872 // XXXPERM bool should_collect(bool full, size_t size, bool tlab); 873 bool shouldConcurrentCollect(); 874 875 void collect(bool full, 876 bool clear_all_soft_refs, 877 size_t size, 878 bool tlab); 879 void collect_in_background(bool clear_all_soft_refs, GCCause::Cause cause); 880 void collect_in_foreground(bool clear_all_soft_refs, GCCause::Cause cause); 881 882 // In support of ExplicitGCInvokesConcurrent 883 static void request_full_gc(unsigned int full_gc_count, GCCause::Cause cause); 884 // Should we unload classes in a particular concurrent cycle? 885 bool should_unload_classes() const { 886 return _should_unload_classes; 887 } 888 void update_should_unload_classes(); 889 890 void direct_allocated(HeapWord* start, size_t size); 891 892 // Object is dead if not marked and current phase is sweeping. 893 bool is_dead_obj(oop obj) const; 894 895 // After a promotion (of "start"), do any necessary marking. 896 // If "par", then it's being done by a parallel GC thread. 897 // The last two args indicate if we need precise marking 898 // and if so the size of the object so it can be dirtied 899 // in its entirety. 900 void promoted(bool par, HeapWord* start, 901 bool is_obj_array, size_t obj_size); 902 903 void getFreelistLocks() const; 904 void releaseFreelistLocks() const; 905 bool haveFreelistLocks() const; 906 907 // Adjust size of underlying generation 908 void compute_new_size(); 909 910 // GC prologue and epilogue 911 void gc_prologue(bool full); 912 void gc_epilogue(bool full); 913 914 jlong time_of_last_gc(jlong now) { 915 if (_collectorState <= Idling) { 916 // gc not in progress 917 return _time_of_last_gc; 918 } else { 919 // collection in progress 920 return now; 921 } 922 } 923 924 // Support for parallel remark of survivor space 925 void* get_data_recorder(int thr_num); 926 void sample_eden_chunk(); 927 928 CMSBitMap* markBitMap() { return &_markBitMap; } 929 void directAllocated(HeapWord* start, size_t size); 930 931 // Main CMS steps and related support 932 void checkpointRootsInitial(bool asynch); 933 bool markFromRoots(bool asynch); // a return value of false indicates failure 934 // due to stack overflow 935 void preclean(); 936 void checkpointRootsFinal(bool asynch, bool clear_all_soft_refs, 937 bool init_mark_was_synchronous); 938 void sweep(bool asynch); 939 940 // Check that the currently executing thread is the expected 941 // one (foreground collector or background collector). 942 static void check_correct_thread_executing() PRODUCT_RETURN; 943 // XXXPERM void print_statistics() PRODUCT_RETURN; 944 945 bool is_cms_reachable(HeapWord* addr); 946 947 // Performance Counter Support 948 CollectorCounters* counters() { return _gc_counters; } 949 950 // Timer stuff 951 void startTimer() { assert(!_timer.is_active(), "Error"); _timer.start(); } 952 void stopTimer() { assert( _timer.is_active(), "Error"); _timer.stop(); } 953 void resetTimer() { assert(!_timer.is_active(), "Error"); _timer.reset(); } 954 double timerValue() { assert(!_timer.is_active(), "Error"); return _timer.seconds(); } 955 956 int yields() { return _numYields; } 957 void resetYields() { _numYields = 0; } 958 void incrementYields() { _numYields++; } 959 void resetNumDirtyCards() { _numDirtyCards = 0; } 960 void incrementNumDirtyCards(size_t num) { _numDirtyCards += num; } 961 size_t numDirtyCards() { return _numDirtyCards; } 962 963 static bool foregroundGCShouldWait() { return _foregroundGCShouldWait; } 964 static void set_foregroundGCShouldWait(bool v) { _foregroundGCShouldWait = v; } 965 static bool foregroundGCIsActive() { return _foregroundGCIsActive; } 966 static void set_foregroundGCIsActive(bool v) { _foregroundGCIsActive = v; } 967 size_t sweep_count() const { return _sweep_count; } 968 void increment_sweep_count() { _sweep_count++; } 969 970 // Timers/stats for gc scheduling and incremental mode pacing. 971 CMSStats& stats() { return _stats; } 972 973 // Adaptive size policy 974 AdaptiveSizePolicy* size_policy(); 975 976 static void print_on_error(outputStream* st); 977 978 // Debugging 979 void verify(); 980 bool verify_after_remark(bool silent = VerifySilently); 981 void verify_ok_to_terminate() const PRODUCT_RETURN; 982 void verify_work_stacks_empty() const PRODUCT_RETURN; 983 void verify_overflow_empty() const PRODUCT_RETURN; 984 985 // Convenience methods in support of debugging 986 static const size_t skip_header_HeapWords() PRODUCT_RETURN0; 987 HeapWord* block_start(const void* p) const PRODUCT_RETURN0; 988 989 // Accessors 990 CMSMarkStack* verification_mark_stack() { return &_markStack; } 991 CMSBitMap* verification_mark_bm() { return &_verification_mark_bm; } 992 993 // Initialization errors 994 bool completed_initialization() { return _completed_initialization; } 995 996 void print_eden_and_survivor_chunk_arrays(); 997 }; 998 999 class CMSExpansionCause : public AllStatic { 1000 public: 1001 enum Cause { 1002 _no_expansion, 1003 _satisfy_free_ratio, 1004 _satisfy_promotion, 1005 _satisfy_allocation, 1006 _allocate_par_lab, 1007 _allocate_par_spooling_space, 1008 _adaptive_size_policy 1009 }; 1010 // Return a string describing the cause of the expansion. 1011 static const char* to_string(CMSExpansionCause::Cause cause); 1012 }; 1013 1014 class ConcurrentMarkSweepGeneration: public CardGeneration { 1015 friend class VMStructs; 1016 friend class ConcurrentMarkSweepThread; 1017 friend class ConcurrentMarkSweep; 1018 friend class CMSCollector; 1019 protected: 1020 static CMSCollector* _collector; // the collector that collects us 1021 CompactibleFreeListSpace* _cmsSpace; // underlying space (only one for now) 1022 1023 // Performance Counters 1024 GenerationCounters* _gen_counters; 1025 GSpaceCounters* _space_counters; 1026 1027 // Words directly allocated, used by CMSStats. 1028 size_t _direct_allocated_words; 1029 1030 // Non-product stat counters 1031 NOT_PRODUCT( 1032 size_t _numObjectsPromoted; 1033 size_t _numWordsPromoted; 1034 size_t _numObjectsAllocated; 1035 size_t _numWordsAllocated; 1036 ) 1037 1038 // Used for sizing decisions 1039 bool _incremental_collection_failed; 1040 bool incremental_collection_failed() { 1041 return _incremental_collection_failed; 1042 } 1043 void set_incremental_collection_failed() { 1044 _incremental_collection_failed = true; 1045 } 1046 void clear_incremental_collection_failed() { 1047 _incremental_collection_failed = false; 1048 } 1049 1050 // accessors 1051 void set_expansion_cause(CMSExpansionCause::Cause v) { _expansion_cause = v;} 1052 CMSExpansionCause::Cause expansion_cause() const { return _expansion_cause; } 1053 1054 private: 1055 // For parallel young-gen GC support. 1056 CMSParGCThreadState** _par_gc_thread_states; 1057 1058 // Reason generation was expanded 1059 CMSExpansionCause::Cause _expansion_cause; 1060 1061 // In support of MinChunkSize being larger than min object size 1062 const double _dilatation_factor; 1063 1064 enum CollectionTypes { 1065 Concurrent_collection_type = 0, 1066 MS_foreground_collection_type = 1, 1067 MSC_foreground_collection_type = 2, 1068 Unknown_collection_type = 3 1069 }; 1070 1071 CollectionTypes _debug_collection_type; 1072 1073 // True if a compacting collection was done. 1074 bool _did_compact; 1075 bool did_compact() { return _did_compact; } 1076 1077 // Fraction of current occupancy at which to start a CMS collection which 1078 // will collect this generation (at least). 1079 double _initiating_occupancy; 1080 1081 protected: 1082 // Shrink generation by specified size (returns false if unable to shrink) 1083 void shrink_free_list_by(size_t bytes); 1084 1085 // Update statistics for GC 1086 virtual void update_gc_stats(int level, bool full); 1087 1088 // Maximum available space in the generation (including uncommitted) 1089 // space. 1090 size_t max_available() const; 1091 1092 // getter and initializer for _initiating_occupancy field. 1093 double initiating_occupancy() const { return _initiating_occupancy; } 1094 void init_initiating_occupancy(intx io, uintx tr); 1095 1096 public: 1097 ConcurrentMarkSweepGeneration(ReservedSpace rs, size_t initial_byte_size, 1098 int level, CardTableRS* ct, 1099 bool use_adaptive_freelists, 1100 FreeBlockDictionary<FreeChunk>::DictionaryChoice); 1101 1102 // Accessors 1103 CMSCollector* collector() const { return _collector; } 1104 static void set_collector(CMSCollector* collector) { 1105 assert(_collector == NULL, "already set"); 1106 _collector = collector; 1107 } 1108 CompactibleFreeListSpace* cmsSpace() const { return _cmsSpace; } 1109 1110 Mutex* freelistLock() const; 1111 1112 virtual Generation::Name kind() { return Generation::ConcurrentMarkSweep; } 1113 1114 void set_did_compact(bool v) { _did_compact = v; } 1115 1116 bool refs_discovery_is_atomic() const { return false; } 1117 bool refs_discovery_is_mt() const { 1118 // Note: CMS does MT-discovery during the parallel-remark 1119 // phases. Use ReferenceProcessorMTMutator to make refs 1120 // discovery MT-safe during such phases or other parallel 1121 // discovery phases in the future. This may all go away 1122 // if/when we decide that refs discovery is sufficiently 1123 // rare that the cost of the CAS's involved is in the 1124 // noise. That's a measurement that should be done, and 1125 // the code simplified if that turns out to be the case. 1126 return ConcGCThreads > 1; 1127 } 1128 1129 // Override 1130 virtual void ref_processor_init(); 1131 1132 // Grow generation by specified size (returns false if unable to grow) 1133 bool grow_by(size_t bytes); 1134 // Grow generation to reserved size. 1135 bool grow_to_reserved(); 1136 1137 void clear_expansion_cause() { _expansion_cause = CMSExpansionCause::_no_expansion; } 1138 1139 // Space enquiries 1140 size_t capacity() const; 1141 size_t used() const; 1142 size_t free() const; 1143 double occupancy() const { return ((double)used())/((double)capacity()); } 1144 size_t contiguous_available() const; 1145 size_t unsafe_max_alloc_nogc() const; 1146 1147 // over-rides 1148 MemRegion used_region() const; 1149 MemRegion used_region_at_save_marks() const; 1150 1151 // Does a "full" (forced) collection invoked on this generation collect 1152 // all younger generations as well? Note that the second conjunct is a 1153 // hack to allow the collection of the younger gen first if the flag is 1154 // set. 1155 virtual bool full_collects_younger_generations() const { 1156 return UseCMSCompactAtFullCollection && !ScavengeBeforeFullGC; 1157 } 1158 1159 void space_iterate(SpaceClosure* blk, bool usedOnly = false); 1160 1161 // Support for compaction 1162 CompactibleSpace* first_compaction_space() const; 1163 // Adjust quantities in the generation affected by 1164 // the compaction. 1165 void reset_after_compaction(); 1166 1167 // Allocation support 1168 HeapWord* allocate(size_t size, bool tlab); 1169 HeapWord* have_lock_and_allocate(size_t size, bool tlab); 1170 oop promote(oop obj, size_t obj_size); 1171 HeapWord* par_allocate(size_t size, bool tlab) { 1172 return allocate(size, tlab); 1173 } 1174 1175 1176 // Used by CMSStats to track direct allocation. The value is sampled and 1177 // reset after each young gen collection. 1178 size_t direct_allocated_words() const { return _direct_allocated_words; } 1179 void reset_direct_allocated_words() { _direct_allocated_words = 0; } 1180 1181 // Overrides for parallel promotion. 1182 virtual oop par_promote(int thread_num, 1183 oop obj, markOop m, size_t word_sz); 1184 // This one should not be called for CMS. 1185 virtual void par_promote_alloc_undo(int thread_num, 1186 HeapWord* obj, size_t word_sz); 1187 virtual void par_promote_alloc_done(int thread_num); 1188 virtual void par_oop_since_save_marks_iterate_done(int thread_num); 1189 1190 virtual bool promotion_attempt_is_safe(size_t promotion_in_bytes) const; 1191 1192 // Inform this (non-young) generation that a promotion failure was 1193 // encountered during a collection of a younger generation that 1194 // promotes into this generation. 1195 virtual void promotion_failure_occurred(); 1196 1197 bool should_collect(bool full, size_t size, bool tlab); 1198 virtual bool should_concurrent_collect() const; 1199 virtual bool is_too_full() const; 1200 void collect(bool full, 1201 bool clear_all_soft_refs, 1202 size_t size, 1203 bool tlab); 1204 1205 HeapWord* expand_and_allocate(size_t word_size, 1206 bool tlab, 1207 bool parallel = false); 1208 1209 // GC prologue and epilogue 1210 void gc_prologue(bool full); 1211 void gc_prologue_work(bool full, bool registerClosure, 1212 ModUnionClosure* modUnionClosure); 1213 void gc_epilogue(bool full); 1214 void gc_epilogue_work(bool full); 1215 1216 // Time since last GC of this generation 1217 jlong time_of_last_gc(jlong now) { 1218 return collector()->time_of_last_gc(now); 1219 } 1220 void update_time_of_last_gc(jlong now) { 1221 collector()-> update_time_of_last_gc(now); 1222 } 1223 1224 // Allocation failure 1225 void expand(size_t bytes, size_t expand_bytes, 1226 CMSExpansionCause::Cause cause); 1227 virtual bool expand(size_t bytes, size_t expand_bytes); 1228 void shrink(size_t bytes); 1229 void shrink_by(size_t bytes); 1230 HeapWord* expand_and_par_lab_allocate(CMSParGCThreadState* ps, size_t word_sz); 1231 bool expand_and_ensure_spooling_space(PromotionInfo* promo); 1232 1233 // Iteration support and related enquiries 1234 void save_marks(); 1235 bool no_allocs_since_save_marks(); 1236 void younger_refs_iterate(OopsInGenClosure* cl); 1237 1238 // Iteration support specific to CMS generations 1239 void save_sweep_limit(); 1240 1241 // More iteration support 1242 virtual void oop_iterate(ExtendedOopClosure* cl); 1243 virtual void safe_object_iterate(ObjectClosure* cl); 1244 virtual void object_iterate(ObjectClosure* cl); 1245 1246 // Need to declare the full complement of closures, whether we'll 1247 // override them or not, or get message from the compiler: 1248 // oop_since_save_marks_iterate_nv hides virtual function... 1249 #define CMS_SINCE_SAVE_MARKS_DECL(OopClosureType, nv_suffix) \ 1250 void oop_since_save_marks_iterate##nv_suffix(OopClosureType* cl); 1251 ALL_SINCE_SAVE_MARKS_CLOSURES(CMS_SINCE_SAVE_MARKS_DECL) 1252 1253 // Smart allocation XXX -- move to CFLSpace? 1254 void setNearLargestChunk(); 1255 bool isNearLargestChunk(HeapWord* addr); 1256 1257 // Get the chunk at the end of the space. Delegates to 1258 // the space. 1259 FreeChunk* find_chunk_at_end(); 1260 1261 void post_compact(); 1262 1263 // Debugging 1264 void prepare_for_verify(); 1265 void verify(); 1266 void print_statistics() PRODUCT_RETURN; 1267 1268 // Performance Counters support 1269 virtual void update_counters(); 1270 virtual void update_counters(size_t used); 1271 void initialize_performance_counters(); 1272 CollectorCounters* counters() { return collector()->counters(); } 1273 1274 // Support for parallel remark of survivor space 1275 void* get_data_recorder(int thr_num) { 1276 //Delegate to collector 1277 return collector()->get_data_recorder(thr_num); 1278 } 1279 void sample_eden_chunk() { 1280 //Delegate to collector 1281 return collector()->sample_eden_chunk(); 1282 } 1283 1284 // Printing 1285 const char* name() const; 1286 virtual const char* short_name() const { return "CMS"; } 1287 void print() const; 1288 void printOccupancy(const char* s); 1289 bool must_be_youngest() const { return false; } 1290 bool must_be_oldest() const { return true; } 1291 1292 // Resize the generation after a compacting GC. The 1293 // generation can be treated as a contiguous space 1294 // after the compaction. 1295 virtual void compute_new_size(); 1296 // Resize the generation after a non-compacting 1297 // collection. 1298 void compute_new_size_free_list(); 1299 1300 CollectionTypes debug_collection_type() { return _debug_collection_type; } 1301 void rotate_debug_collection_type(); 1302 }; 1303 1304 // 1305 // Closures of various sorts used by CMS to accomplish its work 1306 // 1307 1308 // This closure is used to do concurrent marking from the roots 1309 // following the first checkpoint. 1310 class MarkFromRootsClosure: public BitMapClosure { 1311 CMSCollector* _collector; 1312 MemRegion _span; 1313 CMSBitMap* _bitMap; 1314 CMSBitMap* _mut; 1315 CMSMarkStack* _markStack; 1316 bool _yield; 1317 int _skipBits; 1318 HeapWord* _finger; 1319 HeapWord* _threshold; 1320 DEBUG_ONLY(bool _verifying;) 1321 1322 public: 1323 MarkFromRootsClosure(CMSCollector* collector, MemRegion span, 1324 CMSBitMap* bitMap, 1325 CMSMarkStack* markStack, 1326 bool should_yield, bool verifying = false); 1327 bool do_bit(size_t offset); 1328 void reset(HeapWord* addr); 1329 inline void do_yield_check(); 1330 1331 private: 1332 void scanOopsInOop(HeapWord* ptr); 1333 void do_yield_work(); 1334 }; 1335 1336 // This closure is used to do concurrent multi-threaded 1337 // marking from the roots following the first checkpoint. 1338 // XXX This should really be a subclass of The serial version 1339 // above, but i have not had the time to refactor things cleanly. 1340 class Par_MarkFromRootsClosure: public BitMapClosure { 1341 CMSCollector* _collector; 1342 MemRegion _whole_span; 1343 MemRegion _span; 1344 CMSBitMap* _bit_map; 1345 CMSBitMap* _mut; 1346 OopTaskQueue* _work_queue; 1347 CMSMarkStack* _overflow_stack; 1348 bool _yield; 1349 int _skip_bits; 1350 HeapWord* _finger; 1351 HeapWord* _threshold; 1352 CMSConcMarkingTask* _task; 1353 public: 1354 Par_MarkFromRootsClosure(CMSConcMarkingTask* task, CMSCollector* collector, 1355 MemRegion span, 1356 CMSBitMap* bit_map, 1357 OopTaskQueue* work_queue, 1358 CMSMarkStack* overflow_stack, 1359 bool should_yield); 1360 bool do_bit(size_t offset); 1361 inline void do_yield_check(); 1362 1363 private: 1364 void scan_oops_in_oop(HeapWord* ptr); 1365 void do_yield_work(); 1366 bool get_work_from_overflow_stack(); 1367 }; 1368 1369 // The following closures are used to do certain kinds of verification of 1370 // CMS marking. 1371 class PushAndMarkVerifyClosure: public MetadataAwareOopClosure { 1372 CMSCollector* _collector; 1373 MemRegion _span; 1374 CMSBitMap* _verification_bm; 1375 CMSBitMap* _cms_bm; 1376 CMSMarkStack* _mark_stack; 1377 protected: 1378 void do_oop(oop p); 1379 template <class T> inline void do_oop_work(T *p) { 1380 oop obj = oopDesc::load_decode_heap_oop(p); 1381 do_oop(obj); 1382 } 1383 public: 1384 PushAndMarkVerifyClosure(CMSCollector* cms_collector, 1385 MemRegion span, 1386 CMSBitMap* verification_bm, 1387 CMSBitMap* cms_bm, 1388 CMSMarkStack* mark_stack); 1389 void do_oop(oop* p); 1390 void do_oop(narrowOop* p); 1391 1392 // Deal with a stack overflow condition 1393 void handle_stack_overflow(HeapWord* lost); 1394 }; 1395 1396 class MarkFromRootsVerifyClosure: public BitMapClosure { 1397 CMSCollector* _collector; 1398 MemRegion _span; 1399 CMSBitMap* _verification_bm; 1400 CMSBitMap* _cms_bm; 1401 CMSMarkStack* _mark_stack; 1402 HeapWord* _finger; 1403 PushAndMarkVerifyClosure _pam_verify_closure; 1404 public: 1405 MarkFromRootsVerifyClosure(CMSCollector* collector, MemRegion span, 1406 CMSBitMap* verification_bm, 1407 CMSBitMap* cms_bm, 1408 CMSMarkStack* mark_stack); 1409 bool do_bit(size_t offset); 1410 void reset(HeapWord* addr); 1411 }; 1412 1413 1414 // This closure is used to check that a certain set of bits is 1415 // "empty" (i.e. the bit vector doesn't have any 1-bits). 1416 class FalseBitMapClosure: public BitMapClosure { 1417 public: 1418 bool do_bit(size_t offset) { 1419 guarantee(false, "Should not have a 1 bit"); 1420 return true; 1421 } 1422 }; 1423 1424 // A version of ObjectClosure with "memory" (see _previous_address below) 1425 class UpwardsObjectClosure: public BoolObjectClosure { 1426 HeapWord* _previous_address; 1427 public: 1428 UpwardsObjectClosure() : _previous_address(NULL) { } 1429 void set_previous(HeapWord* addr) { _previous_address = addr; } 1430 HeapWord* previous() { return _previous_address; } 1431 // A return value of "true" can be used by the caller to decide 1432 // if this object's end should *NOT* be recorded in 1433 // _previous_address above. 1434 virtual bool do_object_bm(oop obj, MemRegion mr) = 0; 1435 }; 1436 1437 // This closure is used during the second checkpointing phase 1438 // to rescan the marked objects on the dirty cards in the mod 1439 // union table and the card table proper. It's invoked via 1440 // MarkFromDirtyCardsClosure below. It uses either 1441 // [Par_]MarkRefsIntoAndScanClosure (Par_ in the parallel case) 1442 // declared in genOopClosures.hpp to accomplish some of its work. 1443 // In the parallel case the bitMap is shared, so access to 1444 // it needs to be suitably synchronized for updates by embedded 1445 // closures that update it; however, this closure itself only 1446 // reads the bit_map and because it is idempotent, is immune to 1447 // reading stale values. 1448 class ScanMarkedObjectsAgainClosure: public UpwardsObjectClosure { 1449 #ifdef ASSERT 1450 CMSCollector* _collector; 1451 MemRegion _span; 1452 union { 1453 CMSMarkStack* _mark_stack; 1454 OopTaskQueue* _work_queue; 1455 }; 1456 #endif // ASSERT 1457 bool _parallel; 1458 CMSBitMap* _bit_map; 1459 union { 1460 MarkRefsIntoAndScanClosure* _scan_closure; 1461 Par_MarkRefsIntoAndScanClosure* _par_scan_closure; 1462 }; 1463 1464 public: 1465 ScanMarkedObjectsAgainClosure(CMSCollector* collector, 1466 MemRegion span, 1467 ReferenceProcessor* rp, 1468 CMSBitMap* bit_map, 1469 CMSMarkStack* mark_stack, 1470 MarkRefsIntoAndScanClosure* cl): 1471 #ifdef ASSERT 1472 _collector(collector), 1473 _span(span), 1474 _mark_stack(mark_stack), 1475 #endif // ASSERT 1476 _parallel(false), 1477 _bit_map(bit_map), 1478 _scan_closure(cl) { } 1479 1480 ScanMarkedObjectsAgainClosure(CMSCollector* collector, 1481 MemRegion span, 1482 ReferenceProcessor* rp, 1483 CMSBitMap* bit_map, 1484 OopTaskQueue* work_queue, 1485 Par_MarkRefsIntoAndScanClosure* cl): 1486 #ifdef ASSERT 1487 _collector(collector), 1488 _span(span), 1489 _work_queue(work_queue), 1490 #endif // ASSERT 1491 _parallel(true), 1492 _bit_map(bit_map), 1493 _par_scan_closure(cl) { } 1494 1495 bool do_object_b(oop obj) { 1496 guarantee(false, "Call do_object_b(oop, MemRegion) form instead"); 1497 return false; 1498 } 1499 bool do_object_bm(oop p, MemRegion mr); 1500 }; 1501 1502 // This closure is used during the second checkpointing phase 1503 // to rescan the marked objects on the dirty cards in the mod 1504 // union table and the card table proper. It invokes 1505 // ScanMarkedObjectsAgainClosure above to accomplish much of its work. 1506 // In the parallel case, the bit map is shared and requires 1507 // synchronized access. 1508 class MarkFromDirtyCardsClosure: public MemRegionClosure { 1509 CompactibleFreeListSpace* _space; 1510 ScanMarkedObjectsAgainClosure _scan_cl; 1511 size_t _num_dirty_cards; 1512 1513 public: 1514 MarkFromDirtyCardsClosure(CMSCollector* collector, 1515 MemRegion span, 1516 CompactibleFreeListSpace* space, 1517 CMSBitMap* bit_map, 1518 CMSMarkStack* mark_stack, 1519 MarkRefsIntoAndScanClosure* cl): 1520 _space(space), 1521 _num_dirty_cards(0), 1522 _scan_cl(collector, span, collector->ref_processor(), bit_map, 1523 mark_stack, cl) { } 1524 1525 MarkFromDirtyCardsClosure(CMSCollector* collector, 1526 MemRegion span, 1527 CompactibleFreeListSpace* space, 1528 CMSBitMap* bit_map, 1529 OopTaskQueue* work_queue, 1530 Par_MarkRefsIntoAndScanClosure* cl): 1531 _space(space), 1532 _num_dirty_cards(0), 1533 _scan_cl(collector, span, collector->ref_processor(), bit_map, 1534 work_queue, cl) { } 1535 1536 void do_MemRegion(MemRegion mr); 1537 void set_space(CompactibleFreeListSpace* space) { _space = space; } 1538 size_t num_dirty_cards() { return _num_dirty_cards; } 1539 }; 1540 1541 // This closure is used in the non-product build to check 1542 // that there are no MemRegions with a certain property. 1543 class FalseMemRegionClosure: public MemRegionClosure { 1544 void do_MemRegion(MemRegion mr) { 1545 guarantee(!mr.is_empty(), "Shouldn't be empty"); 1546 guarantee(false, "Should never be here"); 1547 } 1548 }; 1549 1550 // This closure is used during the precleaning phase 1551 // to "carefully" rescan marked objects on dirty cards. 1552 // It uses MarkRefsIntoAndScanClosure declared in genOopClosures.hpp 1553 // to accomplish some of its work. 1554 class ScanMarkedObjectsAgainCarefullyClosure: public ObjectClosureCareful { 1555 CMSCollector* _collector; 1556 MemRegion _span; 1557 bool _yield; 1558 Mutex* _freelistLock; 1559 CMSBitMap* _bitMap; 1560 CMSMarkStack* _markStack; 1561 MarkRefsIntoAndScanClosure* _scanningClosure; 1562 1563 public: 1564 ScanMarkedObjectsAgainCarefullyClosure(CMSCollector* collector, 1565 MemRegion span, 1566 CMSBitMap* bitMap, 1567 CMSMarkStack* markStack, 1568 MarkRefsIntoAndScanClosure* cl, 1569 bool should_yield): 1570 _collector(collector), 1571 _span(span), 1572 _yield(should_yield), 1573 _bitMap(bitMap), 1574 _markStack(markStack), 1575 _scanningClosure(cl) { 1576 } 1577 1578 void do_object(oop p) { 1579 guarantee(false, "call do_object_careful instead"); 1580 } 1581 1582 size_t do_object_careful(oop p) { 1583 guarantee(false, "Unexpected caller"); 1584 return 0; 1585 } 1586 1587 size_t do_object_careful_m(oop p, MemRegion mr); 1588 1589 void setFreelistLock(Mutex* m) { 1590 _freelistLock = m; 1591 _scanningClosure->set_freelistLock(m); 1592 } 1593 1594 private: 1595 inline bool do_yield_check(); 1596 1597 void do_yield_work(); 1598 }; 1599 1600 class SurvivorSpacePrecleanClosure: public ObjectClosureCareful { 1601 CMSCollector* _collector; 1602 MemRegion _span; 1603 bool _yield; 1604 CMSBitMap* _bit_map; 1605 CMSMarkStack* _mark_stack; 1606 PushAndMarkClosure* _scanning_closure; 1607 unsigned int _before_count; 1608 1609 public: 1610 SurvivorSpacePrecleanClosure(CMSCollector* collector, 1611 MemRegion span, 1612 CMSBitMap* bit_map, 1613 CMSMarkStack* mark_stack, 1614 PushAndMarkClosure* cl, 1615 unsigned int before_count, 1616 bool should_yield): 1617 _collector(collector), 1618 _span(span), 1619 _yield(should_yield), 1620 _bit_map(bit_map), 1621 _mark_stack(mark_stack), 1622 _scanning_closure(cl), 1623 _before_count(before_count) 1624 { } 1625 1626 void do_object(oop p) { 1627 guarantee(false, "call do_object_careful instead"); 1628 } 1629 1630 size_t do_object_careful(oop p); 1631 1632 size_t do_object_careful_m(oop p, MemRegion mr) { 1633 guarantee(false, "Unexpected caller"); 1634 return 0; 1635 } 1636 1637 private: 1638 inline void do_yield_check(); 1639 void do_yield_work(); 1640 }; 1641 1642 // This closure is used to accomplish the sweeping work 1643 // after the second checkpoint but before the concurrent reset 1644 // phase. 1645 // 1646 // Terminology 1647 // left hand chunk (LHC) - block of one or more chunks currently being 1648 // coalesced. The LHC is available for coalescing with a new chunk. 1649 // right hand chunk (RHC) - block that is currently being swept that is 1650 // free or garbage that can be coalesced with the LHC. 1651 // _inFreeRange is true if there is currently a LHC 1652 // _lastFreeRangeCoalesced is true if the LHC consists of more than one chunk. 1653 // _freeRangeInFreeLists is true if the LHC is in the free lists. 1654 // _freeFinger is the address of the current LHC 1655 class SweepClosure: public BlkClosureCareful { 1656 CMSCollector* _collector; // collector doing the work 1657 ConcurrentMarkSweepGeneration* _g; // Generation being swept 1658 CompactibleFreeListSpace* _sp; // Space being swept 1659 HeapWord* _limit;// the address at or above which the sweep should stop 1660 // because we do not expect newly garbage blocks 1661 // eligible for sweeping past that address. 1662 Mutex* _freelistLock; // Free list lock (in space) 1663 CMSBitMap* _bitMap; // Marking bit map (in 1664 // generation) 1665 bool _inFreeRange; // Indicates if we are in the 1666 // midst of a free run 1667 bool _freeRangeInFreeLists; 1668 // Often, we have just found 1669 // a free chunk and started 1670 // a new free range; we do not 1671 // eagerly remove this chunk from 1672 // the free lists unless there is 1673 // a possibility of coalescing. 1674 // When true, this flag indicates 1675 // that the _freeFinger below 1676 // points to a potentially free chunk 1677 // that may still be in the free lists 1678 bool _lastFreeRangeCoalesced; 1679 // free range contains chunks 1680 // coalesced 1681 bool _yield; 1682 // Whether sweeping should be 1683 // done with yields. For instance 1684 // when done by the foreground 1685 // collector we shouldn't yield. 1686 HeapWord* _freeFinger; // When _inFreeRange is set, the 1687 // pointer to the "left hand 1688 // chunk" 1689 size_t _freeRangeSize; 1690 // When _inFreeRange is set, this 1691 // indicates the accumulated size 1692 // of the "left hand chunk" 1693 NOT_PRODUCT( 1694 size_t _numObjectsFreed; 1695 size_t _numWordsFreed; 1696 size_t _numObjectsLive; 1697 size_t _numWordsLive; 1698 size_t _numObjectsAlreadyFree; 1699 size_t _numWordsAlreadyFree; 1700 FreeChunk* _last_fc; 1701 ) 1702 private: 1703 // Code that is common to a free chunk or garbage when 1704 // encountered during sweeping. 1705 void do_post_free_or_garbage_chunk(FreeChunk *fc, size_t chunkSize); 1706 // Process a free chunk during sweeping. 1707 void do_already_free_chunk(FreeChunk *fc); 1708 // Work method called when processing an already free or a 1709 // freshly garbage chunk to do a lookahead and possibly a 1710 // preemptive flush if crossing over _limit. 1711 void lookahead_and_flush(FreeChunk* fc, size_t chunkSize); 1712 // Process a garbage chunk during sweeping. 1713 size_t do_garbage_chunk(FreeChunk *fc); 1714 // Process a live chunk during sweeping. 1715 size_t do_live_chunk(FreeChunk* fc); 1716 1717 // Accessors. 1718 HeapWord* freeFinger() const { return _freeFinger; } 1719 void set_freeFinger(HeapWord* v) { _freeFinger = v; } 1720 bool inFreeRange() const { return _inFreeRange; } 1721 void set_inFreeRange(bool v) { _inFreeRange = v; } 1722 bool lastFreeRangeCoalesced() const { return _lastFreeRangeCoalesced; } 1723 void set_lastFreeRangeCoalesced(bool v) { _lastFreeRangeCoalesced = v; } 1724 bool freeRangeInFreeLists() const { return _freeRangeInFreeLists; } 1725 void set_freeRangeInFreeLists(bool v) { _freeRangeInFreeLists = v; } 1726 1727 // Initialize a free range. 1728 void initialize_free_range(HeapWord* freeFinger, bool freeRangeInFreeLists); 1729 // Return this chunk to the free lists. 1730 void flush_cur_free_chunk(HeapWord* chunk, size_t size); 1731 1732 // Check if we should yield and do so when necessary. 1733 inline void do_yield_check(HeapWord* addr); 1734 1735 // Yield 1736 void do_yield_work(HeapWord* addr); 1737 1738 // Debugging/Printing 1739 void print_free_block_coalesced(FreeChunk* fc) const; 1740 1741 public: 1742 SweepClosure(CMSCollector* collector, ConcurrentMarkSweepGeneration* g, 1743 CMSBitMap* bitMap, bool should_yield); 1744 ~SweepClosure() PRODUCT_RETURN; 1745 1746 size_t do_blk_careful(HeapWord* addr); 1747 void print() const { print_on(tty); } 1748 void print_on(outputStream *st) const; 1749 }; 1750 1751 // Closures related to weak references processing 1752 1753 // During CMS' weak reference processing, this is a 1754 // work-routine/closure used to complete transitive 1755 // marking of objects as live after a certain point 1756 // in which an initial set has been completely accumulated. 1757 // This closure is currently used both during the final 1758 // remark stop-world phase, as well as during the concurrent 1759 // precleaning of the discovered reference lists. 1760 class CMSDrainMarkingStackClosure: public VoidClosure { 1761 CMSCollector* _collector; 1762 MemRegion _span; 1763 CMSMarkStack* _mark_stack; 1764 CMSBitMap* _bit_map; 1765 CMSKeepAliveClosure* _keep_alive; 1766 bool _concurrent_precleaning; 1767 public: 1768 CMSDrainMarkingStackClosure(CMSCollector* collector, MemRegion span, 1769 CMSBitMap* bit_map, CMSMarkStack* mark_stack, 1770 CMSKeepAliveClosure* keep_alive, 1771 bool cpc): 1772 _collector(collector), 1773 _span(span), 1774 _bit_map(bit_map), 1775 _mark_stack(mark_stack), 1776 _keep_alive(keep_alive), 1777 _concurrent_precleaning(cpc) { 1778 assert(_concurrent_precleaning == _keep_alive->concurrent_precleaning(), 1779 "Mismatch"); 1780 } 1781 1782 void do_void(); 1783 }; 1784 1785 // A parallel version of CMSDrainMarkingStackClosure above. 1786 class CMSParDrainMarkingStackClosure: public VoidClosure { 1787 CMSCollector* _collector; 1788 MemRegion _span; 1789 OopTaskQueue* _work_queue; 1790 CMSBitMap* _bit_map; 1791 CMSInnerParMarkAndPushClosure _mark_and_push; 1792 1793 public: 1794 CMSParDrainMarkingStackClosure(CMSCollector* collector, 1795 MemRegion span, CMSBitMap* bit_map, 1796 OopTaskQueue* work_queue): 1797 _collector(collector), 1798 _span(span), 1799 _bit_map(bit_map), 1800 _work_queue(work_queue), 1801 _mark_and_push(collector, span, bit_map, work_queue) { } 1802 1803 public: 1804 void trim_queue(uint max); 1805 void do_void(); 1806 }; 1807 1808 // Allow yielding or short-circuiting of reference list 1809 // precleaning work. 1810 class CMSPrecleanRefsYieldClosure: public YieldClosure { 1811 CMSCollector* _collector; 1812 void do_yield_work(); 1813 public: 1814 CMSPrecleanRefsYieldClosure(CMSCollector* collector): 1815 _collector(collector) {} 1816 virtual bool should_return(); 1817 }; 1818 1819 1820 // Convenience class that locks free list locks for given CMS collector 1821 class FreelistLocker: public StackObj { 1822 private: 1823 CMSCollector* _collector; 1824 public: 1825 FreelistLocker(CMSCollector* collector): 1826 _collector(collector) { 1827 _collector->getFreelistLocks(); 1828 } 1829 1830 ~FreelistLocker() { 1831 _collector->releaseFreelistLocks(); 1832 } 1833 }; 1834 1835 // Mark all dead objects in a given space. 1836 class MarkDeadObjectsClosure: public BlkClosure { 1837 const CMSCollector* _collector; 1838 const CompactibleFreeListSpace* _sp; 1839 CMSBitMap* _live_bit_map; 1840 CMSBitMap* _dead_bit_map; 1841 public: 1842 MarkDeadObjectsClosure(const CMSCollector* collector, 1843 const CompactibleFreeListSpace* sp, 1844 CMSBitMap *live_bit_map, 1845 CMSBitMap *dead_bit_map) : 1846 _collector(collector), 1847 _sp(sp), 1848 _live_bit_map(live_bit_map), 1849 _dead_bit_map(dead_bit_map) {} 1850 size_t do_blk(HeapWord* addr); 1851 }; 1852 1853 class TraceCMSMemoryManagerStats : public TraceMemoryManagerStats { 1854 1855 public: 1856 TraceCMSMemoryManagerStats(CMSCollector::CollectorState phase, GCCause::Cause cause); 1857 }; 1858 1859 1860 #endif // SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_CONCURRENTMARKSWEEPGENERATION_HPP