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_G1COLLECTEDHEAP_HPP 26 #define SHARE_VM_GC_G1_G1COLLECTEDHEAP_HPP 27 28 #include "gc/g1/evacuationInfo.hpp" 29 #include "gc/g1/g1AllocationContext.hpp" 30 #include "gc/g1/g1BiasedArray.hpp" 31 #include "gc/g1/g1CollectionSet.hpp" 32 #include "gc/g1/g1CollectorState.hpp" 33 #include "gc/g1/g1ConcurrentMark.hpp" 34 #include "gc/g1/g1EdenRegions.hpp" 35 #include "gc/g1/g1EvacFailure.hpp" 36 #include "gc/g1/g1EvacStats.hpp" 37 #include "gc/g1/g1HeapTransition.hpp" 38 #include "gc/g1/g1HeapVerifier.hpp" 39 #include "gc/g1/g1HRPrinter.hpp" 40 #include "gc/g1/g1InCSetState.hpp" 41 #include "gc/g1/g1MonitoringSupport.hpp" 42 #include "gc/g1/g1SATBCardTableModRefBS.hpp" 43 #include "gc/g1/g1SurvivorRegions.hpp" 44 #include "gc/g1/g1YCTypes.hpp" 45 #include "gc/g1/heapRegionManager.hpp" 46 #include "gc/g1/heapRegionSet.hpp" 47 #include "gc/shared/barrierSet.hpp" 48 #include "gc/shared/collectedHeap.hpp" 49 #include "gc/shared/gcHeapSummary.hpp" 50 #include "gc/shared/plab.hpp" 51 #include "gc/shared/preservedMarks.hpp" 52 #include "memory/memRegion.hpp" 53 #include "services/memoryManager.hpp" 54 #include "utilities/stack.hpp" 55 56 // A "G1CollectedHeap" is an implementation of a java heap for HotSpot. 57 // It uses the "Garbage First" heap organization and algorithm, which 58 // may combine concurrent marking with parallel, incremental compaction of 59 // heap subsets that will yield large amounts of garbage. 60 61 // Forward declarations 62 class HeapRegion; 63 class HRRSCleanupTask; 64 class GenerationSpec; 65 class G1ParScanThreadState; 66 class G1ParScanThreadStateSet; 67 class G1ParScanThreadState; 68 class MemoryPool; 69 class ObjectClosure; 70 class SpaceClosure; 71 class CompactibleSpaceClosure; 72 class Space; 73 class G1CollectionSet; 74 class G1CollectorPolicy; 75 class G1Policy; 76 class G1HotCardCache; 77 class G1RemSet; 78 class G1YoungRemSetSamplingThread; 79 class HeapRegionRemSetIterator; 80 class G1ConcurrentMark; 81 class ConcurrentMarkThread; 82 class G1ConcurrentRefine; 83 class GenerationCounters; 84 class STWGCTimer; 85 class G1NewTracer; 86 class EvacuationFailedInfo; 87 class nmethod; 88 class Ticks; 89 class WorkGang; 90 class G1Allocator; 91 class G1ArchiveAllocator; 92 class G1FullGCScope; 93 class G1HeapVerifier; 94 class G1HeapSizingPolicy; 95 class G1HeapSummary; 96 class G1EvacSummary; 97 98 typedef OverflowTaskQueue<StarTask, mtGC> RefToScanQueue; 99 typedef GenericTaskQueueSet<RefToScanQueue, mtGC> RefToScanQueueSet; 100 101 typedef int RegionIdx_t; // needs to hold [ 0..max_regions() ) 102 typedef int CardIdx_t; // needs to hold [ 0..CardsPerRegion ) 103 104 // The G1 STW is alive closure. 105 // An instance is embedded into the G1CH and used as the 106 // (optional) _is_alive_non_header closure in the STW 107 // reference processor. It is also extensively used during 108 // reference processing during STW evacuation pauses. 109 class G1STWIsAliveClosure: public BoolObjectClosure { 110 G1CollectedHeap* _g1; 111 public: 112 G1STWIsAliveClosure(G1CollectedHeap* g1) : _g1(g1) {} 113 bool do_object_b(oop p); 114 }; 115 116 class G1RegionMappingChangedListener : public G1MappingChangedListener { 117 private: 118 void reset_from_card_cache(uint start_idx, size_t num_regions); 119 public: 120 virtual void on_commit(uint start_idx, size_t num_regions, bool zero_filled); 121 }; 122 123 class G1CollectedHeap : public CollectedHeap { 124 friend class G1FreeCollectionSetTask; 125 friend class VM_CollectForMetadataAllocation; 126 friend class VM_G1CollectForAllocation; 127 friend class VM_G1CollectFull; 128 friend class VM_G1IncCollectionPause; 129 friend class VMStructs; 130 friend class MutatorAllocRegion; 131 friend class G1FullCollector; 132 friend class G1GCAllocRegion; 133 friend class G1HeapVerifier; 134 135 // Closures used in implementation. 136 friend class G1ParScanThreadState; 137 friend class G1ParScanThreadStateSet; 138 friend class G1ParTask; 139 friend class G1PLABAllocator; 140 friend class G1PrepareCompactClosure; 141 142 // Other related classes. 143 friend class HeapRegionClaimer; 144 145 // Testing classes. 146 friend class G1CheckCSetFastTableClosure; 147 148 private: 149 G1YoungRemSetSamplingThread* _young_gen_sampling_thread; 150 151 WorkGang* _workers; 152 G1CollectorPolicy* _collector_policy; 153 154 GCMemoryManager _memory_manager; 155 GCMemoryManager _full_gc_memory_manager; 156 157 MemoryPool* _eden_pool; 158 MemoryPool* _survivor_pool; 159 MemoryPool* _old_pool; 160 161 static size_t _humongous_object_threshold_in_words; 162 163 // The secondary free list which contains regions that have been 164 // freed up during the cleanup process. This will be appended to 165 // the master free list when appropriate. 166 FreeRegionList _secondary_free_list; 167 168 // It keeps track of the old regions. 169 HeapRegionSet _old_set; 170 171 // It keeps track of the humongous regions. 172 HeapRegionSet _humongous_set; 173 174 void eagerly_reclaim_humongous_regions(); 175 // Start a new incremental collection set for the next pause. 176 void start_new_collection_set(); 177 178 // The number of regions we could create by expansion. 179 uint _expansion_regions; 180 181 // The block offset table for the G1 heap. 182 G1BlockOffsetTable* _bot; 183 184 // Tears down the region sets / lists so that they are empty and the 185 // regions on the heap do not belong to a region set / list. The 186 // only exception is the humongous set which we leave unaltered. If 187 // free_list_only is true, it will only tear down the master free 188 // list. It is called before a Full GC (free_list_only == false) or 189 // before heap shrinking (free_list_only == true). 190 void tear_down_region_sets(bool free_list_only); 191 192 // Rebuilds the region sets / lists so that they are repopulated to 193 // reflect the contents of the heap. The only exception is the 194 // humongous set which was not torn down in the first place. If 195 // free_list_only is true, it will only rebuild the master free 196 // list. It is called after a Full GC (free_list_only == false) or 197 // after heap shrinking (free_list_only == true). 198 void rebuild_region_sets(bool free_list_only); 199 200 // Callback for region mapping changed events. 201 G1RegionMappingChangedListener _listener; 202 203 // The sequence of all heap regions in the heap. 204 HeapRegionManager _hrm; 205 206 // Manages all allocations with regions except humongous object allocations. 207 G1Allocator* _allocator; 208 209 // Manages all heap verification. 210 G1HeapVerifier* _verifier; 211 212 // Outside of GC pauses, the number of bytes used in all regions other 213 // than the current allocation region(s). 214 size_t _summary_bytes_used; 215 216 void increase_used(size_t bytes); 217 void decrease_used(size_t bytes); 218 219 void set_used(size_t bytes); 220 221 // Class that handles archive allocation ranges. 222 G1ArchiveAllocator* _archive_allocator; 223 224 // Statistics for each allocation context 225 AllocationContextStats _allocation_context_stats; 226 227 // GC allocation statistics policy for survivors. 228 G1EvacStats _survivor_evac_stats; 229 230 // GC allocation statistics policy for tenured objects. 231 G1EvacStats _old_evac_stats; 232 233 // It specifies whether we should attempt to expand the heap after a 234 // region allocation failure. If heap expansion fails we set this to 235 // false so that we don't re-attempt the heap expansion (it's likely 236 // that subsequent expansion attempts will also fail if one fails). 237 // Currently, it is only consulted during GC and it's reset at the 238 // start of each GC. 239 bool _expand_heap_after_alloc_failure; 240 241 // Helper for monitoring and management support. 242 G1MonitoringSupport* _g1mm; 243 244 // Records whether the region at the given index is (still) a 245 // candidate for eager reclaim. Only valid for humongous start 246 // regions; other regions have unspecified values. Humongous start 247 // regions are initialized at start of collection pause, with 248 // candidates removed from the set as they are found reachable from 249 // roots or the young generation. 250 class HumongousReclaimCandidates : public G1BiasedMappedArray<bool> { 251 protected: 252 bool default_value() const { return false; } 253 public: 254 void clear() { G1BiasedMappedArray<bool>::clear(); } 255 void set_candidate(uint region, bool value) { 256 set_by_index(region, value); 257 } 258 bool is_candidate(uint region) { 259 return get_by_index(region); 260 } 261 }; 262 263 HumongousReclaimCandidates _humongous_reclaim_candidates; 264 // Stores whether during humongous object registration we found candidate regions. 265 // If not, we can skip a few steps. 266 bool _has_humongous_reclaim_candidates; 267 268 volatile uint _gc_time_stamp; 269 270 G1HRPrinter _hr_printer; 271 272 // It decides whether an explicit GC should start a concurrent cycle 273 // instead of doing a STW GC. Currently, a concurrent cycle is 274 // explicitly started if: 275 // (a) cause == _gc_locker and +GCLockerInvokesConcurrent, or 276 // (b) cause == _g1_humongous_allocation 277 // (c) cause == _java_lang_system_gc and +ExplicitGCInvokesConcurrent. 278 // (d) cause == _dcmd_gc_run and +ExplicitGCInvokesConcurrent. 279 // (e) cause == _update_allocation_context_stats_inc 280 // (f) cause == _wb_conc_mark 281 bool should_do_concurrent_full_gc(GCCause::Cause cause); 282 283 // indicates whether we are in young or mixed GC mode 284 G1CollectorState _collector_state; 285 286 // Keeps track of how many "old marking cycles" (i.e., Full GCs or 287 // concurrent cycles) we have started. 288 volatile uint _old_marking_cycles_started; 289 290 // Keeps track of how many "old marking cycles" (i.e., Full GCs or 291 // concurrent cycles) we have completed. 292 volatile uint _old_marking_cycles_completed; 293 294 // This is a non-product method that is helpful for testing. It is 295 // called at the end of a GC and artificially expands the heap by 296 // allocating a number of dead regions. This way we can induce very 297 // frequent marking cycles and stress the cleanup / concurrent 298 // cleanup code more (as all the regions that will be allocated by 299 // this method will be found dead by the marking cycle). 300 void allocate_dummy_regions() PRODUCT_RETURN; 301 302 // Clear RSets after a compaction. It also resets the GC time stamps. 303 void clear_rsets_post_compaction(); 304 305 // If the HR printer is active, dump the state of the regions in the 306 // heap after a compaction. 307 void print_hrm_post_compaction(); 308 309 // Create a memory mapper for auxiliary data structures of the given size and 310 // translation factor. 311 static G1RegionToSpaceMapper* create_aux_memory_mapper(const char* description, 312 size_t size, 313 size_t translation_factor); 314 315 static G1Policy* create_g1_policy(STWGCTimer* gc_timer); 316 317 void trace_heap(GCWhen::Type when, const GCTracer* tracer); 318 319 // These are macros so that, if the assert fires, we get the correct 320 // line number, file, etc. 321 322 #define heap_locking_asserts_params(_extra_message_) \ 323 "%s : Heap_lock locked: %s, at safepoint: %s, is VM thread: %s", \ 324 (_extra_message_), \ 325 BOOL_TO_STR(Heap_lock->owned_by_self()), \ 326 BOOL_TO_STR(SafepointSynchronize::is_at_safepoint()), \ 327 BOOL_TO_STR(Thread::current()->is_VM_thread()) 328 329 #define assert_heap_locked() \ 330 do { \ 331 assert(Heap_lock->owned_by_self(), \ 332 heap_locking_asserts_params("should be holding the Heap_lock")); \ 333 } while (0) 334 335 #define assert_heap_locked_or_at_safepoint(_should_be_vm_thread_) \ 336 do { \ 337 assert(Heap_lock->owned_by_self() || \ 338 (SafepointSynchronize::is_at_safepoint() && \ 339 ((_should_be_vm_thread_) == Thread::current()->is_VM_thread())), \ 340 heap_locking_asserts_params("should be holding the Heap_lock or " \ 341 "should be at a safepoint")); \ 342 } while (0) 343 344 #define assert_heap_locked_and_not_at_safepoint() \ 345 do { \ 346 assert(Heap_lock->owned_by_self() && \ 347 !SafepointSynchronize::is_at_safepoint(), \ 348 heap_locking_asserts_params("should be holding the Heap_lock and " \ 349 "should not be at a safepoint")); \ 350 } while (0) 351 352 #define assert_heap_not_locked() \ 353 do { \ 354 assert(!Heap_lock->owned_by_self(), \ 355 heap_locking_asserts_params("should not be holding the Heap_lock")); \ 356 } while (0) 357 358 #define assert_heap_not_locked_and_not_at_safepoint() \ 359 do { \ 360 assert(!Heap_lock->owned_by_self() && \ 361 !SafepointSynchronize::is_at_safepoint(), \ 362 heap_locking_asserts_params("should not be holding the Heap_lock and " \ 363 "should not be at a safepoint")); \ 364 } while (0) 365 366 #define assert_at_safepoint(_should_be_vm_thread_) \ 367 do { \ 368 assert(SafepointSynchronize::is_at_safepoint() && \ 369 ((_should_be_vm_thread_) == Thread::current()->is_VM_thread()), \ 370 heap_locking_asserts_params("should be at a safepoint")); \ 371 } while (0) 372 373 #define assert_not_at_safepoint() \ 374 do { \ 375 assert(!SafepointSynchronize::is_at_safepoint(), \ 376 heap_locking_asserts_params("should not be at a safepoint")); \ 377 } while (0) 378 379 protected: 380 381 // The young region list. 382 G1EdenRegions _eden; 383 G1SurvivorRegions _survivor; 384 385 STWGCTimer* _gc_timer_stw; 386 387 G1NewTracer* _gc_tracer_stw; 388 389 // The current policy object for the collector. 390 G1Policy* _g1_policy; 391 G1HeapSizingPolicy* _heap_sizing_policy; 392 393 G1CollectionSet _collection_set; 394 395 // This is the second level of trying to allocate a new region. If 396 // new_region() didn't find a region on the free_list, this call will 397 // check whether there's anything available on the 398 // secondary_free_list and/or wait for more regions to appear on 399 // that list, if _free_regions_coming is set. 400 HeapRegion* new_region_try_secondary_free_list(bool is_old); 401 402 // Try to allocate a single non-humongous HeapRegion sufficient for 403 // an allocation of the given word_size. If do_expand is true, 404 // attempt to expand the heap if necessary to satisfy the allocation 405 // request. If the region is to be used as an old region or for a 406 // humongous object, set is_old to true. If not, to false. 407 HeapRegion* new_region(size_t word_size, bool is_old, bool do_expand); 408 409 // Initialize a contiguous set of free regions of length num_regions 410 // and starting at index first so that they appear as a single 411 // humongous region. 412 HeapWord* humongous_obj_allocate_initialize_regions(uint first, 413 uint num_regions, 414 size_t word_size, 415 AllocationContext_t context); 416 417 // Attempt to allocate a humongous object of the given size. Return 418 // NULL if unsuccessful. 419 HeapWord* humongous_obj_allocate(size_t word_size, AllocationContext_t context); 420 421 // The following two methods, allocate_new_tlab() and 422 // mem_allocate(), are the two main entry points from the runtime 423 // into the G1's allocation routines. They have the following 424 // assumptions: 425 // 426 // * They should both be called outside safepoints. 427 // 428 // * They should both be called without holding the Heap_lock. 429 // 430 // * All allocation requests for new TLABs should go to 431 // allocate_new_tlab(). 432 // 433 // * All non-TLAB allocation requests should go to mem_allocate(). 434 // 435 // * If either call cannot satisfy the allocation request using the 436 // current allocating region, they will try to get a new one. If 437 // this fails, they will attempt to do an evacuation pause and 438 // retry the allocation. 439 // 440 // * If all allocation attempts fail, even after trying to schedule 441 // an evacuation pause, allocate_new_tlab() will return NULL, 442 // whereas mem_allocate() will attempt a heap expansion and/or 443 // schedule a Full GC. 444 // 445 // * We do not allow humongous-sized TLABs. So, allocate_new_tlab 446 // should never be called with word_size being humongous. All 447 // humongous allocation requests should go to mem_allocate() which 448 // will satisfy them with a special path. 449 450 virtual HeapWord* allocate_new_tlab(size_t word_size); 451 452 virtual HeapWord* mem_allocate(size_t word_size, 453 bool* gc_overhead_limit_was_exceeded); 454 455 // The following three methods take a gc_count_before_ret 456 // parameter which is used to return the GC count if the method 457 // returns NULL. Given that we are required to read the GC count 458 // while holding the Heap_lock, and these paths will take the 459 // Heap_lock at some point, it's easier to get them to read the GC 460 // count while holding the Heap_lock before they return NULL instead 461 // of the caller (namely: mem_allocate()) having to also take the 462 // Heap_lock just to read the GC count. 463 464 // First-level mutator allocation attempt: try to allocate out of 465 // the mutator alloc region without taking the Heap_lock. This 466 // should only be used for non-humongous allocations. 467 inline HeapWord* attempt_allocation(size_t word_size, 468 uint* gc_count_before_ret, 469 uint* gclocker_retry_count_ret); 470 471 // Second-level mutator allocation attempt: take the Heap_lock and 472 // retry the allocation attempt, potentially scheduling a GC 473 // pause. This should only be used for non-humongous allocations. 474 HeapWord* attempt_allocation_slow(size_t word_size, 475 AllocationContext_t context, 476 uint* gc_count_before_ret, 477 uint* gclocker_retry_count_ret); 478 479 // Takes the Heap_lock and attempts a humongous allocation. It can 480 // potentially schedule a GC pause. 481 HeapWord* attempt_allocation_humongous(size_t word_size, 482 uint* gc_count_before_ret, 483 uint* gclocker_retry_count_ret); 484 485 // Allocation attempt that should be called during safepoints (e.g., 486 // at the end of a successful GC). expect_null_mutator_alloc_region 487 // specifies whether the mutator alloc region is expected to be NULL 488 // or not. 489 HeapWord* attempt_allocation_at_safepoint(size_t word_size, 490 AllocationContext_t context, 491 bool expect_null_mutator_alloc_region); 492 493 // These methods are the "callbacks" from the G1AllocRegion class. 494 495 // For mutator alloc regions. 496 HeapRegion* new_mutator_alloc_region(size_t word_size, bool force); 497 void retire_mutator_alloc_region(HeapRegion* alloc_region, 498 size_t allocated_bytes); 499 500 // For GC alloc regions. 501 bool has_more_regions(InCSetState dest); 502 HeapRegion* new_gc_alloc_region(size_t word_size, InCSetState dest); 503 void retire_gc_alloc_region(HeapRegion* alloc_region, 504 size_t allocated_bytes, InCSetState dest); 505 506 // - if explicit_gc is true, the GC is for a System.gc() etc, 507 // otherwise it's for a failed allocation. 508 // - if clear_all_soft_refs is true, all soft references should be 509 // cleared during the GC. 510 // - it returns false if it is unable to do the collection due to the 511 // GC locker being active, true otherwise. 512 bool do_full_collection(bool explicit_gc, 513 bool clear_all_soft_refs); 514 515 // Callback from VM_G1CollectFull operation, or collect_as_vm_thread. 516 virtual void do_full_collection(bool clear_all_soft_refs); 517 518 // Resize the heap if necessary after a full collection. 519 void resize_if_necessary_after_full_collection(); 520 521 // Callback from VM_G1CollectForAllocation operation. 522 // This function does everything necessary/possible to satisfy a 523 // failed allocation request (including collection, expansion, etc.) 524 HeapWord* satisfy_failed_allocation(size_t word_size, 525 AllocationContext_t context, 526 bool* succeeded); 527 private: 528 // Internal helpers used during full GC to split it up to 529 // increase readability. 530 void abort_concurrent_cycle(); 531 void verify_before_full_collection(bool explicit_gc); 532 void prepare_heap_for_full_collection(); 533 void prepare_heap_for_mutators(); 534 void abort_refinement(); 535 void verify_after_full_collection(); 536 void print_heap_after_full_collection(G1HeapTransition* heap_transition); 537 538 // Helper method for satisfy_failed_allocation() 539 HeapWord* satisfy_failed_allocation_helper(size_t word_size, 540 AllocationContext_t context, 541 bool do_gc, 542 bool clear_all_soft_refs, 543 bool expect_null_mutator_alloc_region, 544 bool* gc_succeeded); 545 546 protected: 547 // Attempting to expand the heap sufficiently 548 // to support an allocation of the given "word_size". If 549 // successful, perform the allocation and return the address of the 550 // allocated block, or else "NULL". 551 HeapWord* expand_and_allocate(size_t word_size, AllocationContext_t context); 552 553 // Preserve any referents discovered by concurrent marking that have not yet been 554 // copied by the STW pause. 555 void preserve_cm_referents(G1ParScanThreadStateSet* per_thread_states); 556 // Process any reference objects discovered during 557 // an incremental evacuation pause. 558 void process_discovered_references(G1ParScanThreadStateSet* per_thread_states); 559 560 // Enqueue any remaining discovered references 561 // after processing. 562 void enqueue_discovered_references(G1ParScanThreadStateSet* per_thread_states); 563 564 // Merges the information gathered on a per-thread basis for all worker threads 565 // during GC into global variables. 566 void merge_per_thread_state_info(G1ParScanThreadStateSet* per_thread_states); 567 public: 568 G1YoungRemSetSamplingThread* sampling_thread() const { return _young_gen_sampling_thread; } 569 570 WorkGang* workers() const { return _workers; } 571 572 G1Allocator* allocator() { 573 return _allocator; 574 } 575 576 G1HeapVerifier* verifier() { 577 return _verifier; 578 } 579 580 G1MonitoringSupport* g1mm() { 581 assert(_g1mm != NULL, "should have been initialized"); 582 return _g1mm; 583 } 584 585 // Expand the garbage-first heap by at least the given size (in bytes!). 586 // Returns true if the heap was expanded by the requested amount; 587 // false otherwise. 588 // (Rounds up to a HeapRegion boundary.) 589 bool expand(size_t expand_bytes, WorkGang* pretouch_workers = NULL, double* expand_time_ms = NULL); 590 591 // Returns the PLAB statistics for a given destination. 592 inline G1EvacStats* alloc_buffer_stats(InCSetState dest); 593 594 // Determines PLAB size for a given destination. 595 inline size_t desired_plab_sz(InCSetState dest); 596 597 inline AllocationContextStats& allocation_context_stats(); 598 599 // Do anything common to GC's. 600 void gc_prologue(bool full); 601 void gc_epilogue(bool full); 602 603 // Modify the reclaim candidate set and test for presence. 604 // These are only valid for starts_humongous regions. 605 inline void set_humongous_reclaim_candidate(uint region, bool value); 606 inline bool is_humongous_reclaim_candidate(uint region); 607 608 // Remove from the reclaim candidate set. Also remove from the 609 // collection set so that later encounters avoid the slow path. 610 inline void set_humongous_is_live(oop obj); 611 612 // Register the given region to be part of the collection set. 613 inline void register_humongous_region_with_cset(uint index); 614 // Register regions with humongous objects (actually on the start region) in 615 // the in_cset_fast_test table. 616 void register_humongous_regions_with_cset(); 617 // We register a region with the fast "in collection set" test. We 618 // simply set to true the array slot corresponding to this region. 619 void register_young_region_with_cset(HeapRegion* r) { 620 _in_cset_fast_test.set_in_young(r->hrm_index()); 621 } 622 void register_old_region_with_cset(HeapRegion* r) { 623 _in_cset_fast_test.set_in_old(r->hrm_index()); 624 } 625 inline void register_ext_region_with_cset(HeapRegion* r) { 626 _in_cset_fast_test.set_ext(r->hrm_index()); 627 } 628 void clear_in_cset(const HeapRegion* hr) { 629 _in_cset_fast_test.clear(hr); 630 } 631 632 void clear_cset_fast_test() { 633 _in_cset_fast_test.clear(); 634 } 635 636 bool is_user_requested_concurrent_full_gc(GCCause::Cause cause); 637 638 // This is called at the start of either a concurrent cycle or a Full 639 // GC to update the number of old marking cycles started. 640 void increment_old_marking_cycles_started(); 641 642 // This is called at the end of either a concurrent cycle or a Full 643 // GC to update the number of old marking cycles completed. Those two 644 // can happen in a nested fashion, i.e., we start a concurrent 645 // cycle, a Full GC happens half-way through it which ends first, 646 // and then the cycle notices that a Full GC happened and ends 647 // too. The concurrent parameter is a boolean to help us do a bit 648 // tighter consistency checking in the method. If concurrent is 649 // false, the caller is the inner caller in the nesting (i.e., the 650 // Full GC). If concurrent is true, the caller is the outer caller 651 // in this nesting (i.e., the concurrent cycle). Further nesting is 652 // not currently supported. The end of this call also notifies 653 // the FullGCCount_lock in case a Java thread is waiting for a full 654 // GC to happen (e.g., it called System.gc() with 655 // +ExplicitGCInvokesConcurrent). 656 void increment_old_marking_cycles_completed(bool concurrent); 657 658 uint old_marking_cycles_completed() { 659 return _old_marking_cycles_completed; 660 } 661 662 G1HRPrinter* hr_printer() { return &_hr_printer; } 663 664 // Allocates a new heap region instance. 665 HeapRegion* new_heap_region(uint hrs_index, MemRegion mr); 666 667 // Allocate the highest free region in the reserved heap. This will commit 668 // regions as necessary. 669 HeapRegion* alloc_highest_free_region(); 670 671 // Frees a non-humongous region by initializing its contents and 672 // adding it to the free list that's passed as a parameter (this is 673 // usually a local list which will be appended to the master free 674 // list later). The used bytes of freed regions are accumulated in 675 // pre_used. If skip_remset is true, the region's RSet will not be freed 676 // up. If skip_hot_card_cache is true, the region's hot card cache will not 677 // be freed up. The assumption is that this will be done later. 678 // The locked parameter indicates if the caller has already taken 679 // care of proper synchronization. This may allow some optimizations. 680 void free_region(HeapRegion* hr, 681 FreeRegionList* free_list, 682 bool skip_remset, 683 bool skip_hot_card_cache = false, 684 bool locked = false); 685 686 // It dirties the cards that cover the block so that the post 687 // write barrier never queues anything when updating objects on this 688 // block. It is assumed (and in fact we assert) that the block 689 // belongs to a young region. 690 inline void dirty_young_block(HeapWord* start, size_t word_size); 691 692 // Frees a humongous region by collapsing it into individual regions 693 // and calling free_region() for each of them. The freed regions 694 // will be added to the free list that's passed as a parameter (this 695 // is usually a local list which will be appended to the master free 696 // list later). The used bytes of freed regions are accumulated in 697 // pre_used. If skip_remset is true, the region's RSet will not be freed 698 // up. The assumption is that this will be done later. 699 void free_humongous_region(HeapRegion* hr, 700 FreeRegionList* free_list, 701 bool skip_remset); 702 703 // Facility for allocating in 'archive' regions in high heap memory and 704 // recording the allocated ranges. These should all be called from the 705 // VM thread at safepoints, without the heap lock held. They can be used 706 // to create and archive a set of heap regions which can be mapped at the 707 // same fixed addresses in a subsequent JVM invocation. 708 void begin_archive_alloc_range(bool open = false); 709 710 // Check if the requested size would be too large for an archive allocation. 711 bool is_archive_alloc_too_large(size_t word_size); 712 713 // Allocate memory of the requested size from the archive region. This will 714 // return NULL if the size is too large or if no memory is available. It 715 // does not trigger a garbage collection. 716 HeapWord* archive_mem_allocate(size_t word_size); 717 718 // Optionally aligns the end address and returns the allocated ranges in 719 // an array of MemRegions in order of ascending addresses. 720 void end_archive_alloc_range(GrowableArray<MemRegion>* ranges, 721 size_t end_alignment_in_bytes = 0); 722 723 // Facility for allocating a fixed range within the heap and marking 724 // the containing regions as 'archive'. For use at JVM init time, when the 725 // caller may mmap archived heap data at the specified range(s). 726 // Verify that the MemRegions specified in the argument array are within the 727 // reserved heap. 728 bool check_archive_addresses(MemRegion* range, size_t count); 729 730 // Commit the appropriate G1 regions containing the specified MemRegions 731 // and mark them as 'archive' regions. The regions in the array must be 732 // non-overlapping and in order of ascending address. 733 bool alloc_archive_regions(MemRegion* range, size_t count, bool open); 734 735 // Insert any required filler objects in the G1 regions around the specified 736 // ranges to make the regions parseable. This must be called after 737 // alloc_archive_regions, and after class loading has occurred. 738 void fill_archive_regions(MemRegion* range, size_t count); 739 740 // For each of the specified MemRegions, uncommit the containing G1 regions 741 // which had been allocated by alloc_archive_regions. This should be called 742 // rather than fill_archive_regions at JVM init time if the archive file 743 // mapping failed, with the same non-overlapping and sorted MemRegion array. 744 void dealloc_archive_regions(MemRegion* range, size_t count); 745 746 protected: 747 748 // Shrink the garbage-first heap by at most the given size (in bytes!). 749 // (Rounds down to a HeapRegion boundary.) 750 virtual void shrink(size_t expand_bytes); 751 void shrink_helper(size_t expand_bytes); 752 753 #if TASKQUEUE_STATS 754 static void print_taskqueue_stats_hdr(outputStream* const st); 755 void print_taskqueue_stats() const; 756 void reset_taskqueue_stats(); 757 #endif // TASKQUEUE_STATS 758 759 // Schedule the VM operation that will do an evacuation pause to 760 // satisfy an allocation request of word_size. *succeeded will 761 // return whether the VM operation was successful (it did do an 762 // evacuation pause) or not (another thread beat us to it or the GC 763 // locker was active). Given that we should not be holding the 764 // Heap_lock when we enter this method, we will pass the 765 // gc_count_before (i.e., total_collections()) as a parameter since 766 // it has to be read while holding the Heap_lock. Currently, both 767 // methods that call do_collection_pause() release the Heap_lock 768 // before the call, so it's easy to read gc_count_before just before. 769 HeapWord* do_collection_pause(size_t word_size, 770 uint gc_count_before, 771 bool* succeeded, 772 GCCause::Cause gc_cause); 773 774 void wait_for_root_region_scanning(); 775 776 // The guts of the incremental collection pause, executed by the vm 777 // thread. It returns false if it is unable to do the collection due 778 // to the GC locker being active, true otherwise 779 bool do_collection_pause_at_safepoint(double target_pause_time_ms); 780 781 // Actually do the work of evacuating the collection set. 782 virtual void evacuate_collection_set(EvacuationInfo& evacuation_info, G1ParScanThreadStateSet* per_thread_states); 783 784 void pre_evacuate_collection_set(); 785 void post_evacuate_collection_set(EvacuationInfo& evacuation_info, G1ParScanThreadStateSet* pss); 786 787 // Print the header for the per-thread termination statistics. 788 static void print_termination_stats_hdr(); 789 // Print actual per-thread termination statistics. 790 void print_termination_stats(uint worker_id, 791 double elapsed_ms, 792 double strong_roots_ms, 793 double term_ms, 794 size_t term_attempts, 795 size_t alloc_buffer_waste, 796 size_t undo_waste) const; 797 // Update object copying statistics. 798 void record_obj_copy_mem_stats(); 799 800 // The hot card cache for remembered set insertion optimization. 801 G1HotCardCache* _hot_card_cache; 802 803 // The g1 remembered set of the heap. 804 G1RemSet* _g1_rem_set; 805 806 // A set of cards that cover the objects for which the Rsets should be updated 807 // concurrently after the collection. 808 DirtyCardQueueSet _dirty_card_queue_set; 809 810 // After a collection pause, convert the regions in the collection set into free 811 // regions. 812 void free_collection_set(G1CollectionSet* collection_set, EvacuationInfo& evacuation_info, const size_t* surviving_young_words); 813 814 // Abandon the current collection set without recording policy 815 // statistics or updating free lists. 816 void abandon_collection_set(G1CollectionSet* collection_set); 817 818 // The concurrent marker (and the thread it runs in.) 819 G1ConcurrentMark* _cm; 820 ConcurrentMarkThread* _cmThread; 821 822 // The concurrent refiner. 823 G1ConcurrentRefine* _cr; 824 825 // The parallel task queues 826 RefToScanQueueSet *_task_queues; 827 828 // True iff a evacuation has failed in the current collection. 829 bool _evacuation_failed; 830 831 EvacuationFailedInfo* _evacuation_failed_info_array; 832 833 // Failed evacuations cause some logical from-space objects to have 834 // forwarding pointers to themselves. Reset them. 835 void remove_self_forwarding_pointers(); 836 837 // Restore the objects in the regions in the collection set after an 838 // evacuation failure. 839 void restore_after_evac_failure(); 840 841 PreservedMarksSet _preserved_marks_set; 842 843 // Preserve the mark of "obj", if necessary, in preparation for its mark 844 // word being overwritten with a self-forwarding-pointer. 845 void preserve_mark_during_evac_failure(uint worker_id, oop obj, markOop m); 846 847 #ifndef PRODUCT 848 // Support for forcing evacuation failures. Analogous to 849 // PromotionFailureALot for the other collectors. 850 851 // Records whether G1EvacuationFailureALot should be in effect 852 // for the current GC 853 bool _evacuation_failure_alot_for_current_gc; 854 855 // Used to record the GC number for interval checking when 856 // determining whether G1EvaucationFailureALot is in effect 857 // for the current GC. 858 size_t _evacuation_failure_alot_gc_number; 859 860 // Count of the number of evacuations between failures. 861 volatile size_t _evacuation_failure_alot_count; 862 863 // Set whether G1EvacuationFailureALot should be in effect 864 // for the current GC (based upon the type of GC and which 865 // command line flags are set); 866 inline bool evacuation_failure_alot_for_gc_type(bool gcs_are_young, 867 bool during_initial_mark, 868 bool during_marking); 869 870 inline void set_evacuation_failure_alot_for_current_gc(); 871 872 // Return true if it's time to cause an evacuation failure. 873 inline bool evacuation_should_fail(); 874 875 // Reset the G1EvacuationFailureALot counters. Should be called at 876 // the end of an evacuation pause in which an evacuation failure occurred. 877 inline void reset_evacuation_should_fail(); 878 #endif // !PRODUCT 879 880 // ("Weak") Reference processing support. 881 // 882 // G1 has 2 instances of the reference processor class. One 883 // (_ref_processor_cm) handles reference object discovery 884 // and subsequent processing during concurrent marking cycles. 885 // 886 // The other (_ref_processor_stw) handles reference object 887 // discovery and processing during full GCs and incremental 888 // evacuation pauses. 889 // 890 // During an incremental pause, reference discovery will be 891 // temporarily disabled for _ref_processor_cm and will be 892 // enabled for _ref_processor_stw. At the end of the evacuation 893 // pause references discovered by _ref_processor_stw will be 894 // processed and discovery will be disabled. The previous 895 // setting for reference object discovery for _ref_processor_cm 896 // will be re-instated. 897 // 898 // At the start of marking: 899 // * Discovery by the CM ref processor is verified to be inactive 900 // and it's discovered lists are empty. 901 // * Discovery by the CM ref processor is then enabled. 902 // 903 // At the end of marking: 904 // * Any references on the CM ref processor's discovered 905 // lists are processed (possibly MT). 906 // 907 // At the start of full GC we: 908 // * Disable discovery by the CM ref processor and 909 // empty CM ref processor's discovered lists 910 // (without processing any entries). 911 // * Verify that the STW ref processor is inactive and it's 912 // discovered lists are empty. 913 // * Temporarily set STW ref processor discovery as single threaded. 914 // * Temporarily clear the STW ref processor's _is_alive_non_header 915 // field. 916 // * Finally enable discovery by the STW ref processor. 917 // 918 // The STW ref processor is used to record any discovered 919 // references during the full GC. 920 // 921 // At the end of a full GC we: 922 // * Enqueue any reference objects discovered by the STW ref processor 923 // that have non-live referents. This has the side-effect of 924 // making the STW ref processor inactive by disabling discovery. 925 // * Verify that the CM ref processor is still inactive 926 // and no references have been placed on it's discovered 927 // lists (also checked as a precondition during initial marking). 928 929 // The (stw) reference processor... 930 ReferenceProcessor* _ref_processor_stw; 931 932 // During reference object discovery, the _is_alive_non_header 933 // closure (if non-null) is applied to the referent object to 934 // determine whether the referent is live. If so then the 935 // reference object does not need to be 'discovered' and can 936 // be treated as a regular oop. This has the benefit of reducing 937 // the number of 'discovered' reference objects that need to 938 // be processed. 939 // 940 // Instance of the is_alive closure for embedding into the 941 // STW reference processor as the _is_alive_non_header field. 942 // Supplying a value for the _is_alive_non_header field is 943 // optional but doing so prevents unnecessary additions to 944 // the discovered lists during reference discovery. 945 G1STWIsAliveClosure _is_alive_closure_stw; 946 947 // The (concurrent marking) reference processor... 948 ReferenceProcessor* _ref_processor_cm; 949 950 // Instance of the concurrent mark is_alive closure for embedding 951 // into the Concurrent Marking reference processor as the 952 // _is_alive_non_header field. Supplying a value for the 953 // _is_alive_non_header field is optional but doing so prevents 954 // unnecessary additions to the discovered lists during reference 955 // discovery. 956 G1CMIsAliveClosure _is_alive_closure_cm; 957 958 volatile bool _free_regions_coming; 959 960 public: 961 962 RefToScanQueue *task_queue(uint i) const; 963 964 uint num_task_queues() const; 965 966 // A set of cards where updates happened during the GC 967 DirtyCardQueueSet& dirty_card_queue_set() { return _dirty_card_queue_set; } 968 969 // Create a G1CollectedHeap with the specified policy. 970 // Must call the initialize method afterwards. 971 // May not return if something goes wrong. 972 G1CollectedHeap(G1CollectorPolicy* policy); 973 974 private: 975 jint initialize_concurrent_refinement(); 976 jint initialize_young_gen_sampling_thread(); 977 public: 978 // Initialize the G1CollectedHeap to have the initial and 979 // maximum sizes and remembered and barrier sets 980 // specified by the policy object. 981 jint initialize(); 982 983 virtual void stop(); 984 virtual void safepoint_synchronize_begin(); 985 virtual void safepoint_synchronize_end(); 986 987 // Return the (conservative) maximum heap alignment for any G1 heap 988 static size_t conservative_max_heap_alignment(); 989 990 // Does operations required after initialization has been done. 991 void post_initialize(); 992 993 // Initialize weak reference processing. 994 void ref_processing_init(); 995 996 virtual Name kind() const { 997 return CollectedHeap::G1CollectedHeap; 998 } 999 1000 virtual const char* name() const { 1001 return "G1"; 1002 } 1003 1004 const G1CollectorState* collector_state() const { return &_collector_state; } 1005 G1CollectorState* collector_state() { return &_collector_state; } 1006 1007 // The current policy object for the collector. 1008 G1Policy* g1_policy() const { return _g1_policy; } 1009 1010 const G1CollectionSet* collection_set() const { return &_collection_set; } 1011 G1CollectionSet* collection_set() { return &_collection_set; } 1012 1013 virtual CollectorPolicy* collector_policy() const; 1014 1015 // Adaptive size policy. No such thing for g1. 1016 virtual AdaptiveSizePolicy* size_policy() { return NULL; } 1017 1018 virtual GrowableArray<GCMemoryManager*> memory_managers(); 1019 virtual GrowableArray<MemoryPool*> memory_pools(); 1020 1021 // The rem set and barrier set. 1022 G1RemSet* g1_rem_set() const { return _g1_rem_set; } 1023 1024 // Try to minimize the remembered set. 1025 void scrub_rem_set(); 1026 1027 uint get_gc_time_stamp() { 1028 return _gc_time_stamp; 1029 } 1030 1031 inline void reset_gc_time_stamp(); 1032 1033 void check_gc_time_stamps() PRODUCT_RETURN; 1034 1035 inline void increment_gc_time_stamp(); 1036 1037 // Reset the given region's GC timestamp. If it's starts humongous, 1038 // also reset the GC timestamp of its corresponding 1039 // continues humongous regions too. 1040 void reset_gc_time_stamps(HeapRegion* hr); 1041 1042 // Apply the given closure on all cards in the Hot Card Cache, emptying it. 1043 void iterate_hcc_closure(CardTableEntryClosure* cl, uint worker_i); 1044 1045 // Apply the given closure on all cards in the Dirty Card Queue Set, emptying it. 1046 void iterate_dirty_card_closure(CardTableEntryClosure* cl, uint worker_i); 1047 1048 // The shared block offset table array. 1049 G1BlockOffsetTable* bot() const { return _bot; } 1050 1051 // Reference Processing accessors 1052 1053 // The STW reference processor.... 1054 ReferenceProcessor* ref_processor_stw() const { return _ref_processor_stw; } 1055 1056 G1NewTracer* gc_tracer_stw() const { return _gc_tracer_stw; } 1057 1058 // The Concurrent Marking reference processor... 1059 ReferenceProcessor* ref_processor_cm() const { return _ref_processor_cm; } 1060 1061 size_t unused_committed_regions_in_bytes() const; 1062 virtual size_t capacity() const; 1063 virtual size_t used() const; 1064 // This should be called when we're not holding the heap lock. The 1065 // result might be a bit inaccurate. 1066 size_t used_unlocked() const; 1067 size_t recalculate_used() const; 1068 1069 // These virtual functions do the actual allocation. 1070 // Some heaps may offer a contiguous region for shared non-blocking 1071 // allocation, via inlined code (by exporting the address of the top and 1072 // end fields defining the extent of the contiguous allocation region.) 1073 // But G1CollectedHeap doesn't yet support this. 1074 1075 virtual bool is_maximal_no_gc() const { 1076 return _hrm.available() == 0; 1077 } 1078 1079 // The current number of regions in the heap. 1080 uint num_regions() const { return _hrm.length(); } 1081 1082 // The max number of regions in the heap. 1083 uint max_regions() const { return _hrm.max_length(); } 1084 1085 // The number of regions that are completely free. 1086 uint num_free_regions() const { return _hrm.num_free_regions(); } 1087 1088 MemoryUsage get_auxiliary_data_memory_usage() const { 1089 return _hrm.get_auxiliary_data_memory_usage(); 1090 } 1091 1092 // The number of regions that are not completely free. 1093 uint num_used_regions() const { return num_regions() - num_free_regions(); } 1094 1095 #ifdef ASSERT 1096 bool is_on_master_free_list(HeapRegion* hr) { 1097 return _hrm.is_free(hr); 1098 } 1099 #endif // ASSERT 1100 1101 // Wrapper for the region list operations that can be called from 1102 // methods outside this class. 1103 1104 void secondary_free_list_add(FreeRegionList* list) { 1105 _secondary_free_list.add_ordered(list); 1106 } 1107 1108 void append_secondary_free_list() { 1109 _hrm.insert_list_into_free_list(&_secondary_free_list); 1110 } 1111 1112 void append_secondary_free_list_if_not_empty_with_lock() { 1113 // If the secondary free list looks empty there's no reason to 1114 // take the lock and then try to append it. 1115 if (!_secondary_free_list.is_empty()) { 1116 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag); 1117 append_secondary_free_list(); 1118 } 1119 } 1120 1121 inline void old_set_add(HeapRegion* hr); 1122 inline void old_set_remove(HeapRegion* hr); 1123 1124 size_t non_young_capacity_bytes() { 1125 return (_old_set.length() + _humongous_set.length()) * HeapRegion::GrainBytes; 1126 } 1127 1128 void set_free_regions_coming(); 1129 void reset_free_regions_coming(); 1130 bool free_regions_coming() { return _free_regions_coming; } 1131 void wait_while_free_regions_coming(); 1132 1133 // Determine whether the given region is one that we are using as an 1134 // old GC alloc region. 1135 bool is_old_gc_alloc_region(HeapRegion* hr); 1136 1137 // Perform a collection of the heap; intended for use in implementing 1138 // "System.gc". This probably implies as full a collection as the 1139 // "CollectedHeap" supports. 1140 virtual void collect(GCCause::Cause cause); 1141 1142 virtual bool copy_allocation_context_stats(const jint* contexts, 1143 jlong* totals, 1144 jbyte* accuracy, 1145 jint len); 1146 1147 // True iff an evacuation has failed in the most-recent collection. 1148 bool evacuation_failed() { return _evacuation_failed; } 1149 1150 void remove_from_old_sets(const uint old_regions_removed, const uint humongous_regions_removed); 1151 void prepend_to_freelist(FreeRegionList* list); 1152 void decrement_summary_bytes(size_t bytes); 1153 1154 virtual bool is_in(const void* p) const; 1155 #ifdef ASSERT 1156 // Returns whether p is in one of the available areas of the heap. Slow but 1157 // extensive version. 1158 bool is_in_exact(const void* p) const; 1159 #endif 1160 1161 // Return "TRUE" iff the given object address is within the collection 1162 // set. Assumes that the reference points into the heap. 1163 inline bool is_in_cset(const HeapRegion *hr); 1164 inline bool is_in_cset(oop obj); 1165 inline bool is_in_cset(HeapWord* addr); 1166 1167 inline bool is_in_cset_or_humongous(const oop obj); 1168 1169 private: 1170 // This array is used for a quick test on whether a reference points into 1171 // the collection set or not. Each of the array's elements denotes whether the 1172 // corresponding region is in the collection set or not. 1173 G1InCSetStateFastTestBiasedMappedArray _in_cset_fast_test; 1174 1175 public: 1176 1177 inline InCSetState in_cset_state(const oop obj); 1178 1179 // Return "TRUE" iff the given object address is in the reserved 1180 // region of g1. 1181 bool is_in_g1_reserved(const void* p) const { 1182 return _hrm.reserved().contains(p); 1183 } 1184 1185 // Returns a MemRegion that corresponds to the space that has been 1186 // reserved for the heap 1187 MemRegion g1_reserved() const { 1188 return _hrm.reserved(); 1189 } 1190 1191 virtual bool is_in_closed_subset(const void* p) const; 1192 1193 G1SATBCardTableLoggingModRefBS* g1_barrier_set() { 1194 return barrier_set_cast<G1SATBCardTableLoggingModRefBS>(barrier_set()); 1195 } 1196 1197 G1HotCardCache* g1_hot_card_cache() const { return _hot_card_cache; } 1198 1199 // Iteration functions. 1200 1201 // Iterate over all objects, calling "cl.do_object" on each. 1202 virtual void object_iterate(ObjectClosure* cl); 1203 1204 virtual void safe_object_iterate(ObjectClosure* cl) { 1205 object_iterate(cl); 1206 } 1207 1208 // Iterate over heap regions, in address order, terminating the 1209 // iteration early if the "doHeapRegion" method returns "true". 1210 void heap_region_iterate(HeapRegionClosure* blk) const; 1211 1212 // Return the region with the given index. It assumes the index is valid. 1213 inline HeapRegion* region_at(uint index) const; 1214 1215 // Return the next region (by index) that is part of the same 1216 // humongous object that hr is part of. 1217 inline HeapRegion* next_region_in_humongous(HeapRegion* hr) const; 1218 1219 // Calculate the region index of the given address. Given address must be 1220 // within the heap. 1221 inline uint addr_to_region(HeapWord* addr) const; 1222 1223 inline HeapWord* bottom_addr_for_region(uint index) const; 1224 1225 // Two functions to iterate over the heap regions in parallel. Threads 1226 // compete using the HeapRegionClaimer to claim the regions before 1227 // applying the closure on them. 1228 // The _from_worker_offset version uses the HeapRegionClaimer and 1229 // the worker id to calculate a start offset to prevent all workers to 1230 // start from the point. 1231 void heap_region_par_iterate_from_worker_offset(HeapRegionClosure* cl, 1232 HeapRegionClaimer* hrclaimer, 1233 uint worker_id) const; 1234 1235 void heap_region_par_iterate_from_start(HeapRegionClosure* cl, 1236 HeapRegionClaimer* hrclaimer) const; 1237 1238 // Iterate over the regions (if any) in the current collection set. 1239 void collection_set_iterate(HeapRegionClosure* blk); 1240 1241 // Iterate over the regions (if any) in the current collection set. Starts the 1242 // iteration over the entire collection set so that the start regions of a given 1243 // worker id over the set active_workers are evenly spread across the set of 1244 // collection set regions. 1245 void collection_set_iterate_from(HeapRegionClosure *blk, uint worker_id); 1246 1247 // Returns the HeapRegion that contains addr. addr must not be NULL. 1248 template <class T> 1249 inline HeapRegion* heap_region_containing(const T addr) const; 1250 1251 // A CollectedHeap is divided into a dense sequence of "blocks"; that is, 1252 // each address in the (reserved) heap is a member of exactly 1253 // one block. The defining characteristic of a block is that it is 1254 // possible to find its size, and thus to progress forward to the next 1255 // block. (Blocks may be of different sizes.) Thus, blocks may 1256 // represent Java objects, or they might be free blocks in a 1257 // free-list-based heap (or subheap), as long as the two kinds are 1258 // distinguishable and the size of each is determinable. 1259 1260 // Returns the address of the start of the "block" that contains the 1261 // address "addr". We say "blocks" instead of "object" since some heaps 1262 // may not pack objects densely; a chunk may either be an object or a 1263 // non-object. 1264 virtual HeapWord* block_start(const void* addr) const; 1265 1266 // Requires "addr" to be the start of a chunk, and returns its size. 1267 // "addr + size" is required to be the start of a new chunk, or the end 1268 // of the active area of the heap. 1269 virtual size_t block_size(const HeapWord* addr) const; 1270 1271 // Requires "addr" to be the start of a block, and returns "TRUE" iff 1272 // the block is an object. 1273 virtual bool block_is_obj(const HeapWord* addr) const; 1274 1275 // Section on thread-local allocation buffers (TLABs) 1276 // See CollectedHeap for semantics. 1277 1278 bool supports_tlab_allocation() const; 1279 size_t tlab_capacity(Thread* ignored) const; 1280 size_t tlab_used(Thread* ignored) const; 1281 size_t max_tlab_size() const; 1282 size_t unsafe_max_tlab_alloc(Thread* ignored) const; 1283 1284 // Can a compiler initialize a new object without store barriers? 1285 // This permission only extends from the creation of a new object 1286 // via a TLAB up to the first subsequent safepoint. If such permission 1287 // is granted for this heap type, the compiler promises to call 1288 // defer_store_barrier() below on any slow path allocation of 1289 // a new object for which such initializing store barriers will 1290 // have been elided. G1, like CMS, allows this, but should be 1291 // ready to provide a compensating write barrier as necessary 1292 // if that storage came out of a non-young region. The efficiency 1293 // of this implementation depends crucially on being able to 1294 // answer very efficiently in constant time whether a piece of 1295 // storage in the heap comes from a young region or not. 1296 // See ReduceInitialCardMarks. 1297 virtual bool can_elide_tlab_store_barriers() const { 1298 return true; 1299 } 1300 1301 virtual bool card_mark_must_follow_store() const { 1302 return true; 1303 } 1304 1305 inline bool is_in_young(const oop obj); 1306 1307 // We don't need barriers for initializing stores to objects 1308 // in the young gen: for the SATB pre-barrier, there is no 1309 // pre-value that needs to be remembered; for the remembered-set 1310 // update logging post-barrier, we don't maintain remembered set 1311 // information for young gen objects. 1312 virtual inline bool can_elide_initializing_store_barrier(oop new_obj); 1313 1314 // Returns "true" iff the given word_size is "very large". 1315 static bool is_humongous(size_t word_size) { 1316 // Note this has to be strictly greater-than as the TLABs 1317 // are capped at the humongous threshold and we want to 1318 // ensure that we don't try to allocate a TLAB as 1319 // humongous and that we don't allocate a humongous 1320 // object in a TLAB. 1321 return word_size > _humongous_object_threshold_in_words; 1322 } 1323 1324 // Returns the humongous threshold for a specific region size 1325 static size_t humongous_threshold_for(size_t region_size) { 1326 return (region_size / 2); 1327 } 1328 1329 // Returns the number of regions the humongous object of the given word size 1330 // requires. 1331 static size_t humongous_obj_size_in_regions(size_t word_size); 1332 1333 // Print the maximum heap capacity. 1334 virtual size_t max_capacity() const; 1335 1336 virtual jlong millis_since_last_gc(); 1337 1338 1339 // Convenience function to be used in situations where the heap type can be 1340 // asserted to be this type. 1341 static G1CollectedHeap* heap(); 1342 1343 void set_region_short_lived_locked(HeapRegion* hr); 1344 // add appropriate methods for any other surv rate groups 1345 1346 const G1SurvivorRegions* survivor() const { return &_survivor; } 1347 1348 uint survivor_regions_count() const { 1349 return _survivor.length(); 1350 } 1351 1352 uint eden_regions_count() const { 1353 return _eden.length(); 1354 } 1355 1356 uint young_regions_count() const { 1357 return _eden.length() + _survivor.length(); 1358 } 1359 1360 uint old_regions_count() const { return _old_set.length(); } 1361 1362 uint humongous_regions_count() const { return _humongous_set.length(); } 1363 1364 #ifdef ASSERT 1365 bool check_young_list_empty(); 1366 #endif 1367 1368 // *** Stuff related to concurrent marking. It's not clear to me that so 1369 // many of these need to be public. 1370 1371 // The functions below are helper functions that a subclass of 1372 // "CollectedHeap" can use in the implementation of its virtual 1373 // functions. 1374 // This performs a concurrent marking of the live objects in a 1375 // bitmap off to the side. 1376 void doConcurrentMark(); 1377 1378 bool isMarkedNext(oop obj) const; 1379 1380 // Determine if an object is dead, given the object and also 1381 // the region to which the object belongs. An object is dead 1382 // iff a) it was not allocated since the last mark, b) it 1383 // is not marked, and c) it is not in an archive region. 1384 bool is_obj_dead(const oop obj, const HeapRegion* hr) const { 1385 return 1386 hr->is_obj_dead(obj, _cm->prev_mark_bitmap()) && 1387 !hr->is_archive(); 1388 } 1389 1390 // This function returns true when an object has been 1391 // around since the previous marking and hasn't yet 1392 // been marked during this marking, and is not in an archive region. 1393 bool is_obj_ill(const oop obj, const HeapRegion* hr) const { 1394 return 1395 !hr->obj_allocated_since_next_marking(obj) && 1396 !isMarkedNext(obj) && 1397 !hr->is_archive(); 1398 } 1399 1400 // Determine if an object is dead, given only the object itself. 1401 // This will find the region to which the object belongs and 1402 // then call the region version of the same function. 1403 1404 // Added if it is NULL it isn't dead. 1405 1406 inline bool is_obj_dead(const oop obj) const; 1407 1408 inline bool is_obj_ill(const oop obj) const; 1409 1410 inline bool is_obj_dead_full(const oop obj, const HeapRegion* hr) const; 1411 inline bool is_obj_dead_full(const oop obj) const; 1412 1413 G1ConcurrentMark* concurrent_mark() const { return _cm; } 1414 1415 // Refinement 1416 1417 G1ConcurrentRefine* concurrent_refine() const { return _cr; } 1418 1419 // Optimized nmethod scanning support routines 1420 1421 // Is an oop scavengeable 1422 virtual bool is_scavengable(oop obj); 1423 1424 // Register the given nmethod with the G1 heap. 1425 virtual void register_nmethod(nmethod* nm); 1426 1427 // Unregister the given nmethod from the G1 heap. 1428 virtual void unregister_nmethod(nmethod* nm); 1429 1430 // Free up superfluous code root memory. 1431 void purge_code_root_memory(); 1432 1433 // Rebuild the strong code root lists for each region 1434 // after a full GC. 1435 void rebuild_strong_code_roots(); 1436 1437 // Partial cleaning used when class unloading is disabled. 1438 // Let the caller choose what structures to clean out: 1439 // - StringTable 1440 // - SymbolTable 1441 // - StringDeduplication structures 1442 void partial_cleaning(BoolObjectClosure* is_alive, bool unlink_strings, bool unlink_symbols, bool unlink_string_dedup); 1443 1444 // Complete cleaning used when class unloading is enabled. 1445 // Cleans out all structures handled by partial_cleaning and also the CodeCache. 1446 void complete_cleaning(BoolObjectClosure* is_alive, bool class_unloading_occurred); 1447 1448 // Redirty logged cards in the refinement queue. 1449 void redirty_logged_cards(); 1450 // Verification 1451 1452 // Perform any cleanup actions necessary before allowing a verification. 1453 virtual void prepare_for_verify(); 1454 1455 // Perform verification. 1456 1457 // vo == UsePrevMarking -> use "prev" marking information, 1458 // vo == UseNextMarking -> use "next" marking information 1459 // vo == UseFullMarking -> use "next" marking bitmap but no TAMS 1460 // 1461 // NOTE: Only the "prev" marking information is guaranteed to be 1462 // consistent most of the time, so most calls to this should use 1463 // vo == UsePrevMarking. 1464 // Currently, there is only one case where this is called with 1465 // vo == UseNextMarking, which is to verify the "next" marking 1466 // information at the end of remark. 1467 // Currently there is only one place where this is called with 1468 // vo == UseFullMarking, which is to verify the marking during a 1469 // full GC. 1470 void verify(VerifyOption vo); 1471 1472 // WhiteBox testing support. 1473 virtual bool supports_concurrent_phase_control() const; 1474 virtual const char* const* concurrent_phases() const; 1475 virtual bool request_concurrent_phase(const char* phase); 1476 1477 // The methods below are here for convenience and dispatch the 1478 // appropriate method depending on value of the given VerifyOption 1479 // parameter. The values for that parameter, and their meanings, 1480 // are the same as those above. 1481 1482 bool is_obj_dead_cond(const oop obj, 1483 const HeapRegion* hr, 1484 const VerifyOption vo) const; 1485 1486 bool is_obj_dead_cond(const oop obj, 1487 const VerifyOption vo) const; 1488 1489 G1HeapSummary create_g1_heap_summary(); 1490 G1EvacSummary create_g1_evac_summary(G1EvacStats* stats); 1491 1492 // Printing 1493 private: 1494 void print_heap_regions() const; 1495 void print_regions_on(outputStream* st) const; 1496 1497 public: 1498 virtual void print_on(outputStream* st) const; 1499 virtual void print_extended_on(outputStream* st) const; 1500 virtual void print_on_error(outputStream* st) const; 1501 1502 virtual void print_gc_threads_on(outputStream* st) const; 1503 virtual void gc_threads_do(ThreadClosure* tc) const; 1504 1505 // Override 1506 void print_tracing_info() const; 1507 1508 // The following two methods are helpful for debugging RSet issues. 1509 void print_cset_rsets() PRODUCT_RETURN; 1510 void print_all_rsets() PRODUCT_RETURN; 1511 1512 public: 1513 size_t pending_card_num(); 1514 1515 protected: 1516 size_t _max_heap_capacity; 1517 }; 1518 1519 class G1ParEvacuateFollowersClosure : public VoidClosure { 1520 private: 1521 double _start_term; 1522 double _term_time; 1523 size_t _term_attempts; 1524 1525 void start_term_time() { _term_attempts++; _start_term = os::elapsedTime(); } 1526 void end_term_time() { _term_time += os::elapsedTime() - _start_term; } 1527 protected: 1528 G1CollectedHeap* _g1h; 1529 G1ParScanThreadState* _par_scan_state; 1530 RefToScanQueueSet* _queues; 1531 ParallelTaskTerminator* _terminator; 1532 1533 G1ParScanThreadState* par_scan_state() { return _par_scan_state; } 1534 RefToScanQueueSet* queues() { return _queues; } 1535 ParallelTaskTerminator* terminator() { return _terminator; } 1536 1537 public: 1538 G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h, 1539 G1ParScanThreadState* par_scan_state, 1540 RefToScanQueueSet* queues, 1541 ParallelTaskTerminator* terminator) 1542 : _g1h(g1h), _par_scan_state(par_scan_state), 1543 _queues(queues), _terminator(terminator), 1544 _start_term(0.0), _term_time(0.0), _term_attempts(0) {} 1545 1546 void do_void(); 1547 1548 double term_time() const { return _term_time; } 1549 size_t term_attempts() const { return _term_attempts; } 1550 1551 private: 1552 inline bool offer_termination(); 1553 }; 1554 1555 #endif // SHARE_VM_GC_G1_G1COLLECTEDHEAP_HPP