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