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