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