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