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_G1_CONCURRENTMARK_HPP 26 #define SHARE_VM_GC_G1_CONCURRENTMARK_HPP 27 28 #include "classfile/javaClasses.hpp" 29 #include "gc/g1/g1RegionToSpaceMapper.hpp" 30 #include "gc/g1/heapRegionSet.hpp" 31 #include "gc/shared/cmBitMap.inline.hpp" 32 #include "gc/shared/gcId.hpp" 33 #include "gc/shared/taskqueue.hpp" 34 35 class G1CollectedHeap; 36 class CMBitMap; 37 class CMTask; 38 class ConcurrentMark; 39 typedef GenericTaskQueue<oop, mtGC> CMTaskQueue; 40 typedef GenericTaskQueueSet<CMTaskQueue, mtGC> CMTaskQueueSet; 41 42 // Closure used by CM during concurrent reference discovery 43 // and reference processing (during remarking) to determine 44 // if a particular object is alive. It is primarily used 45 // to determine if referents of discovered reference objects 46 // are alive. An instance is also embedded into the 47 // reference processor as the _is_alive_non_header field 48 class G1CMIsAliveClosure: public BoolObjectClosure { 49 G1CollectedHeap* _g1; 50 public: 51 G1CMIsAliveClosure(G1CollectedHeap* g1) : _g1(g1) { } 52 53 bool do_object_b(oop obj); 54 }; 55 56 class CMBitMapMappingChangedListener : public G1MappingChangedListener { 57 private: 58 CMBitMap* _bm; 59 public: 60 CMBitMapMappingChangedListener() : _bm(NULL) {} 61 62 void set_bitmap(CMBitMap* bm) { _bm = bm; } 63 64 virtual void on_commit(uint start_idx, size_t num_regions, bool zero_filled); 65 }; 66 67 class G1CMBitMap : public CMBitMap { 68 private: 69 CMBitMapMappingChangedListener _listener; 70 71 public: 72 G1CMBitMap() : CMBitMap(), _listener() { _listener.set_bitmap(this); } 73 static size_t compute_size(size_t heap_size); 74 // Returns the amount of bytes on the heap between two marks in the bitmap. 75 static size_t mark_distance(); 76 // Returns how many bytes (or bits) of the heap a single byte (or bit) of the 77 // mark bitmap corresponds to. This is the same as the mark distance above. 78 static size_t heap_map_factor() { 79 return mark_distance(); 80 } 81 82 // Initializes the underlying BitMap to cover the given area. 83 void initialize(MemRegion heap, G1RegionToSpaceMapper* storage); 84 85 // Clear the whole mark bitmap. 86 void clearAll(); 87 }; 88 89 // Represents a marking stack used by ConcurrentMarking in the G1 collector. 90 class CMMarkStack VALUE_OBJ_CLASS_SPEC { 91 VirtualSpace _virtual_space; // Underlying backing store for actual stack 92 ConcurrentMark* _cm; 93 oop* _base; // bottom of stack 94 jint _index; // one more than last occupied index 95 jint _capacity; // max #elements 96 jint _saved_index; // value of _index saved at start of GC 97 98 bool _overflow; 99 bool _should_expand; 100 DEBUG_ONLY(bool _drain_in_progress;) 101 DEBUG_ONLY(bool _drain_in_progress_yields;) 102 103 oop pop() { 104 if (!isEmpty()) { 105 return _base[--_index] ; 106 } 107 return NULL; 108 } 109 110 public: 111 CMMarkStack(ConcurrentMark* cm); 112 ~CMMarkStack(); 113 114 bool allocate(size_t capacity); 115 116 // Pushes the first "n" elements of "ptr_arr" on the stack. 117 // Locking impl: concurrency is allowed only with 118 // "par_push_arr" and/or "par_pop_arr" operations, which use the same 119 // locking strategy. 120 void par_push_arr(oop* ptr_arr, int n); 121 122 // If returns false, the array was empty. Otherwise, removes up to "max" 123 // elements from the stack, and transfers them to "ptr_arr" in an 124 // unspecified order. The actual number transferred is given in "n" ("n 125 // == 0" is deliberately redundant with the return value.) Locking impl: 126 // concurrency is allowed only with "par_push_arr" and/or "par_pop_arr" 127 // operations, which use the same locking strategy. 128 bool par_pop_arr(oop* ptr_arr, int max, int* n); 129 130 // Drain the mark stack, applying the given closure to all fields of 131 // objects on the stack. (That is, continue until the stack is empty, 132 // even if closure applications add entries to the stack.) The "bm" 133 // argument, if non-null, may be used to verify that only marked objects 134 // are on the mark stack. If "yield_after" is "true", then the 135 // concurrent marker performing the drain offers to yield after 136 // processing each object. If a yield occurs, stops the drain operation 137 // and returns false. Otherwise, returns true. 138 template<class OopClosureClass> 139 bool drain(OopClosureClass* cl, CMBitMap* bm, bool yield_after = false); 140 141 bool isEmpty() { return _index == 0; } 142 int maxElems() { return _capacity; } 143 144 bool overflow() { return _overflow; } 145 void clear_overflow() { _overflow = false; } 146 147 bool should_expand() const { return _should_expand; } 148 void set_should_expand(); 149 150 // Expand the stack, typically in response to an overflow condition 151 void expand(); 152 153 int size() { return _index; } 154 155 void setEmpty() { _index = 0; clear_overflow(); } 156 157 // Record the current index. 158 void note_start_of_gc(); 159 160 // Make sure that we have not added any entries to the stack during GC. 161 void note_end_of_gc(); 162 163 // Apply fn to each oop in the mark stack, up to the bound recorded 164 // via one of the above "note" functions. The mark stack must not 165 // be modified while iterating. 166 template<typename Fn> void iterate(Fn fn); 167 }; 168 169 class ForceOverflowSettings VALUE_OBJ_CLASS_SPEC { 170 private: 171 #ifndef PRODUCT 172 uintx _num_remaining; 173 bool _force; 174 #endif // !defined(PRODUCT) 175 176 public: 177 void init() PRODUCT_RETURN; 178 void update() PRODUCT_RETURN; 179 bool should_force() PRODUCT_RETURN_( return false; ); 180 }; 181 182 // this will enable a variety of different statistics per GC task 183 #define _MARKING_STATS_ 0 184 // this will enable the higher verbose levels 185 #define _MARKING_VERBOSE_ 0 186 187 #if _MARKING_STATS_ 188 #define statsOnly(statement) \ 189 do { \ 190 statement ; \ 191 } while (0) 192 #else // _MARKING_STATS_ 193 #define statsOnly(statement) \ 194 do { \ 195 } while (0) 196 #endif // _MARKING_STATS_ 197 198 typedef enum { 199 no_verbose = 0, // verbose turned off 200 stats_verbose, // only prints stats at the end of marking 201 low_verbose, // low verbose, mostly per region and per major event 202 medium_verbose, // a bit more detailed than low 203 high_verbose // per object verbose 204 } CMVerboseLevel; 205 206 class YoungList; 207 208 // Root Regions are regions that are not empty at the beginning of a 209 // marking cycle and which we might collect during an evacuation pause 210 // while the cycle is active. Given that, during evacuation pauses, we 211 // do not copy objects that are explicitly marked, what we have to do 212 // for the root regions is to scan them and mark all objects reachable 213 // from them. According to the SATB assumptions, we only need to visit 214 // each object once during marking. So, as long as we finish this scan 215 // before the next evacuation pause, we can copy the objects from the 216 // root regions without having to mark them or do anything else to them. 217 // 218 // Currently, we only support root region scanning once (at the start 219 // of the marking cycle) and the root regions are all the survivor 220 // regions populated during the initial-mark pause. 221 class CMRootRegions VALUE_OBJ_CLASS_SPEC { 222 private: 223 YoungList* _young_list; 224 ConcurrentMark* _cm; 225 226 volatile bool _scan_in_progress; 227 volatile bool _should_abort; 228 HeapRegion* volatile _next_survivor; 229 230 public: 231 CMRootRegions(); 232 // We actually do most of the initialization in this method. 233 void init(G1CollectedHeap* g1h, ConcurrentMark* cm); 234 235 // Reset the claiming / scanning of the root regions. 236 void prepare_for_scan(); 237 238 // Forces get_next() to return NULL so that the iteration aborts early. 239 void abort() { _should_abort = true; } 240 241 // Return true if the CM thread are actively scanning root regions, 242 // false otherwise. 243 bool scan_in_progress() { return _scan_in_progress; } 244 245 // Claim the next root region to scan atomically, or return NULL if 246 // all have been claimed. 247 HeapRegion* claim_next(); 248 249 // Flag that we're done with root region scanning and notify anyone 250 // who's waiting on it. If aborted is false, assume that all regions 251 // have been claimed. 252 void scan_finished(); 253 254 // If CM threads are still scanning root regions, wait until they 255 // are done. Return true if we had to wait, false otherwise. 256 bool wait_until_scan_finished(); 257 }; 258 259 class ConcurrentMarkThread; 260 261 class ConcurrentMark: public CHeapObj<mtGC> { 262 friend class CMMarkStack; 263 friend class ConcurrentMarkThread; 264 friend class CMTask; 265 friend class CMBitMapClosure; 266 friend class CMRemarkTask; 267 friend class CMConcurrentMarkingTask; 268 friend class G1ParNoteEndTask; 269 friend class CalcLiveObjectsClosure; 270 friend class G1CMRefProcTaskProxy; 271 friend class G1CMRefProcTaskExecutor; 272 friend class G1CMKeepAliveAndDrainClosure; 273 friend class G1CMDrainMarkingStackClosure; 274 275 protected: 276 ConcurrentMarkThread* _cmThread; // The thread doing the work 277 G1CollectedHeap* _g1h; // The heap 278 uint _parallel_marking_threads; // The number of marking 279 // threads we're using 280 uint _max_parallel_marking_threads; // Max number of marking 281 // threads we'll ever use 282 double _sleep_factor; // How much we have to sleep, with 283 // respect to the work we just did, to 284 // meet the marking overhead goal 285 double _marking_task_overhead; // Marking target overhead for 286 // a single task 287 288 // Same as the two above, but for the cleanup task 289 double _cleanup_sleep_factor; 290 double _cleanup_task_overhead; 291 292 FreeRegionList _cleanup_list; 293 294 // Concurrent marking support structures 295 G1CMBitMap _markBitMap1; 296 G1CMBitMap _markBitMap2; 297 CMBitMapRO* _prevMarkBitMap; // Completed mark bitmap 298 CMBitMap* _nextMarkBitMap; // Under-construction mark bitmap 299 300 BitMap _region_bm; 301 BitMap _card_bm; 302 303 // Heap bounds 304 HeapWord* _heap_start; 305 HeapWord* _heap_end; 306 307 // Root region tracking and claiming 308 CMRootRegions _root_regions; 309 310 // For gray objects 311 CMMarkStack _markStack; // Grey objects behind global finger 312 HeapWord* volatile _finger; // The global finger, region aligned, 313 // always points to the end of the 314 // last claimed region 315 316 // Marking tasks 317 uint _max_worker_id;// Maximum worker id 318 uint _active_tasks; // Task num currently active 319 CMTask** _tasks; // Task queue array (max_worker_id len) 320 CMTaskQueueSet* _task_queues; // Task queue set 321 ParallelTaskTerminator _terminator; // For termination 322 323 // Two sync barriers that are used to synchronize tasks when an 324 // overflow occurs. The algorithm is the following. All tasks enter 325 // the first one to ensure that they have all stopped manipulating 326 // the global data structures. After they exit it, they re-initialize 327 // their data structures and task 0 re-initializes the global data 328 // structures. Then, they enter the second sync barrier. This 329 // ensure, that no task starts doing work before all data 330 // structures (local and global) have been re-initialized. When they 331 // exit it, they are free to start working again. 332 WorkGangBarrierSync _first_overflow_barrier_sync; 333 WorkGangBarrierSync _second_overflow_barrier_sync; 334 335 // This is set by any task, when an overflow on the global data 336 // structures is detected 337 volatile bool _has_overflown; 338 // True: marking is concurrent, false: we're in remark 339 volatile bool _concurrent; 340 // Set at the end of a Full GC so that marking aborts 341 volatile bool _has_aborted; 342 GCId _aborted_gc_id; 343 344 // Used when remark aborts due to an overflow to indicate that 345 // another concurrent marking phase should start 346 volatile bool _restart_for_overflow; 347 348 // This is true from the very start of concurrent marking until the 349 // point when all the tasks complete their work. It is really used 350 // to determine the points between the end of concurrent marking and 351 // time of remark. 352 volatile bool _concurrent_marking_in_progress; 353 354 // Verbose level 355 CMVerboseLevel _verbose_level; 356 357 // All of these times are in ms 358 NumberSeq _init_times; 359 NumberSeq _remark_times; 360 NumberSeq _remark_mark_times; 361 NumberSeq _remark_weak_ref_times; 362 NumberSeq _cleanup_times; 363 double _total_counting_time; 364 double _total_rs_scrub_time; 365 366 double* _accum_task_vtime; // Accumulated task vtime 367 368 WorkGang* _parallel_workers; 369 370 ForceOverflowSettings _force_overflow_conc; 371 ForceOverflowSettings _force_overflow_stw; 372 373 void weakRefsWorkParallelPart(BoolObjectClosure* is_alive, bool purged_classes); 374 void weakRefsWork(bool clear_all_soft_refs); 375 376 void swapMarkBitMaps(); 377 378 // It resets the global marking data structures, as well as the 379 // task local ones; should be called during initial mark. 380 void reset(); 381 382 // Resets all the marking data structures. Called when we have to restart 383 // marking or when marking completes (via set_non_marking_state below). 384 void reset_marking_state(bool clear_overflow = true); 385 386 // We do this after we're done with marking so that the marking data 387 // structures are initialized to a sensible and predictable state. 388 void set_non_marking_state(); 389 390 // Called to indicate how many threads are currently active. 391 void set_concurrency(uint active_tasks); 392 393 // It should be called to indicate which phase we're in (concurrent 394 // mark or remark) and how many threads are currently active. 395 void set_concurrency_and_phase(uint active_tasks, bool concurrent); 396 397 // Prints all gathered CM-related statistics 398 void print_stats(); 399 400 bool cleanup_list_is_empty() { 401 return _cleanup_list.is_empty(); 402 } 403 404 // Accessor methods 405 uint parallel_marking_threads() const { return _parallel_marking_threads; } 406 uint max_parallel_marking_threads() const { return _max_parallel_marking_threads;} 407 double sleep_factor() { return _sleep_factor; } 408 double marking_task_overhead() { return _marking_task_overhead;} 409 double cleanup_sleep_factor() { return _cleanup_sleep_factor; } 410 double cleanup_task_overhead() { return _cleanup_task_overhead;} 411 412 HeapWord* finger() { return _finger; } 413 bool concurrent() { return _concurrent; } 414 uint active_tasks() { return _active_tasks; } 415 ParallelTaskTerminator* terminator() { return &_terminator; } 416 417 // It claims the next available region to be scanned by a marking 418 // task/thread. It might return NULL if the next region is empty or 419 // we have run out of regions. In the latter case, out_of_regions() 420 // determines whether we've really run out of regions or the task 421 // should call claim_region() again. This might seem a bit 422 // awkward. Originally, the code was written so that claim_region() 423 // either successfully returned with a non-empty region or there 424 // were no more regions to be claimed. The problem with this was 425 // that, in certain circumstances, it iterated over large chunks of 426 // the heap finding only empty regions and, while it was working, it 427 // was preventing the calling task to call its regular clock 428 // method. So, this way, each task will spend very little time in 429 // claim_region() and is allowed to call the regular clock method 430 // frequently. 431 HeapRegion* claim_region(uint worker_id); 432 433 // It determines whether we've run out of regions to scan. Note that 434 // the finger can point past the heap end in case the heap was expanded 435 // to satisfy an allocation without doing a GC. This is fine, because all 436 // objects in those regions will be considered live anyway because of 437 // SATB guarantees (i.e. their TAMS will be equal to bottom). 438 bool out_of_regions() { return _finger >= _heap_end; } 439 440 // Returns the task with the given id 441 CMTask* task(int id) { 442 assert(0 <= id && id < (int) _active_tasks, 443 "task id not within active bounds"); 444 return _tasks[id]; 445 } 446 447 // Returns the task queue with the given id 448 CMTaskQueue* task_queue(int id) { 449 assert(0 <= id && id < (int) _active_tasks, 450 "task queue id not within active bounds"); 451 return (CMTaskQueue*) _task_queues->queue(id); 452 } 453 454 // Returns the task queue set 455 CMTaskQueueSet* task_queues() { return _task_queues; } 456 457 // Access / manipulation of the overflow flag which is set to 458 // indicate that the global stack has overflown 459 bool has_overflown() { return _has_overflown; } 460 void set_has_overflown() { _has_overflown = true; } 461 void clear_has_overflown() { _has_overflown = false; } 462 bool restart_for_overflow() { return _restart_for_overflow; } 463 464 // Methods to enter the two overflow sync barriers 465 void enter_first_sync_barrier(uint worker_id); 466 void enter_second_sync_barrier(uint worker_id); 467 468 ForceOverflowSettings* force_overflow_conc() { 469 return &_force_overflow_conc; 470 } 471 472 ForceOverflowSettings* force_overflow_stw() { 473 return &_force_overflow_stw; 474 } 475 476 ForceOverflowSettings* force_overflow() { 477 if (concurrent()) { 478 return force_overflow_conc(); 479 } else { 480 return force_overflow_stw(); 481 } 482 } 483 484 // Live Data Counting data structures... 485 // These data structures are initialized at the start of 486 // marking. They are written to while marking is active. 487 // They are aggregated during remark; the aggregated values 488 // are then used to populate the _region_bm, _card_bm, and 489 // the total live bytes, which are then subsequently updated 490 // during cleanup. 491 492 // An array of bitmaps (one bit map per task). Each bitmap 493 // is used to record the cards spanned by the live objects 494 // marked by that task/worker. 495 BitMap* _count_card_bitmaps; 496 497 // Used to record the number of marked live bytes 498 // (for each region, by worker thread). 499 size_t** _count_marked_bytes; 500 501 // Card index of the bottom of the G1 heap. Used for biasing indices into 502 // the card bitmaps. 503 intptr_t _heap_bottom_card_num; 504 505 // Set to true when initialization is complete 506 bool _completed_initialization; 507 508 public: 509 // Manipulation of the global mark stack. 510 // The push and pop operations are used by tasks for transfers 511 // between task-local queues and the global mark stack, and use 512 // locking for concurrency safety. 513 bool mark_stack_push(oop* arr, int n) { 514 _markStack.par_push_arr(arr, n); 515 if (_markStack.overflow()) { 516 set_has_overflown(); 517 return false; 518 } 519 return true; 520 } 521 void mark_stack_pop(oop* arr, int max, int* n) { 522 _markStack.par_pop_arr(arr, max, n); 523 } 524 size_t mark_stack_size() { return _markStack.size(); } 525 size_t partial_mark_stack_size_target() { return _markStack.maxElems()/3; } 526 bool mark_stack_overflow() { return _markStack.overflow(); } 527 bool mark_stack_empty() { return _markStack.isEmpty(); } 528 529 CMRootRegions* root_regions() { return &_root_regions; } 530 531 bool concurrent_marking_in_progress() { 532 return _concurrent_marking_in_progress; 533 } 534 void set_concurrent_marking_in_progress() { 535 _concurrent_marking_in_progress = true; 536 } 537 void clear_concurrent_marking_in_progress() { 538 _concurrent_marking_in_progress = false; 539 } 540 541 void update_accum_task_vtime(int i, double vtime) { 542 _accum_task_vtime[i] += vtime; 543 } 544 545 double all_task_accum_vtime() { 546 double ret = 0.0; 547 for (uint i = 0; i < _max_worker_id; ++i) 548 ret += _accum_task_vtime[i]; 549 return ret; 550 } 551 552 // Attempts to steal an object from the task queues of other tasks 553 bool try_stealing(uint worker_id, int* hash_seed, oop& obj); 554 555 ConcurrentMark(G1CollectedHeap* g1h, 556 G1RegionToSpaceMapper* prev_bitmap_storage, 557 G1RegionToSpaceMapper* next_bitmap_storage); 558 ~ConcurrentMark(); 559 560 ConcurrentMarkThread* cmThread() { return _cmThread; } 561 562 CMBitMapRO* prevMarkBitMap() const { return _prevMarkBitMap; } 563 CMBitMap* nextMarkBitMap() const { return _nextMarkBitMap; } 564 565 // Returns the number of GC threads to be used in a concurrent 566 // phase based on the number of GC threads being used in a STW 567 // phase. 568 uint scale_parallel_threads(uint n_par_threads); 569 570 // Calculates the number of GC threads to be used in a concurrent phase. 571 uint calc_parallel_marking_threads(); 572 573 // The following three are interaction between CM and 574 // G1CollectedHeap 575 576 // This notifies CM that a root during initial-mark needs to be 577 // grayed. It is MT-safe. word_size is the size of the object in 578 // words. It is passed explicitly as sometimes we cannot calculate 579 // it from the given object because it might be in an inconsistent 580 // state (e.g., in to-space and being copied). So the caller is 581 // responsible for dealing with this issue (e.g., get the size from 582 // the from-space image when the to-space image might be 583 // inconsistent) and always passing the size. hr is the region that 584 // contains the object and it's passed optionally from callers who 585 // might already have it (no point in recalculating it). 586 inline void grayRoot(oop obj, 587 size_t word_size, 588 uint worker_id, 589 HeapRegion* hr = NULL); 590 591 // It iterates over the heap and for each object it comes across it 592 // will dump the contents of its reference fields, as well as 593 // liveness information for the object and its referents. The dump 594 // will be written to a file with the following name: 595 // G1PrintReachableBaseFile + "." + str. 596 // vo decides whether the prev (vo == UsePrevMarking), the next 597 // (vo == UseNextMarking) marking information, or the mark word 598 // (vo == UseMarkWord) will be used to determine the liveness of 599 // each object / referent. 600 // If all is true, all objects in the heap will be dumped, otherwise 601 // only the live ones. In the dump the following symbols / breviations 602 // are used: 603 // M : an explicitly live object (its bitmap bit is set) 604 // > : an implicitly live object (over tams) 605 // O : an object outside the G1 heap (typically: in the perm gen) 606 // NOT : a reference field whose referent is not live 607 // AND MARKED : indicates that an object is both explicitly and 608 // implicitly live (it should be one or the other, not both) 609 void print_reachable(const char* str, 610 VerifyOption vo, 611 bool all) PRODUCT_RETURN; 612 613 // Clear the next marking bitmap (will be called concurrently). 614 void clearNextBitmap(); 615 616 // Return whether the next mark bitmap has no marks set. To be used for assertions 617 // only. Will not yield to pause requests. 618 bool nextMarkBitmapIsClear(); 619 620 // These two do the work that needs to be done before and after the 621 // initial root checkpoint. Since this checkpoint can be done at two 622 // different points (i.e. an explicit pause or piggy-backed on a 623 // young collection), then it's nice to be able to easily share the 624 // pre/post code. It might be the case that we can put everything in 625 // the post method. TP 626 void checkpointRootsInitialPre(); 627 void checkpointRootsInitialPost(); 628 629 // Scan all the root regions and mark everything reachable from 630 // them. 631 void scanRootRegions(); 632 633 // Scan a single root region and mark everything reachable from it. 634 void scanRootRegion(HeapRegion* hr, uint worker_id); 635 636 // Do concurrent phase of marking, to a tentative transitive closure. 637 void markFromRoots(); 638 639 void checkpointRootsFinal(bool clear_all_soft_refs); 640 void checkpointRootsFinalWork(); 641 void cleanup(); 642 void completeCleanup(); 643 644 // Mark in the previous bitmap. NB: this is usually read-only, so use 645 // this carefully! 646 inline void markPrev(oop p); 647 648 // Clears marks for all objects in the given range, for the prev or 649 // next bitmaps. NB: the previous bitmap is usually 650 // read-only, so use this carefully! 651 void clearRangePrevBitmap(MemRegion mr); 652 void clearRangeNextBitmap(MemRegion mr); 653 654 // Notify data structures that a GC has started. 655 void note_start_of_gc() { 656 _markStack.note_start_of_gc(); 657 } 658 659 // Notify data structures that a GC is finished. 660 void note_end_of_gc() { 661 _markStack.note_end_of_gc(); 662 } 663 664 // Verify that there are no CSet oops on the stacks (taskqueues / 665 // global mark stack) and fingers (global / per-task). 666 // If marking is not in progress, it's a no-op. 667 void verify_no_cset_oops() PRODUCT_RETURN; 668 669 bool isPrevMarked(oop p) const { 670 assert(p != NULL && p->is_oop(), "expected an oop"); 671 HeapWord* addr = (HeapWord*)p; 672 assert(addr >= _prevMarkBitMap->startWord() || 673 addr < _prevMarkBitMap->endWord(), "in a region"); 674 675 return _prevMarkBitMap->isMarked(addr); 676 } 677 678 inline bool do_yield_check(uint worker_i = 0); 679 680 // Called to abort the marking cycle after a Full GC takes place. 681 void abort(); 682 683 bool has_aborted() { return _has_aborted; } 684 685 const GCId& concurrent_gc_id(); 686 687 // This prints the global/local fingers. It is used for debugging. 688 NOT_PRODUCT(void print_finger();) 689 690 void print_summary_info(); 691 692 void print_worker_threads_on(outputStream* st) const; 693 694 void print_on_error(outputStream* st) const; 695 696 // The following indicate whether a given verbose level has been 697 // set. Notice that anything above stats is conditional to 698 // _MARKING_VERBOSE_ having been set to 1 699 bool verbose_stats() { 700 return _verbose_level >= stats_verbose; 701 } 702 bool verbose_low() { 703 return _MARKING_VERBOSE_ && _verbose_level >= low_verbose; 704 } 705 bool verbose_medium() { 706 return _MARKING_VERBOSE_ && _verbose_level >= medium_verbose; 707 } 708 bool verbose_high() { 709 return _MARKING_VERBOSE_ && _verbose_level >= high_verbose; 710 } 711 712 // Liveness counting 713 714 // Utility routine to set an exclusive range of cards on the given 715 // card liveness bitmap 716 inline void set_card_bitmap_range(BitMap* card_bm, 717 BitMap::idx_t start_idx, 718 BitMap::idx_t end_idx, 719 bool is_par); 720 721 // Returns the card number of the bottom of the G1 heap. 722 // Used in biasing indices into accounting card bitmaps. 723 intptr_t heap_bottom_card_num() const { 724 return _heap_bottom_card_num; 725 } 726 727 // Returns the card bitmap for a given task or worker id. 728 BitMap* count_card_bitmap_for(uint worker_id) { 729 assert(worker_id < _max_worker_id, "oob"); 730 assert(_count_card_bitmaps != NULL, "uninitialized"); 731 BitMap* task_card_bm = &_count_card_bitmaps[worker_id]; 732 assert(task_card_bm->size() == _card_bm.size(), "size mismatch"); 733 return task_card_bm; 734 } 735 736 // Returns the array containing the marked bytes for each region, 737 // for the given worker or task id. 738 size_t* count_marked_bytes_array_for(uint worker_id) { 739 assert(worker_id < _max_worker_id, "oob"); 740 assert(_count_marked_bytes != NULL, "uninitialized"); 741 size_t* marked_bytes_array = _count_marked_bytes[worker_id]; 742 assert(marked_bytes_array != NULL, "uninitialized"); 743 return marked_bytes_array; 744 } 745 746 // Returns the index in the liveness accounting card table bitmap 747 // for the given address 748 inline BitMap::idx_t card_bitmap_index_for(HeapWord* addr); 749 750 // Counts the size of the given memory region in the the given 751 // marked_bytes array slot for the given HeapRegion. 752 // Sets the bits in the given card bitmap that are associated with the 753 // cards that are spanned by the memory region. 754 inline void count_region(MemRegion mr, 755 HeapRegion* hr, 756 size_t* marked_bytes_array, 757 BitMap* task_card_bm); 758 759 // Counts the given memory region in the task/worker counting 760 // data structures for the given worker id. 761 inline void count_region(MemRegion mr, HeapRegion* hr, uint worker_id); 762 763 // Counts the given object in the given task/worker counting 764 // data structures. 765 inline void count_object(oop obj, 766 HeapRegion* hr, 767 size_t* marked_bytes_array, 768 BitMap* task_card_bm); 769 770 // Attempts to mark the given object and, if successful, counts 771 // the object in the given task/worker counting structures. 772 inline bool par_mark_and_count(oop obj, 773 HeapRegion* hr, 774 size_t* marked_bytes_array, 775 BitMap* task_card_bm); 776 777 // Attempts to mark the given object and, if successful, counts 778 // the object in the task/worker counting structures for the 779 // given worker id. 780 inline bool par_mark_and_count(oop obj, 781 size_t word_size, 782 HeapRegion* hr, 783 uint worker_id); 784 785 // Returns true if initialization was successfully completed. 786 bool completed_initialization() const { 787 return _completed_initialization; 788 } 789 790 protected: 791 // Clear all the per-task bitmaps and arrays used to store the 792 // counting data. 793 void clear_all_count_data(); 794 795 // Aggregates the counting data for each worker/task 796 // that was constructed while marking. Also sets 797 // the amount of marked bytes for each region and 798 // the top at concurrent mark count. 799 void aggregate_count_data(); 800 801 // Verification routine 802 void verify_count_data(); 803 }; 804 805 // A class representing a marking task. 806 class CMTask : public TerminatorTerminator { 807 private: 808 enum PrivateConstants { 809 // the regular clock call is called once the scanned words reaches 810 // this limit 811 words_scanned_period = 12*1024, 812 // the regular clock call is called once the number of visited 813 // references reaches this limit 814 refs_reached_period = 384, 815 // initial value for the hash seed, used in the work stealing code 816 init_hash_seed = 17, 817 // how many entries will be transferred between global stack and 818 // local queues 819 global_stack_transfer_size = 16 820 }; 821 822 uint _worker_id; 823 G1CollectedHeap* _g1h; 824 ConcurrentMark* _cm; 825 CMBitMap* _nextMarkBitMap; 826 // the task queue of this task 827 CMTaskQueue* _task_queue; 828 private: 829 // the task queue set---needed for stealing 830 CMTaskQueueSet* _task_queues; 831 // indicates whether the task has been claimed---this is only for 832 // debugging purposes 833 bool _claimed; 834 835 // number of calls to this task 836 int _calls; 837 838 // when the virtual timer reaches this time, the marking step should 839 // exit 840 double _time_target_ms; 841 // the start time of the current marking step 842 double _start_time_ms; 843 844 // the oop closure used for iterations over oops 845 G1CMOopClosure* _cm_oop_closure; 846 847 // the region this task is scanning, NULL if we're not scanning any 848 HeapRegion* _curr_region; 849 // the local finger of this task, NULL if we're not scanning a region 850 HeapWord* _finger; 851 // limit of the region this task is scanning, NULL if we're not scanning one 852 HeapWord* _region_limit; 853 854 // the number of words this task has scanned 855 size_t _words_scanned; 856 // When _words_scanned reaches this limit, the regular clock is 857 // called. Notice that this might be decreased under certain 858 // circumstances (i.e. when we believe that we did an expensive 859 // operation). 860 size_t _words_scanned_limit; 861 // the initial value of _words_scanned_limit (i.e. what it was 862 // before it was decreased). 863 size_t _real_words_scanned_limit; 864 865 // the number of references this task has visited 866 size_t _refs_reached; 867 // When _refs_reached reaches this limit, the regular clock is 868 // called. Notice this this might be decreased under certain 869 // circumstances (i.e. when we believe that we did an expensive 870 // operation). 871 size_t _refs_reached_limit; 872 // the initial value of _refs_reached_limit (i.e. what it was before 873 // it was decreased). 874 size_t _real_refs_reached_limit; 875 876 // used by the work stealing stuff 877 int _hash_seed; 878 // if this is true, then the task has aborted for some reason 879 bool _has_aborted; 880 // set when the task aborts because it has met its time quota 881 bool _has_timed_out; 882 // true when we're draining SATB buffers; this avoids the task 883 // aborting due to SATB buffers being available (as we're already 884 // dealing with them) 885 bool _draining_satb_buffers; 886 887 // number sequence of past step times 888 NumberSeq _step_times_ms; 889 // elapsed time of this task 890 double _elapsed_time_ms; 891 // termination time of this task 892 double _termination_time_ms; 893 // when this task got into the termination protocol 894 double _termination_start_time_ms; 895 896 // true when the task is during a concurrent phase, false when it is 897 // in the remark phase (so, in the latter case, we do not have to 898 // check all the things that we have to check during the concurrent 899 // phase, i.e. SATB buffer availability...) 900 bool _concurrent; 901 902 TruncatedSeq _marking_step_diffs_ms; 903 904 // Counting data structures. Embedding the task's marked_bytes_array 905 // and card bitmap into the actual task saves having to go through 906 // the ConcurrentMark object. 907 size_t* _marked_bytes_array; 908 BitMap* _card_bm; 909 910 // LOTS of statistics related with this task 911 #if _MARKING_STATS_ 912 NumberSeq _all_clock_intervals_ms; 913 double _interval_start_time_ms; 914 915 size_t _aborted; 916 size_t _aborted_overflow; 917 size_t _aborted_cm_aborted; 918 size_t _aborted_yield; 919 size_t _aborted_timed_out; 920 size_t _aborted_satb; 921 size_t _aborted_termination; 922 923 size_t _steal_attempts; 924 size_t _steals; 925 926 size_t _clock_due_to_marking; 927 size_t _clock_due_to_scanning; 928 929 size_t _local_pushes; 930 size_t _local_pops; 931 size_t _local_max_size; 932 size_t _objs_scanned; 933 934 size_t _global_pushes; 935 size_t _global_pops; 936 size_t _global_max_size; 937 938 size_t _global_transfers_to; 939 size_t _global_transfers_from; 940 941 size_t _regions_claimed; 942 size_t _objs_found_on_bitmap; 943 944 size_t _satb_buffers_processed; 945 #endif // _MARKING_STATS_ 946 947 // it updates the local fields after this task has claimed 948 // a new region to scan 949 void setup_for_region(HeapRegion* hr); 950 // it brings up-to-date the limit of the region 951 void update_region_limit(); 952 953 // called when either the words scanned or the refs visited limit 954 // has been reached 955 void reached_limit(); 956 // recalculates the words scanned and refs visited limits 957 void recalculate_limits(); 958 // decreases the words scanned and refs visited limits when we reach 959 // an expensive operation 960 void decrease_limits(); 961 // it checks whether the words scanned or refs visited reached their 962 // respective limit and calls reached_limit() if they have 963 void check_limits() { 964 if (_words_scanned >= _words_scanned_limit || 965 _refs_reached >= _refs_reached_limit) { 966 reached_limit(); 967 } 968 } 969 // this is supposed to be called regularly during a marking step as 970 // it checks a bunch of conditions that might cause the marking step 971 // to abort 972 void regular_clock_call(); 973 bool concurrent() { return _concurrent; } 974 975 // Test whether obj might have already been passed over by the 976 // mark bitmap scan, and so needs to be pushed onto the mark stack. 977 bool is_below_finger(oop obj, HeapWord* global_finger) const; 978 979 template<bool scan> void process_grey_object(oop obj); 980 981 public: 982 // It resets the task; it should be called right at the beginning of 983 // a marking phase. 984 void reset(CMBitMap* _nextMarkBitMap); 985 // it clears all the fields that correspond to a claimed region. 986 void clear_region_fields(); 987 988 void set_concurrent(bool concurrent) { _concurrent = concurrent; } 989 990 // The main method of this class which performs a marking step 991 // trying not to exceed the given duration. However, it might exit 992 // prematurely, according to some conditions (i.e. SATB buffers are 993 // available for processing). 994 void do_marking_step(double target_ms, 995 bool do_termination, 996 bool is_serial); 997 998 // These two calls start and stop the timer 999 void record_start_time() { 1000 _elapsed_time_ms = os::elapsedTime() * 1000.0; 1001 } 1002 void record_end_time() { 1003 _elapsed_time_ms = os::elapsedTime() * 1000.0 - _elapsed_time_ms; 1004 } 1005 1006 // returns the worker ID associated with this task. 1007 uint worker_id() { return _worker_id; } 1008 1009 // From TerminatorTerminator. It determines whether this task should 1010 // exit the termination protocol after it's entered it. 1011 virtual bool should_exit_termination(); 1012 1013 // Resets the local region fields after a task has finished scanning a 1014 // region; or when they have become stale as a result of the region 1015 // being evacuated. 1016 void giveup_current_region(); 1017 1018 HeapWord* finger() { return _finger; } 1019 1020 bool has_aborted() { return _has_aborted; } 1021 void set_has_aborted() { _has_aborted = true; } 1022 void clear_has_aborted() { _has_aborted = false; } 1023 bool has_timed_out() { return _has_timed_out; } 1024 bool claimed() { return _claimed; } 1025 1026 void set_cm_oop_closure(G1CMOopClosure* cm_oop_closure); 1027 1028 // Increment the number of references this task has visited. 1029 void increment_refs_reached() { ++_refs_reached; } 1030 1031 // Grey the object by marking it. If not already marked, push it on 1032 // the local queue if below the finger. 1033 // Precondition: obj is in region. 1034 // Precondition: obj is below region's NTAMS. 1035 inline void make_reference_grey(oop obj, HeapRegion* region); 1036 1037 // Grey the object (by calling make_grey_reference) if required, 1038 // e.g. obj is below its containing region's NTAMS. 1039 // Precondition: obj is a valid heap object. 1040 inline void deal_with_reference(oop obj); 1041 1042 // It scans an object and visits its children. 1043 inline void scan_object(oop obj); 1044 1045 // It pushes an object on the local queue. 1046 inline void push(oop obj); 1047 1048 // These two move entries to/from the global stack. 1049 void move_entries_to_global_stack(); 1050 void get_entries_from_global_stack(); 1051 1052 // It pops and scans objects from the local queue. If partially is 1053 // true, then it stops when the queue size is of a given limit. If 1054 // partially is false, then it stops when the queue is empty. 1055 void drain_local_queue(bool partially); 1056 // It moves entries from the global stack to the local queue and 1057 // drains the local queue. If partially is true, then it stops when 1058 // both the global stack and the local queue reach a given size. If 1059 // partially if false, it tries to empty them totally. 1060 void drain_global_stack(bool partially); 1061 // It keeps picking SATB buffers and processing them until no SATB 1062 // buffers are available. 1063 void drain_satb_buffers(); 1064 1065 // moves the local finger to a new location 1066 inline void move_finger_to(HeapWord* new_finger) { 1067 assert(new_finger >= _finger && new_finger < _region_limit, "invariant"); 1068 _finger = new_finger; 1069 } 1070 1071 CMTask(uint worker_id, 1072 ConcurrentMark *cm, 1073 size_t* marked_bytes, 1074 BitMap* card_bm, 1075 CMTaskQueue* task_queue, 1076 CMTaskQueueSet* task_queues); 1077 1078 // it prints statistics associated with this task 1079 void print_stats(); 1080 1081 #if _MARKING_STATS_ 1082 void increase_objs_found_on_bitmap() { ++_objs_found_on_bitmap; } 1083 #endif // _MARKING_STATS_ 1084 }; 1085 1086 // Class that's used to to print out per-region liveness 1087 // information. It's currently used at the end of marking and also 1088 // after we sort the old regions at the end of the cleanup operation. 1089 class G1PrintRegionLivenessInfoClosure: public HeapRegionClosure { 1090 private: 1091 outputStream* _out; 1092 1093 // Accumulators for these values. 1094 size_t _total_used_bytes; 1095 size_t _total_capacity_bytes; 1096 size_t _total_prev_live_bytes; 1097 size_t _total_next_live_bytes; 1098 1099 // These are set up when we come across a "stars humongous" region 1100 // (as this is where most of this information is stored, not in the 1101 // subsequent "continues humongous" regions). After that, for every 1102 // region in a given humongous region series we deduce the right 1103 // values for it by simply subtracting the appropriate amount from 1104 // these fields. All these values should reach 0 after we've visited 1105 // the last region in the series. 1106 size_t _hum_used_bytes; 1107 size_t _hum_capacity_bytes; 1108 size_t _hum_prev_live_bytes; 1109 size_t _hum_next_live_bytes; 1110 1111 // Accumulator for the remembered set size 1112 size_t _total_remset_bytes; 1113 1114 // Accumulator for strong code roots memory size 1115 size_t _total_strong_code_roots_bytes; 1116 1117 static double perc(size_t val, size_t total) { 1118 if (total == 0) { 1119 return 0.0; 1120 } else { 1121 return 100.0 * ((double) val / (double) total); 1122 } 1123 } 1124 1125 static double bytes_to_mb(size_t val) { 1126 return (double) val / (double) M; 1127 } 1128 1129 // See the .cpp file. 1130 size_t get_hum_bytes(size_t* hum_bytes); 1131 void get_hum_bytes(size_t* used_bytes, size_t* capacity_bytes, 1132 size_t* prev_live_bytes, size_t* next_live_bytes); 1133 1134 public: 1135 // The header and footer are printed in the constructor and 1136 // destructor respectively. 1137 G1PrintRegionLivenessInfoClosure(outputStream* out, const char* phase_name); 1138 virtual bool doHeapRegion(HeapRegion* r); 1139 ~G1PrintRegionLivenessInfoClosure(); 1140 }; 1141 1142 #endif // SHARE_VM_GC_G1_CONCURRENTMARK_HPP