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