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