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