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

1180 
1181   // Returns "true" iff the given word_size is "very large".
1182   static bool is_humongous(size_t word_size) {
1183     // Note this has to be strictly greater-than as the TLABs
1184     // are capped at the humongous threshold and we want to
1185     // ensure that we don't try to allocate a TLAB as
1186     // humongous and that we don't allocate a humongous
1187     // object in a TLAB.
1188     return word_size > _humongous_object_threshold_in_words;
1189   }
1190 
1191   // Returns the humongous threshold for a specific region size
1192   static size_t humongous_threshold_for(size_t region_size) {
1193     return (region_size / 2);
1194   }
1195 
1196   // Returns the number of regions the humongous object of the given word size
1197   // requires.
1198   static size_t humongous_obj_size_in_regions(size_t word_size);
1199 
1200   // Print the maximum heap capacity.
1201   size_t max_capacity() const override;
1202 
1203   Tickspan time_since_last_collection() const { return Ticks::now() - _collection_pause_end; }
1204 
1205   // Convenience function to be used in situations where the heap type can be
1206   // asserted to be this type.
1207   static G1CollectedHeap* heap() {
1208     return named_heap<G1CollectedHeap>(CollectedHeap::G1);
1209   }
1210 
1211   void set_region_short_lived_locked(HeapRegion* hr);
1212   // add appropriate methods for any other surv rate groups
1213 
1214   G1SurvivorRegions* survivor() { return &_survivor; }
1215 
1216   uint eden_regions_count() const { return _eden.length(); }
1217   uint eden_regions_count(uint node_index) const { return _eden.regions_on_node(node_index); }
1218   uint survivor_regions_count() const { return _survivor.length(); }
1219   uint survivor_regions_count(uint node_index) const { return _survivor.regions_on_node(node_index); }
1220   size_t eden_regions_used_bytes() const { return _eden.used_bytes(); }
1221   size_t survivor_regions_used_bytes() const { return _survivor.used_bytes(); }
1222   uint young_regions_count() const { return _eden.length() + _survivor.length(); }
1223   uint old_regions_count() const { return _old_set.length(); }
1224   uint archive_regions_count() const { return _archive_set.length(); }
1225   uint humongous_regions_count() const { return _humongous_set.length(); }
1226 
1227 #ifdef ASSERT
1228   bool check_young_list_empty();
1229 #endif
1230 
1231   bool is_marked_next(oop obj) const;
1232 
1233   // Determine if an object is dead, given the object and also
1234   // the region to which the object belongs.
1235   inline bool is_obj_dead(const oop obj, const HeapRegion* hr) const;
1236 
1237   // This function returns true when an object has been
1238   // around since the previous marking and hasn't yet
1239   // been marked during this marking, and is not in a closed archive region.
1240   inline bool is_obj_ill(const oop obj, const HeapRegion* hr) const;
1241 
1242   // Determine if an object is dead, given only the object itself.
1243   // This will find the region to which the object belongs and
1244   // then call the region version of the same function.
1245 
1246   // Added if it is NULL it isn't dead.
1247 
1248   inline bool is_obj_dead(const oop obj) const;
1249 
1250   inline bool is_obj_ill(const oop obj) const;
1251 
1252   inline bool is_obj_dead_full(const oop obj, const HeapRegion* hr) const;
1253   inline bool is_obj_dead_full(const oop obj) const;
1254 
1255   G1ConcurrentMark* concurrent_mark() const { return _cm; }
1256 
1257   // Refinement
1258 
1259   G1ConcurrentRefine* concurrent_refine() const { return _cr; }
1260 
1261   // Optimized nmethod scanning support routines
1262 
1263   // Register the given nmethod with the G1 heap.
1264   void register_nmethod(nmethod* nm) override;
1265 
1266   // Unregister the given nmethod from the G1 heap.
1267   void unregister_nmethod(nmethod* nm) override;
1268 
1269   // No nmethod flushing needed.
1270   void flush_nmethod(nmethod* nm) override {}
1271 
1272   // No nmethod verification implemented.
1273   void verify_nmethod(nmethod* nm) override {}
1274 
1275   // Recalculate amount of used memory after GC. Must be called after all allocation
1276   // has finished.
1277   void update_used_after_gc(bool evacuation_failed);
1278   // Reset and re-enable the hot card cache.
1279   // Note the counts for the cards in the regions in the
1280   // collection set are reset when the collection set is freed.
1281   void reset_hot_card_cache();
1282   // Free up superfluous code root memory.
1283   void purge_code_root_memory();
1284 
1285   // Rebuild the strong code root lists for each region
1286   // after a full GC.
1287   void rebuild_strong_code_roots();
1288 
1289   // Performs cleaning of data structures after class unloading.
1290   void complete_cleaning(BoolObjectClosure* is_alive, bool class_unloading_occurred);
1291 
1292   // Verification
1293 
1294   // Perform any cleanup actions necessary before allowing a verification.
1295   void prepare_for_verify() override;
1296 
1297   // Perform verification.
1298 
1299   // vo == UsePrevMarking -> use "prev" marking information,
1300   // vo == UseNextMarking -> use "next" marking information
1301   // vo == UseFullMarking -> use "next" marking bitmap but no TAMS
1302   //
1303   // NOTE: Only the "prev" marking information is guaranteed to be
1304   // consistent most of the time, so most calls to this should use
1305   // vo == UsePrevMarking.
1306   // Currently, there is only one case where this is called with
1307   // vo == UseNextMarking, which is to verify the "next" marking
1308   // information at the end of remark.
1309   // Currently there is only one place where this is called with
1310   // vo == UseFullMarking, which is to verify the marking during a
1311   // full GC.
1312   void verify(VerifyOption vo) override;
1313 
1314   // WhiteBox testing support.
1315   bool supports_concurrent_gc_breakpoints() const override;
1316 
1317   WorkerThreads* safepoint_workers() override { return _workers; }
1318 
1319   bool is_archived_object(oop object) const override;
1320 
1321   // The methods below are here for convenience and dispatch the
1322   // appropriate method depending on value of the given VerifyOption
1323   // parameter. The values for that parameter, and their meanings,
1324   // are the same as those above.
1325 
1326   bool is_obj_dead_cond(const oop obj,
1327                         const HeapRegion* hr,
1328                         const VerifyOption vo) const;
1329 
1330   bool is_obj_dead_cond(const oop obj,
1331                         const VerifyOption vo) const;
1332 
1333   G1HeapSummary create_g1_heap_summary();
1334   G1EvacSummary create_g1_evac_summary(G1EvacStats* stats);
1335 
1336   // Printing
1337 private:
1338   void print_heap_regions() const;
1339   void print_regions_on(outputStream* st) const;
1340 
1341 public:
1342   void print_on(outputStream* st) const override;
1343   void print_extended_on(outputStream* st) const override;
1344   void print_on_error(outputStream* st) const override;
1345 
1346   void gc_threads_do(ThreadClosure* tc) const override;
1347 
1348   // Override
1349   void print_tracing_info() const override;
1350 
1351   // The following two methods are helpful for debugging RSet issues.
1352   void print_cset_rsets() PRODUCT_RETURN;
1353   void print_all_rsets() PRODUCT_RETURN;
1354 
1355   // Used to print information about locations in the hs_err file.
1356   bool print_location(outputStream* st, void* addr) const override;
1357 };
1358 
1359 // Scoped object that performs common pre- and post-gc heap printing operations.
1360 class G1HeapPrinterMark : public StackObj {
1361   G1CollectedHeap* _g1h;
1362   G1HeapTransition _heap_transition;
1363 
1364 public:
1365   G1HeapPrinterMark(G1CollectedHeap* g1h);
1366   ~G1HeapPrinterMark();
1367 };
1368 
1369 // Scoped object that performs common pre- and post-gc operations related to
1370 // JFR events.
1371 class G1JFRTracerMark : public StackObj {
1372 protected:
1373   STWGCTimer* _timer;
1374   GCTracer* _tracer;
1375 
1376 public:
1377   G1JFRTracerMark(STWGCTimer* timer, GCTracer* tracer);
1378   ~G1JFRTracerMark();
1379 };
1380 
1381 #endif // SHARE_GC_G1_G1COLLECTEDHEAP_HPP
--- EOF ---