1 /*
   2  * Copyright (c) 2013, 2021, Red Hat, Inc. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "memory/allocation.hpp"
  27 #include "memory/universe.hpp"
  28 
  29 #include "gc/shared/gcArguments.hpp"
  30 #include "gc/shared/gcTimer.hpp"
  31 #include "gc/shared/gcTraceTime.inline.hpp"
  32 #include "gc/shared/locationPrinter.inline.hpp"
  33 #include "gc/shared/memAllocator.hpp"
  34 #include "gc/shared/plab.hpp"
  35 #include "gc/shared/tlab_globals.hpp"
  36 
  37 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
  38 #include "gc/shenandoah/shenandoahCardTable.hpp"
  39 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
  40 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  41 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
  42 #include "gc/shenandoah/shenandoahConcurrentMark.hpp"
  43 #include "gc/shenandoah/shenandoahControlThread.hpp"
  44 #include "gc/shenandoah/shenandoahRegulatorThread.hpp"
  45 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  46 #include "gc/shenandoah/shenandoahGlobalGeneration.hpp"
  47 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  48 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  49 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
  50 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  51 #include "gc/shenandoah/shenandoahInitLogger.hpp"
  52 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  53 #include "gc/shenandoah/shenandoahMemoryPool.hpp"
  54 #include "gc/shenandoah/shenandoahMetrics.hpp"
  55 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
  56 #include "gc/shenandoah/shenandoahOldGeneration.hpp"
  57 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
  58 #include "gc/shenandoah/shenandoahPacer.inline.hpp"
  59 #include "gc/shenandoah/shenandoahPadding.hpp"
  60 #include "gc/shenandoah/shenandoahParallelCleaning.inline.hpp"
  61 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
  62 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
  63 #include "gc/shenandoah/shenandoahScanRemembered.inline.hpp"
  64 #include "gc/shenandoah/shenandoahStringDedup.hpp"
  65 #include "gc/shenandoah/shenandoahSTWMark.hpp"
  66 #include "gc/shenandoah/shenandoahUtils.hpp"
  67 #include "gc/shenandoah/shenandoahVerifier.hpp"
  68 #include "gc/shenandoah/shenandoahCodeRoots.hpp"
  69 #include "gc/shenandoah/shenandoahVMOperations.hpp"
  70 #include "gc/shenandoah/shenandoahWorkGroup.hpp"
  71 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
  72 #include "gc/shenandoah/shenandoahYoungGeneration.hpp"
  73 #include "gc/shenandoah/mode/shenandoahGenerationalMode.hpp"
  74 #include "gc/shenandoah/mode/shenandoahIUMode.hpp"
  75 #include "gc/shenandoah/mode/shenandoahPassiveMode.hpp"
  76 #include "gc/shenandoah/mode/shenandoahSATBMode.hpp"
  77 
  78 #if INCLUDE_JFR
  79 #include "gc/shenandoah/shenandoahJfrSupport.hpp"
  80 #endif
  81 
  82 #include "gc/shenandoah/heuristics/shenandoahOldHeuristics.hpp"
  83 
  84 #include "classfile/systemDictionary.hpp"
  85 #include "memory/classLoaderMetaspace.hpp"
  86 #include "memory/metaspaceUtils.hpp"
  87 #include "oops/compressedOops.inline.hpp"
  88 #include "prims/jvmtiTagMap.hpp"
  89 #include "runtime/atomic.hpp"
  90 #include "runtime/globals.hpp"
  91 #include "runtime/interfaceSupport.inline.hpp"
  92 #include "runtime/java.hpp"
  93 #include "runtime/orderAccess.hpp"
  94 #include "runtime/safepointMechanism.hpp"
  95 #include "runtime/vmThread.hpp"
  96 #include "services/mallocTracker.hpp"
  97 #include "services/memTracker.hpp"
  98 #include "utilities/events.hpp"
  99 #include "utilities/powerOfTwo.hpp"
 100 
 101 class ShenandoahPretouchHeapTask : public WorkerTask {
 102 private:
 103   ShenandoahRegionIterator _regions;
 104   const size_t _page_size;
 105 public:
 106   ShenandoahPretouchHeapTask(size_t page_size) :
 107     WorkerTask("Shenandoah Pretouch Heap"),
 108     _page_size(page_size) {}
 109 
 110   virtual void work(uint worker_id) {
 111     ShenandoahHeapRegion* r = _regions.next();
 112     while (r != NULL) {
 113       if (r->is_committed()) {
 114         os::pretouch_memory(r->bottom(), r->end(), _page_size);
 115       }
 116       r = _regions.next();
 117     }
 118   }
 119 };
 120 
 121 class ShenandoahPretouchBitmapTask : public WorkerTask {
 122 private:
 123   ShenandoahRegionIterator _regions;
 124   char* _bitmap_base;
 125   const size_t _bitmap_size;
 126   const size_t _page_size;
 127 public:
 128   ShenandoahPretouchBitmapTask(char* bitmap_base, size_t bitmap_size, size_t page_size) :
 129     WorkerTask("Shenandoah Pretouch Bitmap"),
 130     _bitmap_base(bitmap_base),
 131     _bitmap_size(bitmap_size),
 132     _page_size(page_size) {}
 133 
 134   virtual void work(uint worker_id) {
 135     ShenandoahHeapRegion* r = _regions.next();
 136     while (r != NULL) {
 137       size_t start = r->index()       * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
 138       size_t end   = (r->index() + 1) * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
 139       assert (end <= _bitmap_size, "end is sane: " SIZE_FORMAT " < " SIZE_FORMAT, end, _bitmap_size);
 140 
 141       if (r->is_committed()) {
 142         os::pretouch_memory(_bitmap_base + start, _bitmap_base + end, _page_size);
 143       }
 144 
 145       r = _regions.next();
 146     }
 147   }
 148 };
 149 
 150 jint ShenandoahHeap::initialize() {
 151   //
 152   // Figure out heap sizing
 153   //
 154 
 155   size_t init_byte_size = InitialHeapSize;
 156   size_t min_byte_size  = MinHeapSize;
 157   size_t max_byte_size  = MaxHeapSize;
 158   size_t heap_alignment = HeapAlignment;
 159 
 160   size_t reg_size_bytes = ShenandoahHeapRegion::region_size_bytes();
 161 
 162   Universe::check_alignment(max_byte_size,  reg_size_bytes, "Shenandoah heap");
 163   Universe::check_alignment(init_byte_size, reg_size_bytes, "Shenandoah heap");
 164 
 165   _num_regions = ShenandoahHeapRegion::region_count();
 166   assert(_num_regions == (max_byte_size / reg_size_bytes),
 167          "Regions should cover entire heap exactly: " SIZE_FORMAT " != " SIZE_FORMAT "/" SIZE_FORMAT,
 168          _num_regions, max_byte_size, reg_size_bytes);
 169 
 170   size_t num_committed_regions = init_byte_size / reg_size_bytes;
 171   num_committed_regions = MIN2(num_committed_regions, _num_regions);
 172   assert(num_committed_regions <= _num_regions, "sanity");
 173   _initial_size = num_committed_regions * reg_size_bytes;
 174 
 175   size_t num_min_regions = min_byte_size / reg_size_bytes;
 176   num_min_regions = MIN2(num_min_regions, _num_regions);
 177   assert(num_min_regions <= _num_regions, "sanity");
 178   _minimum_size = num_min_regions * reg_size_bytes;
 179 
 180   // Default to max heap size.
 181   _soft_max_size = _num_regions * reg_size_bytes;
 182 
 183   _committed = _initial_size;
 184 
 185   // Now we know the number of regions and heap sizes, initialize the heuristics.
 186   initialize_generations();
 187   initialize_heuristics();
 188 
 189   size_t heap_page_size   = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 190   size_t bitmap_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 191   size_t region_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 192 
 193   //
 194   // Reserve and commit memory for heap
 195   //
 196 
 197   ReservedHeapSpace heap_rs = Universe::reserve_heap(max_byte_size, heap_alignment);
 198   initialize_reserved_region(heap_rs);
 199   _heap_region = MemRegion((HeapWord*)heap_rs.base(), heap_rs.size() / HeapWordSize);
 200   _heap_region_special = heap_rs.special();
 201 
 202   assert((((size_t) base()) & ShenandoahHeapRegion::region_size_bytes_mask()) == 0,
 203          "Misaligned heap: " PTR_FORMAT, p2i(base()));
 204 
 205 #if SHENANDOAH_OPTIMIZED_MARKTASK
 206   // The optimized ShenandoahMarkTask takes some bits away from the full object bits.
 207   // Fail if we ever attempt to address more than we can.
 208   if ((uintptr_t)heap_rs.end() >= ShenandoahMarkTask::max_addressable()) {
 209     FormatBuffer<512> buf("Shenandoah reserved [" PTR_FORMAT ", " PTR_FORMAT") for the heap, \n"
 210                           "but max object address is " PTR_FORMAT ". Try to reduce heap size, or try other \n"
 211                           "VM options that allocate heap at lower addresses (HeapBaseMinAddress, AllocateHeapAt, etc).",
 212                 p2i(heap_rs.base()), p2i(heap_rs.end()), ShenandoahMarkTask::max_addressable());
 213     vm_exit_during_initialization("Fatal Error", buf);
 214   }
 215 #endif
 216 
 217   ReservedSpace sh_rs = heap_rs.first_part(max_byte_size);
 218   if (!_heap_region_special) {
 219     os::commit_memory_or_exit(sh_rs.base(), _initial_size, heap_alignment, false,
 220                               "Cannot commit heap memory");
 221   }
 222 
 223   BarrierSet::set_barrier_set(new ShenandoahBarrierSet(this, _heap_region));
 224 
 225   //
 226   // After reserving the Java heap, create the card table, barriers, and workers, in dependency order
 227   //
 228   if (mode()->is_generational()) {
 229     ShenandoahDirectCardMarkRememberedSet *rs;
 230     ShenandoahCardTable* card_table = ShenandoahBarrierSet::barrier_set()->card_table();
 231     size_t card_count = card_table->cards_required(heap_rs.size() / HeapWordSize) - 1;
 232     rs = new ShenandoahDirectCardMarkRememberedSet(ShenandoahBarrierSet::barrier_set()->card_table(), card_count);
 233     _card_scan = new ShenandoahScanRemembered<ShenandoahDirectCardMarkRememberedSet>(rs);
 234   }
 235 
 236   _workers = new ShenandoahWorkerThreads("Shenandoah GC Threads", _max_workers);
 237   if (_workers == NULL) {
 238     vm_exit_during_initialization("Failed necessary allocation.");
 239   } else {
 240     _workers->initialize_workers();
 241   }
 242 
 243   if (ParallelGCThreads > 1) {
 244     _safepoint_workers = new ShenandoahWorkerThreads("Safepoint Cleanup Thread", ParallelGCThreads);
 245     _safepoint_workers->initialize_workers();
 246   }
 247 
 248   //
 249   // Reserve and commit memory for bitmap(s)
 250   //
 251 
 252   _bitmap_size = ShenandoahMarkBitMap::compute_size(heap_rs.size());
 253   _bitmap_size = align_up(_bitmap_size, bitmap_page_size);
 254 
 255   size_t bitmap_bytes_per_region = reg_size_bytes / ShenandoahMarkBitMap::heap_map_factor();
 256 
 257   guarantee(bitmap_bytes_per_region != 0,
 258             "Bitmap bytes per region should not be zero");
 259   guarantee(is_power_of_2(bitmap_bytes_per_region),
 260             "Bitmap bytes per region should be power of two: " SIZE_FORMAT, bitmap_bytes_per_region);
 261 
 262   if (bitmap_page_size > bitmap_bytes_per_region) {
 263     _bitmap_regions_per_slice = bitmap_page_size / bitmap_bytes_per_region;
 264     _bitmap_bytes_per_slice = bitmap_page_size;
 265   } else {
 266     _bitmap_regions_per_slice = 1;
 267     _bitmap_bytes_per_slice = bitmap_bytes_per_region;
 268   }
 269 
 270   guarantee(_bitmap_regions_per_slice >= 1,
 271             "Should have at least one region per slice: " SIZE_FORMAT,
 272             _bitmap_regions_per_slice);
 273 
 274   guarantee(((_bitmap_bytes_per_slice) % bitmap_page_size) == 0,
 275             "Bitmap slices should be page-granular: bps = " SIZE_FORMAT ", page size = " SIZE_FORMAT,
 276             _bitmap_bytes_per_slice, bitmap_page_size);
 277 
 278   ReservedSpace bitmap(_bitmap_size, bitmap_page_size);
 279   MemTracker::record_virtual_memory_type(bitmap.base(), mtGC);
 280   _bitmap_region = MemRegion((HeapWord*) bitmap.base(), bitmap.size() / HeapWordSize);
 281   _bitmap_region_special = bitmap.special();
 282 
 283   size_t bitmap_init_commit = _bitmap_bytes_per_slice *
 284                               align_up(num_committed_regions, _bitmap_regions_per_slice) / _bitmap_regions_per_slice;
 285   bitmap_init_commit = MIN2(_bitmap_size, bitmap_init_commit);
 286   if (!_bitmap_region_special) {
 287     os::commit_memory_or_exit((char *) _bitmap_region.start(), bitmap_init_commit, bitmap_page_size, false,
 288                               "Cannot commit bitmap memory");
 289   }
 290 
 291   _marking_context = new ShenandoahMarkingContext(_heap_region, _bitmap_region, _num_regions);
 292 
 293   if (ShenandoahVerify) {
 294     ReservedSpace verify_bitmap(_bitmap_size, bitmap_page_size);
 295     if (!verify_bitmap.special()) {
 296       os::commit_memory_or_exit(verify_bitmap.base(), verify_bitmap.size(), bitmap_page_size, false,
 297                                 "Cannot commit verification bitmap memory");
 298     }
 299     MemTracker::record_virtual_memory_type(verify_bitmap.base(), mtGC);
 300     MemRegion verify_bitmap_region = MemRegion((HeapWord *) verify_bitmap.base(), verify_bitmap.size() / HeapWordSize);
 301     _verification_bit_map.initialize(_heap_region, verify_bitmap_region);
 302     _verifier = new ShenandoahVerifier(this, &_verification_bit_map);
 303   }
 304 
 305   // Reserve aux bitmap for use in object_iterate(). We don't commit it here.
 306   ReservedSpace aux_bitmap(_bitmap_size, bitmap_page_size);
 307   MemTracker::record_virtual_memory_type(aux_bitmap.base(), mtGC);
 308   _aux_bitmap_region = MemRegion((HeapWord*) aux_bitmap.base(), aux_bitmap.size() / HeapWordSize);
 309   _aux_bitmap_region_special = aux_bitmap.special();
 310   _aux_bit_map.initialize(_heap_region, _aux_bitmap_region);
 311 
 312   //
 313   // Create regions and region sets
 314   //
 315   size_t region_align = align_up(sizeof(ShenandoahHeapRegion), SHENANDOAH_CACHE_LINE_SIZE);
 316   size_t region_storage_size = align_up(region_align * _num_regions, region_page_size);
 317   region_storage_size = align_up(region_storage_size, os::vm_allocation_granularity());
 318 
 319   ReservedSpace region_storage(region_storage_size, region_page_size);
 320   MemTracker::record_virtual_memory_type(region_storage.base(), mtGC);
 321   if (!region_storage.special()) {
 322     os::commit_memory_or_exit(region_storage.base(), region_storage_size, region_page_size, false,
 323                               "Cannot commit region memory");
 324   }
 325 
 326   // Try to fit the collection set bitmap at lower addresses. This optimizes code generation for cset checks.
 327   // Go up until a sensible limit (subject to encoding constraints) and try to reserve the space there.
 328   // If not successful, bite a bullet and allocate at whatever address.
 329   {
 330     size_t cset_align = MAX2<size_t>(os::vm_page_size(), os::vm_allocation_granularity());
 331     size_t cset_size = align_up(((size_t) sh_rs.base() + sh_rs.size()) >> ShenandoahHeapRegion::region_size_bytes_shift(), cset_align);
 332 
 333     uintptr_t min = round_up_power_of_2(cset_align);
 334     uintptr_t max = (1u << 30u);
 335 
 336     for (uintptr_t addr = min; addr <= max; addr <<= 1u) {
 337       char* req_addr = (char*)addr;
 338       assert(is_aligned(req_addr, cset_align), "Should be aligned");
 339       ReservedSpace cset_rs(cset_size, cset_align, os::vm_page_size(), req_addr);
 340       if (cset_rs.is_reserved()) {
 341         assert(cset_rs.base() == req_addr, "Allocated where requested: " PTR_FORMAT ", " PTR_FORMAT, p2i(cset_rs.base()), addr);
 342         _collection_set = new ShenandoahCollectionSet(this, cset_rs, sh_rs.base());
 343         break;
 344       }
 345     }
 346 
 347     if (_collection_set == NULL) {
 348       ReservedSpace cset_rs(cset_size, cset_align, os::vm_page_size());
 349       _collection_set = new ShenandoahCollectionSet(this, cset_rs, sh_rs.base());
 350     }
 351   }
 352 
 353   _regions = NEW_C_HEAP_ARRAY(ShenandoahHeapRegion*, _num_regions, mtGC);
 354   _free_set = new ShenandoahFreeSet(this, _num_regions);
 355 
 356   {
 357     ShenandoahHeapLocker locker(lock());
 358 
 359     for (size_t i = 0; i < _num_regions; i++) {
 360       HeapWord* start = (HeapWord*)sh_rs.base() + ShenandoahHeapRegion::region_size_words() * i;
 361       bool is_committed = i < num_committed_regions;
 362       void* loc = region_storage.base() + i * region_align;
 363 
 364       ShenandoahHeapRegion* r = new (loc) ShenandoahHeapRegion(start, i, is_committed);
 365       assert(is_aligned(r, SHENANDOAH_CACHE_LINE_SIZE), "Sanity");
 366 
 367       _marking_context->initialize_top_at_mark_start(r);
 368       _regions[i] = r;
 369       assert(!collection_set()->is_in(i), "New region should not be in collection set");
 370     }
 371 
 372     // Initialize to complete
 373     _marking_context->mark_complete();
 374 
 375     _free_set->rebuild();
 376   }
 377 
 378   if (AlwaysPreTouch) {
 379     // For NUMA, it is important to pre-touch the storage under bitmaps with worker threads,
 380     // before initialize() below zeroes it with initializing thread. For any given region,
 381     // we touch the region and the corresponding bitmaps from the same thread.
 382     ShenandoahPushWorkerScope scope(workers(), _max_workers, false);
 383 
 384     _pretouch_heap_page_size = heap_page_size;
 385     _pretouch_bitmap_page_size = bitmap_page_size;
 386 
 387 #ifdef LINUX
 388     // UseTransparentHugePages would madvise that backing memory can be coalesced into huge
 389     // pages. But, the kernel needs to know that every small page is used, in order to coalesce
 390     // them into huge one. Therefore, we need to pretouch with smaller pages.
 391     if (UseTransparentHugePages) {
 392       _pretouch_heap_page_size = (size_t)os::vm_page_size();
 393       _pretouch_bitmap_page_size = (size_t)os::vm_page_size();
 394     }
 395 #endif
 396 
 397     // OS memory managers may want to coalesce back-to-back pages. Make their jobs
 398     // simpler by pre-touching continuous spaces (heap and bitmap) separately.
 399 
 400     ShenandoahPretouchBitmapTask bcl(bitmap.base(), _bitmap_size, _pretouch_bitmap_page_size);
 401     _workers->run_task(&bcl);
 402 
 403     ShenandoahPretouchHeapTask hcl(_pretouch_heap_page_size);
 404     _workers->run_task(&hcl);
 405   }
 406 
 407   //
 408   // Initialize the rest of GC subsystems
 409   //
 410 
 411   _liveness_cache = NEW_C_HEAP_ARRAY(ShenandoahLiveData*, _max_workers, mtGC);
 412   for (uint worker = 0; worker < _max_workers; worker++) {
 413     _liveness_cache[worker] = NEW_C_HEAP_ARRAY(ShenandoahLiveData, _num_regions, mtGC);
 414     Copy::fill_to_bytes(_liveness_cache[worker], _num_regions * sizeof(ShenandoahLiveData));
 415   }
 416 
 417   // There should probably be Shenandoah-specific options for these,
 418   // just as there are G1-specific options.
 419   {
 420     ShenandoahSATBMarkQueueSet& satbqs = ShenandoahBarrierSet::satb_mark_queue_set();
 421     satbqs.set_process_completed_buffers_threshold(20); // G1SATBProcessCompletedThreshold
 422     satbqs.set_buffer_enqueue_threshold_percentage(60); // G1SATBBufferEnqueueingThresholdPercent
 423   }
 424 
 425   _monitoring_support = new ShenandoahMonitoringSupport(this);
 426   _phase_timings = new ShenandoahPhaseTimings(max_workers());
 427   ShenandoahCodeRoots::initialize();
 428 
 429   if (ShenandoahPacing) {
 430     _pacer = new ShenandoahPacer(this);
 431     _pacer->setup_for_idle();
 432   } else {
 433     _pacer = NULL;
 434   }
 435 
 436   _control_thread = new ShenandoahControlThread();
 437   _regulator_thread = new ShenandoahRegulatorThread(_control_thread);
 438 
 439   ShenandoahInitLogger::print();
 440 
 441   return JNI_OK;
 442 }
 443 
 444 void ShenandoahHeap::initialize_generations() {
 445   size_t max_capacity_new      = young_generation_capacity(max_capacity());
 446   size_t soft_max_capacity_new = young_generation_capacity(soft_max_capacity());
 447   size_t max_capacity_old      = max_capacity() - max_capacity_new;
 448   size_t soft_max_capacity_old = soft_max_capacity() - soft_max_capacity_new;
 449 
 450   _young_generation = new ShenandoahYoungGeneration(_max_workers, max_capacity_new, soft_max_capacity_new);
 451   _old_generation = new ShenandoahOldGeneration(_max_workers, max_capacity_old, soft_max_capacity_old);
 452   _global_generation = new ShenandoahGlobalGeneration(_max_workers);
 453 }
 454 
 455 void ShenandoahHeap::initialize_heuristics() {
 456   if (ShenandoahGCMode != NULL) {
 457     if (strcmp(ShenandoahGCMode, "satb") == 0) {
 458       _gc_mode = new ShenandoahSATBMode();
 459     } else if (strcmp(ShenandoahGCMode, "iu") == 0) {
 460       _gc_mode = new ShenandoahIUMode();
 461     } else if (strcmp(ShenandoahGCMode, "passive") == 0) {
 462       _gc_mode = new ShenandoahPassiveMode();
 463     } else if (strcmp(ShenandoahGCMode, "generational") == 0) {
 464       _gc_mode = new ShenandoahGenerationalMode();
 465     } else {
 466       vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option");
 467     }
 468   } else {
 469     vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option (null)");
 470   }
 471   _gc_mode->initialize_flags();
 472   if (_gc_mode->is_diagnostic() && !UnlockDiagnosticVMOptions) {
 473     vm_exit_during_initialization(
 474             err_msg("GC mode \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",
 475                     _gc_mode->name()));
 476   }
 477   if (_gc_mode->is_experimental() && !UnlockExperimentalVMOptions) {
 478     vm_exit_during_initialization(
 479             err_msg("GC mode \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",
 480                     _gc_mode->name()));
 481   }
 482 
 483   _global_generation->initialize_heuristics(_gc_mode);
 484   if (mode()->is_generational()) {
 485     _young_generation->initialize_heuristics(_gc_mode);
 486     _old_generation->initialize_heuristics(_gc_mode);
 487 
 488     ShenandoahEvacWaste = ShenandoahGenerationalEvacWaste;
 489   }
 490 }
 491 
 492 #ifdef _MSC_VER
 493 #pragma warning( push )
 494 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
 495 #endif
 496 
 497 ShenandoahHeap::ShenandoahHeap(ShenandoahCollectorPolicy* policy) :
 498   CollectedHeap(),
 499   _gc_generation(NULL),
 500   _prep_for_mixed_evac_in_progress(false),
 501   _initial_size(0),
 502   _used(0),
 503   _committed(0),
 504   _max_workers(MAX3(ConcGCThreads, ParallelGCThreads, 1U)),
 505   _workers(NULL),
 506   _safepoint_workers(NULL),
 507   _heap_region_special(false),
 508   _num_regions(0),
 509   _regions(NULL),
 510   _update_refs_iterator(this),
 511   _alloc_supplement_reserve(0),
 512   _promotion_reserve(0),
 513   _old_evac_reserve(0),
 514   _old_evac_expended(0),
 515   _young_evac_reserve(0),
 516   _captured_old_usage(0),
 517   _previous_promotion(0),
 518   _cancel_requested_time(0),
 519   _young_generation(NULL),
 520   _global_generation(NULL),
 521   _old_generation(NULL),
 522   _control_thread(NULL),
 523   _regulator_thread(NULL),
 524   _shenandoah_policy(policy),
 525   _free_set(NULL),
 526   _pacer(NULL),
 527   _verifier(NULL),
 528   _phase_timings(NULL),
 529   _monitoring_support(NULL),
 530   _memory_pool(NULL),
 531   _young_gen_memory_pool(NULL),
 532   _old_gen_memory_pool(NULL),
 533   _stw_memory_manager("Shenandoah Pauses", "end of GC pause"),
 534   _cycle_memory_manager("Shenandoah Cycles", "end of GC cycle"),
 535   _gc_timer(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
 536   _soft_ref_policy(),
 537   _log_min_obj_alignment_in_bytes(LogMinObjAlignmentInBytes),
 538   _marking_context(NULL),
 539   _bitmap_size(0),
 540   _bitmap_regions_per_slice(0),
 541   _bitmap_bytes_per_slice(0),
 542   _bitmap_region_special(false),
 543   _aux_bitmap_region_special(false),
 544   _liveness_cache(NULL),
 545   _collection_set(NULL),
 546   _card_scan(NULL)
 547 {
 548 }
 549 
 550 #ifdef _MSC_VER
 551 #pragma warning( pop )
 552 #endif
 553 
 554 void ShenandoahHeap::print_on(outputStream* st) const {
 555   st->print_cr("Shenandoah Heap");
 556   st->print_cr(" " SIZE_FORMAT "%s max, " SIZE_FORMAT "%s soft max, " SIZE_FORMAT "%s committed, " SIZE_FORMAT "%s used",
 557                byte_size_in_proper_unit(max_capacity()), proper_unit_for_byte_size(max_capacity()),
 558                byte_size_in_proper_unit(soft_max_capacity()), proper_unit_for_byte_size(soft_max_capacity()),
 559                byte_size_in_proper_unit(committed()),    proper_unit_for_byte_size(committed()),
 560                byte_size_in_proper_unit(used()),         proper_unit_for_byte_size(used()));
 561   st->print_cr(" " SIZE_FORMAT " x " SIZE_FORMAT"%s regions",
 562                num_regions(),
 563                byte_size_in_proper_unit(ShenandoahHeapRegion::region_size_bytes()),
 564                proper_unit_for_byte_size(ShenandoahHeapRegion::region_size_bytes()));
 565 
 566   st->print("Status: ");
 567   if (has_forwarded_objects())                 st->print("has forwarded objects, ");
 568   if (is_concurrent_old_mark_in_progress())    st->print("old marking, ");
 569   if (is_concurrent_young_mark_in_progress())  st->print("young marking, ");
 570   if (is_evacuation_in_progress())             st->print("evacuating, ");
 571   if (is_update_refs_in_progress())            st->print("updating refs, ");
 572   if (is_degenerated_gc_in_progress())         st->print("degenerated gc, ");
 573   if (is_full_gc_in_progress())                st->print("full gc, ");
 574   if (is_full_gc_move_in_progress())           st->print("full gc move, ");
 575   if (is_concurrent_weak_root_in_progress())   st->print("concurrent weak roots, ");
 576   if (is_concurrent_strong_root_in_progress() &&
 577       !is_concurrent_weak_root_in_progress())  st->print("concurrent strong roots, ");
 578 
 579   if (cancelled_gc()) {
 580     st->print("cancelled");
 581   } else {
 582     st->print("not cancelled");
 583   }
 584   st->cr();
 585 
 586   st->print_cr("Reserved region:");
 587   st->print_cr(" - [" PTR_FORMAT ", " PTR_FORMAT ") ",
 588                p2i(reserved_region().start()),
 589                p2i(reserved_region().end()));
 590 
 591   ShenandoahCollectionSet* cset = collection_set();
 592   st->print_cr("Collection set:");
 593   if (cset != NULL) {
 594     st->print_cr(" - map (vanilla): " PTR_FORMAT, p2i(cset->map_address()));
 595     st->print_cr(" - map (biased):  " PTR_FORMAT, p2i(cset->biased_map_address()));
 596   } else {
 597     st->print_cr(" (NULL)");
 598   }
 599 
 600   st->cr();
 601   MetaspaceUtils::print_on(st);
 602 
 603   if (Verbose) {
 604     print_heap_regions_on(st);
 605   }
 606 }
 607 
 608 class ShenandoahInitWorkerGCLABClosure : public ThreadClosure {
 609 public:
 610   void do_thread(Thread* thread) {
 611     assert(thread != NULL, "Sanity");
 612     assert(thread->is_Worker_thread(), "Only worker thread expected");
 613     ShenandoahThreadLocalData::initialize_gclab(thread);
 614   }
 615 };
 616 
 617 void ShenandoahHeap::post_initialize() {
 618   CollectedHeap::post_initialize();
 619   MutexLocker ml(Threads_lock);
 620 
 621   ShenandoahInitWorkerGCLABClosure init_gclabs;
 622   _workers->threads_do(&init_gclabs);
 623 
 624   // gclab can not be initialized early during VM startup, as it can not determinate its max_size.
 625   // Now, we will let WorkerThreads to initialize gclab when new worker is created.
 626   _workers->set_initialize_gclab();
 627   if (_safepoint_workers != NULL) {
 628     _safepoint_workers->threads_do(&init_gclabs);
 629     _safepoint_workers->set_initialize_gclab();
 630   }
 631 
 632   JFR_ONLY(ShenandoahJFRSupport::register_jfr_type_serializers());
 633 }
 634 
 635 
 636 ShenandoahOldHeuristics* ShenandoahHeap::old_heuristics() {
 637   return (ShenandoahOldHeuristics*) _old_generation->heuristics();
 638 }
 639 
 640 bool ShenandoahHeap::doing_mixed_evacuations() {
 641   return old_heuristics()->unprocessed_old_collection_candidates() > 0;
 642 }
 643 
 644 bool ShenandoahHeap::is_gc_generation_young() const {
 645   return _gc_generation != NULL && _gc_generation->generation_mode() == YOUNG;
 646 }
 647 
 648 // There are three JVM parameters for setting young gen capacity:
 649 //    NewSize, MaxNewSize, NewRatio.
 650 //
 651 // If only NewSize is set, it assigns a fixed size and the other two parameters are ignored.
 652 // Otherwise NewRatio applies.
 653 //
 654 // If NewSize is set in any combination, it provides a lower bound.
 655 //
 656 // If MaxNewSize is set it provides an upper bound.
 657 // If this bound is smaller than NewSize, it supersedes,
 658 // resulting in a fixed size given by MaxNewSize.
 659 size_t ShenandoahHeap::young_generation_capacity(size_t capacity) {
 660   if (FLAG_IS_CMDLINE(NewSize) && !FLAG_IS_CMDLINE(MaxNewSize) && !FLAG_IS_CMDLINE(NewRatio)) {
 661     capacity = MIN2(NewSize, capacity);
 662   } else {
 663     capacity /= NewRatio + 1;
 664     if (FLAG_IS_CMDLINE(NewSize)) {
 665       capacity = MAX2(NewSize, capacity);
 666     }
 667     if (FLAG_IS_CMDLINE(MaxNewSize)) {
 668       capacity = MIN2(MaxNewSize, capacity);
 669     }
 670   }
 671   return capacity;
 672 }
 673 
 674 size_t ShenandoahHeap::used() const {
 675   return Atomic::load(&_used);
 676 }
 677 
 678 size_t ShenandoahHeap::committed() const {
 679   return Atomic::load(&_committed);
 680 }
 681 
 682 void ShenandoahHeap::increase_committed(size_t bytes) {
 683   shenandoah_assert_heaplocked_or_safepoint();
 684   _committed += bytes;
 685 }
 686 
 687 void ShenandoahHeap::decrease_committed(size_t bytes) {
 688   shenandoah_assert_heaplocked_or_safepoint();
 689   _committed -= bytes;
 690 }
 691 
 692 void ShenandoahHeap::increase_used(size_t bytes) {
 693   Atomic::add(&_used, bytes, memory_order_relaxed);
 694 }
 695 
 696 void ShenandoahHeap::set_used(size_t bytes) {
 697   Atomic::store(&_used, bytes);
 698 }
 699 
 700 void ShenandoahHeap::decrease_used(size_t bytes) {
 701   assert(used() >= bytes, "never decrease heap size by more than we've left");
 702   Atomic::sub(&_used, bytes, memory_order_relaxed);
 703 }
 704 
 705 void ShenandoahHeap::notify_mutator_alloc_words(size_t words, bool waste) {
 706   size_t bytes = words * HeapWordSize;
 707   if (!waste) {
 708     increase_used(bytes);
 709   }
 710 
 711   if (ShenandoahPacing) {
 712     control_thread()->pacing_notify_alloc(words);
 713     if (waste) {
 714       pacer()->claim_for_alloc(words, true);
 715     }
 716   }
 717 }
 718 
 719 size_t ShenandoahHeap::capacity() const {
 720   return committed();
 721 }
 722 
 723 size_t ShenandoahHeap::max_capacity() const {
 724   return _num_regions * ShenandoahHeapRegion::region_size_bytes();
 725 }
 726 
 727 size_t ShenandoahHeap::soft_max_capacity() const {
 728   size_t v = Atomic::load(&_soft_max_size);
 729   assert(min_capacity() <= v && v <= max_capacity(),
 730          "Should be in bounds: " SIZE_FORMAT " <= " SIZE_FORMAT " <= " SIZE_FORMAT,
 731          min_capacity(), v, max_capacity());
 732   return v;
 733 }
 734 
 735 void ShenandoahHeap::set_soft_max_capacity(size_t v) {
 736   assert(min_capacity() <= v && v <= max_capacity(),
 737          "Should be in bounds: " SIZE_FORMAT " <= " SIZE_FORMAT " <= " SIZE_FORMAT,
 738          min_capacity(), v, max_capacity());
 739   Atomic::store(&_soft_max_size, v);
 740 
 741   if (mode()->is_generational()) {
 742     size_t soft_max_capacity_young = young_generation_capacity(_soft_max_size);
 743     size_t soft_max_capacity_old = _soft_max_size - soft_max_capacity_young;
 744     _young_generation->set_soft_max_capacity(soft_max_capacity_young);
 745     _old_generation->set_soft_max_capacity(soft_max_capacity_old);
 746   }
 747 }
 748 
 749 size_t ShenandoahHeap::min_capacity() const {
 750   return _minimum_size;
 751 }
 752 
 753 size_t ShenandoahHeap::initial_capacity() const {
 754   return _initial_size;
 755 }
 756 
 757 bool ShenandoahHeap::is_in(const void* p) const {
 758   HeapWord* heap_base = (HeapWord*) base();
 759   HeapWord* last_region_end = heap_base + ShenandoahHeapRegion::region_size_words() * num_regions();
 760   return p >= heap_base && p < last_region_end;
 761 }
 762 
 763 bool ShenandoahHeap::is_in_young(const void* p) const {
 764   return is_in(p) && heap_region_containing(p)->affiliation() == ShenandoahRegionAffiliation::YOUNG_GENERATION;
 765 }
 766 
 767 bool ShenandoahHeap::is_in_old(const void* p) const {
 768   return is_in(p) && heap_region_containing(p)->affiliation() == ShenandoahRegionAffiliation::OLD_GENERATION;
 769 }
 770 
 771 bool ShenandoahHeap::is_in_active_generation(oop obj) const {
 772   if (!mode()->is_generational()) {
 773     // everything is the same single generation
 774     return true;
 775   }
 776 
 777   if (active_generation() == NULL) {
 778     // no collection is happening, only expect this to be called
 779     // when concurrent processing is active, but that could change
 780     return false;
 781   }
 782 
 783   return active_generation()->contains(obj);
 784 }
 785 
 786 void ShenandoahHeap::op_uncommit(double shrink_before, size_t shrink_until) {
 787   assert (ShenandoahUncommit, "should be enabled");
 788 
 789   // Application allocates from the beginning of the heap, and GC allocates at
 790   // the end of it. It is more efficient to uncommit from the end, so that applications
 791   // could enjoy the near committed regions. GC allocations are much less frequent,
 792   // and therefore can accept the committing costs.
 793 
 794   size_t count = 0;
 795   for (size_t i = num_regions(); i > 0; i--) { // care about size_t underflow
 796     ShenandoahHeapRegion* r = get_region(i - 1);
 797     if (r->is_empty_committed() && (r->empty_time() < shrink_before)) {
 798       ShenandoahHeapLocker locker(lock());
 799       if (r->is_empty_committed()) {
 800         if (committed() < shrink_until + ShenandoahHeapRegion::region_size_bytes()) {
 801           break;
 802         }
 803 
 804         r->make_uncommitted();
 805         count++;
 806       }
 807     }
 808     SpinPause(); // allow allocators to take the lock
 809   }
 810 
 811   if (count > 0) {
 812     control_thread()->notify_heap_changed();
 813     regulator_thread()->notify_heap_changed();
 814   }
 815 }
 816 
 817 void ShenandoahHeap::handle_old_evacuation(HeapWord* obj, size_t words, bool promotion) {
 818   // Only register the copy of the object that won the evacuation race.
 819   card_scan()->register_object_wo_lock(obj);
 820 
 821   // Mark the entire range of the evacuated object as dirty.  At next remembered set scan,
 822   // we will clear dirty bits that do not hold interesting pointers.  It's more efficient to
 823   // do this in batch, in a background GC thread than to try to carefully dirty only cards
 824   // that hold interesting pointers right now.
 825   card_scan()->mark_range_as_dirty(obj, words);
 826 
 827   if (promotion) {
 828     // This evacuation was a promotion, track this as allocation against old gen
 829     old_generation()->increase_allocated(words * HeapWordSize);
 830   }
 831 }
 832 
 833 void ShenandoahHeap::handle_old_evacuation_failure() {
 834   if (_old_gen_oom_evac.try_set()) {
 835     log_info(gc)("Old gen evac failure.");
 836   }
 837 }
 838 
 839 void ShenandoahHeap::handle_promotion_failure() {
 840   old_heuristics()->handle_promotion_failure();
 841 }
 842 
 843 HeapWord* ShenandoahHeap::allocate_from_gclab_slow(Thread* thread, size_t size) {
 844   // New object should fit the GCLAB size
 845   size_t min_size = MAX2(size, PLAB::min_size());
 846 
 847   // Figure out size of new GCLAB, looking back at heuristics. Expand aggressively.
 848   size_t new_size = ShenandoahThreadLocalData::gclab_size(thread) * 2;
 849 
 850   // Limit growth of GCLABs to ShenandoahMaxEvacLABRatio * the minimum size.  This enables more equitable distribution of
 851   // available evacuation buidget between the many threads that are coordinating in the evacuation effort.
 852   if (ShenandoahMaxEvacLABRatio > 0) {
 853     new_size = MIN2(new_size, PLAB::min_size() * ShenandoahMaxEvacLABRatio);
 854   }
 855   new_size = MIN2(new_size, PLAB::max_size());
 856   new_size = MAX2(new_size, PLAB::min_size());
 857 
 858   // Record new heuristic value even if we take any shortcut. This captures
 859   // the case when moderately-sized objects always take a shortcut. At some point,
 860   // heuristics should catch up with them.
 861   ShenandoahThreadLocalData::set_gclab_size(thread, new_size);
 862 
 863   if (new_size < size) {
 864     // New size still does not fit the object. Fall back to shared allocation.
 865     // This avoids retiring perfectly good GCLABs, when we encounter a large object.
 866     return NULL;
 867   }
 868 
 869   // Retire current GCLAB, and allocate a new one.
 870   PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
 871   gclab->retire();
 872 
 873   size_t actual_size = 0;
 874   HeapWord* gclab_buf = allocate_new_gclab(min_size, new_size, &actual_size);
 875   if (gclab_buf == NULL) {
 876     return NULL;
 877   }
 878 
 879   assert (size <= actual_size, "allocation should fit");
 880 
 881   if (ZeroTLAB) {
 882     // ..and clear it.
 883     Copy::zero_to_words(gclab_buf, actual_size);
 884   } else {
 885     // ...and zap just allocated object.
 886 #ifdef ASSERT
 887     // Skip mangling the space corresponding to the object header to
 888     // ensure that the returned space is not considered parsable by
 889     // any concurrent GC thread.
 890     size_t hdr_size = oopDesc::header_size();
 891     Copy::fill_to_words(gclab_buf + hdr_size, actual_size - hdr_size, badHeapWordVal);
 892 #endif // ASSERT
 893   }
 894   gclab->set_buf(gclab_buf, actual_size);
 895   return gclab->allocate(size);
 896 }
 897 
 898 // Establish a new PLAB and allocate size HeapWords within it.
 899 HeapWord* ShenandoahHeap::allocate_from_plab_slow(Thread* thread, size_t size, bool is_promotion) {
 900   // New object should fit the PLAB size
 901   size_t min_size = MAX2(size, PLAB::min_size());
 902 
 903   // Figure out size of new PLAB, looking back at heuristics. Expand aggressively.
 904   size_t new_size = ShenandoahThreadLocalData::plab_size(thread) * 2;
 905   // Limit growth of PLABs to ShenandoahMaxEvacLABRatio * the minimum size.  This enables more equitable distribution of
 906   // available evacuation buidget between the many threads that are coordinating in the evacuation effort.
 907   if (ShenandoahMaxEvacLABRatio > 0) {
 908     new_size = MIN2(new_size, PLAB::min_size() * ShenandoahMaxEvacLABRatio);
 909   }
 910   new_size = MIN2(new_size, PLAB::max_size());
 911   new_size = MAX2(new_size, PLAB::min_size());
 912 
 913   size_t unalignment = new_size % CardTable::card_size_in_words();
 914   if (unalignment != 0) {
 915     new_size = new_size - unalignment + CardTable::card_size_in_words();
 916   }
 917 
 918   // Record new heuristic value even if we take any shortcut. This captures
 919   // the case when moderately-sized objects always take a shortcut. At some point,
 920   // heuristics should catch up with them.  Note that the requested new_size may
 921   // not be honored, but we remember that this is the preferred size.
 922   ShenandoahThreadLocalData::set_plab_size(thread, new_size);
 923 
 924   if (new_size < size) {
 925     // New size still does not fit the object. Fall back to shared allocation.
 926     // This avoids retiring perfectly good PLABs, when we encounter a large object.
 927     return NULL;
 928   }
 929 
 930   // Retire current PLAB, and allocate a new one.
 931   PLAB* plab = ShenandoahThreadLocalData::plab(thread);
 932   // CAUTION: retire_plab may register the remnant filler object with the remembered set scanner without a lock.  This
 933   // is safe iff it is assured that each PLAB is a whole-number multiple of card-mark memory size and each PLAB is
 934   // aligned with the start of a card's memory range.
 935   retire_plab(plab);
 936 
 937   size_t actual_size = 0;
 938   // allocate_new_plab resets plab_evacuated and plab_promoted and disables promotions if old-gen available is
 939   // less than the remaining evacuation need.
 940   HeapWord* plab_buf = allocate_new_plab(min_size, new_size, &actual_size);
 941   if (plab_buf == NULL) {
 942     return NULL;
 943   }
 944 
 945   assert (size <= actual_size, "allocation should fit");
 946 
 947   if (ZeroTLAB) {
 948     // ..and clear it.
 949     Copy::zero_to_words(plab_buf, actual_size);
 950   } else {
 951     // ...and zap just allocated object.
 952 #ifdef ASSERT
 953     // Skip mangling the space corresponding to the object header to
 954     // ensure that the returned space is not considered parsable by
 955     // any concurrent GC thread.
 956     size_t hdr_size = oopDesc::header_size();
 957     Copy::fill_to_words(plab_buf + hdr_size, actual_size - hdr_size, badHeapWordVal);
 958 #endif // ASSERT
 959   }
 960   plab->set_buf(plab_buf, actual_size);
 961 
 962   if (is_promotion && !ShenandoahThreadLocalData::allow_plab_promotions(thread)) {
 963     return nullptr;
 964   }
 965   return plab->allocate(size);
 966 }
 967 
 968 // TODO: It is probably most efficient to register all objects (both promotions and evacuations) that were allocated within
 969 // this plab at the time we retire the plab.  A tight registration loop will run within both code and data caches.  This change
 970 // would allow smaller and faster in-line implementation of alloc_from_plab().  Since plabs are aligned on card-table boundaries,
 971 // this object registration loop can be performed without acquiring a lock.
 972 void ShenandoahHeap::retire_plab(PLAB* plab) {
 973   if (!mode()->is_generational()) {
 974     plab->retire();
 975   } else {
 976     Thread* thread = Thread::current();
 977     size_t evacuated = ShenandoahThreadLocalData::get_plab_evacuated(thread);
 978     // We don't enforce limits on get_plab_promoted(thread).  Promotion uses any memory not required for evacuation.
 979     expend_old_evac(evacuated);
 980     size_t waste = plab->waste();
 981     HeapWord* top = plab->top();
 982     plab->retire();
 983     if (top != NULL && plab->waste() > waste && is_in_old(top)) {
 984       // If retiring the plab created a filler object, then we
 985       // need to register it with our card scanner so it can
 986       // safely walk the region backing the plab.
 987       log_debug(gc)("retire_plab() is registering remnant of size " SIZE_FORMAT " at " PTR_FORMAT,
 988                     plab->waste() - waste, p2i(top));
 989       card_scan()->register_object_wo_lock(top);
 990     }
 991   }
 992 }
 993 
 994 void ShenandoahHeap::cancel_old_gc() {
 995   shenandoah_assert_safepoint();
 996   assert(_old_generation != NULL, "Should only have mixed collections in generation mode.");
 997   log_info(gc)("Terminating old gc cycle.");
 998 
 999   // Stop marking
1000   old_generation()->cancel_marking();
1001   // Stop coalescing undead objects
1002   set_concurrent_prep_for_mixed_evacuation_in_progress(false);
1003   // Stop tracking old regions
1004   old_heuristics()->abandon_collection_candidates();
1005   // Remove old generation access to young generation mark queues
1006   young_generation()->set_old_gen_task_queues(nullptr);
1007 }
1008 
1009 bool ShenandoahHeap::is_old_gc_active() {
1010   return is_concurrent_old_mark_in_progress()
1011       || is_concurrent_prep_for_mixed_evacuation_in_progress()
1012       || old_heuristics()->unprocessed_old_or_hidden_collection_candidates() > 0
1013       || young_generation()->old_gen_task_queues() != nullptr;
1014 }
1015 
1016 void ShenandoahHeap::coalesce_and_fill_old_regions() {
1017   class ShenandoahGlobalCoalesceAndFill : public ShenandoahHeapRegionClosure {
1018    public:
1019     virtual void heap_region_do(ShenandoahHeapRegion* region) override {
1020       // old region is not in the collection set and was not immediately trashed
1021       if (region->is_old() && region->is_active() && !region->is_humongous()) {
1022         // Reset the coalesce and fill boundary because this is a global collect
1023         // and cannot be preempted by young collects. We want to be sure the entire
1024         // region is coalesced here and does not resume from a previously interrupted
1025         // or completed coalescing.
1026         region->begin_preemptible_coalesce_and_fill();
1027         region->oop_fill_and_coalesce();
1028       }
1029     }
1030 
1031     virtual bool is_thread_safe() override {
1032       return true;
1033     }
1034   };
1035   ShenandoahGlobalCoalesceAndFill coalesce;
1036   parallel_heap_region_iterate(&coalesce);
1037 }
1038 
1039 HeapWord* ShenandoahHeap::allocate_new_tlab(size_t min_size,
1040                                             size_t requested_size,
1041                                             size_t* actual_size) {
1042   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_tlab(min_size, requested_size);
1043   HeapWord* res = allocate_memory(req, false);
1044   if (res != NULL) {
1045     *actual_size = req.actual_size();
1046   } else {
1047     *actual_size = 0;
1048   }
1049   return res;
1050 }
1051 
1052 HeapWord* ShenandoahHeap::allocate_new_gclab(size_t min_size,
1053                                              size_t word_size,
1054                                              size_t* actual_size) {
1055   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_gclab(min_size, word_size);
1056   HeapWord* res = allocate_memory(req, false);
1057   if (res != NULL) {
1058     *actual_size = req.actual_size();
1059   } else {
1060     *actual_size = 0;
1061   }
1062   return res;
1063 }
1064 
1065 HeapWord* ShenandoahHeap::allocate_new_plab(size_t min_size,
1066                                             size_t word_size,
1067                                             size_t* actual_size) {
1068   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_plab(min_size, word_size);
1069   // Note that allocate_memory() sets a thread-local flag to prohibit further promotions by this thread
1070   // if we are at risk of exceeding the old-gen evacuation budget.
1071   HeapWord* res = allocate_memory(req, false);
1072   if (res != NULL) {
1073     *actual_size = req.actual_size();
1074   } else {
1075     *actual_size = 0;
1076   }
1077   return res;
1078 }
1079 
1080 // is_promotion is true iff this allocation is known for sure to hold the result of young-gen evacuation
1081 // to old-gen.  plab allocates arre not known as such, since they may hold old-gen evacuations.
1082 HeapWord* ShenandoahHeap::allocate_memory(ShenandoahAllocRequest& req, bool is_promotion) {
1083   intptr_t pacer_epoch = 0;
1084   bool in_new_region = false;
1085   HeapWord* result = NULL;
1086 
1087   if (req.is_mutator_alloc()) {
1088     if (ShenandoahPacing) {
1089       pacer()->pace_for_alloc(req.size());
1090       pacer_epoch = pacer()->epoch();
1091     }
1092 
1093     if (!ShenandoahAllocFailureALot || !should_inject_alloc_failure()) {
1094       result = allocate_memory_under_lock(req, in_new_region, is_promotion);
1095     }
1096 
1097     // Allocation failed, block until control thread reacted, then retry allocation.
1098     //
1099     // It might happen that one of the threads requesting allocation would unblock
1100     // way later after GC happened, only to fail the second allocation, because
1101     // other threads have already depleted the free storage. In this case, a better
1102     // strategy is to try again, as long as GC makes progress.
1103     //
1104     // Then, we need to make sure the allocation was retried after at least one
1105     // Full GC, which means we want to try more than ShenandoahFullGCThreshold times.
1106 
1107     size_t tries = 0;
1108 
1109     while (result == NULL && _progress_last_gc.is_set()) {
1110       tries++;
1111       control_thread()->handle_alloc_failure(req);
1112       result = allocate_memory_under_lock(req, in_new_region, is_promotion);
1113     }
1114 
1115     while (result == NULL && tries <= ShenandoahFullGCThreshold) {
1116       tries++;
1117       control_thread()->handle_alloc_failure(req);
1118       result = allocate_memory_under_lock(req, in_new_region, is_promotion);
1119     }
1120 
1121   } else {
1122     assert(req.is_gc_alloc(), "Can only accept GC allocs here");
1123     result = allocate_memory_under_lock(req, in_new_region, is_promotion);
1124     // Do not call handle_alloc_failure() here, because we cannot block.
1125     // The allocation failure would be handled by the LRB slowpath with handle_alloc_failure_evac().
1126   }
1127 
1128   if (in_new_region) {
1129     control_thread()->notify_heap_changed();
1130     regulator_thread()->notify_heap_changed();
1131   }
1132 
1133   if (result != NULL) {
1134     ShenandoahGeneration* alloc_generation = generation_for(req.affiliation());
1135     size_t requested = req.size();
1136     size_t actual = req.actual_size();
1137     size_t actual_bytes = actual * HeapWordSize;
1138 
1139     assert (req.is_lab_alloc() || (requested == actual),
1140             "Only LAB allocations are elastic: %s, requested = " SIZE_FORMAT ", actual = " SIZE_FORMAT,
1141             ShenandoahAllocRequest::alloc_type_to_string(req.type()), requested, actual);
1142 
1143     if (req.is_mutator_alloc()) {
1144       notify_mutator_alloc_words(actual, false);
1145       alloc_generation->increase_allocated(actual_bytes);
1146 
1147       // If we requested more than we were granted, give the rest back to pacer.
1148       // This only matters if we are in the same pacing epoch: do not try to unpace
1149       // over the budget for the other phase.
1150       if (ShenandoahPacing && (pacer_epoch > 0) && (requested > actual)) {
1151         pacer()->unpace_for_alloc(pacer_epoch, requested - actual);
1152       }
1153     } else {
1154       increase_used(actual_bytes);
1155     }
1156   }
1157 
1158   return result;
1159 }
1160 
1161 HeapWord* ShenandoahHeap::allocate_memory_under_lock(ShenandoahAllocRequest& req, bool& in_new_region, bool is_promotion) {
1162   size_t requested_bytes = req.size() * HeapWordSize;
1163 
1164   ShenandoahHeapLocker locker(lock());
1165   if (mode()->is_generational()) {
1166     if (req.affiliation() == YOUNG_GENERATION) {
1167       if (req.is_mutator_alloc()) {
1168         if (requested_bytes >= young_generation()->adjusted_available()) {
1169           // We know this is not a GCLAB.  This must be a TLAB or a shared allocation.  Reject the allocation request if
1170           // exceeds established capacity limits.
1171           return nullptr;
1172         }
1173       }
1174     } else {                    // reg.affiliation() == OLD_GENERATION
1175       assert(req.type() != ShenandoahAllocRequest::_alloc_gclab, "GCLAB pertains only to young-gen memory");
1176 
1177       if (req.type() ==  ShenandoahAllocRequest::_alloc_plab) {
1178         // We've already retired this thread's previously exhausted PLAB and have accounted for how that PLAB's
1179         // memory was allotted.
1180         Thread* thread = Thread::current();
1181         ShenandoahThreadLocalData::reset_plab_evacuated(thread);
1182         ShenandoahThreadLocalData::reset_plab_promoted(thread);
1183 
1184         // Conservatively, assume this entire PLAB will be used for promotion.  Act as if we need to serve the
1185         // rest of evacuation need from as-yet unallocated old-gen memory.
1186         size_t remaining_evac_need = get_old_evac_reserve() - get_old_evac_expended();
1187         size_t evac_available = old_generation()->adjusted_available() - requested_bytes;
1188         if (remaining_evac_need >= evac_available) {
1189           // Disable promotions within this thread because the entirety of this PLAB must be available to hold
1190           // old-gen evacuations.
1191           ShenandoahThreadLocalData::disable_plab_promotions(thread);
1192         } else {
1193           ShenandoahThreadLocalData::enable_plab_promotions(thread);
1194         }
1195       } else if (is_promotion) {
1196         // This is a shared alloc for promotion
1197         Thread* thread = Thread::current();
1198         size_t remaining_evac_need = get_old_evac_reserve() - get_old_evac_expended();
1199         size_t evac_available = old_generation()->adjusted_available() - requested_bytes;
1200         if (remaining_evac_need >= evac_available) {
1201           return nullptr;       // We need to reserve the remaining memory for evacuation so defer the promotion
1202         }
1203         // Else, we'll allow the allocation to proceed.  (Since we hold heap lock, the tested condition remains true.)
1204       } else {
1205         // This is a shared allocation for evacuation.  Memory has already been reserved for this purpose.
1206       }
1207     }
1208   }
1209 
1210   HeapWord* result = _free_set->allocate(req, in_new_region);
1211   if (result != NULL) {
1212     if (req.affiliation() == ShenandoahRegionAffiliation::OLD_GENERATION) {
1213       // Register the newly allocated object while we're holding the global lock since there's no synchronization
1214       // built in to the implementation of register_object().  There are potential races when multiple independent
1215       // threads are allocating objects, some of which might span the same card region.  For example, consider
1216       // a card table's memory region within which three objects are being allocated by three different threads:
1217       //
1218       // objects being "concurrently" allocated:
1219       //    [-----a------][-----b-----][--------------c------------------]
1220       //            [---- card table memory range --------------]
1221       //
1222       // Before any objects are allocated, this card's memory range holds no objects.  Note that:
1223       //   allocation of object a wants to set the has-object, first-start, and last-start attributes of the preceding card region.
1224       //   allocation of object b wants to set the has-object, first-start, and last-start attributes of this card region.
1225       //   allocation of object c also wants to set the has-object, first-start, and last-start attributes of this card region.
1226       //
1227       // The thread allocating b and the thread allocating c can "race" in various ways, resulting in confusion, such as last-start
1228       // representing object b while first-start represents object c.  This is why we need to require all register_object()
1229       // invocations to be "mutually exclusive" with respect to each card's memory range.
1230       ShenandoahHeap::heap()->card_scan()->register_object(result);
1231     }
1232   }
1233   return result;
1234 }
1235 
1236 HeapWord* ShenandoahHeap::mem_allocate(size_t size,
1237                                         bool*  gc_overhead_limit_was_exceeded) {
1238   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared(size);
1239   return allocate_memory(req, false);
1240 }
1241 
1242 MetaWord* ShenandoahHeap::satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,
1243                                                              size_t size,
1244                                                              Metaspace::MetadataType mdtype) {
1245   MetaWord* result;
1246 
1247   // Inform metaspace OOM to GC heuristics if class unloading is possible.
1248   ShenandoahHeuristics* h = global_generation()->heuristics();
1249   if (h->can_unload_classes()) {
1250     h->record_metaspace_oom();
1251   }
1252 
1253   // Expand and retry allocation
1254   result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
1255   if (result != NULL) {
1256     return result;
1257   }
1258 
1259   // Start full GC
1260   collect(GCCause::_metadata_GC_clear_soft_refs);
1261 
1262   // Retry allocation
1263   result = loader_data->metaspace_non_null()->allocate(size, mdtype);
1264   if (result != NULL) {
1265     return result;
1266   }
1267 
1268   // Expand and retry allocation
1269   result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
1270   if (result != NULL) {
1271     return result;
1272   }
1273 
1274   // Out of memory
1275   return NULL;
1276 }
1277 
1278 class ShenandoahConcurrentEvacuateRegionObjectClosure : public ObjectClosure {
1279 private:
1280   ShenandoahHeap* const _heap;
1281   Thread* const _thread;
1282 public:
1283   ShenandoahConcurrentEvacuateRegionObjectClosure(ShenandoahHeap* heap) :
1284     _heap(heap), _thread(Thread::current()) {}
1285 
1286   void do_object(oop p) {
1287     shenandoah_assert_marked(NULL, p);
1288     if (!p->is_forwarded()) {
1289       _heap->evacuate_object(p, _thread);
1290     }
1291   }
1292 };
1293 
1294 class ShenandoahEvacuationTask : public WorkerTask {
1295 private:
1296   ShenandoahHeap* const _sh;
1297   ShenandoahCollectionSet* const _cs;
1298   bool _concurrent;
1299 public:
1300   ShenandoahEvacuationTask(ShenandoahHeap* sh,
1301                            ShenandoahCollectionSet* cs,
1302                            bool concurrent) :
1303     WorkerTask("Shenandoah Evacuation"),
1304     _sh(sh),
1305     _cs(cs),
1306     _concurrent(concurrent)
1307   {}
1308 
1309   void work(uint worker_id) {
1310     if (_concurrent) {
1311       ShenandoahConcurrentWorkerSession worker_session(worker_id);
1312       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
1313       ShenandoahEvacOOMScope oom_evac_scope;
1314       do_work();
1315     } else {
1316       ShenandoahParallelWorkerSession worker_session(worker_id);
1317       ShenandoahEvacOOMScope oom_evac_scope;
1318       do_work();
1319     }
1320   }
1321 
1322 private:
1323   void do_work() {
1324     ShenandoahConcurrentEvacuateRegionObjectClosure cl(_sh);
1325     ShenandoahHeapRegion* r;
1326     while ((r =_cs->claim_next()) != NULL) {
1327       assert(r->has_live(), "Region " SIZE_FORMAT " should have been reclaimed early", r->index());
1328 
1329       _sh->marked_object_iterate(r, &cl);
1330 
1331       if (ShenandoahPacing) {
1332         _sh->pacer()->report_evac(r->used() >> LogHeapWordSize);
1333       }
1334       if (_sh->check_cancelled_gc_and_yield(_concurrent)) {
1335         break;
1336       }
1337     }
1338   }
1339 };
1340 
1341 // Unlike ShenandoahEvacuationTask, this iterates over all regions rather than just the collection set.
1342 // This is needed in order to promote humongous start regions if age() >= tenure threshold.
1343 class ShenandoahGenerationalEvacuationTask : public WorkerTask {
1344 private:
1345   ShenandoahHeap* const _sh;
1346   ShenandoahRegionIterator *_regions;
1347   bool _concurrent;
1348 public:
1349   ShenandoahGenerationalEvacuationTask(ShenandoahHeap* sh,
1350                                        ShenandoahRegionIterator* iterator,
1351                                        bool concurrent) :
1352     WorkerTask("Shenandoah Evacuation"),
1353     _sh(sh),
1354     _regions(iterator),
1355     _concurrent(concurrent)
1356   {}
1357 
1358   void work(uint worker_id) {
1359     if (_concurrent) {
1360       ShenandoahConcurrentWorkerSession worker_session(worker_id);
1361       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
1362       ShenandoahEvacOOMScope oom_evac_scope;
1363       do_work();
1364     } else {
1365       ShenandoahParallelWorkerSession worker_session(worker_id);
1366       ShenandoahEvacOOMScope oom_evac_scope;
1367       do_work();
1368     }
1369   }
1370 
1371 private:
1372   void do_work() {
1373     ShenandoahConcurrentEvacuateRegionObjectClosure cl(_sh);
1374     ShenandoahHeapRegion* r;
1375     while ((r = _regions->next()) != nullptr) {
1376       log_debug(gc)("GenerationalEvacuationTask do_work(), looking at %s region " SIZE_FORMAT ", (age: %d) [%s, %s]",
1377                     r->is_old()? "old": r->is_young()? "young": "free", r->index(), r->age(),
1378                     r->is_active()? "active": "inactive",
1379                     r->is_humongous()? (r->is_humongous_start()? "humongous_start": "humongous_continuation"): "regular");
1380       if (r->is_cset()) {
1381         assert(r->has_live(), "Region " SIZE_FORMAT " should have been reclaimed early", r->index());
1382         _sh->marked_object_iterate(r, &cl);
1383         if (ShenandoahPacing) {
1384           _sh->pacer()->report_evac(r->used() >> LogHeapWordSize);
1385         }
1386       } else if (r->is_young() && r->is_active() && r->is_humongous_start() && (r->age() > InitialTenuringThreshold)) {
1387         // We promote humongous_start regions along with their affiliated continuations during evacuation rather than
1388         // doing this work during a safepoint.  We cannot put humongous regions into the collection set because that
1389         // triggers the load-reference barrier (LRB) to copy on reference fetch.
1390         r->promote_humongous();
1391       }
1392       // else, region is free, or OLD, or not in collection set, or humongous_continuation,
1393       // or is young humongous_start that is too young to be promoted
1394 
1395       if (_sh->check_cancelled_gc_and_yield(_concurrent)) {
1396         break;
1397       }
1398     }
1399   }
1400 };
1401 
1402 void ShenandoahHeap::evacuate_collection_set(bool concurrent) {
1403   if (ShenandoahHeap::heap()->mode()->is_generational()) {
1404     ShenandoahRegionIterator regions;
1405     ShenandoahGenerationalEvacuationTask task(this, &regions, concurrent);
1406     workers()->run_task(&task);
1407   } else {
1408     ShenandoahEvacuationTask task(this, _collection_set, concurrent);
1409     workers()->run_task(&task);
1410   }
1411 }
1412 
1413 void ShenandoahHeap::trash_cset_regions() {
1414   ShenandoahHeapLocker locker(lock());
1415 
1416   ShenandoahCollectionSet* set = collection_set();
1417   ShenandoahHeapRegion* r;
1418   set->clear_current_index();
1419   while ((r = set->next()) != NULL) {
1420     r->make_trash();
1421   }
1422   collection_set()->clear();
1423 }
1424 
1425 void ShenandoahHeap::print_heap_regions_on(outputStream* st) const {
1426   st->print_cr("Heap Regions:");
1427   st->print_cr("EU=empty-uncommitted, EC=empty-committed, R=regular, H=humongous start, HC=humongous continuation, CS=collection set, T=trash, P=pinned");
1428   st->print_cr("BTE=bottom/top/end, U=used, T=TLAB allocs, G=GCLAB allocs, S=shared allocs, L=live data");
1429   st->print_cr("R=root, CP=critical pins, TAMS=top-at-mark-start, UWM=update watermark");
1430   st->print_cr("SN=alloc sequence number");
1431 
1432   for (size_t i = 0; i < num_regions(); i++) {
1433     get_region(i)->print_on(st);
1434   }
1435 }
1436 
1437 size_t ShenandoahHeap::trash_humongous_region_at(ShenandoahHeapRegion* start) {
1438   assert(start->is_humongous_start(), "reclaim regions starting with the first one");
1439 
1440   oop humongous_obj = cast_to_oop(start->bottom());
1441   size_t size = humongous_obj->size();
1442   size_t required_regions = ShenandoahHeapRegion::required_regions(size * HeapWordSize);
1443   size_t index = start->index() + required_regions - 1;
1444 
1445   assert(!start->has_live(), "liveness must be zero");
1446 
1447   for(size_t i = 0; i < required_regions; i++) {
1448     // Reclaim from tail. Otherwise, assertion fails when printing region to trace log,
1449     // as it expects that every region belongs to a humongous region starting with a humongous start region.
1450     ShenandoahHeapRegion* region = get_region(index --);
1451 
1452     assert(region->is_humongous(), "expect correct humongous start or continuation");
1453     assert(!region->is_cset(), "Humongous region should not be in collection set");
1454 
1455     region->make_trash_immediate();
1456   }
1457   return required_regions;
1458 }
1459 
1460 class ShenandoahCheckCleanGCLABClosure : public ThreadClosure {
1461 public:
1462   ShenandoahCheckCleanGCLABClosure() {}
1463   void do_thread(Thread* thread) {
1464     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1465     assert(gclab != NULL, "GCLAB should be initialized for %s", thread->name());
1466     assert(gclab->words_remaining() == 0, "GCLAB should not need retirement");
1467 
1468     PLAB* plab = ShenandoahThreadLocalData::plab(thread);
1469     assert(plab != NULL, "PLAB should be initialized for %s", thread->name());
1470     assert(plab->words_remaining() == 0, "PLAB should not need retirement");
1471   }
1472 };
1473 
1474 class ShenandoahRetireGCLABClosure : public ThreadClosure {
1475 private:
1476   bool const _resize;
1477 public:
1478   ShenandoahRetireGCLABClosure(bool resize) : _resize(resize) {}
1479   void do_thread(Thread* thread) {
1480     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1481     assert(gclab != NULL, "GCLAB should be initialized for %s", thread->name());
1482     gclab->retire();
1483     if (_resize && ShenandoahThreadLocalData::gclab_size(thread) > 0) {
1484       ShenandoahThreadLocalData::set_gclab_size(thread, 0);
1485     }
1486 
1487     PLAB* plab = ShenandoahThreadLocalData::plab(thread);
1488     assert(plab != NULL, "PLAB should be initialized for %s", thread->name());
1489     // TODO; Retiring a PLAB disables it so it cannot support future allocations.  This is overkill.  For old-gen
1490     // regions, the important thing is to make the memory parsable by the remembered-set scanning code that drives
1491     // the update-refs processing that follows.  After the updating of old-gen references is done, it is ok to carve
1492     // this remnant object into smaller pieces during the subsequent evacuation pass, as long as the PLAB is made parsable
1493     // again before the next update-refs phase.
1494     ShenandoahHeap::heap()->retire_plab(plab);
1495     if (_resize && ShenandoahThreadLocalData::plab_size(thread) > 0) {
1496       ShenandoahThreadLocalData::set_plab_size(thread, 0);
1497     }
1498   }
1499 };
1500 
1501 void ShenandoahHeap::labs_make_parsable() {
1502   assert(UseTLAB, "Only call with UseTLAB");
1503 
1504   ShenandoahRetireGCLABClosure cl(false);
1505 
1506   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1507     ThreadLocalAllocBuffer& tlab = t->tlab();
1508     tlab.make_parsable();
1509     cl.do_thread(t);
1510   }
1511 
1512   workers()->threads_do(&cl);
1513 }
1514 
1515 void ShenandoahHeap::tlabs_retire(bool resize) {
1516   assert(UseTLAB, "Only call with UseTLAB");
1517   assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled");
1518 
1519   ThreadLocalAllocStats stats;
1520 
1521   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1522     ThreadLocalAllocBuffer& tlab = t->tlab();
1523     tlab.retire(&stats);
1524     if (resize) {
1525       tlab.resize();
1526     }
1527   }
1528 
1529   stats.publish();
1530 
1531 #ifdef ASSERT
1532   ShenandoahCheckCleanGCLABClosure cl;
1533   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1534     cl.do_thread(t);
1535   }
1536   workers()->threads_do(&cl);
1537 #endif
1538 }
1539 
1540 void ShenandoahHeap::gclabs_retire(bool resize) {
1541   assert(UseTLAB, "Only call with UseTLAB");
1542   assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled");
1543 
1544   ShenandoahRetireGCLABClosure cl(resize);
1545   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1546     cl.do_thread(t);
1547   }
1548   workers()->threads_do(&cl);
1549 
1550   if (safepoint_workers() != NULL) {
1551     safepoint_workers()->threads_do(&cl);
1552   }
1553 }
1554 
1555 class ShenandoahTagGCLABClosure : public ThreadClosure {
1556 public:
1557   void do_thread(Thread* thread) {
1558     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1559     assert(gclab != NULL, "GCLAB should be initialized for %s", thread->name());
1560     if (gclab->words_remaining() > 0) {
1561       ShenandoahHeapRegion* r = ShenandoahHeap::heap()->heap_region_containing(gclab->allocate(0));
1562       r->set_young_lab_flag();
1563     }
1564   }
1565 };
1566 
1567 void ShenandoahHeap::set_young_lab_region_flags() {
1568   if (!UseTLAB) {
1569     return;
1570   }
1571   for (size_t i = 0; i < _num_regions; i++) {
1572     _regions[i]->clear_young_lab_flags();
1573   }
1574   ShenandoahTagGCLABClosure cl;
1575   workers()->threads_do(&cl);
1576   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1577     cl.do_thread(t);
1578     ThreadLocalAllocBuffer& tlab = t->tlab();
1579     if (tlab.end() != NULL) {
1580       ShenandoahHeapRegion* r = heap_region_containing(tlab.start());
1581       r->set_young_lab_flag();
1582     }
1583   }
1584 }
1585 
1586 // Returns size in bytes
1587 size_t ShenandoahHeap::unsafe_max_tlab_alloc(Thread *thread) const {
1588   if (ShenandoahElasticTLAB) {
1589     // With Elastic TLABs, return the max allowed size, and let the allocation path
1590     // figure out the safe size for current allocation.
1591     return ShenandoahHeapRegion::max_tlab_size_bytes();
1592   } else {
1593     return MIN2(_free_set->unsafe_peek_free(), ShenandoahHeapRegion::max_tlab_size_bytes());
1594   }
1595 }
1596 
1597 size_t ShenandoahHeap::max_tlab_size() const {
1598   // Returns size in words
1599   return ShenandoahHeapRegion::max_tlab_size_words();
1600 }
1601 
1602 void ShenandoahHeap::collect(GCCause::Cause cause) {
1603   control_thread()->request_gc(cause);
1604 }
1605 
1606 void ShenandoahHeap::do_full_collection(bool clear_all_soft_refs) {
1607   //assert(false, "Shouldn't need to do full collections");
1608 }
1609 
1610 HeapWord* ShenandoahHeap::block_start(const void* addr) const {
1611   ShenandoahHeapRegion* r = heap_region_containing(addr);
1612   if (r != NULL) {
1613     return r->block_start(addr);
1614   }
1615   return NULL;
1616 }
1617 
1618 bool ShenandoahHeap::block_is_obj(const HeapWord* addr) const {
1619   ShenandoahHeapRegion* r = heap_region_containing(addr);
1620   return r->block_is_obj(addr);
1621 }
1622 
1623 bool ShenandoahHeap::print_location(outputStream* st, void* addr) const {
1624   return BlockLocationPrinter<ShenandoahHeap>::print_location(st, addr);
1625 }
1626 
1627 void ShenandoahHeap::prepare_for_verify() {
1628   if (SafepointSynchronize::is_at_safepoint() && UseTLAB) {
1629     labs_make_parsable();
1630   }
1631 }
1632 
1633 void ShenandoahHeap::gc_threads_do(ThreadClosure* tcl) const {
1634   workers()->threads_do(tcl);
1635   if (_safepoint_workers != NULL) {
1636     _safepoint_workers->threads_do(tcl);
1637   }
1638   if (ShenandoahStringDedup::is_enabled()) {
1639     ShenandoahStringDedup::threads_do(tcl);
1640   }
1641 }
1642 
1643 void ShenandoahHeap::print_tracing_info() const {
1644   LogTarget(Info, gc, stats) lt;
1645   if (lt.is_enabled()) {
1646     ResourceMark rm;
1647     LogStream ls(lt);
1648 
1649     phase_timings()->print_global_on(&ls);
1650 
1651     ls.cr();
1652     ls.cr();
1653 
1654     shenandoah_policy()->print_gc_stats(&ls);
1655 
1656     ls.cr();
1657     ls.cr();
1658   }
1659 }
1660 
1661 void ShenandoahHeap::verify(VerifyOption vo) {
1662   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
1663     if (ShenandoahVerify) {
1664       verifier()->verify_generic(vo);
1665     } else {
1666       // TODO: Consider allocating verification bitmaps on demand,
1667       // and turn this on unconditionally.
1668     }
1669   }
1670 }
1671 size_t ShenandoahHeap::tlab_capacity(Thread *thr) const {
1672   return _free_set->capacity();
1673 }
1674 
1675 class ObjectIterateScanRootClosure : public BasicOopIterateClosure {
1676 private:
1677   MarkBitMap* _bitmap;
1678   ShenandoahScanObjectStack* _oop_stack;
1679   ShenandoahHeap* const _heap;
1680   ShenandoahMarkingContext* const _marking_context;
1681 
1682   template <class T>
1683   void do_oop_work(T* p) {
1684     T o = RawAccess<>::oop_load(p);
1685     if (!CompressedOops::is_null(o)) {
1686       oop obj = CompressedOops::decode_not_null(o);
1687       if (_heap->is_concurrent_weak_root_in_progress() && !_marking_context->is_marked(obj)) {
1688         // There may be dead oops in weak roots in concurrent root phase, do not touch them.
1689         return;
1690       }
1691       obj = ShenandoahBarrierSet::resolve_forwarded_not_null(obj);
1692 
1693       assert(oopDesc::is_oop(obj), "must be a valid oop");
1694       if (!_bitmap->is_marked(obj)) {
1695         _bitmap->mark(obj);
1696         _oop_stack->push(obj);
1697       }
1698     }
1699   }
1700 public:
1701   ObjectIterateScanRootClosure(MarkBitMap* bitmap, ShenandoahScanObjectStack* oop_stack) :
1702     _bitmap(bitmap), _oop_stack(oop_stack), _heap(ShenandoahHeap::heap()),
1703     _marking_context(_heap->marking_context()) {}
1704   void do_oop(oop* p)       { do_oop_work(p); }
1705   void do_oop(narrowOop* p) { do_oop_work(p); }
1706 };
1707 
1708 /*
1709  * This is public API, used in preparation of object_iterate().
1710  * Since we don't do linear scan of heap in object_iterate() (see comment below), we don't
1711  * need to make the heap parsable. For Shenandoah-internal linear heap scans that we can
1712  * control, we call SH::tlabs_retire, SH::gclabs_retire.
1713  */
1714 void ShenandoahHeap::ensure_parsability(bool retire_tlabs) {
1715   // No-op.
1716 }
1717 
1718 /*
1719  * Iterates objects in the heap. This is public API, used for, e.g., heap dumping.
1720  *
1721  * We cannot safely iterate objects by doing a linear scan at random points in time. Linear
1722  * scanning needs to deal with dead objects, which may have dead Klass* pointers (e.g.
1723  * calling oopDesc::size() would crash) or dangling reference fields (crashes) etc. Linear
1724  * scanning therefore depends on having a valid marking bitmap to support it. However, we only
1725  * have a valid marking bitmap after successful marking. In particular, we *don't* have a valid
1726  * marking bitmap during marking, after aborted marking or during/after cleanup (when we just
1727  * wiped the bitmap in preparation for next marking).
1728  *
1729  * For all those reasons, we implement object iteration as a single marking traversal, reporting
1730  * objects as we mark+traverse through the heap, starting from GC roots. JVMTI IterateThroughHeap
1731  * is allowed to report dead objects, but is not required to do so.
1732  */
1733 void ShenandoahHeap::object_iterate(ObjectClosure* cl) {
1734   // Reset bitmap
1735   if (!prepare_aux_bitmap_for_iteration())
1736     return;
1737 
1738   ShenandoahScanObjectStack oop_stack;
1739   ObjectIterateScanRootClosure oops(&_aux_bit_map, &oop_stack);
1740   // Seed the stack with root scan
1741   scan_roots_for_iteration(&oop_stack, &oops);
1742 
1743   // Work through the oop stack to traverse heap
1744   while (! oop_stack.is_empty()) {
1745     oop obj = oop_stack.pop();
1746     assert(oopDesc::is_oop(obj), "must be a valid oop");
1747     cl->do_object(obj);
1748     obj->oop_iterate(&oops);
1749   }
1750 
1751   assert(oop_stack.is_empty(), "should be empty");
1752   // Reclaim bitmap
1753   reclaim_aux_bitmap_for_iteration();
1754 }
1755 
1756 bool ShenandoahHeap::prepare_aux_bitmap_for_iteration() {
1757   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1758 
1759   if (!_aux_bitmap_region_special && !os::commit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size(), false)) {
1760     log_warning(gc)("Could not commit native memory for auxiliary marking bitmap for heap iteration");
1761     return false;
1762   }
1763   // Reset bitmap
1764   _aux_bit_map.clear();
1765   return true;
1766 }
1767 
1768 void ShenandoahHeap::scan_roots_for_iteration(ShenandoahScanObjectStack* oop_stack, ObjectIterateScanRootClosure* oops) {
1769   // Process GC roots according to current GC cycle
1770   // This populates the work stack with initial objects
1771   // It is important to relinquish the associated locks before diving
1772   // into heap dumper
1773   uint n_workers = safepoint_workers() != NULL ? safepoint_workers()->active_workers() : 1;
1774   ShenandoahHeapIterationRootScanner rp(n_workers);
1775   rp.roots_do(oops);
1776 }
1777 
1778 void ShenandoahHeap::reclaim_aux_bitmap_for_iteration() {
1779   if (!_aux_bitmap_region_special && !os::uncommit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size())) {
1780     log_warning(gc)("Could not uncommit native memory for auxiliary marking bitmap for heap iteration");
1781   }
1782 }
1783 
1784 // Closure for parallelly iterate objects
1785 class ShenandoahObjectIterateParScanClosure : public BasicOopIterateClosure {
1786 private:
1787   MarkBitMap* _bitmap;
1788   ShenandoahObjToScanQueue* _queue;
1789   ShenandoahHeap* const _heap;
1790   ShenandoahMarkingContext* const _marking_context;
1791 
1792   template <class T>
1793   void do_oop_work(T* p) {
1794     T o = RawAccess<>::oop_load(p);
1795     if (!CompressedOops::is_null(o)) {
1796       oop obj = CompressedOops::decode_not_null(o);
1797       if (_heap->is_concurrent_weak_root_in_progress() && !_marking_context->is_marked(obj)) {
1798         // There may be dead oops in weak roots in concurrent root phase, do not touch them.
1799         return;
1800       }
1801       obj = ShenandoahBarrierSet::resolve_forwarded_not_null(obj);
1802 
1803       assert(oopDesc::is_oop(obj), "Must be a valid oop");
1804       if (_bitmap->par_mark(obj)) {
1805         _queue->push(ShenandoahMarkTask(obj));
1806       }
1807     }
1808   }
1809 public:
1810   ShenandoahObjectIterateParScanClosure(MarkBitMap* bitmap, ShenandoahObjToScanQueue* q) :
1811     _bitmap(bitmap), _queue(q), _heap(ShenandoahHeap::heap()),
1812     _marking_context(_heap->marking_context()) {}
1813   void do_oop(oop* p)       { do_oop_work(p); }
1814   void do_oop(narrowOop* p) { do_oop_work(p); }
1815 };
1816 
1817 // Object iterator for parallel heap iteraion.
1818 // The root scanning phase happenes in construction as a preparation of
1819 // parallel marking queues.
1820 // Every worker processes it's own marking queue. work-stealing is used
1821 // to balance workload.
1822 class ShenandoahParallelObjectIterator : public ParallelObjectIteratorImpl {
1823 private:
1824   uint                         _num_workers;
1825   bool                         _init_ready;
1826   MarkBitMap*                  _aux_bit_map;
1827   ShenandoahHeap*              _heap;
1828   ShenandoahScanObjectStack    _roots_stack; // global roots stack
1829   ShenandoahObjToScanQueueSet* _task_queues;
1830 public:
1831   ShenandoahParallelObjectIterator(uint num_workers, MarkBitMap* bitmap) :
1832         _num_workers(num_workers),
1833         _init_ready(false),
1834         _aux_bit_map(bitmap),
1835         _heap(ShenandoahHeap::heap()) {
1836     // Initialize bitmap
1837     _init_ready = _heap->prepare_aux_bitmap_for_iteration();
1838     if (!_init_ready) {
1839       return;
1840     }
1841 
1842     ObjectIterateScanRootClosure oops(_aux_bit_map, &_roots_stack);
1843     _heap->scan_roots_for_iteration(&_roots_stack, &oops);
1844 
1845     _init_ready = prepare_worker_queues();
1846   }
1847 
1848   ~ShenandoahParallelObjectIterator() {
1849     // Reclaim bitmap
1850     _heap->reclaim_aux_bitmap_for_iteration();
1851     // Reclaim queue for workers
1852     if (_task_queues!= NULL) {
1853       for (uint i = 0; i < _num_workers; ++i) {
1854         ShenandoahObjToScanQueue* q = _task_queues->queue(i);
1855         if (q != NULL) {
1856           delete q;
1857           _task_queues->register_queue(i, NULL);
1858         }
1859       }
1860       delete _task_queues;
1861       _task_queues = NULL;
1862     }
1863   }
1864 
1865   virtual void object_iterate(ObjectClosure* cl, uint worker_id) {
1866     if (_init_ready) {
1867       object_iterate_parallel(cl, worker_id, _task_queues);
1868     }
1869   }
1870 
1871 private:
1872   // Divide global root_stack into worker queues
1873   bool prepare_worker_queues() {
1874     _task_queues = new ShenandoahObjToScanQueueSet((int) _num_workers);
1875     // Initialize queues for every workers
1876     for (uint i = 0; i < _num_workers; ++i) {
1877       ShenandoahObjToScanQueue* task_queue = new ShenandoahObjToScanQueue();
1878       _task_queues->register_queue(i, task_queue);
1879     }
1880     // Divide roots among the workers. Assume that object referencing distribution
1881     // is related with root kind, use round-robin to make every worker have same chance
1882     // to process every kind of roots
1883     size_t roots_num = _roots_stack.size();
1884     if (roots_num == 0) {
1885       // No work to do
1886       return false;
1887     }
1888 
1889     for (uint j = 0; j < roots_num; j++) {
1890       uint stack_id = j % _num_workers;
1891       oop obj = _roots_stack.pop();
1892       _task_queues->queue(stack_id)->push(ShenandoahMarkTask(obj));
1893     }
1894     return true;
1895   }
1896 
1897   void object_iterate_parallel(ObjectClosure* cl,
1898                                uint worker_id,
1899                                ShenandoahObjToScanQueueSet* queue_set) {
1900     assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1901     assert(queue_set != NULL, "task queue must not be NULL");
1902 
1903     ShenandoahObjToScanQueue* q = queue_set->queue(worker_id);
1904     assert(q != NULL, "object iterate queue must not be NULL");
1905 
1906     ShenandoahMarkTask t;
1907     ShenandoahObjectIterateParScanClosure oops(_aux_bit_map, q);
1908 
1909     // Work through the queue to traverse heap.
1910     // Steal when there is no task in queue.
1911     while (q->pop(t) || queue_set->steal(worker_id, t)) {
1912       oop obj = t.obj();
1913       assert(oopDesc::is_oop(obj), "must be a valid oop");
1914       cl->do_object(obj);
1915       obj->oop_iterate(&oops);
1916     }
1917     assert(q->is_empty(), "should be empty");
1918   }
1919 };
1920 
1921 ParallelObjectIteratorImpl* ShenandoahHeap::parallel_object_iterator(uint workers) {
1922   return new ShenandoahParallelObjectIterator(workers, &_aux_bit_map);
1923 }
1924 
1925 // Keep alive an object that was loaded with AS_NO_KEEPALIVE.
1926 void ShenandoahHeap::keep_alive(oop obj) {
1927   if (is_concurrent_mark_in_progress() && (obj != NULL)) {
1928     ShenandoahBarrierSet::barrier_set()->enqueue(obj);
1929   }
1930 }
1931 
1932 void ShenandoahHeap::heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1933   for (size_t i = 0; i < num_regions(); i++) {
1934     ShenandoahHeapRegion* current = get_region(i);
1935     blk->heap_region_do(current);
1936   }
1937 }
1938 
1939 class ShenandoahParallelHeapRegionTask : public WorkerTask {
1940 private:
1941   ShenandoahHeap* const _heap;
1942   ShenandoahHeapRegionClosure* const _blk;
1943 
1944   shenandoah_padding(0);
1945   volatile size_t _index;
1946   shenandoah_padding(1);
1947 
1948 public:
1949   ShenandoahParallelHeapRegionTask(ShenandoahHeapRegionClosure* blk) :
1950           WorkerTask("Shenandoah Parallel Region Operation"),
1951           _heap(ShenandoahHeap::heap()), _blk(blk), _index(0) {}
1952 
1953   void work(uint worker_id) {
1954     ShenandoahParallelWorkerSession worker_session(worker_id);
1955     size_t stride = ShenandoahParallelRegionStride;
1956 
1957     size_t max = _heap->num_regions();
1958     while (Atomic::load(&_index) < max) {
1959       size_t cur = Atomic::fetch_and_add(&_index, stride, memory_order_relaxed);
1960       size_t start = cur;
1961       size_t end = MIN2(cur + stride, max);
1962       if (start >= max) break;
1963 
1964       for (size_t i = cur; i < end; i++) {
1965         ShenandoahHeapRegion* current = _heap->get_region(i);
1966         _blk->heap_region_do(current);
1967       }
1968     }
1969   }
1970 };
1971 
1972 void ShenandoahHeap::parallel_heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1973   assert(blk->is_thread_safe(), "Only thread-safe closures here");
1974   if (num_regions() > ShenandoahParallelRegionStride) {
1975     ShenandoahParallelHeapRegionTask task(blk);
1976     workers()->run_task(&task);
1977   } else {
1978     heap_region_iterate(blk);
1979   }
1980 }
1981 
1982 class ShenandoahRendezvousClosure : public HandshakeClosure {
1983 public:
1984   inline ShenandoahRendezvousClosure() : HandshakeClosure("ShenandoahRendezvous") {}
1985   inline void do_thread(Thread* thread) {}
1986 };
1987 
1988 void ShenandoahHeap::rendezvous_threads() {
1989   ShenandoahRendezvousClosure cl;
1990   Handshake::execute(&cl);
1991 }
1992 
1993 void ShenandoahHeap::recycle_trash() {
1994   free_set()->recycle_trash();
1995 }
1996 
1997 void ShenandoahHeap::do_class_unloading() {
1998   _unloader.unload();
1999 }
2000 
2001 void ShenandoahHeap::stw_weak_refs(bool full_gc) {
2002   // Weak refs processing
2003   ShenandoahPhaseTimings::Phase phase = full_gc ? ShenandoahPhaseTimings::full_gc_weakrefs
2004                                                 : ShenandoahPhaseTimings::degen_gc_weakrefs;
2005   ShenandoahTimingsTracker t(phase);
2006   ShenandoahGCWorkerPhase worker_phase(phase);
2007   active_generation()->ref_processor()->process_references(phase, workers(), false /* concurrent */);
2008 }
2009 
2010 void ShenandoahHeap::prepare_update_heap_references(bool concurrent) {
2011   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2012 
2013   // Evacuation is over, no GCLABs are needed anymore. GCLABs are under URWM, so we need to
2014   // make them parsable for update code to work correctly. Plus, we can compute new sizes
2015   // for future GCLABs here.
2016   if (UseTLAB) {
2017     ShenandoahGCPhase phase(concurrent ?
2018                             ShenandoahPhaseTimings::init_update_refs_manage_gclabs :
2019                             ShenandoahPhaseTimings::degen_gc_init_update_refs_manage_gclabs);
2020     gclabs_retire(ResizeTLAB);
2021   }
2022 
2023   _update_refs_iterator.reset();
2024 }
2025 
2026 void ShenandoahHeap::set_gc_state_all_threads(char state) {
2027   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
2028     ShenandoahThreadLocalData::set_gc_state(t, state);
2029   }
2030 }
2031 
2032 void ShenandoahHeap::set_gc_state_mask(uint mask, bool value) {
2033   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should really be Shenandoah safepoint");
2034   _gc_state.set_cond(mask, value);
2035   set_gc_state_all_threads(_gc_state.raw_value());
2036 }
2037 
2038 void ShenandoahHeap::set_concurrent_young_mark_in_progress(bool in_progress) {
2039   if (has_forwarded_objects()) {
2040     set_gc_state_mask(YOUNG_MARKING | UPDATEREFS, in_progress);
2041   } else {
2042     set_gc_state_mask(YOUNG_MARKING, in_progress);
2043   }
2044 
2045   manage_satb_barrier(in_progress);
2046 }
2047 
2048 void ShenandoahHeap::set_concurrent_old_mark_in_progress(bool in_progress) {
2049   if (has_forwarded_objects()) {
2050     set_gc_state_mask(OLD_MARKING | UPDATEREFS, in_progress);
2051   } else {
2052     set_gc_state_mask(OLD_MARKING, in_progress);
2053   }
2054 
2055   manage_satb_barrier(in_progress);
2056 }
2057 
2058 void ShenandoahHeap::set_concurrent_prep_for_mixed_evacuation_in_progress(bool in_progress) {
2059   // Unlike other set-gc-state functions, this may happen outside safepoint.
2060   // Is only set and queried by control thread, so no coherence issues.
2061   _prep_for_mixed_evac_in_progress = in_progress;
2062 }
2063 
2064 bool ShenandoahHeap::is_concurrent_prep_for_mixed_evacuation_in_progress() {
2065   return _prep_for_mixed_evac_in_progress;
2066 }
2067 
2068 void ShenandoahHeap::set_aging_cycle(bool in_progress) {
2069   _is_aging_cycle.set_cond(in_progress);
2070 }
2071 
2072 void ShenandoahHeap::manage_satb_barrier(bool active) {
2073   if (is_concurrent_mark_in_progress()) {
2074     // Ignore request to deactivate barrier while concurrent mark is in progress.
2075     // Do not attempt to re-activate the barrier if it is already active.
2076     if (active && !ShenandoahBarrierSet::satb_mark_queue_set().is_active()) {
2077       ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(active, !active);
2078     }
2079   } else {
2080     // No concurrent marking is in progress so honor request to deactivate,
2081     // but only if the barrier is already active.
2082     if (!active && ShenandoahBarrierSet::satb_mark_queue_set().is_active()) {
2083       ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(active, !active);
2084     }
2085   }
2086 }
2087 
2088 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {
2089   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint");
2090   set_gc_state_mask(EVACUATION, in_progress);
2091 }
2092 
2093 void ShenandoahHeap::set_concurrent_strong_root_in_progress(bool in_progress) {
2094   if (in_progress) {
2095     _concurrent_strong_root_in_progress.set();
2096   } else {
2097     _concurrent_strong_root_in_progress.unset();
2098   }
2099 }
2100 
2101 void ShenandoahHeap::set_concurrent_weak_root_in_progress(bool cond) {
2102   set_gc_state_mask(WEAK_ROOTS, cond);
2103 }
2104 
2105 GCTracer* ShenandoahHeap::tracer() {
2106   return shenandoah_policy()->tracer();
2107 }
2108 
2109 size_t ShenandoahHeap::tlab_used(Thread* thread) const {
2110   return _free_set->used();
2111 }
2112 
2113 bool ShenandoahHeap::try_cancel_gc() {
2114   while (true) {
2115     jbyte prev = _cancelled_gc.cmpxchg(CANCELLED, CANCELLABLE);
2116     if (prev == CANCELLABLE) return true;
2117     else if (prev == CANCELLED) return false;
2118     assert(ShenandoahSuspendibleWorkers, "should not get here when not using suspendible workers");
2119     assert(prev == NOT_CANCELLED, "must be NOT_CANCELLED");
2120     Thread* thread = Thread::current();
2121     if (thread->is_Java_thread()) {
2122       // We need to provide a safepoint here, otherwise we might
2123       // spin forever if a SP is pending.
2124       ThreadBlockInVM sp(JavaThread::cast(thread));
2125       SpinPause();
2126     }
2127   }
2128 }
2129 
2130 void ShenandoahHeap::cancel_concurrent_mark() {
2131   _young_generation->cancel_marking();
2132   _old_generation->cancel_marking();
2133   _global_generation->cancel_marking();
2134 
2135   ShenandoahBarrierSet::satb_mark_queue_set().abandon_partial_marking();
2136 }
2137 
2138 void ShenandoahHeap::cancel_gc(GCCause::Cause cause) {
2139   if (try_cancel_gc()) {
2140     FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause));
2141     log_info(gc)("%s", msg.buffer());
2142     Events::log(Thread::current(), "%s", msg.buffer());
2143     _cancel_requested_time = os::elapsedTime();
2144     if (cause == GCCause::_shenandoah_upgrade_to_full_gc) {
2145       _upgraded_to_full = true;
2146     }
2147   }
2148 }
2149 
2150 uint ShenandoahHeap::max_workers() {
2151   return _max_workers;
2152 }
2153 
2154 void ShenandoahHeap::stop() {
2155   // The shutdown sequence should be able to terminate when GC is running.
2156 
2157   // Step 0a. Stop requesting collections.
2158   regulator_thread()->stop();
2159 
2160   // Step 0. Notify policy to disable event recording.
2161   _shenandoah_policy->record_shutdown();
2162 
2163   // Step 1. Notify control thread that we are in shutdown.
2164   // Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown.
2165   // Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below.
2166   control_thread()->prepare_for_graceful_shutdown();
2167 
2168   // Step 2. Notify GC workers that we are cancelling GC.
2169   cancel_gc(GCCause::_shenandoah_stop_vm);
2170 
2171   // Step 3. Wait until GC worker exits normally.
2172   control_thread()->stop();
2173 }
2174 
2175 void ShenandoahHeap::stw_unload_classes(bool full_gc) {
2176   if (!unload_classes()) return;
2177   // Unload classes and purge SystemDictionary.
2178   {
2179     ShenandoahPhaseTimings::Phase phase = full_gc ?
2180                                           ShenandoahPhaseTimings::full_gc_purge_class_unload :
2181                                           ShenandoahPhaseTimings::degen_gc_purge_class_unload;
2182     ShenandoahGCPhase gc_phase(phase);
2183     ShenandoahGCWorkerPhase worker_phase(phase);
2184     bool purged_class = SystemDictionary::do_unloading(gc_timer());
2185 
2186     ShenandoahIsAliveSelector is_alive;
2187     uint num_workers = _workers->active_workers();
2188     ShenandoahClassUnloadingTask unlink_task(phase, is_alive.is_alive_closure(), num_workers, purged_class);
2189     _workers->run_task(&unlink_task);
2190   }
2191 
2192   {
2193     ShenandoahGCPhase phase(full_gc ?
2194                             ShenandoahPhaseTimings::full_gc_purge_cldg :
2195                             ShenandoahPhaseTimings::degen_gc_purge_cldg);
2196     ClassLoaderDataGraph::purge(/*at_safepoint*/true);
2197   }
2198   // Resize and verify metaspace
2199   MetaspaceGC::compute_new_size();
2200   DEBUG_ONLY(MetaspaceUtils::verify();)
2201 }
2202 
2203 // Weak roots are either pre-evacuated (final mark) or updated (final updaterefs),
2204 // so they should not have forwarded oops.
2205 // However, we do need to "null" dead oops in the roots, if can not be done
2206 // in concurrent cycles.
2207 void ShenandoahHeap::stw_process_weak_roots(bool full_gc) {
2208   uint num_workers = _workers->active_workers();
2209   ShenandoahPhaseTimings::Phase timing_phase = full_gc ?
2210                                                ShenandoahPhaseTimings::full_gc_purge_weak_par :
2211                                                ShenandoahPhaseTimings::degen_gc_purge_weak_par;
2212   ShenandoahGCPhase phase(timing_phase);
2213   ShenandoahGCWorkerPhase worker_phase(timing_phase);
2214   // Cleanup weak roots
2215   if (has_forwarded_objects()) {
2216     ShenandoahForwardedIsAliveClosure is_alive;
2217     ShenandoahUpdateRefsClosure keep_alive;
2218     ShenandoahParallelWeakRootsCleaningTask<ShenandoahForwardedIsAliveClosure, ShenandoahUpdateRefsClosure>
2219       cleaning_task(timing_phase, &is_alive, &keep_alive, num_workers);
2220     _workers->run_task(&cleaning_task);
2221   } else {
2222     ShenandoahIsAliveClosure is_alive;
2223 #ifdef ASSERT
2224     ShenandoahAssertNotForwardedClosure verify_cl;
2225     ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, ShenandoahAssertNotForwardedClosure>
2226       cleaning_task(timing_phase, &is_alive, &verify_cl, num_workers);
2227 #else
2228     ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, DoNothingClosure>
2229       cleaning_task(timing_phase, &is_alive, &do_nothing_cl, num_workers);
2230 #endif
2231     _workers->run_task(&cleaning_task);
2232   }
2233 }
2234 
2235 void ShenandoahHeap::parallel_cleaning(bool full_gc) {
2236   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2237   assert(is_stw_gc_in_progress(), "Only for Degenerated and Full GC");
2238   ShenandoahGCPhase phase(full_gc ?
2239                           ShenandoahPhaseTimings::full_gc_purge :
2240                           ShenandoahPhaseTimings::degen_gc_purge);
2241   stw_weak_refs(full_gc);
2242   stw_process_weak_roots(full_gc);
2243   stw_unload_classes(full_gc);
2244 }
2245 
2246 void ShenandoahHeap::set_has_forwarded_objects(bool cond) {
2247   set_gc_state_mask(HAS_FORWARDED, cond);
2248 }
2249 
2250 void ShenandoahHeap::set_unload_classes(bool uc) {
2251   _unload_classes.set_cond(uc);
2252 }
2253 
2254 bool ShenandoahHeap::unload_classes() const {
2255   return _unload_classes.is_set();
2256 }
2257 
2258 address ShenandoahHeap::in_cset_fast_test_addr() {
2259   ShenandoahHeap* heap = ShenandoahHeap::heap();
2260   assert(heap->collection_set() != NULL, "Sanity");
2261   return (address) heap->collection_set()->biased_map_address();
2262 }
2263 
2264 address ShenandoahHeap::gc_state_addr() {
2265   return (address) ShenandoahHeap::heap()->_gc_state.addr_of();
2266 }
2267 
2268 void ShenandoahHeap::reset_bytes_allocated_since_gc_start() {
2269   if (mode()->is_generational()) {
2270     young_generation()->reset_bytes_allocated_since_gc_start();
2271     old_generation()->reset_bytes_allocated_since_gc_start();
2272   }
2273 
2274   global_generation()->reset_bytes_allocated_since_gc_start();
2275 }
2276 
2277 void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) {
2278   _degenerated_gc_in_progress.set_cond(in_progress);
2279 }
2280 
2281 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {
2282   _full_gc_in_progress.set_cond(in_progress);
2283 }
2284 
2285 void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) {
2286   assert (is_full_gc_in_progress(), "should be");
2287   _full_gc_move_in_progress.set_cond(in_progress);
2288 }
2289 
2290 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {
2291   set_gc_state_mask(UPDATEREFS, in_progress);
2292 }
2293 
2294 void ShenandoahHeap::register_nmethod(nmethod* nm) {
2295   ShenandoahCodeRoots::register_nmethod(nm);
2296 }
2297 
2298 void ShenandoahHeap::unregister_nmethod(nmethod* nm) {
2299   ShenandoahCodeRoots::unregister_nmethod(nm);
2300 }
2301 
2302 void ShenandoahHeap::flush_nmethod(nmethod* nm) {
2303   ShenandoahCodeRoots::flush_nmethod(nm);
2304 }
2305 
2306 oop ShenandoahHeap::pin_object(JavaThread* thr, oop o) {
2307   heap_region_containing(o)->record_pin();
2308   return o;
2309 }
2310 
2311 void ShenandoahHeap::unpin_object(JavaThread* thr, oop o) {
2312   ShenandoahHeapRegion* r = heap_region_containing(o);
2313   assert(r != NULL, "Sanity");
2314   assert(r->pin_count() > 0, "Region " SIZE_FORMAT " should have non-zero pins", r->index());
2315   r->record_unpin();
2316 }
2317 
2318 void ShenandoahHeap::sync_pinned_region_status() {
2319   ShenandoahHeapLocker locker(lock());
2320 
2321   for (size_t i = 0; i < num_regions(); i++) {
2322     ShenandoahHeapRegion *r = get_region(i);
2323     if (r->is_active()) {
2324       if (r->is_pinned()) {
2325         if (r->pin_count() == 0) {
2326           r->make_unpinned();
2327         }
2328       } else {
2329         if (r->pin_count() > 0) {
2330           r->make_pinned();
2331         }
2332       }
2333     }
2334   }
2335 
2336   assert_pinned_region_status();
2337 }
2338 
2339 #ifdef ASSERT
2340 void ShenandoahHeap::assert_pinned_region_status() {
2341   for (size_t i = 0; i < num_regions(); i++) {
2342     ShenandoahHeapRegion* r = get_region(i);
2343     if (active_generation()->contains(r)) {
2344       assert((r->is_pinned() && r->pin_count() > 0) || (!r->is_pinned() && r->pin_count() == 0),
2345              "Region " SIZE_FORMAT " pinning status is inconsistent", i);
2346     }
2347   }
2348 }
2349 #endif
2350 
2351 ConcurrentGCTimer* ShenandoahHeap::gc_timer() const {
2352   return _gc_timer;
2353 }
2354 
2355 void ShenandoahHeap::prepare_concurrent_roots() {
2356   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2357   assert(!is_stw_gc_in_progress(), "Only concurrent GC");
2358   set_concurrent_strong_root_in_progress(!collection_set()->is_empty());
2359   set_concurrent_weak_root_in_progress(true);
2360   if (unload_classes()) {
2361     _unloader.prepare();
2362   }
2363 }
2364 
2365 void ShenandoahHeap::finish_concurrent_roots() {
2366   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2367   assert(!is_stw_gc_in_progress(), "Only concurrent GC");
2368   if (unload_classes()) {
2369     _unloader.finish();
2370   }
2371 }
2372 
2373 #ifdef ASSERT
2374 void ShenandoahHeap::assert_gc_workers(uint nworkers) {
2375   assert(nworkers > 0 && nworkers <= max_workers(), "Sanity");
2376 
2377   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
2378     if (UseDynamicNumberOfGCThreads) {
2379       assert(nworkers <= ParallelGCThreads, "Cannot use more than it has");
2380     } else {
2381       // Use ParallelGCThreads inside safepoints
2382       assert(nworkers == ParallelGCThreads, "Use ParallelGCThreads within safepoints");
2383     }
2384   } else {
2385     if (UseDynamicNumberOfGCThreads) {
2386       assert(nworkers <= ConcGCThreads, "Cannot use more than it has");
2387     } else {
2388       // Use ConcGCThreads outside safepoints
2389       assert(nworkers == ConcGCThreads, "Use ConcGCThreads outside safepoints");
2390     }
2391   }
2392 }
2393 #endif
2394 
2395 ShenandoahVerifier* ShenandoahHeap::verifier() {
2396   guarantee(ShenandoahVerify, "Should be enabled");
2397   assert (_verifier != NULL, "sanity");
2398   return _verifier;
2399 }
2400 
2401 template<bool CONCURRENT>
2402 class ShenandoahUpdateHeapRefsTask : public WorkerTask {
2403 private:
2404   ShenandoahHeap* _heap;
2405   ShenandoahRegionIterator* _regions;
2406 
2407 public:
2408   explicit ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions) :
2409     WorkerTask("Shenandoah Update References"),
2410     _heap(ShenandoahHeap::heap()),
2411     _regions(regions)
2412   {
2413   }
2414 
2415   void work(uint worker_id) {
2416     if (CONCURRENT) {
2417       ShenandoahConcurrentWorkerSession worker_session(worker_id);
2418       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
2419       do_work<ShenandoahConcUpdateRefsClosure>(worker_id);
2420     } else {
2421       ShenandoahParallelWorkerSession worker_session(worker_id);
2422       do_work<ShenandoahSTWUpdateRefsClosure>(worker_id);
2423     }
2424   }
2425 
2426 private:
2427   template<class T>
2428   void do_work(uint worker_id) {
2429     T cl;
2430     ShenandoahHeapRegion* r = _regions->next();
2431 
2432     // We update references for global, old, and young collections.
2433     assert(_heap->active_generation()->is_mark_complete(), "Expected complete marking");
2434     ShenandoahMarkingContext* const ctx = _heap->marking_context();
2435     bool is_mixed = _heap->collection_set()->has_old_regions();
2436     while (r != NULL) {
2437       HeapWord* update_watermark = r->get_update_watermark();
2438       assert (update_watermark >= r->bottom(), "sanity");
2439 
2440       log_debug(gc)("ShenandoahUpdateHeapRefsTask::do_work(%u) looking at region " SIZE_FORMAT, worker_id, r->index());
2441       if (r->is_active() && !r->is_cset()) {
2442         if (!_heap->mode()->is_generational() || (r->affiliation() == ShenandoahRegionAffiliation::YOUNG_GENERATION)) {
2443           _heap->marked_object_oop_iterate(r, &cl, update_watermark);
2444         } else if (r->affiliation() == ShenandoahRegionAffiliation::OLD_GENERATION) {
2445           if (_heap->active_generation()->generation_mode() == GLOBAL) {
2446             _heap->marked_object_oop_iterate(r, &cl, update_watermark);
2447           } else {
2448             // Old region in a young cycle or mixed cycle.
2449             if (!is_mixed) {
2450               // This is a young evac..
2451               _heap->card_scan()->process_region(r, &cl, true);
2452             } else {
2453               // This is a _mixed_evac.
2454               //
2455               // TODO: For _mixed_evac, consider building an old-gen remembered set that allows restricted updating
2456               // within old-gen HeapRegions.  This remembered set can be constructed by old-gen concurrent marking
2457               // and augmented by card marking.  For example, old-gen concurrent marking can remember for each old-gen
2458               // card which other old-gen regions it refers to: none, one-other specifically, multiple-other non-specific.
2459               // Update-references when _mixed_evac processess each old-gen memory range that has a traditional DIRTY
2460               // card or if the "old-gen remembered set" indicates that this card holds pointers specifically to an
2461               // old-gen region in the most recent collection set, or if this card holds pointers to other non-specific
2462               // old-gen heap regions.
2463               if (r->is_humongous()) {
2464                 r->oop_iterate_humongous(&cl);
2465               } else {
2466                 // This is a mixed evacuation.  Old regions that are candidates for collection have not been coalesced
2467                 // and filled.  Use mark bits to find objects that need to be updated.
2468                 //
2469                 // Future TODO: establish a second remembered set to identify which old-gen regions point to other old-gen
2470                 // regions which are in the collection set for a particular mixed evacuation.
2471                 HeapWord *p = r->bottom();
2472                 ShenandoahObjectToOopBoundedClosure<T> objs(&cl, p, update_watermark);
2473 
2474                 // Anything beyond update_watermark was allocated during evacuation.  Thus, it is known to not hold
2475                 // references to collection set objects.
2476                 while (p < update_watermark) {
2477                   oop obj = cast_to_oop(p);
2478                   if (ctx->is_marked(obj)) {
2479                     objs.do_object(obj);
2480                     p += obj->size();
2481                   } else {
2482                     // This object is not marked so we don't scan it.
2483                     HeapWord* tams = ctx->top_at_mark_start(r);
2484                     if (p >= tams) {
2485                       p += obj->size();
2486                     } else {
2487                       p = ctx->get_next_marked_addr(p, tams);
2488                     }
2489                   }
2490                 }
2491               }
2492             }
2493           }
2494         } else {
2495           // Because updating of references runs concurrently, it is possible that a FREE inactive region transitions
2496           // to a non-free active region while this loop is executing.  Whenever this happens, the changing of a region's
2497           // active status may propagate at a different speed than the changing of the region's affiliation.
2498 
2499           // When we reach this control point, it is because a race has allowed a region's is_active() status to be seen
2500           // by this thread before the region's affiliation() is seen by this thread.
2501 
2502           // It's ok for this race to occur because the newly transformed region does not have any references to be
2503           // updated.
2504 
2505           assert(r->get_update_watermark() == r->bottom(),
2506                  "%s Region " SIZE_FORMAT " is_active but not recognized as YOUNG or OLD so must be newly transitioned from FREE",
2507                  affiliation_name(r->affiliation()), r->index());
2508         }
2509       }
2510       if (ShenandoahPacing) {
2511         _heap->pacer()->report_updaterefs(pointer_delta(update_watermark, r->bottom()));
2512       }
2513       if (_heap->check_cancelled_gc_and_yield(CONCURRENT)) {
2514         return;
2515       }
2516       r = _regions->next();
2517     }
2518   }
2519 };
2520 
2521 void ShenandoahHeap::update_heap_references(bool concurrent) {
2522   assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
2523 
2524   if (concurrent) {
2525     ShenandoahUpdateHeapRefsTask<true> task(&_update_refs_iterator);
2526     workers()->run_task(&task);
2527   } else {
2528     ShenandoahUpdateHeapRefsTask<false> task(&_update_refs_iterator);
2529     workers()->run_task(&task);
2530   }
2531 }
2532 
2533 
2534 class ShenandoahFinalUpdateRefsUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
2535 private:
2536   ShenandoahMarkingContext* _ctx;
2537   ShenandoahHeapLock* const _lock;
2538   bool _is_generational;
2539 
2540 public:
2541   ShenandoahFinalUpdateRefsUpdateRegionStateClosure(
2542     ShenandoahMarkingContext* ctx) : _ctx(ctx), _lock(ShenandoahHeap::heap()->lock()),
2543                                      _is_generational(ShenandoahHeap::heap()->mode()->is_generational()) { }
2544 
2545   void heap_region_do(ShenandoahHeapRegion* r) {
2546 
2547     // Maintenance of region age must follow evacuation in order to account for evacuation allocations within survivor
2548     // regions.  We consult region age during the subsequent evacuation to determine whether certain objects need to
2549     // be promoted.
2550     if (_is_generational && r->is_young()) {
2551       HeapWord *tams = _ctx->top_at_mark_start(r);
2552       HeapWord *top = r->top();
2553 
2554       // Allocations move the watermark when top moves.  However compacting
2555       // objects will sometimes lower top beneath the watermark, after which,
2556       // attempts to read the watermark will assert out (watermark should not be
2557       // higher than top).
2558       if (top > tams) {
2559         // There have been allocations in this region since the start of the cycle.
2560         // Any objects new to this region must not assimilate elevated age.
2561         r->reset_age();
2562       } else if (ShenandoahHeap::heap()->is_aging_cycle()) {
2563         r->increment_age();
2564       }
2565     }
2566 
2567     // Drop unnecessary "pinned" state from regions that does not have CP marks
2568     // anymore, as this would allow trashing them.
2569     if (r->is_active()) {
2570       if (r->is_pinned()) {
2571         if (r->pin_count() == 0) {
2572           ShenandoahHeapLocker locker(_lock);
2573           r->make_unpinned();
2574         }
2575       } else {
2576         if (r->pin_count() > 0) {
2577           ShenandoahHeapLocker locker(_lock);
2578           r->make_pinned();
2579         }
2580       }
2581     }
2582   }
2583 
2584   bool is_thread_safe() { return true; }
2585 };
2586 
2587 void ShenandoahHeap::update_heap_region_states(bool concurrent) {
2588   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2589   assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
2590 
2591   {
2592     ShenandoahGCPhase phase(concurrent ?
2593                             ShenandoahPhaseTimings::final_update_refs_update_region_states :
2594                             ShenandoahPhaseTimings::degen_gc_final_update_refs_update_region_states);
2595     ShenandoahFinalUpdateRefsUpdateRegionStateClosure cl (active_generation()->complete_marking_context());
2596     parallel_heap_region_iterate(&cl);
2597 
2598     assert_pinned_region_status();
2599   }
2600 
2601   {
2602     ShenandoahGCPhase phase(concurrent ?
2603                             ShenandoahPhaseTimings::final_update_refs_trash_cset :
2604                             ShenandoahPhaseTimings::degen_gc_final_update_refs_trash_cset);
2605     trash_cset_regions();
2606   }
2607 }
2608 
2609 void ShenandoahHeap::rebuild_free_set(bool concurrent) {
2610   {
2611     ShenandoahGCPhase phase(concurrent ?
2612                             ShenandoahPhaseTimings::final_update_refs_rebuild_freeset :
2613                             ShenandoahPhaseTimings::degen_gc_final_update_refs_rebuild_freeset);
2614     ShenandoahHeapLocker locker(lock());
2615     _free_set->rebuild();
2616   }
2617 }
2618 
2619 void ShenandoahHeap::print_extended_on(outputStream *st) const {
2620   print_on(st);
2621   print_heap_regions_on(st);
2622 }
2623 
2624 bool ShenandoahHeap::is_bitmap_slice_committed(ShenandoahHeapRegion* r, bool skip_self) {
2625   size_t slice = r->index() / _bitmap_regions_per_slice;
2626 
2627   size_t regions_from = _bitmap_regions_per_slice * slice;
2628   size_t regions_to   = MIN2(num_regions(), _bitmap_regions_per_slice * (slice + 1));
2629   for (size_t g = regions_from; g < regions_to; g++) {
2630     assert (g / _bitmap_regions_per_slice == slice, "same slice");
2631     if (skip_self && g == r->index()) continue;
2632     if (get_region(g)->is_committed()) {
2633       return true;
2634     }
2635   }
2636   return false;
2637 }
2638 
2639 bool ShenandoahHeap::commit_bitmap_slice(ShenandoahHeapRegion* r) {
2640   shenandoah_assert_heaplocked();
2641 
2642   // Bitmaps in special regions do not need commits
2643   if (_bitmap_region_special) {
2644     return true;
2645   }
2646 
2647   if (is_bitmap_slice_committed(r, true)) {
2648     // Some other region from the group is already committed, meaning the bitmap
2649     // slice is already committed, we exit right away.
2650     return true;
2651   }
2652 
2653   // Commit the bitmap slice:
2654   size_t slice = r->index() / _bitmap_regions_per_slice;
2655   size_t off = _bitmap_bytes_per_slice * slice;
2656   size_t len = _bitmap_bytes_per_slice;
2657   char* start = (char*) _bitmap_region.start() + off;
2658 
2659   if (!os::commit_memory(start, len, false)) {
2660     return false;
2661   }
2662 
2663   if (AlwaysPreTouch) {
2664     os::pretouch_memory(start, start + len, _pretouch_bitmap_page_size);
2665   }
2666 
2667   return true;
2668 }
2669 
2670 bool ShenandoahHeap::uncommit_bitmap_slice(ShenandoahHeapRegion *r) {
2671   shenandoah_assert_heaplocked();
2672 
2673   // Bitmaps in special regions do not need uncommits
2674   if (_bitmap_region_special) {
2675     return true;
2676   }
2677 
2678   if (is_bitmap_slice_committed(r, true)) {
2679     // Some other region from the group is still committed, meaning the bitmap
2680     // slice is should stay committed, exit right away.
2681     return true;
2682   }
2683 
2684   // Uncommit the bitmap slice:
2685   size_t slice = r->index() / _bitmap_regions_per_slice;
2686   size_t off = _bitmap_bytes_per_slice * slice;
2687   size_t len = _bitmap_bytes_per_slice;
2688   if (!os::uncommit_memory((char*)_bitmap_region.start() + off, len)) {
2689     return false;
2690   }
2691   return true;
2692 }
2693 
2694 void ShenandoahHeap::safepoint_synchronize_begin() {
2695   if (ShenandoahSuspendibleWorkers || UseStringDeduplication) {
2696     SuspendibleThreadSet::synchronize();
2697   }
2698 }
2699 
2700 void ShenandoahHeap::safepoint_synchronize_end() {
2701   if (ShenandoahSuspendibleWorkers || UseStringDeduplication) {
2702     SuspendibleThreadSet::desynchronize();
2703   }
2704 }
2705 
2706 void ShenandoahHeap::entry_uncommit(double shrink_before, size_t shrink_until) {
2707   static const char *msg = "Concurrent uncommit";
2708   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_uncommit, true /* log_heap_usage */);
2709   EventMark em("%s", msg);
2710 
2711   op_uncommit(shrink_before, shrink_until);
2712 }
2713 
2714 void ShenandoahHeap::try_inject_alloc_failure() {
2715   if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) {
2716     _inject_alloc_failure.set();
2717     os::naked_short_sleep(1);
2718     if (cancelled_gc()) {
2719       log_info(gc)("Allocation failure was successfully injected");
2720     }
2721   }
2722 }
2723 
2724 bool ShenandoahHeap::should_inject_alloc_failure() {
2725   return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset();
2726 }
2727 
2728 void ShenandoahHeap::initialize_serviceability() {
2729   if (mode()->is_generational()) {
2730     _young_gen_memory_pool = new ShenandoahYoungGenMemoryPool(this);
2731     _old_gen_memory_pool = new ShenandoahOldGenMemoryPool(this);
2732     _cycle_memory_manager.add_pool(_young_gen_memory_pool);
2733     _cycle_memory_manager.add_pool(_old_gen_memory_pool);
2734     _stw_memory_manager.add_pool(_young_gen_memory_pool);
2735     _stw_memory_manager.add_pool(_old_gen_memory_pool);
2736   } else {
2737     _memory_pool = new ShenandoahMemoryPool(this);
2738     _cycle_memory_manager.add_pool(_memory_pool);
2739     _stw_memory_manager.add_pool(_memory_pool);
2740   }
2741 }
2742 
2743 GrowableArray<GCMemoryManager*> ShenandoahHeap::memory_managers() {
2744   GrowableArray<GCMemoryManager*> memory_managers(2);
2745   memory_managers.append(&_cycle_memory_manager);
2746   memory_managers.append(&_stw_memory_manager);
2747   return memory_managers;
2748 }
2749 
2750 GrowableArray<MemoryPool*> ShenandoahHeap::memory_pools() {
2751   GrowableArray<MemoryPool*> memory_pools(1);
2752   if (mode()->is_generational()) {
2753     memory_pools.append(_young_gen_memory_pool);
2754     memory_pools.append(_old_gen_memory_pool);
2755   } else {
2756     memory_pools.append(_memory_pool);
2757   }
2758   return memory_pools;
2759 }
2760 
2761 MemoryUsage ShenandoahHeap::memory_usage() {
2762   return MemoryUsage(_initial_size, used(), committed(), max_capacity());
2763 }
2764 
2765 ShenandoahRegionIterator::ShenandoahRegionIterator() :
2766   _heap(ShenandoahHeap::heap()),
2767   _index(0) {}
2768 
2769 ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) :
2770   _heap(heap),
2771   _index(0) {}
2772 
2773 void ShenandoahRegionIterator::reset() {
2774   _index = 0;
2775 }
2776 
2777 bool ShenandoahRegionIterator::has_next() const {
2778   return _index < _heap->num_regions();
2779 }
2780 
2781 char ShenandoahHeap::gc_state() const {
2782   return _gc_state.raw_value();
2783 }
2784 
2785 ShenandoahLiveData* ShenandoahHeap::get_liveness_cache(uint worker_id) {
2786 #ifdef ASSERT
2787   assert(_liveness_cache != NULL, "sanity");
2788   assert(worker_id < _max_workers, "sanity");
2789   for (uint i = 0; i < num_regions(); i++) {
2790     assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty");
2791   }
2792 #endif
2793   return _liveness_cache[worker_id];
2794 }
2795 
2796 void ShenandoahHeap::flush_liveness_cache(uint worker_id) {
2797   assert(worker_id < _max_workers, "sanity");
2798   assert(_liveness_cache != NULL, "sanity");
2799   ShenandoahLiveData* ld = _liveness_cache[worker_id];
2800 
2801   for (uint i = 0; i < num_regions(); i++) {
2802     ShenandoahLiveData live = ld[i];
2803     if (live > 0) {
2804       ShenandoahHeapRegion* r = get_region(i);
2805       r->increase_live_data_gc_words(live);
2806       ld[i] = 0;
2807     }
2808   }
2809 }
2810 
2811 void ShenandoahHeap::transfer_old_pointers_from_satb() {
2812   ((ShenandoahOldGeneration*) _old_generation)->transfer_pointers_from_satb();
2813 }
2814 
2815 template<>
2816 void ShenandoahGenerationRegionClosure<YOUNG>::heap_region_do(ShenandoahHeapRegion* region) {
2817   // Visit young and free regions
2818   if (region->affiliation() != OLD_GENERATION) {
2819     _cl->heap_region_do(region);
2820   }
2821 }
2822 
2823 template<>
2824 void ShenandoahGenerationRegionClosure<OLD>::heap_region_do(ShenandoahHeapRegion* region) {
2825   // Visit old and free regions
2826   if (region->affiliation() != YOUNG_GENERATION) {
2827     _cl->heap_region_do(region);
2828   }
2829 }
2830 
2831 template<>
2832 void ShenandoahGenerationRegionClosure<GLOBAL>::heap_region_do(ShenandoahHeapRegion* region) {
2833   _cl->heap_region_do(region);
2834 }
2835 
2836 // Assure that the remember set has a dirty card everywhere there is an interesting pointer.
2837 // This examines the read_card_table between bottom() and top() since all PLABS are retired
2838 // before the safepoint for init_mark.  Actually, we retire them before update-references and don't
2839 // restore them until the start of evacuation.
2840 void ShenandoahHeap::verify_rem_set_at_mark() {
2841   shenandoah_assert_safepoint();
2842   assert(mode()->is_generational(), "Only verify remembered set for generational operational modes");
2843 
2844   ShenandoahRegionIterator iterator;
2845   RememberedScanner* scanner = card_scan();
2846   ShenandoahVerifyRemSetClosure check_interesting_pointers(true);
2847   ShenandoahMarkingContext* ctx;
2848 
2849   log_debug(gc)("Verifying remembered set at %s mark", doing_mixed_evacuations()? "mixed": "young");
2850 
2851   if (doing_mixed_evacuations() ||
2852       is_concurrent_prep_for_mixed_evacuation_in_progress() || active_generation()->generation_mode() == GLOBAL) {
2853     ctx = complete_marking_context();
2854   } else {
2855     ctx = nullptr;
2856   }
2857 
2858   while (iterator.has_next()) {
2859     ShenandoahHeapRegion* r = iterator.next();
2860     if (r == nullptr)
2861       break;
2862     if (r->is_old() && r->is_active()) {
2863       HeapWord* obj_addr = r->bottom();
2864       if (r->is_humongous_start()) {
2865         oop obj = cast_to_oop(obj_addr);
2866         if (!ctx || ctx->is_marked(obj)) {
2867           // For humongous objects, the typical object is an array, so the following checks may be overkill
2868           // For regular objects (not object arrays), if the card holding the start of the object is dirty,
2869           // we do not need to verify that cards spanning interesting pointers within this object are dirty.
2870           if (!scanner->is_card_dirty(obj_addr) || obj->is_objArray()) {
2871             obj->oop_iterate(&check_interesting_pointers);
2872           }
2873           // else, object's start is marked dirty and obj is not an objArray, so any interesting pointers are covered
2874         }
2875         // else, this humongous object is not marked so no need to verify its internal pointers
2876         if (!scanner->verify_registration(obj_addr, ctx)) {
2877           ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, obj_addr, NULL,
2878                                           "Verify init-mark remembered set violation", "object not properly registered", __FILE__, __LINE__);
2879         }
2880       } else if (!r->is_humongous()) {
2881         HeapWord* top = r->top();
2882         while (obj_addr < top) {
2883           oop obj = cast_to_oop(obj_addr);
2884           // ctx->is_marked() returns true if mark bit set (TAMS not relevant during init mark)
2885           if (!ctx || ctx->is_marked(obj)) {
2886             // For regular objects (not object arrays), if the card holding the start of the object is dirty,
2887             // we do not need to verify that cards spanning interesting pointers within this object are dirty.
2888             if (!scanner->is_card_dirty(obj_addr) || obj->is_objArray()) {
2889               obj->oop_iterate(&check_interesting_pointers);
2890             }
2891             // else, object's start is marked dirty and obj is not an objArray, so any interesting pointers are covered
2892             if (!scanner->verify_registration(obj_addr, ctx)) {
2893               ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, obj_addr, NULL,
2894                                             "Verify init-mark remembered set violation", "object not properly registered", __FILE__, __LINE__);
2895             }
2896             obj_addr += obj->size();
2897           } else {
2898             // This object is not live so we don't verify dirty cards contained therein
2899             assert(ctx->top_at_mark_start(r) == top, "Expect tams == top at start of mark.");
2900             obj_addr = ctx->get_next_marked_addr(obj_addr, top);
2901           }
2902         }
2903       } // else, we ignore humongous continuation region
2904     } // else, this is not an OLD region so we ignore it
2905   } // all regions have been processed
2906 }
2907 
2908 void ShenandoahHeap::help_verify_region_rem_set(ShenandoahHeapRegion* r, ShenandoahMarkingContext* ctx, HeapWord* from,
2909                                                 HeapWord* top, HeapWord* registration_watermark, const char* message) {
2910   RememberedScanner* scanner = card_scan();
2911   ShenandoahVerifyRemSetClosure check_interesting_pointers(false);
2912 
2913   HeapWord* obj_addr = from;
2914   if (r->is_humongous_start()) {
2915     oop obj = cast_to_oop(obj_addr);
2916     if (!ctx || ctx->is_marked(obj)) {
2917       size_t card_index = scanner->card_index_for_addr(obj_addr);
2918       // For humongous objects, the typical object is an array, so the following checks may be overkill
2919       // For regular objects (not object arrays), if the card holding the start of the object is dirty,
2920       // we do not need to verify that cards spanning interesting pointers within this object are dirty.
2921       if (!scanner->is_write_card_dirty(card_index) || obj->is_objArray()) {
2922         obj->oop_iterate(&check_interesting_pointers);
2923       }
2924       // else, object's start is marked dirty and obj is not an objArray, so any interesting pointers are covered
2925     }
2926     // else, this humongous object is not live so no need to verify its internal pointers
2927 
2928     if ((obj_addr < registration_watermark) && !scanner->verify_registration(obj_addr, ctx)) {
2929       ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, obj_addr, NULL, message,
2930                                        "object not properly registered", __FILE__, __LINE__);
2931     }
2932   } else if (!r->is_humongous()) {
2933     while (obj_addr < top) {
2934       oop obj = cast_to_oop(obj_addr);
2935       // ctx->is_marked() returns true if mark bit set or if obj above TAMS.
2936       if (!ctx || ctx->is_marked(obj)) {
2937         size_t card_index = scanner->card_index_for_addr(obj_addr);
2938         // For regular objects (not object arrays), if the card holding the start of the object is dirty,
2939         // we do not need to verify that cards spanning interesting pointers within this object are dirty.
2940         if (!scanner->is_write_card_dirty(card_index) || obj->is_objArray()) {
2941           obj->oop_iterate(&check_interesting_pointers);
2942         }
2943         // else, object's start is marked dirty and obj is not an objArray, so any interesting pointers are covered
2944 
2945         if ((obj_addr < registration_watermark) && !scanner->verify_registration(obj_addr, ctx)) {
2946           ShenandoahAsserts::print_failure(ShenandoahAsserts::_safe_all, obj, obj_addr, NULL, message,
2947                                            "object not properly registered", __FILE__, __LINE__);
2948         }
2949         obj_addr += obj->size();
2950       } else {
2951         // This object is not live so we don't verify dirty cards contained therein
2952         HeapWord* tams = ctx->top_at_mark_start(r);
2953         obj_addr = ctx->get_next_marked_addr(obj_addr, tams);
2954       }
2955     }
2956   }
2957 }
2958 
2959 void ShenandoahHeap::verify_rem_set_after_full_gc() {
2960   shenandoah_assert_safepoint();
2961   assert(mode()->is_generational(), "Only verify remembered set for generational operational modes");
2962 
2963   ShenandoahRegionIterator iterator;
2964 
2965   while (iterator.has_next()) {
2966     ShenandoahHeapRegion* r = iterator.next();
2967     if (r == nullptr)
2968       break;
2969     if (r->is_old() && !r->is_cset()) {
2970       help_verify_region_rem_set(r, nullptr, r->bottom(), r->top(), r->top(), "Remembered set violation at end of Full GC");
2971     }
2972   }
2973 }
2974 
2975 // Assure that the remember set has a dirty card everywhere there is an interesting pointer.  Even though
2976 // the update-references scan of remembered set only examines cards up to update_watermark, the remembered
2977 // set should be valid through top.  This examines the write_card_table between bottom() and top() because
2978 // all PLABS are retired immediately before the start of update refs.
2979 void ShenandoahHeap::verify_rem_set_at_update_ref() {
2980   shenandoah_assert_safepoint();
2981   assert(mode()->is_generational(), "Only verify remembered set for generational operational modes");
2982 
2983   ShenandoahRegionIterator iterator;
2984   ShenandoahMarkingContext* ctx;
2985 
2986   if (doing_mixed_evacuations() ||
2987       is_concurrent_prep_for_mixed_evacuation_in_progress() || active_generation()->generation_mode() == GLOBAL) {
2988     ctx = complete_marking_context();
2989   } else {
2990     ctx = nullptr;
2991   }
2992 
2993   while (iterator.has_next()) {
2994     ShenandoahHeapRegion* r = iterator.next();
2995     if (r == nullptr)
2996       break;
2997     if (r->is_old() && !r->is_cset()) {
2998       help_verify_region_rem_set(r, ctx, r->bottom(), r->top(), r->get_update_watermark(),
2999                                  "Remembered set violation at init-update-references");
3000     }
3001   }
3002 }
3003 
3004 ShenandoahGeneration* ShenandoahHeap::generation_for(ShenandoahRegionAffiliation affiliation) const {
3005   if (!mode()->is_generational()) {
3006     return global_generation();
3007   } else if (affiliation == YOUNG_GENERATION) {
3008     return young_generation();
3009   } else if (affiliation == OLD_GENERATION) {
3010     return old_generation();
3011   }
3012 
3013   ShouldNotReachHere();
3014   return nullptr;
3015 }