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