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