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