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