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