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