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