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