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