1 /*
   2  * Copyright (c) 2013, 2018, Red Hat, Inc. All rights reserved.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.
   7  *
   8  * This code is distributed in the hope that it will be useful, but WITHOUT
   9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  11  * version 2 for more details (a copy is included in the LICENSE file that
  12  * accompanied this code).
  13  *
  14  * You should have received a copy of the GNU General Public License version
  15  * 2 along with this work; if not, write to the Free Software Foundation,
  16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  17  *
  18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19  * or visit www.oracle.com if you need additional information or have any
  20  * questions.
  21  *
  22  */
  23 
  24 #include "precompiled.hpp"
  25 #include "memory/allocation.hpp"
  26 
  27 #include "gc_implementation/shared/gcTimer.hpp"
  28 #include "gc_implementation/shenandoah/shenandoahGCTraceTime.hpp"
  29 
  30 #include "gc_implementation/shenandoah/shenandoahBarrierSet.hpp"
  31 #include "gc_implementation/shenandoah/shenandoahClosures.inline.hpp"
  32 #include "gc_implementation/shenandoah/shenandoahCollectionSet.hpp"
  33 #include "gc_implementation/shenandoah/shenandoahCollectorPolicy.hpp"
  34 #include "gc_implementation/shenandoah/shenandoahConcurrentMark.inline.hpp"
  35 #include "gc_implementation/shenandoah/shenandoahControlThread.hpp"
  36 #include "gc_implementation/shenandoah/shenandoahFreeSet.hpp"
  37 #include "gc_implementation/shenandoah/shenandoahPhaseTimings.hpp"
  38 #include "gc_implementation/shenandoah/shenandoahHeap.inline.hpp"
  39 #include "gc_implementation/shenandoah/shenandoahHeapRegion.inline.hpp"
  40 #include "gc_implementation/shenandoah/shenandoahHeapRegionSet.hpp"
  41 #include "gc_implementation/shenandoah/shenandoahMarkCompact.hpp"
  42 #include "gc_implementation/shenandoah/shenandoahMarkingContext.inline.hpp"
  43 #include "gc_implementation/shenandoah/shenandoahMonitoringSupport.hpp"
  44 #include "gc_implementation/shenandoah/shenandoahMetrics.hpp"
  45 #include "gc_implementation/shenandoah/shenandoahOopClosures.inline.hpp"
  46 #include "gc_implementation/shenandoah/shenandoahPacer.inline.hpp"
  47 #include "gc_implementation/shenandoah/shenandoahPadding.hpp"
  48 #include "gc_implementation/shenandoah/shenandoahParallelCleaning.hpp"
  49 #include "gc_implementation/shenandoah/shenandoahRootProcessor.inline.hpp"
  50 #include "gc_implementation/shenandoah/shenandoahTaskqueue.hpp"
  51 #include "gc_implementation/shenandoah/shenandoahUtils.hpp"
  52 #include "gc_implementation/shenandoah/shenandoahVerifier.hpp"
  53 #include "gc_implementation/shenandoah/shenandoahCodeRoots.hpp"
  54 #include "gc_implementation/shenandoah/shenandoahVMOperations.hpp"
  55 #include "gc_implementation/shenandoah/shenandoahWorkGroup.hpp"
  56 #include "gc_implementation/shenandoah/shenandoahWorkerPolicy.hpp"
  57 #include "gc_implementation/shenandoah/heuristics/shenandoahHeuristics.hpp"
  58 #include "gc_implementation/shenandoah/mode/shenandoahIUMode.hpp"
  59 #include "gc_implementation/shenandoah/mode/shenandoahPassiveMode.hpp"
  60 #include "gc_implementation/shenandoah/mode/shenandoahSATBMode.hpp"
  61 
  62 #include "memory/metaspace.hpp"
  63 #include "runtime/vmThread.hpp"
  64 #include "services/mallocTracker.hpp"
  65 
  66 ShenandoahHeap* ShenandoahHeap::_heap = NULL;
  67 
  68 class ShenandoahPretouchHeapTask : public AbstractGangTask {
  69 private:
  70   ShenandoahRegionIterator _regions;
  71   const size_t _page_size;
  72 public:
  73   ShenandoahPretouchHeapTask(size_t page_size) :
  74     AbstractGangTask("Shenandoah Pretouch Heap"),
  75     _page_size(page_size) {}
  76 
  77   virtual void work(uint worker_id) {
  78     ShenandoahHeapRegion* r = _regions.next();
  79     while (r != NULL) {
  80       if (r->is_committed()) {
  81         os::pretouch_memory((char *) r->bottom(), (char *) r->end());
  82       }
  83       r = _regions.next();
  84     }
  85   }
  86 };
  87 
  88 class ShenandoahPretouchBitmapTask : public AbstractGangTask {
  89 private:
  90   ShenandoahRegionIterator _regions;
  91   char* _bitmap_base;
  92   const size_t _bitmap_size;
  93   const size_t _page_size;
  94 public:
  95   ShenandoahPretouchBitmapTask(char* bitmap_base, size_t bitmap_size, size_t page_size) :
  96     AbstractGangTask("Shenandoah Pretouch Bitmap"),
  97     _bitmap_base(bitmap_base),
  98     _bitmap_size(bitmap_size),
  99     _page_size(page_size) {}
 100 
 101   virtual void work(uint worker_id) {
 102     ShenandoahHeapRegion* r = _regions.next();
 103     while (r != NULL) {
 104       size_t start = r->index()       * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
 105       size_t end   = (r->index() + 1) * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
 106       assert (end <= _bitmap_size, err_msg("end is sane: " SIZE_FORMAT " < " SIZE_FORMAT, end, _bitmap_size));
 107 
 108       if (r->is_committed()) {
 109         os::pretouch_memory(_bitmap_base + start, _bitmap_base + end);
 110       }
 111 
 112       r = _regions.next();
 113     }
 114   }
 115 };
 116 
 117 jint ShenandoahHeap::initialize() {
 118   CollectedHeap::pre_initialize();
 119 
 120   //
 121   // Figure out heap sizing
 122   //
 123 
 124   size_t init_byte_size = collector_policy()->initial_heap_byte_size();
 125   size_t min_byte_size  = collector_policy()->min_heap_byte_size();
 126   size_t max_byte_size  = collector_policy()->max_heap_byte_size();
 127   size_t heap_alignment = collector_policy()->heap_alignment();
 128 
 129   size_t reg_size_bytes = ShenandoahHeapRegion::region_size_bytes();
 130 
 131   Universe::check_alignment(max_byte_size,  reg_size_bytes, "Shenandoah heap");
 132   Universe::check_alignment(init_byte_size, reg_size_bytes, "Shenandoah heap");
 133 
 134   _num_regions = ShenandoahHeapRegion::region_count();
 135 
 136   // Now we know the number of regions, initialize the heuristics.
 137   initialize_heuristics();
 138 
 139   size_t num_committed_regions = init_byte_size / reg_size_bytes;
 140   num_committed_regions = MIN2(num_committed_regions, _num_regions);
 141   assert(num_committed_regions <= _num_regions, "sanity");
 142   _initial_size = num_committed_regions * reg_size_bytes;
 143 
 144   size_t num_min_regions = min_byte_size / reg_size_bytes;
 145   num_min_regions = MIN2(num_min_regions, _num_regions);
 146   assert(num_min_regions <= _num_regions, "sanity");
 147   _minimum_size = num_min_regions * reg_size_bytes;
 148 
 149   _committed = _initial_size;
 150 
 151   size_t heap_page_size   = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 152   size_t bitmap_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 153   size_t region_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 154 
 155   //
 156   // Reserve and commit memory for heap
 157   //
 158 
 159   ReservedSpace heap_rs = Universe::reserve_heap(max_byte_size, heap_alignment);
 160   _reserved.set_word_size(0);
 161   _reserved.set_start((HeapWord*)heap_rs.base());
 162   _reserved.set_end((HeapWord*)(heap_rs.base() + heap_rs.size()));
 163   _heap_region = MemRegion((HeapWord*)heap_rs.base(), heap_rs.size() / HeapWordSize);
 164   _heap_region_special = heap_rs.special();
 165 
 166   assert((((size_t) base()) & ShenandoahHeapRegion::region_size_bytes_mask()) == 0,
 167          err_msg("Misaligned heap: " PTR_FORMAT, p2i(base())));
 168 
 169 #if SHENANDOAH_OPTIMIZED_OBJTASK
 170   // The optimized ObjArrayChunkedTask takes some bits away from the full object bits.
 171   // Fail if we ever attempt to address more than we can.
 172   if ((uintptr_t)(heap_rs.base() + heap_rs.size()) >= ObjArrayChunkedTask::max_addressable()) {
 173     FormatBuffer<512> buf("Shenandoah reserved [" PTR_FORMAT ", " PTR_FORMAT") for the heap, \n"
 174                           "but max object address is " PTR_FORMAT ". Try to reduce heap size, or try other \n"
 175                           "VM options that allocate heap at lower addresses (HeapBaseMinAddress, AllocateHeapAt, etc).",
 176                 p2i(heap_rs.base()), p2i(heap_rs.base() + heap_rs.size()), ObjArrayChunkedTask::max_addressable());
 177     vm_exit_during_initialization("Fatal Error", buf);
 178   }
 179 #endif
 180 
 181   ReservedSpace sh_rs = heap_rs.first_part(max_byte_size);
 182   if (!_heap_region_special) {
 183     os::commit_memory_or_exit(sh_rs.base(), _initial_size, heap_alignment, false,
 184                               "Cannot commit heap memory");
 185   }
 186 
 187   //
 188   // Reserve and commit memory for bitmap(s)
 189   //
 190 
 191   _bitmap_size = MarkBitMap::compute_size(heap_rs.size());
 192   _bitmap_size = align_size_up(_bitmap_size, bitmap_page_size);
 193 
 194   size_t bitmap_bytes_per_region = reg_size_bytes / MarkBitMap::heap_map_factor();
 195 
 196   guarantee(bitmap_bytes_per_region != 0,
 197             err_msg("Bitmap bytes per region should not be zero"));
 198   guarantee(is_power_of_2(bitmap_bytes_per_region),
 199             err_msg("Bitmap bytes per region should be power of two: " SIZE_FORMAT, bitmap_bytes_per_region));
 200 
 201   if (bitmap_page_size > bitmap_bytes_per_region) {
 202     _bitmap_regions_per_slice = bitmap_page_size / bitmap_bytes_per_region;
 203     _bitmap_bytes_per_slice = bitmap_page_size;
 204   } else {
 205     _bitmap_regions_per_slice = 1;
 206     _bitmap_bytes_per_slice = bitmap_bytes_per_region;
 207   }
 208 
 209   guarantee(_bitmap_regions_per_slice >= 1,
 210             err_msg("Should have at least one region per slice: " SIZE_FORMAT,
 211                     _bitmap_regions_per_slice));
 212 
 213   guarantee(((_bitmap_bytes_per_slice) % bitmap_page_size) == 0,
 214             err_msg("Bitmap slices should be page-granular: bps = " SIZE_FORMAT ", page size = " SIZE_FORMAT,
 215                     _bitmap_bytes_per_slice, bitmap_page_size));
 216 
 217   ReservedSpace bitmap(_bitmap_size, bitmap_page_size);
 218   MemTracker::record_virtual_memory_type(bitmap.base(), mtGC);
 219   _bitmap_region = MemRegion((HeapWord*) bitmap.base(), bitmap.size() / HeapWordSize);
 220   _bitmap_region_special = bitmap.special();
 221 
 222   size_t bitmap_init_commit = _bitmap_bytes_per_slice *
 223                               align_size_up(num_committed_regions, _bitmap_regions_per_slice) / _bitmap_regions_per_slice;
 224   bitmap_init_commit = MIN2(_bitmap_size, bitmap_init_commit);
 225   if (!_bitmap_region_special) {
 226     os::commit_memory_or_exit((char *) _bitmap_region.start(), bitmap_init_commit, bitmap_page_size, false,
 227                               "Cannot commit bitmap memory");
 228   }
 229 
 230   _marking_context = new ShenandoahMarkingContext(_heap_region, _bitmap_region, _num_regions);
 231 
 232   if (ShenandoahVerify) {
 233     ReservedSpace verify_bitmap(_bitmap_size, bitmap_page_size);
 234     if (!verify_bitmap.special()) {
 235       os::commit_memory_or_exit(verify_bitmap.base(), verify_bitmap.size(), bitmap_page_size, false,
 236                                 "Cannot commit verification bitmap memory");
 237     }
 238     MemTracker::record_virtual_memory_type(verify_bitmap.base(), mtGC);
 239     MemRegion verify_bitmap_region = MemRegion((HeapWord *) verify_bitmap.base(), verify_bitmap.size() / HeapWordSize);
 240     _verification_bit_map.initialize(_heap_region, verify_bitmap_region);
 241     _verifier = new ShenandoahVerifier(this, &_verification_bit_map);
 242   }
 243 
 244   // Reserve aux bitmap for use in object_iterate(). We don't commit it here.
 245   ReservedSpace aux_bitmap(_bitmap_size, bitmap_page_size);
 246   MemTracker::record_virtual_memory_type(aux_bitmap.base(), mtGC);
 247   _aux_bitmap_region = MemRegion((HeapWord*) aux_bitmap.base(), aux_bitmap.size() / HeapWordSize);
 248   _aux_bitmap_region_special = aux_bitmap.special();
 249   _aux_bit_map.initialize(_heap_region, _aux_bitmap_region);
 250 
 251   //
 252   // Create regions and region sets
 253   //
 254   size_t region_align = align_size_up(sizeof(ShenandoahHeapRegion), SHENANDOAH_CACHE_LINE_SIZE);
 255   size_t region_storage_size = align_size_up(region_align * _num_regions, region_page_size);
 256   region_storage_size = align_size_up(region_storage_size, os::vm_allocation_granularity());
 257 
 258   ReservedSpace region_storage(region_storage_size, region_page_size);
 259   MemTracker::record_virtual_memory_type(region_storage.base(), mtGC);
 260   if (!region_storage.special()) {
 261     os::commit_memory_or_exit(region_storage.base(), region_storage_size, region_page_size, false,
 262                               "Cannot commit region memory");
 263   }
 264 
 265   // Try to fit the collection set bitmap at lower addresses. This optimizes code generation for cset checks.
 266   // Go up until a sensible limit (subject to encoding constraints) and try to reserve the space there.
 267   // If not successful, bite a bullet and allocate at whatever address.
 268   {
 269     size_t cset_align = MAX2<size_t>(os::vm_page_size(), os::vm_allocation_granularity());
 270     size_t cset_size = align_size_up(((size_t) sh_rs.base() + sh_rs.size()) >> ShenandoahHeapRegion::region_size_bytes_shift(), cset_align);
 271 
 272     uintptr_t min = ShenandoahUtils::round_up_power_of_2(cset_align);
 273     uintptr_t max = (1u << 30u);
 274 
 275     for (uintptr_t addr = min; addr <= max; addr <<= 1u) {
 276       char* req_addr = (char*)addr;
 277       assert(is_ptr_aligned(req_addr, cset_align), "Should be aligned");
 278       ReservedSpace cset_rs(cset_size, cset_align, false, req_addr);
 279       if (cset_rs.is_reserved()) {
 280         assert(cset_rs.base() == req_addr, err_msg("Allocated where requested: " PTR_FORMAT ", " PTR_FORMAT, p2i(cset_rs.base()), addr));
 281         _collection_set = new ShenandoahCollectionSet(this, cset_rs, sh_rs.base());
 282         break;
 283       }
 284     }
 285 
 286     if (_collection_set == NULL) {
 287       ReservedSpace cset_rs(cset_size, cset_align, false);
 288       _collection_set = new ShenandoahCollectionSet(this, cset_rs, sh_rs.base());
 289     }
 290   }
 291 
 292   _regions = NEW_C_HEAP_ARRAY(ShenandoahHeapRegion*, _num_regions, mtGC);
 293   _free_set = new ShenandoahFreeSet(this, _num_regions);
 294 
 295   {
 296     ShenandoahHeapLocker locker(lock());
 297 
 298     for (size_t i = 0; i < _num_regions; i++) {
 299       HeapWord* start = (HeapWord*)sh_rs.base() + ShenandoahHeapRegion::region_size_words() * i;
 300       bool is_committed = i < num_committed_regions;
 301       void* loc = region_storage.base() + i * region_align;
 302 
 303       ShenandoahHeapRegion* r = new (loc) ShenandoahHeapRegion(start, i, is_committed);
 304       assert(is_ptr_aligned(r, SHENANDOAH_CACHE_LINE_SIZE), "Sanity");
 305 
 306       _marking_context->initialize_top_at_mark_start(r);
 307       _regions[i] = r;
 308       assert(!collection_set()->is_in(i), "New region should not be in collection set");
 309     }
 310 
 311     // Initialize to complete
 312     _marking_context->mark_complete();
 313 
 314     _free_set->rebuild();
 315   }
 316 
 317   if (AlwaysPreTouch) {
 318     // For NUMA, it is important to pre-touch the storage under bitmaps with worker threads,
 319     // before initialize() below zeroes it with initializing thread. For any given region,
 320     // we touch the region and the corresponding bitmaps from the same thread.
 321     ShenandoahPushWorkerScope scope(workers(), _max_workers, false);
 322 
 323     _pretouch_heap_page_size = heap_page_size;
 324     _pretouch_bitmap_page_size = bitmap_page_size;
 325 
 326 #ifdef LINUX
 327     // UseTransparentHugePages would madvise that backing memory can be coalesced into huge
 328     // pages. But, the kernel needs to know that every small page is used, in order to coalesce
 329     // them into huge one. Therefore, we need to pretouch with smaller pages.
 330     if (UseTransparentHugePages) {
 331       _pretouch_heap_page_size = (size_t)os::vm_page_size();
 332       _pretouch_bitmap_page_size = (size_t)os::vm_page_size();
 333     }
 334 #endif
 335 
 336     // OS memory managers may want to coalesce back-to-back pages. Make their jobs
 337     // simpler by pre-touching continuous spaces (heap and bitmap) separately.
 338 
 339     ShenandoahPretouchBitmapTask bcl(bitmap.base(), _bitmap_size, _pretouch_bitmap_page_size);
 340     _workers->run_task(&bcl);
 341 
 342     ShenandoahPretouchHeapTask hcl(_pretouch_heap_page_size);
 343     _workers->run_task(&hcl);
 344   }
 345 
 346   //
 347   // Initialize the rest of GC subsystems
 348   //
 349 
 350   set_barrier_set(new ShenandoahBarrierSet(this));
 351 
 352   _liveness_cache = NEW_C_HEAP_ARRAY(ShenandoahLiveData*, _max_workers, mtGC);
 353   for (uint worker = 0; worker < _max_workers; worker++) {
 354     _liveness_cache[worker] = NEW_C_HEAP_ARRAY(ShenandoahLiveData, _num_regions, mtGC);
 355     Copy::fill_to_bytes(_liveness_cache[worker], _num_regions * sizeof(ShenandoahLiveData));
 356   }
 357 
 358   // The call below uses stuff (the SATB* things) that are in G1, but probably
 359   // belong into a shared location.
 360   JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon,
 361                                                SATB_Q_FL_lock,
 362                                                20 /*G1SATBProcessCompletedThreshold */,
 363                                                Shared_SATB_Q_lock);
 364 
 365   _monitoring_support = new ShenandoahMonitoringSupport(this);
 366   _phase_timings = new ShenandoahPhaseTimings(max_workers());
 367   ShenandoahStringDedup::initialize();
 368   ShenandoahCodeRoots::initialize();
 369 
 370   if (ShenandoahPacing) {
 371     _pacer = new ShenandoahPacer(this);
 372     _pacer->setup_for_idle();
 373   } else {
 374     _pacer = NULL;
 375   }
 376 
 377   _control_thread = new ShenandoahControlThread();
 378 
 379   log_info(gc, init)("Initialize Shenandoah heap: " SIZE_FORMAT "%s initial, " SIZE_FORMAT "%s min, " SIZE_FORMAT "%s max",
 380                      byte_size_in_proper_unit(_initial_size),  proper_unit_for_byte_size(_initial_size),
 381                      byte_size_in_proper_unit(_minimum_size),  proper_unit_for_byte_size(_minimum_size),
 382                      byte_size_in_proper_unit(max_capacity()), proper_unit_for_byte_size(max_capacity())
 383   );
 384 
 385   return JNI_OK;
 386 }
 387 
 388 #ifdef _MSC_VER
 389 #pragma warning( push )
 390 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
 391 #endif
 392 
 393 void ShenandoahHeap::initialize_heuristics() {
 394   if (ShenandoahGCMode != NULL) {
 395     if (strcmp(ShenandoahGCMode, "satb") == 0) {
 396       _gc_mode = new ShenandoahSATBMode();
 397     } else if (strcmp(ShenandoahGCMode, "iu") == 0) {
 398       _gc_mode = new ShenandoahIUMode();
 399     } else if (strcmp(ShenandoahGCMode, "passive") == 0) {
 400       _gc_mode = new ShenandoahPassiveMode();
 401     } else {
 402       vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option");
 403     }
 404   } else {
 405     ShouldNotReachHere();
 406   }
 407   _gc_mode->initialize_flags();
 408   if (_gc_mode->is_diagnostic() && !UnlockDiagnosticVMOptions) {
 409     vm_exit_during_initialization(
 410             err_msg("GC mode \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",
 411                     _gc_mode->name()));
 412   }
 413   if (_gc_mode->is_experimental() && !UnlockExperimentalVMOptions) {
 414     vm_exit_during_initialization(
 415             err_msg("GC mode \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",
 416                     _gc_mode->name()));
 417   }
 418   log_info(gc, init)("Shenandoah GC mode: %s",
 419                      _gc_mode->name());
 420 
 421   _heuristics = _gc_mode->initialize_heuristics();
 422 
 423   if (_heuristics->is_diagnostic() && !UnlockDiagnosticVMOptions) {
 424     vm_exit_during_initialization(
 425             err_msg("Heuristics \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",
 426                     _heuristics->name()));
 427   }
 428   if (_heuristics->is_experimental() && !UnlockExperimentalVMOptions) {
 429     vm_exit_during_initialization(
 430             err_msg("Heuristics \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",
 431                     _heuristics->name()));
 432   }
 433   log_info(gc, init)("Shenandoah heuristics: %s",
 434                      _heuristics->name());
 435 }
 436 
 437 ShenandoahHeap::ShenandoahHeap(ShenandoahCollectorPolicy* policy) :
 438   SharedHeap(policy),
 439   _shenandoah_policy(policy),
 440   _heap_region_special(false),
 441   _regions(NULL),
 442   _free_set(NULL),
 443   _collection_set(NULL),
 444   _update_refs_iterator(this),
 445   _bytes_allocated_since_gc_start(0),
 446   _max_workers((uint)MAX2(ConcGCThreads, ParallelGCThreads)),
 447   _ref_processor(NULL),
 448   _marking_context(NULL),
 449   _bitmap_size(0),
 450   _bitmap_regions_per_slice(0),
 451   _bitmap_bytes_per_slice(0),
 452   _bitmap_region_special(false),
 453   _aux_bitmap_region_special(false),
 454   _liveness_cache(NULL),
 455   _aux_bit_map(),
 456   _verifier(NULL),
 457   _pacer(NULL),
 458   _gc_timer(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
 459   _phase_timings(NULL)
 460 {
 461   _heap = this;
 462 
 463   log_info(gc, init)("GC threads: " UINTX_FORMAT " parallel, " UINTX_FORMAT " concurrent", ParallelGCThreads, ConcGCThreads);
 464 
 465   _scm = new ShenandoahConcurrentMark();
 466 
 467   _full_gc = new ShenandoahMarkCompact();
 468   _used = 0;
 469 
 470   _max_workers = MAX2(_max_workers, 1U);
 471 
 472   // SharedHeap did not initialize this for us, and we want our own workgang anyway.
 473   assert(SharedHeap::_workers == NULL && _workers == NULL, "Should not be initialized yet");
 474   _workers = new ShenandoahWorkGang("Shenandoah GC Threads", _max_workers,
 475                             /* are_GC_task_threads */true,
 476                             /* are_ConcurrentGC_threads */false);
 477   if (_workers == NULL) {
 478     vm_exit_during_initialization("Failed necessary allocation.");
 479   } else {
 480     _workers->initialize_workers();
 481   }
 482   assert(SharedHeap::_workers == _workers, "Sanity: initialized the correct field");
 483 }
 484 
 485 #ifdef _MSC_VER
 486 #pragma warning( pop )
 487 #endif
 488 
 489 class ShenandoahResetBitmapTask : public AbstractGangTask {
 490 private:
 491   ShenandoahRegionIterator _regions;
 492 
 493 public:
 494   ShenandoahResetBitmapTask() :
 495     AbstractGangTask("Parallel Reset Bitmap Task") {}
 496 
 497   void work(uint worker_id) {
 498     ShenandoahHeapRegion* region = _regions.next();
 499     ShenandoahHeap* heap = ShenandoahHeap::heap();
 500     ShenandoahMarkingContext* const ctx = heap->marking_context();
 501     while (region != NULL) {
 502       if (heap->is_bitmap_slice_committed(region)) {
 503         ctx->clear_bitmap(region);
 504       }
 505       region = _regions.next();
 506     }
 507   }
 508 };
 509 
 510 void ShenandoahHeap::reset_mark_bitmap() {
 511   assert_gc_workers(_workers->active_workers());
 512   mark_incomplete_marking_context();
 513 
 514   ShenandoahResetBitmapTask task;
 515   _workers->run_task(&task);
 516 }
 517 
 518 void ShenandoahHeap::print_on(outputStream* st) const {
 519   st->print_cr("Shenandoah Heap");
 520   st->print_cr(" " SIZE_FORMAT "%s total, " SIZE_FORMAT "%s committed, " SIZE_FORMAT "%s used",
 521                byte_size_in_proper_unit(max_capacity()), proper_unit_for_byte_size(max_capacity()),
 522                byte_size_in_proper_unit(committed()),    proper_unit_for_byte_size(committed()),
 523                byte_size_in_proper_unit(used()),         proper_unit_for_byte_size(used()));
 524   st->print_cr(" " SIZE_FORMAT " x " SIZE_FORMAT"%s regions",
 525                num_regions(),
 526                byte_size_in_proper_unit(ShenandoahHeapRegion::region_size_bytes()),
 527                proper_unit_for_byte_size(ShenandoahHeapRegion::region_size_bytes()));
 528 
 529   st->print("Status: ");
 530   if (has_forwarded_objects())               st->print("has forwarded objects, ");
 531   if (is_concurrent_mark_in_progress())      st->print("marking, ");
 532   if (is_evacuation_in_progress())           st->print("evacuating, ");
 533   if (is_update_refs_in_progress())          st->print("updating refs, ");
 534   if (is_degenerated_gc_in_progress())       st->print("degenerated gc, ");
 535   if (is_full_gc_in_progress())              st->print("full gc, ");
 536   if (is_full_gc_move_in_progress())         st->print("full gc move, ");
 537 
 538   if (cancelled_gc()) {
 539     st->print("cancelled");
 540   } else {
 541     st->print("not cancelled");
 542   }
 543   st->cr();
 544 
 545   st->print_cr("Reserved region:");
 546   st->print_cr(" - [" PTR_FORMAT ", " PTR_FORMAT ") ",
 547                p2i(reserved_region().start()),
 548                p2i(reserved_region().end()));
 549 
 550   ShenandoahCollectionSet* cset = collection_set();
 551   st->print_cr("Collection set:");
 552   if (cset != NULL) {
 553     st->print_cr(" - map (vanilla): " PTR_FORMAT, p2i(cset->map_address()));
 554     st->print_cr(" - map (biased):  " PTR_FORMAT, p2i(cset->biased_map_address()));
 555   } else {
 556     st->print_cr(" (NULL)");
 557   }
 558 
 559   st->cr();
 560   MetaspaceAux::print_on(st);
 561 
 562   if (Verbose) {
 563     print_heap_regions_on(st);
 564   }
 565 }
 566 
 567 class ShenandoahInitGCLABClosure : public ThreadClosure {
 568 public:
 569   void do_thread(Thread* thread) {
 570     assert(thread == NULL || !thread->is_Java_thread(), "Don't expect JavaThread this early");
 571     if (thread != NULL && thread->is_Worker_thread()) {
 572       thread->gclab().initialize(true);
 573     }
 574   }
 575 };
 576 
 577 void ShenandoahHeap::post_initialize() {
 578   if (UseTLAB) {
 579     MutexLocker ml(Threads_lock);
 580 
 581     ShenandoahInitGCLABClosure init_gclabs;
 582     Threads::threads_do(&init_gclabs);
 583   }
 584 
 585   _scm->initialize(_max_workers);
 586   _full_gc->initialize(_gc_timer);
 587 
 588   ref_processing_init();
 589 
 590   _heuristics->initialize();
 591 }
 592 
 593 size_t ShenandoahHeap::used() const {
 594   OrderAccess::acquire();
 595   return (size_t) _used;
 596 }
 597 
 598 size_t ShenandoahHeap::committed() const {
 599   OrderAccess::acquire();
 600   return _committed;
 601 }
 602 
 603 void ShenandoahHeap::increase_committed(size_t bytes) {
 604   shenandoah_assert_heaplocked_or_safepoint();
 605   _committed += bytes;
 606 }
 607 
 608 void ShenandoahHeap::decrease_committed(size_t bytes) {
 609   shenandoah_assert_heaplocked_or_safepoint();
 610   _committed -= bytes;
 611 }
 612 
 613 void ShenandoahHeap::increase_used(size_t bytes) {
 614   Atomic::add(bytes, &_used);
 615 }
 616 
 617 void ShenandoahHeap::set_used(size_t bytes) {
 618   OrderAccess::release_store_fence(&_used, bytes);
 619 }
 620 
 621 void ShenandoahHeap::decrease_used(size_t bytes) {
 622   assert(used() >= bytes, "never decrease heap size by more than we've left");
 623   Atomic::add(-(jlong)bytes, &_used);
 624 }
 625 
 626 void ShenandoahHeap::increase_allocated(size_t bytes) {
 627   Atomic::add(bytes, &_bytes_allocated_since_gc_start);
 628 }
 629 
 630 void ShenandoahHeap::notify_mutator_alloc_words(size_t words, bool waste) {
 631   size_t bytes = words * HeapWordSize;
 632   if (!waste) {
 633     increase_used(bytes);
 634   }
 635   increase_allocated(bytes);
 636   if (ShenandoahPacing) {
 637     control_thread()->pacing_notify_alloc(words);
 638     if (waste) {
 639       pacer()->claim_for_alloc(words, true);
 640     }
 641   }
 642 }
 643 
 644 size_t ShenandoahHeap::capacity() const {
 645   return committed();
 646 }
 647 
 648 size_t ShenandoahHeap::max_capacity() const {
 649   return _num_regions * ShenandoahHeapRegion::region_size_bytes();
 650 }
 651 
 652 size_t ShenandoahHeap::min_capacity() const {
 653   return _minimum_size;
 654 }
 655 
 656 size_t ShenandoahHeap::initial_capacity() const {
 657   return _initial_size;
 658 }
 659 
 660 bool ShenandoahHeap::is_in(const void* p) const {
 661   HeapWord* heap_base = (HeapWord*) base();
 662   HeapWord* last_region_end = heap_base + ShenandoahHeapRegion::region_size_words() * num_regions();
 663   return p >= heap_base && p < last_region_end;
 664 }
 665 
 666 void ShenandoahHeap::op_uncommit(double shrink_before) {
 667   assert (ShenandoahUncommit, "should be enabled");
 668 
 669   // Application allocates from the beginning of the heap, and GC allocates at
 670   // the end of it. It is more efficient to uncommit from the end, so that applications
 671   // could enjoy the near committed regions. GC allocations are much less frequent,
 672   // and therefore can accept the committing costs.
 673 
 674   size_t count = 0;
 675   for (size_t i = num_regions(); i > 0; i--) { // care about size_t underflow
 676     ShenandoahHeapRegion* r = get_region(i - 1);
 677     if (r->is_empty_committed() && (r->empty_time() < shrink_before)) {
 678       ShenandoahHeapLocker locker(lock());
 679       if (r->is_empty_committed()) {
 680         // Do not uncommit below minimal capacity
 681         if (committed() < min_capacity() + ShenandoahHeapRegion::region_size_bytes()) {
 682           break;
 683         }
 684 
 685         r->make_uncommitted();
 686         count++;
 687       }
 688     }
 689     SpinPause(); // allow allocators to take the lock
 690   }
 691 
 692   if (count > 0) {
 693     _control_thread->notify_heap_changed();
 694   }
 695 }
 696 
 697 HeapWord* ShenandoahHeap::allocate_from_gclab_slow(Thread* thread, size_t size) {
 698   // Retain tlab and allocate object in shared space if
 699   // the amount free in the tlab is too large to discard.
 700   if (thread->gclab().free() > thread->gclab().refill_waste_limit()) {
 701     thread->gclab().record_slow_allocation(size);
 702     return NULL;
 703   }
 704 
 705   // Discard gclab and allocate a new one.
 706   // To minimize fragmentation, the last GCLAB may be smaller than the rest.
 707   size_t new_gclab_size = thread->gclab().compute_size(size);
 708 
 709   thread->gclab().clear_before_allocation();
 710 
 711   if (new_gclab_size == 0) {
 712     return NULL;
 713   }
 714 
 715   // Allocated object should fit in new GCLAB, and new_gclab_size should be larger than min
 716   size_t min_size = MAX2(size + ThreadLocalAllocBuffer::alignment_reserve(), ThreadLocalAllocBuffer::min_size());
 717   new_gclab_size = MAX2(new_gclab_size, min_size);
 718 
 719   // Allocate a new GCLAB...
 720   size_t actual_size = 0;
 721   HeapWord* obj = allocate_new_gclab(min_size, new_gclab_size, &actual_size);
 722 
 723   if (obj == NULL) {
 724     return NULL;
 725   }
 726 
 727   assert (size <= actual_size, "allocation should fit");
 728 
 729   if (ZeroTLAB) {
 730     // ..and clear it.
 731     Copy::zero_to_words(obj, actual_size);
 732   } else {
 733     // ...and zap just allocated object.
 734 #ifdef ASSERT
 735     // Skip mangling the space corresponding to the object header to
 736     // ensure that the returned space is not considered parsable by
 737     // any concurrent GC thread.
 738     size_t hdr_size = oopDesc::header_size();
 739     Copy::fill_to_words(obj + hdr_size, actual_size - hdr_size, badHeapWordVal);
 740 #endif // ASSERT
 741   }
 742   thread->gclab().fill(obj, obj + size, actual_size);
 743   return obj;
 744 }
 745 
 746 HeapWord* ShenandoahHeap::allocate_new_tlab(size_t word_size) {
 747   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_tlab(word_size);
 748   return allocate_memory(req);
 749 }
 750 
 751 HeapWord* ShenandoahHeap::allocate_new_gclab(size_t min_size,
 752                                              size_t word_size,
 753                                              size_t* actual_size) {
 754   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_gclab(min_size, word_size);
 755   HeapWord* res = allocate_memory(req);
 756   if (res != NULL) {
 757     *actual_size = req.actual_size();
 758   } else {
 759     *actual_size = 0;
 760   }
 761   return res;
 762 }
 763 
 764 HeapWord* ShenandoahHeap::allocate_memory(ShenandoahAllocRequest& req) {
 765   intptr_t pacer_epoch = 0;
 766   bool in_new_region = false;
 767   HeapWord* result = NULL;
 768 
 769   if (req.is_mutator_alloc()) {
 770     if (ShenandoahPacing) {
 771       pacer()->pace_for_alloc(req.size());
 772       pacer_epoch = pacer()->epoch();
 773     }
 774 
 775     if (!ShenandoahAllocFailureALot || !should_inject_alloc_failure()) {
 776       result = allocate_memory_under_lock(req, in_new_region);
 777     }
 778 
 779     // Allocation failed, block until control thread reacted, then retry allocation.
 780     //
 781     // It might happen that one of the threads requesting allocation would unblock
 782     // way later after GC happened, only to fail the second allocation, because
 783     // other threads have already depleted the free storage. In this case, a better
 784     // strategy is to try again, as long as GC makes progress.
 785     //
 786     // Then, we need to make sure the allocation was retried after at least one
 787     // Full GC, which means we want to try more than ShenandoahFullGCThreshold times.
 788 
 789     size_t tries = 0;
 790 
 791     while (result == NULL && _progress_last_gc.is_set()) {
 792       tries++;
 793       control_thread()->handle_alloc_failure(req);
 794       result = allocate_memory_under_lock(req, in_new_region);
 795     }
 796 
 797     while (result == NULL && tries <= ShenandoahFullGCThreshold) {
 798       tries++;
 799       control_thread()->handle_alloc_failure(req);
 800       result = allocate_memory_under_lock(req, in_new_region);
 801     }
 802 
 803   } else {
 804     assert(req.is_gc_alloc(), "Can only accept GC allocs here");
 805     result = allocate_memory_under_lock(req, in_new_region);
 806     // Do not call handle_alloc_failure() here, because we cannot block.
 807     // The allocation failure would be handled by the WB slowpath with handle_alloc_failure_evac().
 808   }
 809 
 810   if (in_new_region) {
 811     control_thread()->notify_heap_changed();
 812   }
 813 
 814   if (result != NULL) {
 815     size_t requested = req.size();
 816     size_t actual = req.actual_size();
 817 
 818     assert (req.is_lab_alloc() || (requested == actual),
 819             err_msg("Only LAB allocations are elastic: %s, requested = " SIZE_FORMAT ", actual = " SIZE_FORMAT,
 820                     ShenandoahAllocRequest::alloc_type_to_string(req.type()), requested, actual));
 821 
 822     if (req.is_mutator_alloc()) {
 823       notify_mutator_alloc_words(actual, false);
 824 
 825       // If we requested more than we were granted, give the rest back to pacer.
 826       // This only matters if we are in the same pacing epoch: do not try to unpace
 827       // over the budget for the other phase.
 828       if (ShenandoahPacing && (pacer_epoch > 0) && (requested > actual)) {
 829         pacer()->unpace_for_alloc(pacer_epoch, requested - actual);
 830       }
 831     } else {
 832       increase_used(actual*HeapWordSize);
 833     }
 834   }
 835 
 836   return result;
 837 }
 838 
 839 HeapWord* ShenandoahHeap::allocate_memory_under_lock(ShenandoahAllocRequest& req, bool& in_new_region) {
 840   ShenandoahHeapLocker locker(lock());
 841   return _free_set->allocate(req, in_new_region);
 842 }
 843 
 844 HeapWord*  ShenandoahHeap::mem_allocate(size_t size,
 845                                         bool*  gc_overhead_limit_was_exceeded) {
 846   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared(size);
 847   return allocate_memory(req);
 848 }
 849 
 850 class ShenandoahConcurrentEvacuateRegionObjectClosure : public ObjectClosure {
 851 private:
 852   ShenandoahHeap* const _heap;
 853   Thread* const _thread;
 854 public:
 855   ShenandoahConcurrentEvacuateRegionObjectClosure(ShenandoahHeap* heap) :
 856     _heap(heap), _thread(Thread::current()) {}
 857 
 858   void do_object(oop p) {
 859     shenandoah_assert_marked(NULL, p);
 860     if (!p->is_forwarded()) {
 861       _heap->evacuate_object(p, _thread);
 862     }
 863   }
 864 };
 865 
 866 class ShenandoahEvacuationTask : public AbstractGangTask {
 867 private:
 868   ShenandoahHeap* const _sh;
 869   ShenandoahCollectionSet* const _cs;
 870   bool _concurrent;
 871 public:
 872   ShenandoahEvacuationTask(ShenandoahHeap* sh,
 873                            ShenandoahCollectionSet* cs,
 874                            bool concurrent) :
 875     AbstractGangTask("Parallel Evacuation Task"),
 876     _sh(sh),
 877     _cs(cs),
 878     _concurrent(concurrent)
 879   {}
 880 
 881   void work(uint worker_id) {
 882     ShenandoahEvacOOMScope oom_evac_scope;
 883     if (_concurrent) {
 884       ShenandoahConcurrentWorkerSession worker_session(worker_id);
 885       do_work();
 886     } else {
 887       ShenandoahParallelWorkerSession worker_session(worker_id);
 888       do_work();
 889     }
 890   }
 891 
 892 private:
 893   void do_work() {
 894     ShenandoahConcurrentEvacuateRegionObjectClosure cl(_sh);
 895     ShenandoahHeapRegion* r;
 896     while ((r =_cs->claim_next()) != NULL) {
 897       assert(r->has_live(), err_msg("Region " SIZE_FORMAT " should have been reclaimed early", r->index()));
 898       _sh->marked_object_iterate(r, &cl);
 899 
 900       if (ShenandoahPacing) {
 901         _sh->pacer()->report_evac(r->used() >> LogHeapWordSize);
 902       }
 903 
 904       if (_sh->cancelled_gc()) {
 905         break;
 906       }
 907     }
 908   }
 909 };
 910 
 911 void ShenandoahHeap::trash_cset_regions() {
 912   ShenandoahHeapLocker locker(lock());
 913 
 914   ShenandoahCollectionSet* set = collection_set();
 915   ShenandoahHeapRegion* r;
 916   set->clear_current_index();
 917   while ((r = set->next()) != NULL) {
 918     r->make_trash();
 919   }
 920   collection_set()->clear();
 921 }
 922 
 923 void ShenandoahHeap::print_heap_regions_on(outputStream* st) const {
 924   st->print_cr("Heap Regions:");
 925   st->print_cr("EU=empty-uncommitted, EC=empty-committed, R=regular, H=humongous start, HC=humongous continuation, CS=collection set, T=trash, P=pinned");
 926   st->print_cr("BTE=bottom/top/end, U=used, T=TLAB allocs, G=GCLAB allocs, S=shared allocs, L=live data");
 927   st->print_cr("R=root, CP=critical pins, TAMS=top-at-mark-start, UWM=update watermark");
 928   st->print_cr("SN=alloc sequence number");
 929 
 930   for (size_t i = 0; i < num_regions(); i++) {
 931     get_region(i)->print_on(st);
 932   }
 933 }
 934 
 935 void ShenandoahHeap::trash_humongous_region_at(ShenandoahHeapRegion* start) {
 936   assert(start->is_humongous_start(), "reclaim regions starting with the first one");
 937 
 938   oop humongous_obj = oop(start->bottom());
 939   size_t size = humongous_obj->size();
 940   size_t required_regions = ShenandoahHeapRegion::required_regions(size * HeapWordSize);
 941   size_t index = start->index() + required_regions - 1;
 942 
 943   assert(!start->has_live(), "liveness must be zero");
 944 
 945   for(size_t i = 0; i < required_regions; i++) {
 946      // Reclaim from tail. Otherwise, assertion fails when printing region to trace log,
 947      // as it expects that every region belongs to a humongous region starting with a humongous start region.
 948      ShenandoahHeapRegion* region = get_region(index --);
 949 
 950     assert(region->is_humongous(), "expect correct humongous start or continuation");
 951     assert(!region->is_cset(), "Humongous region should not be in collection set");
 952 
 953     region->make_trash_immediate();
 954   }
 955 }
 956 
 957 class ShenandoahRetireGCLABClosure : public ThreadClosure {
 958 private:
 959   bool _retire;
 960 public:
 961   ShenandoahRetireGCLABClosure(bool retire) : _retire(retire) {};
 962 
 963   void do_thread(Thread* thread) {
 964     assert(thread->gclab().is_initialized(), err_msg("GCLAB should be initialized for %s", thread->name()));
 965     thread->gclab().make_parsable(_retire);
 966   }
 967 };
 968 
 969 void ShenandoahHeap::make_parsable(bool retire_tlabs) {
 970   if (UseTLAB) {
 971     CollectedHeap::ensure_parsability(retire_tlabs);
 972     ShenandoahRetireGCLABClosure cl(retire_tlabs);
 973     Threads::java_threads_do(&cl);
 974     _workers->threads_do(&cl);
 975   }
 976 }
 977 
 978 class ShenandoahEvacuateUpdateRootsTask : public AbstractGangTask {
 979 private:
 980   ShenandoahRootEvacuator* _rp;
 981 
 982 public:
 983   ShenandoahEvacuateUpdateRootsTask(ShenandoahRootEvacuator* rp) :
 984     AbstractGangTask("Shenandoah evacuate and update roots"),
 985     _rp(rp) {}
 986 
 987   void work(uint worker_id) {
 988     ShenandoahParallelWorkerSession worker_session(worker_id);
 989     ShenandoahEvacOOMScope oom_evac_scope;
 990     ShenandoahEvacuateUpdateRootsClosure cl;
 991 
 992     MarkingCodeBlobClosure blobsCl(&cl, CodeBlobToOopClosure::FixRelocations);
 993     _rp->roots_do(worker_id, &cl);
 994   }
 995 };
 996 
 997 void ShenandoahHeap::evacuate_and_update_roots() {
 998   COMPILER2_PRESENT(DerivedPointerTable::clear());
 999 
1000   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only iterate roots while world is stopped");
1001 
1002   {
1003     ShenandoahRootEvacuator rp(ShenandoahPhaseTimings::init_evac);
1004     ShenandoahEvacuateUpdateRootsTask roots_task(&rp);
1005     workers()->run_task(&roots_task);
1006   }
1007 
1008   COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
1009 }
1010 
1011 size_t  ShenandoahHeap::unsafe_max_tlab_alloc(Thread *thread) const {
1012   // Returns size in bytes
1013   return MIN2(_free_set->unsafe_peek_free(), ShenandoahHeapRegion::max_tlab_size_bytes());
1014 }
1015 
1016 size_t ShenandoahHeap::max_tlab_size() const {
1017   // Returns size in words
1018   return ShenandoahHeapRegion::max_tlab_size_words();
1019 }
1020 
1021 class ShenandoahResizeGCLABClosure : public ThreadClosure {
1022 public:
1023   void do_thread(Thread* thread) {
1024     assert(thread->gclab().is_initialized(), err_msg("GCLAB should be initialized for %s", thread->name()));
1025     thread->gclab().resize();
1026   }
1027 };
1028 
1029 void ShenandoahHeap::resize_all_tlabs() {
1030   CollectedHeap::resize_all_tlabs();
1031 
1032   ShenandoahResizeGCLABClosure cl;
1033   Threads::java_threads_do(&cl);
1034   _workers->threads_do(&cl);
1035 }
1036 
1037 class ShenandoahAccumulateStatisticsGCLABClosure : public ThreadClosure {
1038 public:
1039   void do_thread(Thread* thread) {
1040     assert(thread->gclab().is_initialized(), err_msg("GCLAB should be initialized for %s", thread->name()));
1041     thread->gclab().accumulate_statistics();
1042     thread->gclab().initialize_statistics();
1043   }
1044 };
1045 
1046 void ShenandoahHeap::accumulate_statistics_all_gclabs() {
1047   ShenandoahAccumulateStatisticsGCLABClosure cl;
1048   Threads::java_threads_do(&cl);
1049   _workers->threads_do(&cl);
1050 }
1051 
1052 void ShenandoahHeap::collect(GCCause::Cause cause) {
1053   _control_thread->request_gc(cause);
1054 }
1055 
1056 void ShenandoahHeap::do_full_collection(bool clear_all_soft_refs) {
1057   //assert(false, "Shouldn't need to do full collections");
1058 }
1059 
1060 CollectorPolicy* ShenandoahHeap::collector_policy() const {
1061   return _shenandoah_policy;
1062 }
1063 
1064 void ShenandoahHeap::resize_tlabs() {
1065   CollectedHeap::resize_all_tlabs();
1066 }
1067 
1068 void ShenandoahHeap::accumulate_statistics_tlabs() {
1069   CollectedHeap::accumulate_statistics_all_tlabs();
1070 }
1071 
1072 HeapWord* ShenandoahHeap::block_start(const void* addr) const {
1073   ShenandoahHeapRegion* r = heap_region_containing(addr);
1074   if (r != NULL) {
1075     return r->block_start(addr);
1076   }
1077   return NULL;
1078 }
1079 
1080 size_t ShenandoahHeap::block_size(const HeapWord* addr) const {
1081   ShenandoahHeapRegion* r = heap_region_containing(addr);
1082   return r->block_size(addr);
1083 }
1084 
1085 bool ShenandoahHeap::block_is_obj(const HeapWord* addr) const {
1086   ShenandoahHeapRegion* r = heap_region_containing(addr);
1087   return r->block_is_obj(addr);
1088 }
1089 
1090 jlong ShenandoahHeap::millis_since_last_gc() {
1091   double v = heuristics()->time_since_last_gc() * 1000;
1092   assert(0 <= v && v <= max_jlong, err_msg("value should fit: %f", v));
1093   return (jlong)v;
1094 }
1095 
1096 void ShenandoahHeap::prepare_for_verify() {
1097   if (SafepointSynchronize::is_at_safepoint()) {
1098     make_parsable(false);
1099   }
1100 }
1101 
1102 void ShenandoahHeap::print_gc_threads_on(outputStream* st) const {
1103   workers()->print_worker_threads_on(st);
1104   if (ShenandoahStringDedup::is_enabled()) {
1105     ShenandoahStringDedup::print_worker_threads_on(st);
1106   }
1107 }
1108 
1109 void ShenandoahHeap::gc_threads_do(ThreadClosure* tcl) const {
1110   workers()->threads_do(tcl);
1111   if (ShenandoahStringDedup::is_enabled()) {
1112     ShenandoahStringDedup::threads_do(tcl);
1113   }
1114 }
1115 
1116 void ShenandoahHeap::print_tracing_info() const {
1117   if (PrintGC || TraceGen0Time || TraceGen1Time) {
1118     ResourceMark rm;
1119     outputStream* out = gclog_or_tty;
1120     phase_timings()->print_global_on(out);
1121 
1122     out->cr();
1123     out->cr();
1124 
1125     shenandoah_policy()->print_gc_stats(out);
1126 
1127     out->cr();
1128     out->cr();
1129   }
1130 }
1131 
1132 void ShenandoahHeap::verify(bool silent, VerifyOption vo) {
1133   if (ShenandoahSafepoint::is_at_shenandoah_safepoint() || ! UseTLAB) {
1134     if (ShenandoahVerify) {
1135       verifier()->verify_generic(vo);
1136     } else {
1137       // TODO: Consider allocating verification bitmaps on demand,
1138       // and turn this on unconditionally.
1139     }
1140   }
1141 }
1142 size_t ShenandoahHeap::tlab_capacity(Thread *thr) const {
1143   return _free_set->capacity();
1144 }
1145 
1146 class ObjectIterateScanRootClosure : public ExtendedOopClosure {
1147 private:
1148   MarkBitMap* _bitmap;
1149   Stack<oop,mtGC>* _oop_stack;
1150 
1151   template <class T>
1152   void do_oop_work(T* p) {
1153     T o = oopDesc::load_heap_oop(p);
1154     if (!oopDesc::is_null(o)) {
1155       oop obj = oopDesc::decode_heap_oop_not_null(o);
1156       obj = (oop) ShenandoahBarrierSet::resolve_forwarded_not_null(obj);
1157       assert(obj->is_oop(), "must be a valid oop");
1158       if (!_bitmap->isMarked((HeapWord*) obj)) {
1159         _bitmap->mark((HeapWord*) obj);
1160         _oop_stack->push(obj);
1161       }
1162     }
1163   }
1164 public:
1165   ObjectIterateScanRootClosure(MarkBitMap* bitmap, Stack<oop,mtGC>* oop_stack) :
1166     _bitmap(bitmap), _oop_stack(oop_stack) {}
1167   void do_oop(oop* p)       { do_oop_work(p); }
1168   void do_oop(narrowOop* p) { do_oop_work(p); }
1169 };
1170 
1171 /*
1172  * This is public API, used in preparation of object_iterate().
1173  * Since we don't do linear scan of heap in object_iterate() (see comment below), we don't
1174  * need to make the heap parsable. For Shenandoah-internal linear heap scans that we can
1175  * control, we call SH::make_parsable().
1176  */
1177 void ShenandoahHeap::ensure_parsability(bool retire_tlabs) {
1178   // No-op.
1179 }
1180 
1181 /*
1182  * Iterates objects in the heap. This is public API, used for, e.g., heap dumping.
1183  *
1184  * We cannot safely iterate objects by doing a linear scan at random points in time. Linear
1185  * scanning needs to deal with dead objects, which may have dead Klass* pointers (e.g.
1186  * calling oopDesc::size() would crash) or dangling reference fields (crashes) etc. Linear
1187  * scanning therefore depends on having a valid marking bitmap to support it. However, we only
1188  * have a valid marking bitmap after successful marking. In particular, we *don't* have a valid
1189  * marking bitmap during marking, after aborted marking or during/after cleanup (when we just
1190  * wiped the bitmap in preparation for next marking).
1191  *
1192  * For all those reasons, we implement object iteration as a single marking traversal, reporting
1193  * objects as we mark+traverse through the heap, starting from GC roots. JVMTI IterateThroughHeap
1194  * is allowed to report dead objects, but is not required to do so.
1195  */
1196 void ShenandoahHeap::object_iterate(ObjectClosure* cl) {
1197   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1198   if (!_aux_bitmap_region_special && !os::commit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size(), false)) {
1199     log_warning(gc)("Could not commit native memory for auxiliary marking bitmap for heap iteration");
1200     return;
1201   }
1202 
1203   // Reset bitmap
1204   _aux_bit_map.clear();
1205 
1206   Stack<oop,mtGC> oop_stack;
1207  
1208   ObjectIterateScanRootClosure oops(&_aux_bit_map, &oop_stack);
1209  
1210   {
1211     // First, we process GC roots according to current GC cycle.
1212     // This populates the work stack with initial objects.
1213     // It is important to relinquish the associated locks before diving
1214     // into heap dumper.
1215     ShenandoahHeapIterationRootScanner rp;
1216     rp.roots_do(&oops);
1217   }
1218 
1219   // Work through the oop stack to traverse heap.
1220   while (! oop_stack.is_empty()) {
1221     oop obj = oop_stack.pop();
1222     assert(obj->is_oop(), "must be a valid oop");
1223     cl->do_object(obj);
1224     obj->oop_iterate(&oops);
1225   }
1226 
1227   assert(oop_stack.is_empty(), "should be empty");
1228 
1229   if (!_aux_bitmap_region_special && !os::uncommit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size())) {
1230     log_warning(gc)("Could not uncommit native memory for auxiliary marking bitmap for heap iteration");
1231   }
1232 }
1233 
1234 void ShenandoahHeap::safe_object_iterate(ObjectClosure* cl) {
1235   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1236   object_iterate(cl);
1237 }
1238 
1239 void ShenandoahHeap::oop_iterate(ExtendedOopClosure* cl) {
1240   ObjectToOopClosure cl2(cl);
1241   object_iterate(&cl2);
1242 }
1243 
1244 void  ShenandoahHeap::gc_prologue(bool b) {
1245   Unimplemented();
1246 }
1247 
1248 void  ShenandoahHeap::gc_epilogue(bool b) {
1249   Unimplemented();
1250 }
1251 
1252 void ShenandoahHeap::heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1253   for (size_t i = 0; i < num_regions(); i++) {
1254     ShenandoahHeapRegion* current = get_region(i);
1255     blk->heap_region_do(current);
1256   }
1257 }
1258 
1259 class ShenandoahParallelHeapRegionTask : public AbstractGangTask {
1260 private:
1261   ShenandoahHeap* const _heap;
1262   ShenandoahHeapRegionClosure* const _blk;
1263 
1264   shenandoah_padding(0);
1265   volatile jint _index;
1266   shenandoah_padding(1);
1267 
1268 public:
1269   ShenandoahParallelHeapRegionTask(ShenandoahHeapRegionClosure* blk) :
1270           AbstractGangTask("Parallel Region Task"),
1271           _heap(ShenandoahHeap::heap()), _blk(blk), _index(0) {}
1272 
1273   void work(uint worker_id) {
1274     jint stride = (jint)ShenandoahParallelRegionStride;
1275 
1276     jint max = (jint)_heap->num_regions();
1277     while (_index < max) {
1278       jint cur = Atomic::add(stride, &_index) - stride;
1279       jint start = cur;
1280       jint end = MIN2(cur + stride, max);
1281       if (start >= max) break;
1282 
1283       for (jint i = cur; i < end; i++) {
1284         ShenandoahHeapRegion* current = _heap->get_region((size_t)i);
1285         _blk->heap_region_do(current);
1286       }
1287     }
1288   }
1289 };
1290 
1291 void ShenandoahHeap::parallel_heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1292   assert(blk->is_thread_safe(), "Only thread-safe closures here");
1293   if (num_regions() > ShenandoahParallelRegionStride) {
1294     ShenandoahParallelHeapRegionTask task(blk);
1295     workers()->run_task(&task);
1296   } else {
1297     heap_region_iterate(blk);
1298   }
1299 }
1300 
1301 class ShenandoahInitMarkUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
1302 private:
1303   ShenandoahMarkingContext* const _ctx;
1304 public:
1305   ShenandoahInitMarkUpdateRegionStateClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
1306 
1307   void heap_region_do(ShenandoahHeapRegion* r) {
1308     assert(!r->has_live(),
1309            err_msg("Region " SIZE_FORMAT " should have no live data", r->index()));
1310     if (r->is_active()) {
1311       // Check if region needs updating its TAMS. We have updated it already during concurrent
1312       // reset, so it is very likely we don't need to do another write here.
1313       if (_ctx->top_at_mark_start(r) != r->top()) {
1314         _ctx->capture_top_at_mark_start(r);
1315       }
1316     } else {
1317       assert(_ctx->top_at_mark_start(r) == r->top(),
1318              err_msg("Region " SIZE_FORMAT " should already have correct TAMS", r->index()));
1319     }
1320   }
1321 
1322   bool is_thread_safe() { return true; }
1323 };
1324 
1325 void ShenandoahHeap::op_init_mark() {
1326   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1327   assert(Thread::current()->is_VM_thread(), "can only do this in VMThread");
1328 
1329   assert(marking_context()->is_bitmap_clear(), "need clear marking bitmap");
1330   assert(!marking_context()->is_complete(), "should not be complete");
1331   assert(!has_forwarded_objects(), "No forwarded objects on this path");
1332 
1333   if (ShenandoahVerify) {
1334     verifier()->verify_before_concmark();
1335   }
1336 
1337   {
1338     ShenandoahGCPhase phase(ShenandoahPhaseTimings::accumulate_stats);
1339     accumulate_statistics_tlabs();
1340   }
1341 
1342   if (VerifyBeforeGC) {
1343     Universe::verify();
1344   }
1345 
1346   set_concurrent_mark_in_progress(true);
1347   // We need to reset all TLABs because we'd lose marks on all objects allocated in them.
1348   if (UseTLAB) {
1349     ShenandoahGCPhase phase(ShenandoahPhaseTimings::make_parsable);
1350     make_parsable(true);
1351   }
1352 
1353   {
1354     ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_region_states);
1355     ShenandoahInitMarkUpdateRegionStateClosure cl;
1356     parallel_heap_region_iterate(&cl);
1357   }
1358 
1359   // Make above changes visible to worker threads
1360   OrderAccess::fence();
1361 
1362   concurrent_mark()->mark_roots(ShenandoahPhaseTimings::scan_roots);
1363 
1364   if (UseTLAB) {
1365     ShenandoahGCPhase phase(ShenandoahPhaseTimings::resize_tlabs);
1366     resize_tlabs();
1367   }
1368 
1369   if (ShenandoahPacing) {
1370     pacer()->setup_for_mark();
1371   }
1372 }
1373 
1374 void ShenandoahHeap::op_mark() {
1375   concurrent_mark()->mark_from_roots();
1376 }
1377 
1378 class ShenandoahFinalMarkUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
1379 private:
1380   ShenandoahMarkingContext* const _ctx;
1381   ShenandoahHeapLock* const _lock;
1382 
1383 public:
1384   ShenandoahFinalMarkUpdateRegionStateClosure() :
1385     _ctx(ShenandoahHeap::heap()->complete_marking_context()), _lock(ShenandoahHeap::heap()->lock()) {}
1386 
1387   void heap_region_do(ShenandoahHeapRegion* r) {
1388     if (r->is_active()) {
1389       // All allocations past TAMS are implicitly live, adjust the region data.
1390       // Bitmaps/TAMS are swapped at this point, so we need to poll complete bitmap.
1391       HeapWord *tams = _ctx->top_at_mark_start(r);
1392       HeapWord *top = r->top();
1393       if (top > tams) {
1394         r->increase_live_data_alloc_words(pointer_delta(top, tams));
1395       }
1396 
1397       // We are about to select the collection set, make sure it knows about
1398       // current pinning status. Also, this allows trashing more regions that
1399       // now have their pinning status dropped.
1400       if (r->is_pinned()) {
1401         if (r->pin_count() == 0) {
1402           ShenandoahHeapLocker locker(_lock);
1403           r->make_unpinned();
1404         }
1405       } else {
1406         if (r->pin_count() > 0) {
1407           ShenandoahHeapLocker locker(_lock);
1408           r->make_pinned();
1409         }
1410       }
1411 
1412       // Remember limit for updating refs. It's guaranteed that we get no
1413       // from-space-refs written from here on.
1414       r->set_update_watermark_at_safepoint(r->top());
1415     } else {
1416       assert(!r->has_live(),
1417              err_msg("Region " SIZE_FORMAT " should have no live data", r->index()));
1418       assert(_ctx->top_at_mark_start(r) == r->top(),
1419              err_msg("Region " SIZE_FORMAT " should have correct TAMS", r->index()));
1420     }
1421   }
1422 
1423   bool is_thread_safe() { return true; }
1424 };
1425 
1426 void ShenandoahHeap::op_final_mark() {
1427   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1428   assert(!has_forwarded_objects(), "No forwarded objects on this path");
1429 
1430   // It is critical that we
1431   // evacuate roots right after finishing marking, so that we don't
1432   // get unmarked objects in the roots.
1433 
1434   if (!cancelled_gc()) {
1435     concurrent_mark()->finish_mark_from_roots(/* full_gc = */ false);
1436 
1437     TASKQUEUE_STATS_ONLY(concurrent_mark()->task_queues()->reset_taskqueue_stats());
1438 
1439     if (ShenandoahVerify) {
1440       verifier()->verify_roots_no_forwarded();
1441     }
1442 
1443     TASKQUEUE_STATS_ONLY(concurrent_mark()->task_queues()->print_taskqueue_stats());
1444 
1445     stop_concurrent_marking();
1446 
1447     {
1448       ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_region_states);
1449       ShenandoahFinalMarkUpdateRegionStateClosure cl;
1450       parallel_heap_region_iterate(&cl);
1451 
1452       assert_pinned_region_status();
1453     }
1454 
1455     // Force the threads to reacquire their TLABs outside the collection set.
1456     {
1457       ShenandoahGCPhase phase(ShenandoahPhaseTimings::retire_tlabs);
1458       make_parsable(true);
1459     }
1460 
1461     {
1462       ShenandoahGCPhase phase(ShenandoahPhaseTimings::choose_cset);
1463       ShenandoahHeapLocker locker(lock());
1464       _collection_set->clear();
1465       heuristics()->choose_collection_set(_collection_set);
1466     }
1467 
1468     {
1469       ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_rebuild_freeset);
1470       ShenandoahHeapLocker locker(lock());
1471       _free_set->rebuild();
1472     }
1473 
1474     // If collection set has candidates, start evacuation.
1475     // Otherwise, bypass the rest of the cycle.
1476     if (!collection_set()->is_empty()) {
1477       ShenandoahGCPhase init_evac(ShenandoahPhaseTimings::init_evac);
1478 
1479       if (ShenandoahVerify) {
1480         verifier()->verify_before_evacuation();
1481       }
1482 
1483       set_evacuation_in_progress(true);
1484       // From here on, we need to update references.
1485       set_has_forwarded_objects(true);
1486 
1487       if (!is_degenerated_gc_in_progress()) {
1488         evacuate_and_update_roots();
1489       }
1490  
1491       if (ShenandoahPacing) {
1492         pacer()->setup_for_evac();
1493       }
1494 
1495       if (ShenandoahVerify) {
1496         verifier()->verify_roots_no_forwarded();
1497         verifier()->verify_during_evacuation();
1498       }
1499     } else {
1500       if (ShenandoahVerify) {
1501         verifier()->verify_after_concmark();
1502       }
1503 
1504       if (VerifyAfterGC) {
1505         Universe::verify();
1506       }
1507     }
1508 
1509   } else {
1510     concurrent_mark()->cancel();
1511     stop_concurrent_marking();
1512 
1513     if (process_references()) {
1514       // Abandon reference processing right away: pre-cleaning must have failed.
1515       ReferenceProcessor *rp = ref_processor();
1516       rp->disable_discovery();
1517       rp->abandon_partial_discovery();
1518       rp->verify_no_references_recorded();
1519     }
1520   }
1521 }
1522 
1523 void ShenandoahHeap::op_conc_evac() {
1524   ShenandoahEvacuationTask task(this, _collection_set, true);
1525   workers()->run_task(&task);
1526 }
1527 
1528 void ShenandoahHeap::op_stw_evac() {
1529   ShenandoahEvacuationTask task(this, _collection_set, false);
1530   workers()->run_task(&task);
1531 }
1532 
1533 void ShenandoahHeap::op_updaterefs() {
1534   update_heap_references(true);
1535 }
1536 
1537 void ShenandoahHeap::op_cleanup_early() {
1538   free_set()->recycle_trash();
1539 }
1540 
1541 void ShenandoahHeap::op_cleanup_complete() {
1542   free_set()->recycle_trash();
1543 }
1544 
1545 class ShenandoahResetUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
1546 private:
1547   ShenandoahMarkingContext* const _ctx;
1548 public:
1549   ShenandoahResetUpdateRegionStateClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
1550 
1551   void heap_region_do(ShenandoahHeapRegion* r) {
1552     if (r->is_active()) {
1553       // Reset live data and set TAMS optimistically. We would recheck these under the pause
1554       // anyway to capture any updates that happened since now.
1555       r->clear_live_data();
1556       _ctx->capture_top_at_mark_start(r);
1557     }
1558   }
1559 
1560   bool is_thread_safe() { return true; }
1561 };
1562 
1563 void ShenandoahHeap::op_reset() {
1564   if (ShenandoahPacing) {
1565     pacer()->setup_for_reset();
1566   }
1567   reset_mark_bitmap();
1568 
1569   ShenandoahResetUpdateRegionStateClosure cl;
1570   parallel_heap_region_iterate(&cl);
1571 }
1572 
1573 void ShenandoahHeap::op_preclean() {
1574   if (ShenandoahPacing) {
1575     pacer()->setup_for_preclean();
1576   }
1577   concurrent_mark()->preclean_weak_refs();
1578 }
1579 
1580 void ShenandoahHeap::op_full(GCCause::Cause cause) {
1581   ShenandoahMetricsSnapshot metrics;
1582   metrics.snap_before();
1583 
1584   full_gc()->do_it(cause);
1585 
1586   metrics.snap_after();
1587 
1588   if (metrics.is_good_progress()) {
1589     _progress_last_gc.set();
1590   } else {
1591     // Nothing to do. Tell the allocation path that we have failed to make
1592     // progress, and it can finally fail.
1593     _progress_last_gc.unset();
1594   }
1595 }
1596 
1597 void ShenandoahHeap::op_degenerated(ShenandoahDegenPoint point) {
1598   // Degenerated GC is STW, but it can also fail. Current mechanics communicates
1599   // GC failure via cancelled_concgc() flag. So, if we detect the failure after
1600   // some phase, we have to upgrade the Degenerate GC to Full GC.
1601 
1602   clear_cancelled_gc();
1603 
1604   ShenandoahMetricsSnapshot metrics;
1605   metrics.snap_before();
1606 
1607   switch (point) {
1608     // The cases below form the Duff's-like device: it describes the actual GC cycle,
1609     // but enters it at different points, depending on which concurrent phase had
1610     // degenerated.
1611 
1612     case _degenerated_outside_cycle:
1613       // We have degenerated from outside the cycle, which means something is bad with
1614       // the heap, most probably heavy humongous fragmentation, or we are very low on free
1615       // space. It makes little sense to wait for Full GC to reclaim as much as it can, when
1616       // we can do the most aggressive degen cycle, which includes processing references and
1617       // class unloading, unless those features are explicitly disabled.
1618       //
1619       // Note that we can only do this for "outside-cycle" degens, otherwise we would risk
1620       // changing the cycle parameters mid-cycle during concurrent -> degenerated handover.
1621       set_process_references(heuristics()->can_process_references());
1622       set_unload_classes(heuristics()->can_unload_classes());
1623 
1624       op_reset();
1625 
1626       op_init_mark();
1627       if (cancelled_gc()) {
1628         op_degenerated_fail();
1629         return;
1630       }
1631 
1632     case _degenerated_mark:
1633       op_final_mark();
1634       if (cancelled_gc()) {
1635         op_degenerated_fail();
1636         return;
1637       }
1638 
1639       op_cleanup_early();
1640 
1641     case _degenerated_evac:
1642       // If heuristics thinks we should do the cycle, this flag would be set,
1643       // and we can do evacuation. Otherwise, it would be the shortcut cycle.
1644       if (is_evacuation_in_progress()) {
1645 
1646         // Degeneration under oom-evac protocol might have left some objects in
1647         // collection set un-evacuated. Restart evacuation from the beginning to
1648         // capture all objects. For all the objects that are already evacuated,
1649         // it would be a simple check, which is supposed to be fast. This is also
1650         // safe to do even without degeneration, as CSet iterator is at beginning
1651         // in preparation for evacuation anyway.
1652         //
1653         // Before doing that, we need to make sure we never had any cset-pinned
1654         // regions. This may happen if allocation failure happened when evacuating
1655         // the about-to-be-pinned object, oom-evac protocol left the object in
1656         // the collection set, and then the pin reached the cset region. If we continue
1657         // the cycle here, we would trash the cset and alive objects in it. To avoid
1658         // it, we fail degeneration right away and slide into Full GC to recover.
1659 
1660         {
1661           sync_pinned_region_status();
1662           collection_set()->clear_current_index();
1663 
1664           ShenandoahHeapRegion* r;
1665           while ((r = collection_set()->next()) != NULL) {
1666             if (r->is_pinned()) {
1667               cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1668               op_degenerated_fail();
1669               return;
1670             }
1671           }
1672 
1673           collection_set()->clear_current_index();
1674         }
1675 
1676         op_stw_evac();
1677         if (cancelled_gc()) {
1678           op_degenerated_fail();
1679           return;
1680         }
1681       }
1682 
1683       // If heuristics thinks we should do the cycle, this flag would be set,
1684       // and we need to do update-refs. Otherwise, it would be the shortcut cycle.
1685       if (has_forwarded_objects()) {
1686         op_init_updaterefs();
1687         if (cancelled_gc()) {
1688           op_degenerated_fail();
1689           return;
1690         }
1691       }
1692 
1693     case _degenerated_updaterefs:
1694       if (has_forwarded_objects()) {
1695         op_final_updaterefs();
1696         if (cancelled_gc()) {
1697           op_degenerated_fail();
1698           return;
1699         }
1700       }
1701 
1702       op_cleanup_complete();
1703       break;
1704 
1705     default:
1706       ShouldNotReachHere();
1707   }
1708 
1709   if (ShenandoahVerify) {
1710     verifier()->verify_after_degenerated();
1711   }
1712 
1713   if (VerifyAfterGC) {
1714     Universe::verify();
1715   }
1716 
1717   metrics.snap_after();
1718 
1719   // Check for futility and fail. There is no reason to do several back-to-back Degenerated cycles,
1720   // because that probably means the heap is overloaded and/or fragmented.
1721   if (!metrics.is_good_progress()) {
1722     _progress_last_gc.unset();
1723     cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1724     op_degenerated_futile();
1725   } else {
1726     _progress_last_gc.set();
1727   }
1728 }
1729 
1730 void ShenandoahHeap::op_degenerated_fail() {
1731   log_info(gc)("Cannot finish degeneration, upgrading to Full GC");
1732   shenandoah_policy()->record_degenerated_upgrade_to_full();
1733   op_full(GCCause::_shenandoah_upgrade_to_full_gc);
1734 }
1735 
1736 void ShenandoahHeap::op_degenerated_futile() {
1737   shenandoah_policy()->record_degenerated_upgrade_to_full();
1738   op_full(GCCause::_shenandoah_upgrade_to_full_gc);
1739 }
1740 
1741 void ShenandoahHeap::stop_concurrent_marking() {
1742   assert(is_concurrent_mark_in_progress(), "How else could we get here?");
1743   set_concurrent_mark_in_progress(false);
1744   if (!cancelled_gc()) {
1745     // If we needed to update refs, and concurrent marking has been cancelled,
1746     // we need to finish updating references.
1747     set_has_forwarded_objects(false);
1748     mark_complete_marking_context();
1749   }
1750 }
1751 
1752 void ShenandoahHeap::force_satb_flush_all_threads() {
1753   if (!is_concurrent_mark_in_progress()) {
1754     // No need to flush SATBs
1755     return;
1756   }
1757 
1758   // Do not block if Threads lock is busy. This avoids the potential deadlock
1759   // when this code is called from the periodic task, and something else is
1760   // expecting the periodic task to complete without blocking. On the off-chance
1761   // Threads lock is busy momentarily, try to acquire several times.
1762   for (int t = 0; t < 10; t++) {
1763     if (Threads_lock->try_lock()) {
1764       JavaThread::set_force_satb_flush_all_threads(true);
1765       Threads_lock->unlock();
1766 
1767       // The threads are not "acquiring" their thread-local data, but it does not
1768       // hurt to "release" the updates here anyway.
1769       OrderAccess::fence();
1770       break;
1771     }
1772     os::naked_short_sleep(1);
1773   }
1774 }
1775 
1776 void ShenandoahHeap::set_gc_state_mask(uint mask, bool value) {
1777   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should really be Shenandoah safepoint");
1778   _gc_state.set_cond(mask, value);
1779   JavaThread::set_gc_state_all_threads(_gc_state.raw_value());
1780 }
1781 
1782 void ShenandoahHeap::set_concurrent_mark_in_progress(bool in_progress) {
1783   if (has_forwarded_objects()) {
1784     set_gc_state_mask(MARKING | UPDATEREFS, in_progress);
1785   } else {
1786     set_gc_state_mask(MARKING, in_progress);
1787   }
1788   JavaThread::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
1789 }
1790 
1791 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {
1792   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint");
1793   set_gc_state_mask(EVACUATION, in_progress);
1794 }
1795 
1796 void ShenandoahHeap::ref_processing_init() {
1797   MemRegion mr = reserved_region();
1798 
1799   assert(_max_workers > 0, "Sanity");
1800 
1801   bool mt_processing = ParallelRefProcEnabled && (ParallelGCThreads > 1);
1802   bool mt_discovery = _max_workers > 1;
1803 
1804   _ref_processor =
1805     new ReferenceProcessor(mr,    // span
1806                            mt_processing,           // MT processing
1807                            _max_workers,            // Degree of MT processing
1808                            mt_discovery,            // MT discovery
1809                            _max_workers,            // Degree of MT discovery
1810                            false,                   // Reference discovery is not atomic
1811                            NULL);                   // No closure, should be installed before use
1812 
1813   log_info(gc, init)("Reference processing: %s discovery, %s processing",
1814           mt_discovery ? "parallel" : "serial",
1815           mt_processing ? "parallel" : "serial");
1816 
1817   shenandoah_assert_rp_isalive_not_installed();
1818 }
1819 
1820 void ShenandoahHeap::acquire_pending_refs_lock() {
1821   _control_thread->slt()->manipulatePLL(SurrogateLockerThread::acquirePLL);
1822 }
1823 
1824 void ShenandoahHeap::release_pending_refs_lock() {
1825   _control_thread->slt()->manipulatePLL(SurrogateLockerThread::releaseAndNotifyPLL);
1826 }
1827 
1828 GCTracer* ShenandoahHeap::tracer() {
1829   return shenandoah_policy()->tracer();
1830 }
1831 
1832 size_t ShenandoahHeap::tlab_used(Thread* thread) const {
1833   return _free_set->used();
1834 }
1835 
1836 void ShenandoahHeap::cancel_gc(GCCause::Cause cause) {
1837   if (try_cancel_gc()) {
1838     FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause));
1839     log_info(gc)("%s", msg.buffer());
1840     Events::log(Thread::current(), "%s", msg.buffer());
1841   }
1842 }
1843 
1844 uint ShenandoahHeap::max_workers() {
1845   return _max_workers;
1846 }
1847 
1848 void ShenandoahHeap::stop() {
1849   // The shutdown sequence should be able to terminate when GC is running.
1850 
1851   // Step 0. Notify policy to disable event recording.
1852   _shenandoah_policy->record_shutdown();
1853 
1854   // Step 1. Notify control thread that we are in shutdown.
1855   // Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown.
1856   // Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below.
1857   _control_thread->prepare_for_graceful_shutdown();
1858 
1859   // Step 2. Notify GC workers that we are cancelling GC.
1860   cancel_gc(GCCause::_shenandoah_stop_vm);
1861 
1862   // Step 3. Wait until GC worker exits normally.
1863   _control_thread->stop();
1864 
1865   // Step 4. Stop String Dedup thread if it is active
1866   if (ShenandoahStringDedup::is_enabled()) {
1867     ShenandoahStringDedup::stop();
1868   }
1869 }
1870 
1871 void ShenandoahHeap::unload_classes_and_cleanup_tables(bool full_gc) {
1872   assert(heuristics()->can_unload_classes(), "Class unloading should be enabled");
1873 
1874   ShenandoahGCPhase root_phase(full_gc ?
1875                                ShenandoahPhaseTimings::full_gc_purge :
1876                                ShenandoahPhaseTimings::purge);
1877 
1878   ShenandoahIsAliveSelector alive;
1879   BoolObjectClosure* is_alive = alive.is_alive_closure();
1880 
1881   // Cleaning of klasses depends on correct information from MetadataMarkOnStack. The CodeCache::mark_on_stack
1882   // part is too slow to be done serially, so it is handled during the ShenandoahParallelCleaning phase.
1883   // Defer the cleaning until we have complete on_stack data.
1884   MetadataOnStackMark md_on_stack(false /* Don't visit the code cache at this point */);
1885 
1886   bool purged_class;
1887 
1888   // Unload classes and purge SystemDictionary.
1889   {
1890     ShenandoahGCPhase phase(full_gc ?
1891                             ShenandoahPhaseTimings::full_gc_purge_class_unload :
1892                             ShenandoahPhaseTimings::purge_class_unload);
1893     purged_class = SystemDictionary::do_unloading(is_alive,
1894                                                   false /* Defer klass cleaning */);
1895   }
1896   {
1897     ShenandoahGCPhase phase(full_gc ?
1898                             ShenandoahPhaseTimings::full_gc_purge_par :
1899                             ShenandoahPhaseTimings::purge_par);
1900     uint active = _workers->active_workers();
1901     ShenandoahParallelCleaningTask unlink_task(is_alive, true, true, active, purged_class);
1902     _workers->run_task(&unlink_task);
1903   }
1904 
1905   {
1906     ShenandoahGCPhase phase(full_gc ?
1907                             ShenandoahPhaseTimings::full_gc_purge_metadata :
1908                             ShenandoahPhaseTimings::purge_metadata);
1909     ClassLoaderDataGraph::free_deallocate_lists();
1910   }
1911 
1912   if (ShenandoahStringDedup::is_enabled()) {
1913     ShenandoahGCPhase phase(full_gc ?
1914                             ShenandoahPhaseTimings::full_gc_purge_string_dedup :
1915                             ShenandoahPhaseTimings::purge_string_dedup);
1916     ShenandoahStringDedup::parallel_cleanup();
1917   }
1918 
1919   {
1920     ShenandoahGCPhase phase(full_gc ?
1921                             ShenandoahPhaseTimings::full_gc_purge_cldg :
1922                             ShenandoahPhaseTimings::purge_cldg);
1923     ClassLoaderDataGraph::purge();
1924   }
1925 }
1926 
1927 void ShenandoahHeap::set_has_forwarded_objects(bool cond) {
1928   set_gc_state_mask(HAS_FORWARDED, cond);
1929 }
1930 
1931 void ShenandoahHeap::set_process_references(bool pr) {
1932   _process_references.set_cond(pr);
1933 }
1934 
1935 void ShenandoahHeap::set_unload_classes(bool uc) {
1936   _unload_classes.set_cond(uc);
1937 }
1938 
1939 bool ShenandoahHeap::process_references() const {
1940   return _process_references.is_set();
1941 }
1942 
1943 bool ShenandoahHeap::unload_classes() const {
1944   return _unload_classes.is_set();
1945 }
1946 
1947 address ShenandoahHeap::in_cset_fast_test_addr() {
1948   ShenandoahHeap* heap = ShenandoahHeap::heap();
1949   assert(heap->collection_set() != NULL, "Sanity");
1950   return (address) heap->collection_set()->biased_map_address();
1951 }
1952 
1953 address ShenandoahHeap::cancelled_gc_addr() {
1954   return (address) ShenandoahHeap::heap()->_cancelled_gc.addr_of();
1955 }
1956 
1957 address ShenandoahHeap::gc_state_addr() {
1958   return (address) ShenandoahHeap::heap()->_gc_state.addr_of();
1959 }
1960 
1961 size_t ShenandoahHeap::conservative_max_heap_alignment() {
1962   size_t align = ShenandoahMaxRegionSize;
1963   if (UseLargePages) {
1964     align = MAX2(align, os::large_page_size());
1965   }
1966   return align;
1967 }
1968 
1969 size_t ShenandoahHeap::bytes_allocated_since_gc_start() {
1970   return OrderAccess::load_acquire(&_bytes_allocated_since_gc_start);
1971 }
1972 
1973 void ShenandoahHeap::reset_bytes_allocated_since_gc_start() {
1974   OrderAccess::release_store_fence(&_bytes_allocated_since_gc_start, (size_t)0);
1975 }
1976 
1977 void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) {
1978   _degenerated_gc_in_progress.set_cond(in_progress);
1979 }
1980 
1981 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {
1982   _full_gc_in_progress.set_cond(in_progress);
1983 }
1984 
1985 void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) {
1986   assert (is_full_gc_in_progress(), "should be");
1987   _full_gc_move_in_progress.set_cond(in_progress);
1988 }
1989 
1990 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {
1991   set_gc_state_mask(UPDATEREFS, in_progress);
1992 }
1993 
1994 void ShenandoahHeap::register_nmethod(nmethod* nm) {
1995   ShenandoahCodeRoots::add_nmethod(nm);
1996 }
1997 
1998 void ShenandoahHeap::unregister_nmethod(nmethod* nm) {
1999   ShenandoahCodeRoots::remove_nmethod(nm);
2000 }
2001 
2002 oop ShenandoahHeap::pin_object(JavaThread* thr, oop o) {
2003   heap_region_containing(o)->record_pin();
2004   return o;
2005 }
2006 
2007 void ShenandoahHeap::unpin_object(JavaThread* thr, oop o) {
2008   heap_region_containing(o)->record_unpin();
2009 }
2010 
2011 void ShenandoahHeap::sync_pinned_region_status() {
2012   ShenandoahHeapLocker locker(lock());
2013 
2014   for (size_t i = 0; i < num_regions(); i++) {
2015     ShenandoahHeapRegion *r = get_region(i);
2016     if (r->is_active()) {
2017       if (r->is_pinned()) {
2018         if (r->pin_count() == 0) {
2019           r->make_unpinned();
2020         }
2021       } else {
2022         if (r->pin_count() > 0) {
2023           r->make_pinned();
2024         }
2025       }
2026     }
2027   }
2028 
2029   assert_pinned_region_status();
2030 }
2031 
2032 #ifdef ASSERT
2033 void ShenandoahHeap::assert_pinned_region_status() {
2034   for (size_t i = 0; i < num_regions(); i++) {
2035     ShenandoahHeapRegion* r = get_region(i);
2036     assert((r->is_pinned() && r->pin_count() > 0) || (!r->is_pinned() && r->pin_count() == 0),
2037            err_msg("Region " SIZE_FORMAT " pinning status is inconsistent", i));
2038   }
2039 }
2040 #endif
2041 
2042 GCTimer* ShenandoahHeap::gc_timer() const {
2043   return _gc_timer;
2044 }
2045 
2046 #ifdef ASSERT
2047 void ShenandoahHeap::assert_gc_workers(uint nworkers) {
2048   assert(nworkers > 0 && nworkers <= max_workers(), "Sanity");
2049 
2050   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
2051     if (UseDynamicNumberOfGCThreads ||
2052         (FLAG_IS_DEFAULT(ParallelGCThreads) && ForceDynamicNumberOfGCThreads)) {
2053       assert(nworkers <= ParallelGCThreads, "Cannot use more than it has");
2054     } else {
2055       // Use ParallelGCThreads inside safepoints
2056       assert(nworkers == ParallelGCThreads, "Use ParalleGCThreads within safepoints");
2057     }
2058   } else {
2059     if (UseDynamicNumberOfGCThreads ||
2060         (FLAG_IS_DEFAULT(ConcGCThreads) && ForceDynamicNumberOfGCThreads)) {
2061       assert(nworkers <= ConcGCThreads, "Cannot use more than it has");
2062     } else {
2063       // Use ConcGCThreads outside safepoints
2064       assert(nworkers == ConcGCThreads, "Use ConcGCThreads outside safepoints");
2065     }
2066   }
2067 }
2068 #endif
2069 
2070 ShenandoahVerifier* ShenandoahHeap::verifier() {
2071   guarantee(ShenandoahVerify, "Should be enabled");
2072   assert (_verifier != NULL, "sanity");
2073   return _verifier;
2074 }
2075 
2076 ShenandoahUpdateHeapRefsClosure::ShenandoahUpdateHeapRefsClosure() :
2077   _heap(ShenandoahHeap::heap()) {}
2078 
2079 class ShenandoahUpdateHeapRefsTask : public AbstractGangTask {
2080 private:
2081   ShenandoahHeap* _heap;
2082   ShenandoahRegionIterator* _regions;
2083   bool _concurrent;
2084 
2085 public:
2086   ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions, bool concurrent) :
2087     AbstractGangTask("Concurrent Update References Task"),
2088     _heap(ShenandoahHeap::heap()),
2089     _regions(regions),
2090     _concurrent(concurrent) {
2091   }
2092 
2093   void work(uint worker_id) {
2094     ShenandoahConcurrentWorkerSession worker_session(worker_id);
2095     ShenandoahUpdateHeapRefsClosure cl;
2096     ShenandoahHeapRegion* r = _regions->next();
2097     ShenandoahMarkingContext* const ctx = _heap->complete_marking_context();
2098     while (r != NULL) {
2099       HeapWord* update_watermark = r->get_update_watermark();
2100       assert (update_watermark >= r->bottom(), "sanity");
2101       if (r->is_active() && !r->is_cset()) {
2102         _heap->marked_object_oop_iterate(r, &cl, update_watermark);
2103       }
2104       if (ShenandoahPacing) {
2105         _heap->pacer()->report_updaterefs(pointer_delta(update_watermark, r->bottom()));
2106       }
2107       if (_heap->cancelled_gc()) {
2108         return;
2109       }
2110       r = _regions->next();
2111     }
2112   }
2113 };
2114 
2115 void ShenandoahHeap::update_heap_references(bool concurrent) {
2116   ShenandoahUpdateHeapRefsTask task(&_update_refs_iterator, concurrent);
2117   workers()->run_task(&task);
2118 }
2119 
2120 void ShenandoahHeap::op_init_updaterefs() {
2121   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2122 
2123   set_evacuation_in_progress(false);
2124 
2125   if (ShenandoahVerify) {
2126     if (!is_degenerated_gc_in_progress()) {
2127       verifier()->verify_roots_no_forwarded_except(ShenandoahRootVerifier::ThreadRoots);
2128     }
2129     verifier()->verify_before_updaterefs();
2130   }
2131 
2132   set_update_refs_in_progress(true);
2133 
2134   {
2135     ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs_prepare);
2136 
2137     make_parsable(true);
2138 
2139     // Reset iterator.
2140     _update_refs_iterator.reset();
2141   }
2142 
2143   if (ShenandoahPacing) {
2144     pacer()->setup_for_updaterefs();
2145   }
2146 }
2147 
2148 class ShenandoahFinalUpdateRefsUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
2149 private:
2150   ShenandoahHeapLock* const _lock;
2151 
2152 public:
2153   ShenandoahFinalUpdateRefsUpdateRegionStateClosure() : _lock(ShenandoahHeap::heap()->lock()) {}
2154 
2155   void heap_region_do(ShenandoahHeapRegion* r) {
2156     // Drop unnecessary "pinned" state from regions that does not have CP marks
2157     // anymore, as this would allow trashing them.
2158 
2159     if (r->is_active()) {
2160       if (r->is_pinned()) {
2161         if (r->pin_count() == 0) {
2162           ShenandoahHeapLocker locker(_lock);
2163           r->make_unpinned();
2164         }
2165       } else {
2166         if (r->pin_count() > 0) {
2167           ShenandoahHeapLocker locker(_lock);
2168           r->make_pinned();
2169         }
2170       }
2171     }
2172   }
2173 
2174   bool is_thread_safe() { return true; }
2175 };
2176 
2177 void ShenandoahHeap::op_final_updaterefs() {
2178   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2179 
2180   // Check if there is left-over work, and finish it
2181   if (_update_refs_iterator.has_next()) {
2182     ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_finish_work);
2183 
2184     // Finish updating references where we left off.
2185     clear_cancelled_gc();
2186     update_heap_references(false);
2187   }
2188 
2189   // Clear cancelled GC, if set. On cancellation path, the block before would handle
2190   // everything. On degenerated paths, cancelled gc would not be set anyway.
2191   if (cancelled_gc()) {
2192     clear_cancelled_gc();
2193   }
2194   assert(!cancelled_gc(), "Should have been done right before");
2195 
2196   if (ShenandoahVerify && !is_degenerated_gc_in_progress()) {
2197     verifier()->verify_roots_no_forwarded_except(ShenandoahRootVerifier::ThreadRoots);
2198   }
2199 
2200   if (is_degenerated_gc_in_progress()) {
2201     concurrent_mark()->update_roots(ShenandoahPhaseTimings::degen_gc_update_roots);
2202   } else {
2203     concurrent_mark()->update_thread_roots(ShenandoahPhaseTimings::final_update_refs_roots);
2204   }
2205 
2206   // Has to be done before cset is clear
2207   if (ShenandoahVerify) {
2208     verifier()->verify_roots_in_to_space();
2209   }
2210 
2211   {
2212     ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_trash_cset);
2213     trash_cset_regions();
2214   }
2215 
2216   set_has_forwarded_objects(false);
2217   set_update_refs_in_progress(false);
2218 
2219   if (ShenandoahVerify) {
2220     verifier()->verify_after_updaterefs();
2221   }
2222 
2223   if (VerifyAfterGC) {
2224     Universe::verify();
2225   }
2226 
2227   {
2228     ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_update_region_states);
2229     ShenandoahFinalUpdateRefsUpdateRegionStateClosure cl;
2230     parallel_heap_region_iterate(&cl);
2231 
2232     assert_pinned_region_status();
2233   }
2234 
2235   {
2236     ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_rebuild_freeset);
2237     ShenandoahHeapLocker locker(lock());
2238     _free_set->rebuild();
2239   }
2240 }
2241 
2242 void ShenandoahHeap::print_extended_on(outputStream *st) const {
2243   print_on(st);
2244   print_heap_regions_on(st);
2245 }
2246 
2247 bool ShenandoahHeap::is_bitmap_slice_committed(ShenandoahHeapRegion* r, bool skip_self) {
2248   size_t slice = r->index() / _bitmap_regions_per_slice;
2249 
2250   size_t regions_from = _bitmap_regions_per_slice * slice;
2251   size_t regions_to   = MIN2(num_regions(), _bitmap_regions_per_slice * (slice + 1));
2252   for (size_t g = regions_from; g < regions_to; g++) {
2253     assert (g / _bitmap_regions_per_slice == slice, "same slice");
2254     if (skip_self && g == r->index()) continue;
2255     if (get_region(g)->is_committed()) {
2256       return true;
2257     }
2258   }
2259   return false;
2260 }
2261 
2262 bool ShenandoahHeap::commit_bitmap_slice(ShenandoahHeapRegion* r) {
2263   shenandoah_assert_heaplocked();
2264 
2265   // Bitmaps in special regions do not need commits
2266   if (_bitmap_region_special) {
2267     return true;
2268   }
2269 
2270   if (is_bitmap_slice_committed(r, true)) {
2271     // Some other region from the group is already committed, meaning the bitmap
2272     // slice is already committed, we exit right away.
2273     return true;
2274   }
2275 
2276   // Commit the bitmap slice:
2277   size_t slice = r->index() / _bitmap_regions_per_slice;
2278   size_t off = _bitmap_bytes_per_slice * slice;
2279   size_t len = _bitmap_bytes_per_slice;
2280   char* start = (char*) _bitmap_region.start() + off;
2281 
2282   if (!os::commit_memory(start, len, false)) {
2283     return false;
2284   }
2285 
2286   if (AlwaysPreTouch) {
2287     os::pretouch_memory(start, start + len);
2288   }
2289 
2290   return true;
2291 }
2292 
2293 bool ShenandoahHeap::uncommit_bitmap_slice(ShenandoahHeapRegion *r) {
2294   shenandoah_assert_heaplocked();
2295 
2296   // Bitmaps in special regions do not need uncommits
2297   if (_bitmap_region_special) {
2298     return true;
2299   }
2300 
2301   if (is_bitmap_slice_committed(r, true)) {
2302     // Some other region from the group is still committed, meaning the bitmap
2303     // slice is should stay committed, exit right away.
2304     return true;
2305   }
2306 
2307   // Uncommit the bitmap slice:
2308   size_t slice = r->index() / _bitmap_regions_per_slice;
2309   size_t off = _bitmap_bytes_per_slice * slice;
2310   size_t len = _bitmap_bytes_per_slice;
2311   if (!os::uncommit_memory((char*)_bitmap_region.start() + off, len)) {
2312     return false;
2313   }
2314   return true;
2315 }
2316 
2317 void ShenandoahHeap::vmop_entry_init_mark() {
2318   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2319   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_mark_gross);
2320 
2321   try_inject_alloc_failure();
2322   VM_ShenandoahInitMark op;
2323   VMThread::execute(&op); // jump to entry_init_mark() under safepoint
2324 }
2325 
2326 void ShenandoahHeap::vmop_entry_final_mark() {
2327   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2328   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_mark_gross);
2329 
2330   try_inject_alloc_failure();
2331   VM_ShenandoahFinalMarkStartEvac op;
2332   VMThread::execute(&op); // jump to entry_final_mark under safepoint
2333 }
2334 
2335 void ShenandoahHeap::vmop_entry_init_updaterefs() {
2336   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2337   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs_gross);
2338 
2339   try_inject_alloc_failure();
2340   VM_ShenandoahInitUpdateRefs op;
2341   VMThread::execute(&op);
2342 }
2343 
2344 void ShenandoahHeap::vmop_entry_final_updaterefs() {
2345   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2346   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_gross);
2347 
2348   try_inject_alloc_failure();
2349   VM_ShenandoahFinalUpdateRefs op;
2350   VMThread::execute(&op);
2351 }
2352 
2353 void ShenandoahHeap::vmop_entry_full(GCCause::Cause cause) {
2354   TraceCollectorStats tcs(monitoring_support()->full_stw_collection_counters());
2355   ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_gross);
2356 
2357   try_inject_alloc_failure();
2358   VM_ShenandoahFullGC op(cause);
2359   VMThread::execute(&op);
2360 }
2361 
2362 void ShenandoahHeap::vmop_degenerated(ShenandoahDegenPoint point) {
2363   TraceCollectorStats tcs(monitoring_support()->full_stw_collection_counters());
2364   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_gross);
2365 
2366   VM_ShenandoahDegeneratedGC degenerated_gc((int)point);
2367   VMThread::execute(&degenerated_gc);
2368 }
2369 
2370 void ShenandoahHeap::entry_init_mark() {
2371   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_mark);
2372 
2373   const char* msg = init_mark_event_message();
2374   GCTraceTime time(msg, PrintGC, _gc_timer, tracer()->gc_id());
2375   EventMark em("%s", msg);
2376 
2377   ShenandoahWorkerScope scope(workers(),
2378                               ShenandoahWorkerPolicy::calc_workers_for_init_marking(),
2379                               "init marking");
2380 
2381   op_init_mark();
2382 }
2383 
2384 void ShenandoahHeap::entry_final_mark() {
2385   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_mark);
2386 
2387   const char* msg = final_mark_event_message();
2388   GCTraceTime time(msg, PrintGC, _gc_timer, tracer()->gc_id());
2389   EventMark em("%s", msg);
2390 
2391   ShenandoahWorkerScope scope(workers(),
2392                               ShenandoahWorkerPolicy::calc_workers_for_final_marking(),
2393                               "final marking");
2394 
2395   op_final_mark();
2396 }
2397 
2398 void ShenandoahHeap::entry_init_updaterefs() {
2399   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs);
2400 
2401   static const char* msg = "Pause Init Update Refs";
2402   GCTraceTime time(msg, PrintGC, _gc_timer, tracer()->gc_id());
2403   EventMark em("%s", msg);
2404 
2405   // No workers used in this phase, no setup required
2406 
2407   op_init_updaterefs();
2408 }
2409 
2410 void ShenandoahHeap::entry_final_updaterefs() {
2411   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs);
2412 
2413   static const char* msg = "Pause Final Update Refs";
2414   GCTraceTime time(msg, PrintGC, _gc_timer, tracer()->gc_id());
2415   EventMark em("%s", msg);
2416 
2417   ShenandoahWorkerScope scope(workers(),
2418                               ShenandoahWorkerPolicy::calc_workers_for_final_update_ref(),
2419                               "final reference update");
2420 
2421   op_final_updaterefs();
2422 }
2423 
2424 void ShenandoahHeap::entry_full(GCCause::Cause cause) {
2425   ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc);
2426 
2427   static const char* msg = "Pause Full";
2428   GCTraceTime time(msg, PrintGC, _gc_timer, tracer()->gc_id(), true);
2429   EventMark em("%s", msg);
2430 
2431   ShenandoahWorkerScope scope(workers(),
2432                               ShenandoahWorkerPolicy::calc_workers_for_fullgc(),
2433                               "full gc");
2434 
2435   op_full(cause);
2436 }
2437 
2438 void ShenandoahHeap::entry_degenerated(int point) {
2439   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc);
2440 
2441   ShenandoahDegenPoint dpoint = (ShenandoahDegenPoint)point;
2442   const char* msg = degen_event_message(dpoint);
2443   GCTraceTime time(msg, PrintGC, _gc_timer, tracer()->gc_id(), true);
2444   EventMark em("%s", msg);
2445 
2446   ShenandoahWorkerScope scope(workers(),
2447                               ShenandoahWorkerPolicy::calc_workers_for_stw_degenerated(),
2448                               "stw degenerated gc");
2449 
2450   set_degenerated_gc_in_progress(true);
2451   op_degenerated(dpoint);
2452   set_degenerated_gc_in_progress(false);
2453 }
2454 
2455 void ShenandoahHeap::entry_mark() {
2456   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2457 
2458   const char* msg = conc_mark_event_message();
2459   GCTraceTime time(msg, PrintGC, NULL, tracer()->gc_id());
2460   EventMark em("%s", msg);
2461 
2462   ShenandoahWorkerScope scope(workers(),
2463                               ShenandoahWorkerPolicy::calc_workers_for_conc_marking(),
2464                               "concurrent marking");
2465 
2466   try_inject_alloc_failure();
2467   op_mark();
2468 }
2469 
2470 void ShenandoahHeap::entry_evac() {
2471   ShenandoahGCPhase conc_evac_phase(ShenandoahPhaseTimings::conc_evac);
2472   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2473 
2474   static const char *msg = "Concurrent evacuation";
2475   GCTraceTime time(msg, PrintGC, NULL, tracer()->gc_id());
2476   EventMark em("%s", msg);
2477 
2478   ShenandoahWorkerScope scope(workers(),
2479                               ShenandoahWorkerPolicy::calc_workers_for_conc_evac(),
2480                               "concurrent evacuation");
2481 
2482   try_inject_alloc_failure();
2483   op_conc_evac();
2484 }
2485 
2486 void ShenandoahHeap::entry_updaterefs() {
2487   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_update_refs);
2488 
2489   static const char* msg = "Concurrent update references";
2490   GCTraceTime time(msg, PrintGC, NULL, tracer()->gc_id());
2491   EventMark em("%s", msg);
2492 
2493   ShenandoahWorkerScope scope(workers(),
2494                               ShenandoahWorkerPolicy::calc_workers_for_conc_update_ref(),
2495                               "concurrent reference update");
2496 
2497   try_inject_alloc_failure();
2498   op_updaterefs();
2499 }
2500 
2501 void ShenandoahHeap::entry_cleanup_early() {
2502   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_cleanup_early);
2503 
2504   static const char* msg = "Concurrent cleanup";
2505   GCTraceTime time(msg, PrintGC, NULL, tracer()->gc_id(), true);
2506   EventMark em("%s", msg);
2507 
2508   // This phase does not use workers, no need for setup
2509 
2510   try_inject_alloc_failure();
2511   op_cleanup_early();
2512 }
2513 
2514 void ShenandoahHeap::entry_cleanup_complete() {
2515   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_cleanup_complete);
2516 
2517   static const char* msg = "Concurrent cleanup";
2518   GCTraceTime time(msg, PrintGC, NULL, tracer()->gc_id(), true);
2519   EventMark em("%s", msg);
2520 
2521   // This phase does not use workers, no need for setup
2522 
2523   try_inject_alloc_failure();
2524   op_cleanup_complete();
2525 }
2526 
2527 void ShenandoahHeap::entry_reset() {
2528   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_reset);
2529 
2530   static const char* msg = "Concurrent reset";
2531   GCTraceTime time(msg, PrintGC, NULL, tracer()->gc_id());
2532   EventMark em("%s", msg);
2533 
2534   ShenandoahWorkerScope scope(workers(),
2535                               ShenandoahWorkerPolicy::calc_workers_for_conc_reset(),
2536                               "concurrent reset");
2537 
2538   try_inject_alloc_failure();
2539   op_reset();
2540 }
2541 
2542 void ShenandoahHeap::entry_preclean() {
2543   if (ShenandoahPreclean && process_references()) {
2544     ShenandoahGCPhase conc_preclean(ShenandoahPhaseTimings::conc_preclean);
2545 
2546     static const char* msg = "Concurrent precleaning";
2547     GCTraceTime time(msg, PrintGC, NULL, tracer()->gc_id());
2548     EventMark em("%s", msg);
2549 
2550     ShenandoahWorkerScope scope(workers(),
2551                                 ShenandoahWorkerPolicy::calc_workers_for_conc_preclean(),
2552                                 "concurrent preclean",
2553                                 /* check_workers = */ false);
2554 
2555     try_inject_alloc_failure();
2556     op_preclean();
2557   }
2558 }
2559 
2560 void ShenandoahHeap::entry_uncommit(double shrink_before) {
2561   static const char *msg = "Concurrent uncommit";
2562   GCTraceTime time(msg, PrintGC, NULL, tracer()->gc_id(), true);
2563   EventMark em("%s", msg);
2564 
2565   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_uncommit);
2566 
2567   op_uncommit(shrink_before);
2568 }
2569 
2570 void ShenandoahHeap::try_inject_alloc_failure() {
2571   if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) {
2572     _inject_alloc_failure.set();
2573     os::naked_short_sleep(1);
2574     if (cancelled_gc()) {
2575       log_info(gc)("Allocation failure was successfully injected");
2576     }
2577   }
2578 }
2579 
2580 bool ShenandoahHeap::should_inject_alloc_failure() {
2581   return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset();
2582 }
2583 
2584 void ShenandoahHeap::enter_evacuation() {
2585   _oom_evac_handler.enter_evacuation();
2586 }
2587 
2588 void ShenandoahHeap::leave_evacuation() {
2589   _oom_evac_handler.leave_evacuation();
2590 }
2591 
2592 ShenandoahRegionIterator::ShenandoahRegionIterator() :
2593   _heap(ShenandoahHeap::heap()),
2594   _index(0) {}
2595 
2596 ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) :
2597   _heap(heap),
2598   _index(0) {}
2599 
2600 void ShenandoahRegionIterator::reset() {
2601   _index = 0;
2602 }
2603 
2604 bool ShenandoahRegionIterator::has_next() const {
2605   return _index < (jint)_heap->num_regions();
2606 }
2607 
2608 char ShenandoahHeap::gc_state() {
2609   return _gc_state.raw_value();
2610 }
2611 
2612 const char* ShenandoahHeap::init_mark_event_message() const {
2613   assert(!has_forwarded_objects(), "Should not have forwarded objects here");
2614 
2615   bool proc_refs = process_references();
2616   bool unload_cls = unload_classes();
2617 
2618   if (proc_refs && unload_cls) {
2619     return "Pause Init Mark (process weakrefs) (unload classes)";
2620   } else if (proc_refs) {
2621     return "Pause Init Mark (process weakrefs)";
2622   } else if (unload_cls) {
2623     return "Pause Init Mark (unload classes)";
2624   } else {
2625     return "Pause Init Mark";
2626   }
2627 }
2628 
2629 const char* ShenandoahHeap::final_mark_event_message() const {
2630   assert(!has_forwarded_objects(), "Should not have forwarded objects here");
2631 
2632   bool proc_refs = process_references();
2633   bool unload_cls = unload_classes();
2634 
2635   if (proc_refs && unload_cls) {
2636     return "Pause Final Mark (process weakrefs) (unload classes)";
2637   } else if (proc_refs) {
2638     return "Pause Final Mark (process weakrefs)";
2639   } else if (unload_cls) {
2640     return "Pause Final Mark (unload classes)";
2641   } else {
2642     return "Pause Final Mark";
2643   }
2644 }
2645 
2646 const char* ShenandoahHeap::conc_mark_event_message() const {
2647   assert(!has_forwarded_objects(), "Should not have forwarded objects here");
2648 
2649   bool proc_refs = process_references();
2650   bool unload_cls = unload_classes();
2651 
2652   if (proc_refs && unload_cls) {
2653     return "Concurrent marking (process weakrefs) (unload classes)";
2654   } else if (proc_refs) {
2655     return "Concurrent marking (process weakrefs)";
2656   } else if (unload_cls) {
2657     return "Concurrent marking (unload classes)";
2658   } else {
2659     return "Concurrent marking";
2660   }
2661 }
2662 
2663 const char* ShenandoahHeap::degen_event_message(ShenandoahDegenPoint point) const {
2664   switch (point) {
2665     case _degenerated_unset:
2666       return "Pause Degenerated GC (<UNSET>)";
2667     case _degenerated_outside_cycle:
2668       return "Pause Degenerated GC (Outside of Cycle)";
2669     case _degenerated_mark:
2670       return "Pause Degenerated GC (Mark)";
2671     case _degenerated_evac:
2672       return "Pause Degenerated GC (Evacuation)";
2673     case _degenerated_updaterefs:
2674       return "Pause Degenerated GC (Update Refs)";
2675     default:
2676       ShouldNotReachHere();
2677       return "ERROR";
2678   }
2679 }
2680 
2681 ShenandoahLiveData* ShenandoahHeap::get_liveness_cache(uint worker_id) {
2682 #ifdef ASSERT
2683   assert(_liveness_cache != NULL, "sanity");
2684   assert(worker_id < _max_workers, "sanity");
2685   for (uint i = 0; i < num_regions(); i++) {
2686     assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty");
2687   }
2688 #endif
2689   return _liveness_cache[worker_id];
2690 }
2691 
2692 void ShenandoahHeap::flush_liveness_cache(uint worker_id) {
2693   assert(worker_id < _max_workers, "sanity");
2694   assert(_liveness_cache != NULL, "sanity");
2695   ShenandoahLiveData* ld = _liveness_cache[worker_id];
2696   for (uint i = 0; i < num_regions(); i++) {
2697     ShenandoahLiveData live = ld[i];
2698     if (live > 0) {
2699       ShenandoahHeapRegion* r = get_region(i);
2700       r->increase_live_data_gc_words(live);
2701       ld[i] = 0;
2702     }
2703   }
2704 }