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