1 /*
   2  * Copyright (c) 2001, 2021, 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_GC_G1_G1COLLECTEDHEAP_HPP
  26 #define SHARE_GC_G1_G1COLLECTEDHEAP_HPP
  27 
  28 #include "gc/g1/g1BarrierSet.hpp"
  29 #include "gc/g1/g1BiasedArray.hpp"
  30 #include "gc/g1/g1CardSetFreeMemoryTask.hpp"
  31 #include "gc/g1/g1CardTable.hpp"
  32 #include "gc/g1/g1CollectionSet.hpp"
  33 #include "gc/g1/g1CollectorState.hpp"
  34 #include "gc/g1/g1ConcurrentMark.hpp"
  35 #include "gc/g1/g1EdenRegions.hpp"
  36 #include "gc/g1/g1EvacStats.hpp"
  37 #include "gc/g1/g1GCPauseType.hpp"
  38 #include "gc/g1/g1HeapTransition.hpp"
  39 #include "gc/g1/g1HeapVerifier.hpp"
  40 #include "gc/g1/g1HRPrinter.hpp"
  41 #include "gc/g1/g1HeapRegionAttr.hpp"
  42 #include "gc/g1/g1MonitoringSupport.hpp"
  43 #include "gc/g1/g1NUMA.hpp"
  44 #include "gc/g1/g1SurvivorRegions.hpp"
  45 #include "gc/g1/g1YoungGCEvacFailureInjector.hpp"
  46 #include "gc/g1/heapRegionManager.hpp"
  47 #include "gc/g1/heapRegionSet.hpp"
  48 #include "gc/shared/barrierSet.hpp"
  49 #include "gc/shared/collectedHeap.hpp"
  50 #include "gc/shared/gcHeapSummary.hpp"
  51 #include "gc/shared/plab.hpp"
  52 #include "gc/shared/softRefPolicy.hpp"
  53 #include "gc/shared/taskqueue.hpp"
  54 #include "memory/allocation.hpp"
  55 #include "memory/iterator.hpp"
  56 #include "memory/memRegion.hpp"
  57 #include "utilities/bitMap.hpp"
  58 
  59 // A "G1CollectedHeap" is an implementation of a java heap for HotSpot.
  60 // It uses the "Garbage First" heap organization and algorithm, which
  61 // may combine concurrent marking with parallel, incremental compaction of
  62 // heap subsets that will yield large amounts of garbage.
  63 
  64 // Forward declarations
  65 class G1Allocator;
  66 class G1ArchiveAllocator;
  67 class G1BatchedTask;
  68 class G1CardTableEntryClosure;
  69 class G1ConcurrentMark;
  70 class G1ConcurrentMarkThread;
  71 class G1ConcurrentRefine;
  72 class G1GCCounters;
  73 class G1GCPhaseTimes;
  74 class G1HeapSizingPolicy;
  75 class G1HotCardCache;
  76 class G1NewTracer;
  77 class G1RemSet;
  78 class G1ServiceTask;
  79 class G1ServiceThread;
  80 class GCMemoryManager;
  81 class HeapRegion;
  82 class MemoryPool;
  83 class nmethod;
  84 class ReferenceProcessor;
  85 class STWGCTimer;
  86 class SlidingForwarding;
  87 class WorkerThreads;
  88 
  89 typedef OverflowTaskQueue<ScannerTask, mtGC>           G1ScannerTasksQueue;
  90 typedef GenericTaskQueueSet<G1ScannerTasksQueue, mtGC> G1ScannerTasksQueueSet;
  91 
  92 typedef int RegionIdx_t;   // needs to hold [ 0..max_reserved_regions() )
  93 typedef int CardIdx_t;     // needs to hold [ 0..CardsPerRegion )
  94 
  95 // The G1 STW is alive closure.
  96 // An instance is embedded into the G1CH and used as the
  97 // (optional) _is_alive_non_header closure in the STW
  98 // reference processor. It is also extensively used during
  99 // reference processing during STW evacuation pauses.
 100 class G1STWIsAliveClosure : public BoolObjectClosure {
 101   G1CollectedHeap* _g1h;
 102 public:
 103   G1STWIsAliveClosure(G1CollectedHeap* g1h) : _g1h(g1h) {}
 104   bool do_object_b(oop p) override;
 105 };
 106 
 107 class G1STWSubjectToDiscoveryClosure : public BoolObjectClosure {
 108   G1CollectedHeap* _g1h;
 109 public:
 110   G1STWSubjectToDiscoveryClosure(G1CollectedHeap* g1h) : _g1h(g1h) {}
 111   bool do_object_b(oop p) override;
 112 };
 113 
 114 class G1RegionMappingChangedListener : public G1MappingChangedListener {
 115  private:
 116   void reset_from_card_cache(uint start_idx, size_t num_regions);
 117  public:
 118   void on_commit(uint start_idx, size_t num_regions, bool zero_filled) override;
 119 };
 120 
 121 class G1CollectedHeap : public CollectedHeap {
 122   friend class VM_G1CollectForAllocation;
 123   friend class VM_G1CollectFull;
 124   friend class VM_G1TryInitiateConcMark;
 125   friend class VMStructs;
 126   friend class MutatorAllocRegion;
 127   friend class G1FullCollector;
 128   friend class G1GCAllocRegion;
 129   friend class G1HeapVerifier;
 130 
 131   friend class G1YoungGCVerifierMark;
 132 
 133   // Closures used in implementation.
 134   friend class G1EvacuateRegionsTask;
 135   friend class G1PLABAllocator;
 136 
 137   // Other related classes.
 138   friend class G1HeapPrinterMark;
 139   friend class HeapRegionClaimer;
 140 
 141   // Testing classes.
 142   friend class G1CheckRegionAttrTableClosure;
 143 
 144 private:
 145   G1ServiceThread* _service_thread;
 146   G1ServiceTask* _periodic_gc_task;
 147   G1CardSetFreeMemoryTask* _free_card_set_memory_task;
 148 
 149   WorkerThreads* _workers;
 150   G1CardTable* _card_table;
 151 
 152   Ticks _collection_pause_end;
 153 
 154   SoftRefPolicy      _soft_ref_policy;
 155 
 156   static size_t _humongous_object_threshold_in_words;
 157 
 158   // These sets keep track of old, archive and humongous regions respectively.
 159   HeapRegionSet _old_set;
 160   HeapRegionSet _archive_set;
 161   HeapRegionSet _humongous_set;
 162 
 163   // Young gen memory statistics before GC.
 164   G1CardSetMemoryStats _young_gen_card_set_stats;
 165   // Collection set candidates memory statistics after GC.
 166   G1CardSetMemoryStats _collection_set_candidates_card_set_stats;
 167 
 168   // The block offset table for the G1 heap.
 169   G1BlockOffsetTable* _bot;
 170 
 171 public:
 172   void rebuild_free_region_list();
 173   // Start a new incremental collection set for the next pause.
 174   void start_new_collection_set();
 175 
 176   void prepare_region_for_full_compaction(HeapRegion* hr);
 177 
 178 private:
 179   // Rebuilds the region sets / lists so that they are repopulated to
 180   // reflect the contents of the heap. The only exception is the
 181   // humongous set which was not torn down in the first place. If
 182   // free_list_only is true, it will only rebuild the free list.
 183   void rebuild_region_sets(bool free_list_only);
 184 
 185   // Callback for region mapping changed events.
 186   G1RegionMappingChangedListener _listener;
 187 
 188   // Handle G1 NUMA support.
 189   G1NUMA* _numa;
 190 
 191   // The sequence of all heap regions in the heap.
 192   HeapRegionManager _hrm;
 193 
 194   // Manages all allocations with regions except humongous object allocations.
 195   G1Allocator* _allocator;
 196 
 197   G1YoungGCEvacFailureInjector _evac_failure_injector;
 198 
 199   // Manages all heap verification.
 200   G1HeapVerifier* _verifier;
 201 
 202   // Outside of GC pauses, the number of bytes used in all regions other
 203   // than the current allocation region(s).
 204   volatile size_t _summary_bytes_used;
 205 
 206   void increase_used(size_t bytes);
 207   void decrease_used(size_t bytes);
 208 
 209   void set_used(size_t bytes);
 210 
 211   // Number of bytes used in all regions during GC. Typically changed when
 212   // retiring a GC alloc region.
 213   size_t _bytes_used_during_gc;
 214 
 215 public:
 216   size_t bytes_used_during_gc() const { return _bytes_used_during_gc; }
 217 
 218 private:
 219   // Class that handles archive allocation ranges.
 220   G1ArchiveAllocator* _archive_allocator;
 221 
 222   // GC allocation statistics policy for survivors.
 223   G1EvacStats _survivor_evac_stats;
 224 
 225   // GC allocation statistics policy for tenured objects.
 226   G1EvacStats _old_evac_stats;
 227 
 228   // Helper for monitoring and management support.
 229   G1MonitoringSupport* _monitoring_support;
 230 
 231   SlidingForwarding* _forwarding;
 232 
 233   // Records whether the region at the given index is (still) a
 234   // candidate for eager reclaim.  Only valid for humongous start
 235   // regions; other regions have unspecified values.  Humongous start
 236   // regions are initialized at start of collection pause, with
 237   // candidates removed from the set as they are found reachable from
 238   // roots or the young generation.
 239   class HumongousReclaimCandidates : public G1BiasedMappedArray<bool> {
 240   protected:
 241     bool default_value() const override { return false; }
 242   public:
 243     void clear() { G1BiasedMappedArray<bool>::clear(); }
 244     void set_candidate(uint region, bool value) {
 245       set_by_index(region, value);
 246     }
 247     bool is_candidate(uint region) {
 248       return get_by_index(region);
 249     }
 250   };
 251 
 252   HumongousReclaimCandidates _humongous_reclaim_candidates;
 253   uint _num_humongous_objects; // Current amount of (all) humongous objects found in the heap.
 254   uint _num_humongous_reclaim_candidates; // Number of humongous object eager reclaim candidates.
 255 public:
 256   uint num_humongous_objects() const { return _num_humongous_objects; }
 257   uint num_humongous_reclaim_candidates() const { return _num_humongous_reclaim_candidates; }
 258   bool has_humongous_reclaim_candidates() const { return _num_humongous_reclaim_candidates > 0; }
 259 
 260   bool should_do_eager_reclaim() const;
 261 
 262   void set_humongous_stats(uint num_humongous_total, uint num_humongous_candidates);
 263 
 264   bool should_sample_collection_set_candidates() const;
 265   void set_collection_set_candidates_stats(G1CardSetMemoryStats& stats);
 266   void set_young_gen_card_set_stats(const G1CardSetMemoryStats& stats);
 267 
 268   SlidingForwarding* forwarding() const {
 269     return _forwarding;
 270   }
 271 
 272 private:
 273 
 274   G1HRPrinter _hr_printer;
 275 
 276   // Return true if an explicit GC should start a concurrent cycle instead
 277   // of doing a STW full GC. A concurrent cycle should be started if:
 278   // (a) cause == _g1_humongous_allocation,
 279   // (b) cause == _java_lang_system_gc and +ExplicitGCInvokesConcurrent,
 280   // (c) cause == _dcmd_gc_run and +ExplicitGCInvokesConcurrent,
 281   // (d) cause == _wb_conc_mark or _wb_breakpoint,
 282   // (e) cause == _g1_periodic_collection and +G1PeriodicGCInvokesConcurrent.
 283   bool should_do_concurrent_full_gc(GCCause::Cause cause);
 284 
 285   // Attempt to start a concurrent cycle with the indicated cause.
 286   // precondition: should_do_concurrent_full_gc(cause)
 287   bool try_collect_concurrently(GCCause::Cause cause,
 288                                 uint gc_counter,
 289                                 uint old_marking_started_before);
 290 
 291   // indicates whether we are in young or mixed GC mode
 292   G1CollectorState _collector_state;
 293 
 294   // Keeps track of how many "old marking cycles" (i.e., Full GCs or
 295   // concurrent cycles) we have started.
 296   volatile uint _old_marking_cycles_started;
 297 
 298   // Keeps track of how many "old marking cycles" (i.e., Full GCs or
 299   // concurrent cycles) we have completed.
 300   volatile uint _old_marking_cycles_completed;
 301 
 302   // This is a non-product method that is helpful for testing. It is
 303   // called at the end of a GC and artificially expands the heap by
 304   // allocating a number of dead regions. This way we can induce very
 305   // frequent marking cycles and stress the cleanup / concurrent
 306   // cleanup code more (as all the regions that will be allocated by
 307   // this method will be found dead by the marking cycle).
 308   void allocate_dummy_regions() PRODUCT_RETURN;
 309 
 310   // Create a memory mapper for auxiliary data structures of the given size and
 311   // translation factor.
 312   static G1RegionToSpaceMapper* create_aux_memory_mapper(const char* description,
 313                                                          size_t size,
 314                                                          size_t translation_factor);
 315 
 316   void trace_heap(GCWhen::Type when, const GCTracer* tracer) override;
 317 
 318   // These are macros so that, if the assert fires, we get the correct
 319   // line number, file, etc.
 320 
 321 #define heap_locking_asserts_params(_extra_message_)                          \
 322   "%s : Heap_lock locked: %s, at safepoint: %s, is VM thread: %s",            \
 323   (_extra_message_),                                                          \
 324   BOOL_TO_STR(Heap_lock->owned_by_self()),                                    \
 325   BOOL_TO_STR(SafepointSynchronize::is_at_safepoint()),                       \
 326   BOOL_TO_STR(Thread::current()->is_VM_thread())
 327 
 328 #define assert_heap_locked()                                                  \
 329   do {                                                                        \
 330     assert(Heap_lock->owned_by_self(),                                        \
 331            heap_locking_asserts_params("should be holding the Heap_lock"));   \
 332   } while (0)
 333 
 334 #define assert_heap_locked_or_at_safepoint(_should_be_vm_thread_)             \
 335   do {                                                                        \
 336     assert(Heap_lock->owned_by_self() ||                                      \
 337            (SafepointSynchronize::is_at_safepoint() &&                        \
 338              ((_should_be_vm_thread_) == Thread::current()->is_VM_thread())), \
 339            heap_locking_asserts_params("should be holding the Heap_lock or "  \
 340                                         "should be at a safepoint"));         \
 341   } while (0)
 342 
 343 #define assert_heap_locked_and_not_at_safepoint()                             \
 344   do {                                                                        \
 345     assert(Heap_lock->owned_by_self() &&                                      \
 346                                     !SafepointSynchronize::is_at_safepoint(), \
 347           heap_locking_asserts_params("should be holding the Heap_lock and "  \
 348                                        "should not be at a safepoint"));      \
 349   } while (0)
 350 
 351 #define assert_heap_not_locked()                                              \
 352   do {                                                                        \
 353     assert(!Heap_lock->owned_by_self(),                                       \
 354         heap_locking_asserts_params("should not be holding the Heap_lock"));  \
 355   } while (0)
 356 
 357 #define assert_heap_not_locked_and_not_at_safepoint()                         \
 358   do {                                                                        \
 359     assert(!Heap_lock->owned_by_self() &&                                     \
 360                                     !SafepointSynchronize::is_at_safepoint(), \
 361       heap_locking_asserts_params("should not be holding the Heap_lock and "  \
 362                                    "should not be at a safepoint"));          \
 363   } while (0)
 364 
 365 #define assert_at_safepoint_on_vm_thread()                                    \
 366   do {                                                                        \
 367     assert_at_safepoint();                                                    \
 368     assert(Thread::current_or_null() != NULL, "no current thread");           \
 369     assert(Thread::current()->is_VM_thread(), "current thread is not VM thread"); \
 370   } while (0)
 371 
 372 #ifdef ASSERT
 373 #define assert_used_and_recalculate_used_equal(g1h)                           \
 374   do {                                                                        \
 375     size_t cur_used_bytes = g1h->used();                                      \
 376     size_t recal_used_bytes = g1h->recalculate_used();                        \
 377     assert(cur_used_bytes == recal_used_bytes, "Used(" SIZE_FORMAT ") is not" \
 378            " same as recalculated used(" SIZE_FORMAT ").",                    \
 379            cur_used_bytes, recal_used_bytes);                                 \
 380   } while (0)
 381 #else
 382 #define assert_used_and_recalculate_used_equal(g1h) do {} while(0)
 383 #endif
 384 
 385   // The young region list.
 386   G1EdenRegions _eden;
 387   G1SurvivorRegions _survivor;
 388 
 389   STWGCTimer* _gc_timer_stw;
 390 
 391   G1NewTracer* _gc_tracer_stw;
 392 
 393   // The current policy object for the collector.
 394   G1Policy* _policy;
 395   G1HeapSizingPolicy* _heap_sizing_policy;
 396 
 397   G1CollectionSet _collection_set;
 398 
 399   // Try to allocate a single non-humongous HeapRegion sufficient for
 400   // an allocation of the given word_size. If do_expand is true,
 401   // attempt to expand the heap if necessary to satisfy the allocation
 402   // request. 'type' takes the type of region to be allocated. (Use constants
 403   // Old, Eden, Humongous, Survivor defined in HeapRegionType.)
 404   HeapRegion* new_region(size_t word_size,
 405                          HeapRegionType type,
 406                          bool do_expand,
 407                          uint node_index = G1NUMA::AnyNodeIndex);
 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(HeapRegion* first_hr,
 413                                                       uint num_regions,
 414                                                       size_t word_size);
 415 
 416   // Attempt to allocate a humongous object of the given size. Return
 417   // NULL if unsuccessful.
 418   HeapWord* humongous_obj_allocate(size_t word_size);
 419 
 420   // The following two methods, allocate_new_tlab() and
 421   // mem_allocate(), are the two main entry points from the runtime
 422   // into the G1's allocation routines. They have the following
 423   // assumptions:
 424   //
 425   // * They should both be called outside safepoints.
 426   //
 427   // * They should both be called without holding the Heap_lock.
 428   //
 429   // * All allocation requests for new TLABs should go to
 430   //   allocate_new_tlab().
 431   //
 432   // * All non-TLAB allocation requests should go to mem_allocate().
 433   //
 434   // * If either call cannot satisfy the allocation request using the
 435   //   current allocating region, they will try to get a new one. If
 436   //   this fails, they will attempt to do an evacuation pause and
 437   //   retry the allocation.
 438   //
 439   // * If all allocation attempts fail, even after trying to schedule
 440   //   an evacuation pause, allocate_new_tlab() will return NULL,
 441   //   whereas mem_allocate() will attempt a heap expansion and/or
 442   //   schedule a Full GC.
 443   //
 444   // * We do not allow humongous-sized TLABs. So, allocate_new_tlab
 445   //   should never be called with word_size being humongous. All
 446   //   humongous allocation requests should go to mem_allocate() which
 447   //   will satisfy them with a special path.
 448 
 449   HeapWord* allocate_new_tlab(size_t min_size,
 450                               size_t requested_size,
 451                               size_t* actual_size) override;
 452 
 453   HeapWord* mem_allocate(size_t word_size,
 454                          bool*  gc_overhead_limit_was_exceeded) override;
 455 
 456   // First-level mutator allocation attempt: try to allocate out of
 457   // the mutator alloc region without taking the Heap_lock. This
 458   // should only be used for non-humongous allocations.
 459   inline HeapWord* attempt_allocation(size_t min_word_size,
 460                                       size_t desired_word_size,
 461                                       size_t* actual_word_size);
 462 
 463   // Second-level mutator allocation attempt: take the Heap_lock and
 464   // retry the allocation attempt, potentially scheduling a GC
 465   // pause. This should only be used for non-humongous allocations.
 466   HeapWord* attempt_allocation_slow(size_t word_size);
 467 
 468   // Takes the Heap_lock and attempts a humongous allocation. It can
 469   // potentially schedule a GC pause.
 470   HeapWord* attempt_allocation_humongous(size_t word_size);
 471 
 472   // Allocation attempt that should be called during safepoints (e.g.,
 473   // at the end of a successful GC). expect_null_mutator_alloc_region
 474   // specifies whether the mutator alloc region is expected to be NULL
 475   // or not.
 476   HeapWord* attempt_allocation_at_safepoint(size_t word_size,
 477                                             bool expect_null_mutator_alloc_region);
 478 
 479   // These methods are the "callbacks" from the G1AllocRegion class.
 480 
 481   // For mutator alloc regions.
 482   HeapRegion* new_mutator_alloc_region(size_t word_size, bool force, uint node_index);
 483   void retire_mutator_alloc_region(HeapRegion* alloc_region,
 484                                    size_t allocated_bytes);
 485 
 486   // For GC alloc regions.
 487   bool has_more_regions(G1HeapRegionAttr dest);
 488   HeapRegion* new_gc_alloc_region(size_t word_size, G1HeapRegionAttr dest, uint node_index);
 489   void retire_gc_alloc_region(HeapRegion* alloc_region,
 490                               size_t allocated_bytes, G1HeapRegionAttr dest);
 491 
 492   // - if explicit_gc is true, the GC is for a System.gc() etc,
 493   //   otherwise it's for a failed allocation.
 494   // - if clear_all_soft_refs is true, all soft references should be
 495   //   cleared during the GC.
 496   // - if do_maximum_compaction is true, full gc will do a maximally
 497   //   compacting collection, leaving no dead wood.
 498   // - it returns false if it is unable to do the collection due to the
 499   //   GC locker being active, true otherwise.
 500   bool do_full_collection(bool explicit_gc,
 501                           bool clear_all_soft_refs,
 502                           bool do_maximum_compaction);
 503 
 504   // Callback from VM_G1CollectFull operation, or collect_as_vm_thread.
 505   void do_full_collection(bool clear_all_soft_refs) override;
 506 
 507   // Helper to do a full collection that clears soft references.
 508   bool upgrade_to_full_collection();
 509 
 510   // Callback from VM_G1CollectForAllocation operation.
 511   // This function does everything necessary/possible to satisfy a
 512   // failed allocation request (including collection, expansion, etc.)
 513   HeapWord* satisfy_failed_allocation(size_t word_size,
 514                                       bool* succeeded);
 515   // Internal helpers used during full GC to split it up to
 516   // increase readability.
 517   void abort_concurrent_cycle();
 518   void verify_before_full_collection(bool explicit_gc);
 519   void prepare_heap_for_full_collection();
 520   void prepare_heap_for_mutators();
 521   void abort_refinement();
 522   void verify_after_full_collection();
 523   void print_heap_after_full_collection();
 524 
 525   // Helper method for satisfy_failed_allocation()
 526   HeapWord* satisfy_failed_allocation_helper(size_t word_size,
 527                                              bool do_gc,
 528                                              bool maximum_compaction,
 529                                              bool expect_null_mutator_alloc_region,
 530                                              bool* gc_succeeded);
 531 
 532   // Attempting to expand the heap sufficiently
 533   // to support an allocation of the given "word_size".  If
 534   // successful, perform the allocation and return the address of the
 535   // allocated block, or else "NULL".
 536   HeapWord* expand_and_allocate(size_t word_size);
 537 
 538   void verify_numa_regions(const char* desc);
 539 
 540 public:
 541   // If during a concurrent start pause we may install a pending list head which is not
 542   // otherwise reachable, ensure that it is marked in the bitmap for concurrent marking
 543   // to discover.
 544   void make_pending_list_reachable();
 545 
 546   G1ServiceThread* service_thread() const { return _service_thread; }
 547 
 548   WorkerThreads* workers() const { return _workers; }
 549 
 550   // Run the given batch task using the workers.
 551   void run_batch_task(G1BatchedTask* cl);
 552 
 553   G1Allocator* allocator() {
 554     return _allocator;
 555   }
 556 
 557   G1YoungGCEvacFailureInjector* evac_failure_injector() { return &_evac_failure_injector; }
 558 
 559   G1HeapVerifier* verifier() {
 560     return _verifier;
 561   }
 562 
 563   G1MonitoringSupport* monitoring_support() {
 564     assert(_monitoring_support != nullptr, "should have been initialized");
 565     return _monitoring_support;
 566   }
 567 
 568   void resize_heap_if_necessary();
 569 
 570   // Check if there is memory to uncommit and if so schedule a task to do it.
 571   void uncommit_regions_if_necessary();
 572   // Immediately uncommit uncommittable regions.
 573   uint uncommit_regions(uint region_limit);
 574   bool has_uncommittable_regions();
 575 
 576   G1NUMA* numa() const { return _numa; }
 577 
 578   // Expand the garbage-first heap by at least the given size (in bytes!).
 579   // Returns true if the heap was expanded by the requested amount;
 580   // false otherwise.
 581   // (Rounds up to a HeapRegion boundary.)
 582   bool expand(size_t expand_bytes, WorkerThreads* pretouch_workers = NULL, double* expand_time_ms = NULL);
 583   bool expand_single_region(uint node_index);
 584 
 585   // Returns the PLAB statistics for a given destination.
 586   inline G1EvacStats* alloc_buffer_stats(G1HeapRegionAttr dest);
 587 
 588   // Determines PLAB size for a given destination.
 589   inline size_t desired_plab_sz(G1HeapRegionAttr dest);
 590 
 591   // Do anything common to GC's.
 592   void gc_prologue(bool full);
 593   void gc_epilogue(bool full);
 594 
 595   // Does the given region fulfill remembered set based eager reclaim candidate requirements?
 596   bool is_potential_eager_reclaim_candidate(HeapRegion* r) const;
 597 
 598   // Modify the reclaim candidate set and test for presence.
 599   // These are only valid for starts_humongous regions.
 600   inline void set_humongous_reclaim_candidate(uint region, bool value);
 601   inline bool is_humongous_reclaim_candidate(uint region);
 602 
 603   // Remove from the reclaim candidate set.  Also remove from the
 604   // collection set so that later encounters avoid the slow path.
 605   inline void set_humongous_is_live(oop obj);
 606 
 607   // Register the given region to be part of the collection set.
 608   inline void register_humongous_region_with_region_attr(uint index);
 609 
 610   // We register a region with the fast "in collection set" test. We
 611   // simply set to true the array slot corresponding to this region.
 612   void register_young_region_with_region_attr(HeapRegion* r) {
 613     _region_attr.set_in_young(r->hrm_index());
 614   }
 615   inline void register_new_survivor_region_with_region_attr(HeapRegion* r);
 616   inline void register_region_with_region_attr(HeapRegion* r);
 617   inline void register_old_region_with_region_attr(HeapRegion* r);
 618   inline void register_optional_region_with_region_attr(HeapRegion* r);
 619 
 620   void clear_region_attr(const HeapRegion* hr) {
 621     _region_attr.clear(hr);
 622   }
 623 
 624   void clear_region_attr() {
 625     _region_attr.clear();
 626   }
 627 
 628   // Verify that the G1RegionAttr remset tracking corresponds to actual remset tracking
 629   // for all regions.
 630   void verify_region_attr_remset_is_tracked() PRODUCT_RETURN;
 631 
 632   bool is_user_requested_concurrent_full_gc(GCCause::Cause cause);
 633 
 634   // This is called at the start of either a concurrent cycle or a Full
 635   // GC to update the number of old marking cycles started.
 636   void increment_old_marking_cycles_started();
 637 
 638   // This is called at the end of either a concurrent cycle or a Full
 639   // GC to update the number of old marking cycles completed. Those two
 640   // can happen in a nested fashion, i.e., we start a concurrent
 641   // cycle, a Full GC happens half-way through it which ends first,
 642   // and then the cycle notices that a Full GC happened and ends
 643   // too. The concurrent parameter is a boolean to help us do a bit
 644   // tighter consistency checking in the method. If concurrent is
 645   // false, the caller is the inner caller in the nesting (i.e., the
 646   // Full GC). If concurrent is true, the caller is the outer caller
 647   // in this nesting (i.e., the concurrent cycle). Further nesting is
 648   // not currently supported. The end of this call also notifies
 649   // the G1OldGCCount_lock in case a Java thread is waiting for a full
 650   // GC to happen (e.g., it called System.gc() with
 651   // +ExplicitGCInvokesConcurrent).
 652   // whole_heap_examined should indicate that during that old marking
 653   // cycle the whole heap has been examined for live objects (as opposed
 654   // to only parts, or aborted before completion).
 655   void increment_old_marking_cycles_completed(bool concurrent, bool whole_heap_examined);
 656 
 657   uint old_marking_cycles_started() const {
 658     return _old_marking_cycles_started;
 659   }
 660 
 661   uint old_marking_cycles_completed() const {
 662     return _old_marking_cycles_completed;
 663   }
 664 
 665   G1HRPrinter* hr_printer() { return &_hr_printer; }
 666 
 667   // Allocates a new heap region instance.
 668   HeapRegion* new_heap_region(uint hrs_index, MemRegion mr);
 669 
 670   // Allocate the highest free region in the reserved heap. This will commit
 671   // regions as necessary.
 672   HeapRegion* alloc_highest_free_region();
 673 
 674   // Frees a region by resetting its metadata and adding it to the free list
 675   // passed as a parameter (this is usually a local list which will be appended
 676   // to the master free list later or NULL if free list management is handled
 677   // in another way).
 678   // Callers must ensure they are the only one calling free on the given region
 679   // at the same time.
 680   void free_region(HeapRegion* hr, FreeRegionList* free_list);
 681 
 682   // It dirties the cards that cover the block so that the post
 683   // write barrier never queues anything when updating objects on this
 684   // block. It is assumed (and in fact we assert) that the block
 685   // belongs to a young region.
 686   inline void dirty_young_block(HeapWord* start, size_t word_size);
 687 
 688   // Frees a humongous region by collapsing it into individual regions
 689   // and calling free_region() for each of them. The freed regions
 690   // will be added to the free list that's passed as a parameter (this
 691   // is usually a local list which will be appended to the master free
 692   // list later).
 693   // The method assumes that only a single thread is ever calling
 694   // this for a particular region at once.
 695   void free_humongous_region(HeapRegion* hr,
 696                              FreeRegionList* free_list);
 697 
 698   // Facility for allocating in 'archive' regions in high heap memory and
 699   // recording the allocated ranges. These should all be called from the
 700   // VM thread at safepoints, without the heap lock held. They can be used
 701   // to create and archive a set of heap regions which can be mapped at the
 702   // same fixed addresses in a subsequent JVM invocation.
 703   void begin_archive_alloc_range(bool open = false);
 704 
 705   // Check if the requested size would be too large for an archive allocation.
 706   bool is_archive_alloc_too_large(size_t word_size);
 707 
 708   // Allocate memory of the requested size from the archive region. This will
 709   // return NULL if the size is too large or if no memory is available. It
 710   // does not trigger a garbage collection.
 711   HeapWord* archive_mem_allocate(size_t word_size);
 712 
 713   // Optionally aligns the end address and returns the allocated ranges in
 714   // an array of MemRegions in order of ascending addresses.
 715   void end_archive_alloc_range(GrowableArray<MemRegion>* ranges,
 716                                size_t end_alignment_in_bytes = 0);
 717 
 718   // Facility for allocating a fixed range within the heap and marking
 719   // the containing regions as 'archive'. For use at JVM init time, when the
 720   // caller may mmap archived heap data at the specified range(s).
 721   // Verify that the MemRegions specified in the argument array are within the
 722   // reserved heap.
 723   bool check_archive_addresses(MemRegion* range, size_t count);
 724 
 725   // Commit the appropriate G1 regions containing the specified MemRegions
 726   // and mark them as 'archive' regions. The regions in the array must be
 727   // non-overlapping and in order of ascending address.
 728   bool alloc_archive_regions(MemRegion* range, size_t count, bool open);
 729 
 730   // Insert any required filler objects in the G1 regions around the specified
 731   // ranges to make the regions parseable. This must be called after
 732   // alloc_archive_regions, and after class loading has occurred.
 733   void fill_archive_regions(MemRegion* range, size_t count);
 734 
 735   // Populate the G1BlockOffsetTablePart for archived regions with the given
 736   // memory ranges.
 737   void populate_archive_regions_bot_part(MemRegion* range, size_t count);
 738 
 739   // For each of the specified MemRegions, uncommit the containing G1 regions
 740   // which had been allocated by alloc_archive_regions. This should be called
 741   // rather than fill_archive_regions at JVM init time if the archive file
 742   // mapping failed, with the same non-overlapping and sorted MemRegion array.
 743   void dealloc_archive_regions(MemRegion* range, size_t count);
 744 
 745 private:
 746 
 747   // Shrink the garbage-first heap by at most the given size (in bytes!).
 748   // (Rounds down to a HeapRegion boundary.)
 749   void shrink(size_t shrink_bytes);
 750   void shrink_helper(size_t expand_bytes);
 751 
 752   // Schedule the VM operation that will do an evacuation pause to
 753   // satisfy an allocation request of word_size. *succeeded will
 754   // return whether the VM operation was successful (it did do an
 755   // evacuation pause) or not (another thread beat us to it or the GC
 756   // locker was active). Given that we should not be holding the
 757   // Heap_lock when we enter this method, we will pass the
 758   // gc_count_before (i.e., total_collections()) as a parameter since
 759   // it has to be read while holding the Heap_lock. Currently, both
 760   // methods that call do_collection_pause() release the Heap_lock
 761   // before the call, so it's easy to read gc_count_before just before.
 762   HeapWord* do_collection_pause(size_t         word_size,
 763                                 uint           gc_count_before,
 764                                 bool*          succeeded,
 765                                 GCCause::Cause gc_cause);
 766 
 767   // Perform an incremental collection at a safepoint, possibly
 768   // followed by a by-policy upgrade to a full collection.  Returns
 769   // false if unable to do the collection due to the GC locker being
 770   // active, true otherwise.
 771   // precondition: at safepoint on VM thread
 772   // precondition: !is_gc_active()
 773   bool do_collection_pause_at_safepoint(double target_pause_time_ms);
 774 
 775   // Helper for do_collection_pause_at_safepoint, containing the guts
 776   // of the incremental collection pause, executed by the vm thread.
 777   void do_collection_pause_at_safepoint_helper(double target_pause_time_ms);
 778 
 779   G1HeapVerifier::G1VerifyType young_collection_verify_type() const;
 780   void verify_before_young_collection(G1HeapVerifier::G1VerifyType type);
 781   void verify_after_young_collection(G1HeapVerifier::G1VerifyType type);
 782 
 783 public:
 784   // Start a concurrent cycle.
 785   void start_concurrent_cycle(bool concurrent_operation_is_full_mark);
 786 
 787   void prepare_tlabs_for_mutator();
 788 
 789   void retire_tlabs();
 790 
 791   void expand_heap_after_young_collection();
 792   // Update object copying statistics.
 793   void record_obj_copy_mem_stats();
 794 
 795 private:
 796   // The hot card cache for remembered set insertion optimization.
 797   G1HotCardCache* _hot_card_cache;
 798 
 799   // The g1 remembered set of the heap.
 800   G1RemSet* _rem_set;
 801   // Global card set configuration
 802   G1CardSetConfiguration _card_set_config;
 803 
 804 public:
 805   // After a collection pause, reset eden and the collection set.
 806   void clear_eden();
 807   void clear_collection_set();
 808 
 809   // Abandon the current collection set without recording policy
 810   // statistics or updating free lists.
 811   void abandon_collection_set(G1CollectionSet* collection_set);
 812 
 813   // The concurrent marker (and the thread it runs in.)
 814   G1ConcurrentMark* _cm;
 815   G1ConcurrentMarkThread* _cm_thread;
 816 
 817   // The concurrent refiner.
 818   G1ConcurrentRefine* _cr;
 819 
 820   // The parallel task queues
 821   G1ScannerTasksQueueSet *_task_queues;
 822 
 823   // ("Weak") Reference processing support.
 824   //
 825   // G1 has 2 instances of the reference processor class.
 826   //
 827   // One (_ref_processor_cm) handles reference object discovery and subsequent
 828   // processing during concurrent marking cycles. Discovery is enabled/disabled
 829   // at the start/end of a concurrent marking cycle.
 830   //
 831   // The other (_ref_processor_stw) handles reference object discovery and
 832   // processing during incremental evacuation pauses and full GC pauses.
 833   //
 834   // ## Incremental evacuation pauses
 835   //
 836   // STW ref processor discovery is enabled/disabled at the start/end of an
 837   // incremental evacuation pause. No particular handling of the CM ref
 838   // processor is needed, apart from treating the discovered references as
 839   // roots; CM discovery does not need to be temporarily disabled as all
 840   // marking threads are paused during incremental evacuation pauses.
 841   //
 842   // ## Full GC pauses
 843   //
 844   // We abort any ongoing concurrent marking cycle, disable CM discovery, and
 845   // temporarily substitute a new closure for the STW ref processor's
 846   // _is_alive_non_header field (old value is restored after the full GC). Then
 847   // STW ref processor discovery is enabled, and marking & compaction
 848   // commences.
 849 
 850   // The (stw) reference processor...
 851   ReferenceProcessor* _ref_processor_stw;
 852 
 853   // During reference object discovery, the _is_alive_non_header
 854   // closure (if non-null) is applied to the referent object to
 855   // determine whether the referent is live. If so then the
 856   // reference object does not need to be 'discovered' and can
 857   // be treated as a regular oop. This has the benefit of reducing
 858   // the number of 'discovered' reference objects that need to
 859   // be processed.
 860   //
 861   // Instance of the is_alive closure for embedding into the
 862   // STW reference processor as the _is_alive_non_header field.
 863   // Supplying a value for the _is_alive_non_header field is
 864   // optional but doing so prevents unnecessary additions to
 865   // the discovered lists during reference discovery.
 866   G1STWIsAliveClosure _is_alive_closure_stw;
 867 
 868   G1STWSubjectToDiscoveryClosure _is_subject_to_discovery_stw;
 869 
 870   // The (concurrent marking) reference processor...
 871   ReferenceProcessor* _ref_processor_cm;
 872 
 873   // Instance of the concurrent mark is_alive closure for embedding
 874   // into the Concurrent Marking reference processor as the
 875   // _is_alive_non_header field. Supplying a value for the
 876   // _is_alive_non_header field is optional but doing so prevents
 877   // unnecessary additions to the discovered lists during reference
 878   // discovery.
 879   G1CMIsAliveClosure _is_alive_closure_cm;
 880 
 881   G1CMSubjectToDiscoveryClosure _is_subject_to_discovery_cm;
 882 public:
 883 
 884   G1ScannerTasksQueueSet* task_queues() const;
 885   G1ScannerTasksQueue* task_queue(uint i) const;
 886 
 887   // Create a G1CollectedHeap.
 888   // Must call the initialize method afterwards.
 889   // May not return if something goes wrong.
 890   G1CollectedHeap();
 891 
 892 private:
 893   jint initialize_concurrent_refinement();
 894   jint initialize_service_thread();
 895 public:
 896   // Initialize the G1CollectedHeap to have the initial and
 897   // maximum sizes and remembered and barrier sets
 898   // specified by the policy object.
 899   jint initialize() override;
 900 
 901   // Returns whether concurrent mark threads (and the VM) are about to terminate.
 902   bool concurrent_mark_is_terminating() const;
 903 
 904   void stop() override;
 905   void safepoint_synchronize_begin() override;
 906   void safepoint_synchronize_end() override;
 907 
 908   // Does operations required after initialization has been done.
 909   void post_initialize() override;
 910 
 911   // Initialize weak reference processing.
 912   void ref_processing_init();
 913 
 914   Name kind() const override {
 915     return CollectedHeap::G1;
 916   }
 917 
 918   const char* name() const override {
 919     return "G1";
 920   }
 921 
 922   const G1CollectorState* collector_state() const { return &_collector_state; }
 923   G1CollectorState* collector_state() { return &_collector_state; }
 924 
 925   // The current policy object for the collector.
 926   G1Policy* policy() const { return _policy; }
 927   // The remembered set.
 928   G1RemSet* rem_set() const { return _rem_set; }
 929 
 930   inline G1GCPhaseTimes* phase_times() const;
 931 
 932   const G1CollectionSet* collection_set() const { return &_collection_set; }
 933   G1CollectionSet* collection_set() { return &_collection_set; }
 934 
 935   SoftRefPolicy* soft_ref_policy() override;
 936 
 937   void initialize_serviceability() override;
 938   MemoryUsage memory_usage() override;
 939   GrowableArray<GCMemoryManager*> memory_managers() override;
 940   GrowableArray<MemoryPool*> memory_pools() override;
 941 
 942   void fill_with_dummy_object(HeapWord* start, HeapWord* end, bool zap) override;
 943 
 944   // Apply the given closure on all cards in the Hot Card Cache, emptying it.
 945   void iterate_hcc_closure(G1CardTableEntryClosure* cl, uint worker_id);
 946 
 947   // The shared block offset table array.
 948   G1BlockOffsetTable* bot() const { return _bot; }
 949 
 950   // Reference Processing accessors
 951 
 952   // The STW reference processor....
 953   ReferenceProcessor* ref_processor_stw() const { return _ref_processor_stw; }
 954 
 955   G1NewTracer* gc_tracer_stw() const { return _gc_tracer_stw; }
 956   STWGCTimer* gc_timer_stw() const { return _gc_timer_stw; }
 957 
 958   // The Concurrent Marking reference processor...
 959   ReferenceProcessor* ref_processor_cm() const { return _ref_processor_cm; }
 960 
 961   size_t unused_committed_regions_in_bytes() const;
 962 
 963   size_t capacity() const override;
 964   size_t used() const override;
 965   // This should be called when we're not holding the heap lock. The
 966   // result might be a bit inaccurate.
 967   size_t used_unlocked() const;
 968   size_t recalculate_used() const;
 969 
 970   // These virtual functions do the actual allocation.
 971   // Some heaps may offer a contiguous region for shared non-blocking
 972   // allocation, via inlined code (by exporting the address of the top and
 973   // end fields defining the extent of the contiguous allocation region.)
 974   // But G1CollectedHeap doesn't yet support this.
 975 
 976   bool is_maximal_no_gc() const override {
 977     return _hrm.available() == 0;
 978   }
 979 
 980   // Returns true if an incremental GC should be upgrade to a full gc. This
 981   // is done when there are no free regions and the heap can't be expanded.
 982   bool should_upgrade_to_full_gc() const {
 983     return is_maximal_no_gc() && num_free_regions() == 0;
 984   }
 985 
 986   // The current number of regions in the heap.
 987   uint num_regions() const { return _hrm.length(); }
 988 
 989   // The max number of regions reserved for the heap. Except for static array
 990   // sizing purposes you probably want to use max_regions().
 991   uint max_reserved_regions() const { return _hrm.reserved_length(); }
 992 
 993   // Max number of regions that can be committed.
 994   uint max_regions() const { return _hrm.max_length(); }
 995 
 996   // The number of regions that are completely free.
 997   uint num_free_regions() const { return _hrm.num_free_regions(); }
 998 
 999   // The number of regions that can be allocated into.
1000   uint num_free_or_available_regions() const { return num_free_regions() + _hrm.available(); }
1001 
1002   MemoryUsage get_auxiliary_data_memory_usage() const {
1003     return _hrm.get_auxiliary_data_memory_usage();
1004   }
1005 
1006   // The number of regions that are not completely free.
1007   uint num_used_regions() const { return num_regions() - num_free_regions(); }
1008 
1009 #ifdef ASSERT
1010   bool is_on_master_free_list(HeapRegion* hr) {
1011     return _hrm.is_free(hr);
1012   }
1013 #endif // ASSERT
1014 
1015   inline void old_set_add(HeapRegion* hr);
1016   inline void old_set_remove(HeapRegion* hr);
1017 
1018   inline void archive_set_add(HeapRegion* hr);
1019 
1020   size_t non_young_capacity_bytes() {
1021     return (old_regions_count() + _archive_set.length() + humongous_regions_count()) * HeapRegion::GrainBytes;
1022   }
1023 
1024   // Determine whether the given region is one that we are using as an
1025   // old GC alloc region.
1026   bool is_old_gc_alloc_region(HeapRegion* hr);
1027 
1028   // Perform a collection of the heap; intended for use in implementing
1029   // "System.gc".  This probably implies as full a collection as the
1030   // "CollectedHeap" supports.
1031   void collect(GCCause::Cause cause) override;
1032 
1033   // Perform a collection of the heap with the given cause.
1034   // Returns whether this collection actually executed.
1035   bool try_collect(GCCause::Cause cause, const G1GCCounters& counters_before);
1036 
1037   void start_concurrent_gc_for_metadata_allocation(GCCause::Cause gc_cause);
1038 
1039   void remove_from_old_gen_sets(const uint old_regions_removed,
1040                                 const uint archive_regions_removed,
1041                                 const uint humongous_regions_removed);
1042   void prepend_to_freelist(FreeRegionList* list);
1043   void decrement_summary_bytes(size_t bytes);
1044 
1045   bool is_in(const void* p) const override;
1046 
1047   // Return "TRUE" iff the given object address is within the collection
1048   // set. Assumes that the reference points into the heap.
1049   inline bool is_in_cset(const HeapRegion *hr);
1050   inline bool is_in_cset(oop obj);
1051   inline bool is_in_cset(HeapWord* addr);
1052 
1053   inline bool is_in_cset_or_humongous(const oop obj);
1054 
1055  private:
1056   // This array is used for a quick test on whether a reference points into
1057   // the collection set or not. Each of the array's elements denotes whether the
1058   // corresponding region is in the collection set or not.
1059   G1HeapRegionAttrBiasedMappedArray _region_attr;
1060 
1061  public:
1062 
1063   inline G1HeapRegionAttr region_attr(const void* obj) const;
1064   inline G1HeapRegionAttr region_attr(uint idx) const;
1065 
1066   MemRegion reserved() const {
1067     return _hrm.reserved();
1068   }
1069 
1070   bool is_in_reserved(const void* addr) const {
1071     return reserved().contains(addr);
1072   }
1073 
1074   G1HotCardCache* hot_card_cache() const { return _hot_card_cache; }
1075 
1076   G1CardTable* card_table() const {
1077     return _card_table;
1078   }
1079 
1080   // Iteration functions.
1081 
1082   void object_iterate_parallel(ObjectClosure* cl, uint worker_id, HeapRegionClaimer* claimer);
1083 
1084   // Iterate over all objects, calling "cl.do_object" on each.
1085   void object_iterate(ObjectClosure* cl) override;
1086 
1087   ParallelObjectIterator* parallel_object_iterator(uint thread_num) override;
1088 
1089   // Keep alive an object that was loaded with AS_NO_KEEPALIVE.
1090   void keep_alive(oop obj) override;
1091 
1092   // Iterate over heap regions, in address order, terminating the
1093   // iteration early if the "do_heap_region" method returns "true".
1094   void heap_region_iterate(HeapRegionClosure* blk) const;
1095 
1096   // Return the region with the given index. It assumes the index is valid.
1097   inline HeapRegion* region_at(uint index) const;
1098   inline HeapRegion* region_at_or_null(uint index) const;
1099 
1100   // Return the next region (by index) that is part of the same
1101   // humongous object that hr is part of.
1102   inline HeapRegion* next_region_in_humongous(HeapRegion* hr) const;
1103 
1104   // Calculate the region index of the given address. Given address must be
1105   // within the heap.
1106   inline uint addr_to_region(HeapWord* addr) const;
1107 
1108   inline HeapWord* bottom_addr_for_region(uint index) const;
1109 
1110   // Two functions to iterate over the heap regions in parallel. Threads
1111   // compete using the HeapRegionClaimer to claim the regions before
1112   // applying the closure on them.
1113   // The _from_worker_offset version uses the HeapRegionClaimer and
1114   // the worker id to calculate a start offset to prevent all workers to
1115   // start from the point.
1116   void heap_region_par_iterate_from_worker_offset(HeapRegionClosure* cl,
1117                                                   HeapRegionClaimer* hrclaimer,
1118                                                   uint worker_id) const;
1119 
1120   void heap_region_par_iterate_from_start(HeapRegionClosure* cl,
1121                                           HeapRegionClaimer* hrclaimer) const;
1122 
1123   // Iterate over all regions in the collection set in parallel.
1124   void collection_set_par_iterate_all(HeapRegionClosure* cl,
1125                                       HeapRegionClaimer* hr_claimer,
1126                                       uint worker_id);
1127 
1128   // Iterate over all regions currently in the current collection set.
1129   void collection_set_iterate_all(HeapRegionClosure* blk);
1130 
1131   // Iterate over the regions in the current increment of the collection set.
1132   // Starts the iteration so that the start regions of a given worker id over the
1133   // set active_workers are evenly spread across the set of collection set regions
1134   // to be iterated.
1135   // The variant with the HeapRegionClaimer guarantees that the closure will be
1136   // applied to a particular region exactly once.
1137   void collection_set_iterate_increment_from(HeapRegionClosure *blk, uint worker_id) {
1138     collection_set_iterate_increment_from(blk, NULL, worker_id);
1139   }
1140   void collection_set_iterate_increment_from(HeapRegionClosure *blk, HeapRegionClaimer* hr_claimer, uint worker_id);
1141   // Iterate over the array of region indexes, uint regions[length], applying
1142   // the given HeapRegionClosure on each region. The worker_id will determine where
1143   // to start the iteration to allow for more efficient parallel iteration.
1144   void par_iterate_regions_array(HeapRegionClosure* cl,
1145                                  HeapRegionClaimer* hr_claimer,
1146                                  const uint regions[],
1147                                  size_t length,
1148                                  uint worker_id) const;
1149 
1150   // Returns the HeapRegion that contains addr. addr must not be NULL.
1151   template <class T>
1152   inline HeapRegion* heap_region_containing(const T addr) const;
1153 
1154   // Returns the HeapRegion that contains addr, or NULL if that is an uncommitted
1155   // region. addr must not be NULL.
1156   template <class T>
1157   inline HeapRegion* heap_region_containing_or_null(const T addr) const;
1158 
1159   // A CollectedHeap is divided into a dense sequence of "blocks"; that is,
1160   // each address in the (reserved) heap is a member of exactly
1161   // one block.  The defining characteristic of a block is that it is
1162   // possible to find its size, and thus to progress forward to the next
1163   // block.  (Blocks may be of different sizes.)  Thus, blocks may
1164   // represent Java objects, or they might be free blocks in a
1165   // free-list-based heap (or subheap), as long as the two kinds are
1166   // distinguishable and the size of each is determinable.
1167 
1168   // Returns the address of the start of the "block" that contains the
1169   // address "addr".  We say "blocks" instead of "object" since some heaps
1170   // may not pack objects densely; a chunk may either be an object or a
1171   // non-object.
1172   HeapWord* block_start(const void* addr) const;
1173 
1174   // Requires "addr" to be the start of a block, and returns "TRUE" iff
1175   // the block is an object.
1176   bool block_is_obj(const HeapWord* addr) const;
1177 
1178   // Section on thread-local allocation buffers (TLABs)
1179   // See CollectedHeap for semantics.
1180 
1181   size_t tlab_capacity(Thread* ignored) const override;
1182   size_t tlab_used(Thread* ignored) const override;
1183   size_t max_tlab_size() const override;
1184   size_t unsafe_max_tlab_alloc(Thread* ignored) const override;
1185 
1186   inline bool is_in_young(const oop obj);
1187 
1188   // Returns "true" iff the given word_size is "very large".
1189   static bool is_humongous(size_t word_size) {
1190     // Note this has to be strictly greater-than as the TLABs
1191     // are capped at the humongous threshold and we want to
1192     // ensure that we don't try to allocate a TLAB as
1193     // humongous and that we don't allocate a humongous
1194     // object in a TLAB.
1195     return word_size > _humongous_object_threshold_in_words;
1196   }
1197 
1198   // Returns the humongous threshold for a specific region size
1199   static size_t humongous_threshold_for(size_t region_size) {
1200     return (region_size / 2);
1201   }
1202 
1203   // Returns the number of regions the humongous object of the given word size
1204   // requires.
1205   static size_t humongous_obj_size_in_regions(size_t word_size);
1206 
1207   // Print the maximum heap capacity.
1208   size_t max_capacity() const override;
1209 
1210   Tickspan time_since_last_collection() const { return Ticks::now() - _collection_pause_end; }
1211 
1212   // Convenience function to be used in situations where the heap type can be
1213   // asserted to be this type.
1214   static G1CollectedHeap* heap() {
1215     return named_heap<G1CollectedHeap>(CollectedHeap::G1);
1216   }
1217 
1218   void set_region_short_lived_locked(HeapRegion* hr);
1219   // add appropriate methods for any other surv rate groups
1220 
1221   G1SurvivorRegions* survivor() { return &_survivor; }
1222 
1223   uint eden_regions_count() const { return _eden.length(); }
1224   uint eden_regions_count(uint node_index) const { return _eden.regions_on_node(node_index); }
1225   uint survivor_regions_count() const { return _survivor.length(); }
1226   uint survivor_regions_count(uint node_index) const { return _survivor.regions_on_node(node_index); }
1227   size_t eden_regions_used_bytes() const { return _eden.used_bytes(); }
1228   size_t survivor_regions_used_bytes() const { return _survivor.used_bytes(); }
1229   uint young_regions_count() const { return _eden.length() + _survivor.length(); }
1230   uint old_regions_count() const { return _old_set.length(); }
1231   uint archive_regions_count() const { return _archive_set.length(); }
1232   uint humongous_regions_count() const { return _humongous_set.length(); }
1233 
1234 #ifdef ASSERT
1235   bool check_young_list_empty();
1236 #endif
1237 
1238   bool is_marked_next(oop obj) const;
1239 
1240   // Determine if an object is dead, given the object and also
1241   // the region to which the object belongs.
1242   inline bool is_obj_dead(const oop obj, const HeapRegion* hr) const;
1243 
1244   // This function returns true when an object has been
1245   // around since the previous marking and hasn't yet
1246   // been marked during this marking, and is not in a closed archive region.
1247   inline bool is_obj_ill(const oop obj, const HeapRegion* hr) const;
1248 
1249   // Determine if an object is dead, given only the object itself.
1250   // This will find the region to which the object belongs and
1251   // then call the region version of the same function.
1252 
1253   // Added if it is NULL it isn't dead.
1254 
1255   inline bool is_obj_dead(const oop obj) const;
1256 
1257   inline bool is_obj_ill(const oop obj) const;
1258 
1259   inline bool is_obj_dead_full(const oop obj, const HeapRegion* hr) const;
1260   inline bool is_obj_dead_full(const oop obj) const;
1261 
1262   G1ConcurrentMark* concurrent_mark() const { return _cm; }
1263 
1264   // Refinement
1265 
1266   G1ConcurrentRefine* concurrent_refine() const { return _cr; }
1267 
1268   // Optimized nmethod scanning support routines
1269 
1270   // Register the given nmethod with the G1 heap.
1271   void register_nmethod(nmethod* nm) override;
1272 
1273   // Unregister the given nmethod from the G1 heap.
1274   void unregister_nmethod(nmethod* nm) override;
1275 
1276   // No nmethod flushing needed.
1277   void flush_nmethod(nmethod* nm) override {}
1278 
1279   // No nmethod verification implemented.
1280   void verify_nmethod(nmethod* nm) override {}
1281 
1282   // Recalculate amount of used memory after GC. Must be called after all allocation
1283   // has finished.
1284   void update_used_after_gc(bool evacuation_failed);
1285   // Reset and re-enable the hot card cache.
1286   // Note the counts for the cards in the regions in the
1287   // collection set are reset when the collection set is freed.
1288   void reset_hot_card_cache();
1289   // Free up superfluous code root memory.
1290   void purge_code_root_memory();
1291 
1292   // Rebuild the strong code root lists for each region
1293   // after a full GC.
1294   void rebuild_strong_code_roots();
1295 
1296   // Performs cleaning of data structures after class unloading.
1297   void complete_cleaning(BoolObjectClosure* is_alive, bool class_unloading_occurred);
1298 
1299   // Verification
1300 
1301   // Perform any cleanup actions necessary before allowing a verification.
1302   void prepare_for_verify() override;
1303 
1304   // Perform verification.
1305 
1306   // vo == UsePrevMarking -> use "prev" marking information,
1307   // vo == UseNextMarking -> use "next" marking information
1308   // vo == UseFullMarking -> use "next" marking bitmap but no TAMS
1309   //
1310   // NOTE: Only the "prev" marking information is guaranteed to be
1311   // consistent most of the time, so most calls to this should use
1312   // vo == UsePrevMarking.
1313   // Currently, there is only one case where this is called with
1314   // vo == UseNextMarking, which is to verify the "next" marking
1315   // information at the end of remark.
1316   // Currently there is only one place where this is called with
1317   // vo == UseFullMarking, which is to verify the marking during a
1318   // full GC.
1319   void verify(VerifyOption vo) override;
1320 
1321   // WhiteBox testing support.
1322   bool supports_concurrent_gc_breakpoints() const override;
1323 
1324   WorkerThreads* safepoint_workers() override { return _workers; }
1325 
1326   bool is_archived_object(oop object) const override;
1327 
1328   // The methods below are here for convenience and dispatch the
1329   // appropriate method depending on value of the given VerifyOption
1330   // parameter. The values for that parameter, and their meanings,
1331   // are the same as those above.
1332 
1333   bool is_obj_dead_cond(const oop obj,
1334                         const HeapRegion* hr,
1335                         const VerifyOption vo) const;
1336 
1337   bool is_obj_dead_cond(const oop obj,
1338                         const VerifyOption vo) const;
1339 
1340   G1HeapSummary create_g1_heap_summary();
1341   G1EvacSummary create_g1_evac_summary(G1EvacStats* stats);
1342 
1343   // Printing
1344 private:
1345   void print_heap_regions() const;
1346   void print_regions_on(outputStream* st) const;
1347 
1348 public:
1349   void print_on(outputStream* st) const override;
1350   void print_extended_on(outputStream* st) const override;
1351   void print_on_error(outputStream* st) const override;
1352 
1353   void gc_threads_do(ThreadClosure* tc) const override;
1354 
1355   // Override
1356   void print_tracing_info() const override;
1357 
1358   // The following two methods are helpful for debugging RSet issues.
1359   void print_cset_rsets() PRODUCT_RETURN;
1360   void print_all_rsets() PRODUCT_RETURN;
1361 
1362   // Used to print information about locations in the hs_err file.
1363   bool print_location(outputStream* st, void* addr) const override;
1364 };
1365 
1366 // Scoped object that performs common pre- and post-gc heap printing operations.
1367 class G1HeapPrinterMark : public StackObj {
1368   G1CollectedHeap* _g1h;
1369   G1HeapTransition _heap_transition;
1370 
1371 public:
1372   G1HeapPrinterMark(G1CollectedHeap* g1h);
1373   ~G1HeapPrinterMark();
1374 };
1375 
1376 // Scoped object that performs common pre- and post-gc operations related to
1377 // JFR events.
1378 class G1JFRTracerMark : public StackObj {
1379 protected:
1380   STWGCTimer* _timer;
1381   GCTracer* _tracer;
1382 
1383 public:
1384   G1JFRTracerMark(STWGCTimer* timer, GCTracer* tracer);
1385   ~G1JFRTracerMark();
1386 };
1387 
1388 #endif // SHARE_GC_G1_G1COLLECTEDHEAP_HPP