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