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