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