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