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