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/slidingForwarding.hpp"
  36 #include "gc/shared/tlab_globals.hpp"
  37 
  38 #include "gc/shenandoah/shenandoahBarrierSet.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/shenandoahFreeSet.hpp"
  45 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  46 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  47 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp"
  48 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  49 #include "gc/shenandoah/shenandoahInitLogger.hpp"
  50 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp"
  51 #include "gc/shenandoah/shenandoahMemoryPool.hpp"
  52 #include "gc/shenandoah/shenandoahMetrics.hpp"
  53 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
  54 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
  55 #include "gc/shenandoah/shenandoahPacer.inline.hpp"
  56 #include "gc/shenandoah/shenandoahPadding.hpp"
  57 #include "gc/shenandoah/shenandoahParallelCleaning.inline.hpp"
  58 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp"
  59 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp"
  60 #include "gc/shenandoah/shenandoahStringDedup.hpp"
  61 #include "gc/shenandoah/shenandoahSTWMark.hpp"
  62 #include "gc/shenandoah/shenandoahUtils.hpp"
  63 #include "gc/shenandoah/shenandoahVerifier.hpp"
  64 #include "gc/shenandoah/shenandoahCodeRoots.hpp"
  65 #include "gc/shenandoah/shenandoahVMOperations.hpp"
  66 #include "gc/shenandoah/shenandoahWorkGroup.hpp"
  67 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
  68 #include "gc/shenandoah/mode/shenandoahIUMode.hpp"
  69 #include "gc/shenandoah/mode/shenandoahPassiveMode.hpp"
  70 #include "gc/shenandoah/mode/shenandoahSATBMode.hpp"
  71 #if INCLUDE_JFR
  72 #include "gc/shenandoah/shenandoahJfrSupport.hpp"
  73 #endif
  74 
  75 #include "classfile/systemDictionary.hpp"
  76 #include "memory/classLoaderMetaspace.hpp"
  77 #include "memory/metaspaceUtils.hpp"
  78 #include "oops/compressedOops.inline.hpp"
  79 #include "prims/jvmtiTagMap.hpp"
  80 #include "runtime/atomic.hpp"
  81 #include "runtime/globals.hpp"
  82 #include "runtime/interfaceSupport.inline.hpp"
  83 #include "runtime/java.hpp"
  84 #include "runtime/orderAccess.hpp"
  85 #include "runtime/safepointMechanism.hpp"
  86 #include "runtime/vmThread.hpp"
  87 #include "services/mallocTracker.hpp"
  88 #include "services/memTracker.hpp"
  89 #include "utilities/events.hpp"
  90 #include "utilities/powerOfTwo.hpp"
  91 
  92 class ShenandoahPretouchHeapTask : public AbstractGangTask {
  93 private:
  94   ShenandoahRegionIterator _regions;
  95   const size_t _page_size;
  96 public:
  97   ShenandoahPretouchHeapTask(size_t page_size) :
  98     AbstractGangTask("Shenandoah Pretouch Heap"),
  99     _page_size(page_size) {}
 100 
 101   virtual void work(uint worker_id) {
 102     ShenandoahHeapRegion* r = _regions.next();
 103     while (r != NULL) {
 104       if (r->is_committed()) {
 105         os::pretouch_memory(r->bottom(), r->end(), _page_size);
 106       }
 107       r = _regions.next();
 108     }
 109   }
 110 };
 111 
 112 class ShenandoahPretouchBitmapTask : public AbstractGangTask {
 113 private:
 114   ShenandoahRegionIterator _regions;
 115   char* _bitmap_base;
 116   const size_t _bitmap_size;
 117   const size_t _page_size;
 118 public:
 119   ShenandoahPretouchBitmapTask(char* bitmap_base, size_t bitmap_size, size_t page_size) :
 120     AbstractGangTask("Shenandoah Pretouch Bitmap"),
 121     _bitmap_base(bitmap_base),
 122     _bitmap_size(bitmap_size),
 123     _page_size(page_size) {}
 124 
 125   virtual void work(uint worker_id) {
 126     ShenandoahHeapRegion* r = _regions.next();
 127     while (r != NULL) {
 128       size_t start = r->index()       * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
 129       size_t end   = (r->index() + 1) * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
 130       assert (end <= _bitmap_size, "end is sane: " SIZE_FORMAT " < " SIZE_FORMAT, end, _bitmap_size);
 131 
 132       if (r->is_committed()) {
 133         os::pretouch_memory(_bitmap_base + start, _bitmap_base + end, _page_size);
 134       }
 135 
 136       r = _regions.next();
 137     }
 138   }
 139 };
 140 
 141 jint ShenandoahHeap::initialize() {
 142   //
 143   // Figure out heap sizing
 144   //
 145 
 146   size_t init_byte_size = InitialHeapSize;
 147   size_t min_byte_size  = MinHeapSize;
 148   size_t max_byte_size  = MaxHeapSize;
 149   size_t heap_alignment = HeapAlignment;
 150 
 151   size_t reg_size_bytes = ShenandoahHeapRegion::region_size_bytes();
 152 
 153   Universe::check_alignment(max_byte_size,  reg_size_bytes, "Shenandoah heap");
 154   Universe::check_alignment(init_byte_size, reg_size_bytes, "Shenandoah heap");
 155 
 156   _num_regions = ShenandoahHeapRegion::region_count();
 157   assert(_num_regions == (max_byte_size / reg_size_bytes),
 158          "Regions should cover entire heap exactly: " SIZE_FORMAT " != " SIZE_FORMAT "/" SIZE_FORMAT,
 159          _num_regions, max_byte_size, reg_size_bytes);
 160 
 161   // Now we know the number of regions, initialize the heuristics.
 162   initialize_heuristics();
 163 
 164   size_t num_committed_regions = init_byte_size / reg_size_bytes;
 165   num_committed_regions = MIN2(num_committed_regions, _num_regions);
 166   assert(num_committed_regions <= _num_regions, "sanity");
 167   _initial_size = num_committed_regions * reg_size_bytes;
 168 
 169   size_t num_min_regions = min_byte_size / reg_size_bytes;
 170   num_min_regions = MIN2(num_min_regions, _num_regions);
 171   assert(num_min_regions <= _num_regions, "sanity");
 172   _minimum_size = num_min_regions * reg_size_bytes;
 173 
 174   // Default to max heap size.
 175   _soft_max_size = _num_regions * reg_size_bytes;
 176 
 177   _committed = _initial_size;
 178 
 179   size_t heap_page_size   = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 180   size_t bitmap_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 181   size_t region_page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 182 
 183   //
 184   // Reserve and commit memory for heap
 185   //
 186 
 187   ReservedHeapSpace heap_rs = Universe::reserve_heap(max_byte_size, heap_alignment);
 188   initialize_reserved_region(heap_rs);
 189   _heap_region = MemRegion((HeapWord*)heap_rs.base(), heap_rs.size() / HeapWordSize);
 190   _heap_region_special = heap_rs.special();
 191 
 192   assert((((size_t) base()) & ShenandoahHeapRegion::region_size_bytes_mask()) == 0,
 193          "Misaligned heap: " PTR_FORMAT, p2i(base()));
 194 
 195 #if SHENANDOAH_OPTIMIZED_MARKTASK
 196   // The optimized ShenandoahMarkTask takes some bits away from the full object bits.
 197   // Fail if we ever attempt to address more than we can.
 198   if ((uintptr_t)heap_rs.end() >= ShenandoahMarkTask::max_addressable()) {
 199     FormatBuffer<512> buf("Shenandoah reserved [" PTR_FORMAT ", " PTR_FORMAT") for the heap, \n"
 200                           "but max object address is " PTR_FORMAT ". Try to reduce heap size, or try other \n"
 201                           "VM options that allocate heap at lower addresses (HeapBaseMinAddress, AllocateHeapAt, etc).",
 202                 p2i(heap_rs.base()), p2i(heap_rs.end()), ShenandoahMarkTask::max_addressable());
 203     vm_exit_during_initialization("Fatal Error", buf);
 204   }
 205 #endif
 206 
 207   ReservedSpace sh_rs = heap_rs.first_part(max_byte_size);
 208   if (!_heap_region_special) {
 209     os::commit_memory_or_exit(sh_rs.base(), _initial_size, heap_alignment, false,
 210                               "Cannot commit heap memory");
 211   }
 212 
 213   //
 214   // Reserve and commit memory for bitmap(s)
 215   //
 216 
 217   _bitmap_size = ShenandoahMarkBitMap::compute_size(heap_rs.size());
 218   _bitmap_size = align_up(_bitmap_size, bitmap_page_size);
 219 
 220   size_t bitmap_bytes_per_region = reg_size_bytes / ShenandoahMarkBitMap::heap_map_factor();
 221 
 222   guarantee(bitmap_bytes_per_region != 0,
 223             "Bitmap bytes per region should not be zero");
 224   guarantee(is_power_of_2(bitmap_bytes_per_region),
 225             "Bitmap bytes per region should be power of two: " SIZE_FORMAT, bitmap_bytes_per_region);
 226 
 227   if (bitmap_page_size > bitmap_bytes_per_region) {
 228     _bitmap_regions_per_slice = bitmap_page_size / bitmap_bytes_per_region;
 229     _bitmap_bytes_per_slice = bitmap_page_size;
 230   } else {
 231     _bitmap_regions_per_slice = 1;
 232     _bitmap_bytes_per_slice = bitmap_bytes_per_region;
 233   }
 234 
 235   guarantee(_bitmap_regions_per_slice >= 1,
 236             "Should have at least one region per slice: " SIZE_FORMAT,
 237             _bitmap_regions_per_slice);
 238 
 239   guarantee(((_bitmap_bytes_per_slice) % bitmap_page_size) == 0,
 240             "Bitmap slices should be page-granular: bps = " SIZE_FORMAT ", page size = " SIZE_FORMAT,
 241             _bitmap_bytes_per_slice, bitmap_page_size);
 242 
 243   ReservedSpace bitmap(_bitmap_size, bitmap_page_size);
 244   MemTracker::record_virtual_memory_type(bitmap.base(), mtGC);
 245   _bitmap_region = MemRegion((HeapWord*) bitmap.base(), bitmap.size() / HeapWordSize);
 246   _bitmap_region_special = bitmap.special();
 247 
 248   size_t bitmap_init_commit = _bitmap_bytes_per_slice *
 249                               align_up(num_committed_regions, _bitmap_regions_per_slice) / _bitmap_regions_per_slice;
 250   bitmap_init_commit = MIN2(_bitmap_size, bitmap_init_commit);
 251   if (!_bitmap_region_special) {
 252     os::commit_memory_or_exit((char *) _bitmap_region.start(), bitmap_init_commit, bitmap_page_size, false,
 253                               "Cannot commit bitmap memory");
 254   }
 255 
 256   _marking_context = new ShenandoahMarkingContext(_heap_region, _bitmap_region, _num_regions, _max_workers);
 257 
 258   if (ShenandoahVerify) {
 259     ReservedSpace verify_bitmap(_bitmap_size, bitmap_page_size);
 260     if (!verify_bitmap.special()) {
 261       os::commit_memory_or_exit(verify_bitmap.base(), verify_bitmap.size(), bitmap_page_size, false,
 262                                 "Cannot commit verification bitmap memory");
 263     }
 264     MemTracker::record_virtual_memory_type(verify_bitmap.base(), mtGC);
 265     MemRegion verify_bitmap_region = MemRegion((HeapWord *) verify_bitmap.base(), verify_bitmap.size() / HeapWordSize);
 266     _verification_bit_map.initialize(_heap_region, verify_bitmap_region);
 267     _verifier = new ShenandoahVerifier(this, &_verification_bit_map);
 268   }
 269 
 270   // Reserve aux bitmap for use in object_iterate(). We don't commit it here.
 271   ReservedSpace aux_bitmap(_bitmap_size, bitmap_page_size);
 272   MemTracker::record_virtual_memory_type(aux_bitmap.base(), mtGC);
 273   _aux_bitmap_region = MemRegion((HeapWord*) aux_bitmap.base(), aux_bitmap.size() / HeapWordSize);
 274   _aux_bitmap_region_special = aux_bitmap.special();
 275   _aux_bit_map.initialize(_heap_region, _aux_bitmap_region);
 276 
 277   //
 278   // Create regions and region sets
 279   //
 280   size_t region_align = align_up(sizeof(ShenandoahHeapRegion), SHENANDOAH_CACHE_LINE_SIZE);
 281   size_t region_storage_size = align_up(region_align * _num_regions, region_page_size);
 282   region_storage_size = align_up(region_storage_size, os::vm_allocation_granularity());
 283 
 284   ReservedSpace region_storage(region_storage_size, region_page_size);
 285   MemTracker::record_virtual_memory_type(region_storage.base(), mtGC);
 286   if (!region_storage.special()) {
 287     os::commit_memory_or_exit(region_storage.base(), region_storage_size, region_page_size, false,
 288                               "Cannot commit region memory");
 289   }
 290 
 291   // Try to fit the collection set bitmap at lower addresses. This optimizes code generation for cset checks.
 292   // Go up until a sensible limit (subject to encoding constraints) and try to reserve the space there.
 293   // If not successful, bite a bullet and allocate at whatever address.
 294   {
 295     size_t cset_align = MAX2<size_t>(os::vm_page_size(), os::vm_allocation_granularity());
 296     size_t cset_size = align_up(((size_t) sh_rs.base() + sh_rs.size()) >> ShenandoahHeapRegion::region_size_bytes_shift(), cset_align);
 297 
 298     uintptr_t min = round_up_power_of_2(cset_align);
 299     uintptr_t max = (1u << 30u);
 300 
 301     for (uintptr_t addr = min; addr <= max; addr <<= 1u) {
 302       char* req_addr = (char*)addr;
 303       assert(is_aligned(req_addr, cset_align), "Should be aligned");
 304       ReservedSpace cset_rs(cset_size, cset_align, os::vm_page_size(), req_addr);
 305       if (cset_rs.is_reserved()) {
 306         assert(cset_rs.base() == req_addr, "Allocated where requested: " PTR_FORMAT ", " PTR_FORMAT, p2i(cset_rs.base()), addr);
 307         _collection_set = new ShenandoahCollectionSet(this, cset_rs, sh_rs.base());
 308         break;
 309       }
 310     }
 311 
 312     if (_collection_set == NULL) {
 313       ReservedSpace cset_rs(cset_size, cset_align, os::vm_page_size());
 314       _collection_set = new ShenandoahCollectionSet(this, cset_rs, sh_rs.base());
 315     }
 316   }
 317 
 318   _regions = NEW_C_HEAP_ARRAY(ShenandoahHeapRegion*, _num_regions, mtGC);
 319   _free_set = new ShenandoahFreeSet(this, _num_regions);
 320 
 321   {
 322     ShenandoahHeapLocker locker(lock());
 323 
 324     for (size_t i = 0; i < _num_regions; i++) {
 325       HeapWord* start = (HeapWord*)sh_rs.base() + ShenandoahHeapRegion::region_size_words() * i;
 326       bool is_committed = i < num_committed_regions;
 327       void* loc = region_storage.base() + i * region_align;
 328 
 329       ShenandoahHeapRegion* r = new (loc) ShenandoahHeapRegion(start, i, is_committed);
 330       assert(is_aligned(r, SHENANDOAH_CACHE_LINE_SIZE), "Sanity");
 331 
 332       _marking_context->initialize_top_at_mark_start(r);
 333       _regions[i] = r;
 334       assert(!collection_set()->is_in(i), "New region should not be in collection set");
 335     }
 336 
 337     // Initialize to complete
 338     _marking_context->mark_complete();
 339 
 340     _free_set->rebuild();
 341   }
 342 
 343   if (AlwaysPreTouch) {
 344     // For NUMA, it is important to pre-touch the storage under bitmaps with worker threads,
 345     // before initialize() below zeroes it with initializing thread. For any given region,
 346     // we touch the region and the corresponding bitmaps from the same thread.
 347     ShenandoahPushWorkerScope scope(workers(), _max_workers, false);
 348 
 349     _pretouch_heap_page_size = heap_page_size;
 350     _pretouch_bitmap_page_size = bitmap_page_size;
 351 
 352 #ifdef LINUX
 353     // UseTransparentHugePages would madvise that backing memory can be coalesced into huge
 354     // pages. But, the kernel needs to know that every small page is used, in order to coalesce
 355     // them into huge one. Therefore, we need to pretouch with smaller pages.
 356     if (UseTransparentHugePages) {
 357       _pretouch_heap_page_size = (size_t)os::vm_page_size();
 358       _pretouch_bitmap_page_size = (size_t)os::vm_page_size();
 359     }
 360 #endif
 361 
 362     // OS memory managers may want to coalesce back-to-back pages. Make their jobs
 363     // simpler by pre-touching continuous spaces (heap and bitmap) separately.
 364 
 365     ShenandoahPretouchBitmapTask bcl(bitmap.base(), _bitmap_size, _pretouch_bitmap_page_size);
 366     _workers->run_task(&bcl);
 367 
 368     ShenandoahPretouchHeapTask hcl(_pretouch_heap_page_size);
 369     _workers->run_task(&hcl);
 370   }
 371 
 372   //
 373   // Initialize the rest of GC subsystems
 374   //
 375 
 376   _liveness_cache = NEW_C_HEAP_ARRAY(ShenandoahLiveData*, _max_workers, mtGC);
 377   for (uint worker = 0; worker < _max_workers; worker++) {
 378     _liveness_cache[worker] = NEW_C_HEAP_ARRAY(ShenandoahLiveData, _num_regions, mtGC);
 379     Copy::fill_to_bytes(_liveness_cache[worker], _num_regions * sizeof(ShenandoahLiveData));
 380   }
 381 
 382   // There should probably be Shenandoah-specific options for these,
 383   // just as there are G1-specific options.
 384   {
 385     ShenandoahSATBMarkQueueSet& satbqs = ShenandoahBarrierSet::satb_mark_queue_set();
 386     satbqs.set_process_completed_buffers_threshold(20); // G1SATBProcessCompletedThreshold
 387     satbqs.set_buffer_enqueue_threshold_percentage(60); // G1SATBBufferEnqueueingThresholdPercent
 388   }
 389 
 390   _monitoring_support = new ShenandoahMonitoringSupport(this);
 391   _phase_timings = new ShenandoahPhaseTimings(max_workers());
 392   ShenandoahCodeRoots::initialize();
 393 
 394   if (ShenandoahPacing) {
 395     _pacer = new ShenandoahPacer(this);
 396     _pacer->setup_for_idle();
 397   } else {
 398     _pacer = NULL;
 399   }
 400 
 401   _control_thread = new ShenandoahControlThread();
 402 
 403   ShenandoahInitLogger::print();
 404 
 405   SlidingForwarding::initialize(_heap_region, ShenandoahHeapRegion::region_size_words());
 406 
 407   return JNI_OK;
 408 }
 409 
 410 void ShenandoahHeap::initialize_mode() {
 411   if (ShenandoahGCMode != NULL) {
 412     if (strcmp(ShenandoahGCMode, "satb") == 0) {
 413       _gc_mode = new ShenandoahSATBMode();
 414     } else if (strcmp(ShenandoahGCMode, "iu") == 0) {
 415       _gc_mode = new ShenandoahIUMode();
 416     } else if (strcmp(ShenandoahGCMode, "passive") == 0) {
 417       _gc_mode = new ShenandoahPassiveMode();
 418     } else {
 419       vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option");
 420     }
 421   } else {
 422     vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option (null)");
 423   }
 424   _gc_mode->initialize_flags();
 425   if (_gc_mode->is_diagnostic() && !UnlockDiagnosticVMOptions) {
 426     vm_exit_during_initialization(
 427             err_msg("GC mode \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",
 428                     _gc_mode->name()));
 429   }
 430   if (_gc_mode->is_experimental() && !UnlockExperimentalVMOptions) {
 431     vm_exit_during_initialization(
 432             err_msg("GC mode \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",
 433                     _gc_mode->name()));
 434   }
 435 }
 436 
 437 void ShenandoahHeap::initialize_heuristics() {
 438   assert(_gc_mode != NULL, "Must be initialized");
 439   _heuristics = _gc_mode->initialize_heuristics();
 440 
 441   if (_heuristics->is_diagnostic() && !UnlockDiagnosticVMOptions) {
 442     vm_exit_during_initialization(
 443             err_msg("Heuristics \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.",
 444                     _heuristics->name()));
 445   }
 446   if (_heuristics->is_experimental() && !UnlockExperimentalVMOptions) {
 447     vm_exit_during_initialization(
 448             err_msg("Heuristics \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.",
 449                     _heuristics->name()));
 450   }
 451 }
 452 
 453 #ifdef _MSC_VER
 454 #pragma warning( push )
 455 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list
 456 #endif
 457 
 458 ShenandoahHeap::ShenandoahHeap(ShenandoahCollectorPolicy* policy) :
 459   CollectedHeap(),
 460   _initial_size(0),
 461   _used(0),
 462   _committed(0),
 463   _bytes_allocated_since_gc_start(0),
 464   _max_workers(MAX2(ConcGCThreads, ParallelGCThreads)),
 465   _workers(NULL),
 466   _safepoint_workers(NULL),
 467   _heap_region_special(false),
 468   _num_regions(0),
 469   _regions(NULL),
 470   _update_refs_iterator(this),
 471   _control_thread(NULL),
 472   _shenandoah_policy(policy),
 473   _gc_mode(NULL),
 474   _heuristics(NULL),
 475   _free_set(NULL),
 476   _pacer(NULL),
 477   _verifier(NULL),
 478   _phase_timings(NULL),
 479   _monitoring_support(NULL),
 480   _memory_pool(NULL),
 481   _stw_memory_manager("Shenandoah Pauses"),
 482   _cycle_memory_manager("Shenandoah Cycles"),
 483   _gc_timer(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
 484   _soft_ref_policy(),
 485   _log_min_obj_alignment_in_bytes(LogMinObjAlignmentInBytes),
 486   _ref_processor(new ShenandoahReferenceProcessor(MAX2(_max_workers, 1U))),
 487   _marking_context(NULL),
 488   _bitmap_size(0),
 489   _bitmap_regions_per_slice(0),
 490   _bitmap_bytes_per_slice(0),
 491   _bitmap_region_special(false),
 492   _aux_bitmap_region_special(false),
 493   _liveness_cache(NULL),
 494   _collection_set(NULL)
 495 {
 496   // Initialize GC mode early, so we can adjust barrier support
 497   initialize_mode();
 498   BarrierSet::set_barrier_set(new ShenandoahBarrierSet(this));
 499 
 500   _max_workers = MAX2(_max_workers, 1U);
 501   _workers = new ShenandoahWorkGang("Shenandoah GC Threads", _max_workers,
 502                             /* are_GC_task_threads */ true,
 503                             /* are_ConcurrentGC_threads */ true);
 504   if (_workers == NULL) {
 505     vm_exit_during_initialization("Failed necessary allocation.");
 506   } else {
 507     _workers->initialize_workers();
 508   }
 509 
 510   if (ParallelGCThreads > 1) {
 511     _safepoint_workers = new ShenandoahWorkGang("Safepoint Cleanup Thread",
 512                                                 ParallelGCThreads,
 513                       /* are_GC_task_threads */ false,
 514                  /* are_ConcurrentGC_threads */ false);
 515     _safepoint_workers->initialize_workers();
 516   }
 517 }
 518 
 519 #ifdef _MSC_VER
 520 #pragma warning( pop )
 521 #endif
 522 
 523 class ShenandoahResetBitmapTask : public AbstractGangTask {
 524 private:
 525   ShenandoahRegionIterator _regions;
 526 
 527 public:
 528   ShenandoahResetBitmapTask() :
 529     AbstractGangTask("Shenandoah Reset Bitmap") {}
 530 
 531   void work(uint worker_id) {
 532     ShenandoahHeapRegion* region = _regions.next();
 533     ShenandoahHeap* heap = ShenandoahHeap::heap();
 534     ShenandoahMarkingContext* const ctx = heap->marking_context();
 535     while (region != NULL) {
 536       if (heap->is_bitmap_slice_committed(region)) {
 537         ctx->clear_bitmap(region);
 538       }
 539       region = _regions.next();
 540     }
 541   }
 542 };
 543 
 544 void ShenandoahHeap::reset_mark_bitmap() {
 545   assert_gc_workers(_workers->active_workers());
 546   mark_incomplete_marking_context();
 547 
 548   ShenandoahResetBitmapTask task;
 549   _workers->run_task(&task);
 550 }
 551 
 552 void ShenandoahHeap::print_on(outputStream* st) const {
 553   st->print_cr("Shenandoah Heap");
 554   st->print_cr(" " SIZE_FORMAT "%s max, " SIZE_FORMAT "%s soft max, " SIZE_FORMAT "%s committed, " SIZE_FORMAT "%s used",
 555                byte_size_in_proper_unit(max_capacity()), proper_unit_for_byte_size(max_capacity()),
 556                byte_size_in_proper_unit(soft_max_capacity()), proper_unit_for_byte_size(soft_max_capacity()),
 557                byte_size_in_proper_unit(committed()),    proper_unit_for_byte_size(committed()),
 558                byte_size_in_proper_unit(used()),         proper_unit_for_byte_size(used()));
 559   st->print_cr(" " SIZE_FORMAT " x " SIZE_FORMAT"%s regions",
 560                num_regions(),
 561                byte_size_in_proper_unit(ShenandoahHeapRegion::region_size_bytes()),
 562                proper_unit_for_byte_size(ShenandoahHeapRegion::region_size_bytes()));
 563 
 564   st->print("Status: ");
 565   if (has_forwarded_objects())                 st->print("has forwarded objects, ");
 566   if (is_concurrent_mark_in_progress())        st->print("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     st->cr();
 602     print_heap_regions_on(st);
 603   }
 604 }
 605 
 606 class ShenandoahInitWorkerGCLABClosure : public ThreadClosure {
 607 public:
 608   void do_thread(Thread* thread) {
 609     assert(thread != NULL, "Sanity");
 610     assert(thread->is_Worker_thread(), "Only worker thread expected");
 611     ShenandoahThreadLocalData::initialize_gclab(thread);
 612   }
 613 };
 614 
 615 void ShenandoahHeap::post_initialize() {
 616   CollectedHeap::post_initialize();
 617   MutexLocker ml(Threads_lock);
 618 
 619   ShenandoahInitWorkerGCLABClosure init_gclabs;
 620   _workers->threads_do(&init_gclabs);
 621 
 622   // gclab can not be initialized early during VM startup, as it can not determinate its max_size.
 623   // Now, we will let WorkGang to initialize gclab when new worker is created.
 624   _workers->set_initialize_gclab();
 625   if (_safepoint_workers != NULL) {
 626     _safepoint_workers->threads_do(&init_gclabs);
 627     _safepoint_workers->set_initialize_gclab();
 628   }
 629 
 630   _heuristics->initialize();
 631 
 632   JFR_ONLY(ShenandoahJFRSupport::register_jfr_type_serializers());
 633 }
 634 
 635 size_t ShenandoahHeap::used() const {
 636   return Atomic::load(&_used);
 637 }
 638 
 639 size_t ShenandoahHeap::committed() const {
 640   return Atomic::load(&_committed);
 641 }
 642 
 643 void ShenandoahHeap::increase_committed(size_t bytes) {
 644   shenandoah_assert_heaplocked_or_safepoint();
 645   _committed += bytes;
 646 }
 647 
 648 void ShenandoahHeap::decrease_committed(size_t bytes) {
 649   shenandoah_assert_heaplocked_or_safepoint();
 650   _committed -= bytes;
 651 }
 652 
 653 void ShenandoahHeap::increase_used(size_t bytes) {
 654   Atomic::add(&_used, bytes, memory_order_relaxed);
 655 }
 656 
 657 void ShenandoahHeap::set_used(size_t bytes) {
 658   Atomic::store(&_used, bytes);
 659 }
 660 
 661 void ShenandoahHeap::decrease_used(size_t bytes) {
 662   assert(used() >= bytes, "never decrease heap size by more than we've left");
 663   Atomic::sub(&_used, bytes, memory_order_relaxed);
 664 }
 665 
 666 void ShenandoahHeap::increase_allocated(size_t bytes) {
 667   Atomic::add(&_bytes_allocated_since_gc_start, bytes, memory_order_relaxed);
 668 }
 669 
 670 void ShenandoahHeap::notify_mutator_alloc_words(size_t words, bool waste) {
 671   size_t bytes = words * HeapWordSize;
 672   if (!waste) {
 673     increase_used(bytes);
 674   }
 675   increase_allocated(bytes);
 676   if (ShenandoahPacing) {
 677     control_thread()->pacing_notify_alloc(words);
 678     if (waste) {
 679       pacer()->claim_for_alloc(words, true);
 680     }
 681   }
 682 }
 683 
 684 size_t ShenandoahHeap::capacity() const {
 685   return committed();
 686 }
 687 
 688 size_t ShenandoahHeap::max_capacity() const {
 689   return _num_regions * ShenandoahHeapRegion::region_size_bytes();
 690 }
 691 
 692 size_t ShenandoahHeap::soft_max_capacity() const {
 693   size_t v = Atomic::load(&_soft_max_size);
 694   assert(min_capacity() <= v && v <= max_capacity(),
 695          "Should be in bounds: " SIZE_FORMAT " <= " SIZE_FORMAT " <= " SIZE_FORMAT,
 696          min_capacity(), v, max_capacity());
 697   return v;
 698 }
 699 
 700 void ShenandoahHeap::set_soft_max_capacity(size_t v) {
 701   assert(min_capacity() <= v && v <= max_capacity(),
 702          "Should be in bounds: " SIZE_FORMAT " <= " SIZE_FORMAT " <= " SIZE_FORMAT,
 703          min_capacity(), v, max_capacity());
 704   Atomic::store(&_soft_max_size, v);
 705 }
 706 
 707 size_t ShenandoahHeap::min_capacity() const {
 708   return _minimum_size;
 709 }
 710 
 711 size_t ShenandoahHeap::initial_capacity() const {
 712   return _initial_size;
 713 }
 714 
 715 bool ShenandoahHeap::is_in(const void* p) const {
 716   HeapWord* heap_base = (HeapWord*) base();
 717   HeapWord* last_region_end = heap_base + ShenandoahHeapRegion::region_size_words() * num_regions();
 718   return p >= heap_base && p < last_region_end;
 719 }
 720 
 721 void ShenandoahHeap::op_uncommit(double shrink_before, size_t shrink_until) {
 722   assert (ShenandoahUncommit, "should be enabled");
 723 
 724   // Application allocates from the beginning of the heap, and GC allocates at
 725   // the end of it. It is more efficient to uncommit from the end, so that applications
 726   // could enjoy the near committed regions. GC allocations are much less frequent,
 727   // and therefore can accept the committing costs.
 728 
 729   size_t count = 0;
 730   for (size_t i = num_regions(); i > 0; i--) { // care about size_t underflow
 731     ShenandoahHeapRegion* r = get_region(i - 1);
 732     if (r->is_empty_committed() && (r->empty_time() < shrink_before)) {
 733       ShenandoahHeapLocker locker(lock());
 734       if (r->is_empty_committed()) {
 735         if (committed() < shrink_until + ShenandoahHeapRegion::region_size_bytes()) {
 736           break;
 737         }
 738 
 739         r->make_uncommitted();
 740         count++;
 741       }
 742     }
 743     SpinPause(); // allow allocators to take the lock
 744   }
 745 
 746   if (count > 0) {
 747     control_thread()->notify_heap_changed();
 748   }
 749 }
 750 
 751 HeapWord* ShenandoahHeap::allocate_from_gclab_slow(Thread* thread, size_t size) {
 752   // New object should fit the GCLAB size
 753   size_t min_size = MAX2(size, PLAB::min_size());
 754 
 755   // Figure out size of new GCLAB, looking back at heuristics. Expand aggressively.
 756   size_t new_size = ShenandoahThreadLocalData::gclab_size(thread) * 2;
 757   new_size = MIN2(new_size, PLAB::max_size());
 758   new_size = MAX2(new_size, PLAB::min_size());
 759 
 760   // Record new heuristic value even if we take any shortcut. This captures
 761   // the case when moderately-sized objects always take a shortcut. At some point,
 762   // heuristics should catch up with them.
 763   ShenandoahThreadLocalData::set_gclab_size(thread, new_size);
 764 
 765   if (new_size < size) {
 766     // New size still does not fit the object. Fall back to shared allocation.
 767     // This avoids retiring perfectly good GCLABs, when we encounter a large object.
 768     return NULL;
 769   }
 770 
 771   // Retire current GCLAB, and allocate a new one.
 772   PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
 773   gclab->retire();
 774 
 775   size_t actual_size = 0;
 776   HeapWord* gclab_buf = allocate_new_gclab(min_size, new_size, &actual_size);
 777   if (gclab_buf == NULL) {
 778     return NULL;
 779   }
 780 
 781   assert (size <= actual_size, "allocation should fit");
 782 
 783   if (ZeroTLAB) {
 784     // ..and clear it.
 785     Copy::zero_to_words(gclab_buf, actual_size);
 786   } else {
 787     // ...and zap just allocated object.
 788 #ifdef ASSERT
 789     // Skip mangling the space corresponding to the object header to
 790     // ensure that the returned space is not considered parsable by
 791     // any concurrent GC thread.
 792     size_t hdr_size = oopDesc::header_size();
 793     Copy::fill_to_words(gclab_buf + hdr_size, actual_size - hdr_size, badHeapWordVal);
 794 #endif // ASSERT
 795   }
 796   gclab->set_buf(gclab_buf, actual_size);
 797   return gclab->allocate(size);
 798 }
 799 
 800 HeapWord* ShenandoahHeap::allocate_new_tlab(size_t min_size,
 801                                             size_t requested_size,
 802                                             size_t* actual_size) {
 803   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_tlab(min_size, requested_size);
 804   HeapWord* res = allocate_memory(req);
 805   if (res != NULL) {
 806     *actual_size = req.actual_size();
 807   } else {
 808     *actual_size = 0;
 809   }
 810   return res;
 811 }
 812 
 813 HeapWord* ShenandoahHeap::allocate_new_gclab(size_t min_size,
 814                                              size_t word_size,
 815                                              size_t* actual_size) {
 816   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_gclab(min_size, word_size);
 817   HeapWord* res = allocate_memory(req);
 818   if (res != NULL) {
 819     *actual_size = req.actual_size();
 820   } else {
 821     *actual_size = 0;
 822   }
 823   return res;
 824 }
 825 
 826 HeapWord* ShenandoahHeap::allocate_memory(ShenandoahAllocRequest& req) {
 827   intptr_t pacer_epoch = 0;
 828   bool in_new_region = false;
 829   HeapWord* result = NULL;
 830 
 831   if (req.is_mutator_alloc()) {
 832     if (ShenandoahPacing) {
 833       pacer()->pace_for_alloc(req.size());
 834       pacer_epoch = pacer()->epoch();
 835     }
 836 
 837     if (!ShenandoahAllocFailureALot || !should_inject_alloc_failure()) {
 838       result = allocate_memory_under_lock(req, in_new_region);
 839     }
 840 
 841     // Allocation failed, block until control thread reacted, then retry allocation.
 842     //
 843     // It might happen that one of the threads requesting allocation would unblock
 844     // way later after GC happened, only to fail the second allocation, because
 845     // other threads have already depleted the free storage. In this case, a better
 846     // strategy is to try again, as long as GC makes progress.
 847     //
 848     // Then, we need to make sure the allocation was retried after at least one
 849     // Full GC, which means we want to try more than ShenandoahFullGCThreshold times.
 850 
 851     size_t tries = 0;
 852 
 853     while (result == NULL && _progress_last_gc.is_set()) {
 854       tries++;
 855       control_thread()->handle_alloc_failure(req);
 856       result = allocate_memory_under_lock(req, in_new_region);
 857     }
 858 
 859     while (result == NULL && tries <= ShenandoahFullGCThreshold) {
 860       tries++;
 861       control_thread()->handle_alloc_failure(req);
 862       result = allocate_memory_under_lock(req, in_new_region);
 863     }
 864 
 865   } else {
 866     assert(req.is_gc_alloc(), "Can only accept GC allocs here");
 867     result = allocate_memory_under_lock(req, in_new_region);
 868     // Do not call handle_alloc_failure() here, because we cannot block.
 869     // The allocation failure would be handled by the LRB slowpath with handle_alloc_failure_evac().
 870   }
 871 
 872   if (in_new_region) {
 873     control_thread()->notify_heap_changed();
 874   }
 875 
 876   if (result != NULL) {
 877     size_t requested = req.size();
 878     size_t actual = req.actual_size();
 879 
 880     assert (req.is_lab_alloc() || (requested == actual),
 881             "Only LAB allocations are elastic: %s, requested = " SIZE_FORMAT ", actual = " SIZE_FORMAT,
 882             ShenandoahAllocRequest::alloc_type_to_string(req.type()), requested, actual);
 883 
 884     if (req.is_mutator_alloc()) {
 885       notify_mutator_alloc_words(actual, false);
 886 
 887       // If we requested more than we were granted, give the rest back to pacer.
 888       // This only matters if we are in the same pacing epoch: do not try to unpace
 889       // over the budget for the other phase.
 890       if (ShenandoahPacing && (pacer_epoch > 0) && (requested > actual)) {
 891         pacer()->unpace_for_alloc(pacer_epoch, requested - actual);
 892       }
 893     } else {
 894       increase_used(actual*HeapWordSize);
 895     }
 896   }
 897 
 898   return result;
 899 }
 900 
 901 HeapWord* ShenandoahHeap::allocate_memory_under_lock(ShenandoahAllocRequest& req, bool& in_new_region) {
 902   ShenandoahHeapLocker locker(lock());
 903   return _free_set->allocate(req, in_new_region);
 904 }
 905 
 906 HeapWord* ShenandoahHeap::mem_allocate(size_t size,
 907                                         bool*  gc_overhead_limit_was_exceeded) {
 908   ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared(size);
 909   return allocate_memory(req);
 910 }
 911 
 912 MetaWord* ShenandoahHeap::satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,
 913                                                              size_t size,
 914                                                              Metaspace::MetadataType mdtype) {
 915   MetaWord* result;
 916 
 917   // Inform metaspace OOM to GC heuristics if class unloading is possible.
 918   if (heuristics()->can_unload_classes()) {
 919     ShenandoahHeuristics* h = heuristics();
 920     h->record_metaspace_oom();
 921   }
 922 
 923   // Expand and retry allocation
 924   result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
 925   if (result != NULL) {
 926     return result;
 927   }
 928 
 929   // Start full GC
 930   collect(GCCause::_metadata_GC_clear_soft_refs);
 931 
 932   // Retry allocation
 933   result = loader_data->metaspace_non_null()->allocate(size, mdtype);
 934   if (result != NULL) {
 935     return result;
 936   }
 937 
 938   // Expand and retry allocation
 939   result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype);
 940   if (result != NULL) {
 941     return result;
 942   }
 943 
 944   // Out of memory
 945   return NULL;
 946 }
 947 
 948 class ShenandoahConcurrentEvacuateRegionObjectClosure : public ObjectClosure {
 949 private:
 950   ShenandoahHeap* const _heap;
 951   Thread* const _thread;
 952 public:
 953   ShenandoahConcurrentEvacuateRegionObjectClosure(ShenandoahHeap* heap) :
 954     _heap(heap), _thread(Thread::current()) {}
 955 
 956   void do_object(oop p) {
 957     shenandoah_assert_marked(NULL, p);
 958     if (!ShenandoahForwarding::is_forwarded(p)) {
 959       _heap->evacuate_object(p, _thread);
 960     }
 961   }
 962 };
 963 
 964 class ShenandoahEvacuationTask : public AbstractGangTask {
 965 private:
 966   ShenandoahHeap* const _sh;
 967   ShenandoahCollectionSet* const _cs;
 968   bool _concurrent;
 969 public:
 970   ShenandoahEvacuationTask(ShenandoahHeap* sh,
 971                            ShenandoahCollectionSet* cs,
 972                            bool concurrent) :
 973     AbstractGangTask("Shenandoah Evacuation"),
 974     _sh(sh),
 975     _cs(cs),
 976     _concurrent(concurrent)
 977   {}
 978 
 979   void work(uint worker_id) {
 980     if (_concurrent) {
 981       ShenandoahConcurrentWorkerSession worker_session(worker_id);
 982       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
 983       ShenandoahEvacOOMScope oom_evac_scope;
 984       do_work();
 985     } else {
 986       ShenandoahParallelWorkerSession worker_session(worker_id);
 987       ShenandoahEvacOOMScope oom_evac_scope;
 988       do_work();
 989     }
 990   }
 991 
 992 private:
 993   void do_work() {
 994     ShenandoahConcurrentEvacuateRegionObjectClosure cl(_sh);
 995     ShenandoahHeapRegion* r;
 996     while ((r =_cs->claim_next()) != NULL) {
 997       assert(r->has_live(), "Region " SIZE_FORMAT " should have been reclaimed early", r->index());
 998       _sh->marked_object_iterate(r, &cl);
 999 
1000       if (ShenandoahPacing) {
1001         _sh->pacer()->report_evac(r->used() >> LogHeapWordSize);
1002       }
1003 
1004       if (_sh->check_cancelled_gc_and_yield(_concurrent)) {
1005         break;
1006       }
1007     }
1008   }
1009 };
1010 
1011 void ShenandoahHeap::evacuate_collection_set(bool concurrent) {
1012   ShenandoahEvacuationTask task(this, _collection_set, concurrent);
1013   workers()->run_task(&task);
1014 }
1015 
1016 void ShenandoahHeap::trash_cset_regions() {
1017   ShenandoahHeapLocker locker(lock());
1018 
1019   ShenandoahCollectionSet* set = collection_set();
1020   ShenandoahHeapRegion* r;
1021   set->clear_current_index();
1022   while ((r = set->next()) != NULL) {
1023     r->make_trash();
1024   }
1025   collection_set()->clear();
1026 }
1027 
1028 void ShenandoahHeap::print_heap_regions_on(outputStream* st) const {
1029   st->print_cr("Heap Regions:");
1030   st->print_cr("Region state: EU=empty-uncommitted, EC=empty-committed, R=regular, H=humongous start, HP=pinned humongous start");
1031   st->print_cr("              HC=humongous continuation, CS=collection set, TR=trash, P=pinned, CSP=pinned collection set");
1032   st->print_cr("BTE=bottom/top/end, TAMS=top-at-mark-start");
1033   st->print_cr("UWM=update watermark, U=used");
1034   st->print_cr("T=TLAB allocs, G=GCLAB allocs");
1035   st->print_cr("S=shared allocs, L=live data");
1036   st->print_cr("CP=critical pins");
1037 
1038   for (size_t i = 0; i < num_regions(); i++) {
1039     get_region(i)->print_on(st);
1040   }
1041 }
1042 
1043 void ShenandoahHeap::trash_humongous_region_at(ShenandoahHeapRegion* start) {
1044   assert(start->is_humongous_start(), "reclaim regions starting with the first one");
1045 
1046   oop humongous_obj = cast_to_oop(start->bottom());
1047   size_t size = humongous_obj->size();
1048   size_t required_regions = ShenandoahHeapRegion::required_regions(size * HeapWordSize);
1049   size_t index = start->index() + required_regions - 1;
1050 
1051   assert(!start->has_live(), "liveness must be zero");
1052 
1053   for(size_t i = 0; i < required_regions; i++) {
1054     // Reclaim from tail. Otherwise, assertion fails when printing region to trace log,
1055     // as it expects that every region belongs to a humongous region starting with a humongous start region.
1056     ShenandoahHeapRegion* region = get_region(index --);
1057 
1058     assert(region->is_humongous(), "expect correct humongous start or continuation");
1059     assert(!region->is_cset(), "Humongous region should not be in collection set");
1060 
1061     region->make_trash_immediate();
1062   }
1063 }
1064 
1065 class ShenandoahCheckCleanGCLABClosure : public ThreadClosure {
1066 public:
1067   ShenandoahCheckCleanGCLABClosure() {}
1068   void do_thread(Thread* thread) {
1069     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1070     assert(gclab != NULL, "GCLAB should be initialized for %s", thread->name());
1071     assert(gclab->words_remaining() == 0, "GCLAB should not need retirement");
1072   }
1073 };
1074 
1075 class ShenandoahRetireGCLABClosure : public ThreadClosure {
1076 private:
1077   bool const _resize;
1078 public:
1079   ShenandoahRetireGCLABClosure(bool resize) : _resize(resize) {}
1080   void do_thread(Thread* thread) {
1081     PLAB* gclab = ShenandoahThreadLocalData::gclab(thread);
1082     assert(gclab != NULL, "GCLAB should be initialized for %s", thread->name());
1083     gclab->retire();
1084     if (_resize && ShenandoahThreadLocalData::gclab_size(thread) > 0) {
1085       ShenandoahThreadLocalData::set_gclab_size(thread, 0);
1086     }
1087   }
1088 };
1089 
1090 void ShenandoahHeap::labs_make_parsable() {
1091   assert(UseTLAB, "Only call with UseTLAB");
1092 
1093   ShenandoahRetireGCLABClosure cl(false);
1094 
1095   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1096     ThreadLocalAllocBuffer& tlab = t->tlab();
1097     tlab.make_parsable();
1098     cl.do_thread(t);
1099   }
1100 
1101   workers()->threads_do(&cl);
1102 }
1103 
1104 void ShenandoahHeap::tlabs_retire(bool resize) {
1105   assert(UseTLAB, "Only call with UseTLAB");
1106   assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled");
1107 
1108   ThreadLocalAllocStats stats;
1109 
1110   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1111     ThreadLocalAllocBuffer& tlab = t->tlab();
1112     tlab.retire(&stats);
1113     if (resize) {
1114       tlab.resize();
1115     }
1116   }
1117 
1118   stats.publish();
1119 
1120 #ifdef ASSERT
1121   ShenandoahCheckCleanGCLABClosure cl;
1122   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1123     cl.do_thread(t);
1124   }
1125   workers()->threads_do(&cl);
1126 #endif
1127 }
1128 
1129 void ShenandoahHeap::gclabs_retire(bool resize) {
1130   assert(UseTLAB, "Only call with UseTLAB");
1131   assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled");
1132 
1133   ShenandoahRetireGCLABClosure cl(resize);
1134   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1135     cl.do_thread(t);
1136   }
1137   workers()->threads_do(&cl);
1138 
1139   if (safepoint_workers() != NULL) {
1140     safepoint_workers()->threads_do(&cl);
1141   }
1142 }
1143 
1144 // Returns size in bytes
1145 size_t ShenandoahHeap::unsafe_max_tlab_alloc(Thread *thread) const {
1146   if (ShenandoahElasticTLAB) {
1147     // With Elastic TLABs, return the max allowed size, and let the allocation path
1148     // figure out the safe size for current allocation.
1149     return ShenandoahHeapRegion::max_tlab_size_bytes();
1150   } else {
1151     return MIN2(_free_set->unsafe_peek_free(), ShenandoahHeapRegion::max_tlab_size_bytes());
1152   }
1153 }
1154 
1155 size_t ShenandoahHeap::max_tlab_size() const {
1156   // Returns size in words
1157   return ShenandoahHeapRegion::max_tlab_size_words();
1158 }
1159 
1160 void ShenandoahHeap::collect(GCCause::Cause cause) {
1161   control_thread()->request_gc(cause);
1162 }
1163 
1164 void ShenandoahHeap::do_full_collection(bool clear_all_soft_refs) {
1165   //assert(false, "Shouldn't need to do full collections");
1166 }
1167 
1168 HeapWord* ShenandoahHeap::block_start(const void* addr) const {
1169   ShenandoahHeapRegion* r = heap_region_containing(addr);
1170   if (r != NULL) {
1171     return r->block_start(addr);
1172   }
1173   return NULL;
1174 }
1175 
1176 bool ShenandoahHeap::block_is_obj(const HeapWord* addr) const {
1177   ShenandoahHeapRegion* r = heap_region_containing(addr);
1178   return r->block_is_obj(addr);
1179 }
1180 
1181 bool ShenandoahHeap::print_location(outputStream* st, void* addr) const {
1182   return BlockLocationPrinter<ShenandoahHeap>::print_location(st, addr);
1183 }
1184 
1185 void ShenandoahHeap::prepare_for_verify() {
1186   if (SafepointSynchronize::is_at_safepoint() && UseTLAB) {
1187     labs_make_parsable();
1188   }
1189 }
1190 
1191 void ShenandoahHeap::gc_threads_do(ThreadClosure* tcl) const {
1192   tcl->do_thread(_control_thread);
1193   workers()->threads_do(tcl);
1194   if (_safepoint_workers != NULL) {
1195     _safepoint_workers->threads_do(tcl);
1196   }
1197   if (ShenandoahStringDedup::is_enabled()) {
1198     ShenandoahStringDedup::threads_do(tcl);
1199   }
1200 }
1201 
1202 void ShenandoahHeap::print_tracing_info() const {
1203   LogTarget(Info, gc, stats) lt;
1204   if (lt.is_enabled()) {
1205     ResourceMark rm;
1206     LogStream ls(lt);
1207 
1208     phase_timings()->print_global_on(&ls);
1209 
1210     ls.cr();
1211     ls.cr();
1212 
1213     shenandoah_policy()->print_gc_stats(&ls);
1214 
1215     ls.cr();
1216     ls.cr();
1217   }
1218 }
1219 
1220 void ShenandoahHeap::verify(VerifyOption vo) {
1221   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
1222     if (ShenandoahVerify) {
1223       verifier()->verify_generic(vo);
1224     } else {
1225       // TODO: Consider allocating verification bitmaps on demand,
1226       // and turn this on unconditionally.
1227     }
1228   }
1229 }
1230 size_t ShenandoahHeap::tlab_capacity(Thread *thr) const {
1231   return _free_set->capacity();
1232 }
1233 
1234 class ObjectIterateScanRootClosure : public BasicOopIterateClosure {
1235 private:
1236   MarkBitMap* _bitmap;
1237   ShenandoahScanObjectStack* _oop_stack;
1238   ShenandoahHeap* const _heap;
1239   ShenandoahMarkingContext* const _marking_context;
1240 
1241   template <class T>
1242   void do_oop_work(T* p) {
1243     T o = RawAccess<>::oop_load(p);
1244     if (!CompressedOops::is_null(o)) {
1245       oop obj = CompressedOops::decode_not_null(o);
1246       if (_heap->is_concurrent_weak_root_in_progress() && !_marking_context->is_marked(obj)) {
1247         // There may be dead oops in weak roots in concurrent root phase, do not touch them.
1248         return;
1249       }
1250       obj = ShenandoahBarrierSet::barrier_set()->load_reference_barrier(obj);
1251 
1252       assert(oopDesc::is_oop(obj), "must be a valid oop");
1253       if (!_bitmap->is_marked(obj)) {
1254         _bitmap->mark(obj);
1255         _oop_stack->push(obj);
1256       }
1257     }
1258   }
1259 public:
1260   ObjectIterateScanRootClosure(MarkBitMap* bitmap, ShenandoahScanObjectStack* oop_stack) :
1261     _bitmap(bitmap), _oop_stack(oop_stack), _heap(ShenandoahHeap::heap()),
1262     _marking_context(_heap->marking_context()) {}
1263   void do_oop(oop* p)       { do_oop_work(p); }
1264   void do_oop(narrowOop* p) { do_oop_work(p); }
1265 };
1266 
1267 /*
1268  * This is public API, used in preparation of object_iterate().
1269  * Since we don't do linear scan of heap in object_iterate() (see comment below), we don't
1270  * need to make the heap parsable. For Shenandoah-internal linear heap scans that we can
1271  * control, we call SH::tlabs_retire, SH::gclabs_retire.
1272  */
1273 void ShenandoahHeap::ensure_parsability(bool retire_tlabs) {
1274   // No-op.
1275 }
1276 
1277 /*
1278  * Iterates objects in the heap. This is public API, used for, e.g., heap dumping.
1279  *
1280  * We cannot safely iterate objects by doing a linear scan at random points in time. Linear
1281  * scanning needs to deal with dead objects, which may have dead Klass* pointers (e.g.
1282  * calling oopDesc::size() would crash) or dangling reference fields (crashes) etc. Linear
1283  * scanning therefore depends on having a valid marking bitmap to support it. However, we only
1284  * have a valid marking bitmap after successful marking. In particular, we *don't* have a valid
1285  * marking bitmap during marking, after aborted marking or during/after cleanup (when we just
1286  * wiped the bitmap in preparation for next marking).
1287  *
1288  * For all those reasons, we implement object iteration as a single marking traversal, reporting
1289  * objects as we mark+traverse through the heap, starting from GC roots. JVMTI IterateThroughHeap
1290  * is allowed to report dead objects, but is not required to do so.
1291  */
1292 void ShenandoahHeap::object_iterate(ObjectClosure* cl) {
1293   // Reset bitmap
1294   if (!prepare_aux_bitmap_for_iteration())
1295     return;
1296 
1297   ShenandoahScanObjectStack oop_stack;
1298   ObjectIterateScanRootClosure oops(&_aux_bit_map, &oop_stack);
1299   // Seed the stack with root scan
1300   scan_roots_for_iteration(&oop_stack, &oops);
1301 
1302   // Work through the oop stack to traverse heap
1303   while (! oop_stack.is_empty()) {
1304     oop obj = oop_stack.pop();
1305     assert(oopDesc::is_oop(obj), "must be a valid oop");
1306     shenandoah_assert_not_in_cset_except(NULL, obj, cancelled_gc());
1307     cl->do_object(obj);
1308     obj->oop_iterate(&oops);
1309   }
1310 
1311   assert(oop_stack.is_empty(), "should be empty");
1312   // Reclaim bitmap
1313   reclaim_aux_bitmap_for_iteration();
1314 }
1315 
1316 bool ShenandoahHeap::prepare_aux_bitmap_for_iteration() {
1317   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1318 
1319   if (!_aux_bitmap_region_special && !os::commit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size(), false)) {
1320     log_warning(gc)("Could not commit native memory for auxiliary marking bitmap for heap iteration");
1321     return false;
1322   }
1323   // Reset bitmap
1324   _aux_bit_map.clear();
1325   return true;
1326 }
1327 
1328 void ShenandoahHeap::scan_roots_for_iteration(ShenandoahScanObjectStack* oop_stack, ObjectIterateScanRootClosure* oops) {
1329   // Process GC roots according to current GC cycle
1330   // This populates the work stack with initial objects
1331   // It is important to relinquish the associated locks before diving
1332   // into heap dumper
1333   ShenandoahHeapIterationRootScanner rp;
1334   rp.roots_do(oops);
1335 }
1336 
1337 void ShenandoahHeap::reclaim_aux_bitmap_for_iteration() {
1338   if (!_aux_bitmap_region_special && !os::uncommit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size())) {
1339     log_warning(gc)("Could not uncommit native memory for auxiliary marking bitmap for heap iteration");
1340   }
1341 }
1342 
1343 // Closure for parallelly iterate objects
1344 class ShenandoahObjectIterateParScanClosure : public BasicOopIterateClosure {
1345 private:
1346   MarkBitMap* _bitmap;
1347   ShenandoahObjToScanQueue* _queue;
1348   ShenandoahHeap* const _heap;
1349   ShenandoahMarkingContext* const _marking_context;
1350 
1351   template <class T>
1352   void do_oop_work(T* p) {
1353     T o = RawAccess<>::oop_load(p);
1354     if (!CompressedOops::is_null(o)) {
1355       oop obj = CompressedOops::decode_not_null(o);
1356       if (_heap->is_concurrent_weak_root_in_progress() && !_marking_context->is_marked(obj)) {
1357         // There may be dead oops in weak roots in concurrent root phase, do not touch them.
1358         return;
1359       }
1360       obj = ShenandoahBarrierSet::barrier_set()->load_reference_barrier(obj);
1361 
1362       assert(oopDesc::is_oop(obj), "Must be a valid oop");
1363       if (_bitmap->par_mark(obj)) {
1364         _queue->push(ShenandoahMarkTask(obj));
1365       }
1366     }
1367   }
1368 public:
1369   ShenandoahObjectIterateParScanClosure(MarkBitMap* bitmap, ShenandoahObjToScanQueue* q) :
1370     _bitmap(bitmap), _queue(q), _heap(ShenandoahHeap::heap()),
1371     _marking_context(_heap->marking_context()) {}
1372   void do_oop(oop* p)       { do_oop_work(p); }
1373   void do_oop(narrowOop* p) { do_oop_work(p); }
1374 };
1375 
1376 // Object iterator for parallel heap iteraion.
1377 // The root scanning phase happenes in construction as a preparation of
1378 // parallel marking queues.
1379 // Every worker processes it's own marking queue. work-stealing is used
1380 // to balance workload.
1381 class ShenandoahParallelObjectIterator : public ParallelObjectIteratorImpl {
1382 private:
1383   uint                         _num_workers;
1384   bool                         _init_ready;
1385   MarkBitMap*                  _aux_bit_map;
1386   ShenandoahHeap*              _heap;
1387   ShenandoahScanObjectStack    _roots_stack; // global roots stack
1388   ShenandoahObjToScanQueueSet* _task_queues;
1389 public:
1390   ShenandoahParallelObjectIterator(uint num_workers, MarkBitMap* bitmap) :
1391         _num_workers(num_workers),
1392         _init_ready(false),
1393         _aux_bit_map(bitmap),
1394         _heap(ShenandoahHeap::heap()) {
1395     // Initialize bitmap
1396     _init_ready = _heap->prepare_aux_bitmap_for_iteration();
1397     if (!_init_ready) {
1398       return;
1399     }
1400 
1401     ObjectIterateScanRootClosure oops(_aux_bit_map, &_roots_stack);
1402     _heap->scan_roots_for_iteration(&_roots_stack, &oops);
1403 
1404     _init_ready = prepare_worker_queues();
1405   }
1406 
1407   ~ShenandoahParallelObjectIterator() {
1408     // Reclaim bitmap
1409     _heap->reclaim_aux_bitmap_for_iteration();
1410     // Reclaim queue for workers
1411     if (_task_queues!= NULL) {
1412       for (uint i = 0; i < _num_workers; ++i) {
1413         ShenandoahObjToScanQueue* q = _task_queues->queue(i);
1414         if (q != NULL) {
1415           delete q;
1416           _task_queues->register_queue(i, NULL);
1417         }
1418       }
1419       delete _task_queues;
1420       _task_queues = NULL;
1421     }
1422   }
1423 
1424   virtual void object_iterate(ObjectClosure* cl, uint worker_id) {
1425     if (_init_ready) {
1426       object_iterate_parallel(cl, worker_id, _task_queues);
1427     }
1428   }
1429 
1430 private:
1431   // Divide global root_stack into worker queues
1432   bool prepare_worker_queues() {
1433     _task_queues = new ShenandoahObjToScanQueueSet((int) _num_workers);
1434     // Initialize queues for every workers
1435     for (uint i = 0; i < _num_workers; ++i) {
1436       ShenandoahObjToScanQueue* task_queue = new ShenandoahObjToScanQueue();
1437       task_queue->initialize();
1438       _task_queues->register_queue(i, task_queue);
1439     }
1440     // Divide roots among the workers. Assume that object referencing distribution
1441     // is related with root kind, use round-robin to make every worker have same chance
1442     // to process every kind of roots
1443     size_t roots_num = _roots_stack.size();
1444     if (roots_num == 0) {
1445       // No work to do
1446       return false;
1447     }
1448 
1449     for (uint j = 0; j < roots_num; j++) {
1450       uint stack_id = j % _num_workers;
1451       oop obj = _roots_stack.pop();
1452       _task_queues->queue(stack_id)->push(ShenandoahMarkTask(obj));
1453     }
1454     return true;
1455   }
1456 
1457   void object_iterate_parallel(ObjectClosure* cl,
1458                                uint worker_id,
1459                                ShenandoahObjToScanQueueSet* queue_set) {
1460     assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1461     assert(queue_set != NULL, "task queue must not be NULL");
1462 
1463     ShenandoahObjToScanQueue* q = queue_set->queue(worker_id);
1464     assert(q != NULL, "object iterate queue must not be NULL");
1465 
1466     ShenandoahMarkTask t;
1467     ShenandoahObjectIterateParScanClosure oops(_aux_bit_map, q);
1468 
1469     // Work through the queue to traverse heap.
1470     // Steal when there is no task in queue.
1471     while (q->pop(t) || queue_set->steal(worker_id, t)) {
1472       oop obj = t.obj();
1473       assert(oopDesc::is_oop(obj), "must be a valid oop");
1474       cl->do_object(obj);
1475       obj->oop_iterate(&oops);
1476     }
1477     assert(q->is_empty(), "should be empty");
1478   }
1479 };
1480 
1481 ParallelObjectIteratorImpl* ShenandoahHeap::parallel_object_iterator(uint workers) {
1482   return new ShenandoahParallelObjectIterator(workers, &_aux_bit_map);
1483 }
1484 
1485 // Keep alive an object that was loaded with AS_NO_KEEPALIVE.
1486 void ShenandoahHeap::keep_alive(oop obj) {
1487   if (is_concurrent_mark_in_progress() && (obj != NULL)) {
1488     ShenandoahBarrierSet::barrier_set()->enqueue(obj);
1489   }
1490 }
1491 
1492 void ShenandoahHeap::heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1493   for (size_t i = 0; i < num_regions(); i++) {
1494     ShenandoahHeapRegion* current = get_region(i);
1495     blk->heap_region_do(current);
1496   }
1497 }
1498 
1499 class ShenandoahParallelHeapRegionTask : public AbstractGangTask {
1500 private:
1501   ShenandoahHeap* const _heap;
1502   ShenandoahHeapRegionClosure* const _blk;
1503 
1504   shenandoah_padding(0);
1505   volatile size_t _index;
1506   shenandoah_padding(1);
1507 
1508 public:
1509   ShenandoahParallelHeapRegionTask(ShenandoahHeapRegionClosure* blk) :
1510           AbstractGangTask("Shenandoah Parallel Region Operation"),
1511           _heap(ShenandoahHeap::heap()), _blk(blk), _index(0) {}
1512 
1513   void work(uint worker_id) {
1514     ShenandoahParallelWorkerSession worker_session(worker_id);
1515     size_t stride = ShenandoahParallelRegionStride;
1516 
1517     size_t max = _heap->num_regions();
1518     while (Atomic::load(&_index) < max) {
1519       size_t cur = Atomic::fetch_and_add(&_index, stride, memory_order_relaxed);
1520       size_t start = cur;
1521       size_t end = MIN2(cur + stride, max);
1522       if (start >= max) break;
1523 
1524       for (size_t i = cur; i < end; i++) {
1525         ShenandoahHeapRegion* current = _heap->get_region(i);
1526         _blk->heap_region_do(current);
1527       }
1528     }
1529   }
1530 };
1531 
1532 void ShenandoahHeap::parallel_heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1533   assert(blk->is_thread_safe(), "Only thread-safe closures here");
1534   if (num_regions() > ShenandoahParallelRegionStride) {
1535     ShenandoahParallelHeapRegionTask task(blk);
1536     workers()->run_task(&task);
1537   } else {
1538     heap_region_iterate(blk);
1539   }
1540 }
1541 
1542 class ShenandoahInitMarkUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
1543 private:
1544   ShenandoahMarkingContext* const _ctx;
1545 public:
1546   ShenandoahInitMarkUpdateRegionStateClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
1547 
1548   void heap_region_do(ShenandoahHeapRegion* r) {
1549     assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->index());
1550     if (r->is_active()) {
1551       // Check if region needs updating its TAMS. We have updated it already during concurrent
1552       // reset, so it is very likely we don't need to do another write here.
1553       if (_ctx->top_at_mark_start(r) != r->top()) {
1554         _ctx->capture_top_at_mark_start(r);
1555       }
1556     } else {
1557       assert(_ctx->top_at_mark_start(r) == r->top(),
1558              "Region " SIZE_FORMAT " should already have correct TAMS", r->index());
1559     }
1560   }
1561 
1562   bool is_thread_safe() { return true; }
1563 };
1564 
1565 class ShenandoahRendezvousClosure : public HandshakeClosure {
1566 public:
1567   inline ShenandoahRendezvousClosure() : HandshakeClosure("ShenandoahRendezvous") {}
1568   inline void do_thread(Thread* thread) {}
1569 };
1570 
1571 void ShenandoahHeap::rendezvous_threads() {
1572   ShenandoahRendezvousClosure cl;
1573   Handshake::execute(&cl);
1574 }
1575 
1576 void ShenandoahHeap::recycle_trash() {
1577   free_set()->recycle_trash();
1578 }
1579 
1580 class ShenandoahResetUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
1581 private:
1582   ShenandoahMarkingContext* const _ctx;
1583 public:
1584   ShenandoahResetUpdateRegionStateClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
1585 
1586   void heap_region_do(ShenandoahHeapRegion* r) {
1587     if (r->is_active()) {
1588       // Reset live data and set TAMS optimistically. We would recheck these under the pause
1589       // anyway to capture any updates that happened since now.
1590       r->clear_live_data();
1591       _ctx->capture_top_at_mark_start(r);
1592     }
1593   }
1594 
1595   bool is_thread_safe() { return true; }
1596 };
1597 
1598 void ShenandoahHeap::prepare_gc() {
1599   reset_mark_bitmap();
1600 
1601   ShenandoahResetUpdateRegionStateClosure cl;
1602   parallel_heap_region_iterate(&cl);
1603 }
1604 
1605 class ShenandoahFinalMarkUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
1606 private:
1607   ShenandoahMarkingContext* const _ctx;
1608   ShenandoahHeapLock* const _lock;
1609 
1610 public:
1611   ShenandoahFinalMarkUpdateRegionStateClosure() :
1612     _ctx(ShenandoahHeap::heap()->complete_marking_context()), _lock(ShenandoahHeap::heap()->lock()) {}
1613 
1614   void heap_region_do(ShenandoahHeapRegion* r) {
1615     if (r->is_active()) {
1616       // All allocations past TAMS are implicitly live, adjust the region data.
1617       // Bitmaps/TAMS are swapped at this point, so we need to poll complete bitmap.
1618       HeapWord *tams = _ctx->top_at_mark_start(r);
1619       HeapWord *top = r->top();
1620       if (top > tams) {
1621         r->increase_live_data_alloc_words(pointer_delta(top, tams));
1622       }
1623 
1624       // We are about to select the collection set, make sure it knows about
1625       // current pinning status. Also, this allows trashing more regions that
1626       // now have their pinning status dropped.
1627       if (r->is_pinned()) {
1628         if (r->pin_count() == 0) {
1629           ShenandoahHeapLocker locker(_lock);
1630           r->make_unpinned();
1631         }
1632       } else {
1633         if (r->pin_count() > 0) {
1634           ShenandoahHeapLocker locker(_lock);
1635           r->make_pinned();
1636         }
1637       }
1638 
1639       // Remember limit for updating refs. It's guaranteed that we get no
1640       // from-space-refs written from here on.
1641       r->set_update_watermark_at_safepoint(r->top());
1642     } else {
1643       assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->index());
1644       assert(_ctx->top_at_mark_start(r) == r->top(),
1645              "Region " SIZE_FORMAT " should have correct TAMS", r->index());
1646     }
1647   }
1648 
1649   bool is_thread_safe() { return true; }
1650 };
1651 
1652 void ShenandoahHeap::prepare_regions_and_collection_set(bool concurrent) {
1653   assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
1654   {
1655     ShenandoahGCPhase phase(concurrent ? ShenandoahPhaseTimings::final_update_region_states :
1656                                          ShenandoahPhaseTimings::degen_gc_final_update_region_states);
1657     ShenandoahFinalMarkUpdateRegionStateClosure cl;
1658     parallel_heap_region_iterate(&cl);
1659 
1660     assert_pinned_region_status();
1661   }
1662 
1663   {
1664     ShenandoahGCPhase phase(concurrent ? ShenandoahPhaseTimings::choose_cset :
1665                                          ShenandoahPhaseTimings::degen_gc_choose_cset);
1666     ShenandoahHeapLocker locker(lock());
1667     _collection_set->clear();
1668     heuristics()->choose_collection_set(_collection_set);
1669   }
1670 
1671   {
1672     ShenandoahGCPhase phase(concurrent ? ShenandoahPhaseTimings::final_rebuild_freeset :
1673                                          ShenandoahPhaseTimings::degen_gc_final_rebuild_freeset);
1674     ShenandoahHeapLocker locker(lock());
1675     _free_set->rebuild();
1676   }
1677 }
1678 
1679 void ShenandoahHeap::do_class_unloading() {
1680   _unloader.unload();
1681 }
1682 
1683 void ShenandoahHeap::stw_weak_refs(bool full_gc) {
1684   // Weak refs processing
1685   ShenandoahPhaseTimings::Phase phase = full_gc ? ShenandoahPhaseTimings::full_gc_weakrefs
1686                                                 : ShenandoahPhaseTimings::degen_gc_weakrefs;
1687   ShenandoahTimingsTracker t(phase);
1688   ShenandoahGCWorkerPhase worker_phase(phase);
1689   ref_processor()->process_references(phase, workers(), false /* concurrent */);
1690 }
1691 
1692 void ShenandoahHeap::prepare_update_heap_references(bool concurrent) {
1693   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
1694 
1695   // Evacuation is over, no GCLABs are needed anymore. GCLABs are under URWM, so we need to
1696   // make them parsable for update code to work correctly. Plus, we can compute new sizes
1697   // for future GCLABs here.
1698   if (UseTLAB) {
1699     ShenandoahGCPhase phase(concurrent ?
1700                             ShenandoahPhaseTimings::init_update_refs_manage_gclabs :
1701                             ShenandoahPhaseTimings::degen_gc_init_update_refs_manage_gclabs);
1702     gclabs_retire(ResizeTLAB);
1703   }
1704 
1705   _update_refs_iterator.reset();
1706 }
1707 
1708 void ShenandoahHeap::set_gc_state_all_threads(char state) {
1709   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
1710     ShenandoahThreadLocalData::set_gc_state(t, state);
1711   }
1712 }
1713 
1714 void ShenandoahHeap::set_gc_state_mask(uint mask, bool value) {
1715   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should really be Shenandoah safepoint");
1716   _gc_state.set_cond(mask, value);
1717   set_gc_state_all_threads(_gc_state.raw_value());
1718 }
1719 
1720 void ShenandoahHeap::set_concurrent_mark_in_progress(bool in_progress) {
1721   assert(!has_forwarded_objects(), "Not expected before/after mark phase");
1722   set_gc_state_mask(MARKING, in_progress);
1723   ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
1724 }
1725 
1726 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {
1727   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint");
1728   set_gc_state_mask(EVACUATION, in_progress);
1729 }
1730 
1731 void ShenandoahHeap::set_concurrent_strong_root_in_progress(bool in_progress) {
1732   if (in_progress) {
1733     _concurrent_strong_root_in_progress.set();
1734   } else {
1735     _concurrent_strong_root_in_progress.unset();
1736   }
1737 }
1738 
1739 void ShenandoahHeap::set_concurrent_weak_root_in_progress(bool cond) {
1740   set_gc_state_mask(WEAK_ROOTS, cond);
1741 }
1742 
1743 GCTracer* ShenandoahHeap::tracer() {
1744   return shenandoah_policy()->tracer();
1745 }
1746 
1747 size_t ShenandoahHeap::tlab_used(Thread* thread) const {
1748   return _free_set->used();
1749 }
1750 
1751 bool ShenandoahHeap::try_cancel_gc() {
1752   jbyte prev = _cancelled_gc.cmpxchg(CANCELLED, CANCELLABLE);
1753   return prev == CANCELLABLE;
1754 }
1755 
1756 void ShenandoahHeap::cancel_gc(GCCause::Cause cause) {
1757   if (try_cancel_gc()) {
1758     FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause));
1759     log_info(gc)("%s", msg.buffer());
1760     Events::log(Thread::current(), "%s", msg.buffer());
1761   }
1762 }
1763 
1764 uint ShenandoahHeap::max_workers() {
1765   return _max_workers;
1766 }
1767 
1768 void ShenandoahHeap::stop() {
1769   // The shutdown sequence should be able to terminate when GC is running.
1770 
1771   // Step 0. Notify policy to disable event recording.
1772   _shenandoah_policy->record_shutdown();
1773 
1774   // Step 1. Notify control thread that we are in shutdown.
1775   // Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown.
1776   // Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below.
1777   control_thread()->prepare_for_graceful_shutdown();
1778 
1779   // Step 2. Notify GC workers that we are cancelling GC.
1780   cancel_gc(GCCause::_shenandoah_stop_vm);
1781 
1782   // Step 3. Wait until GC worker exits normally.
1783   control_thread()->stop();
1784 }
1785 
1786 void ShenandoahHeap::stw_unload_classes(bool full_gc) {
1787   if (!unload_classes()) return;
1788   // Unload classes and purge SystemDictionary.
1789   {
1790     ShenandoahPhaseTimings::Phase phase = full_gc ?
1791                                           ShenandoahPhaseTimings::full_gc_purge_class_unload :
1792                                           ShenandoahPhaseTimings::degen_gc_purge_class_unload;
1793     ShenandoahGCPhase gc_phase(phase);
1794     ShenandoahGCWorkerPhase worker_phase(phase);
1795     bool purged_class = SystemDictionary::do_unloading(gc_timer());
1796 
1797     ShenandoahIsAliveSelector is_alive;
1798     uint num_workers = _workers->active_workers();
1799     ShenandoahClassUnloadingTask unlink_task(phase, is_alive.is_alive_closure(), num_workers, purged_class);
1800     _workers->run_task(&unlink_task);
1801   }
1802 
1803   {
1804     ShenandoahGCPhase phase(full_gc ?
1805                             ShenandoahPhaseTimings::full_gc_purge_cldg :
1806                             ShenandoahPhaseTimings::degen_gc_purge_cldg);
1807     ClassLoaderDataGraph::purge(/*at_safepoint*/true);
1808   }
1809   // Resize and verify metaspace
1810   MetaspaceGC::compute_new_size();
1811   DEBUG_ONLY(MetaspaceUtils::verify();)
1812 }
1813 
1814 // Weak roots are either pre-evacuated (final mark) or updated (final updaterefs),
1815 // so they should not have forwarded oops.
1816 // However, we do need to "null" dead oops in the roots, if can not be done
1817 // in concurrent cycles.
1818 void ShenandoahHeap::stw_process_weak_roots(bool full_gc) {
1819   uint num_workers = _workers->active_workers();
1820   ShenandoahPhaseTimings::Phase timing_phase = full_gc ?
1821                                                ShenandoahPhaseTimings::full_gc_purge_weak_par :
1822                                                ShenandoahPhaseTimings::degen_gc_purge_weak_par;
1823   ShenandoahGCPhase phase(timing_phase);
1824   ShenandoahGCWorkerPhase worker_phase(timing_phase);
1825   // Cleanup weak roots
1826   if (has_forwarded_objects()) {
1827     ShenandoahForwardedIsAliveClosure is_alive;
1828     ShenandoahUpdateRefsClosure keep_alive;
1829     ShenandoahParallelWeakRootsCleaningTask<ShenandoahForwardedIsAliveClosure, ShenandoahUpdateRefsClosure>
1830       cleaning_task(timing_phase, &is_alive, &keep_alive, num_workers);
1831     _workers->run_task(&cleaning_task);
1832   } else {
1833     ShenandoahIsAliveClosure is_alive;
1834 #ifdef ASSERT
1835     ShenandoahAssertNotForwardedClosure verify_cl;
1836     ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, ShenandoahAssertNotForwardedClosure>
1837       cleaning_task(timing_phase, &is_alive, &verify_cl, num_workers);
1838 #else
1839     ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, DoNothingClosure>
1840       cleaning_task(timing_phase, &is_alive, &do_nothing_cl, num_workers);
1841 #endif
1842     _workers->run_task(&cleaning_task);
1843   }
1844 }
1845 
1846 void ShenandoahHeap::parallel_cleaning(bool full_gc) {
1847   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
1848   assert(is_stw_gc_in_progress(), "Only for Degenerated and Full GC");
1849   ShenandoahGCPhase phase(full_gc ?
1850                           ShenandoahPhaseTimings::full_gc_purge :
1851                           ShenandoahPhaseTimings::degen_gc_purge);
1852   stw_weak_refs(full_gc);
1853   stw_process_weak_roots(full_gc);
1854   stw_unload_classes(full_gc);
1855 }
1856 
1857 void ShenandoahHeap::set_has_forwarded_objects(bool cond) {
1858   set_gc_state_mask(HAS_FORWARDED, cond);
1859 }
1860 
1861 void ShenandoahHeap::set_unload_classes(bool uc) {
1862   _unload_classes.set_cond(uc);
1863 }
1864 
1865 bool ShenandoahHeap::unload_classes() const {
1866   return _unload_classes.is_set();
1867 }
1868 
1869 address ShenandoahHeap::in_cset_fast_test_addr() {
1870   ShenandoahHeap* heap = ShenandoahHeap::heap();
1871   assert(heap->collection_set() != NULL, "Sanity");
1872   return (address) heap->collection_set()->biased_map_address();
1873 }
1874 
1875 address ShenandoahHeap::cancelled_gc_addr() {
1876   return (address) ShenandoahHeap::heap()->_cancelled_gc.addr_of();
1877 }
1878 
1879 address ShenandoahHeap::gc_state_addr() {
1880   return (address) ShenandoahHeap::heap()->_gc_state.addr_of();
1881 }
1882 
1883 size_t ShenandoahHeap::bytes_allocated_since_gc_start() {
1884   return Atomic::load(&_bytes_allocated_since_gc_start);
1885 }
1886 
1887 void ShenandoahHeap::reset_bytes_allocated_since_gc_start() {
1888   Atomic::store(&_bytes_allocated_since_gc_start, (size_t)0);
1889 }
1890 
1891 void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) {
1892   _degenerated_gc_in_progress.set_cond(in_progress);
1893 }
1894 
1895 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {
1896   _full_gc_in_progress.set_cond(in_progress);
1897 }
1898 
1899 void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) {
1900   assert (is_full_gc_in_progress(), "should be");
1901   _full_gc_move_in_progress.set_cond(in_progress);
1902 }
1903 
1904 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {
1905   set_gc_state_mask(UPDATEREFS, in_progress);
1906 }
1907 
1908 void ShenandoahHeap::register_nmethod(nmethod* nm) {
1909   ShenandoahCodeRoots::register_nmethod(nm);
1910 }
1911 
1912 void ShenandoahHeap::unregister_nmethod(nmethod* nm) {
1913   ShenandoahCodeRoots::unregister_nmethod(nm);
1914 }
1915 
1916 void ShenandoahHeap::flush_nmethod(nmethod* nm) {
1917   ShenandoahCodeRoots::flush_nmethod(nm);
1918 }
1919 
1920 oop ShenandoahHeap::pin_object(JavaThread* thr, oop o) {
1921   heap_region_containing(o)->record_pin();
1922   return o;
1923 }
1924 
1925 void ShenandoahHeap::unpin_object(JavaThread* thr, oop o) {
1926   ShenandoahHeapRegion* r = heap_region_containing(o);
1927   assert(r != NULL, "Sanity");
1928   assert(r->pin_count() > 0, "Region " SIZE_FORMAT " should have non-zero pins", r->index());
1929   r->record_unpin();
1930 }
1931 
1932 void ShenandoahHeap::sync_pinned_region_status() {
1933   ShenandoahHeapLocker locker(lock());
1934 
1935   for (size_t i = 0; i < num_regions(); i++) {
1936     ShenandoahHeapRegion *r = get_region(i);
1937     if (r->is_active()) {
1938       if (r->is_pinned()) {
1939         if (r->pin_count() == 0) {
1940           r->make_unpinned();
1941         }
1942       } else {
1943         if (r->pin_count() > 0) {
1944           r->make_pinned();
1945         }
1946       }
1947     }
1948   }
1949 
1950   assert_pinned_region_status();
1951 }
1952 
1953 #ifdef ASSERT
1954 void ShenandoahHeap::assert_pinned_region_status() {
1955   for (size_t i = 0; i < num_regions(); i++) {
1956     ShenandoahHeapRegion* r = get_region(i);
1957     assert((r->is_pinned() && r->pin_count() > 0) || (!r->is_pinned() && r->pin_count() == 0),
1958            "Region " SIZE_FORMAT " pinning status is inconsistent", i);
1959   }
1960 }
1961 #endif
1962 
1963 ConcurrentGCTimer* ShenandoahHeap::gc_timer() const {
1964   return _gc_timer;
1965 }
1966 
1967 void ShenandoahHeap::prepare_concurrent_roots() {
1968   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
1969   assert(!is_stw_gc_in_progress(), "Only concurrent GC");
1970   set_concurrent_strong_root_in_progress(!collection_set()->is_empty());
1971   set_concurrent_weak_root_in_progress(true);
1972   if (unload_classes()) {
1973     _unloader.prepare();
1974   }
1975 }
1976 
1977 void ShenandoahHeap::finish_concurrent_roots() {
1978   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
1979   assert(!is_stw_gc_in_progress(), "Only concurrent GC");
1980   if (unload_classes()) {
1981     _unloader.finish();
1982   }
1983 }
1984 
1985 #ifdef ASSERT
1986 void ShenandoahHeap::assert_gc_workers(uint nworkers) {
1987   assert(nworkers > 0 && nworkers <= max_workers(), "Sanity");
1988 
1989   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
1990     if (UseDynamicNumberOfGCThreads) {
1991       assert(nworkers <= ParallelGCThreads, "Cannot use more than it has");
1992     } else {
1993       // Use ParallelGCThreads inside safepoints
1994       assert(nworkers == ParallelGCThreads, "Use ParallelGCThreads within safepoints");
1995     }
1996   } else {
1997     if (UseDynamicNumberOfGCThreads) {
1998       assert(nworkers <= ConcGCThreads, "Cannot use more than it has");
1999     } else {
2000       // Use ConcGCThreads outside safepoints
2001       assert(nworkers == ConcGCThreads, "Use ConcGCThreads outside safepoints");
2002     }
2003   }
2004 }
2005 #endif
2006 
2007 ShenandoahVerifier* ShenandoahHeap::verifier() {
2008   guarantee(ShenandoahVerify, "Should be enabled");
2009   assert (_verifier != NULL, "sanity");
2010   return _verifier;
2011 }
2012 
2013 template<bool CONCURRENT>
2014 class ShenandoahUpdateHeapRefsTask : public AbstractGangTask {
2015 private:
2016   ShenandoahHeap* _heap;
2017   ShenandoahRegionIterator* _regions;
2018 public:
2019   ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions) :
2020     AbstractGangTask("Shenandoah Update References"),
2021     _heap(ShenandoahHeap::heap()),
2022     _regions(regions) {
2023   }
2024 
2025   void work(uint worker_id) {
2026     if (CONCURRENT) {
2027       ShenandoahConcurrentWorkerSession worker_session(worker_id);
2028       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
2029       do_work<ShenandoahConcUpdateRefsClosure>();
2030     } else {
2031       ShenandoahParallelWorkerSession worker_session(worker_id);
2032       do_work<ShenandoahSTWUpdateRefsClosure>();
2033     }
2034   }
2035 
2036 private:
2037   template<class T>
2038   void do_work() {
2039     T cl;
2040     ShenandoahHeapRegion* r = _regions->next();
2041     ShenandoahMarkingContext* const ctx = _heap->complete_marking_context();
2042     while (r != NULL) {
2043       HeapWord* update_watermark = r->get_update_watermark();
2044       assert (update_watermark >= r->bottom(), "sanity");
2045       if (r->is_active() && !r->is_cset()) {
2046         _heap->marked_object_oop_iterate(r, &cl, update_watermark);
2047       }
2048       if (ShenandoahPacing) {
2049         _heap->pacer()->report_updaterefs(pointer_delta(update_watermark, r->bottom()));
2050       }
2051       if (_heap->check_cancelled_gc_and_yield(CONCURRENT)) {
2052         return;
2053       }
2054       r = _regions->next();
2055     }
2056   }
2057 };
2058 
2059 void ShenandoahHeap::update_heap_references(bool concurrent) {
2060   assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
2061 
2062   if (concurrent) {
2063     ShenandoahUpdateHeapRefsTask<true> task(&_update_refs_iterator);
2064     workers()->run_task(&task);
2065   } else {
2066     ShenandoahUpdateHeapRefsTask<false> task(&_update_refs_iterator);
2067     workers()->run_task(&task);
2068   }
2069 }
2070 
2071 
2072 class ShenandoahFinalUpdateRefsUpdateRegionStateClosure : public ShenandoahHeapRegionClosure {
2073 private:
2074   ShenandoahHeapLock* const _lock;
2075 
2076 public:
2077   ShenandoahFinalUpdateRefsUpdateRegionStateClosure() : _lock(ShenandoahHeap::heap()->lock()) {}
2078 
2079   void heap_region_do(ShenandoahHeapRegion* r) {
2080     // Drop unnecessary "pinned" state from regions that does not have CP marks
2081     // anymore, as this would allow trashing them.
2082 
2083     if (r->is_active()) {
2084       if (r->is_pinned()) {
2085         if (r->pin_count() == 0) {
2086           ShenandoahHeapLocker locker(_lock);
2087           r->make_unpinned();
2088         }
2089       } else {
2090         if (r->pin_count() > 0) {
2091           ShenandoahHeapLocker locker(_lock);
2092           r->make_pinned();
2093         }
2094       }
2095     }
2096   }
2097 
2098   bool is_thread_safe() { return true; }
2099 };
2100 
2101 void ShenandoahHeap::update_heap_region_states(bool concurrent) {
2102   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2103   assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
2104 
2105   {
2106     ShenandoahGCPhase phase(concurrent ?
2107                             ShenandoahPhaseTimings::final_update_refs_update_region_states :
2108                             ShenandoahPhaseTimings::degen_gc_final_update_refs_update_region_states);
2109     ShenandoahFinalUpdateRefsUpdateRegionStateClosure cl;
2110     parallel_heap_region_iterate(&cl);
2111 
2112     assert_pinned_region_status();
2113   }
2114 
2115   {
2116     ShenandoahGCPhase phase(concurrent ?
2117                             ShenandoahPhaseTimings::final_update_refs_trash_cset :
2118                             ShenandoahPhaseTimings::degen_gc_final_update_refs_trash_cset);
2119     trash_cset_regions();
2120   }
2121 }
2122 
2123 void ShenandoahHeap::rebuild_free_set(bool concurrent) {
2124   {
2125     ShenandoahGCPhase phase(concurrent ?
2126                             ShenandoahPhaseTimings::final_update_refs_rebuild_freeset :
2127                             ShenandoahPhaseTimings::degen_gc_final_update_refs_rebuild_freeset);
2128     ShenandoahHeapLocker locker(lock());
2129     _free_set->rebuild();
2130   }
2131 }
2132 
2133 void ShenandoahHeap::print_extended_on(outputStream *st) const {
2134   print_on(st);
2135   st->cr();
2136   print_heap_regions_on(st);
2137 }
2138 
2139 bool ShenandoahHeap::is_bitmap_slice_committed(ShenandoahHeapRegion* r, bool skip_self) {
2140   size_t slice = r->index() / _bitmap_regions_per_slice;
2141 
2142   size_t regions_from = _bitmap_regions_per_slice * slice;
2143   size_t regions_to   = MIN2(num_regions(), _bitmap_regions_per_slice * (slice + 1));
2144   for (size_t g = regions_from; g < regions_to; g++) {
2145     assert (g / _bitmap_regions_per_slice == slice, "same slice");
2146     if (skip_self && g == r->index()) continue;
2147     if (get_region(g)->is_committed()) {
2148       return true;
2149     }
2150   }
2151   return false;
2152 }
2153 
2154 bool ShenandoahHeap::commit_bitmap_slice(ShenandoahHeapRegion* r) {
2155   shenandoah_assert_heaplocked();
2156 
2157   // Bitmaps in special regions do not need commits
2158   if (_bitmap_region_special) {
2159     return true;
2160   }
2161 
2162   if (is_bitmap_slice_committed(r, true)) {
2163     // Some other region from the group is already committed, meaning the bitmap
2164     // slice is already committed, we exit right away.
2165     return true;
2166   }
2167 
2168   // Commit the bitmap slice:
2169   size_t slice = r->index() / _bitmap_regions_per_slice;
2170   size_t off = _bitmap_bytes_per_slice * slice;
2171   size_t len = _bitmap_bytes_per_slice;
2172   char* start = (char*) _bitmap_region.start() + off;
2173 
2174   if (!os::commit_memory(start, len, false)) {
2175     return false;
2176   }
2177 
2178   if (AlwaysPreTouch) {
2179     os::pretouch_memory(start, start + len, _pretouch_bitmap_page_size);
2180   }
2181 
2182   return true;
2183 }
2184 
2185 bool ShenandoahHeap::uncommit_bitmap_slice(ShenandoahHeapRegion *r) {
2186   shenandoah_assert_heaplocked();
2187 
2188   // Bitmaps in special regions do not need uncommits
2189   if (_bitmap_region_special) {
2190     return true;
2191   }
2192 
2193   if (is_bitmap_slice_committed(r, true)) {
2194     // Some other region from the group is still committed, meaning the bitmap
2195     // slice is should stay committed, exit right away.
2196     return true;
2197   }
2198 
2199   // Uncommit the bitmap slice:
2200   size_t slice = r->index() / _bitmap_regions_per_slice;
2201   size_t off = _bitmap_bytes_per_slice * slice;
2202   size_t len = _bitmap_bytes_per_slice;
2203   if (!os::uncommit_memory((char*)_bitmap_region.start() + off, len)) {
2204     return false;
2205   }
2206   return true;
2207 }
2208 
2209 void ShenandoahHeap::safepoint_synchronize_begin() {
2210   if (ShenandoahSuspendibleWorkers || UseStringDeduplication) {
2211     SuspendibleThreadSet::synchronize();
2212   }
2213 }
2214 
2215 void ShenandoahHeap::safepoint_synchronize_end() {
2216   if (ShenandoahSuspendibleWorkers || UseStringDeduplication) {
2217     SuspendibleThreadSet::desynchronize();
2218   }
2219 }
2220 
2221 void ShenandoahHeap::entry_uncommit(double shrink_before, size_t shrink_until) {
2222   static const char *msg = "Concurrent uncommit";
2223   ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_uncommit, true /* log_heap_usage */);
2224   EventMark em("%s", msg);
2225 
2226   op_uncommit(shrink_before, shrink_until);
2227 }
2228 
2229 void ShenandoahHeap::try_inject_alloc_failure() {
2230   if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) {
2231     _inject_alloc_failure.set();
2232     os::naked_short_sleep(1);
2233     if (cancelled_gc()) {
2234       log_info(gc)("Allocation failure was successfully injected");
2235     }
2236   }
2237 }
2238 
2239 bool ShenandoahHeap::should_inject_alloc_failure() {
2240   return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset();
2241 }
2242 
2243 void ShenandoahHeap::initialize_serviceability() {
2244   _memory_pool = new ShenandoahMemoryPool(this);
2245   _cycle_memory_manager.add_pool(_memory_pool);
2246   _stw_memory_manager.add_pool(_memory_pool);
2247 }
2248 
2249 GrowableArray<GCMemoryManager*> ShenandoahHeap::memory_managers() {
2250   GrowableArray<GCMemoryManager*> memory_managers(2);
2251   memory_managers.append(&_cycle_memory_manager);
2252   memory_managers.append(&_stw_memory_manager);
2253   return memory_managers;
2254 }
2255 
2256 GrowableArray<MemoryPool*> ShenandoahHeap::memory_pools() {
2257   GrowableArray<MemoryPool*> memory_pools(1);
2258   memory_pools.append(_memory_pool);
2259   return memory_pools;
2260 }
2261 
2262 MemoryUsage ShenandoahHeap::memory_usage() {
2263   return _memory_pool->get_memory_usage();
2264 }
2265 
2266 ShenandoahRegionIterator::ShenandoahRegionIterator() :
2267   _heap(ShenandoahHeap::heap()),
2268   _index(0) {}
2269 
2270 ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) :
2271   _heap(heap),
2272   _index(0) {}
2273 
2274 void ShenandoahRegionIterator::reset() {
2275   _index = 0;
2276 }
2277 
2278 bool ShenandoahRegionIterator::has_next() const {
2279   return _index < _heap->num_regions();
2280 }
2281 
2282 char ShenandoahHeap::gc_state() const {
2283   return _gc_state.raw_value();
2284 }
2285 
2286 ShenandoahLiveData* ShenandoahHeap::get_liveness_cache(uint worker_id) {
2287 #ifdef ASSERT
2288   assert(_liveness_cache != NULL, "sanity");
2289   assert(worker_id < _max_workers, "sanity");
2290   for (uint i = 0; i < num_regions(); i++) {
2291     assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty");
2292   }
2293 #endif
2294   return _liveness_cache[worker_id];
2295 }
2296 
2297 void ShenandoahHeap::flush_liveness_cache(uint worker_id) {
2298   assert(worker_id < _max_workers, "sanity");
2299   assert(_liveness_cache != NULL, "sanity");
2300   ShenandoahLiveData* ld = _liveness_cache[worker_id];
2301   for (uint i = 0; i < num_regions(); i++) {
2302     ShenandoahLiveData live = ld[i];
2303     if (live > 0) {
2304       ShenandoahHeapRegion* r = get_region(i);
2305       r->increase_live_data_gc_words(live);
2306       ld[i] = 0;
2307     }
2308   }
2309 }
--- EOF ---