1 /* 2 * Copyright (c) 2001, 2016, 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_G1CONCURRENTMARK_HPP 26 #define SHARE_VM_GC_G1_G1CONCURRENTMARK_HPP 27 28 #include "classfile/javaClasses.hpp" 29 #include "gc/g1/g1ConcurrentMarkObjArrayProcessor.hpp" 30 #include "gc/g1/g1RegionToSpaceMapper.hpp" 31 #include "gc/g1/heapRegionSet.hpp" 32 #include "gc/shared/taskqueue.hpp" 33 34 class G1CollectedHeap; 35 class G1CMBitMap; 36 class G1CMTask; 37 class G1ConcurrentMark; 38 class ConcurrentGCTimer; 39 class G1OldTracer; 40 class G1SurvivorRegions; 41 typedef GenericTaskQueue<oop, mtGC> G1CMTaskQueue; 42 typedef GenericTaskQueueSet<G1CMTaskQueue, mtGC> G1CMTaskQueueSet; 43 44 // Closure used by CM during concurrent reference discovery 45 // and reference processing (during remarking) to determine 46 // if a particular object is alive. It is primarily used 47 // to determine if referents of discovered reference objects 48 // are alive. An instance is also embedded into the 49 // reference processor as the _is_alive_non_header field 50 class G1CMIsAliveClosure: public BoolObjectClosure { 51 G1CollectedHeap* _g1; 52 public: 53 G1CMIsAliveClosure(G1CollectedHeap* g1) : _g1(g1) { } 54 55 bool do_object_b(oop obj); 56 }; 57 58 // A generic CM bit map. This is essentially a wrapper around the BitMap 59 // class, with one bit per (1<<_shifter) HeapWords. 60 61 class G1CMBitMapRO VALUE_OBJ_CLASS_SPEC { 62 protected: 63 HeapWord* _bmStartWord; // base address of range covered by map 64 size_t _bmWordSize; // map size (in #HeapWords covered) 65 const int _shifter; // map to char or bit 66 BitMapView _bm; // the bit map itself 67 68 public: 69 // constructor 70 G1CMBitMapRO(int shifter); 71 72 // inquiries 73 HeapWord* startWord() const { return _bmStartWord; } 74 // the following is one past the last word in space 75 HeapWord* endWord() const { return _bmStartWord + _bmWordSize; } 76 77 // read marks 78 79 bool isMarked(HeapWord* addr) const { 80 assert(_bmStartWord <= addr && addr < (_bmStartWord + _bmWordSize), 81 "outside underlying space?"); 82 return _bm.at(heapWordToOffset(addr)); 83 } 84 85 // iteration 86 inline bool iterate(BitMapClosure* cl, MemRegion mr); 87 88 // Return the address corresponding to the next marked bit at or after 89 // "addr", and before "limit", if "limit" is non-NULL. If there is no 90 // such bit, returns "limit" if that is non-NULL, or else "endWord()". 91 HeapWord* getNextMarkedWordAddress(const HeapWord* addr, 92 const HeapWord* limit = NULL) const; 93 94 // conversion utilities 95 HeapWord* offsetToHeapWord(size_t offset) const { 96 return _bmStartWord + (offset << _shifter); 97 } 98 size_t heapWordToOffset(const HeapWord* addr) const { 99 return pointer_delta(addr, _bmStartWord) >> _shifter; 100 } 101 102 // The argument addr should be the start address of a valid object 103 inline HeapWord* nextObject(HeapWord* addr); 104 105 void print_on_error(outputStream* st, const char* prefix) const; 106 107 // debugging 108 NOT_PRODUCT(bool covers(MemRegion rs) const;) 109 }; 110 111 class G1CMBitMapMappingChangedListener : public G1MappingChangedListener { 112 private: 113 G1CMBitMap* _bm; 114 public: 115 G1CMBitMapMappingChangedListener() : _bm(NULL) {} 116 117 void set_bitmap(G1CMBitMap* bm) { _bm = bm; } 118 119 virtual void on_commit(uint start_idx, size_t num_regions, bool zero_filled); 120 }; 121 122 class G1CMBitMap : public G1CMBitMapRO { 123 private: 124 G1CMBitMapMappingChangedListener _listener; 125 126 public: 127 static size_t compute_size(size_t heap_size); 128 // Returns the amount of bytes on the heap between two marks in the bitmap. 129 static size_t mark_distance(); 130 // Returns how many bytes (or bits) of the heap a single byte (or bit) of the 131 // mark bitmap corresponds to. This is the same as the mark distance above. 132 static size_t heap_map_factor() { 133 return mark_distance(); 134 } 135 136 G1CMBitMap() : G1CMBitMapRO(LogMinObjAlignment), _listener() { _listener.set_bitmap(this); } 137 138 // Initializes the underlying BitMap to cover the given area. 139 void initialize(MemRegion heap, G1RegionToSpaceMapper* storage); 140 141 // Write marks. 142 inline void mark(HeapWord* addr); 143 inline void clear(HeapWord* addr); 144 inline bool parMark(HeapWord* addr); 145 146 void clear_range(MemRegion mr); 147 }; 148 149 // Represents the overflow mark stack used by concurrent marking. 150 // 151 // Stores oops in a huge buffer in virtual memory that is always fully committed. 152 // Resizing may only happen during a STW pause when the stack is empty. 153 // 154 // Memory is allocated on a "chunk" basis, i.e. a set of oops. For this, the mark 155 // stack memory is split into evenly sized chunks of oops. Users can only 156 // add or remove entries on that basis. 157 // Chunks are filled in increasing address order. Not completely filled chunks 158 // have a NULL element as a terminating element. 159 // 160 // Every chunk has a header containing a single pointer element used for memory 161 // management. This wastes some space, but is negligible (< .1% with current sizing). 162 // 163 // Memory management is done using a mix of tracking a high water-mark indicating 164 // that all chunks at a lower address are valid chunks, and a singly linked free 165 // list connecting all empty chunks. 166 class G1CMMarkStack VALUE_OBJ_CLASS_SPEC { 167 public: 168 // Number of oops that can fit in a single chunk. 169 static const size_t OopsPerChunk = 1024 - 1 /* One reference for the next pointer */; 170 private: 171 struct OopChunk { 172 OopChunk* next; 173 oop data[OopsPerChunk]; 174 }; 175 176 size_t _max_chunk_capacity; // Maximum number of OopChunk elements on the stack. 177 178 OopChunk* _base; // Bottom address of allocated memory area. 179 size_t _chunk_capacity; // Current maximum number of OopChunk elements. 180 181 char _pad0[DEFAULT_CACHE_LINE_SIZE]; 182 OopChunk* volatile _free_list; // Linked list of free chunks that can be allocated by users. 183 char _pad1[DEFAULT_CACHE_LINE_SIZE - sizeof(OopChunk*)]; 184 OopChunk* volatile _chunk_list; // List of chunks currently containing data. 185 volatile size_t _chunks_in_chunk_list; 186 char _pad2[DEFAULT_CACHE_LINE_SIZE - sizeof(OopChunk*) - sizeof(size_t)]; 187 188 volatile size_t _hwm; // High water mark within the reserved space. 189 char _pad4[DEFAULT_CACHE_LINE_SIZE - sizeof(size_t)]; 190 191 // Allocate a new chunk from the reserved memory, using the high water mark. Returns 192 // NULL if out of memory. 193 OopChunk* allocate_new_chunk(); 194 195 volatile bool _out_of_memory; 196 197 // Atomically add the given chunk to the list. 198 void add_chunk_to_list(OopChunk* volatile* list, OopChunk* elem); 199 // Atomically remove and return a chunk from the given list. Returns NULL if the 200 // list is empty. 201 OopChunk* remove_chunk_from_list(OopChunk* volatile* list); 202 203 void add_chunk_to_chunk_list(OopChunk* elem); 204 void add_chunk_to_free_list(OopChunk* elem); 205 206 OopChunk* remove_chunk_from_chunk_list(); 207 OopChunk* remove_chunk_from_free_list(); 208 209 bool _should_expand; 210 211 // Resizes the mark stack to the given new capacity. Releases any previous 212 // memory if successful. 213 bool resize(size_t new_capacity); 214 215 public: 216 G1CMMarkStack(); 217 ~G1CMMarkStack(); 218 219 // Alignment and minimum capacity of this mark stack in number of oops. 220 static size_t capacity_alignment(); 221 222 // Allocate and initialize the mark stack with the given number of oops. 223 bool initialize(size_t initial_capacity, size_t max_capacity); 224 225 // Pushes the given buffer containing at most OopsPerChunk elements on the mark 226 // stack. If less than OopsPerChunk elements are to be pushed, the array must 227 // be terminated with a NULL. 228 // Returns whether the buffer contents were successfully pushed to the global mark 229 // stack. 230 bool par_push_chunk(oop* buffer); 231 232 // Pops a chunk from this mark stack, copying them into the given buffer. This 233 // chunk may contain up to OopsPerChunk elements. If there are less, the last 234 // element in the array is a NULL pointer. 235 bool par_pop_chunk(oop* buffer); 236 237 // Return whether the chunk list is empty. Racy due to unsynchronized access to 238 // _chunk_list. 239 bool is_empty() const { return _chunk_list == NULL; } 240 241 size_t capacity() const { return _chunk_capacity; } 242 243 bool is_out_of_memory() const { return _out_of_memory; } 244 void clear_out_of_memory() { _out_of_memory = false; } 245 246 bool should_expand() const { return _should_expand; } 247 void set_should_expand(bool value) { _should_expand = value; } 248 249 // Expand the stack, typically in response to an overflow condition 250 void expand(); 251 252 // Return the approximate number of oops on this mark stack. Racy due to 253 // unsynchronized access to _chunks_in_chunk_list. 254 size_t size() const { return _chunks_in_chunk_list * OopsPerChunk; } 255 256 void set_empty(); 257 258 // Apply Fn to every oop on the mark stack. The mark stack must not 259 // be modified while iterating. 260 template<typename Fn> void iterate(Fn fn) const PRODUCT_RETURN; 261 }; 262 263 // Root Regions are regions that are not empty at the beginning of a 264 // marking cycle and which we might collect during an evacuation pause 265 // while the cycle is active. Given that, during evacuation pauses, we 266 // do not copy objects that are explicitly marked, what we have to do 267 // for the root regions is to scan them and mark all objects reachable 268 // from them. According to the SATB assumptions, we only need to visit 269 // each object once during marking. So, as long as we finish this scan 270 // before the next evacuation pause, we can copy the objects from the 271 // root regions without having to mark them or do anything else to them. 272 // 273 // Currently, we only support root region scanning once (at the start 274 // of the marking cycle) and the root regions are all the survivor 275 // regions populated during the initial-mark pause. 276 class G1CMRootRegions VALUE_OBJ_CLASS_SPEC { 277 private: 278 const G1SurvivorRegions* _survivors; 279 G1ConcurrentMark* _cm; 280 281 volatile bool _scan_in_progress; 282 volatile bool _should_abort; 283 volatile int _claimed_survivor_index; 284 285 void notify_scan_done(); 286 287 public: 288 G1CMRootRegions(); 289 // We actually do most of the initialization in this method. 290 void init(const G1SurvivorRegions* survivors, G1ConcurrentMark* cm); 291 292 // Reset the claiming / scanning of the root regions. 293 void prepare_for_scan(); 294 295 // Forces get_next() to return NULL so that the iteration aborts early. 296 void abort() { _should_abort = true; } 297 298 // Return true if the CM thread are actively scanning root regions, 299 // false otherwise. 300 bool scan_in_progress() { return _scan_in_progress; } 301 302 // Claim the next root region to scan atomically, or return NULL if 303 // all have been claimed. 304 HeapRegion* claim_next(); 305 306 // The number of root regions to scan. 307 uint num_root_regions() const; 308 309 void cancel_scan(); 310 311 // Flag that we're done with root region scanning and notify anyone 312 // who's waiting on it. If aborted is false, assume that all regions 313 // have been claimed. 314 void scan_finished(); 315 316 // If CM threads are still scanning root regions, wait until they 317 // are done. Return true if we had to wait, false otherwise. 318 bool wait_until_scan_finished(); 319 }; 320 321 class ConcurrentMarkThread; 322 323 class G1ConcurrentMark: public CHeapObj<mtGC> { 324 friend class ConcurrentMarkThread; 325 friend class G1ParNoteEndTask; 326 friend class G1VerifyLiveDataClosure; 327 friend class G1CMRefProcTaskProxy; 328 friend class G1CMRefProcTaskExecutor; 329 friend class G1CMKeepAliveAndDrainClosure; 330 friend class G1CMDrainMarkingStackClosure; 331 friend class G1CMBitMapClosure; 332 friend class G1CMConcurrentMarkingTask; 333 friend class G1CMRemarkTask; 334 friend class G1CMTask; 335 336 protected: 337 ConcurrentMarkThread* _cmThread; // The thread doing the work 338 G1CollectedHeap* _g1h; // The heap 339 uint _parallel_marking_threads; // The number of marking 340 // threads we're using 341 uint _max_parallel_marking_threads; // Max number of marking 342 // threads we'll ever use 343 double _sleep_factor; // How much we have to sleep, with 344 // respect to the work we just did, to 345 // meet the marking overhead goal 346 double _marking_task_overhead; // Marking target overhead for 347 // a single task 348 349 FreeRegionList _cleanup_list; 350 351 // Concurrent marking support structures 352 G1CMBitMap _markBitMap1; 353 G1CMBitMap _markBitMap2; 354 G1CMBitMapRO* _prevMarkBitMap; // Completed mark bitmap 355 G1CMBitMap* _nextMarkBitMap; // Under-construction mark bitmap 356 357 // Heap bounds 358 HeapWord* _heap_start; 359 HeapWord* _heap_end; 360 361 // Root region tracking and claiming 362 G1CMRootRegions _root_regions; 363 364 // For gray objects 365 G1CMMarkStack _global_mark_stack; // Grey objects behind global finger 366 HeapWord* volatile _finger; // The global finger, region aligned, 367 // always points to the end of the 368 // last claimed region 369 370 // Marking tasks 371 uint _max_worker_id;// Maximum worker id 372 uint _active_tasks; // Task num currently active 373 G1CMTask** _tasks; // Task queue array (max_worker_id len) 374 G1CMTaskQueueSet* _task_queues; // Task queue set 375 ParallelTaskTerminator _terminator; // For termination 376 377 // Two sync barriers that are used to synchronize tasks when an 378 // overflow occurs. The algorithm is the following. All tasks enter 379 // the first one to ensure that they have all stopped manipulating 380 // the global data structures. After they exit it, they re-initialize 381 // their data structures and task 0 re-initializes the global data 382 // structures. Then, they enter the second sync barrier. This 383 // ensure, that no task starts doing work before all data 384 // structures (local and global) have been re-initialized. When they 385 // exit it, they are free to start working again. 386 WorkGangBarrierSync _first_overflow_barrier_sync; 387 WorkGangBarrierSync _second_overflow_barrier_sync; 388 389 // This is set by any task, when an overflow on the global data 390 // structures is detected 391 volatile bool _has_overflown; 392 // True: marking is concurrent, false: we're in remark 393 volatile bool _concurrent; 394 // Set at the end of a Full GC so that marking aborts 395 volatile bool _has_aborted; 396 397 // Used when remark aborts due to an overflow to indicate that 398 // another concurrent marking phase should start 399 volatile bool _restart_for_overflow; 400 401 // This is true from the very start of concurrent marking until the 402 // point when all the tasks complete their work. It is really used 403 // to determine the points between the end of concurrent marking and 404 // time of remark. 405 volatile bool _concurrent_marking_in_progress; 406 407 ConcurrentGCTimer* _gc_timer_cm; 408 409 G1OldTracer* _gc_tracer_cm; 410 411 // All of these times are in ms 412 NumberSeq _init_times; 413 NumberSeq _remark_times; 414 NumberSeq _remark_mark_times; 415 NumberSeq _remark_weak_ref_times; 416 NumberSeq _cleanup_times; 417 double _total_counting_time; 418 double _total_rs_scrub_time; 419 420 double* _accum_task_vtime; // Accumulated task vtime 421 422 WorkGang* _parallel_workers; 423 424 void weakRefsWorkParallelPart(BoolObjectClosure* is_alive, bool purged_classes); 425 void weakRefsWork(bool clear_all_soft_refs); 426 427 void swapMarkBitMaps(); 428 429 // It resets the global marking data structures, as well as the 430 // task local ones; should be called during initial mark. 431 void reset(); 432 433 // Resets all the marking data structures. Called when we have to restart 434 // marking or when marking completes (via set_non_marking_state below). 435 void reset_marking_state(bool clear_overflow = true); 436 437 // We do this after we're done with marking so that the marking data 438 // structures are initialized to a sensible and predictable state. 439 void set_non_marking_state(); 440 441 // Called to indicate how many threads are currently active. 442 void set_concurrency(uint active_tasks); 443 444 // It should be called to indicate which phase we're in (concurrent 445 // mark or remark) and how many threads are currently active. 446 void set_concurrency_and_phase(uint active_tasks, bool concurrent); 447 448 // Prints all gathered CM-related statistics 449 void print_stats(); 450 451 bool cleanup_list_is_empty() { 452 return _cleanup_list.is_empty(); 453 } 454 455 // Accessor methods 456 uint parallel_marking_threads() const { return _parallel_marking_threads; } 457 uint max_parallel_marking_threads() const { return _max_parallel_marking_threads;} 458 double sleep_factor() { return _sleep_factor; } 459 double marking_task_overhead() { return _marking_task_overhead;} 460 461 HeapWord* finger() { return _finger; } 462 bool concurrent() { return _concurrent; } 463 uint active_tasks() { return _active_tasks; } 464 ParallelTaskTerminator* terminator() { return &_terminator; } 465 466 // It claims the next available region to be scanned by a marking 467 // task/thread. It might return NULL if the next region is empty or 468 // we have run out of regions. In the latter case, out_of_regions() 469 // determines whether we've really run out of regions or the task 470 // should call claim_region() again. This might seem a bit 471 // awkward. Originally, the code was written so that claim_region() 472 // either successfully returned with a non-empty region or there 473 // were no more regions to be claimed. The problem with this was 474 // that, in certain circumstances, it iterated over large chunks of 475 // the heap finding only empty regions and, while it was working, it 476 // was preventing the calling task to call its regular clock 477 // method. So, this way, each task will spend very little time in 478 // claim_region() and is allowed to call the regular clock method 479 // frequently. 480 HeapRegion* claim_region(uint worker_id); 481 482 // It determines whether we've run out of regions to scan. Note that 483 // the finger can point past the heap end in case the heap was expanded 484 // to satisfy an allocation without doing a GC. This is fine, because all 485 // objects in those regions will be considered live anyway because of 486 // SATB guarantees (i.e. their TAMS will be equal to bottom). 487 bool out_of_regions() { return _finger >= _heap_end; } 488 489 // Returns the task with the given id 490 G1CMTask* task(int id) { 491 assert(0 <= id && id < (int) _active_tasks, 492 "task id not within active bounds"); 493 return _tasks[id]; 494 } 495 496 // Returns the task queue with the given id 497 G1CMTaskQueue* task_queue(int id) { 498 assert(0 <= id && id < (int) _active_tasks, 499 "task queue id not within active bounds"); 500 return (G1CMTaskQueue*) _task_queues->queue(id); 501 } 502 503 // Returns the task queue set 504 G1CMTaskQueueSet* task_queues() { return _task_queues; } 505 506 // Access / manipulation of the overflow flag which is set to 507 // indicate that the global stack has overflown 508 bool has_overflown() { return _has_overflown; } 509 void set_has_overflown() { _has_overflown = true; } 510 void clear_has_overflown() { _has_overflown = false; } 511 bool restart_for_overflow() { return _restart_for_overflow; } 512 513 // Methods to enter the two overflow sync barriers 514 void enter_first_sync_barrier(uint worker_id); 515 void enter_second_sync_barrier(uint worker_id); 516 517 // Card index of the bottom of the G1 heap. Used for biasing indices into 518 // the card bitmaps. 519 intptr_t _heap_bottom_card_num; 520 521 // Set to true when initialization is complete 522 bool _completed_initialization; 523 524 // end_timer, true to end gc timer after ending concurrent phase. 525 void register_concurrent_phase_end_common(bool end_timer); 526 527 // Clear the given bitmap in parallel using the given WorkGang. If may_yield is 528 // true, periodically insert checks to see if this method should exit prematurely. 529 void clear_bitmap(G1CMBitMap* bitmap, WorkGang* workers, bool may_yield); 530 public: 531 // Manipulation of the global mark stack. 532 // The push and pop operations are used by tasks for transfers 533 // between task-local queues and the global mark stack. 534 bool mark_stack_push(oop* arr) { 535 if (!_global_mark_stack.par_push_chunk(arr)) { 536 set_has_overflown(); 537 return false; 538 } 539 return true; 540 } 541 bool mark_stack_pop(oop* arr) { 542 return _global_mark_stack.par_pop_chunk(arr); 543 } 544 size_t mark_stack_size() { return _global_mark_stack.size(); } 545 size_t partial_mark_stack_size_target() { return _global_mark_stack.capacity()/3; } 546 bool mark_stack_overflow() { return _global_mark_stack.is_out_of_memory(); } 547 bool mark_stack_empty() { return _global_mark_stack.is_empty(); } 548 549 G1CMRootRegions* root_regions() { return &_root_regions; } 550 551 bool concurrent_marking_in_progress() { 552 return _concurrent_marking_in_progress; 553 } 554 void set_concurrent_marking_in_progress() { 555 _concurrent_marking_in_progress = true; 556 } 557 void clear_concurrent_marking_in_progress() { 558 _concurrent_marking_in_progress = false; 559 } 560 561 void concurrent_cycle_start(); 562 void concurrent_cycle_end(); 563 564 void update_accum_task_vtime(int i, double vtime) { 565 _accum_task_vtime[i] += vtime; 566 } 567 568 double all_task_accum_vtime() { 569 double ret = 0.0; 570 for (uint i = 0; i < _max_worker_id; ++i) 571 ret += _accum_task_vtime[i]; 572 return ret; 573 } 574 575 // Attempts to steal an object from the task queues of other tasks 576 bool try_stealing(uint worker_id, int* hash_seed, oop& obj); 577 578 G1ConcurrentMark(G1CollectedHeap* g1h, 579 G1RegionToSpaceMapper* prev_bitmap_storage, 580 G1RegionToSpaceMapper* next_bitmap_storage); 581 ~G1ConcurrentMark(); 582 583 ConcurrentMarkThread* cmThread() { return _cmThread; } 584 585 G1CMBitMapRO* prevMarkBitMap() const { return _prevMarkBitMap; } 586 G1CMBitMap* nextMarkBitMap() const { return _nextMarkBitMap; } 587 588 // Returns the number of GC threads to be used in a concurrent 589 // phase based on the number of GC threads being used in a STW 590 // phase. 591 uint scale_parallel_threads(uint n_par_threads); 592 593 // Calculates the number of GC threads to be used in a concurrent phase. 594 uint calc_parallel_marking_threads(); 595 596 // The following three are interaction between CM and 597 // G1CollectedHeap 598 599 // This notifies CM that a root during initial-mark needs to be 600 // grayed. It is MT-safe. hr is the region that 601 // contains the object and it's passed optionally from callers who 602 // might already have it (no point in recalculating it). 603 inline void grayRoot(oop obj, 604 HeapRegion* hr = NULL); 605 606 // Prepare internal data structures for the next mark cycle. This includes clearing 607 // the next mark bitmap and some internal data structures. This method is intended 608 // to be called concurrently to the mutator. It will yield to safepoint requests. 609 void cleanup_for_next_mark(); 610 611 // Clear the previous marking bitmap during safepoint. 612 void clear_prev_bitmap(WorkGang* workers); 613 614 // Return whether the next mark bitmap has no marks set. To be used for assertions 615 // only. Will not yield to pause requests. 616 bool nextMarkBitmapIsClear(); 617 618 // These two do the work that needs to be done before and after the 619 // initial root checkpoint. Since this checkpoint can be done at two 620 // different points (i.e. an explicit pause or piggy-backed on a 621 // young collection), then it's nice to be able to easily share the 622 // pre/post code. It might be the case that we can put everything in 623 // the post method. TP 624 void checkpointRootsInitialPre(); 625 void checkpointRootsInitialPost(); 626 627 // Scan all the root regions and mark everything reachable from 628 // them. 629 void scan_root_regions(); 630 631 // Scan a single root region and mark everything reachable from it. 632 void scanRootRegion(HeapRegion* hr); 633 634 // Do concurrent phase of marking, to a tentative transitive closure. 635 void mark_from_roots(); 636 637 void checkpointRootsFinal(bool clear_all_soft_refs); 638 void checkpointRootsFinalWork(); 639 void cleanup(); 640 void complete_cleanup(); 641 642 // Mark in the previous bitmap. NB: this is usually read-only, so use 643 // this carefully! 644 inline void markPrev(oop p); 645 646 // Clears marks for all objects in the given range, for the prev or 647 // next bitmaps. NB: the previous bitmap is usually 648 // read-only, so use this carefully! 649 void clearRangePrevBitmap(MemRegion mr); 650 651 // Verify that there are no CSet oops on the stacks (taskqueues / 652 // global mark stack) and fingers (global / per-task). 653 // If marking is not in progress, it's a no-op. 654 void verify_no_cset_oops() PRODUCT_RETURN; 655 656 inline bool isPrevMarked(oop p) const; 657 658 inline bool do_yield_check(); 659 660 // Abandon current marking iteration due to a Full GC. 661 void abort(); 662 663 bool has_aborted() { return _has_aborted; } 664 665 void print_summary_info(); 666 667 void print_worker_threads_on(outputStream* st) const; 668 void threads_do(ThreadClosure* tc) const; 669 670 void print_on_error(outputStream* st) const; 671 672 // Attempts to mark the given object on the next mark bitmap. 673 inline bool par_mark(oop obj); 674 675 // Returns true if initialization was successfully completed. 676 bool completed_initialization() const { 677 return _completed_initialization; 678 } 679 680 ConcurrentGCTimer* gc_timer_cm() const { return _gc_timer_cm; } 681 G1OldTracer* gc_tracer_cm() const { return _gc_tracer_cm; } 682 683 private: 684 // Clear (Reset) all liveness count data. 685 void clear_live_data(WorkGang* workers); 686 687 #ifdef ASSERT 688 // Verify all of the above data structures that they are in initial state. 689 void verify_live_data_clear(); 690 #endif 691 692 // Aggregates the per-card liveness data based on the current marking. Also sets 693 // the amount of marked bytes for each region. 694 void create_live_data(); 695 696 void finalize_live_data(); 697 698 void verify_live_data(); 699 }; 700 701 // A class representing a marking task. 702 class G1CMTask : public TerminatorTerminator { 703 private: 704 enum PrivateConstants { 705 // The regular clock call is called once the scanned words reaches 706 // this limit 707 words_scanned_period = 12*1024, 708 // The regular clock call is called once the number of visited 709 // references reaches this limit 710 refs_reached_period = 1024, 711 // Initial value for the hash seed, used in the work stealing code 712 init_hash_seed = 17 713 }; 714 715 G1CMObjArrayProcessor _objArray_processor; 716 717 uint _worker_id; 718 G1CollectedHeap* _g1h; 719 G1ConcurrentMark* _cm; 720 G1CMBitMap* _nextMarkBitMap; 721 // the task queue of this task 722 G1CMTaskQueue* _task_queue; 723 private: 724 // the task queue set---needed for stealing 725 G1CMTaskQueueSet* _task_queues; 726 // indicates whether the task has been claimed---this is only for 727 // debugging purposes 728 bool _claimed; 729 730 // number of calls to this task 731 int _calls; 732 733 // when the virtual timer reaches this time, the marking step should 734 // exit 735 double _time_target_ms; 736 // the start time of the current marking step 737 double _start_time_ms; 738 739 // the oop closure used for iterations over oops 740 G1CMOopClosure* _cm_oop_closure; 741 742 // the region this task is scanning, NULL if we're not scanning any 743 HeapRegion* _curr_region; 744 // the local finger of this task, NULL if we're not scanning a region 745 HeapWord* _finger; 746 // limit of the region this task is scanning, NULL if we're not scanning one 747 HeapWord* _region_limit; 748 749 // the number of words this task has scanned 750 size_t _words_scanned; 751 // When _words_scanned reaches this limit, the regular clock is 752 // called. Notice that this might be decreased under certain 753 // circumstances (i.e. when we believe that we did an expensive 754 // operation). 755 size_t _words_scanned_limit; 756 // the initial value of _words_scanned_limit (i.e. what it was 757 // before it was decreased). 758 size_t _real_words_scanned_limit; 759 760 // the number of references this task has visited 761 size_t _refs_reached; 762 // When _refs_reached reaches this limit, the regular clock is 763 // called. Notice this this might be decreased under certain 764 // circumstances (i.e. when we believe that we did an expensive 765 // operation). 766 size_t _refs_reached_limit; 767 // the initial value of _refs_reached_limit (i.e. what it was before 768 // it was decreased). 769 size_t _real_refs_reached_limit; 770 771 // used by the work stealing stuff 772 int _hash_seed; 773 // if this is true, then the task has aborted for some reason 774 bool _has_aborted; 775 // set when the task aborts because it has met its time quota 776 bool _has_timed_out; 777 // true when we're draining SATB buffers; this avoids the task 778 // aborting due to SATB buffers being available (as we're already 779 // dealing with them) 780 bool _draining_satb_buffers; 781 782 // number sequence of past step times 783 NumberSeq _step_times_ms; 784 // elapsed time of this task 785 double _elapsed_time_ms; 786 // termination time of this task 787 double _termination_time_ms; 788 // when this task got into the termination protocol 789 double _termination_start_time_ms; 790 791 // true when the task is during a concurrent phase, false when it is 792 // in the remark phase (so, in the latter case, we do not have to 793 // check all the things that we have to check during the concurrent 794 // phase, i.e. SATB buffer availability...) 795 bool _concurrent; 796 797 TruncatedSeq _marking_step_diffs_ms; 798 799 // it updates the local fields after this task has claimed 800 // a new region to scan 801 void setup_for_region(HeapRegion* hr); 802 // it brings up-to-date the limit of the region 803 void update_region_limit(); 804 805 // called when either the words scanned or the refs visited limit 806 // has been reached 807 void reached_limit(); 808 // recalculates the words scanned and refs visited limits 809 void recalculate_limits(); 810 // decreases the words scanned and refs visited limits when we reach 811 // an expensive operation 812 void decrease_limits(); 813 // it checks whether the words scanned or refs visited reached their 814 // respective limit and calls reached_limit() if they have 815 void check_limits() { 816 if (_words_scanned >= _words_scanned_limit || 817 _refs_reached >= _refs_reached_limit) { 818 reached_limit(); 819 } 820 } 821 // this is supposed to be called regularly during a marking step as 822 // it checks a bunch of conditions that might cause the marking step 823 // to abort 824 void regular_clock_call(); 825 bool concurrent() { return _concurrent; } 826 827 // Test whether obj might have already been passed over by the 828 // mark bitmap scan, and so needs to be pushed onto the mark stack. 829 bool is_below_finger(oop obj, HeapWord* global_finger) const; 830 831 template<bool scan> void process_grey_object(oop obj); 832 public: 833 // Apply the closure on the given area of the objArray. Return the number of words 834 // scanned. 835 inline size_t scan_objArray(objArrayOop obj, MemRegion mr); 836 // It resets the task; it should be called right at the beginning of 837 // a marking phase. 838 void reset(G1CMBitMap* _nextMarkBitMap); 839 // it clears all the fields that correspond to a claimed region. 840 void clear_region_fields(); 841 842 void set_concurrent(bool concurrent) { _concurrent = concurrent; } 843 844 // The main method of this class which performs a marking step 845 // trying not to exceed the given duration. However, it might exit 846 // prematurely, according to some conditions (i.e. SATB buffers are 847 // available for processing). 848 void do_marking_step(double target_ms, 849 bool do_termination, 850 bool is_serial); 851 852 // These two calls start and stop the timer 853 void record_start_time() { 854 _elapsed_time_ms = os::elapsedTime() * 1000.0; 855 } 856 void record_end_time() { 857 _elapsed_time_ms = os::elapsedTime() * 1000.0 - _elapsed_time_ms; 858 } 859 860 // returns the worker ID associated with this task. 861 uint worker_id() { return _worker_id; } 862 863 // From TerminatorTerminator. It determines whether this task should 864 // exit the termination protocol after it's entered it. 865 virtual bool should_exit_termination(); 866 867 // Resets the local region fields after a task has finished scanning a 868 // region; or when they have become stale as a result of the region 869 // being evacuated. 870 void giveup_current_region(); 871 872 HeapWord* finger() { return _finger; } 873 874 bool has_aborted() { return _has_aborted; } 875 void set_has_aborted() { _has_aborted = true; } 876 void clear_has_aborted() { _has_aborted = false; } 877 bool has_timed_out() { return _has_timed_out; } 878 bool claimed() { return _claimed; } 879 880 void set_cm_oop_closure(G1CMOopClosure* cm_oop_closure); 881 882 // Increment the number of references this task has visited. 883 void increment_refs_reached() { ++_refs_reached; } 884 885 // Grey the object by marking it. If not already marked, push it on 886 // the local queue if below the finger. 887 // obj is below its region's NTAMS. 888 inline void make_reference_grey(oop obj); 889 890 // Grey the object (by calling make_grey_reference) if required, 891 // e.g. obj is below its containing region's NTAMS. 892 // Precondition: obj is a valid heap object. 893 inline void deal_with_reference(oop obj); 894 895 // It scans an object and visits its children. 896 inline void scan_object(oop obj); 897 898 // It pushes an object on the local queue. 899 inline void push(oop obj); 900 901 // Move entries to the global stack. 902 void move_entries_to_global_stack(); 903 // Move entries from the global stack, return true if we were successful to do so. 904 bool get_entries_from_global_stack(); 905 906 // It pops and scans objects from the local queue. If partially is 907 // true, then it stops when the queue size is of a given limit. If 908 // partially is false, then it stops when the queue is empty. 909 void drain_local_queue(bool partially); 910 // It moves entries from the global stack to the local queue and 911 // drains the local queue. If partially is true, then it stops when 912 // both the global stack and the local queue reach a given size. If 913 // partially if false, it tries to empty them totally. 914 void drain_global_stack(bool partially); 915 // It keeps picking SATB buffers and processing them until no SATB 916 // buffers are available. 917 void drain_satb_buffers(); 918 919 // moves the local finger to a new location 920 inline void move_finger_to(HeapWord* new_finger) { 921 assert(new_finger >= _finger && new_finger < _region_limit, "invariant"); 922 _finger = new_finger; 923 } 924 925 G1CMTask(uint worker_id, 926 G1ConcurrentMark *cm, 927 G1CMTaskQueue* task_queue, 928 G1CMTaskQueueSet* task_queues); 929 930 // it prints statistics associated with this task 931 void print_stats(); 932 }; 933 934 // Class that's used to to print out per-region liveness 935 // information. It's currently used at the end of marking and also 936 // after we sort the old regions at the end of the cleanup operation. 937 class G1PrintRegionLivenessInfoClosure: public HeapRegionClosure { 938 private: 939 // Accumulators for these values. 940 size_t _total_used_bytes; 941 size_t _total_capacity_bytes; 942 size_t _total_prev_live_bytes; 943 size_t _total_next_live_bytes; 944 945 // Accumulator for the remembered set size 946 size_t _total_remset_bytes; 947 948 // Accumulator for strong code roots memory size 949 size_t _total_strong_code_roots_bytes; 950 951 static double perc(size_t val, size_t total) { 952 if (total == 0) { 953 return 0.0; 954 } else { 955 return 100.0 * ((double) val / (double) total); 956 } 957 } 958 959 static double bytes_to_mb(size_t val) { 960 return (double) val / (double) M; 961 } 962 963 public: 964 // The header and footer are printed in the constructor and 965 // destructor respectively. 966 G1PrintRegionLivenessInfoClosure(const char* phase_name); 967 virtual bool doHeapRegion(HeapRegion* r); 968 ~G1PrintRegionLivenessInfoClosure(); 969 }; 970 971 #endif // SHARE_VM_GC_G1_G1CONCURRENTMARK_HPP