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