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       obj = ShenandoahBarrierSet::resolve_forwarded_not_null(obj);
1170       assert(obj->is_oop(), "must be a valid oop");
1171       if (!_bitmap->isMarked((HeapWord*) obj)) {
1172         _bitmap->mark((HeapWord*) obj);
1173         _oop_stack->push(obj);
1174       }
1175     }
1176   }
1177 public:
1178   ObjectIterateScanRootClosure(MarkBitMap* bitmap, Stack<oop,mtGC>* oop_stack) :
1179     _bitmap(bitmap), _oop_stack(oop_stack) {}
1180   void do_oop(oop* p)       { do_oop_work(p); }
1181   void do_oop(narrowOop* p) { do_oop_work(p); }
1182 };
1183 
1184 /*
1185  * This is public API, used in preparation of object_iterate().
1186  * Since we don't do linear scan of heap in object_iterate() (see comment below), we don't
1187  * need to make the heap parsable. For Shenandoah-internal linear heap scans that we can
1188  * control, we call SH::make_parsable().
1189  */
1190 void ShenandoahHeap::ensure_parsability(bool retire_tlabs) {
1191   // No-op.
1192 }
1193 
1194 /*
1195  * Iterates objects in the heap. This is public API, used for, e.g., heap dumping.
1196  *
1197  * We cannot safely iterate objects by doing a linear scan at random points in time. Linear
1198  * scanning needs to deal with dead objects, which may have dead Klass* pointers (e.g.
1199  * calling oopDesc::size() would crash) or dangling reference fields (crashes) etc. Linear
1200  * scanning therefore depends on having a valid marking bitmap to support it. However, we only
1201  * have a valid marking bitmap after successful marking. In particular, we *don't* have a valid
1202  * marking bitmap during marking, after aborted marking or during/after cleanup (when we just
1203  * wiped the bitmap in preparation for next marking).
1204  *
1205  * For all those reasons, we implement object iteration as a single marking traversal, reporting
1206  * objects as we mark+traverse through the heap, starting from GC roots. JVMTI IterateThroughHeap
1207  * is allowed to report dead objects, but is not required to do so.
1208  */
1209 void ShenandoahHeap::object_iterate(ObjectClosure* cl) {
1210   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1211   if (!_aux_bitmap_region_special && !os::commit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size(), false)) {
1212     log_warning(gc)("Could not commit native memory for auxiliary marking bitmap for heap iteration");
1213     return;
1214   }
1215 
1216   // Reset bitmap
1217   _aux_bit_map.clear();
1218 
1219   Stack<oop,mtGC> oop_stack;
1220 
1221   // First, we process all GC roots. This populates the work stack with initial objects.
1222   ShenandoahRootProcessor rp(this, 1, ShenandoahPhaseTimings::_num_phases);
1223   ObjectIterateScanRootClosure oops(&_aux_bit_map, &oop_stack);
1224   CLDToOopClosure clds(&oops, false);
1225   CodeBlobToOopClosure blobs(&oops, false);
1226   rp.process_all_roots(&oops, &oops, &clds, &blobs, NULL, 0);
1227 
1228   // Work through the oop stack to traverse heap.
1229   while (! oop_stack.is_empty()) {
1230     oop obj = oop_stack.pop();
1231     assert(obj->is_oop(), "must be a valid oop");
1232     cl->do_object(obj);
1233     obj->oop_iterate(&oops);
1234   }
1235 
1236   assert(oop_stack.is_empty(), "should be empty");
1237 
1238   if (!_aux_bitmap_region_special && !os::uncommit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size())) {
1239     log_warning(gc)("Could not uncommit native memory for auxiliary marking bitmap for heap iteration");
1240   }
1241 }
1242 
1243 void ShenandoahHeap::safe_object_iterate(ObjectClosure* cl) {
1244   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1245   object_iterate(cl);
1246 }
1247 
1248 void ShenandoahHeap::oop_iterate(ExtendedOopClosure* cl) {
1249   ObjectToOopClosure cl2(cl);
1250   object_iterate(&cl2);
1251 }
1252 
1253 class ShenandoahSpaceClosureRegionClosure: public ShenandoahHeapRegionClosure {
1254   SpaceClosure* _cl;
1255 public:
1256   ShenandoahSpaceClosureRegionClosure(SpaceClosure* cl) : _cl(cl) {}
1257   void heap_region_do(ShenandoahHeapRegion* r) {
1258     _cl->do_space(r);
1259   }
1260 };
1261 
1262 void  ShenandoahHeap::space_iterate(SpaceClosure* cl) {
1263   ShenandoahSpaceClosureRegionClosure blk(cl);
1264   heap_region_iterate(&blk);
1265 }
1266 
1267 Space*  ShenandoahHeap::space_containing(const void* oop) const {
1268   Space* res = heap_region_containing(oop);
1269   return res;
1270 }
1271 
1272 void  ShenandoahHeap::gc_prologue(bool b) {
1273   Unimplemented();
1274 }
1275 
1276 void  ShenandoahHeap::gc_epilogue(bool b) {
1277   Unimplemented();
1278 }
1279 
1280 void ShenandoahHeap::heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1281   for (size_t i = 0; i < num_regions(); i++) {
1282     ShenandoahHeapRegion* current = get_region(i);
1283     blk->heap_region_do(current);
1284   }
1285 }
1286 
1287 class ShenandoahParallelHeapRegionTask : public AbstractGangTask {
1288 private:
1289   ShenandoahHeap* const _heap;
1290   ShenandoahHeapRegionClosure* const _blk;
1291 
1292   char _pad0[DEFAULT_CACHE_LINE_SIZE];
1293   volatile jint _index;
1294   char _pad1[DEFAULT_CACHE_LINE_SIZE];
1295 
1296 public:
1297   ShenandoahParallelHeapRegionTask(ShenandoahHeapRegionClosure* blk) :
1298           AbstractGangTask("Parallel Region Task"),
1299           _heap(ShenandoahHeap::heap()), _blk(blk), _index(0) {}
1300 
1301   void work(uint worker_id) {
1302     jint stride = (jint)ShenandoahParallelRegionStride;
1303 
1304     jint max = (jint)_heap->num_regions();
1305     while (_index < max) {
1306       jint cur = Atomic::add(stride, &_index) - stride;
1307       jint start = cur;
1308       jint end = MIN2(cur + stride, max);
1309       if (start >= max) break;
1310 
1311       for (jint i = cur; i < end; i++) {
1312         ShenandoahHeapRegion* current = _heap->get_region((size_t)i);
1313         _blk->heap_region_do(current);
1314       }
1315     }
1316   }
1317 };
1318 
1319 void ShenandoahHeap::parallel_heap_region_iterate(ShenandoahHeapRegionClosure* blk) const {
1320   assert(blk->is_thread_safe(), "Only thread-safe closures here");
1321   if (num_regions() > ShenandoahParallelRegionStride) {
1322     ShenandoahParallelHeapRegionTask task(blk);
1323     workers()->run_task(&task);
1324   } else {
1325     heap_region_iterate(blk);
1326   }
1327 }
1328 
1329 class ShenandoahClearLivenessClosure : public ShenandoahHeapRegionClosure {
1330 private:
1331   ShenandoahMarkingContext* const _ctx;
1332 public:
1333   ShenandoahClearLivenessClosure() : _ctx(ShenandoahHeap::heap()->marking_context()) {}
1334 
1335   void heap_region_do(ShenandoahHeapRegion* r) {
1336     if (r->is_active()) {
1337       r->clear_live_data();
1338       _ctx->capture_top_at_mark_start(r);
1339     } else {
1340       assert(!r->has_live(),
1341              err_msg("Region " SIZE_FORMAT " should have no live data", r->region_number()));
1342       assert(_ctx->top_at_mark_start(r) == r->top(),
1343              err_msg("Region " SIZE_FORMAT " should already have correct TAMS", r->region_number()));
1344     }
1345   }
1346 
1347   bool is_thread_safe() { return true; }
1348 };
1349 
1350 void ShenandoahHeap::op_init_mark() {
1351   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1352   assert(Thread::current()->is_VM_thread(), "can only do this in VMThread");
1353 
1354   assert(marking_context()->is_bitmap_clear(), "need clear marking bitmap");
1355   assert(!marking_context()->is_complete(), "should not be complete");
1356 
1357   if (ShenandoahVerify) {
1358     verifier()->verify_before_concmark();
1359   }
1360 
1361   {
1362     ShenandoahGCPhase phase(ShenandoahPhaseTimings::accumulate_stats);
1363     accumulate_statistics_tlabs();
1364   }
1365 
1366   if (VerifyBeforeGC) {
1367     Universe::verify();
1368   }
1369 
1370   set_concurrent_mark_in_progress(true);
1371   // We need to reset all TLABs because we'd lose marks on all objects allocated in them.
1372   if (UseTLAB) {
1373     ShenandoahGCPhase phase(ShenandoahPhaseTimings::make_parsable);
1374     make_parsable(true);
1375   }
1376 
1377   {
1378     ShenandoahGCPhase phase(ShenandoahPhaseTimings::clear_liveness);
1379     ShenandoahClearLivenessClosure clc;
1380     parallel_heap_region_iterate(&clc);
1381   }
1382 
1383   // Make above changes visible to worker threads
1384   OrderAccess::fence();
1385 
1386   concurrent_mark()->mark_roots(ShenandoahPhaseTimings::scan_roots);
1387 
1388   if (UseTLAB) {
1389     ShenandoahGCPhase phase(ShenandoahPhaseTimings::resize_tlabs);
1390     resize_tlabs();
1391   }
1392 
1393   if (ShenandoahPacing) {
1394     pacer()->setup_for_mark();
1395   }
1396 }
1397 
1398 void ShenandoahHeap::op_mark() {
1399   concurrent_mark()->mark_from_roots();
1400 }
1401 
1402 class ShenandoahCompleteLivenessClosure : public ShenandoahHeapRegionClosure {
1403 private:
1404   ShenandoahMarkingContext* const _ctx;
1405 public:
1406   ShenandoahCompleteLivenessClosure() : _ctx(ShenandoahHeap::heap()->complete_marking_context()) {}
1407 
1408   void heap_region_do(ShenandoahHeapRegion* r) {
1409     if (r->is_active()) {
1410       HeapWord *tams = _ctx->top_at_mark_start(r);
1411       HeapWord *top = r->top();
1412       if (top > tams) {
1413         r->increase_live_data_alloc_words(pointer_delta(top, tams));
1414       }
1415     } else {
1416       assert(!r->has_live(),
1417              err_msg("Region " SIZE_FORMAT " should have no live data", r->region_number()));
1418       assert(_ctx->top_at_mark_start(r) == r->top(),
1419              err_msg("Region " SIZE_FORMAT " should have correct TAMS", r->region_number()));
1420     }
1421   }
1422 
1423   bool is_thread_safe() { return true; }
1424 };
1425 
1426 void ShenandoahHeap::op_final_mark() {
1427   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1428 
1429   // It is critical that we
1430   // evacuate roots right after finishing marking, so that we don't
1431   // get unmarked objects in the roots.
1432 
1433   if (!cancelled_gc()) {
1434     concurrent_mark()->finish_mark_from_roots(/* full_gc = */ false);
1435 
1436     TASKQUEUE_STATS_ONLY(concurrent_mark()->task_queues()->reset_taskqueue_stats());
1437 
1438     if (has_forwarded_objects()) {
1439       concurrent_mark()->update_roots(ShenandoahPhaseTimings::update_roots);
1440     }
1441 
1442     TASKQUEUE_STATS_ONLY(concurrent_mark()->task_queues()->print_taskqueue_stats());
1443 
1444     stop_concurrent_marking();
1445 
1446     {
1447       ShenandoahGCPhase phase(ShenandoahPhaseTimings::complete_liveness);
1448 
1449       // All allocations past TAMS are implicitly live, adjust the region data.
1450       // Bitmaps/TAMS are swapped at this point, so we need to poll complete bitmap.
1451       ShenandoahCompleteLivenessClosure cl;
1452       parallel_heap_region_iterate(&cl);
1453     }
1454 
1455     {
1456       ShenandoahGCPhase prepare_evac(ShenandoahPhaseTimings::prepare_evac);
1457 
1458       make_parsable(true);
1459 
1460       trash_cset_regions();
1461 
1462       {
1463         ShenandoahHeapLocker locker(lock());
1464         _collection_set->clear();
1465         _free_set->clear();
1466 
1467         heuristics()->choose_collection_set(_collection_set);
1468         _free_set->rebuild();
1469       }
1470     }
1471 
1472     // If collection set has candidates, start evacuation.
1473     // Otherwise, bypass the rest of the cycle.
1474     if (!collection_set()->is_empty()) {
1475       ShenandoahGCPhase init_evac(ShenandoahPhaseTimings::init_evac);
1476 
1477       if (ShenandoahVerify) {
1478         verifier()->verify_before_evacuation();
1479       }
1480 
1481       set_evacuation_in_progress(true);
1482       // From here on, we need to update references.
1483       set_has_forwarded_objects(true);
1484 
1485       evacuate_and_update_roots();
1486 
1487       if (ShenandoahPacing) {
1488         pacer()->setup_for_evac();
1489       }
1490 
1491       if (ShenandoahVerify) {
1492         verifier()->verify_during_evacuation();
1493       }
1494     } else {
1495       if (ShenandoahVerify) {
1496         verifier()->verify_after_concmark();
1497       }
1498 
1499       if (VerifyAfterGC) {
1500         Universe::verify();
1501       }
1502     }
1503 
1504   } else {
1505     concurrent_mark()->cancel();
1506     stop_concurrent_marking();
1507 
1508     if (process_references()) {
1509       // Abandon reference processing right away: pre-cleaning must have failed.
1510       ReferenceProcessor *rp = ref_processor();
1511       rp->disable_discovery();
1512       rp->abandon_partial_discovery();
1513       rp->verify_no_references_recorded();
1514     }
1515   }
1516 }
1517 
1518 void ShenandoahHeap::op_final_evac() {
1519   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint");
1520 
1521   set_evacuation_in_progress(false);
1522   if (ShenandoahVerify) {
1523     verifier()->verify_after_evacuation();
1524   }
1525 
1526   if (VerifyAfterGC) {
1527     Universe::verify();
1528   }
1529 }
1530 
1531 void ShenandoahHeap::op_conc_evac() {
1532   ShenandoahEvacuationTask task(this, _collection_set, true);
1533   workers()->run_task(&task);
1534 }
1535 
1536 void ShenandoahHeap::op_stw_evac() {
1537   ShenandoahEvacuationTask task(this, _collection_set, false);
1538   workers()->run_task(&task);
1539 }
1540 
1541 void ShenandoahHeap::op_updaterefs() {
1542   update_heap_references(true);
1543 }
1544 
1545 void ShenandoahHeap::op_cleanup() {
1546   free_set()->recycle_trash();
1547 }
1548 
1549 void ShenandoahHeap::op_reset() {
1550   reset_mark_bitmap();
1551 }
1552 
1553 void ShenandoahHeap::op_preclean() {
1554   concurrent_mark()->preclean_weak_refs();
1555 }
1556 
1557 void ShenandoahHeap::op_full(GCCause::Cause cause) {
1558   ShenandoahMetricsSnapshot metrics;
1559   metrics.snap_before();
1560 
1561   full_gc()->do_it(cause);
1562 
1563   metrics.snap_after();
1564   metrics.print();
1565 
1566   if (metrics.is_good_progress("Full GC")) {
1567     _progress_last_gc.set();
1568   } else {
1569     // Nothing to do. Tell the allocation path that we have failed to make
1570     // progress, and it can finally fail.
1571     _progress_last_gc.unset();
1572   }
1573 }
1574 
1575 void ShenandoahHeap::op_degenerated(ShenandoahDegenPoint point) {
1576   // Degenerated GC is STW, but it can also fail. Current mechanics communicates
1577   // GC failure via cancelled_concgc() flag. So, if we detect the failure after
1578   // some phase, we have to upgrade the Degenerate GC to Full GC.
1579 
1580   clear_cancelled_gc();
1581 
1582   ShenandoahMetricsSnapshot metrics;
1583   metrics.snap_before();
1584 
1585   switch (point) {
1586     // The cases below form the Duff's-like device: it describes the actual GC cycle,
1587     // but enters it at different points, depending on which concurrent phase had
1588     // degenerated.
1589 
1590     case _degenerated_outside_cycle:
1591       // We have degenerated from outside the cycle, which means something is bad with
1592       // the heap, most probably heavy humongous fragmentation, or we are very low on free
1593       // space. It makes little sense to wait for Full GC to reclaim as much as it can, when
1594       // we can do the most aggressive degen cycle, which includes processing references and
1595       // class unloading, unless those features are explicitly disabled.
1596       //
1597       // Note that we can only do this for "outside-cycle" degens, otherwise we would risk
1598       // changing the cycle parameters mid-cycle during concurrent -> degenerated handover.
1599       set_process_references(heuristics()->can_process_references());
1600       set_unload_classes(heuristics()->can_unload_classes());
1601 
1602       op_reset();
1603 
1604       op_init_mark();
1605       if (cancelled_gc()) {
1606         op_degenerated_fail();
1607         return;
1608       }
1609 
1610     case _degenerated_mark:
1611       op_final_mark();
1612       if (cancelled_gc()) {
1613         op_degenerated_fail();
1614         return;
1615       }
1616 
1617       op_cleanup();
1618 
1619     case _degenerated_evac:
1620       // If heuristics thinks we should do the cycle, this flag would be set,
1621       // and we can do evacuation. Otherwise, it would be the shortcut cycle.
1622       if (is_evacuation_in_progress()) {
1623 
1624         // Degeneration under oom-evac protocol might have left some objects in
1625         // collection set un-evacuated. Restart evacuation from the beginning to
1626         // capture all objects. For all the objects that are already evacuated,
1627         // it would be a simple check, which is supposed to be fast. This is also
1628         // safe to do even without degeneration, as CSet iterator is at beginning
1629         // in preparation for evacuation anyway.
1630         collection_set()->clear_current_index();
1631 
1632         op_stw_evac();
1633         if (cancelled_gc()) {
1634           op_degenerated_fail();
1635           return;
1636         }
1637       }
1638 
1639       // If heuristics thinks we should do the cycle, this flag would be set,
1640       // and we need to do update-refs. Otherwise, it would be the shortcut cycle.
1641       if (has_forwarded_objects()) {
1642         op_init_updaterefs();
1643         if (cancelled_gc()) {
1644           op_degenerated_fail();
1645           return;
1646         }
1647       }
1648 
1649     case _degenerated_updaterefs:
1650       if (has_forwarded_objects()) {
1651         op_final_updaterefs();
1652         if (cancelled_gc()) {
1653           op_degenerated_fail();
1654           return;
1655         }
1656       }
1657 
1658       op_cleanup();
1659       break;
1660 
1661     default:
1662       ShouldNotReachHere();
1663   }
1664 
1665   if (ShenandoahVerify) {
1666     verifier()->verify_after_degenerated();
1667   }
1668 
1669   if (VerifyAfterGC) {
1670     Universe::verify();
1671   }
1672 
1673   metrics.snap_after();
1674   metrics.print();
1675 
1676   // Check for futility and fail. There is no reason to do several back-to-back Degenerated cycles,
1677   // because that probably means the heap is overloaded and/or fragmented.
1678   if (!metrics.is_good_progress("Degenerated GC")) {
1679     _progress_last_gc.unset();
1680     cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc);
1681     op_degenerated_futile();
1682   } else {
1683     _progress_last_gc.set();
1684   }
1685 }
1686 
1687 void ShenandoahHeap::op_degenerated_fail() {
1688   log_info(gc)("Cannot finish degeneration, upgrading to Full GC");
1689   shenandoah_policy()->record_degenerated_upgrade_to_full();
1690   op_full(GCCause::_shenandoah_upgrade_to_full_gc);
1691 }
1692 
1693 void ShenandoahHeap::op_degenerated_futile() {
1694   shenandoah_policy()->record_degenerated_upgrade_to_full();
1695   op_full(GCCause::_shenandoah_upgrade_to_full_gc);
1696 }
1697 
1698 void ShenandoahHeap::stop_concurrent_marking() {
1699   assert(is_concurrent_mark_in_progress(), "How else could we get here?");
1700   if (!cancelled_gc()) {
1701     // If we needed to update refs, and concurrent marking has been cancelled,
1702     // we need to finish updating references.
1703     set_has_forwarded_objects(false);
1704     mark_complete_marking_context();
1705   }
1706   set_concurrent_mark_in_progress(false);
1707 }
1708 
1709 void ShenandoahHeap::force_satb_flush_all_threads() {
1710   if (!is_concurrent_mark_in_progress()) {
1711     // No need to flush SATBs
1712     return;
1713   }
1714 
1715   // Do not block if Threads lock is busy. This avoids the potential deadlock
1716   // when this code is called from the periodic task, and something else is
1717   // expecting the periodic task to complete without blocking. On the off-chance
1718   // Threads lock is busy momentarily, try to acquire several times.
1719   for (int t = 0; t < 10; t++) {
1720     if (Threads_lock->try_lock()) {
1721       JavaThread::set_force_satb_flush_all_threads(true);
1722       Threads_lock->unlock();
1723 
1724       // The threads are not "acquiring" their thread-local data, but it does not
1725       // hurt to "release" the updates here anyway.
1726       OrderAccess::fence();
1727       break;
1728     }
1729     os::naked_short_sleep(1);
1730   }
1731 }
1732 
1733 void ShenandoahHeap::set_gc_state_mask(uint mask, bool value) {
1734   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should really be Shenandoah safepoint");
1735   _gc_state.set_cond(mask, value);
1736   JavaThread::set_gc_state_all_threads(_gc_state.raw_value());
1737 }
1738 
1739 void ShenandoahHeap::set_concurrent_mark_in_progress(bool in_progress) {
1740   set_gc_state_mask(MARKING, in_progress);
1741   JavaThread::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
1742 }
1743 
1744 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {
1745   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint");
1746   set_gc_state_mask(EVACUATION, in_progress);
1747 }
1748 
1749 void ShenandoahHeap::ref_processing_init() {
1750   MemRegion mr = reserved_region();
1751 
1752   assert(_max_workers > 0, "Sanity");
1753 
1754   _ref_processor =
1755     new ReferenceProcessor(mr,    // span
1756                            ParallelRefProcEnabled,  // MT processing
1757                            _max_workers,            // Degree of MT processing
1758                            true,                    // MT discovery
1759                            _max_workers,            // Degree of MT discovery
1760                            false,                   // Reference discovery is not atomic
1761                            NULL);                   // No closure, should be installed before use
1762 
1763   shenandoah_assert_rp_isalive_not_installed();
1764 }
1765 
1766 void ShenandoahHeap::acquire_pending_refs_lock() {
1767   _control_thread->slt()->manipulatePLL(SurrogateLockerThread::acquirePLL);
1768 }
1769 
1770 void ShenandoahHeap::release_pending_refs_lock() {
1771   _control_thread->slt()->manipulatePLL(SurrogateLockerThread::releaseAndNotifyPLL);
1772 }
1773 
1774 GCTracer* ShenandoahHeap::tracer() {
1775   return shenandoah_policy()->tracer();
1776 }
1777 
1778 size_t ShenandoahHeap::tlab_used(Thread* thread) const {
1779   return _free_set->used();
1780 }
1781 
1782 void ShenandoahHeap::cancel_gc(GCCause::Cause cause) {
1783   if (try_cancel_gc()) {
1784     FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause));
1785     log_info(gc)("%s", msg.buffer());
1786     Events::log(Thread::current(), "%s", msg.buffer());
1787   }
1788 }
1789 
1790 uint ShenandoahHeap::max_workers() {
1791   return _max_workers;
1792 }
1793 
1794 void ShenandoahHeap::stop() {
1795   // The shutdown sequence should be able to terminate when GC is running.
1796 
1797   // Step 0. Notify policy to disable event recording.
1798   _shenandoah_policy->record_shutdown();
1799 
1800   // Step 1. Notify control thread that we are in shutdown.
1801   // Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown.
1802   // Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below.
1803   _control_thread->prepare_for_graceful_shutdown();
1804 
1805   // Step 2. Notify GC workers that we are cancelling GC.
1806   cancel_gc(GCCause::_shenandoah_stop_vm);
1807 
1808   // Step 3. Wait until GC worker exits normally.
1809   _control_thread->stop();
1810 
1811   // Step 4. Stop String Dedup thread if it is active
1812   if (ShenandoahStringDedup::is_enabled()) {
1813     ShenandoahStringDedup::stop();
1814   }
1815 }
1816 
1817 void ShenandoahHeap::unload_classes_and_cleanup_tables(bool full_gc) {
1818   assert(heuristics()->can_unload_classes(), "Class unloading should be enabled");
1819 
1820   ShenandoahGCPhase root_phase(full_gc ?
1821                                ShenandoahPhaseTimings::full_gc_purge :
1822                                ShenandoahPhaseTimings::purge);
1823 
1824   ShenandoahIsAliveSelector alive;
1825   BoolObjectClosure* is_alive = alive.is_alive_closure();
1826 
1827   bool purged_class;
1828 
1829   // Unload classes and purge SystemDictionary.
1830   {
1831     ShenandoahGCPhase phase(full_gc ?
1832                             ShenandoahPhaseTimings::full_gc_purge_class_unload :
1833                             ShenandoahPhaseTimings::purge_class_unload);
1834     purged_class = SystemDictionary::do_unloading(is_alive,
1835                                                   full_gc /* do_cleaning*/ );
1836   }
1837 
1838   {
1839     ShenandoahGCPhase phase(full_gc ?
1840                             ShenandoahPhaseTimings::full_gc_purge_par :
1841                             ShenandoahPhaseTimings::purge_par);
1842     uint active = _workers->active_workers();
1843     ParallelCleaningTask unlink_task(is_alive, true, true, active, purged_class);
1844     _workers->run_task(&unlink_task);
1845   }
1846 
1847   if (ShenandoahStringDedup::is_enabled()) {
1848     ShenandoahGCPhase phase(full_gc ?
1849                             ShenandoahPhaseTimings::full_gc_purge_string_dedup :
1850                             ShenandoahPhaseTimings::purge_string_dedup);
1851     ShenandoahStringDedup::parallel_cleanup();
1852   }
1853 
1854   {
1855     ShenandoahGCPhase phase(full_gc ?
1856                             ShenandoahPhaseTimings::full_gc_purge_cldg :
1857                             ShenandoahPhaseTimings::purge_cldg);
1858     ClassLoaderDataGraph::purge();
1859   }
1860 }
1861 
1862 void ShenandoahHeap::set_has_forwarded_objects(bool cond) {
1863   set_gc_state_mask(HAS_FORWARDED, cond);
1864 }
1865 
1866 void ShenandoahHeap::set_process_references(bool pr) {
1867   _process_references.set_cond(pr);
1868 }
1869 
1870 void ShenandoahHeap::set_unload_classes(bool uc) {
1871   _unload_classes.set_cond(uc);
1872 }
1873 
1874 bool ShenandoahHeap::process_references() const {
1875   return _process_references.is_set();
1876 }
1877 
1878 bool ShenandoahHeap::unload_classes() const {
1879   return _unload_classes.is_set();
1880 }
1881 
1882 address ShenandoahHeap::in_cset_fast_test_addr() {
1883   ShenandoahHeap* heap = ShenandoahHeap::heap();
1884   assert(heap->collection_set() != NULL, "Sanity");
1885   return (address) heap->collection_set()->biased_map_address();
1886 }
1887 
1888 address ShenandoahHeap::cancelled_gc_addr() {
1889   return (address) ShenandoahHeap::heap()->_cancelled_gc.addr_of();
1890 }
1891 
1892 address ShenandoahHeap::gc_state_addr() {
1893   return (address) ShenandoahHeap::heap()->_gc_state.addr_of();
1894 }
1895 
1896 size_t ShenandoahHeap::conservative_max_heap_alignment() {
1897   size_t align = ShenandoahMaxRegionSize;
1898   if (UseLargePages) {
1899     align = MAX2(align, os::large_page_size());
1900   }
1901   return align;
1902 }
1903 
1904 size_t ShenandoahHeap::bytes_allocated_since_gc_start() {
1905   return OrderAccess::load_acquire(&_bytes_allocated_since_gc_start);
1906 }
1907 
1908 void ShenandoahHeap::reset_bytes_allocated_since_gc_start() {
1909   OrderAccess::release_store_fence(&_bytes_allocated_since_gc_start, (size_t)0);
1910 }
1911 
1912 void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) {
1913   _degenerated_gc_in_progress.set_cond(in_progress);
1914 }
1915 
1916 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {
1917   _full_gc_in_progress.set_cond(in_progress);
1918 }
1919 
1920 void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) {
1921   assert (is_full_gc_in_progress(), "should be");
1922   _full_gc_move_in_progress.set_cond(in_progress);
1923 }
1924 
1925 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {
1926   set_gc_state_mask(UPDATEREFS, in_progress);
1927 }
1928 
1929 void ShenandoahHeap::register_nmethod(nmethod* nm) {
1930   ShenandoahCodeRoots::add_nmethod(nm);
1931 }
1932 
1933 void ShenandoahHeap::unregister_nmethod(nmethod* nm) {
1934   ShenandoahCodeRoots::remove_nmethod(nm);
1935 }
1936 
1937 oop ShenandoahHeap::pin_object(JavaThread* thr, oop o) {
1938   ShenandoahHeapLocker locker(lock());
1939   heap_region_containing(o)->make_pinned();
1940   return o;
1941 }
1942 
1943 void ShenandoahHeap::unpin_object(JavaThread* thr, oop o) {
1944   ShenandoahHeapLocker locker(lock());
1945   heap_region_containing(o)->make_unpinned();
1946 }
1947 
1948 GCTimer* ShenandoahHeap::gc_timer() const {
1949   return _gc_timer;
1950 }
1951 
1952 #ifdef ASSERT
1953 void ShenandoahHeap::assert_gc_workers(uint nworkers) {
1954   assert(nworkers > 0 && nworkers <= max_workers(), "Sanity");
1955 
1956   if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) {
1957     if (UseDynamicNumberOfGCThreads ||
1958         (FLAG_IS_DEFAULT(ParallelGCThreads) && ForceDynamicNumberOfGCThreads)) {
1959       assert(nworkers <= ParallelGCThreads, "Cannot use more than it has");
1960     } else {
1961       // Use ParallelGCThreads inside safepoints
1962       assert(nworkers == ParallelGCThreads, "Use ParalleGCThreads within safepoints");
1963     }
1964   } else {
1965     if (UseDynamicNumberOfGCThreads ||
1966         (FLAG_IS_DEFAULT(ConcGCThreads) && ForceDynamicNumberOfGCThreads)) {
1967       assert(nworkers <= ConcGCThreads, "Cannot use more than it has");
1968     } else {
1969       // Use ConcGCThreads outside safepoints
1970       assert(nworkers == ConcGCThreads, "Use ConcGCThreads outside safepoints");
1971     }
1972   }
1973 }
1974 #endif
1975 
1976 ShenandoahVerifier* ShenandoahHeap::verifier() {
1977   guarantee(ShenandoahVerify, "Should be enabled");
1978   assert (_verifier != NULL, "sanity");
1979   return _verifier;
1980 }
1981 
1982 ShenandoahUpdateHeapRefsClosure::ShenandoahUpdateHeapRefsClosure() :
1983   _heap(ShenandoahHeap::heap()) {}
1984 
1985 class ShenandoahUpdateHeapRefsTask : public AbstractGangTask {
1986 private:
1987   ShenandoahHeap* _heap;
1988   ShenandoahRegionIterator* _regions;
1989   bool _concurrent;
1990 
1991 public:
1992   ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions, bool concurrent) :
1993     AbstractGangTask("Concurrent Update References Task"),
1994     _heap(ShenandoahHeap::heap()),
1995     _regions(regions),
1996     _concurrent(concurrent) {
1997   }
1998 
1999   void work(uint worker_id) {
2000     ShenandoahConcurrentWorkerSession worker_session(worker_id);
2001     ShenandoahUpdateHeapRefsClosure cl;
2002     ShenandoahHeapRegion* r = _regions->next();
2003     ShenandoahMarkingContext* const ctx = _heap->complete_marking_context();
2004     while (r != NULL) {
2005       HeapWord* top_at_start_ur = r->concurrent_iteration_safe_limit();
2006       assert (top_at_start_ur >= r->bottom(), "sanity");
2007       if (r->is_active() && !r->is_cset()) {
2008         _heap->marked_object_oop_iterate(r, &cl, top_at_start_ur);
2009       }
2010       if (ShenandoahPacing) {
2011         _heap->pacer()->report_updaterefs(pointer_delta(top_at_start_ur, r->bottom()));
2012       }
2013       if (_heap->cancelled_gc()) {
2014         return;
2015       }
2016       r = _regions->next();
2017     }
2018   }
2019 };
2020 
2021 void ShenandoahHeap::update_heap_references(bool concurrent) {
2022   ShenandoahUpdateHeapRefsTask task(&_update_refs_iterator, concurrent);
2023   workers()->run_task(&task);
2024 }
2025 
2026 void ShenandoahHeap::op_init_updaterefs() {
2027   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2028 
2029   set_evacuation_in_progress(false);
2030 
2031   if (ShenandoahVerify) {
2032     verifier()->verify_before_updaterefs();
2033   }
2034 
2035   set_update_refs_in_progress(true);
2036   make_parsable(true);
2037   for (uint i = 0; i < num_regions(); i++) {
2038     ShenandoahHeapRegion* r = get_region(i);
2039     r->set_concurrent_iteration_safe_limit(r->top());
2040   }
2041 
2042   // Reset iterator.
2043   _update_refs_iterator.reset();
2044 
2045   if (ShenandoahPacing) {
2046     pacer()->setup_for_updaterefs();
2047   }
2048 }
2049 
2050 void ShenandoahHeap::op_final_updaterefs() {
2051   assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint");
2052 
2053   // Check if there is left-over work, and finish it
2054   if (_update_refs_iterator.has_next()) {
2055     ShenandoahGCPhase final_work(ShenandoahPhaseTimings::final_update_refs_finish_work);
2056 
2057     // Finish updating references where we left off.
2058     clear_cancelled_gc();
2059     update_heap_references(false);
2060   }
2061 
2062   // Clear cancelled GC, if set. On cancellation path, the block before would handle
2063   // everything. On degenerated paths, cancelled gc would not be set anyway.
2064   if (cancelled_gc()) {
2065     clear_cancelled_gc();
2066   }
2067   assert(!cancelled_gc(), "Should have been done right before");
2068 
2069   concurrent_mark()->update_roots(is_degenerated_gc_in_progress() ?
2070                                  ShenandoahPhaseTimings::degen_gc_update_roots:
2071                                  ShenandoahPhaseTimings::final_update_refs_roots);
2072 
2073   ShenandoahGCPhase final_update_refs(ShenandoahPhaseTimings::final_update_refs_recycle);
2074 
2075   trash_cset_regions();
2076   set_has_forwarded_objects(false);
2077   set_update_refs_in_progress(false);
2078 
2079   if (ShenandoahVerify) {
2080     verifier()->verify_after_updaterefs();
2081   }
2082 
2083   if (VerifyAfterGC) {
2084     Universe::verify();
2085   }
2086 
2087   {
2088     ShenandoahHeapLocker locker(lock());
2089     _free_set->rebuild();
2090   }
2091 }
2092 
2093 #ifdef ASSERT
2094 void ShenandoahHeap::assert_heaplock_not_owned_by_current_thread() {
2095   _lock.assert_not_owned_by_current_thread();
2096 }
2097 
2098 void ShenandoahHeap::assert_heaplock_owned_by_current_thread() {
2099   _lock.assert_owned_by_current_thread();
2100 }
2101 
2102 void ShenandoahHeap::assert_heaplock_or_safepoint() {
2103   _lock.assert_owned_by_current_thread_or_safepoint();
2104 }
2105 #endif
2106 
2107 void ShenandoahHeap::print_extended_on(outputStream *st) const {
2108   print_on(st);
2109   print_heap_regions_on(st);
2110 }
2111 
2112 bool ShenandoahHeap::is_bitmap_slice_committed(ShenandoahHeapRegion* r, bool skip_self) {
2113   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2114 
2115   size_t regions_from = _bitmap_regions_per_slice * slice;
2116   size_t regions_to   = MIN2(num_regions(), _bitmap_regions_per_slice * (slice + 1));
2117   for (size_t g = regions_from; g < regions_to; g++) {
2118     assert (g / _bitmap_regions_per_slice == slice, "same slice");
2119     if (skip_self && g == r->region_number()) continue;
2120     if (get_region(g)->is_committed()) {
2121       return true;
2122     }
2123   }
2124   return false;
2125 }
2126 
2127 bool ShenandoahHeap::commit_bitmap_slice(ShenandoahHeapRegion* r) {
2128   assert_heaplock_owned_by_current_thread();
2129 
2130   // Bitmaps in special regions do not need commits
2131   if (_bitmap_region_special) {
2132     return true;
2133   }
2134 
2135   if (is_bitmap_slice_committed(r, true)) {
2136     // Some other region from the group is already committed, meaning the bitmap
2137     // slice is already committed, we exit right away.
2138     return true;
2139   }
2140 
2141   // Commit the bitmap slice:
2142   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2143   size_t off = _bitmap_bytes_per_slice * slice;
2144   size_t len = _bitmap_bytes_per_slice;
2145   if (!os::commit_memory((char*)_bitmap_region.start() + off, len, false)) {
2146     return false;
2147   }
2148   return true;
2149 }
2150 
2151 bool ShenandoahHeap::uncommit_bitmap_slice(ShenandoahHeapRegion *r) {
2152   assert_heaplock_owned_by_current_thread();
2153 
2154   // Bitmaps in special regions do not need uncommits
2155   if (_bitmap_region_special) {
2156     return true;
2157   }
2158 
2159   if (is_bitmap_slice_committed(r, true)) {
2160     // Some other region from the group is still committed, meaning the bitmap
2161     // slice is should stay committed, exit right away.
2162     return true;
2163   }
2164 
2165   // Uncommit the bitmap slice:
2166   size_t slice = r->region_number() / _bitmap_regions_per_slice;
2167   size_t off = _bitmap_bytes_per_slice * slice;
2168   size_t len = _bitmap_bytes_per_slice;
2169   if (!os::uncommit_memory((char*)_bitmap_region.start() + off, len)) {
2170     return false;
2171   }
2172   return true;
2173 }
2174 
2175 void ShenandoahHeap::vmop_entry_init_mark() {
2176   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2177   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2178   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_mark_gross);
2179 
2180   try_inject_alloc_failure();
2181   VM_ShenandoahInitMark op;
2182   VMThread::execute(&op); // jump to entry_init_mark() under safepoint
2183 }
2184 
2185 void ShenandoahHeap::vmop_entry_final_mark() {
2186   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2187   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2188   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_mark_gross);
2189 
2190   try_inject_alloc_failure();
2191   VM_ShenandoahFinalMarkStartEvac op;
2192   VMThread::execute(&op); // jump to entry_final_mark under safepoint
2193 }
2194 
2195 void ShenandoahHeap::vmop_entry_final_evac() {
2196   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2197   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2198   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac_gross);
2199 
2200   VM_ShenandoahFinalEvac op;
2201   VMThread::execute(&op); // jump to entry_final_evac under safepoint
2202 }
2203 
2204 void ShenandoahHeap::vmop_entry_init_updaterefs() {
2205   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2206   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2207   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs_gross);
2208 
2209   try_inject_alloc_failure();
2210   VM_ShenandoahInitUpdateRefs op;
2211   VMThread::execute(&op);
2212 }
2213 
2214 void ShenandoahHeap::vmop_entry_final_updaterefs() {
2215   TraceCollectorStats tcs(monitoring_support()->stw_collection_counters());
2216   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2217   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_gross);
2218 
2219   try_inject_alloc_failure();
2220   VM_ShenandoahFinalUpdateRefs op;
2221   VMThread::execute(&op);
2222 }
2223 
2224 void ShenandoahHeap::vmop_entry_full(GCCause::Cause cause) {
2225   TraceCollectorStats tcs(monitoring_support()->full_stw_collection_counters());
2226   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2227   ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_gross);
2228 
2229   try_inject_alloc_failure();
2230   VM_ShenandoahFullGC op(cause);
2231   VMThread::execute(&op);
2232 }
2233 
2234 void ShenandoahHeap::vmop_degenerated(ShenandoahDegenPoint point) {
2235   TraceCollectorStats tcs(monitoring_support()->full_stw_collection_counters());
2236   ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross);
2237   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_gross);
2238 
2239   VM_ShenandoahDegeneratedGC degenerated_gc((int)point);
2240   VMThread::execute(&degenerated_gc);
2241 }
2242 
2243 void ShenandoahHeap::entry_init_mark() {
2244   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2245   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_mark);
2246 
2247   const char* msg = init_mark_event_message();
2248   GCTraceTime time(msg, PrintGC, _gc_timer, tracer()->gc_id());
2249   EventMark em("%s", msg);
2250 
2251   ShenandoahWorkerScope scope(workers(),
2252                               ShenandoahWorkerPolicy::calc_workers_for_init_marking(),
2253                               "init marking");
2254 
2255   op_init_mark();
2256 }
2257 
2258 void ShenandoahHeap::entry_final_mark() {
2259   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2260   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_mark);
2261 
2262   const char* msg = final_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_final_marking(),
2268                               "final marking");
2269 
2270   op_final_mark();
2271 }
2272 
2273 void ShenandoahHeap::entry_final_evac() {
2274   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2275   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac);
2276 
2277   const char* msg = "Pause Final Evac";
2278   GCTraceTime time(msg, PrintGC, _gc_timer, tracer()->gc_id());
2279   EventMark em("%s", msg);
2280 
2281   op_final_evac();
2282 }
2283 
2284 void ShenandoahHeap::entry_init_updaterefs() {
2285   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2286   ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs);
2287 
2288   static const char* msg = "Pause Init Update Refs";
2289   GCTraceTime time(msg, PrintGC, _gc_timer, tracer()->gc_id());
2290   EventMark em("%s", msg);
2291 
2292   // No workers used in this phase, no setup required
2293 
2294   op_init_updaterefs();
2295 }
2296 
2297 void ShenandoahHeap::entry_final_updaterefs() {
2298   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2299   ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs);
2300 
2301   static const char* msg = "Pause Final Update Refs";
2302   GCTraceTime time(msg, PrintGC, _gc_timer, tracer()->gc_id());
2303   EventMark em("%s", msg);
2304 
2305   ShenandoahWorkerScope scope(workers(),
2306                               ShenandoahWorkerPolicy::calc_workers_for_final_update_ref(),
2307                               "final reference update");
2308 
2309   op_final_updaterefs();
2310 }
2311 
2312 void ShenandoahHeap::entry_full(GCCause::Cause cause) {
2313   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2314   ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc);
2315 
2316   static const char* msg = "Pause Full";
2317   GCTraceTime time(msg, PrintGC, _gc_timer, tracer()->gc_id(), true);
2318   EventMark em("%s", msg);
2319 
2320   ShenandoahWorkerScope scope(workers(),
2321                               ShenandoahWorkerPolicy::calc_workers_for_fullgc(),
2322                               "full gc");
2323 
2324   op_full(cause);
2325 }
2326 
2327 void ShenandoahHeap::entry_degenerated(int point) {
2328   ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause);
2329   ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc);
2330 
2331   ShenandoahDegenPoint dpoint = (ShenandoahDegenPoint)point;
2332   const char* msg = degen_event_message(dpoint);
2333   GCTraceTime time(msg, PrintGC, _gc_timer, tracer()->gc_id(), true);
2334   EventMark em("%s", msg);
2335 
2336   ShenandoahWorkerScope scope(workers(),
2337                               ShenandoahWorkerPolicy::calc_workers_for_stw_degenerated(),
2338                               "stw degenerated gc");
2339 
2340   set_degenerated_gc_in_progress(true);
2341   op_degenerated(dpoint);
2342   set_degenerated_gc_in_progress(false);
2343 }
2344 
2345 void ShenandoahHeap::entry_mark() {
2346   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2347 
2348   const char* msg = conc_mark_event_message();
2349   GCTraceTime time(msg, PrintGC, NULL, tracer()->gc_id(), true);
2350   EventMark em("%s", msg);
2351 
2352   ShenandoahWorkerScope scope(workers(),
2353                               ShenandoahWorkerPolicy::calc_workers_for_conc_marking(),
2354                               "concurrent marking");
2355 
2356   try_inject_alloc_failure();
2357   op_mark();
2358 }
2359 
2360 void ShenandoahHeap::entry_evac() {
2361   ShenandoahGCPhase conc_evac_phase(ShenandoahPhaseTimings::conc_evac);
2362   TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
2363 
2364   static const char *msg = "Concurrent evacuation";
2365   GCTraceTime time(msg, PrintGC, NULL, tracer()->gc_id(), true);
2366   EventMark em("%s", msg);
2367 
2368   ShenandoahWorkerScope scope(workers(),
2369                               ShenandoahWorkerPolicy::calc_workers_for_conc_evac(),
2370                               "concurrent evacuation");
2371 
2372   try_inject_alloc_failure();
2373   op_conc_evac();
2374 }
2375 
2376 void ShenandoahHeap::entry_updaterefs() {
2377   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_update_refs);
2378 
2379   static const char* msg = "Concurrent update references";
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_update_ref(),
2385                               "concurrent reference update");
2386 
2387   try_inject_alloc_failure();
2388   op_updaterefs();
2389 }
2390 
2391 void ShenandoahHeap::entry_cleanup() {
2392   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_cleanup);
2393 
2394   static const char* msg = "Concurrent cleanup";
2395   GCTraceTime time(msg, PrintGC, NULL, tracer()->gc_id(), true);
2396   EventMark em("%s", msg);
2397 
2398   // This phase does not use workers, no need for setup
2399 
2400   try_inject_alloc_failure();
2401   op_cleanup();
2402 }
2403 
2404 void ShenandoahHeap::entry_reset() {
2405   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_reset);
2406 
2407   static const char* msg = "Concurrent reset";
2408   GCTraceTime time(msg, PrintGC, NULL, tracer()->gc_id(), true);
2409   EventMark em("%s", msg);
2410 
2411   ShenandoahWorkerScope scope(workers(),
2412                               ShenandoahWorkerPolicy::calc_workers_for_conc_reset(),
2413                               "concurrent reset");
2414 
2415   try_inject_alloc_failure();
2416   op_reset();
2417 }
2418 
2419 void ShenandoahHeap::entry_preclean() {
2420   if (ShenandoahPreclean && process_references()) {
2421     ShenandoahGCPhase conc_preclean(ShenandoahPhaseTimings::conc_preclean);
2422 
2423     static const char* msg = "Concurrent precleaning";
2424     GCTraceTime time(msg, PrintGC, NULL, tracer()->gc_id(), true);
2425     EventMark em("%s", msg);
2426 
2427     ShenandoahWorkerScope scope(workers(),
2428                                 ShenandoahWorkerPolicy::calc_workers_for_conc_preclean(),
2429                                 "concurrent preclean",
2430                                 /* check_workers = */ false);
2431 
2432     try_inject_alloc_failure();
2433     op_preclean();
2434   }
2435 }
2436 
2437 void ShenandoahHeap::entry_uncommit(double shrink_before) {
2438   static const char *msg = "Concurrent uncommit";
2439   GCTraceTime time(msg, PrintGC, NULL, tracer()->gc_id(), true);
2440   EventMark em("%s", msg);
2441 
2442   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_uncommit);
2443 
2444   op_uncommit(shrink_before);
2445 }
2446 
2447 void ShenandoahHeap::try_inject_alloc_failure() {
2448   if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) {
2449     _inject_alloc_failure.set();
2450     os::naked_short_sleep(1);
2451     if (cancelled_gc()) {
2452       log_info(gc)("Allocation failure was successfully injected");
2453     }
2454   }
2455 }
2456 
2457 bool ShenandoahHeap::should_inject_alloc_failure() {
2458   return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset();
2459 }
2460 
2461 void ShenandoahHeap::enter_evacuation() {
2462   _oom_evac_handler.enter_evacuation();
2463 }
2464 
2465 void ShenandoahHeap::leave_evacuation() {
2466   _oom_evac_handler.leave_evacuation();
2467 }
2468 
2469 ShenandoahRegionIterator::ShenandoahRegionIterator() :
2470   _heap(ShenandoahHeap::heap()),
2471   _index(0) {}
2472 
2473 ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) :
2474   _heap(heap),
2475   _index(0) {}
2476 
2477 void ShenandoahRegionIterator::reset() {
2478   _index = 0;
2479 }
2480 
2481 bool ShenandoahRegionIterator::has_next() const {
2482   return _index < (jint)_heap->num_regions();
2483 }
2484 
2485 char ShenandoahHeap::gc_state() {
2486   return _gc_state.raw_value();
2487 }
2488 
2489 const char* ShenandoahHeap::init_mark_event_message() const {
2490   bool update_refs = has_forwarded_objects();
2491   bool proc_refs = process_references();
2492   bool unload_cls = unload_classes();
2493 
2494   if (update_refs && proc_refs && unload_cls) {
2495     return "Pause Init Mark (update refs) (process weakrefs) (unload classes)";
2496   } else if (update_refs && proc_refs) {
2497     return "Pause Init Mark (update refs) (process weakrefs)";
2498   } else if (update_refs && unload_cls) {
2499     return "Pause Init Mark (update refs) (unload classes)";
2500   } else if (proc_refs && unload_cls) {
2501     return "Pause Init Mark (process weakrefs) (unload classes)";
2502   } else if (update_refs) {
2503     return "Pause Init Mark (update refs)";
2504   } else if (proc_refs) {
2505     return "Pause Init Mark (process weakrefs)";
2506   } else if (unload_cls) {
2507     return "Pause Init Mark (unload classes)";
2508   } else {
2509     return "Pause Init Mark";
2510   }
2511 }
2512 
2513 const char* ShenandoahHeap::final_mark_event_message() const {
2514   bool update_refs = has_forwarded_objects();
2515   bool proc_refs = process_references();
2516   bool unload_cls = unload_classes();
2517 
2518   if (update_refs && proc_refs && unload_cls) {
2519     return "Pause Final Mark (update refs) (process weakrefs) (unload classes)";
2520   } else if (update_refs && proc_refs) {
2521     return "Pause Final Mark (update refs) (process weakrefs)";
2522   } else if (update_refs && unload_cls) {
2523     return "Pause Final Mark (update refs) (unload classes)";
2524   } else if (proc_refs && unload_cls) {
2525     return "Pause Final Mark (process weakrefs) (unload classes)";
2526   } else if (update_refs) {
2527     return "Pause Final Mark (update refs)";
2528   } else if (proc_refs) {
2529     return "Pause Final Mark (process weakrefs)";
2530   } else if (unload_cls) {
2531     return "Pause Final Mark (unload classes)";
2532   } else {
2533     return "Pause Final Mark";
2534   }
2535 }
2536 
2537 const char* ShenandoahHeap::conc_mark_event_message() const {
2538   bool update_refs = has_forwarded_objects();
2539   bool proc_refs = process_references();
2540   bool unload_cls = unload_classes();
2541 
2542   if (update_refs && proc_refs && unload_cls) {
2543     return "Concurrent marking (update refs) (process weakrefs) (unload classes)";
2544   } else if (update_refs && proc_refs) {
2545     return "Concurrent marking (update refs) (process weakrefs)";
2546   } else if (update_refs && unload_cls) {
2547     return "Concurrent marking (update refs) (unload classes)";
2548   } else if (proc_refs && unload_cls) {
2549     return "Concurrent marking (process weakrefs) (unload classes)";
2550   } else if (update_refs) {
2551     return "Concurrent marking (update refs)";
2552   } else if (proc_refs) {
2553     return "Concurrent marking (process weakrefs)";
2554   } else if (unload_cls) {
2555     return "Concurrent marking (unload classes)";
2556   } else {
2557     return "Concurrent marking";
2558   }
2559 }
2560 
2561 const char* ShenandoahHeap::degen_event_message(ShenandoahDegenPoint point) const {
2562   switch (point) {
2563     case _degenerated_unset:
2564       return "Pause Degenerated GC (<UNSET>)";
2565     case _degenerated_outside_cycle:
2566       return "Pause Degenerated GC (Outside of Cycle)";
2567     case _degenerated_mark:
2568       return "Pause Degenerated GC (Mark)";
2569     case _degenerated_evac:
2570       return "Pause Degenerated GC (Evacuation)";
2571     case _degenerated_updaterefs:
2572       return "Pause Degenerated GC (Update Refs)";
2573     default:
2574       ShouldNotReachHere();
2575       return "ERROR";
2576   }
2577 }
2578 
2579 jushort* ShenandoahHeap::get_liveness_cache(uint worker_id) {
2580 #ifdef ASSERT
2581   assert(_liveness_cache != NULL, "sanity");
2582   assert(worker_id < _max_workers, "sanity");
2583   for (uint i = 0; i < num_regions(); i++) {
2584     assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty");
2585   }
2586 #endif
2587   return _liveness_cache[worker_id];
2588 }
2589 
2590 void ShenandoahHeap::flush_liveness_cache(uint worker_id) {
2591   assert(worker_id < _max_workers, "sanity");
2592   assert(_liveness_cache != NULL, "sanity");
2593   jushort* ld = _liveness_cache[worker_id];
2594   for (uint i = 0; i < num_regions(); i++) {
2595     ShenandoahHeapRegion* r = get_region(i);
2596     jushort live = ld[i];
2597     if (live > 0) {
2598       r->increase_live_data_gc_words(live);
2599       ld[i] = 0;
2600     }
2601   }
2602 }