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