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