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   ShenandoahHeap* const _heap;
1234   ShenandoahMarkingContext* const _marking_context;
1235 
1236   template <class T>
1237   void do_oop_work(T* p) {
1238     T o = RawAccess<>::oop_load(p);
1239     if (!CompressedOops::is_null(o)) {
1240       oop obj = CompressedOops::decode_not_null(o);
1241       if (_heap->is_concurrent_root_in_progress() && !_marking_context->is_marked(obj)) {
1242         // There may be dead oops in weak roots in concurrent root phase, do not touch them.
1243         return;
1244       }
1245       obj = ShenandoahBarrierSet::resolve_forwarded_not_null(obj);
1246 
1247       assert(oopDesc::is_oop(obj), "must be a valid oop");
1248       if (!_bitmap->is_marked(obj)) {
1249         _bitmap->mark(obj);
1250         _oop_stack->push(obj);
1251       }
1252     }
1253   }
1254 public:
1255   ObjectIterateScanRootClosure(MarkBitMap* bitmap, Stack<oop,mtGC>* oop_stack) :
1256     _bitmap(bitmap), _oop_stack(oop_stack), _heap(ShenandoahHeap::heap()),
1257     _marking_context(_heap->marking_context()) {}
1258   void do_oop(oop* p)       { do_oop_work(p); }
1259   void do_oop(narrowOop* p) { do_oop_work(p); }
1260 };
1261 
1262 /*
1263  * This is public API, used in preparation of object_iterate().
1264  * Since we don't do linear scan of heap in object_iterate() (see comment below), we don't
1265  * need to make the heap parsable. For Shenandoah-internal linear heap scans that we can
1266  * control, we call SH::make_tlabs_parsable().
1267  */
1268 void ShenandoahHeap::ensure_parsability(bool retire_tlabs) {
1269   // No-op.
1270 }
1271 
1272 /*
1273  * Iterates objects in the heap. This is public API, used for, e.g., heap dumping.
1274  *
1275  * We cannot safely iterate objects by doing a linear scan at random points in time. Linear
1276  * scanning needs to deal with dead objects, which may have dead Klass* pointers (e.g.
1277  * calling oopDesc::size() would crash) or dangling reference fields (crashes) etc. Linear
1278  * scanning therefore depends on having a valid marking bitmap to support it. However, we only
1279  * have a valid marking bitmap after successful marking. In particular, we *don't* have a valid
1280  * marking bitmap during marking, after aborted marking or during/after cleanup (when we just
1281  * wiped the bitmap in preparation for next marking).
1282  *
1283  * For all those reasons, we implement object iteration as a single marking traversal, reporting
1284  * objects as we mark+traverse through the heap, starting from GC roots. JVMTI IterateThroughHeap
1285  * is allowed to report dead objects, but is not required to do so.
1286  */
1287 void ShenandoahHeap::object_iterate(ObjectClosure* cl) {
1288   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1289   if (!_aux_bitmap_region_special && !os::commit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size(), false)) {
1290     log_warning(gc)("Could not commit native memory for auxiliary marking bitmap for heap iteration");
1291     return;
1292   }
1293 
1294   // Reset bitmap
1295   _aux_bit_map.clear();
1296 
1297   Stack<oop,mtGC> oop_stack;
1298 
1299   // First, we process GC roots according to current GC cycle. This populates the work stack with initial objects.
1300   ShenandoahHeapIterationRootScanner rp;
1301   ObjectIterateScanRootClosure oops(&_aux_bit_map, &oop_stack);
1302 
1303   rp.roots_do(&oops);
1304 
1305   // Work through the oop stack to traverse heap.
1306   while (! oop_stack.is_empty()) {
1307     oop obj = oop_stack.pop();
1308     assert(oopDesc::is_oop(obj), "must be a valid oop");
1309     cl->do_object(obj);
1310     obj->oop_iterate(&oops);
1311   }
1312 
1313   assert(oop_stack.is_empty(), "should be empty");
1314 
1315   if (!_aux_bitmap_region_special && !os::uncommit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size())) {
1316     log_warning(gc)("Could not uncommit native memory for auxiliary marking bitmap for heap iteration");
1317   }
1318 }
1319 
1320 // Keep alive an object that was loaded with AS_NO_KEEPALIVE.
1321 void ShenandoahHeap::keep_alive(oop obj) {
1322   if (is_concurrent_mark_in_progress()) {
1323     ShenandoahBarrierSet::barrier_set()->enqueue(obj);
1324   }
1325 }
1326 
1327 void ShenandoahHeap::heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1328   for (size_t i = 0; i < num_regions(); i++) {
1329     ShenandoahHeapRegion* current = get_region(i);
1330     blk->heap_region_do(current);
1331   }
1332 }
1333 
1334 class ShenandoahParallelHeapRegionTask : public AbstractGangTask {
1335 private:
1336   ShenandoahHeap* const _heap;
1337   ShenandoahHeapRegionClosure* const _blk;
1338 
1339   DEFINE_PAD_MINUS_SIZE(0, DEFAULT_CACHE_LINE_SIZE, sizeof(volatile size_t));
1340   volatile size_t _index;
1341   DEFINE_PAD_MINUS_SIZE(1, DEFAULT_CACHE_LINE_SIZE, 0);
1342 
1343 public:
1344   ShenandoahParallelHeapRegionTask(ShenandoahHeapRegionClosure* blk) :
1345           AbstractGangTask("Parallel Region Task"),
1346           _heap(ShenandoahHeap::heap()), _blk(blk), _index(0) {}
1347 
1348   void work(uint worker_id) {
1349     size_t stride = ShenandoahParallelRegionStride;
1350 
1351     size_t max = _heap->num_regions();
1352     while (_index < max) {
1353       size_t cur = Atomic::fetch_and_add(&_index, stride);
1354       size_t start = cur;
1355       size_t end = MIN2(cur + stride, max);
1356       if (start >= max) break;
1357 
1358       for (size_t i = cur; i < end; i++) {
1359         ShenandoahHeapRegion* current = _heap->get_region(i);
1360         _blk->heap_region_do(current);
1361       }
1362     }
1363   }
1364 };
1365 
1366 void ShenandoahHeap::parallel_heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1367   assert(blk->is_thread_safe(), "Only thread-safe closures here");
1368   if (num_regions() > ShenandoahParallelRegionStride) {
1369     ShenandoahParallelHeapRegionTask task(blk);
1370     workers()->run_task(&task);
1371   } else {
1372     heap_region_iterate(blk);
1373   }
1374 }
1375 
1376 class ShenandoahClearLivenessClosure : public ShenandoahHeapRegionClosure {
1377 private:
1378   ShenandoahMarkingContext* const _ctx;
1379 public:
1380   ShenandoahClearLivenessClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
1381 
1382   void heap_region_do(ShenandoahHeapRegion* r) {
1383     if (r->is_active()) {
1384       r->clear_live_data();
1385       _ctx->capture_top_at_mark_start(r);
1386     } else {
1387       assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->region_number());
1388       assert(_ctx->top_at_mark_start(r) == r->top(),
1389              "Region " SIZE_FORMAT " should already have correct TAMS", r->region_number());
1390     }
1391   }
1392 
1393   bool is_thread_safe() { return true; }
1394 };
1395 
1396 void ShenandoahHeap::op_init_mark() {
1397   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1398   assert(Thread::current()->is_VM_thread(), "can only do this in VMThread");
1399 
1400   assert(marking_context()->is_bitmap_clear(), "need clear marking bitmap");
1401   assert(!marking_context()->is_complete(), "should not be complete");
1402 
1403   if (ShenandoahVerify) {
1404     verifier()->verify_before_concmark();
1405   }
1406 
1407   if (VerifyBeforeGC) {
1408     Universe::verify();
1409   }
1410 
1411   set_concurrent_mark_in_progress(true);
1412   // We need to reset all TLABs because we'd lose marks on all objects allocated in them.
1413   {
1414     ShenandoahGCPhase phase(ShenandoahPhaseTimings::make_parsable);
1415     make_parsable(true);
1416   }
1417 
1418   {
1419     ShenandoahGCPhase phase(ShenandoahPhaseTimings::clear_liveness);
1420     ShenandoahClearLivenessClosure clc;
1421     parallel_heap_region_iterate(&clc);
1422   }
1423 
1424   // Make above changes visible to worker threads
1425   OrderAccess::fence();
1426 
1427   concurrent_mark()->mark_roots(ShenandoahPhaseTimings::scan_roots);
1428 
1429   if (UseTLAB) {
1430     ShenandoahGCPhase phase(ShenandoahPhaseTimings::resize_tlabs);
1431     resize_tlabs();
1432   }
1433 
1434   if (ShenandoahPacing) {
1435     pacer()->setup_for_mark();
1436   }
1437 }
1438 
1439 void ShenandoahHeap::op_mark() {
1440   concurrent_mark()->mark_from_roots();
1441 }
1442 
1443 class ShenandoahCompleteLivenessClosure : public ShenandoahHeapRegionClosure {
1444 private:
1445   ShenandoahMarkingContext* const _ctx;
1446 public:
1447   ShenandoahCompleteLivenessClosure() : _ctx(ShenandoahHeap::heap()->complete_marking_context()) {}
1448 
1449   void heap_region_do(ShenandoahHeapRegion* r) {
1450     if (r->is_active()) {
1451       HeapWord *tams = _ctx->top_at_mark_start(r);
1452       HeapWord *top = r->top();
1453       if (top > tams) {
1454         r->increase_live_data_alloc_words(pointer_delta(top, tams));
1455       }
1456     } else {
1457       assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->region_number());
1458       assert(_ctx->top_at_mark_start(r) == r->top(),
1459              "Region " SIZE_FORMAT " should have correct TAMS", r->region_number());
1460     }
1461   }
1462 
1463   bool is_thread_safe() { return true; }
1464 };
1465 
1466 void ShenandoahHeap::op_final_mark() {
1467   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1468 
1469   // It is critical that we
1470   // evacuate roots right after finishing marking, so that we don't
1471   // get unmarked objects in the roots.
1472 
1473   if (!cancelled_gc()) {
1474     concurrent_mark()->finish_mark_from_roots(/* full_gc = */ false);
1475 
1476     // Marking is completed, deactivate SATB barrier
1477     set_concurrent_mark_in_progress(false);
1478     mark_complete_marking_context();
1479 
1480     parallel_cleaning(false /* full gc*/);
1481 
1482     if (has_forwarded_objects()) {
1483       // Degen may be caused by failed evacuation of roots
1484       if (is_degenerated_gc_in_progress()) {
1485         concurrent_mark()->update_roots(ShenandoahPhaseTimings::degen_gc_update_roots);
1486       } else {
1487         concurrent_mark()->update_thread_roots(ShenandoahPhaseTimings::update_roots);
1488       }
1489       set_has_forwarded_objects(false);
1490    }
1491 
1492     if (ShenandoahVerify) {
1493       verifier()->verify_roots_no_forwarded();
1494     }
1495     // All allocations past TAMS are implicitly live, adjust the region data.
1496     // Bitmaps/TAMS are swapped at this point, so we need to poll complete bitmap.
1497     {
1498       ShenandoahGCPhase phase(ShenandoahPhaseTimings::complete_liveness);
1499       ShenandoahCompleteLivenessClosure cl;
1500       parallel_heap_region_iterate(&cl);
1501     }
1502 
1503     // Force the threads to reacquire their TLABs outside the collection set.
1504     {
1505       ShenandoahGCPhase phase(ShenandoahPhaseTimings::retire_tlabs);
1506       make_parsable(true);
1507     }
1508 
1509     // We are about to select the collection set, make sure it knows about
1510     // current pinning status. Also, this allows trashing more regions that
1511     // now have their pinning status dropped.
1512     {
1513       ShenandoahGCPhase phase(ShenandoahPhaseTimings::sync_pinned);
1514       sync_pinned_region_status();
1515     }
1516 
1517     // Trash the collection set left over from previous cycle, if any.
1518     {
1519       ShenandoahGCPhase phase(ShenandoahPhaseTimings::trash_cset);
1520       trash_cset_regions();
1521     }
1522 
1523     {
1524       ShenandoahGCPhase phase(ShenandoahPhaseTimings::prepare_evac);
1525 
1526       ShenandoahHeapLocker locker(lock());
1527       _collection_set->clear();
1528       _free_set->clear();
1529 
1530       heuristics()->choose_collection_set(_collection_set);
1531 
1532       _free_set->rebuild();
1533     }
1534 
1535     if (!is_degenerated_gc_in_progress()) {
1536       prepare_concurrent_roots();
1537       prepare_concurrent_unloading();
1538     }
1539 
1540     // If collection set has candidates, start evacuation.
1541     // Otherwise, bypass the rest of the cycle.
1542     if (!collection_set()->is_empty()) {
1543       ShenandoahGCPhase init_evac(ShenandoahPhaseTimings::init_evac);
1544 
1545       if (ShenandoahVerify) {
1546         verifier()->verify_before_evacuation();
1547       }
1548 
1549       set_evacuation_in_progress(true);
1550       // From here on, we need to update references.
1551       set_has_forwarded_objects(true);
1552 
1553       if (!is_degenerated_gc_in_progress()) {
1554         if (ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) {
1555           ShenandoahCodeRoots::arm_nmethods();
1556         }
1557         evacuate_and_update_roots();
1558       }
1559 
1560       if (ShenandoahPacing) {
1561         pacer()->setup_for_evac();
1562       }
1563 
1564       if (ShenandoahVerify) {
1565         ShenandoahRootVerifier::RootTypes types = ShenandoahRootVerifier::None;
1566         if (ShenandoahConcurrentRoots::should_do_concurrent_roots()) {
1567           types = ShenandoahRootVerifier::combine(ShenandoahRootVerifier::JNIHandleRoots, ShenandoahRootVerifier::WeakRoots);
1568           types = ShenandoahRootVerifier::combine(types, ShenandoahRootVerifier::CLDGRoots);
1569           types = ShenandoahRootVerifier::combine(types, ShenandoahRootVerifier::StringDedupRoots);
1570         }
1571 
1572         if (ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) {
1573           types = ShenandoahRootVerifier::combine(types, ShenandoahRootVerifier::CodeRoots);
1574         }
1575         verifier()->verify_roots_no_forwarded_except(types);
1576         verifier()->verify_during_evacuation();
1577       }
1578     } else {
1579       if (ShenandoahVerify) {
1580         verifier()->verify_after_concmark();
1581       }
1582 
1583       if (VerifyAfterGC) {
1584         Universe::verify();
1585       }
1586     }
1587 
1588   } else {
1589     // If this cycle was updating references, we need to keep the has_forwarded_objects
1590     // flag on, for subsequent phases to deal with it.
1591     concurrent_mark()->cancel();
1592     set_concurrent_mark_in_progress(false);
1593 
1594     if (process_references()) {
1595       // Abandon reference processing right away: pre-cleaning must have failed.
1596       ReferenceProcessor *rp = ref_processor();
1597       rp->disable_discovery();
1598       rp->abandon_partial_discovery();
1599       rp->verify_no_references_recorded();
1600     }
1601   }
1602 }
1603 
1604 void ShenandoahHeap::op_final_evac() {
1605   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1606 
1607   set_evacuation_in_progress(false);
1608 
1609   {
1610     ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac_retire_gclabs);
1611     retire_and_reset_gclabs();
1612   }
1613 
1614   if (ShenandoahVerify) {
1615     verifier()->verify_after_evacuation();
1616   }
1617 
1618   if (VerifyAfterGC) {
1619     Universe::verify();
1620   }
1621 }
1622 
1623 void ShenandoahHeap::op_conc_evac() {
1624   ShenandoahEvacuationTask task(this, _collection_set, true);
1625   workers()->run_task(&task);
1626 }
1627 
1628 void ShenandoahHeap::op_stw_evac() {
1629   ShenandoahEvacuationTask task(this, _collection_set, false);
1630   workers()->run_task(&task);
1631 }
1632 
1633 void ShenandoahHeap::op_updaterefs() {
1634   update_heap_references(true);
1635 }
1636 
1637 void ShenandoahHeap::op_cleanup() {
1638   free_set()->recycle_trash();
1639 }
1640 
1641 class ShenandoahConcurrentRootsEvacUpdateTask : public AbstractGangTask {
1642 private:
1643   ShenandoahVMRoots<true /*concurrent*/>        _vm_roots;
1644   ShenandoahWeakRoots<true /*concurrent*/>      _weak_roots;
1645   ShenandoahClassLoaderDataRoots<true /*concurrent*/, false /*single threaded*/> _cld_roots;
1646   ShenandoahConcurrentStringDedupRoots          _dedup_roots;
1647   bool                                          _include_weak_roots;
1648 
1649 public:
1650   ShenandoahConcurrentRootsEvacUpdateTask(bool include_weak_roots) :
1651     AbstractGangTask("Shenandoah Evacuate/Update Concurrent Roots Task"),
1652     _include_weak_roots(include_weak_roots) {
1653   }
1654 
1655   void work(uint worker_id) {
1656     ShenandoahEvacOOMScope oom;
1657     {
1658       // vm_roots and weak_roots are OopStorage backed roots, concurrent iteration
1659       // may race against OopStorage::release() calls.
1660       ShenandoahEvacUpdateOopStorageRootsClosure cl;
1661       _vm_roots.oops_do<ShenandoahEvacUpdateOopStorageRootsClosure>(&cl);
1662 
1663       if (_include_weak_roots) {
1664         _weak_roots.oops_do<ShenandoahEvacUpdateOopStorageRootsClosure>(&cl);
1665       }
1666     }
1667 
1668     {
1669       ShenandoahEvacuateUpdateRootsClosure<> cl;
1670       CLDToOopClosure clds(&cl, ClassLoaderData::_claim_strong);
1671       _cld_roots.cld_do(&clds);
1672     }
1673 
1674     {
1675       ShenandoahForwardedIsAliveClosure is_alive;
1676       ShenandoahEvacuateUpdateRootsClosure<MO_RELEASE> keep_alive;
1677       _dedup_roots.oops_do(&is_alive, &keep_alive, worker_id);
1678     }
1679   }
1680 };
1681 
1682 class ShenandoahEvacUpdateCleanupOopStorageRootsClosure : public BasicOopIterateClosure {
1683 private:
1684   ShenandoahHeap* const _heap;
1685   ShenandoahMarkingContext* const _mark_context;
1686   bool  _evac_in_progress;
1687   Thread* const _thread;
1688   size_t  _dead_counter;
1689 
1690 public:
1691   ShenandoahEvacUpdateCleanupOopStorageRootsClosure();
1692   void do_oop(oop* p);
1693   void do_oop(narrowOop* p);
1694 
1695   size_t dead_counter() const;
1696   void reset_dead_counter();
1697 };
1698 
1699 ShenandoahEvacUpdateCleanupOopStorageRootsClosure::ShenandoahEvacUpdateCleanupOopStorageRootsClosure() :
1700   _heap(ShenandoahHeap::heap()),
1701   _mark_context(ShenandoahHeap::heap()->marking_context()),
1702   _evac_in_progress(ShenandoahHeap::heap()->is_evacuation_in_progress()),
1703   _thread(Thread::current()),
1704   _dead_counter(0) {
1705 }
1706 
1707 void ShenandoahEvacUpdateCleanupOopStorageRootsClosure::do_oop(oop* p) {
1708   const oop obj = RawAccess<>::oop_load(p);
1709   if (!CompressedOops::is_null(obj)) {
1710     if (!_mark_context->is_marked(obj)) {
1711       shenandoah_assert_correct(p, obj);
1712       oop old = Atomic::cmpxchg(p, obj, oop(NULL));
1713       if (obj == old) {
1714         _dead_counter ++;
1715       }
1716     } else if (_evac_in_progress && _heap->in_collection_set(obj)) {
1717       oop resolved = ShenandoahBarrierSet::resolve_forwarded_not_null(obj);
1718       if (resolved == obj) {
1719         resolved = _heap->evacuate_object(obj, _thread);
1720       }
1721       Atomic::cmpxchg(p, obj, resolved);
1722       assert(_heap->cancelled_gc() ||
1723              _mark_context->is_marked(resolved) && !_heap->in_collection_set(resolved),
1724              "Sanity");
1725     }
1726   }
1727 }
1728 
1729 void ShenandoahEvacUpdateCleanupOopStorageRootsClosure::do_oop(narrowOop* p) {
1730   ShouldNotReachHere();
1731 }
1732 
1733 size_t ShenandoahEvacUpdateCleanupOopStorageRootsClosure::dead_counter() const {
1734   return _dead_counter;
1735 }
1736 
1737 void ShenandoahEvacUpdateCleanupOopStorageRootsClosure::reset_dead_counter() {
1738   _dead_counter = 0;
1739 }
1740 
1741 // This task not only evacuates/updates marked weak roots, but also "NULL"
1742 // dead weak roots.
1743 class ShenandoahConcurrentWeakRootsEvacUpdateTask : public AbstractGangTask {
1744 private:
1745   ShenandoahWeakRoot<true /*concurrent*/>  _jni_roots;
1746   ShenandoahWeakRoot<true /*concurrent*/>  _string_table_roots;
1747   ShenandoahWeakRoot<true /*concurrent*/>  _resolved_method_table_roots;
1748   ShenandoahWeakRoot<true /*concurrent*/>  _vm_roots;
1749 
1750 public:
1751   ShenandoahConcurrentWeakRootsEvacUpdateTask() :
1752     AbstractGangTask("Shenandoah Concurrent Weak Root Task"),
1753     _jni_roots(OopStorageSet::jni_weak(), ShenandoahPhaseTimings::JNIWeakRoots),
1754     _string_table_roots(OopStorageSet::string_table_weak(), ShenandoahPhaseTimings::StringTableRoots),
1755     _resolved_method_table_roots(OopStorageSet::resolved_method_table_weak(), ShenandoahPhaseTimings::ResolvedMethodTableRoots),
1756     _vm_roots(OopStorageSet::vm_weak(), ShenandoahPhaseTimings::VMWeakRoots) {
1757     StringTable::reset_dead_counter();
1758     ResolvedMethodTable::reset_dead_counter();
1759   }
1760 
1761   ~ShenandoahConcurrentWeakRootsEvacUpdateTask() {
1762     StringTable::finish_dead_counter();
1763     ResolvedMethodTable::finish_dead_counter();
1764   }
1765 
1766   void work(uint worker_id) {
1767     ShenandoahEvacOOMScope oom;
1768     // jni_roots and weak_roots are OopStorage backed roots, concurrent iteration
1769     // may race against OopStorage::release() calls.
1770     ShenandoahEvacUpdateCleanupOopStorageRootsClosure cl;
1771     _jni_roots.oops_do(&cl, worker_id);
1772     _vm_roots.oops_do(&cl, worker_id);
1773 
1774     cl.reset_dead_counter();
1775     _string_table_roots.oops_do(&cl, worker_id);
1776     StringTable::inc_dead_counter(cl.dead_counter());
1777 
1778     cl.reset_dead_counter();
1779     _resolved_method_table_roots.oops_do(&cl, worker_id);
1780     ResolvedMethodTable::inc_dead_counter(cl.dead_counter());
1781   }
1782 };
1783 
1784 void ShenandoahHeap::op_roots() {
1785   if (is_concurrent_root_in_progress()) {
1786     if (ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) {
1787       // Concurrent weak root processing
1788       ShenandoahConcurrentWeakRootsEvacUpdateTask task;
1789       workers()->run_task(&task);
1790 
1791       _unloader.unload();
1792     }
1793 
1794     if (ShenandoahConcurrentRoots::should_do_concurrent_roots()) {
1795       ShenandoahConcurrentRootsEvacUpdateTask task(!ShenandoahConcurrentRoots::should_do_concurrent_class_unloading());
1796       workers()->run_task(&task);
1797     }
1798   }
1799 
1800   set_concurrent_root_in_progress(false);
1801 }
1802 
1803 void ShenandoahHeap::op_reset() {
1804   reset_mark_bitmap();
1805 }
1806 
1807 void ShenandoahHeap::op_preclean() {
1808   concurrent_mark()->preclean_weak_refs();
1809 }
1810 
1811 void ShenandoahHeap::op_init_traversal() {
1812   traversal_gc()->init_traversal_collection();
1813 }
1814 
1815 void ShenandoahHeap::op_traversal() {
1816   traversal_gc()->concurrent_traversal_collection();
1817 }
1818 
1819 void ShenandoahHeap::op_final_traversal() {
1820   traversal_gc()->final_traversal_collection();
1821 }
1822 
1823 void ShenandoahHeap::op_full(GCCause::Cause cause) {
1824   ShenandoahMetricsSnapshot metrics;
1825   metrics.snap_before();
1826 
1827   full_gc()->do_it(cause);
1828   if (UseTLAB) {
1829     ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_resize_tlabs);
1830     resize_all_tlabs();
1831   }
1832 
1833   metrics.snap_after();
1834 
1835   if (metrics.is_good_progress()) {
1836     _progress_last_gc.set();
1837   } else {
1838     // Nothing to do. Tell the allocation path that we have failed to make
1839     // progress, and it can finally fail.
1840     _progress_last_gc.unset();
1841   }
1842 }
1843 
1844 void ShenandoahHeap::op_degenerated(ShenandoahDegenPoint point) {
1845   // Degenerated GC is STW, but it can also fail. Current mechanics communicates
1846   // GC failure via cancelled_concgc() flag. So, if we detect the failure after
1847   // some phase, we have to upgrade the Degenerate GC to Full GC.
1848 
1849   clear_cancelled_gc();
1850 
1851   ShenandoahMetricsSnapshot metrics;
1852   metrics.snap_before();
1853 
1854   switch (point) {
1855     case _degenerated_traversal:
1856       {
1857         // Drop the collection set. Note: this leaves some already forwarded objects
1858         // behind, which may be problematic, see comments for ShenandoahEvacAssist
1859         // workarounds in ShenandoahTraversalHeuristics.
1860 
1861         ShenandoahHeapLocker locker(lock());
1862         collection_set()->clear_current_index();
1863         for (size_t i = 0; i < collection_set()->count(); i++) {
1864           ShenandoahHeapRegion* r = collection_set()->next();
1865           r->make_regular_bypass();
1866         }
1867         collection_set()->clear();
1868       }
1869       op_final_traversal();
1870       op_cleanup();
1871       return;
1872 
1873     // The cases below form the Duff's-like device: it describes the actual GC cycle,
1874     // but enters it at different points, depending on which concurrent phase had
1875     // degenerated.
1876 
1877     case _degenerated_outside_cycle:
1878       // We have degenerated from outside the cycle, which means something is bad with
1879       // the heap, most probably heavy humongous fragmentation, or we are very low on free
1880       // space. It makes little sense to wait for Full GC to reclaim as much as it can, when
1881       // we can do the most aggressive degen cycle, which includes processing references and
1882       // class unloading, unless those features are explicitly disabled.
1883       //
1884       // Note that we can only do this for "outside-cycle" degens, otherwise we would risk
1885       // changing the cycle parameters mid-cycle during concurrent -> degenerated handover.
1886       set_process_references(heuristics()->can_process_references());
1887       set_unload_classes(heuristics()->can_unload_classes());
1888 
1889       if (is_traversal_mode()) {
1890         // Not possible to degenerate from here, upgrade to Full GC right away.
1891         cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1892         op_degenerated_fail();
1893         return;
1894       }
1895 
1896       op_reset();
1897 
1898       op_init_mark();
1899       if (cancelled_gc()) {
1900         op_degenerated_fail();
1901         return;
1902       }
1903 
1904     case _degenerated_mark:
1905       op_final_mark();
1906       if (cancelled_gc()) {
1907         op_degenerated_fail();
1908         return;
1909       }
1910 
1911       op_cleanup();
1912 
1913     case _degenerated_evac:
1914       // If heuristics thinks we should do the cycle, this flag would be set,
1915       // and we can do evacuation. Otherwise, it would be the shortcut cycle.
1916       if (is_evacuation_in_progress()) {
1917 
1918         // Degeneration under oom-evac protocol might have left some objects in
1919         // collection set un-evacuated. Restart evacuation from the beginning to
1920         // capture all objects. For all the objects that are already evacuated,
1921         // it would be a simple check, which is supposed to be fast. This is also
1922         // safe to do even without degeneration, as CSet iterator is at beginning
1923         // in preparation for evacuation anyway.
1924         //
1925         // Before doing that, we need to make sure we never had any cset-pinned
1926         // regions. This may happen if allocation failure happened when evacuating
1927         // the about-to-be-pinned object, oom-evac protocol left the object in
1928         // the collection set, and then the pin reached the cset region. If we continue
1929         // the cycle here, we would trash the cset and alive objects in it. To avoid
1930         // it, we fail degeneration right away and slide into Full GC to recover.
1931 
1932         {
1933           sync_pinned_region_status();
1934           collection_set()->clear_current_index();
1935 
1936           ShenandoahHeapRegion* r;
1937           while ((r = collection_set()->next()) != NULL) {
1938             if (r->is_pinned()) {
1939               cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1940               op_degenerated_fail();
1941               return;
1942             }
1943           }
1944 
1945           collection_set()->clear_current_index();
1946         }
1947 
1948         op_stw_evac();
1949         if (cancelled_gc()) {
1950           op_degenerated_fail();
1951           return;
1952         }
1953       }
1954 
1955       // If heuristics thinks we should do the cycle, this flag would be set,
1956       // and we need to do update-refs. Otherwise, it would be the shortcut cycle.
1957       if (has_forwarded_objects()) {
1958         op_init_updaterefs();
1959         if (cancelled_gc()) {
1960           op_degenerated_fail();
1961           return;
1962         }
1963       }
1964 
1965     case _degenerated_updaterefs:
1966       if (has_forwarded_objects()) {
1967         op_final_updaterefs();
1968         if (cancelled_gc()) {
1969           op_degenerated_fail();
1970           return;
1971         }
1972       }
1973 
1974       op_cleanup();
1975       break;
1976 
1977     default:
1978       ShouldNotReachHere();
1979   }
1980 
1981   if (ShenandoahVerify) {
1982     verifier()->verify_after_degenerated();
1983   }
1984 
1985   if (VerifyAfterGC) {
1986     Universe::verify();
1987   }
1988 
1989   metrics.snap_after();
1990 
1991   // Check for futility and fail. There is no reason to do several back-to-back Degenerated cycles,
1992   // because that probably means the heap is overloaded and/or fragmented.
1993   if (!metrics.is_good_progress()) {
1994     _progress_last_gc.unset();
1995     cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1996     op_degenerated_futile();
1997   } else {
1998     _progress_last_gc.set();
1999   }
2000 }
2001 
2002 void ShenandoahHeap::op_degenerated_fail() {
2003   log_info(gc)("Cannot finish degeneration, upgrading to Full GC");
2004   shenandoah_policy()->record_degenerated_upgrade_to_full();
2005   op_full(GCCause::_shenandoah_upgrade_to_full_gc);
2006 }
2007 
2008 void ShenandoahHeap::op_degenerated_futile() {
2009   shenandoah_policy()->record_degenerated_upgrade_to_full();
2010   op_full(GCCause::_shenandoah_upgrade_to_full_gc);
2011 }
2012 
2013 void ShenandoahHeap::force_satb_flush_all_threads() {
2014   if (!is_concurrent_mark_in_progress() && !is_concurrent_traversal_in_progress()) {
2015     // No need to flush SATBs
2016     return;
2017   }
2018 
2019   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
2020     ShenandoahThreadLocalData::set_force_satb_flush(t, true);
2021   }
2022   // The threads are not "acquiring" their thread-local data, but it does not
2023   // hurt to "release" the updates here anyway.
2024   OrderAccess::fence();
2025 }
2026 
2027 void ShenandoahHeap::set_gc_state_all_threads(char state) {
2028   for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) {
2029     ShenandoahThreadLocalData::set_gc_state(t, state);
2030   }
2031 }
2032 
2033 void ShenandoahHeap::set_gc_state_mask(uint mask, bool value) {
2034   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should really be Shenandoah safepoint");
2035   _gc_state.set_cond(mask, value);
2036   set_gc_state_all_threads(_gc_state.raw_value());
2037 }
2038 
2039 void ShenandoahHeap::set_concurrent_mark_in_progress(bool in_progress) {
2040   if (has_forwarded_objects()) {
2041     set_gc_state_mask(MARKING | UPDATEREFS, in_progress);
2042   } else {
2043     set_gc_state_mask(MARKING, in_progress);
2044   }
2045   ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
2046 }
2047 
2048 void ShenandoahHeap::set_concurrent_traversal_in_progress(bool in_progress) {
2049    set_gc_state_mask(TRAVERSAL, in_progress);
2050    ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
2051 }
2052 
2053 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {
2054   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint");
2055   set_gc_state_mask(EVACUATION, in_progress);
2056 }
2057 
2058 void ShenandoahHeap::set_concurrent_root_in_progress(bool in_progress) {
2059   assert(ShenandoahConcurrentRoots::can_do_concurrent_roots(), "Why set the flag?");
2060   if (in_progress) {
2061     _concurrent_root_in_progress.set();
2062   } else {
2063     _concurrent_root_in_progress.unset();
2064   }
2065 }
2066 
2067 void ShenandoahHeap::ref_processing_init() {
2068   assert(_max_workers > 0, "Sanity");
2069 
2070   _ref_processor =
2071     new ReferenceProcessor(&_subject_to_discovery,  // is_subject_to_discovery
2072                            ParallelRefProcEnabled,  // MT processing
2073                            _max_workers,            // Degree of MT processing
2074                            true,                    // MT discovery
2075                            _max_workers,            // Degree of MT discovery
2076                            false,                   // Reference discovery is not atomic
2077                            NULL,                    // No closure, should be installed before use
2078                            true);                   // Scale worker threads
2079 
2080   shenandoah_assert_rp_isalive_not_installed();
2081 }
2082 
2083 GCTracer* ShenandoahHeap::tracer() {
2084   return shenandoah_policy()->tracer();
2085 }
2086 
2087 size_t ShenandoahHeap::tlab_used(Thread* thread) const {
2088   return _free_set->used();
2089 }
2090 
2091 bool ShenandoahHeap::try_cancel_gc() {
2092   while (true) {
2093     jbyte prev = _cancelled_gc.cmpxchg(CANCELLED, CANCELLABLE);
2094     if (prev == CANCELLABLE) return true;
2095     else if (prev == CANCELLED) return false;
2096     assert(ShenandoahSuspendibleWorkers, "should not get here when not using suspendible workers");
2097     assert(prev == NOT_CANCELLED, "must be NOT_CANCELLED");
2098     if (Thread::current()->is_Java_thread()) {
2099       // We need to provide a safepoint here, otherwise we might
2100       // spin forever if a SP is pending.
2101       ThreadBlockInVM sp(JavaThread::current());
2102       SpinPause();
2103     }
2104   }
2105 }
2106 
2107 void ShenandoahHeap::cancel_gc(GCCause::Cause cause) {
2108   if (try_cancel_gc()) {
2109     FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause));
2110     log_info(gc)("%s", msg.buffer());
2111     Events::log(Thread::current(), "%s", msg.buffer());
2112   }
2113 }
2114 
2115 uint ShenandoahHeap::max_workers() {
2116   return _max_workers;
2117 }
2118 
2119 void ShenandoahHeap::stop() {
2120   // The shutdown sequence should be able to terminate when GC is running.
2121 
2122   // Step 0. Notify policy to disable event recording.
2123   _shenandoah_policy->record_shutdown();
2124 
2125   // Step 1. Notify control thread that we are in shutdown.
2126   // Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown.
2127   // Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below.
2128   control_thread()->prepare_for_graceful_shutdown();
2129 
2130   // Step 2. Notify GC workers that we are cancelling GC.
2131   cancel_gc(GCCause::_shenandoah_stop_vm);
2132 
2133   // Step 3. Wait until GC worker exits normally.
2134   control_thread()->stop();
2135 
2136   // Step 4. Stop String Dedup thread if it is active
2137   if (ShenandoahStringDedup::is_enabled()) {
2138     ShenandoahStringDedup::stop();
2139   }
2140 }
2141 
2142 void ShenandoahHeap::stw_unload_classes(bool full_gc) {
2143   if (!unload_classes()) return;
2144   bool purged_class;
2145 
2146   // Unload classes and purge SystemDictionary.
2147   {
2148     ShenandoahGCPhase phase(full_gc ?
2149                             ShenandoahPhaseTimings::full_gc_purge_class_unload :
2150                             ShenandoahPhaseTimings::purge_class_unload);
2151     purged_class = SystemDictionary::do_unloading(gc_timer());
2152   }
2153 
2154   {
2155     ShenandoahGCPhase phase(full_gc ?
2156                             ShenandoahPhaseTimings::full_gc_purge_par :
2157                             ShenandoahPhaseTimings::purge_par);
2158     ShenandoahIsAliveSelector is_alive;
2159     uint num_workers = _workers->active_workers();
2160     ShenandoahClassUnloadingTask unlink_task(is_alive.is_alive_closure(), num_workers, purged_class);
2161     _workers->run_task(&unlink_task);
2162   }
2163 
2164   {
2165     ShenandoahGCPhase phase(full_gc ?
2166                             ShenandoahPhaseTimings::full_gc_purge_cldg :
2167                             ShenandoahPhaseTimings::purge_cldg);
2168     ClassLoaderDataGraph::purge();
2169   }
2170   // Resize and verify metaspace
2171   MetaspaceGC::compute_new_size();
2172   MetaspaceUtils::verify_metrics();
2173 }
2174 
2175 // Weak roots are either pre-evacuated (final mark) or updated (final updaterefs),
2176 // so they should not have forwarded oops.
2177 // However, we do need to "null" dead oops in the roots, if can not be done
2178 // in concurrent cycles.
2179 void ShenandoahHeap::stw_process_weak_roots(bool full_gc) {
2180   ShenandoahGCPhase root_phase(full_gc ?
2181                                ShenandoahPhaseTimings::full_gc_purge :
2182                                ShenandoahPhaseTimings::purge);
2183   uint num_workers = _workers->active_workers();
2184   ShenandoahPhaseTimings::Phase timing_phase = full_gc ?
2185                                                ShenandoahPhaseTimings::full_gc_purge_par :
2186                                                ShenandoahPhaseTimings::purge_par;
2187   // Cleanup weak roots
2188   ShenandoahGCPhase phase(timing_phase);
2189   phase_timings()->record_workers_start(timing_phase);
2190   if (has_forwarded_objects()) {
2191     if (is_traversal_mode()) {
2192       ShenandoahForwardedIsAliveClosure is_alive;
2193       ShenandoahTraversalUpdateRefsClosure keep_alive;
2194       ShenandoahParallelWeakRootsCleaningTask<ShenandoahForwardedIsAliveClosure, ShenandoahTraversalUpdateRefsClosure>
2195         cleaning_task(&is_alive, &keep_alive, num_workers, !ShenandoahConcurrentRoots::should_do_concurrent_class_unloading());
2196       _workers->run_task(&cleaning_task);
2197     } else {
2198       ShenandoahForwardedIsAliveClosure is_alive;
2199       ShenandoahUpdateRefsClosure keep_alive;
2200       ShenandoahParallelWeakRootsCleaningTask<ShenandoahForwardedIsAliveClosure, ShenandoahUpdateRefsClosure>
2201         cleaning_task(&is_alive, &keep_alive, num_workers, !ShenandoahConcurrentRoots::should_do_concurrent_class_unloading());
2202       _workers->run_task(&cleaning_task);
2203     }
2204   } else {
2205     ShenandoahIsAliveClosure is_alive;
2206 #ifdef ASSERT
2207     ShenandoahAssertNotForwardedClosure verify_cl;
2208     ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, ShenandoahAssertNotForwardedClosure>
2209       cleaning_task(&is_alive, &verify_cl, num_workers, !ShenandoahConcurrentRoots::should_do_concurrent_class_unloading());
2210 #else
2211     ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, DoNothingClosure>
2212       cleaning_task(&is_alive, &do_nothing_cl, num_workers, !ShenandoahConcurrentRoots::should_do_concurrent_class_unloading());
2213 #endif
2214     _workers->run_task(&cleaning_task);
2215   }
2216   phase_timings()->record_workers_end(timing_phase);
2217 }
2218 
2219 void ShenandoahHeap::parallel_cleaning(bool full_gc) {
2220   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2221   stw_process_weak_roots(full_gc);
2222   if (!ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) {
2223     stw_unload_classes(full_gc);
2224   }
2225 }
2226 
2227 void ShenandoahHeap::set_has_forwarded_objects(bool cond) {
2228   if (is_traversal_mode()) {
2229     set_gc_state_mask(HAS_FORWARDED | UPDATEREFS, cond);
2230   } else {
2231     set_gc_state_mask(HAS_FORWARDED, cond);
2232   }
2233 
2234 }
2235 
2236 void ShenandoahHeap::set_process_references(bool pr) {
2237   _process_references.set_cond(pr);
2238 }
2239 
2240 void ShenandoahHeap::set_unload_classes(bool uc) {
2241   _unload_classes.set_cond(uc);
2242 }
2243 
2244 bool ShenandoahHeap::process_references() const {
2245   return _process_references.is_set();
2246 }
2247 
2248 bool ShenandoahHeap::unload_classes() const {
2249   return _unload_classes.is_set();
2250 }
2251 
2252 address ShenandoahHeap::in_cset_fast_test_addr() {
2253   ShenandoahHeap* heap = ShenandoahHeap::heap();
2254   assert(heap->collection_set() != NULL, "Sanity");
2255   return (address) heap->collection_set()->biased_map_address();
2256 }
2257 
2258 address ShenandoahHeap::cancelled_gc_addr() {
2259   return (address) ShenandoahHeap::heap()->_cancelled_gc.addr_of();
2260 }
2261 
2262 address ShenandoahHeap::gc_state_addr() {
2263   return (address) ShenandoahHeap::heap()->_gc_state.addr_of();
2264 }
2265 
2266 size_t ShenandoahHeap::bytes_allocated_since_gc_start() {
2267   return Atomic::load_acquire(&_bytes_allocated_since_gc_start);
2268 }
2269 
2270 void ShenandoahHeap::reset_bytes_allocated_since_gc_start() {
2271   Atomic::release_store_fence(&_bytes_allocated_since_gc_start, (size_t)0);
2272 }
2273 
2274 void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) {
2275   _degenerated_gc_in_progress.set_cond(in_progress);
2276 }
2277 
2278 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {
2279   _full_gc_in_progress.set_cond(in_progress);
2280 }
2281 
2282 void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) {
2283   assert (is_full_gc_in_progress(), "should be");
2284   _full_gc_move_in_progress.set_cond(in_progress);
2285 }
2286 
2287 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {
2288   set_gc_state_mask(UPDATEREFS, in_progress);
2289 }
2290 
2291 void ShenandoahHeap::register_nmethod(nmethod* nm) {
2292   ShenandoahCodeRoots::register_nmethod(nm);
2293 }
2294 
2295 void ShenandoahHeap::unregister_nmethod(nmethod* nm) {
2296   ShenandoahCodeRoots::unregister_nmethod(nm);
2297 }
2298 
2299 void ShenandoahHeap::flush_nmethod(nmethod* nm) {
2300   ShenandoahCodeRoots::flush_nmethod(nm);
2301 }
2302 
2303 oop ShenandoahHeap::pin_object(JavaThread* thr, oop o) {
2304   heap_region_containing(o)->record_pin();
2305   return o;
2306 }
2307 
2308 void ShenandoahHeap::unpin_object(JavaThread* thr, oop o) {
2309   heap_region_containing(o)->record_unpin();
2310 }
2311 
2312 void ShenandoahHeap::sync_pinned_region_status() {
2313   ShenandoahHeapLocker locker(lock());
2314 
2315   for (size_t i = 0; i < num_regions(); i++) {
2316     ShenandoahHeapRegion *r = get_region(i);
2317     if (r->is_active()) {
2318       if (r->is_pinned()) {
2319         if (r->pin_count() == 0) {
2320           r->make_unpinned();
2321         }
2322       } else {
2323         if (r->pin_count() > 0) {
2324           r->make_pinned();
2325         }
2326       }
2327     }
2328   }
2329 
2330   assert_pinned_region_status();
2331 }
2332 
2333 #ifdef ASSERT
2334 void ShenandoahHeap::assert_pinned_region_status() {
2335   for (size_t i = 0; i < num_regions(); i++) {
2336     ShenandoahHeapRegion* r = get_region(i);
2337     assert((r->is_pinned() && r->pin_count() > 0) || (!r->is_pinned() && r->pin_count() == 0),
2338            "Region " SIZE_FORMAT " pinning status is inconsistent", i);
2339   }
2340 }
2341 #endif
2342 
2343 GCTimer* ShenandoahHeap::gc_timer() const {
2344   return _gc_timer;
2345 }
2346 
2347 void ShenandoahHeap::prepare_concurrent_roots() {
2348   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2349   if (ShenandoahConcurrentRoots::should_do_concurrent_roots()) {
2350     set_concurrent_root_in_progress(true);
2351   }
2352 }
2353 
2354 void ShenandoahHeap::prepare_concurrent_unloading() {
2355   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2356   if (ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) {
2357     _unloader.prepare();
2358   }
2359 }
2360 
2361 void ShenandoahHeap::finish_concurrent_unloading() {
2362   assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
2363   if (ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) {
2364     _unloader.finish();
2365   }
2366 }
2367 
2368 #ifdef ASSERT
2369 void ShenandoahHeap::assert_gc_workers(uint nworkers) {
2370   assert(nworkers > 0 && nworkers <= max_workers(), "Sanity");
2371 
2372   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
2373     if (UseDynamicNumberOfGCThreads ||
2374         (FLAG_IS_DEFAULT(ParallelGCThreads) && ForceDynamicNumberOfGCThreads)) {
2375       assert(nworkers <= ParallelGCThreads, "Cannot use more than it has");
2376     } else {
2377       // Use ParallelGCThreads inside safepoints
2378       assert(nworkers == ParallelGCThreads, "Use ParalleGCThreads within safepoints");
2379     }
2380   } else {
2381     if (UseDynamicNumberOfGCThreads ||
2382         (FLAG_IS_DEFAULT(ConcGCThreads) && ForceDynamicNumberOfGCThreads)) {
2383       assert(nworkers <= ConcGCThreads, "Cannot use more than it has");
2384     } else {
2385       // Use ConcGCThreads outside safepoints
2386       assert(nworkers == ConcGCThreads, "Use ConcGCThreads outside safepoints");
2387     }
2388   }
2389 }
2390 #endif
2391 
2392 ShenandoahVerifier* ShenandoahHeap::verifier() {
2393   guarantee(ShenandoahVerify, "Should be enabled");
2394   assert (_verifier != NULL, "sanity");
2395   return _verifier;
2396 }
2397 
2398 template<class T>
2399 class ShenandoahUpdateHeapRefsTask : public AbstractGangTask {
2400 private:
2401   T cl;
2402   ShenandoahHeap* _heap;
2403   ShenandoahRegionIterator* _regions;
2404   bool _concurrent;
2405 public:
2406   ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions, bool concurrent) :
2407     AbstractGangTask("Concurrent Update References Task"),
2408     cl(T()),
2409     _heap(ShenandoahHeap::heap()),
2410     _regions(regions),
2411     _concurrent(concurrent) {
2412   }
2413 
2414   void work(uint worker_id) {
2415     if (_concurrent) {
2416       ShenandoahConcurrentWorkerSession worker_session(worker_id);
2417       ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
2418       do_work();
2419     } else {
2420       ShenandoahParallelWorkerSession worker_session(worker_id);
2421       do_work();
2422     }
2423   }
2424 
2425 private:
2426   void do_work() {
2427     ShenandoahHeapRegion* r = _regions->next();
2428     ShenandoahMarkingContext* const ctx = _heap->complete_marking_context();
2429     while (r != NULL) {
2430       HeapWord* top_at_start_ur = r->concurrent_iteration_safe_limit();
2431       assert (top_at_start_ur >= r->bottom(), "sanity");
2432       if (r->is_active() && !r->is_cset()) {
2433         _heap->marked_object_oop_iterate(r, &cl, top_at_start_ur);
2434       }
2435       if (ShenandoahPacing) {
2436         _heap->pacer()->report_updaterefs(pointer_delta(top_at_start_ur, r->bottom()));
2437       }
2438       if (_heap->check_cancelled_gc_and_yield(_concurrent)) {
2439         return;
2440       }
2441       r = _regions->next();
2442     }
2443   }
2444 };
2445 
2446 void ShenandoahHeap::update_heap_references(bool concurrent) {
2447   ShenandoahUpdateHeapRefsTask<ShenandoahUpdateHeapRefsClosure> task(&_update_refs_iterator, concurrent);
2448   workers()->run_task(&task);
2449 }
2450 
2451 void ShenandoahHeap::op_init_updaterefs() {
2452   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2453 
2454   set_evacuation_in_progress(false);
2455 
2456   {
2457     ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs_retire_gclabs);
2458     retire_and_reset_gclabs();
2459   }
2460 
2461   if (ShenandoahVerify) {
2462     if (!is_degenerated_gc_in_progress()) {
2463       verifier()->verify_roots_in_to_space_except(ShenandoahRootVerifier::ThreadRoots);
2464     }
2465     verifier()->verify_before_updaterefs();
2466   }
2467 
2468   set_update_refs_in_progress(true);
2469 
2470   {
2471     ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs_prepare);
2472 
2473     make_parsable(true);
2474     for (uint i = 0; i < num_regions(); i++) {
2475       ShenandoahHeapRegion* r = get_region(i);
2476       r->set_concurrent_iteration_safe_limit(r->top());
2477     }
2478 
2479     // Reset iterator.
2480     _update_refs_iterator.reset();
2481   }
2482 
2483   if (ShenandoahPacing) {
2484     pacer()->setup_for_updaterefs();
2485   }
2486 }
2487 
2488 void ShenandoahHeap::op_final_updaterefs() {
2489   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2490 
2491   finish_concurrent_unloading();
2492 
2493   // Check if there is left-over work, and finish it
2494   if (_update_refs_iterator.has_next()) {
2495     ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_finish_work);
2496 
2497     // Finish updating references where we left off.
2498     clear_cancelled_gc();
2499     update_heap_references(false);
2500   }
2501 
2502   // Clear cancelled GC, if set. On cancellation path, the block before would handle
2503   // everything. On degenerated paths, cancelled gc would not be set anyway.
2504   if (cancelled_gc()) {
2505     clear_cancelled_gc();
2506   }
2507   assert(!cancelled_gc(), "Should have been done right before");
2508 
2509   if (ShenandoahVerify && !is_degenerated_gc_in_progress()) {
2510     verifier()->verify_roots_in_to_space_except(ShenandoahRootVerifier::ThreadRoots);
2511   }
2512 
2513   if (is_degenerated_gc_in_progress()) {
2514     concurrent_mark()->update_roots(ShenandoahPhaseTimings::degen_gc_update_roots);
2515   } else {
2516     concurrent_mark()->update_thread_roots(ShenandoahPhaseTimings::final_update_refs_roots);
2517   }
2518 
2519   // Has to be done before cset is clear
2520   if (ShenandoahVerify) {
2521     verifier()->verify_roots_in_to_space();
2522   }
2523 
2524   // Drop unnecessary "pinned" state from regions that does not have CP marks
2525   // anymore, as this would allow trashing them below.
2526   {
2527     ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_sync_pinned);
2528     sync_pinned_region_status();
2529   }
2530 
2531   {
2532     ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_trash_cset);
2533     trash_cset_regions();
2534   }
2535 
2536   set_has_forwarded_objects(false);
2537   set_update_refs_in_progress(false);
2538 
2539   if (ShenandoahVerify) {
2540     verifier()->verify_after_updaterefs();
2541   }
2542 
2543   if (VerifyAfterGC) {
2544     Universe::verify();
2545   }
2546 
2547   {
2548     ShenandoahHeapLocker locker(lock());
2549     _free_set->rebuild();
2550   }
2551 }
2552 
2553 #ifdef ASSERT
2554 void ShenandoahHeap::assert_heaplock_owned_by_current_thread() {
2555   _lock.assert_owned_by_current_thread();
2556 }
2557 
2558 void ShenandoahHeap::assert_heaplock_not_owned_by_current_thread() {
2559   _lock.assert_not_owned_by_current_thread();
2560 }
2561 
2562 void ShenandoahHeap::assert_heaplock_or_safepoint() {
2563   _lock.assert_owned_by_current_thread_or_safepoint();
2564 }
2565 #endif
2566 
2567 void ShenandoahHeap::print_extended_on(outputStream *st) const {
2568   print_on(st);
2569   print_heap_regions_on(st);
2570 }
2571 
2572 bool ShenandoahHeap::is_bitmap_slice_committed(ShenandoahHeapRegion* r, bool skip_self) {
2573   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2574 
2575   size_t regions_from = _bitmap_regions_per_slice * slice;
2576   size_t regions_to   = MIN2(num_regions(), _bitmap_regions_per_slice * (slice + 1));
2577   for (size_t g = regions_from; g < regions_to; g++) {
2578     assert (g / _bitmap_regions_per_slice == slice, "same slice");
2579     if (skip_self && g == r->region_number()) continue;
2580     if (get_region(g)->is_committed()) {
2581       return true;
2582     }
2583   }
2584   return false;
2585 }
2586 
2587 bool ShenandoahHeap::commit_bitmap_slice(ShenandoahHeapRegion* r) {
2588   assert_heaplock_owned_by_current_thread();
2589 
2590   // Bitmaps in special regions do not need commits
2591   if (_bitmap_region_special) {
2592     return true;
2593   }
2594 
2595   if (is_bitmap_slice_committed(r, true)) {
2596     // Some other region from the group is already committed, meaning the bitmap
2597     // slice is already committed, we exit right away.
2598     return true;
2599   }
2600 
2601   // Commit the bitmap slice:
2602   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2603   size_t off = _bitmap_bytes_per_slice * slice;
2604   size_t len = _bitmap_bytes_per_slice;
2605   if (!os::commit_memory((char*)_bitmap_region.start() + off, len, false)) {
2606     return false;
2607   }
2608   return true;
2609 }
2610 
2611 bool ShenandoahHeap::uncommit_bitmap_slice(ShenandoahHeapRegion *r) {
2612   assert_heaplock_owned_by_current_thread();
2613 
2614   // Bitmaps in special regions do not need uncommits
2615   if (_bitmap_region_special) {
2616     return true;
2617   }
2618 
2619   if (is_bitmap_slice_committed(r, true)) {
2620     // Some other region from the group is still committed, meaning the bitmap
2621     // slice is should stay committed, exit right away.
2622     return true;
2623   }
2624 
2625   // Uncommit the bitmap slice:
2626   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2627   size_t off = _bitmap_bytes_per_slice * slice;
2628   size_t len = _bitmap_bytes_per_slice;
2629   if (!os::uncommit_memory((char*)_bitmap_region.start() + off, len)) {
2630     return false;
2631   }
2632   return true;
2633 }
2634 
2635 void ShenandoahHeap::safepoint_synchronize_begin() {
2636   if (ShenandoahSuspendibleWorkers || UseStringDeduplication) {
2637     SuspendibleThreadSet::synchronize();
2638   }
2639 }
2640 
2641 void ShenandoahHeap::safepoint_synchronize_end() {
2642   if (ShenandoahSuspendibleWorkers || UseStringDeduplication) {
2643     SuspendibleThreadSet::desynchronize();
2644   }
2645 }
2646 
2647 void ShenandoahHeap::vmop_entry_init_mark() {
2648   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2649   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2650   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_mark_gross);
2651 
2652   try_inject_alloc_failure();
2653   VM_ShenandoahInitMark op;
2654   VMThread::execute(&op); // jump to entry_init_mark() under safepoint
2655 }
2656 
2657 void ShenandoahHeap::vmop_entry_final_mark() {
2658   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2659   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2660   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_mark_gross);
2661 
2662   try_inject_alloc_failure();
2663   VM_ShenandoahFinalMarkStartEvac op;
2664   VMThread::execute(&op); // jump to entry_final_mark under safepoint
2665 }
2666 
2667 void ShenandoahHeap::vmop_entry_final_evac() {
2668   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2669   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2670   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac_gross);
2671 
2672   VM_ShenandoahFinalEvac op;
2673   VMThread::execute(&op); // jump to entry_final_evac under safepoint
2674 }
2675 
2676 void ShenandoahHeap::vmop_entry_init_updaterefs() {
2677   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2678   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2679   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs_gross);
2680 
2681   try_inject_alloc_failure();
2682   VM_ShenandoahInitUpdateRefs op;
2683   VMThread::execute(&op);
2684 }
2685 
2686 void ShenandoahHeap::vmop_entry_final_updaterefs() {
2687   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2688   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2689   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_gross);
2690 
2691   try_inject_alloc_failure();
2692   VM_ShenandoahFinalUpdateRefs op;
2693   VMThread::execute(&op);
2694 }
2695 
2696 void ShenandoahHeap::vmop_entry_init_traversal() {
2697   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2698   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2699   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_traversal_gc_gross);
2700 
2701   try_inject_alloc_failure();
2702   VM_ShenandoahInitTraversalGC op;
2703   VMThread::execute(&op);
2704 }
2705 
2706 void ShenandoahHeap::vmop_entry_final_traversal() {
2707   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2708   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2709   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_traversal_gc_gross);
2710 
2711   try_inject_alloc_failure();
2712   VM_ShenandoahFinalTraversalGC op;
2713   VMThread::execute(&op);
2714 }
2715 
2716 void ShenandoahHeap::vmop_entry_full(GCCause::Cause cause) {
2717   TraceCollectorStats tcs(monitoring_support()->full_stw_collection_counters());
2718   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2719   ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_gross);
2720 
2721   try_inject_alloc_failure();
2722   VM_ShenandoahFullGC op(cause);
2723   VMThread::execute(&op);
2724 }
2725 
2726 void ShenandoahHeap::vmop_degenerated(ShenandoahDegenPoint point) {
2727   TraceCollectorStats tcs(monitoring_support()->full_stw_collection_counters());
2728   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2729   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_gross);
2730 
2731   VM_ShenandoahDegeneratedGC degenerated_gc((int)point);
2732   VMThread::execute(&degenerated_gc);
2733 }
2734 
2735 void ShenandoahHeap::entry_init_mark() {
2736   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2737   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_mark);
2738   const char* msg = init_mark_event_message();
2739   GCTraceTime(Info, gc) time(msg, gc_timer());
2740   EventMark em("%s", msg);
2741 
2742   ShenandoahWorkerScope scope(workers(),
2743                               ShenandoahWorkerPolicy::calc_workers_for_init_marking(),
2744                               "init marking");
2745 
2746   op_init_mark();
2747 }
2748 
2749 void ShenandoahHeap::entry_final_mark() {
2750   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2751   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_mark);
2752   const char* msg = final_mark_event_message();
2753   GCTraceTime(Info, gc) time(msg, gc_timer());
2754   EventMark em("%s", msg);
2755 
2756   ShenandoahWorkerScope scope(workers(),
2757                               ShenandoahWorkerPolicy::calc_workers_for_final_marking(),
2758                               "final marking");
2759 
2760   op_final_mark();
2761 }
2762 
2763 void ShenandoahHeap::entry_final_evac() {
2764   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2765   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac);
2766   static const char* msg = "Pause Final Evac";
2767   GCTraceTime(Info, gc) time(msg, gc_timer());
2768   EventMark em("%s", msg);
2769 
2770   op_final_evac();
2771 }
2772 
2773 void ShenandoahHeap::entry_init_updaterefs() {
2774   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2775   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs);
2776 
2777   static const char* msg = "Pause Init Update Refs";
2778   GCTraceTime(Info, gc) time(msg, gc_timer());
2779   EventMark em("%s", msg);
2780 
2781   // No workers used in this phase, no setup required
2782 
2783   op_init_updaterefs();
2784 }
2785 
2786 void ShenandoahHeap::entry_final_updaterefs() {
2787   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2788   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs);
2789 
2790   static const char* msg = "Pause Final Update Refs";
2791   GCTraceTime(Info, gc) time(msg, gc_timer());
2792   EventMark em("%s", msg);
2793 
2794   ShenandoahWorkerScope scope(workers(),
2795                               ShenandoahWorkerPolicy::calc_workers_for_final_update_ref(),
2796                               "final reference update");
2797 
2798   op_final_updaterefs();
2799 }
2800 
2801 void ShenandoahHeap::entry_init_traversal() {
2802   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2803   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_traversal_gc);
2804 
2805   static const char* msg = init_traversal_event_message();
2806   GCTraceTime(Info, gc) time(msg, gc_timer());
2807   EventMark em("%s", msg);
2808 
2809   ShenandoahWorkerScope scope(workers(),
2810                               ShenandoahWorkerPolicy::calc_workers_for_stw_traversal(),
2811                               "init traversal");
2812 
2813   op_init_traversal();
2814 }
2815 
2816 void ShenandoahHeap::entry_final_traversal() {
2817   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2818   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_traversal_gc);
2819 
2820   static const char* msg = final_traversal_event_message();
2821   GCTraceTime(Info, gc) time(msg, gc_timer());
2822   EventMark em("%s", msg);
2823 
2824   ShenandoahWorkerScope scope(workers(),
2825                               ShenandoahWorkerPolicy::calc_workers_for_stw_traversal(),
2826                               "final traversal");
2827 
2828   op_final_traversal();
2829 }
2830 
2831 void ShenandoahHeap::entry_full(GCCause::Cause cause) {
2832   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2833   ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc);
2834 
2835   static const char* msg = "Pause Full";
2836   GCTraceTime(Info, gc) time(msg, gc_timer(), cause, true);
2837   EventMark em("%s", msg);
2838 
2839   ShenandoahWorkerScope scope(workers(),
2840                               ShenandoahWorkerPolicy::calc_workers_for_fullgc(),
2841                               "full gc");
2842 
2843   op_full(cause);
2844 }
2845 
2846 void ShenandoahHeap::entry_degenerated(int point) {
2847   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2848   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc);
2849 
2850   ShenandoahDegenPoint dpoint = (ShenandoahDegenPoint)point;
2851   const char* msg = degen_event_message(dpoint);
2852   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2853   EventMark em("%s", msg);
2854 
2855   ShenandoahWorkerScope scope(workers(),
2856                               ShenandoahWorkerPolicy::calc_workers_for_stw_degenerated(),
2857                               "stw degenerated gc");
2858 
2859   set_degenerated_gc_in_progress(true);
2860   op_degenerated(dpoint);
2861   set_degenerated_gc_in_progress(false);
2862 }
2863 
2864 void ShenandoahHeap::entry_mark() {
2865   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2866 
2867   const char* msg = conc_mark_event_message();
2868   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2869   EventMark em("%s", msg);
2870 
2871   ShenandoahWorkerScope scope(workers(),
2872                               ShenandoahWorkerPolicy::calc_workers_for_conc_marking(),
2873                               "concurrent marking");
2874 
2875   try_inject_alloc_failure();
2876   op_mark();
2877 }
2878 
2879 void ShenandoahHeap::entry_evac() {
2880   ShenandoahGCPhase conc_evac_phase(ShenandoahPhaseTimings::conc_evac);
2881   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2882 
2883   static const char* msg = "Concurrent evacuation";
2884   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2885   EventMark em("%s", msg);
2886 
2887   ShenandoahWorkerScope scope(workers(),
2888                               ShenandoahWorkerPolicy::calc_workers_for_conc_evac(),
2889                               "concurrent evacuation");
2890 
2891   try_inject_alloc_failure();
2892   op_conc_evac();
2893 }
2894 
2895 void ShenandoahHeap::entry_updaterefs() {
2896   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_update_refs);
2897 
2898   static const char* msg = "Concurrent update references";
2899   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2900   EventMark em("%s", msg);
2901 
2902   ShenandoahWorkerScope scope(workers(),
2903                               ShenandoahWorkerPolicy::calc_workers_for_conc_update_ref(),
2904                               "concurrent reference update");
2905 
2906   try_inject_alloc_failure();
2907   op_updaterefs();
2908 }
2909 
2910 void ShenandoahHeap::entry_roots() {
2911   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_roots);
2912 
2913   static const char* msg = "Concurrent roots processing";
2914   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2915   EventMark em("%s", msg);
2916 
2917   ShenandoahWorkerScope scope(workers(),
2918                               ShenandoahWorkerPolicy::calc_workers_for_conc_root_processing(),
2919                               "concurrent root processing");
2920 
2921   try_inject_alloc_failure();
2922   op_roots();
2923 }
2924 
2925 void ShenandoahHeap::entry_cleanup() {
2926   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_cleanup);
2927 
2928   static const char* msg = "Concurrent cleanup";
2929   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2930   EventMark em("%s", msg);
2931 
2932   // This phase does not use workers, no need for setup
2933 
2934   try_inject_alloc_failure();
2935   op_cleanup();
2936 }
2937 
2938 void ShenandoahHeap::entry_reset() {
2939   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_reset);
2940 
2941   static const char* msg = "Concurrent reset";
2942   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2943   EventMark em("%s", msg);
2944 
2945   ShenandoahWorkerScope scope(workers(),
2946                               ShenandoahWorkerPolicy::calc_workers_for_conc_reset(),
2947                               "concurrent reset");
2948 
2949   try_inject_alloc_failure();
2950   op_reset();
2951 }
2952 
2953 void ShenandoahHeap::entry_preclean() {
2954   if (ShenandoahPreclean && process_references()) {
2955     static const char* msg = "Concurrent precleaning";
2956     GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2957     EventMark em("%s", msg);
2958 
2959     ShenandoahGCPhase conc_preclean(ShenandoahPhaseTimings::conc_preclean);
2960 
2961     ShenandoahWorkerScope scope(workers(),
2962                                 ShenandoahWorkerPolicy::calc_workers_for_conc_preclean(),
2963                                 "concurrent preclean",
2964                                 /* check_workers = */ false);
2965 
2966     try_inject_alloc_failure();
2967     op_preclean();
2968   }
2969 }
2970 
2971 void ShenandoahHeap::entry_traversal() {
2972   static const char* msg = conc_traversal_event_message();
2973   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2974   EventMark em("%s", msg);
2975 
2976   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2977 
2978   ShenandoahWorkerScope scope(workers(),
2979                               ShenandoahWorkerPolicy::calc_workers_for_conc_traversal(),
2980                               "concurrent traversal");
2981 
2982   try_inject_alloc_failure();
2983   op_traversal();
2984 }
2985 
2986 void ShenandoahHeap::entry_uncommit(double shrink_before) {
2987   static const char *msg = "Concurrent uncommit";
2988   GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true);
2989   EventMark em("%s", msg);
2990 
2991   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_uncommit);
2992 
2993   op_uncommit(shrink_before);
2994 }
2995 
2996 void ShenandoahHeap::try_inject_alloc_failure() {
2997   if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) {
2998     _inject_alloc_failure.set();
2999     os::naked_short_sleep(1);
3000     if (cancelled_gc()) {
3001       log_info(gc)("Allocation failure was successfully injected");
3002     }
3003   }
3004 }
3005 
3006 bool ShenandoahHeap::should_inject_alloc_failure() {
3007   return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset();
3008 }
3009 
3010 void ShenandoahHeap::initialize_serviceability() {
3011   _memory_pool = new ShenandoahMemoryPool(this);
3012   _cycle_memory_manager.add_pool(_memory_pool);
3013   _stw_memory_manager.add_pool(_memory_pool);
3014 }
3015 
3016 GrowableArray<GCMemoryManager*> ShenandoahHeap::memory_managers() {
3017   GrowableArray<GCMemoryManager*> memory_managers(2);
3018   memory_managers.append(&_cycle_memory_manager);
3019   memory_managers.append(&_stw_memory_manager);
3020   return memory_managers;
3021 }
3022 
3023 GrowableArray<MemoryPool*> ShenandoahHeap::memory_pools() {
3024   GrowableArray<MemoryPool*> memory_pools(1);
3025   memory_pools.append(_memory_pool);
3026   return memory_pools;
3027 }
3028 
3029 MemoryUsage ShenandoahHeap::memory_usage() {
3030   return _memory_pool->get_memory_usage();
3031 }
3032 
3033 void ShenandoahHeap::enter_evacuation() {
3034   _oom_evac_handler.enter_evacuation();
3035 }
3036 
3037 void ShenandoahHeap::leave_evacuation() {
3038   _oom_evac_handler.leave_evacuation();
3039 }
3040 
3041 ShenandoahRegionIterator::ShenandoahRegionIterator() :
3042   _heap(ShenandoahHeap::heap()),
3043   _index(0) {}
3044 
3045 ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) :
3046   _heap(heap),
3047   _index(0) {}
3048 
3049 void ShenandoahRegionIterator::reset() {
3050   _index = 0;
3051 }
3052 
3053 bool ShenandoahRegionIterator::has_next() const {
3054   return _index < _heap->num_regions();
3055 }
3056 
3057 char ShenandoahHeap::gc_state() const {
3058   return _gc_state.raw_value();
3059 }
3060 
3061 void ShenandoahHeap::deduplicate_string(oop str) {
3062   assert(java_lang_String::is_instance(str), "invariant");
3063 
3064   if (ShenandoahStringDedup::is_enabled()) {
3065     ShenandoahStringDedup::deduplicate(str);
3066   }
3067 }
3068 
3069 const char* ShenandoahHeap::init_mark_event_message() const {
3070   bool update_refs = has_forwarded_objects();
3071   bool proc_refs = process_references();
3072   bool unload_cls = unload_classes();
3073 
3074   if (update_refs && proc_refs && unload_cls) {
3075     return "Pause Init Mark (update refs) (process weakrefs) (unload classes)";
3076   } else if (update_refs && proc_refs) {
3077     return "Pause Init Mark (update refs) (process weakrefs)";
3078   } else if (update_refs && unload_cls) {
3079     return "Pause Init Mark (update refs) (unload classes)";
3080   } else if (proc_refs && unload_cls) {
3081     return "Pause Init Mark (process weakrefs) (unload classes)";
3082   } else if (update_refs) {
3083     return "Pause Init Mark (update refs)";
3084   } else if (proc_refs) {
3085     return "Pause Init Mark (process weakrefs)";
3086   } else if (unload_cls) {
3087     return "Pause Init Mark (unload classes)";
3088   } else {
3089     return "Pause Init Mark";
3090   }
3091 }
3092 
3093 const char* ShenandoahHeap::final_mark_event_message() const {
3094   bool update_refs = has_forwarded_objects();
3095   bool proc_refs = process_references();
3096   bool unload_cls = unload_classes();
3097 
3098   if (update_refs && proc_refs && unload_cls) {
3099     return "Pause Final Mark (update refs) (process weakrefs) (unload classes)";
3100   } else if (update_refs && proc_refs) {
3101     return "Pause Final Mark (update refs) (process weakrefs)";
3102   } else if (update_refs && unload_cls) {
3103     return "Pause Final Mark (update refs) (unload classes)";
3104   } else if (proc_refs && unload_cls) {
3105     return "Pause Final Mark (process weakrefs) (unload classes)";
3106   } else if (update_refs) {
3107     return "Pause Final Mark (update refs)";
3108   } else if (proc_refs) {
3109     return "Pause Final Mark (process weakrefs)";
3110   } else if (unload_cls) {
3111     return "Pause Final Mark (unload classes)";
3112   } else {
3113     return "Pause Final Mark";
3114   }
3115 }
3116 
3117 const char* ShenandoahHeap::conc_mark_event_message() const {
3118   bool update_refs = has_forwarded_objects();
3119   bool proc_refs = process_references();
3120   bool unload_cls = unload_classes();
3121 
3122   if (update_refs && proc_refs && unload_cls) {
3123     return "Concurrent marking (update refs) (process weakrefs) (unload classes)";
3124   } else if (update_refs && proc_refs) {
3125     return "Concurrent marking (update refs) (process weakrefs)";
3126   } else if (update_refs && unload_cls) {
3127     return "Concurrent marking (update refs) (unload classes)";
3128   } else if (proc_refs && unload_cls) {
3129     return "Concurrent marking (process weakrefs) (unload classes)";
3130   } else if (update_refs) {
3131     return "Concurrent marking (update refs)";
3132   } else if (proc_refs) {
3133     return "Concurrent marking (process weakrefs)";
3134   } else if (unload_cls) {
3135     return "Concurrent marking (unload classes)";
3136   } else {
3137     return "Concurrent marking";
3138   }
3139 }
3140 
3141 const char* ShenandoahHeap::init_traversal_event_message() const {
3142   bool proc_refs = process_references();
3143   bool unload_cls = unload_classes();
3144 
3145   if (proc_refs && unload_cls) {
3146     return "Pause Init Traversal (process weakrefs) (unload classes)";
3147   } else if (proc_refs) {
3148     return "Pause Init Traversal (process weakrefs)";
3149   } else if (unload_cls) {
3150     return "Pause Init Traversal (unload classes)";
3151   } else {
3152     return "Pause Init Traversal";
3153   }
3154 }
3155 
3156 const char* ShenandoahHeap::final_traversal_event_message() const {
3157   bool proc_refs = process_references();
3158   bool unload_cls = unload_classes();
3159 
3160   if (proc_refs && unload_cls) {
3161     return "Pause Final Traversal (process weakrefs) (unload classes)";
3162   } else if (proc_refs) {
3163     return "Pause Final Traversal (process weakrefs)";
3164   } else if (unload_cls) {
3165     return "Pause Final Traversal (unload classes)";
3166   } else {
3167     return "Pause Final Traversal";
3168   }
3169 }
3170 
3171 const char* ShenandoahHeap::conc_traversal_event_message() const {
3172   bool proc_refs = process_references();
3173   bool unload_cls = unload_classes();
3174 
3175   if (proc_refs && unload_cls) {
3176     return "Concurrent Traversal (process weakrefs) (unload classes)";
3177   } else if (proc_refs) {
3178     return "Concurrent Traversal (process weakrefs)";
3179   } else if (unload_cls) {
3180     return "Concurrent Traversal (unload classes)";
3181   } else {
3182     return "Concurrent Traversal";
3183   }
3184 }
3185 
3186 const char* ShenandoahHeap::degen_event_message(ShenandoahDegenPoint point) const {
3187   switch (point) {
3188     case _degenerated_unset:
3189       return "Pause Degenerated GC (<UNSET>)";
3190     case _degenerated_traversal:
3191       return "Pause Degenerated GC (Traversal)";
3192     case _degenerated_outside_cycle:
3193       return "Pause Degenerated GC (Outside of Cycle)";
3194     case _degenerated_mark:
3195       return "Pause Degenerated GC (Mark)";
3196     case _degenerated_evac:
3197       return "Pause Degenerated GC (Evacuation)";
3198     case _degenerated_updaterefs:
3199       return "Pause Degenerated GC (Update Refs)";
3200     default:
3201       ShouldNotReachHere();
3202       return "ERROR";
3203   }
3204 }
3205 
3206 jushort* ShenandoahHeap::get_liveness_cache(uint worker_id) {
3207 #ifdef ASSERT
3208   assert(_liveness_cache != NULL, "sanity");
3209   assert(worker_id < _max_workers, "sanity");
3210   for (uint i = 0; i < num_regions(); i++) {
3211     assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty");
3212   }
3213 #endif
3214   return _liveness_cache[worker_id];
3215 }
3216 
3217 void ShenandoahHeap::flush_liveness_cache(uint worker_id) {
3218   assert(worker_id < _max_workers, "sanity");
3219   assert(_liveness_cache != NULL, "sanity");
3220   jushort* ld = _liveness_cache[worker_id];
3221   for (uint i = 0; i < num_regions(); i++) {
3222     ShenandoahHeapRegion* r = get_region(i);
3223     jushort live = ld[i];
3224     if (live > 0) {
3225       r->increase_live_data_gc_words(live);
3226       ld[i] = 0;
3227     }
3228   }
3229 }