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