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