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