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