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