1 /*
   2  * Copyright (c) 2001, 2013, 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_VM_GC_IMPLEMENTATION_G1_G1COLLECTEDHEAP_HPP
  26 #define SHARE_VM_GC_IMPLEMENTATION_G1_G1COLLECTEDHEAP_HPP
  27 
  28 #include "gc_implementation/g1/concurrentMark.hpp"
  29 #include "gc_implementation/g1/g1AllocRegion.hpp"
  30 #include "gc_implementation/g1/g1HRPrinter.hpp"
  31 #include "gc_implementation/g1/g1RemSet.hpp"
  32 #include "gc_implementation/g1/g1MonitoringSupport.hpp"
  33 #include "gc_implementation/g1/heapRegionSeq.hpp"
  34 #include "gc_implementation/g1/heapRegionSets.hpp"
  35 #include "gc_implementation/shared/hSpaceCounters.hpp"
  36 #include "gc_implementation/shared/parGCAllocBuffer.hpp"
  37 #include "memory/barrierSet.hpp"
  38 #include "memory/memRegion.hpp"
  39 #include "memory/sharedHeap.hpp"
  40 #include "utilities/stack.hpp"
  41 
  42 // A "G1CollectedHeap" is an implementation of a java heap for HotSpot.
  43 // It uses the "Garbage First" heap organization and algorithm, which
  44 // may combine concurrent marking with parallel, incremental compaction of
  45 // heap subsets that will yield large amounts of garbage.
  46 
  47 // Forward declarations
  48 class HeapRegion;
  49 class HRRSCleanupTask;
  50 class GenerationSpec;
  51 class OopsInHeapRegionClosure;
  52 class G1KlassScanClosure;
  53 class G1ScanHeapEvacClosure;
  54 class ObjectClosure;
  55 class SpaceClosure;
  56 class CompactibleSpaceClosure;
  57 class Space;
  58 class G1CollectorPolicy;
  59 class GenRemSet;
  60 class G1RemSet;
  61 class HeapRegionRemSetIterator;
  62 class ConcurrentMark;
  63 class ConcurrentMarkThread;
  64 class ConcurrentG1Refine;
  65 class GenerationCounters;
  66 class nmethod;
  67 
  68 typedef OverflowTaskQueue<StarTask, mtGC>         RefToScanQueue;
  69 typedef GenericTaskQueueSet<RefToScanQueue, mtGC> RefToScanQueueSet;
  70 
  71 typedef int RegionIdx_t;   // needs to hold [ 0..max_regions() )
  72 typedef int CardIdx_t;     // needs to hold [ 0..CardsPerRegion )
  73 
  74 enum GCAllocPurpose {
  75   GCAllocForTenured,
  76   GCAllocForSurvived,
  77   GCAllocPurposeCount
  78 };
  79 
  80 class YoungList : public CHeapObj<mtGC> {
  81 private:
  82   G1CollectedHeap* _g1h;
  83 
  84   HeapRegion* _head;
  85 
  86   HeapRegion* _survivor_head;
  87   HeapRegion* _survivor_tail;
  88 
  89   HeapRegion* _curr;
  90 
  91   uint        _length;
  92   uint        _survivor_length;
  93 
  94   size_t      _last_sampled_rs_lengths;
  95   size_t      _sampled_rs_lengths;
  96 
  97   void         empty_list(HeapRegion* list);
  98 
  99 public:
 100   YoungList(G1CollectedHeap* g1h);
 101 
 102   void         push_region(HeapRegion* hr);
 103   void         add_survivor_region(HeapRegion* hr);
 104 
 105   void         empty_list();
 106   bool         is_empty() { return _length == 0; }
 107   uint         length() { return _length; }
 108   uint         survivor_length() { return _survivor_length; }
 109 
 110   // Currently we do not keep track of the used byte sum for the
 111   // young list and the survivors and it'd be quite a lot of work to
 112   // do so. When we'll eventually replace the young list with
 113   // instances of HeapRegionLinkedList we'll get that for free. So,
 114   // we'll report the more accurate information then.
 115   size_t       eden_used_bytes() {
 116     assert(length() >= survivor_length(), "invariant");
 117     return (size_t) (length() - survivor_length()) * HeapRegion::GrainBytes;
 118   }
 119   size_t       survivor_used_bytes() {
 120     return (size_t) survivor_length() * HeapRegion::GrainBytes;
 121   }
 122 
 123   void rs_length_sampling_init();
 124   bool rs_length_sampling_more();
 125   void rs_length_sampling_next();
 126 
 127   void reset_sampled_info() {
 128     _last_sampled_rs_lengths =   0;
 129   }
 130   size_t sampled_rs_lengths() { return _last_sampled_rs_lengths; }
 131 
 132   // for development purposes
 133   void reset_auxilary_lists();
 134   void clear() { _head = NULL; _length = 0; }
 135 
 136   void clear_survivors() {
 137     _survivor_head    = NULL;
 138     _survivor_tail    = NULL;
 139     _survivor_length  = 0;
 140   }
 141 
 142   HeapRegion* first_region() { return _head; }
 143   HeapRegion* first_survivor_region() { return _survivor_head; }
 144   HeapRegion* last_survivor_region() { return _survivor_tail; }
 145 
 146   // debugging
 147   bool          check_list_well_formed();
 148   bool          check_list_empty(bool check_sample = true);
 149   void          print();
 150 };
 151 
 152 class MutatorAllocRegion : public G1AllocRegion {
 153 protected:
 154   virtual HeapRegion* allocate_new_region(size_t word_size, bool force);
 155   virtual void retire_region(HeapRegion* alloc_region, size_t allocated_bytes);
 156 public:
 157   MutatorAllocRegion()
 158     : G1AllocRegion("Mutator Alloc Region", false /* bot_updates */) { }
 159 };
 160 
 161 class SurvivorGCAllocRegion : public G1AllocRegion {
 162 protected:
 163   virtual HeapRegion* allocate_new_region(size_t word_size, bool force);
 164   virtual void retire_region(HeapRegion* alloc_region, size_t allocated_bytes);
 165 public:
 166   SurvivorGCAllocRegion()
 167   : G1AllocRegion("Survivor GC Alloc Region", false /* bot_updates */) { }
 168 };
 169 
 170 class OldGCAllocRegion : public G1AllocRegion {
 171 protected:
 172   virtual HeapRegion* allocate_new_region(size_t word_size, bool force);
 173   virtual void retire_region(HeapRegion* alloc_region, size_t allocated_bytes);
 174 public:
 175   OldGCAllocRegion()
 176   : G1AllocRegion("Old GC Alloc Region", true /* bot_updates */) { }
 177 };
 178 
 179 // The G1 STW is alive closure.
 180 // An instance is embedded into the G1CH and used as the
 181 // (optional) _is_alive_non_header closure in the STW
 182 // reference processor. It is also extensively used during
 183 // refence processing during STW evacuation pauses.
 184 class G1STWIsAliveClosure: public BoolObjectClosure {
 185   G1CollectedHeap* _g1;
 186 public:
 187   G1STWIsAliveClosure(G1CollectedHeap* g1) : _g1(g1) {}
 188   bool do_object_b(oop p);
 189 };
 190 
 191 class RefineCardTableEntryClosure;
 192 
 193 class G1CollectedHeap : public SharedHeap {
 194   friend class VM_G1CollectForAllocation;
 195   friend class VM_G1CollectFull;
 196   friend class VM_G1IncCollectionPause;
 197   friend class VMStructs;
 198   friend class MutatorAllocRegion;
 199   friend class SurvivorGCAllocRegion;
 200   friend class OldGCAllocRegion;
 201 
 202   // Closures used in implementation.
 203   template <bool do_gen_barrier, G1Barrier barrier, bool do_mark_object>
 204   friend class G1ParCopyClosure;
 205   friend class G1IsAliveClosure;
 206   friend class G1EvacuateFollowersClosure;
 207   friend class G1ParScanThreadState;
 208   friend class G1ParScanClosureSuper;
 209   friend class G1ParEvacuateFollowersClosure;
 210   friend class G1ParTask;
 211   friend class G1FreeGarbageRegionClosure;
 212   friend class RefineCardTableEntryClosure;
 213   friend class G1PrepareCompactClosure;
 214   friend class RegionSorter;
 215   friend class RegionResetter;
 216   friend class CountRCClosure;
 217   friend class EvacPopObjClosure;
 218   friend class G1ParCleanupCTTask;
 219 
 220   // Other related classes.
 221   friend class G1MarkSweep;
 222 
 223 private:
 224   // The one and only G1CollectedHeap, so static functions can find it.
 225   static G1CollectedHeap* _g1h;
 226 
 227   static size_t _humongous_object_threshold_in_words;
 228 
 229   // Storage for the G1 heap.
 230   VirtualSpace _g1_storage;
 231   MemRegion    _g1_reserved;
 232 
 233   // The part of _g1_storage that is currently committed.
 234   MemRegion _g1_committed;
 235 
 236   // The master free list. It will satisfy all new region allocations.
 237   MasterFreeRegionList      _free_list;
 238 
 239   // The secondary free list which contains regions that have been
 240   // freed up during the cleanup process. This will be appended to the
 241   // master free list when appropriate.
 242   SecondaryFreeRegionList   _secondary_free_list;
 243 
 244   // It keeps track of the old regions.
 245   MasterOldRegionSet        _old_set;
 246 
 247   // It keeps track of the humongous regions.
 248   MasterHumongousRegionSet  _humongous_set;
 249 
 250   // The number of regions we could create by expansion.
 251   uint _expansion_regions;
 252 
 253   // The block offset table for the G1 heap.
 254   G1BlockOffsetSharedArray* _bot_shared;
 255 
 256   // Tears down the region sets / lists so that they are empty and the
 257   // regions on the heap do not belong to a region set / list. The
 258   // only exception is the humongous set which we leave unaltered. If
 259   // free_list_only is true, it will only tear down the master free
 260   // list. It is called before a Full GC (free_list_only == false) or
 261   // before heap shrinking (free_list_only == true).
 262   void tear_down_region_sets(bool free_list_only);
 263 
 264   // Rebuilds the region sets / lists so that they are repopulated to
 265   // reflect the contents of the heap. The only exception is the
 266   // humongous set which was not torn down in the first place. If
 267   // free_list_only is true, it will only rebuild the master free
 268   // list. It is called after a Full GC (free_list_only == false) or
 269   // after heap shrinking (free_list_only == true).
 270   void rebuild_region_sets(bool free_list_only);
 271 
 272   // The sequence of all heap regions in the heap.
 273   HeapRegionSeq _hrs;
 274 
 275   // Alloc region used to satisfy mutator allocation requests.
 276   MutatorAllocRegion _mutator_alloc_region;
 277 
 278   // Alloc region used to satisfy allocation requests by the GC for
 279   // survivor objects.
 280   SurvivorGCAllocRegion _survivor_gc_alloc_region;
 281 
 282   // PLAB sizing policy for survivors.
 283   PLABStats _survivor_plab_stats;
 284 
 285   // Alloc region used to satisfy allocation requests by the GC for
 286   // old objects.
 287   OldGCAllocRegion _old_gc_alloc_region;
 288 
 289   // PLAB sizing policy for tenured objects.
 290   PLABStats _old_plab_stats;
 291 
 292   PLABStats* stats_for_purpose(GCAllocPurpose purpose) {
 293     PLABStats* stats = NULL;
 294 
 295     switch (purpose) {
 296     case GCAllocForSurvived:
 297       stats = &_survivor_plab_stats;
 298       break;
 299     case GCAllocForTenured:
 300       stats = &_old_plab_stats;
 301       break;
 302     default:
 303       assert(false, "unrecognized GCAllocPurpose");
 304     }
 305 
 306     return stats;
 307   }
 308 
 309   // The last old region we allocated to during the last GC.
 310   // Typically, it is not full so we should re-use it during the next GC.
 311   HeapRegion* _retained_old_gc_alloc_region;
 312 
 313   // It specifies whether we should attempt to expand the heap after a
 314   // region allocation failure. If heap expansion fails we set this to
 315   // false so that we don't re-attempt the heap expansion (it's likely
 316   // that subsequent expansion attempts will also fail if one fails).
 317   // Currently, it is only consulted during GC and it's reset at the
 318   // start of each GC.
 319   bool _expand_heap_after_alloc_failure;
 320 
 321   // It resets the mutator alloc region before new allocations can take place.
 322   void init_mutator_alloc_region();
 323 
 324   // It releases the mutator alloc region.
 325   void release_mutator_alloc_region();
 326 
 327   // It initializes the GC alloc regions at the start of a GC.
 328   void init_gc_alloc_regions();
 329 
 330   // It releases the GC alloc regions at the end of a GC.
 331   void release_gc_alloc_regions(uint no_of_gc_workers);
 332 
 333   // It does any cleanup that needs to be done on the GC alloc regions
 334   // before a Full GC.
 335   void abandon_gc_alloc_regions();
 336 
 337   // Helper for monitoring and management support.
 338   G1MonitoringSupport* _g1mm;
 339 
 340   // Determines PLAB size for a particular allocation purpose.
 341   size_t desired_plab_sz(GCAllocPurpose purpose);
 342 
 343   // Outside of GC pauses, the number of bytes used in all regions other
 344   // than the current allocation region.
 345   size_t _summary_bytes_used;
 346 
 347   // This is used for a quick test on whether a reference points into
 348   // the collection set or not. Basically, we have an array, with one
 349   // byte per region, and that byte denotes whether the corresponding
 350   // region is in the collection set or not. The entry corresponding
 351   // the bottom of the heap, i.e., region 0, is pointed to by
 352   // _in_cset_fast_test_base.  The _in_cset_fast_test field has been
 353   // biased so that it actually points to address 0 of the address
 354   // space, to make the test as fast as possible (we can simply shift
 355   // the address to address into it, instead of having to subtract the
 356   // bottom of the heap from the address before shifting it; basically
 357   // it works in the same way the card table works).
 358   bool* _in_cset_fast_test;
 359 
 360   // The allocated array used for the fast test on whether a reference
 361   // points into the collection set or not. This field is also used to
 362   // free the array.
 363   bool* _in_cset_fast_test_base;
 364 
 365   // The length of the _in_cset_fast_test_base array.
 366   uint _in_cset_fast_test_length;
 367 
 368   volatile unsigned _gc_time_stamp;
 369 
 370   size_t* _surviving_young_words;
 371 
 372   G1HRPrinter _hr_printer;
 373 
 374   void setup_surviving_young_words();
 375   void update_surviving_young_words(size_t* surv_young_words);
 376   void cleanup_surviving_young_words();
 377 
 378   // It decides whether an explicit GC should start a concurrent cycle
 379   // instead of doing a STW GC. Currently, a concurrent cycle is
 380   // explicitly started if:
 381   // (a) cause == _gc_locker and +GCLockerInvokesConcurrent, or
 382   // (b) cause == _java_lang_system_gc and +ExplicitGCInvokesConcurrent.
 383   // (c) cause == _g1_humongous_allocation
 384   bool should_do_concurrent_full_gc(GCCause::Cause cause);
 385 
 386   // Keeps track of how many "old marking cycles" (i.e., Full GCs or
 387   // concurrent cycles) we have started.
 388   volatile unsigned int _old_marking_cycles_started;
 389 
 390   // Keeps track of how many "old marking cycles" (i.e., Full GCs or
 391   // concurrent cycles) we have completed.
 392   volatile unsigned int _old_marking_cycles_completed;
 393 
 394   // This is a non-product method that is helpful for testing. It is
 395   // called at the end of a GC and artificially expands the heap by
 396   // allocating a number of dead regions. This way we can induce very
 397   // frequent marking cycles and stress the cleanup / concurrent
 398   // cleanup code more (as all the regions that will be allocated by
 399   // this method will be found dead by the marking cycle).
 400   void allocate_dummy_regions() PRODUCT_RETURN;
 401 
 402   // Clear RSets after a compaction. It also resets the GC time stamps.
 403   void clear_rsets_post_compaction();
 404 
 405   // If the HR printer is active, dump the state of the regions in the
 406   // heap after a compaction.
 407   void print_hrs_post_compaction();
 408 
 409   double verify(bool guard, const char* msg);
 410   void verify_before_gc();
 411   void verify_after_gc();
 412 
 413   void log_gc_header();
 414   void log_gc_footer(double pause_time_sec);
 415 
 416   // These are macros so that, if the assert fires, we get the correct
 417   // line number, file, etc.
 418 
 419 #define heap_locking_asserts_err_msg(_extra_message_)                         \
 420   err_msg("%s : Heap_lock locked: %s, at safepoint: %s, is VM thread: %s",    \
 421           (_extra_message_),                                                  \
 422           BOOL_TO_STR(Heap_lock->owned_by_self()),                            \
 423           BOOL_TO_STR(SafepointSynchronize::is_at_safepoint()),               \
 424           BOOL_TO_STR(Thread::current()->is_VM_thread()))
 425 
 426 #define assert_heap_locked()                                                  \
 427   do {                                                                        \
 428     assert(Heap_lock->owned_by_self(),                                        \
 429            heap_locking_asserts_err_msg("should be holding the Heap_lock"));  \
 430   } while (0)
 431 
 432 #define assert_heap_locked_or_at_safepoint(_should_be_vm_thread_)             \
 433   do {                                                                        \
 434     assert(Heap_lock->owned_by_self() ||                                      \
 435            (SafepointSynchronize::is_at_safepoint() &&                        \
 436              ((_should_be_vm_thread_) == Thread::current()->is_VM_thread())), \
 437            heap_locking_asserts_err_msg("should be holding the Heap_lock or " \
 438                                         "should be at a safepoint"));         \
 439   } while (0)
 440 
 441 #define assert_heap_locked_and_not_at_safepoint()                             \
 442   do {                                                                        \
 443     assert(Heap_lock->owned_by_self() &&                                      \
 444                                     !SafepointSynchronize::is_at_safepoint(), \
 445           heap_locking_asserts_err_msg("should be holding the Heap_lock and " \
 446                                        "should not be at a safepoint"));      \
 447   } while (0)
 448 
 449 #define assert_heap_not_locked()                                              \
 450   do {                                                                        \
 451     assert(!Heap_lock->owned_by_self(),                                       \
 452         heap_locking_asserts_err_msg("should not be holding the Heap_lock")); \
 453   } while (0)
 454 
 455 #define assert_heap_not_locked_and_not_at_safepoint()                         \
 456   do {                                                                        \
 457     assert(!Heap_lock->owned_by_self() &&                                     \
 458                                     !SafepointSynchronize::is_at_safepoint(), \
 459       heap_locking_asserts_err_msg("should not be holding the Heap_lock and " \
 460                                    "should not be at a safepoint"));          \
 461   } while (0)
 462 
 463 #define assert_at_safepoint(_should_be_vm_thread_)                            \
 464   do {                                                                        \
 465     assert(SafepointSynchronize::is_at_safepoint() &&                         \
 466               ((_should_be_vm_thread_) == Thread::current()->is_VM_thread()), \
 467            heap_locking_asserts_err_msg("should be at a safepoint"));         \
 468   } while (0)
 469 
 470 #define assert_not_at_safepoint()                                             \
 471   do {                                                                        \
 472     assert(!SafepointSynchronize::is_at_safepoint(),                          \
 473            heap_locking_asserts_err_msg("should not be at a safepoint"));     \
 474   } while (0)
 475 
 476 protected:
 477 
 478   // The young region list.
 479   YoungList*  _young_list;
 480 
 481   // The current policy object for the collector.
 482   G1CollectorPolicy* _g1_policy;
 483 
 484   // This is the second level of trying to allocate a new region. If
 485   // new_region() didn't find a region on the free_list, this call will
 486   // check whether there's anything available on the
 487   // secondary_free_list and/or wait for more regions to appear on
 488   // that list, if _free_regions_coming is set.
 489   HeapRegion* new_region_try_secondary_free_list();
 490 
 491   // Try to allocate a single non-humongous HeapRegion sufficient for
 492   // an allocation of the given word_size. If do_expand is true,
 493   // attempt to expand the heap if necessary to satisfy the allocation
 494   // request.
 495   HeapRegion* new_region(size_t word_size, bool do_expand);
 496 
 497   // Attempt to satisfy a humongous allocation request of the given
 498   // size by finding a contiguous set of free regions of num_regions
 499   // length and remove them from the master free list. Return the
 500   // index of the first region or G1_NULL_HRS_INDEX if the search
 501   // was unsuccessful.
 502   uint humongous_obj_allocate_find_first(uint num_regions,
 503                                          size_t word_size);
 504 
 505   // Initialize a contiguous set of free regions of length num_regions
 506   // and starting at index first so that they appear as a single
 507   // humongous region.
 508   HeapWord* humongous_obj_allocate_initialize_regions(uint first,
 509                                                       uint num_regions,
 510                                                       size_t word_size);
 511 
 512   // Attempt to allocate a humongous object of the given size. Return
 513   // NULL if unsuccessful.
 514   HeapWord* humongous_obj_allocate(size_t word_size);
 515 
 516   // The following two methods, allocate_new_tlab() and
 517   // mem_allocate(), are the two main entry points from the runtime
 518   // into the G1's allocation routines. They have the following
 519   // assumptions:
 520   //
 521   // * They should both be called outside safepoints.
 522   //
 523   // * They should both be called without holding the Heap_lock.
 524   //
 525   // * All allocation requests for new TLABs should go to
 526   //   allocate_new_tlab().
 527   //
 528   // * All non-TLAB allocation requests should go to mem_allocate().
 529   //
 530   // * If either call cannot satisfy the allocation request using the
 531   //   current allocating region, they will try to get a new one. If
 532   //   this fails, they will attempt to do an evacuation pause and
 533   //   retry the allocation.
 534   //
 535   // * If all allocation attempts fail, even after trying to schedule
 536   //   an evacuation pause, allocate_new_tlab() will return NULL,
 537   //   whereas mem_allocate() will attempt a heap expansion and/or
 538   //   schedule a Full GC.
 539   //
 540   // * We do not allow humongous-sized TLABs. So, allocate_new_tlab
 541   //   should never be called with word_size being humongous. All
 542   //   humongous allocation requests should go to mem_allocate() which
 543   //   will satisfy them with a special path.
 544 
 545   virtual HeapWord* allocate_new_tlab(size_t word_size);
 546 
 547   virtual HeapWord* mem_allocate(size_t word_size,
 548                                  bool*  gc_overhead_limit_was_exceeded);
 549 
 550   // The following three methods take a gc_count_before_ret
 551   // parameter which is used to return the GC count if the method
 552   // returns NULL. Given that we are required to read the GC count
 553   // while holding the Heap_lock, and these paths will take the
 554   // Heap_lock at some point, it's easier to get them to read the GC
 555   // count while holding the Heap_lock before they return NULL instead
 556   // of the caller (namely: mem_allocate()) having to also take the
 557   // Heap_lock just to read the GC count.
 558 
 559   // First-level mutator allocation attempt: try to allocate out of
 560   // the mutator alloc region without taking the Heap_lock. This
 561   // should only be used for non-humongous allocations.
 562   inline HeapWord* attempt_allocation(size_t word_size,
 563                                       unsigned int* gc_count_before_ret,
 564                                       int* gclocker_retry_count_ret);
 565 
 566   // Second-level mutator allocation attempt: take the Heap_lock and
 567   // retry the allocation attempt, potentially scheduling a GC
 568   // pause. This should only be used for non-humongous allocations.
 569   HeapWord* attempt_allocation_slow(size_t word_size,
 570                                     unsigned int* gc_count_before_ret,
 571                                     int* gclocker_retry_count_ret);
 572 
 573   // Takes the Heap_lock and attempts a humongous allocation. It can
 574   // potentially schedule a GC pause.
 575   HeapWord* attempt_allocation_humongous(size_t word_size,
 576                                          unsigned int* gc_count_before_ret,
 577                                          int* gclocker_retry_count_ret);
 578 
 579   // Allocation attempt that should be called during safepoints (e.g.,
 580   // at the end of a successful GC). expect_null_mutator_alloc_region
 581   // specifies whether the mutator alloc region is expected to be NULL
 582   // or not.
 583   HeapWord* attempt_allocation_at_safepoint(size_t word_size,
 584                                        bool expect_null_mutator_alloc_region);
 585 
 586   // It dirties the cards that cover the block so that so that the post
 587   // write barrier never queues anything when updating objects on this
 588   // block. It is assumed (and in fact we assert) that the block
 589   // belongs to a young region.
 590   inline void dirty_young_block(HeapWord* start, size_t word_size);
 591 
 592   // Allocate blocks during garbage collection. Will ensure an
 593   // allocation region, either by picking one or expanding the
 594   // heap, and then allocate a block of the given size. The block
 595   // may not be a humongous - it must fit into a single heap region.
 596   HeapWord* par_allocate_during_gc(GCAllocPurpose purpose, size_t word_size);
 597 
 598   // Ensure that no further allocations can happen in "r", bearing in mind
 599   // that parallel threads might be attempting allocations.
 600   void par_allocate_remaining_space(HeapRegion* r);
 601 
 602   // Allocation attempt during GC for a survivor object / PLAB.
 603   inline HeapWord* survivor_attempt_allocation(size_t word_size);
 604 
 605   // Allocation attempt during GC for an old object / PLAB.
 606   inline HeapWord* old_attempt_allocation(size_t word_size);
 607 
 608   // These methods are the "callbacks" from the G1AllocRegion class.
 609 
 610   // For mutator alloc regions.
 611   HeapRegion* new_mutator_alloc_region(size_t word_size, bool force);
 612   void retire_mutator_alloc_region(HeapRegion* alloc_region,
 613                                    size_t allocated_bytes);
 614 
 615   // For GC alloc regions.
 616   HeapRegion* new_gc_alloc_region(size_t word_size, uint count,
 617                                   GCAllocPurpose ap);
 618   void retire_gc_alloc_region(HeapRegion* alloc_region,
 619                               size_t allocated_bytes, GCAllocPurpose ap);
 620 
 621   // - if explicit_gc is true, the GC is for a System.gc() or a heap
 622   //   inspection request and should collect the entire heap
 623   // - if clear_all_soft_refs is true, all soft references should be
 624   //   cleared during the GC
 625   // - if explicit_gc is false, word_size describes the allocation that
 626   //   the GC should attempt (at least) to satisfy
 627   // - it returns false if it is unable to do the collection due to the
 628   //   GC locker being active, true otherwise
 629   bool do_collection(bool explicit_gc,
 630                      bool clear_all_soft_refs,
 631                      size_t word_size);
 632 
 633   // Callback from VM_G1CollectFull operation.
 634   // Perform a full collection.
 635   virtual void do_full_collection(bool clear_all_soft_refs);
 636 
 637   // Resize the heap if necessary after a full collection.  If this is
 638   // after a collect-for allocation, "word_size" is the allocation size,
 639   // and will be considered part of the used portion of the heap.
 640   void resize_if_necessary_after_full_collection(size_t word_size);
 641 
 642   // Callback from VM_G1CollectForAllocation operation.
 643   // This function does everything necessary/possible to satisfy a
 644   // failed allocation request (including collection, expansion, etc.)
 645   HeapWord* satisfy_failed_allocation(size_t word_size, bool* succeeded);
 646 
 647   // Attempting to expand the heap sufficiently
 648   // to support an allocation of the given "word_size".  If
 649   // successful, perform the allocation and return the address of the
 650   // allocated block, or else "NULL".
 651   HeapWord* expand_and_allocate(size_t word_size);
 652 
 653   // Process any reference objects discovered during
 654   // an incremental evacuation pause.
 655   void process_discovered_references(uint no_of_gc_workers);
 656 
 657   // Enqueue any remaining discovered references
 658   // after processing.
 659   void enqueue_discovered_references(uint no_of_gc_workers);
 660 
 661 public:
 662 
 663   G1MonitoringSupport* g1mm() {
 664     assert(_g1mm != NULL, "should have been initialized");
 665     return _g1mm;
 666   }
 667 
 668   // Expand the garbage-first heap by at least the given size (in bytes!).
 669   // Returns true if the heap was expanded by the requested amount;
 670   // false otherwise.
 671   // (Rounds up to a HeapRegion boundary.)
 672   bool expand(size_t expand_bytes);
 673 
 674   // Do anything common to GC's.
 675   virtual void gc_prologue(bool full);
 676   virtual void gc_epilogue(bool full);
 677 
 678   // We register a region with the fast "in collection set" test. We
 679   // simply set to true the array slot corresponding to this region.
 680   void register_region_with_in_cset_fast_test(HeapRegion* r) {
 681     assert(_in_cset_fast_test_base != NULL, "sanity");
 682     assert(r->in_collection_set(), "invariant");
 683     uint index = r->hrs_index();
 684     assert(index < _in_cset_fast_test_length, "invariant");
 685     assert(!_in_cset_fast_test_base[index], "invariant");
 686     _in_cset_fast_test_base[index] = true;
 687   }
 688 
 689   // This is a fast test on whether a reference points into the
 690   // collection set or not. It does not assume that the reference
 691   // points into the heap; if it doesn't, it will return false.
 692   bool in_cset_fast_test(oop obj) {
 693     assert(_in_cset_fast_test != NULL, "sanity");
 694     if (_g1_committed.contains((HeapWord*) obj)) {
 695       // no need to subtract the bottom of the heap from obj,
 696       // _in_cset_fast_test is biased
 697       uintx index = (uintx) obj >> HeapRegion::LogOfHRGrainBytes;
 698       bool ret = _in_cset_fast_test[index];
 699       // let's make sure the result is consistent with what the slower
 700       // test returns
 701       assert( ret || !obj_in_cs(obj), "sanity");
 702       assert(!ret ||  obj_in_cs(obj), "sanity");
 703       return ret;
 704     } else {
 705       return false;
 706     }
 707   }
 708 
 709   void clear_cset_fast_test() {
 710     assert(_in_cset_fast_test_base != NULL, "sanity");
 711     memset(_in_cset_fast_test_base, false,
 712            (size_t) _in_cset_fast_test_length * sizeof(bool));
 713   }
 714 
 715   // This is called at the start of either a concurrent cycle or a Full
 716   // GC to update the number of old marking cycles started.
 717   void increment_old_marking_cycles_started();
 718 
 719   // This is called at the end of either a concurrent cycle or a Full
 720   // GC to update the number of old marking cycles completed. Those two
 721   // can happen in a nested fashion, i.e., we start a concurrent
 722   // cycle, a Full GC happens half-way through it which ends first,
 723   // and then the cycle notices that a Full GC happened and ends
 724   // too. The concurrent parameter is a boolean to help us do a bit
 725   // tighter consistency checking in the method. If concurrent is
 726   // false, the caller is the inner caller in the nesting (i.e., the
 727   // Full GC). If concurrent is true, the caller is the outer caller
 728   // in this nesting (i.e., the concurrent cycle). Further nesting is
 729   // not currently supported. The end of this call also notifies
 730   // the FullGCCount_lock in case a Java thread is waiting for a full
 731   // GC to happen (e.g., it called System.gc() with
 732   // +ExplicitGCInvokesConcurrent).
 733   void increment_old_marking_cycles_completed(bool concurrent);
 734 
 735   unsigned int old_marking_cycles_completed() {
 736     return _old_marking_cycles_completed;
 737   }
 738 
 739   G1HRPrinter* hr_printer() { return &_hr_printer; }
 740 
 741 protected:
 742 
 743   // Shrink the garbage-first heap by at most the given size (in bytes!).
 744   // (Rounds down to a HeapRegion boundary.)
 745   virtual void shrink(size_t expand_bytes);
 746   void shrink_helper(size_t expand_bytes);
 747 
 748   #if TASKQUEUE_STATS
 749   static void print_taskqueue_stats_hdr(outputStream* const st = gclog_or_tty);
 750   void print_taskqueue_stats(outputStream* const st = gclog_or_tty) const;
 751   void reset_taskqueue_stats();
 752   #endif // TASKQUEUE_STATS
 753 
 754   // Schedule the VM operation that will do an evacuation pause to
 755   // satisfy an allocation request of word_size. *succeeded will
 756   // return whether the VM operation was successful (it did do an
 757   // evacuation pause) or not (another thread beat us to it or the GC
 758   // locker was active). Given that we should not be holding the
 759   // Heap_lock when we enter this method, we will pass the
 760   // gc_count_before (i.e., total_collections()) as a parameter since
 761   // it has to be read while holding the Heap_lock. Currently, both
 762   // methods that call do_collection_pause() release the Heap_lock
 763   // before the call, so it's easy to read gc_count_before just before.
 764   HeapWord* do_collection_pause(size_t       word_size,
 765                                 unsigned int gc_count_before,
 766                                 bool*        succeeded);
 767 
 768   // The guts of the incremental collection pause, executed by the vm
 769   // thread. It returns false if it is unable to do the collection due
 770   // to the GC locker being active, true otherwise
 771   bool do_collection_pause_at_safepoint(double target_pause_time_ms);
 772 
 773   // Actually do the work of evacuating the collection set.
 774   void evacuate_collection_set();
 775 
 776   // The g1 remembered set of the heap.
 777   G1RemSet* _g1_rem_set;
 778   // And it's mod ref barrier set, used to track updates for the above.
 779   ModRefBarrierSet* _mr_bs;
 780 
 781   // A set of cards that cover the objects for which the Rsets should be updated
 782   // concurrently after the collection.
 783   DirtyCardQueueSet _dirty_card_queue_set;
 784 
 785   // The closure used to refine a single card.
 786   RefineCardTableEntryClosure* _refine_cte_cl;
 787 
 788   // A function to check the consistency of dirty card logs.
 789   void check_ct_logs_at_safepoint();
 790 
 791   // A DirtyCardQueueSet that is used to hold cards that contain
 792   // references into the current collection set. This is used to
 793   // update the remembered sets of the regions in the collection
 794   // set in the event of an evacuation failure.
 795   DirtyCardQueueSet _into_cset_dirty_card_queue_set;
 796 
 797   // After a collection pause, make the regions in the CS into free
 798   // regions.
 799   void free_collection_set(HeapRegion* cs_head);
 800 
 801   // Abandon the current collection set without recording policy
 802   // statistics or updating free lists.
 803   void abandon_collection_set(HeapRegion* cs_head);
 804 
 805   // Applies "scan_non_heap_roots" to roots outside the heap,
 806   // "scan_rs" to roots inside the heap (having done "set_region" to
 807   // indicate the region in which the root resides),
 808   // and does "scan_metadata" If "scan_rs" is
 809   // NULL, then this step is skipped.  The "worker_i"
 810   // param is for use with parallel roots processing, and should be
 811   // the "i" of the calling parallel worker thread's work(i) function.
 812   // In the sequential case this param will be ignored.
 813   void g1_process_strong_roots(bool is_scavenging,
 814                                ScanningOption so,
 815                                OopClosure* scan_non_heap_roots,
 816                                OopsInHeapRegionClosure* scan_rs,
 817                                G1KlassScanClosure* scan_klasses,
 818                                int worker_i);
 819 
 820   // Apply "blk" to all the weak roots of the system.  These include
 821   // JNI weak roots, the code cache, system dictionary, symbol table,
 822   // string table, and referents of reachable weak refs.
 823   void g1_process_weak_roots(OopClosure* root_closure);
 824 
 825   // Frees a non-humongous region by initializing its contents and
 826   // adding it to the free list that's passed as a parameter (this is
 827   // usually a local list which will be appended to the master free
 828   // list later). The used bytes of freed regions are accumulated in
 829   // pre_used. If par is true, the region's RSet will not be freed
 830   // up. The assumption is that this will be done later.
 831   void free_region(HeapRegion* hr,
 832                    size_t* pre_used,
 833                    FreeRegionList* free_list,
 834                    bool par);
 835 
 836   // Frees a humongous region by collapsing it into individual regions
 837   // and calling free_region() for each of them. The freed regions
 838   // will be added to the free list that's passed as a parameter (this
 839   // is usually a local list which will be appended to the master free
 840   // list later). The used bytes of freed regions are accumulated in
 841   // pre_used. If par is true, the region's RSet will not be freed
 842   // up. The assumption is that this will be done later.
 843   void free_humongous_region(HeapRegion* hr,
 844                              size_t* pre_used,
 845                              FreeRegionList* free_list,
 846                              HumongousRegionSet* humongous_proxy_set,
 847                              bool par);
 848 
 849   // Notifies all the necessary spaces that the committed space has
 850   // been updated (either expanded or shrunk). It should be called
 851   // after _g1_storage is updated.
 852   void update_committed_space(HeapWord* old_end, HeapWord* new_end);
 853 
 854   // The concurrent marker (and the thread it runs in.)
 855   ConcurrentMark* _cm;
 856   ConcurrentMarkThread* _cmThread;
 857   bool _mark_in_progress;
 858 
 859   // The concurrent refiner.
 860   ConcurrentG1Refine* _cg1r;
 861 
 862   // The parallel task queues
 863   RefToScanQueueSet *_task_queues;
 864 
 865   // True iff a evacuation has failed in the current collection.
 866   bool _evacuation_failed;
 867 
 868   // Set the attribute indicating whether evacuation has failed in the
 869   // current collection.
 870   void set_evacuation_failed(bool b) { _evacuation_failed = b; }
 871 
 872   // Failed evacuations cause some logical from-space objects to have
 873   // forwarding pointers to themselves.  Reset them.
 874   void remove_self_forwarding_pointers();
 875 
 876   // Together, these store an object with a preserved mark, and its mark value.
 877   Stack<oop, mtGC>     _objs_with_preserved_marks;
 878   Stack<markOop, mtGC> _preserved_marks_of_objs;
 879 
 880   // Preserve the mark of "obj", if necessary, in preparation for its mark
 881   // word being overwritten with a self-forwarding-pointer.
 882   void preserve_mark_if_necessary(oop obj, markOop m);
 883 
 884   // The stack of evac-failure objects left to be scanned.
 885   GrowableArray<oop>*    _evac_failure_scan_stack;
 886   // The closure to apply to evac-failure objects.
 887 
 888   OopsInHeapRegionClosure* _evac_failure_closure;
 889   // Set the field above.
 890   void
 891   set_evac_failure_closure(OopsInHeapRegionClosure* evac_failure_closure) {
 892     _evac_failure_closure = evac_failure_closure;
 893   }
 894 
 895   // Push "obj" on the scan stack.
 896   void push_on_evac_failure_scan_stack(oop obj);
 897   // Process scan stack entries until the stack is empty.
 898   void drain_evac_failure_scan_stack();
 899   // True iff an invocation of "drain_scan_stack" is in progress; to
 900   // prevent unnecessary recursion.
 901   bool _drain_in_progress;
 902 
 903   // Do any necessary initialization for evacuation-failure handling.
 904   // "cl" is the closure that will be used to process evac-failure
 905   // objects.
 906   void init_for_evac_failure(OopsInHeapRegionClosure* cl);
 907   // Do any necessary cleanup for evacuation-failure handling data
 908   // structures.
 909   void finalize_for_evac_failure();
 910 
 911   // An attempt to evacuate "obj" has failed; take necessary steps.
 912   oop handle_evacuation_failure_par(OopsInHeapRegionClosure* cl, oop obj);
 913   void handle_evacuation_failure_common(oop obj, markOop m);
 914 
 915 #ifndef PRODUCT
 916   // Support for forcing evacuation failures. Analogous to
 917   // PromotionFailureALot for the other collectors.
 918 
 919   // Records whether G1EvacuationFailureALot should be in effect
 920   // for the current GC
 921   bool _evacuation_failure_alot_for_current_gc;
 922 
 923   // Used to record the GC number for interval checking when
 924   // determining whether G1EvaucationFailureALot is in effect
 925   // for the current GC.
 926   size_t _evacuation_failure_alot_gc_number;
 927 
 928   // Count of the number of evacuations between failures.
 929   volatile size_t _evacuation_failure_alot_count;
 930 
 931   // Set whether G1EvacuationFailureALot should be in effect
 932   // for the current GC (based upon the type of GC and which
 933   // command line flags are set);
 934   inline bool evacuation_failure_alot_for_gc_type(bool gcs_are_young,
 935                                                   bool during_initial_mark,
 936                                                   bool during_marking);
 937 
 938   inline void set_evacuation_failure_alot_for_current_gc();
 939 
 940   // Return true if it's time to cause an evacuation failure.
 941   inline bool evacuation_should_fail();
 942 
 943   // Reset the G1EvacuationFailureALot counters.  Should be called at
 944   // the end of an evacuation pause in which an evacuation failure ocurred.
 945   inline void reset_evacuation_should_fail();
 946 #endif // !PRODUCT
 947 
 948   // ("Weak") Reference processing support.
 949   //
 950   // G1 has 2 instances of the referece processor class. One
 951   // (_ref_processor_cm) handles reference object discovery
 952   // and subsequent processing during concurrent marking cycles.
 953   //
 954   // The other (_ref_processor_stw) handles reference object
 955   // discovery and processing during full GCs and incremental
 956   // evacuation pauses.
 957   //
 958   // During an incremental pause, reference discovery will be
 959   // temporarily disabled for _ref_processor_cm and will be
 960   // enabled for _ref_processor_stw. At the end of the evacuation
 961   // pause references discovered by _ref_processor_stw will be
 962   // processed and discovery will be disabled. The previous
 963   // setting for reference object discovery for _ref_processor_cm
 964   // will be re-instated.
 965   //
 966   // At the start of marking:
 967   //  * Discovery by the CM ref processor is verified to be inactive
 968   //    and it's discovered lists are empty.
 969   //  * Discovery by the CM ref processor is then enabled.
 970   //
 971   // At the end of marking:
 972   //  * Any references on the CM ref processor's discovered
 973   //    lists are processed (possibly MT).
 974   //
 975   // At the start of full GC we:
 976   //  * Disable discovery by the CM ref processor and
 977   //    empty CM ref processor's discovered lists
 978   //    (without processing any entries).
 979   //  * Verify that the STW ref processor is inactive and it's
 980   //    discovered lists are empty.
 981   //  * Temporarily set STW ref processor discovery as single threaded.
 982   //  * Temporarily clear the STW ref processor's _is_alive_non_header
 983   //    field.
 984   //  * Finally enable discovery by the STW ref processor.
 985   //
 986   // The STW ref processor is used to record any discovered
 987   // references during the full GC.
 988   //
 989   // At the end of a full GC we:
 990   //  * Enqueue any reference objects discovered by the STW ref processor
 991   //    that have non-live referents. This has the side-effect of
 992   //    making the STW ref processor inactive by disabling discovery.
 993   //  * Verify that the CM ref processor is still inactive
 994   //    and no references have been placed on it's discovered
 995   //    lists (also checked as a precondition during initial marking).
 996 
 997   // The (stw) reference processor...
 998   ReferenceProcessor* _ref_processor_stw;
 999 
1000   // During reference object discovery, the _is_alive_non_header
1001   // closure (if non-null) is applied to the referent object to
1002   // determine whether the referent is live. If so then the
1003   // reference object does not need to be 'discovered' and can
1004   // be treated as a regular oop. This has the benefit of reducing
1005   // the number of 'discovered' reference objects that need to
1006   // be processed.
1007   //
1008   // Instance of the is_alive closure for embedding into the
1009   // STW reference processor as the _is_alive_non_header field.
1010   // Supplying a value for the _is_alive_non_header field is
1011   // optional but doing so prevents unnecessary additions to
1012   // the discovered lists during reference discovery.
1013   G1STWIsAliveClosure _is_alive_closure_stw;
1014 
1015   // The (concurrent marking) reference processor...
1016   ReferenceProcessor* _ref_processor_cm;
1017 
1018   // Instance of the concurrent mark is_alive closure for embedding
1019   // into the Concurrent Marking reference processor as the
1020   // _is_alive_non_header field. Supplying a value for the
1021   // _is_alive_non_header field is optional but doing so prevents
1022   // unnecessary additions to the discovered lists during reference
1023   // discovery.
1024   G1CMIsAliveClosure _is_alive_closure_cm;
1025 
1026   // Cache used by G1CollectedHeap::start_cset_region_for_worker().
1027   HeapRegion** _worker_cset_start_region;
1028 
1029   // Time stamp to validate the regions recorded in the cache
1030   // used by G1CollectedHeap::start_cset_region_for_worker().
1031   // The heap region entry for a given worker is valid iff
1032   // the associated time stamp value matches the current value
1033   // of G1CollectedHeap::_gc_time_stamp.
1034   unsigned int* _worker_cset_start_region_time_stamp;
1035 
1036   enum G1H_process_strong_roots_tasks {
1037     G1H_PS_filter_satb_buffers,
1038     G1H_PS_refProcessor_oops_do,
1039     // Leave this one last.
1040     G1H_PS_NumElements
1041   };
1042 
1043   SubTasksDone* _process_strong_tasks;
1044 
1045   volatile bool _free_regions_coming;
1046 
1047 public:
1048 
1049   SubTasksDone* process_strong_tasks() { return _process_strong_tasks; }
1050 
1051   void set_refine_cte_cl_concurrency(bool concurrent);
1052 
1053   RefToScanQueue *task_queue(int i) const;
1054 
1055   // A set of cards where updates happened during the GC
1056   DirtyCardQueueSet& dirty_card_queue_set() { return _dirty_card_queue_set; }
1057 
1058   // A DirtyCardQueueSet that is used to hold cards that contain
1059   // references into the current collection set. This is used to
1060   // update the remembered sets of the regions in the collection
1061   // set in the event of an evacuation failure.
1062   DirtyCardQueueSet& into_cset_dirty_card_queue_set()
1063         { return _into_cset_dirty_card_queue_set; }
1064 
1065   // Create a G1CollectedHeap with the specified policy.
1066   // Must call the initialize method afterwards.
1067   // May not return if something goes wrong.
1068   G1CollectedHeap(G1CollectorPolicy* policy);
1069 
1070   // Initialize the G1CollectedHeap to have the initial and
1071   // maximum sizes and remembered and barrier sets
1072   // specified by the policy object.
1073   jint initialize();
1074 
1075   // Initialize weak reference processing.
1076   virtual void ref_processing_init();
1077 
1078   void set_par_threads(uint t) {
1079     SharedHeap::set_par_threads(t);
1080     // Done in SharedHeap but oddly there are
1081     // two _process_strong_tasks's in a G1CollectedHeap
1082     // so do it here too.
1083     _process_strong_tasks->set_n_threads(t);
1084   }
1085 
1086   // Set _n_par_threads according to a policy TBD.
1087   void set_par_threads();
1088 
1089   void set_n_termination(int t) {
1090     _process_strong_tasks->set_n_threads(t);
1091   }
1092 
1093   virtual CollectedHeap::Name kind() const {
1094     return CollectedHeap::G1CollectedHeap;
1095   }
1096 
1097   // The current policy object for the collector.
1098   G1CollectorPolicy* g1_policy() const { return _g1_policy; }
1099 
1100   virtual CollectorPolicy* collector_policy() const { return (CollectorPolicy*) g1_policy(); }
1101 
1102   // Adaptive size policy.  No such thing for g1.
1103   virtual AdaptiveSizePolicy* size_policy() { return NULL; }
1104 
1105   // The rem set and barrier set.
1106   G1RemSet* g1_rem_set() const { return _g1_rem_set; }
1107   ModRefBarrierSet* mr_bs() const { return _mr_bs; }
1108 
1109   unsigned get_gc_time_stamp() {
1110     return _gc_time_stamp;
1111   }
1112 
1113   void reset_gc_time_stamp() {
1114     _gc_time_stamp = 0;
1115     OrderAccess::fence();
1116     // Clear the cached CSet starting regions and time stamps.
1117     // Their validity is dependent on the GC timestamp.
1118     clear_cset_start_regions();
1119   }
1120 
1121   void check_gc_time_stamps() PRODUCT_RETURN;
1122 
1123   void increment_gc_time_stamp() {
1124     ++_gc_time_stamp;
1125     OrderAccess::fence();
1126   }
1127 
1128   // Reset the given region's GC timestamp. If it's starts humongous,
1129   // also reset the GC timestamp of its corresponding
1130   // continues humongous regions too.
1131   void reset_gc_time_stamps(HeapRegion* hr);
1132 
1133   void iterate_dirty_card_closure(CardTableEntryClosure* cl,
1134                                   DirtyCardQueue* into_cset_dcq,
1135                                   bool concurrent, int worker_i);
1136 
1137   // The shared block offset table array.
1138   G1BlockOffsetSharedArray* bot_shared() const { return _bot_shared; }
1139 
1140   // Reference Processing accessors
1141 
1142   // The STW reference processor....
1143   ReferenceProcessor* ref_processor_stw() const { return _ref_processor_stw; }
1144 
1145   // The Concurent Marking reference processor...
1146   ReferenceProcessor* ref_processor_cm() const { return _ref_processor_cm; }
1147 
1148   virtual size_t capacity() const;
1149   virtual size_t used() const;
1150   // This should be called when we're not holding the heap lock. The
1151   // result might be a bit inaccurate.
1152   size_t used_unlocked() const;
1153   size_t recalculate_used() const;
1154 
1155   // These virtual functions do the actual allocation.
1156   // Some heaps may offer a contiguous region for shared non-blocking
1157   // allocation, via inlined code (by exporting the address of the top and
1158   // end fields defining the extent of the contiguous allocation region.)
1159   // But G1CollectedHeap doesn't yet support this.
1160 
1161   // Return an estimate of the maximum allocation that could be performed
1162   // without triggering any collection or expansion activity.  In a
1163   // generational collector, for example, this is probably the largest
1164   // allocation that could be supported (without expansion) in the youngest
1165   // generation.  It is "unsafe" because no locks are taken; the result
1166   // should be treated as an approximation, not a guarantee, for use in
1167   // heuristic resizing decisions.
1168   virtual size_t unsafe_max_alloc();
1169 
1170   virtual bool is_maximal_no_gc() const {
1171     return _g1_storage.uncommitted_size() == 0;
1172   }
1173 
1174   // The total number of regions in the heap.
1175   uint n_regions() { return _hrs.length(); }
1176 
1177   // The max number of regions in the heap.
1178   uint max_regions() { return _hrs.max_length(); }
1179 
1180   // The number of regions that are completely free.
1181   uint free_regions() { return _free_list.length(); }
1182 
1183   // The number of regions that are not completely free.
1184   uint used_regions() { return n_regions() - free_regions(); }
1185 
1186   // The number of regions available for "regular" expansion.
1187   uint expansion_regions() { return _expansion_regions; }
1188 
1189   // Factory method for HeapRegion instances. It will return NULL if
1190   // the allocation fails.
1191   HeapRegion* new_heap_region(uint hrs_index, HeapWord* bottom);
1192 
1193   void verify_not_dirty_region(HeapRegion* hr) PRODUCT_RETURN;
1194   void verify_dirty_region(HeapRegion* hr) PRODUCT_RETURN;
1195   void verify_dirty_young_list(HeapRegion* head) PRODUCT_RETURN;
1196   void verify_dirty_young_regions() PRODUCT_RETURN;
1197 
1198   // verify_region_sets() performs verification over the region
1199   // lists. It will be compiled in the product code to be used when
1200   // necessary (i.e., during heap verification).
1201   void verify_region_sets();
1202 
1203   // verify_region_sets_optional() is planted in the code for
1204   // list verification in non-product builds (and it can be enabled in
1205   // product builds by definning HEAP_REGION_SET_FORCE_VERIFY to be 1).
1206 #if HEAP_REGION_SET_FORCE_VERIFY
1207   void verify_region_sets_optional() {
1208     verify_region_sets();
1209   }
1210 #else // HEAP_REGION_SET_FORCE_VERIFY
1211   void verify_region_sets_optional() { }
1212 #endif // HEAP_REGION_SET_FORCE_VERIFY
1213 
1214 #ifdef ASSERT
1215   bool is_on_master_free_list(HeapRegion* hr) {
1216     return hr->containing_set() == &_free_list;
1217   }
1218 
1219   bool is_in_humongous_set(HeapRegion* hr) {
1220     return hr->containing_set() == &_humongous_set;
1221   }
1222 #endif // ASSERT
1223 
1224   // Wrapper for the region list operations that can be called from
1225   // methods outside this class.
1226 
1227   void secondary_free_list_add_as_tail(FreeRegionList* list) {
1228     _secondary_free_list.add_as_tail(list);
1229   }
1230 
1231   void append_secondary_free_list() {
1232     _free_list.add_as_head(&_secondary_free_list);
1233   }
1234 
1235   void append_secondary_free_list_if_not_empty_with_lock() {
1236     // If the secondary free list looks empty there's no reason to
1237     // take the lock and then try to append it.
1238     if (!_secondary_free_list.is_empty()) {
1239       MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag);
1240       append_secondary_free_list();
1241     }
1242   }
1243 
1244   void old_set_remove(HeapRegion* hr) {
1245     _old_set.remove(hr);
1246   }
1247 
1248   size_t non_young_capacity_bytes() {
1249     return _old_set.total_capacity_bytes() + _humongous_set.total_capacity_bytes();
1250   }
1251 
1252   void set_free_regions_coming();
1253   void reset_free_regions_coming();
1254   bool free_regions_coming() { return _free_regions_coming; }
1255   void wait_while_free_regions_coming();
1256 
1257   // Determine whether the given region is one that we are using as an
1258   // old GC alloc region.
1259   bool is_old_gc_alloc_region(HeapRegion* hr) {
1260     return hr == _retained_old_gc_alloc_region;
1261   }
1262 
1263   // Perform a collection of the heap; intended for use in implementing
1264   // "System.gc".  This probably implies as full a collection as the
1265   // "CollectedHeap" supports.
1266   virtual void collect(GCCause::Cause cause);
1267 
1268   // The same as above but assume that the caller holds the Heap_lock.
1269   void collect_locked(GCCause::Cause cause);
1270 
1271   // True iff a evacuation has failed in the most-recent collection.
1272   bool evacuation_failed() { return _evacuation_failed; }
1273 
1274   // It will free a region if it has allocated objects in it that are
1275   // all dead. It calls either free_region() or
1276   // free_humongous_region() depending on the type of the region that
1277   // is passed to it.
1278   void free_region_if_empty(HeapRegion* hr,
1279                             size_t* pre_used,
1280                             FreeRegionList* free_list,
1281                             OldRegionSet* old_proxy_set,
1282                             HumongousRegionSet* humongous_proxy_set,
1283                             HRRSCleanupTask* hrrs_cleanup_task,
1284                             bool par);
1285 
1286   // It appends the free list to the master free list and updates the
1287   // master humongous list according to the contents of the proxy
1288   // list. It also adjusts the total used bytes according to pre_used
1289   // (if par is true, it will do so by taking the ParGCRareEvent_lock).
1290   void update_sets_after_freeing_regions(size_t pre_used,
1291                                        FreeRegionList* free_list,
1292                                        OldRegionSet* old_proxy_set,
1293                                        HumongousRegionSet* humongous_proxy_set,
1294                                        bool par);
1295 
1296   // Returns "TRUE" iff "p" points into the committed areas of the heap.
1297   virtual bool is_in(const void* p) const;
1298 
1299   // Return "TRUE" iff the given object address is within the collection
1300   // set.
1301   inline bool obj_in_cs(oop obj);
1302 
1303   // Return "TRUE" iff the given object address is in the reserved
1304   // region of g1.
1305   bool is_in_g1_reserved(const void* p) const {
1306     return _g1_reserved.contains(p);
1307   }
1308 
1309   // Returns a MemRegion that corresponds to the space that has been
1310   // reserved for the heap
1311   MemRegion g1_reserved() {
1312     return _g1_reserved;
1313   }
1314 
1315   // Returns a MemRegion that corresponds to the space that has been
1316   // committed in the heap
1317   MemRegion g1_committed() {
1318     return _g1_committed;
1319   }
1320 
1321   virtual bool is_in_closed_subset(const void* p) const;
1322 
1323   // This resets the card table to all zeros.  It is used after
1324   // a collection pause which used the card table to claim cards.
1325   void cleanUpCardTable();
1326 
1327   // Iteration functions.
1328 
1329   // Iterate over all the ref-containing fields of all objects, calling
1330   // "cl.do_oop" on each.
1331   virtual void oop_iterate(ExtendedOopClosure* cl);
1332 
1333   // Same as above, restricted to a memory region.
1334   void oop_iterate(MemRegion mr, ExtendedOopClosure* cl);
1335 
1336   // Iterate over all objects, calling "cl.do_object" on each.
1337   virtual void object_iterate(ObjectClosure* cl);
1338 
1339   virtual void safe_object_iterate(ObjectClosure* cl) {
1340     object_iterate(cl);
1341   }
1342 
1343   // Iterate over all objects allocated since the last collection, calling
1344   // "cl.do_object" on each.  The heap must have been initialized properly
1345   // to support this function, or else this call will fail.
1346   virtual void object_iterate_since_last_GC(ObjectClosure* cl);
1347 
1348   // Iterate over all spaces in use in the heap, in ascending address order.
1349   virtual void space_iterate(SpaceClosure* cl);
1350 
1351   // Iterate over heap regions, in address order, terminating the
1352   // iteration early if the "doHeapRegion" method returns "true".
1353   void heap_region_iterate(HeapRegionClosure* blk) const;
1354 
1355   // Return the region with the given index. It assumes the index is valid.
1356   HeapRegion* region_at(uint index) const { return _hrs.at(index); }
1357 
1358   // Divide the heap region sequence into "chunks" of some size (the number
1359   // of regions divided by the number of parallel threads times some
1360   // overpartition factor, currently 4).  Assumes that this will be called
1361   // in parallel by ParallelGCThreads worker threads with discinct worker
1362   // ids in the range [0..max(ParallelGCThreads-1, 1)], that all parallel
1363   // calls will use the same "claim_value", and that that claim value is
1364   // different from the claim_value of any heap region before the start of
1365   // the iteration.  Applies "blk->doHeapRegion" to each of the regions, by
1366   // attempting to claim the first region in each chunk, and, if
1367   // successful, applying the closure to each region in the chunk (and
1368   // setting the claim value of the second and subsequent regions of the
1369   // chunk.)  For now requires that "doHeapRegion" always returns "false",
1370   // i.e., that a closure never attempt to abort a traversal.
1371   void heap_region_par_iterate_chunked(HeapRegionClosure* blk,
1372                                        uint worker,
1373                                        uint no_of_par_workers,
1374                                        jint claim_value);
1375 
1376   // It resets all the region claim values to the default.
1377   void reset_heap_region_claim_values();
1378 
1379   // Resets the claim values of regions in the current
1380   // collection set to the default.
1381   void reset_cset_heap_region_claim_values();
1382 
1383 #ifdef ASSERT
1384   bool check_heap_region_claim_values(jint claim_value);
1385 
1386   // Same as the routine above but only checks regions in the
1387   // current collection set.
1388   bool check_cset_heap_region_claim_values(jint claim_value);
1389 #endif // ASSERT
1390 
1391   // Clear the cached cset start regions and (more importantly)
1392   // the time stamps. Called when we reset the GC time stamp.
1393   void clear_cset_start_regions();
1394 
1395   // Given the id of a worker, obtain or calculate a suitable
1396   // starting region for iterating over the current collection set.
1397   HeapRegion* start_cset_region_for_worker(int worker_i);
1398 
1399   // This is a convenience method that is used by the
1400   // HeapRegionIterator classes to calculate the starting region for
1401   // each worker so that they do not all start from the same region.
1402   HeapRegion* start_region_for_worker(uint worker_i, uint no_of_par_workers);
1403 
1404   // Iterate over the regions (if any) in the current collection set.
1405   void collection_set_iterate(HeapRegionClosure* blk);
1406 
1407   // As above but starting from region r
1408   void collection_set_iterate_from(HeapRegion* r, HeapRegionClosure *blk);
1409 
1410   // Returns the first (lowest address) compactible space in the heap.
1411   virtual CompactibleSpace* first_compactible_space();
1412 
1413   // A CollectedHeap will contain some number of spaces.  This finds the
1414   // space containing a given address, or else returns NULL.
1415   virtual Space* space_containing(const void* addr) const;
1416 
1417   // A G1CollectedHeap will contain some number of heap regions.  This
1418   // finds the region containing a given address, or else returns NULL.
1419   template <class T>
1420   inline HeapRegion* heap_region_containing(const T addr) const;
1421 
1422   // Like the above, but requires "addr" to be in the heap (to avoid a
1423   // null-check), and unlike the above, may return an continuing humongous
1424   // region.
1425   template <class T>
1426   inline HeapRegion* heap_region_containing_raw(const T addr) const;
1427 
1428   // A CollectedHeap is divided into a dense sequence of "blocks"; that is,
1429   // each address in the (reserved) heap is a member of exactly
1430   // one block.  The defining characteristic of a block is that it is
1431   // possible to find its size, and thus to progress forward to the next
1432   // block.  (Blocks may be of different sizes.)  Thus, blocks may
1433   // represent Java objects, or they might be free blocks in a
1434   // free-list-based heap (or subheap), as long as the two kinds are
1435   // distinguishable and the size of each is determinable.
1436 
1437   // Returns the address of the start of the "block" that contains the
1438   // address "addr".  We say "blocks" instead of "object" since some heaps
1439   // may not pack objects densely; a chunk may either be an object or a
1440   // non-object.
1441   virtual HeapWord* block_start(const void* addr) const;
1442 
1443   // Requires "addr" to be the start of a chunk, and returns its size.
1444   // "addr + size" is required to be the start of a new chunk, or the end
1445   // of the active area of the heap.
1446   virtual size_t block_size(const HeapWord* addr) const;
1447 
1448   // Requires "addr" to be the start of a block, and returns "TRUE" iff
1449   // the block is an object.
1450   virtual bool block_is_obj(const HeapWord* addr) const;
1451 
1452   // Does this heap support heap inspection? (+PrintClassHistogram)
1453   virtual bool supports_heap_inspection() const { return true; }
1454 
1455   // Section on thread-local allocation buffers (TLABs)
1456   // See CollectedHeap for semantics.
1457 
1458   virtual bool supports_tlab_allocation() const;
1459   virtual size_t tlab_capacity(Thread* thr) const;
1460   virtual size_t unsafe_max_tlab_alloc(Thread* thr) const;
1461 
1462   // Can a compiler initialize a new object without store barriers?
1463   // This permission only extends from the creation of a new object
1464   // via a TLAB up to the first subsequent safepoint. If such permission
1465   // is granted for this heap type, the compiler promises to call
1466   // defer_store_barrier() below on any slow path allocation of
1467   // a new object for which such initializing store barriers will
1468   // have been elided. G1, like CMS, allows this, but should be
1469   // ready to provide a compensating write barrier as necessary
1470   // if that storage came out of a non-young region. The efficiency
1471   // of this implementation depends crucially on being able to
1472   // answer very efficiently in constant time whether a piece of
1473   // storage in the heap comes from a young region or not.
1474   // See ReduceInitialCardMarks.
1475   virtual bool can_elide_tlab_store_barriers() const {
1476     return true;
1477   }
1478 
1479   virtual bool card_mark_must_follow_store() const {
1480     return true;
1481   }
1482 
1483   bool is_in_young(const oop obj) {
1484     HeapRegion* hr = heap_region_containing(obj);
1485     return hr != NULL && hr->is_young();
1486   }
1487 
1488 #ifdef ASSERT
1489   virtual bool is_in_partial_collection(const void* p);
1490 #endif
1491 
1492   virtual bool is_scavengable(const void* addr);
1493 
1494   // We don't need barriers for initializing stores to objects
1495   // in the young gen: for the SATB pre-barrier, there is no
1496   // pre-value that needs to be remembered; for the remembered-set
1497   // update logging post-barrier, we don't maintain remembered set
1498   // information for young gen objects.
1499   virtual bool can_elide_initializing_store_barrier(oop new_obj) {
1500     return is_in_young(new_obj);
1501   }
1502 
1503   // Returns "true" iff the given word_size is "very large".
1504   static bool isHumongous(size_t word_size) {
1505     // Note this has to be strictly greater-than as the TLABs
1506     // are capped at the humongous thresold and we want to
1507     // ensure that we don't try to allocate a TLAB as
1508     // humongous and that we don't allocate a humongous
1509     // object in a TLAB.
1510     return word_size > _humongous_object_threshold_in_words;
1511   }
1512 
1513   // Update mod union table with the set of dirty cards.
1514   void updateModUnion();
1515 
1516   // Set the mod union bits corresponding to the given memRegion.  Note
1517   // that this is always a safe operation, since it doesn't clear any
1518   // bits.
1519   void markModUnionRange(MemRegion mr);
1520 
1521   // Records the fact that a marking phase is no longer in progress.
1522   void set_marking_complete() {
1523     _mark_in_progress = false;
1524   }
1525   void set_marking_started() {
1526     _mark_in_progress = true;
1527   }
1528   bool mark_in_progress() {
1529     return _mark_in_progress;
1530   }
1531 
1532   // Print the maximum heap capacity.
1533   virtual size_t max_capacity() const;
1534 
1535   virtual jlong millis_since_last_gc();
1536 
1537   // Convenience function to be used in situations where the heap type can be
1538   // asserted to be this type.
1539   static G1CollectedHeap* heap();
1540 
1541   void set_region_short_lived_locked(HeapRegion* hr);
1542   // add appropriate methods for any other surv rate groups
1543 
1544   YoungList* young_list() { return _young_list; }
1545 
1546   // debugging
1547   bool check_young_list_well_formed() {
1548     return _young_list->check_list_well_formed();
1549   }
1550 
1551   bool check_young_list_empty(bool check_heap,
1552                               bool check_sample = true);
1553 
1554   // *** Stuff related to concurrent marking.  It's not clear to me that so
1555   // many of these need to be public.
1556 
1557   // The functions below are helper functions that a subclass of
1558   // "CollectedHeap" can use in the implementation of its virtual
1559   // functions.
1560   // This performs a concurrent marking of the live objects in a
1561   // bitmap off to the side.
1562   void doConcurrentMark();
1563 
1564   bool isMarkedPrev(oop obj) const;
1565   bool isMarkedNext(oop obj) const;
1566 
1567   // Determine if an object is dead, given the object and also
1568   // the region to which the object belongs. An object is dead
1569   // iff a) it was not allocated since the last mark and b) it
1570   // is not marked.
1571 
1572   bool is_obj_dead(const oop obj, const HeapRegion* hr) const {
1573     return
1574       !hr->obj_allocated_since_prev_marking(obj) &&
1575       !isMarkedPrev(obj);
1576   }
1577 
1578   // This function returns true when an object has been
1579   // around since the previous marking and hasn't yet
1580   // been marked during this marking.
1581 
1582   bool is_obj_ill(const oop obj, const HeapRegion* hr) const {
1583     return
1584       !hr->obj_allocated_since_next_marking(obj) &&
1585       !isMarkedNext(obj);
1586   }
1587 
1588   // Determine if an object is dead, given only the object itself.
1589   // This will find the region to which the object belongs and
1590   // then call the region version of the same function.
1591 
1592   // Added if it is NULL it isn't dead.
1593 
1594   bool is_obj_dead(const oop obj) const {
1595     const HeapRegion* hr = heap_region_containing(obj);
1596     if (hr == NULL) {
1597       if (obj == NULL) return false;
1598       else return true;
1599     }
1600     else return is_obj_dead(obj, hr);
1601   }
1602 
1603   bool is_obj_ill(const oop obj) const {
1604     const HeapRegion* hr = heap_region_containing(obj);
1605     if (hr == NULL) {
1606       if (obj == NULL) return false;
1607       else return true;
1608     }
1609     else return is_obj_ill(obj, hr);
1610   }
1611 
1612   bool allocated_since_marking(oop obj, HeapRegion* hr, VerifyOption vo);
1613   HeapWord* top_at_mark_start(HeapRegion* hr, VerifyOption vo);
1614   bool is_marked(oop obj, VerifyOption vo);
1615   const char* top_at_mark_start_str(VerifyOption vo);
1616 
1617   ConcurrentMark* concurrent_mark() const { return _cm; }
1618 
1619   // Refinement
1620 
1621   ConcurrentG1Refine* concurrent_g1_refine() const { return _cg1r; }
1622 
1623   // The dirty cards region list is used to record a subset of regions
1624   // whose cards need clearing. The list if populated during the
1625   // remembered set scanning and drained during the card table
1626   // cleanup. Although the methods are reentrant, population/draining
1627   // phases must not overlap. For synchronization purposes the last
1628   // element on the list points to itself.
1629   HeapRegion* _dirty_cards_region_list;
1630   void push_dirty_cards_region(HeapRegion* hr);
1631   HeapRegion* pop_dirty_cards_region();
1632 
1633   // Optimized nmethod scanning support routines
1634 
1635   // Register the given nmethod with the G1 heap
1636   virtual void register_nmethod(nmethod* nm);
1637 
1638   // Unregister the given nmethod from the G1 heap
1639   virtual void unregister_nmethod(nmethod* nm);
1640 
1641   // Migrate the nmethods in the code root lists of the regions
1642   // in the collection set to regions in to-space. In the event
1643   // of an evacuation failure, nmethods that reference objects
1644   // that were not successfullly evacuated are not migrated.
1645   void migrate_strong_code_roots();
1646 
1647   // During an initial mark pause, mark all the code roots that
1648   // point into regions *not* in the collection set.
1649   void mark_strong_code_roots(uint worker_id);
1650 
1651   // Rebuild the stong code root lists for each region
1652   // after a full GC
1653   void rebuild_strong_code_roots();
1654 
1655   // Verification
1656 
1657   // The following is just to alert the verification code
1658   // that a full collection has occurred and that the
1659   // remembered sets are no longer up to date.
1660   bool _full_collection;
1661   void set_full_collection() { _full_collection = true;}
1662   void clear_full_collection() {_full_collection = false;}
1663   bool full_collection() {return _full_collection;}
1664 
1665   // Perform any cleanup actions necessary before allowing a verification.
1666   virtual void prepare_for_verify();
1667 
1668   // Perform verification.
1669 
1670   // vo == UsePrevMarking  -> use "prev" marking information,
1671   // vo == UseNextMarking -> use "next" marking information
1672   // vo == UseMarkWord    -> use the mark word in the object header
1673   //
1674   // NOTE: Only the "prev" marking information is guaranteed to be
1675   // consistent most of the time, so most calls to this should use
1676   // vo == UsePrevMarking.
1677   // Currently, there is only one case where this is called with
1678   // vo == UseNextMarking, which is to verify the "next" marking
1679   // information at the end of remark.
1680   // Currently there is only one place where this is called with
1681   // vo == UseMarkWord, which is to verify the marking during a
1682   // full GC.
1683   void verify(bool silent, VerifyOption vo);
1684 
1685   // Override; it uses the "prev" marking information
1686   virtual void verify(bool silent);
1687 
1688   // The methods below are here for convenience and dispatch the
1689   // appropriate method depending on value of the given VerifyOption
1690   // parameter. The values for that parameter, and their meanings,
1691   // are the same as those above.
1692 
1693   bool is_obj_dead_cond(const oop obj,
1694                         const HeapRegion* hr,
1695                         const VerifyOption vo) const {
1696     switch (vo) {
1697     case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj, hr);
1698     case VerifyOption_G1UseNextMarking: return is_obj_ill(obj, hr);
1699     case VerifyOption_G1UseMarkWord:    return !obj->is_gc_marked();
1700     default:                            ShouldNotReachHere();
1701     }
1702     return false; // keep some compilers happy
1703   }
1704 
1705   bool is_obj_dead_cond(const oop obj,
1706                         const VerifyOption vo) const {
1707     switch (vo) {
1708     case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj);
1709     case VerifyOption_G1UseNextMarking: return is_obj_ill(obj);
1710     case VerifyOption_G1UseMarkWord:    return !obj->is_gc_marked();
1711     default:                            ShouldNotReachHere();
1712     }
1713     return false; // keep some compilers happy
1714   }
1715 
1716   // Printing
1717 
1718   virtual void print_on(outputStream* st) const;
1719   virtual void print_extended_on(outputStream* st) const;
1720   virtual void print_on_error(outputStream* st) const;
1721 
1722   virtual void print_gc_threads_on(outputStream* st) const;
1723   virtual void gc_threads_do(ThreadClosure* tc) const;
1724 
1725   // Override
1726   void print_tracing_info() const;
1727 
1728   // The following two methods are helpful for debugging RSet issues.
1729   void print_cset_rsets() PRODUCT_RETURN;
1730   void print_all_rsets() PRODUCT_RETURN;
1731 
1732 public:
1733   void stop_conc_gc_threads();
1734 
1735   size_t pending_card_num();
1736   size_t cards_scanned();
1737 
1738 protected:
1739   size_t _max_heap_capacity;
1740 };
1741 
1742 class G1ParGCAllocBuffer: public ParGCAllocBuffer {
1743 private:
1744   bool        _retired;
1745 
1746 public:
1747   G1ParGCAllocBuffer(size_t gclab_word_size);
1748 
1749   void set_buf(HeapWord* buf) {
1750     ParGCAllocBuffer::set_buf(buf);
1751     _retired = false;
1752   }
1753 
1754   void retire(bool end_of_gc, bool retain) {
1755     if (_retired)
1756       return;
1757     ParGCAllocBuffer::retire(end_of_gc, retain);
1758     _retired = true;
1759   }
1760 
1761   bool is_retired() {
1762     return _retired;
1763   }
1764 };
1765 
1766 class G1ParGCAllocBufferContainer {
1767 protected:
1768   static int const _priority_max = 2;
1769   G1ParGCAllocBuffer* _priority_buffer[_priority_max];
1770 
1771 public:
1772   G1ParGCAllocBufferContainer(size_t gclab_word_size) {
1773     for (int pr = 0; pr < _priority_max; ++pr) {
1774       _priority_buffer[pr] = new G1ParGCAllocBuffer(gclab_word_size);
1775     }
1776   }
1777 
1778   ~G1ParGCAllocBufferContainer() {
1779     for (int pr = 0; pr < _priority_max; ++pr) {
1780       assert(_priority_buffer[pr]->is_retired(), "alloc buffers should all retire at this point.");
1781       delete _priority_buffer[pr];
1782     }
1783   }
1784 
1785   HeapWord* allocate(size_t word_sz) {
1786     HeapWord* obj;
1787     for (int pr = 0; pr < _priority_max; ++pr) {
1788       obj = _priority_buffer[pr]->allocate(word_sz);
1789       if (obj != NULL) return obj;
1790     }
1791     return obj;
1792   }
1793 
1794   bool contains(void* addr) {
1795     for (int pr = 0; pr < _priority_max; ++pr) {
1796       if (_priority_buffer[pr]->contains(addr)) return true;
1797     }
1798     return false;
1799   }
1800 
1801   void undo_allocation(HeapWord* obj, size_t word_sz) {
1802     bool finish_undo;
1803     for (int pr = 0; pr < _priority_max; ++pr) {
1804       if (_priority_buffer[pr]->contains(obj)) {
1805         _priority_buffer[pr]->undo_allocation(obj, word_sz);
1806         finish_undo = true;
1807       }
1808     }
1809     if (!finish_undo) ShouldNotReachHere();
1810   }
1811 
1812   size_t words_remaining() {
1813     size_t result = 0;
1814     for (int pr = 0; pr < _priority_max; ++pr) {
1815       result += _priority_buffer[pr]->words_remaining();
1816     }
1817     return result;
1818   }
1819 
1820   size_t words_remaining_in_retired_buffer() {
1821     G1ParGCAllocBuffer* retired = _priority_buffer[0];
1822     return retired->words_remaining();
1823   }
1824 
1825   void flush_stats_and_retire(PLABStats* stats, bool end_of_gc, bool retain) {
1826     for (int pr = 0; pr < _priority_max; ++pr) {
1827       _priority_buffer[pr]->flush_stats_and_retire(stats, end_of_gc, retain);
1828     }
1829   }
1830 
1831   void update(bool end_of_gc, bool retain, HeapWord* buf, size_t word_sz) {
1832     G1ParGCAllocBuffer* retired_and_set = _priority_buffer[0];
1833     retired_and_set->retire(end_of_gc, retain);
1834     retired_and_set->set_buf(buf);
1835     retired_and_set->set_word_size(word_sz);
1836     adjust_priority_order();
1837   }
1838 
1839 private:
1840   void adjust_priority_order() {
1841     G1ParGCAllocBuffer* retired_and_set = _priority_buffer[0];
1842 
1843     int last = _priority_max - 1;
1844     for (int pr = 0; pr < last; ++pr) {
1845       _priority_buffer[pr] = _priority_buffer[pr + 1];
1846     }
1847     _priority_buffer[last] = retired_and_set;
1848   }
1849 };
1850 
1851 class G1ParScanThreadState : public StackObj {
1852 protected:
1853   G1CollectedHeap* _g1h;
1854   RefToScanQueue*  _refs;
1855   DirtyCardQueue   _dcq;
1856   CardTableModRefBS* _ct_bs;
1857   G1RemSet* _g1_rem;
1858 
1859   G1ParGCAllocBufferContainer  _surviving_alloc_buffer;
1860   G1ParGCAllocBufferContainer  _tenured_alloc_buffer;
1861   G1ParGCAllocBufferContainer* _alloc_buffers[GCAllocPurposeCount];
1862   ageTable            _age_table;
1863 
1864   size_t           _alloc_buffer_waste;
1865   size_t           _undo_waste;
1866 
1867   OopsInHeapRegionClosure*      _evac_failure_cl;
1868   G1ParScanHeapEvacClosure*     _evac_cl;
1869   G1ParScanPartialArrayClosure* _partial_scan_cl;
1870 
1871   int _hash_seed;
1872   uint _queue_num;
1873 
1874   size_t _term_attempts;
1875 
1876   double _start;
1877   double _start_strong_roots;
1878   double _strong_roots_time;
1879   double _start_term;
1880   double _term_time;
1881 
1882   // Map from young-age-index (0 == not young, 1 is youngest) to
1883   // surviving words. base is what we get back from the malloc call
1884   size_t* _surviving_young_words_base;
1885   // this points into the array, as we use the first few entries for padding
1886   size_t* _surviving_young_words;
1887 
1888 #define PADDING_ELEM_NUM (DEFAULT_CACHE_LINE_SIZE / sizeof(size_t))
1889 
1890   void   add_to_alloc_buffer_waste(size_t waste) { _alloc_buffer_waste += waste; }
1891 
1892   void   add_to_undo_waste(size_t waste)         { _undo_waste += waste; }
1893 
1894   DirtyCardQueue& dirty_card_queue()             { return _dcq;  }
1895   CardTableModRefBS* ctbs()                      { return _ct_bs; }
1896 
1897   template <class T> void immediate_rs_update(HeapRegion* from, T* p, int tid) {
1898     if (!from->is_survivor()) {
1899       _g1_rem->par_write_ref(from, p, tid);
1900     }
1901   }
1902 
1903   template <class T> void deferred_rs_update(HeapRegion* from, T* p, int tid) {
1904     // If the new value of the field points to the same region or
1905     // is the to-space, we don't need to include it in the Rset updates.
1906     if (!from->is_in_reserved(oopDesc::load_decode_heap_oop(p)) && !from->is_survivor()) {
1907       size_t card_index = ctbs()->index_for(p);
1908       // If the card hasn't been added to the buffer, do it.
1909       if (ctbs()->mark_card_deferred(card_index)) {
1910         dirty_card_queue().enqueue((jbyte*)ctbs()->byte_for_index(card_index));
1911       }
1912     }
1913   }
1914 
1915 public:
1916   G1ParScanThreadState(G1CollectedHeap* g1h, uint queue_num);
1917 
1918   ~G1ParScanThreadState() {
1919     FREE_C_HEAP_ARRAY(size_t, _surviving_young_words_base, mtGC);
1920   }
1921 
1922   RefToScanQueue*   refs()            { return _refs;             }
1923   ageTable*         age_table()       { return &_age_table;       }
1924 
1925   G1ParGCAllocBufferContainer* alloc_buffer(GCAllocPurpose purpose) {
1926     return _alloc_buffers[purpose];
1927   }
1928 
1929   size_t alloc_buffer_waste() const              { return _alloc_buffer_waste; }
1930   size_t undo_waste() const                      { return _undo_waste; }
1931 
1932 #ifdef ASSERT
1933   bool verify_ref(narrowOop* ref) const;
1934   bool verify_ref(oop* ref) const;
1935   bool verify_task(StarTask ref) const;
1936 #endif // ASSERT
1937 
1938   template <class T> void push_on_queue(T* ref) {
1939     assert(verify_ref(ref), "sanity");
1940     refs()->push(ref);
1941   }
1942 
1943   template <class T> void update_rs(HeapRegion* from, T* p, int tid) {
1944     if (G1DeferredRSUpdate) {
1945       deferred_rs_update(from, p, tid);
1946     } else {
1947       immediate_rs_update(from, p, tid);
1948     }
1949   }
1950 
1951   HeapWord* allocate_slow(GCAllocPurpose purpose, size_t word_sz) {
1952     HeapWord* obj = NULL;
1953     size_t gclab_word_size = _g1h->desired_plab_sz(purpose);
1954     if (word_sz * 100 < gclab_word_size * ParallelGCBufferWastePct) {
1955       G1ParGCAllocBufferContainer* alloc_buf = alloc_buffer(purpose);
1956 
1957       HeapWord* buf = _g1h->par_allocate_during_gc(purpose, gclab_word_size);
1958       if (buf == NULL) return NULL; // Let caller handle allocation failure.
1959 
1960       add_to_alloc_buffer_waste(alloc_buf->words_remaining_in_retired_buffer());
1961       alloc_buf->update(false /* end_of_gc */, false /* retain */, buf, gclab_word_size);
1962 
1963       obj = alloc_buf->allocate(word_sz);
1964       assert(obj != NULL, "buffer was definitely big enough...");
1965     } else {
1966       obj = _g1h->par_allocate_during_gc(purpose, word_sz);
1967     }
1968     return obj;
1969   }
1970 
1971   HeapWord* allocate(GCAllocPurpose purpose, size_t word_sz) {
1972     HeapWord* obj = alloc_buffer(purpose)->allocate(word_sz);
1973     if (obj != NULL) return obj;
1974     return allocate_slow(purpose, word_sz);
1975   }
1976 
1977   void undo_allocation(GCAllocPurpose purpose, HeapWord* obj, size_t word_sz) {
1978     if (alloc_buffer(purpose)->contains(obj)) {
1979       assert(alloc_buffer(purpose)->contains(obj + word_sz - 1),
1980              "should contain whole object");
1981       alloc_buffer(purpose)->undo_allocation(obj, word_sz);
1982     } else {
1983       CollectedHeap::fill_with_object(obj, word_sz);
1984       add_to_undo_waste(word_sz);
1985     }
1986   }
1987 
1988   void set_evac_failure_closure(OopsInHeapRegionClosure* evac_failure_cl) {
1989     _evac_failure_cl = evac_failure_cl;
1990   }
1991   OopsInHeapRegionClosure* evac_failure_closure() {
1992     return _evac_failure_cl;
1993   }
1994 
1995   void set_evac_closure(G1ParScanHeapEvacClosure* evac_cl) {
1996     _evac_cl = evac_cl;
1997   }
1998 
1999   void set_partial_scan_closure(G1ParScanPartialArrayClosure* partial_scan_cl) {
2000     _partial_scan_cl = partial_scan_cl;
2001   }
2002 
2003   int* hash_seed() { return &_hash_seed; }
2004   uint queue_num() { return _queue_num; }
2005 
2006   size_t term_attempts() const  { return _term_attempts; }
2007   void note_term_attempt() { _term_attempts++; }
2008 
2009   void start_strong_roots() {
2010     _start_strong_roots = os::elapsedTime();
2011   }
2012   void end_strong_roots() {
2013     _strong_roots_time += (os::elapsedTime() - _start_strong_roots);
2014   }
2015   double strong_roots_time() const { return _strong_roots_time; }
2016 
2017   void start_term_time() {
2018     note_term_attempt();
2019     _start_term = os::elapsedTime();
2020   }
2021   void end_term_time() {
2022     _term_time += (os::elapsedTime() - _start_term);
2023   }
2024   double term_time() const { return _term_time; }
2025 
2026   double elapsed_time() const {
2027     return os::elapsedTime() - _start;
2028   }
2029 
2030   static void
2031     print_termination_stats_hdr(outputStream* const st = gclog_or_tty);
2032   void
2033     print_termination_stats(int i, outputStream* const st = gclog_or_tty) const;
2034 
2035   size_t* surviving_young_words() {
2036     // We add on to hide entry 0 which accumulates surviving words for
2037     // age -1 regions (i.e. non-young ones)
2038     return _surviving_young_words;
2039   }
2040 
2041   void retire_alloc_buffers() {
2042     for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
2043       size_t waste = _alloc_buffers[ap]->words_remaining();
2044       add_to_alloc_buffer_waste(waste);
2045       _alloc_buffers[ap]->flush_stats_and_retire(_g1h->stats_for_purpose((GCAllocPurpose)ap),
2046                                                  true /* end_of_gc */,
2047                                                  false /* retain */);
2048     }
2049   }
2050 
2051   template <class T> void deal_with_reference(T* ref_to_scan) {
2052     if (has_partial_array_mask(ref_to_scan)) {
2053       _partial_scan_cl->do_oop_nv(ref_to_scan);
2054     } else {
2055       // Note: we can use "raw" versions of "region_containing" because
2056       // "obj_to_scan" is definitely in the heap, and is not in a
2057       // humongous region.
2058       HeapRegion* r = _g1h->heap_region_containing_raw(ref_to_scan);
2059       _evac_cl->set_region(r);
2060       _evac_cl->do_oop_nv(ref_to_scan);
2061     }
2062   }
2063 
2064   void deal_with_reference(StarTask ref) {
2065     assert(verify_task(ref), "sanity");
2066     if (ref.is_narrow()) {
2067       deal_with_reference((narrowOop*)ref);
2068     } else {
2069       deal_with_reference((oop*)ref);
2070     }
2071   }
2072 
2073   void trim_queue();
2074 };
2075 
2076 #endif // SHARE_VM_GC_IMPLEMENTATION_G1_G1COLLECTEDHEAP_HPP