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