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