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