1 /*
   2  * Copyright (c) 2013, 2017, Red Hat, Inc. and/or its affiliates.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.
   7  *
   8  * This code is distributed in the hope that it will be useful, but WITHOUT
   9  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  11  * version 2 for more details (a copy is included in the LICENSE file that
  12  * accompanied this code).
  13  *
  14  * You should have received a copy of the GNU General Public License version
  15  * 2 along with this work; if not, write to the Free Software Foundation,
  16  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  17  *
  18  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  19  * or visit www.oracle.com if you need additional information or have any
  20  * questions.
  21  *
  22  */
  23 
  24 #include "precompiled.hpp"
  25 #include "memory/allocation.hpp"
  26 
  27 #include "gc/shared/gcTimer.hpp"
  28 #include "gc/shared/gcTraceTime.inline.hpp"
  29 #include "gc/shared/parallelCleaning.hpp"
  30 
  31 #include "gc/shenandoah/brooksPointer.hpp"
  32 #include "gc/shenandoah/shenandoahAllocTracker.hpp"
  33 #include "gc/shenandoah/shenandoahBarrierSet.hpp"
  34 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  35 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
  36 #include "gc/shenandoah/shenandoahConcurrentMark.hpp"
  37 #include "gc/shenandoah/shenandoahConcurrentMark.inline.hpp"
  38 #include "gc/shenandoah/shenandoahConcurrentThread.hpp"
  39 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  40 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
  41 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  42 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
  43 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  44 #include "gc/shenandoah/shenandoahMarkCompact.hpp"
  45 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
  46 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
  47 #include "gc/shenandoah/shenandoahPartialGC.hpp"
  48 #include "gc/shenandoah/shenandoahRootProcessor.hpp"
  49 #include "gc/shenandoah/shenandoahStringDedup.hpp"
  50 #include "gc/shenandoah/shenandoahUtils.hpp"
  51 #include "gc/shenandoah/shenandoahVerifier.hpp"
  52 #include "gc/shenandoah/shenandoahCodeRoots.hpp"
  53 #include "gc/shenandoah/vm_operations_shenandoah.hpp"
  54 
  55 #include "runtime/vmThread.hpp"
  56 #include "services/mallocTracker.hpp"
  57 
  58 ShenandoahUpdateRefsClosure::ShenandoahUpdateRefsClosure() : _heap(ShenandoahHeap::heap()) {}
  59 
  60 #ifdef ASSERT
  61 template <class T>
  62 void ShenandoahAssertToSpaceClosure::do_oop_nv(T* p) {
  63   T o = oopDesc::load_heap_oop(p);
  64   if (! oopDesc::is_null(o)) {
  65     oop obj = oopDesc::decode_heap_oop_not_null(o);
  66     assert(oopDesc::unsafe_equals(obj, ShenandoahBarrierSet::resolve_oop_static_not_null(obj)),
  67            "need to-space object here obj: "PTR_FORMAT" , rb(obj): "PTR_FORMAT", p: "PTR_FORMAT,
  68            p2i(obj), p2i(ShenandoahBarrierSet::resolve_oop_static_not_null(obj)), p2i(p));
  69   }
  70 }
  71 
  72 void ShenandoahAssertToSpaceClosure::do_oop(narrowOop* p) { do_oop_nv(p); }
  73 void ShenandoahAssertToSpaceClosure::do_oop(oop* p)       { do_oop_nv(p); }
  74 #endif
  75 
  76 const char* ShenandoahHeap::name() const {
  77   return "Shenandoah";
  78 }
  79 
  80 class ShenandoahPretouchTask : public AbstractGangTask {
  81 private:
  82   ShenandoahHeapRegionSet* _regions;
  83   const size_t _bitmap_size;
  84   const size_t _page_size;
  85   char* _bitmap_base;
  86 public:
  87   ShenandoahPretouchTask(ShenandoahHeapRegionSet* regions,
  88                          char* bitmap_base, size_t bitmap_size,
  89                          size_t page_size) :
  90     AbstractGangTask("Shenandoah PreTouch",
  91                      Universe::is_fully_initialized() ? GCId::current_raw() :
  92                                                         // During VM initialization there is
  93                                                         // no GC cycle that this task can be
  94                                                         // associated with.
  95                                                         GCId::undefined()),
  96     _bitmap_base(bitmap_base),
  97     _regions(regions),
  98     _bitmap_size(bitmap_size),
  99     _page_size(page_size) {
 100     _regions->clear_current_index();
 101   };
 102 
 103   virtual void work(uint worker_id) {
 104     ShenandoahHeapRegion* r = _regions->claim_next();
 105     while (r != NULL) {
 106       log_trace(gc, heap)("Pretouch region " SIZE_FORMAT ": " PTR_FORMAT " -> " PTR_FORMAT,
 107                           r->region_number(), p2i(r->bottom()), p2i(r->end()));
 108       os::pretouch_memory(r->bottom(), r->end(), _page_size);
 109 
 110       size_t start = r->region_number()       * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
 111       size_t end   = (r->region_number() + 1) * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor();
 112       assert (end <= _bitmap_size, "end is sane: " SIZE_FORMAT " < " SIZE_FORMAT, end, _bitmap_size);
 113 
 114       log_trace(gc, heap)("Pretouch bitmap under region " SIZE_FORMAT ": " PTR_FORMAT " -> " PTR_FORMAT,
 115                           r->region_number(), p2i(_bitmap_base + start), p2i(_bitmap_base + end));
 116       os::pretouch_memory(_bitmap_base + start, _bitmap_base + end, _page_size);
 117 
 118       r = _regions->claim_next();
 119     }
 120   }
 121 };
 122 
 123 jint ShenandoahHeap::initialize() {
 124   CollectedHeap::pre_initialize();
 125 
 126   BrooksPointer::initial_checks();
 127 
 128   size_t init_byte_size = collector_policy()->initial_heap_byte_size();
 129   size_t max_byte_size = collector_policy()->max_heap_byte_size();
 130   size_t heap_alignment = collector_policy()->heap_alignment();
 131 
 132   if (ShenandoahAlwaysPreTouch) {
 133     // Enabled pre-touch means the entire heap is committed right away.
 134     init_byte_size = max_byte_size;
 135   }
 136 
 137   Universe::check_alignment(max_byte_size,
 138                             ShenandoahHeapRegion::region_size_bytes(),
 139                             "shenandoah heap");
 140   Universe::check_alignment(init_byte_size,
 141                             ShenandoahHeapRegion::region_size_bytes(),
 142                             "shenandoah heap");
 143 
 144   ReservedSpace heap_rs = Universe::reserve_heap(max_byte_size,
 145                                                  heap_alignment);
 146   initialize_reserved_region((HeapWord*)heap_rs.base(), (HeapWord*) (heap_rs.base() + heap_rs.size()));
 147 
 148   set_barrier_set(new ShenandoahBarrierSet(this));
 149   ReservedSpace pgc_rs = heap_rs.first_part(max_byte_size);
 150 
 151   _num_regions = max_byte_size / ShenandoahHeapRegion::region_size_bytes();
 152   size_t num_committed_regions = init_byte_size / ShenandoahHeapRegion::region_size_bytes();
 153   _initial_size = num_committed_regions * ShenandoahHeapRegion::region_size_bytes();
 154   _committed = _initial_size;
 155 
 156   log_info(gc, heap)("Initialize Shenandoah heap with initial size " SIZE_FORMAT " bytes", init_byte_size);
 157   if (!os::commit_memory(pgc_rs.base(), _initial_size, false)) {
 158     vm_exit_out_of_memory(_initial_size, OOM_MMAP_ERROR, "Shenandoah failed to initialize heap");
 159   }
 160 
 161   size_t reg_size_words = ShenandoahHeapRegion::region_size_words();
 162 
 163   _ordered_regions = new ShenandoahHeapRegionSet(_num_regions);
 164   _free_regions = new ShenandoahFreeSet(_ordered_regions, _num_regions);
 165 
 166   _collection_set = new ShenandoahCollectionSet(this, (HeapWord*)pgc_rs.base());
 167 
 168   _top_at_mark_starts_base = NEW_C_HEAP_ARRAY(HeapWord*, _num_regions, mtGC);
 169   _top_at_mark_starts = _top_at_mark_starts_base -
 170                ((uintx) pgc_rs.base() >> ShenandoahHeapRegion::region_size_bytes_shift());
 171 
 172 
 173   {
 174     ShenandoahHeapLocker locker(lock());
 175     for (size_t i = 0; i < _num_regions; i++) {
 176       ShenandoahHeapRegion* r = new ShenandoahHeapRegion(this,
 177                                                          (HeapWord*) pgc_rs.base() + reg_size_words * i,
 178                                                          reg_size_words,
 179                                                          i,
 180                                                          i < num_committed_regions);
 181 
 182       _top_at_mark_starts_base[i] = r->bottom();
 183 
 184       // Add to ordered regions first.
 185       // We use the active size of ordered regions as the number of active regions in heap,
 186       // free set and collection set use the number to assert the correctness of incoming regions.
 187       _ordered_regions->add_region(r);
 188       _free_regions->add_region(r);
 189       assert(!collection_set()->is_in(i), "New region should not be in collection set");
 190     }
 191   }
 192 
 193   assert(_ordered_regions->active_regions() == _num_regions, "Must match");
 194   assert((((size_t) base()) & ShenandoahHeapRegion::region_size_bytes_mask()) == 0,
 195          "misaligned heap: "PTR_FORMAT, p2i(base()));
 196 
 197   LogTarget(Trace, gc, region) lt;
 198   if (lt.is_enabled()) {
 199     ResourceMark rm;
 200     LogStream ls(lt);
 201     log_trace(gc, region)("All Regions");
 202     _ordered_regions->print_on(&ls);
 203     log_trace(gc, region)("Free Regions");
 204     _free_regions->print_on(&ls);
 205   }
 206 
 207   _recycled_regions = NEW_C_HEAP_ARRAY(size_t, _num_regions, mtGC);
 208 
 209   // The call below uses stuff (the SATB* things) that are in G1, but probably
 210   // belong into a shared location.
 211   JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon,
 212                                                SATB_Q_FL_lock,
 213                                                20 /*G1SATBProcessCompletedThreshold */,
 214                                                Shared_SATB_Q_lock);
 215 
 216   // Reserve space for prev and next bitmap.
 217   _bitmap_size = MarkBitMap::compute_size(heap_rs.size());
 218   _heap_region = MemRegion((HeapWord*) heap_rs.base(), heap_rs.size() / HeapWordSize);
 219 
 220   size_t bitmap_bytes_per_region = _bitmap_size / _num_regions;
 221   _bitmap_words_per_region = bitmap_bytes_per_region / HeapWordSize;
 222 
 223   guarantee(bitmap_bytes_per_region != 0,
 224             "Bitmap bytes per region should not be zero");
 225   guarantee(is_power_of_2(bitmap_bytes_per_region),
 226             "Bitmap bytes per region should be power of two: " SIZE_FORMAT, bitmap_bytes_per_region);
 227   guarantee((bitmap_bytes_per_region % os::vm_page_size()) == 0,
 228             "Bitmap bytes per region should be page-granular: bpr = " SIZE_FORMAT ", page size = %d",
 229             bitmap_bytes_per_region, os::vm_page_size());
 230   guarantee(is_power_of_2(_bitmap_words_per_region),
 231             "Bitmap words per region Should be power of two: " SIZE_FORMAT, _bitmap_words_per_region);
 232 
 233   size_t bitmap_page_size = UseLargePages && (bitmap_bytes_per_region >= (size_t)os::large_page_size()) ?
 234                             (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 235 
 236   ReservedSpace bitmap(_bitmap_size, bitmap_page_size);
 237   MemTracker::record_virtual_memory_type(bitmap.base(), mtGC);
 238   _bitmap_region = MemRegion((HeapWord*) bitmap.base(), bitmap.size() / HeapWordSize);
 239 
 240   {
 241     ShenandoahHeapLocker locker(lock());
 242     for (size_t i = 0; i < _num_regions; i++) {
 243       ShenandoahHeapRegion* r = _ordered_regions->get(i);
 244       if (r->is_committed()) {
 245         commit_bitmaps(r);
 246       }
 247     }
 248   }
 249 
 250   size_t page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 251 
 252   if (ShenandoahVerify) {
 253     ReservedSpace verify_bitmap(_bitmap_size, page_size);
 254     os::commit_memory_or_exit(verify_bitmap.base(), verify_bitmap.size(), false,
 255                               "couldn't allocate verification bitmap");
 256     MemTracker::record_virtual_memory_type(verify_bitmap.base(), mtGC);
 257     MemRegion verify_bitmap_region = MemRegion((HeapWord *) verify_bitmap.base(), verify_bitmap.size() / HeapWordSize);
 258     _verification_bit_map.initialize(_heap_region, verify_bitmap_region);
 259     _verifier = new ShenandoahVerifier(this, &_verification_bit_map);
 260   }
 261 
 262   if (ShenandoahAlwaysPreTouch) {
 263     assert (!AlwaysPreTouch, "Should have been overridden");
 264 
 265     // For NUMA, it is important to pre-touch the storage under bitmaps with worker threads,
 266     // before initialize() below zeroes it with initializing thread. For any given region,
 267     // we touch the region and the corresponding bitmaps from the same thread.
 268 
 269     log_info(gc, heap)("Parallel pretouch " SIZE_FORMAT " regions with " SIZE_FORMAT " byte pages",
 270                        _ordered_regions->count(), page_size);
 271     ShenandoahPretouchTask cl(_ordered_regions, bitmap.base(), _bitmap_size, page_size);
 272     _workers->run_task(&cl);
 273   }
 274 
 275   _mark_bit_map.initialize(_heap_region, _bitmap_region);
 276 
 277   // Reserve aux bitmap for use in object_iterate(). We don't commit it here.
 278   ReservedSpace aux_bitmap(_bitmap_size, bitmap_page_size);
 279   MemTracker::record_virtual_memory_type(aux_bitmap.base(), mtGC);
 280   _aux_bitmap_region = MemRegion((HeapWord*) aux_bitmap.base(), aux_bitmap.size() / HeapWordSize);
 281   _aux_bit_map.initialize(_heap_region, _aux_bitmap_region);
 282 
 283   if (UseShenandoahMatrix) {
 284     _connection_matrix = new ShenandoahConnectionMatrix(_num_regions);
 285   } else {
 286     _connection_matrix = NULL;
 287   }
 288 
 289   _partial_gc = _shenandoah_policy->can_do_partial_gc() ?
 290                 new ShenandoahPartialGC(this, _num_regions) :
 291                 NULL;
 292 
 293   _monitoring_support = new ShenandoahMonitoringSupport(this);
 294 
 295   _phase_timings = new ShenandoahPhaseTimings();
 296 
 297   if (ShenandoahAllocationTrace) {
 298     _alloc_tracker = new ShenandoahAllocTracker();
 299   }
 300 
 301   ShenandoahStringDedup::initialize();
 302 
 303   _concurrent_gc_thread = new ShenandoahConcurrentThread();
 304 
 305   ShenandoahMarkCompact::initialize();
 306 
 307   ShenandoahCodeRoots::initialize();
 308 
 309   return JNI_OK;
 310 }
 311 
 312 ShenandoahHeap::ShenandoahHeap(ShenandoahCollectorPolicy* policy) :
 313   CollectedHeap(),
 314   _shenandoah_policy(policy),
 315   _concurrent_mark_in_progress(0),
 316   _evacuation_in_progress(0),
 317   _full_gc_in_progress(false),
 318   _update_refs_in_progress(false),
 319   _concurrent_partial_in_progress(false),
 320   _free_regions(NULL),
 321   _collection_set(NULL),
 322   _bytes_allocated_since_cm(0),
 323   _bytes_allocated_during_cm(0),
 324   _allocated_last_gc(0),
 325   _used_start_gc(0),
 326   _max_workers(MAX2(ConcGCThreads, ParallelGCThreads)),
 327   _ref_processor(NULL),
 328   _top_at_mark_starts(NULL),
 329   _top_at_mark_starts_base(NULL),
 330   _mark_bit_map(),
 331   _aux_bit_map(),
 332   _connection_matrix(NULL),
 333   _cancelled_concgc(0),
 334   _need_update_refs(false),
 335   _need_reset_bitmap(false),
 336   _bitmap_valid(true),
 337   _verifier(NULL),
 338   _heap_lock(0),
 339   _used_at_last_gc(0),
 340   _alloc_seq_at_last_gc_start(0),
 341   _alloc_seq_at_last_gc_end(0),
 342   _safepoint_workers(NULL),
 343 #ifdef ASSERT
 344   _heap_lock_owner(NULL),
 345   _heap_expansion_count(0),
 346 #endif
 347   _gc_timer(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
 348   _phase_timings(NULL),
 349   _alloc_tracker(NULL)
 350 {
 351   log_info(gc, init)("Parallel GC threads: "UINT32_FORMAT, ParallelGCThreads);
 352   log_info(gc, init)("Concurrent GC threads: "UINT32_FORMAT, ConcGCThreads);
 353   log_info(gc, init)("Parallel reference processing enabled: %s", BOOL_TO_STR(ParallelRefProcEnabled));
 354 
 355   _scm = new ShenandoahConcurrentMark();
 356   _used = 0;
 357 
 358   _max_workers = MAX2(_max_workers, 1U);
 359   _workers = new ShenandoahWorkGang("Shenandoah GC Threads", _max_workers,
 360                             /* are_GC_task_threads */true,
 361                             /* are_ConcurrentGC_threads */false);
 362   if (_workers == NULL) {
 363     vm_exit_during_initialization("Failed necessary allocation.");
 364   } else {
 365     _workers->initialize_workers();
 366   }
 367 
 368   if (ParallelSafepointCleanupThreads > 1) {
 369     _safepoint_workers = new ShenandoahWorkGang("Safepoint Cleanup Thread",
 370                                                 ParallelSafepointCleanupThreads,
 371                                                 false, false);
 372     _safepoint_workers->initialize_workers();
 373   }
 374 }
 375 
 376 class ShenandoahResetBitmapTask : public AbstractGangTask {
 377 private:
 378   ShenandoahHeapRegionSet* _regions;
 379 
 380 public:
 381   ShenandoahResetBitmapTask(ShenandoahHeapRegionSet* regions) :
 382     AbstractGangTask("Parallel Reset Bitmap Task"),
 383     _regions(regions) {
 384     _regions->clear_current_index();
 385   }
 386 
 387   void work(uint worker_id) {
 388     ShenandoahHeapRegion* region = _regions->claim_next();
 389     ShenandoahHeap* heap = ShenandoahHeap::heap();
 390     while (region != NULL) {
 391       if (region->is_committed()) {
 392         HeapWord* bottom = region->bottom();
 393         HeapWord* top = heap->top_at_mark_start(region->bottom());
 394         if (top > bottom) {
 395           heap->mark_bit_map()->clear_range_large(MemRegion(bottom, top));
 396         }
 397         assert(heap->is_bitmap_clear_range(bottom, region->end()), "must be clear");
 398         heap->set_top_at_mark_start(region->bottom(), region->bottom());
 399       }
 400       region = _regions->claim_next();
 401     }
 402   }
 403 };
 404 
 405 void ShenandoahHeap::reset_mark_bitmap(WorkGang* workers) {
 406   assert_gc_workers(workers->active_workers());
 407 
 408   ShenandoahResetBitmapTask task = ShenandoahResetBitmapTask(_ordered_regions);
 409   workers->run_task(&task);
 410 }
 411 
 412 bool ShenandoahHeap::is_bitmap_clear() {
 413   for (size_t idx = 0; idx < _num_regions; idx++) {
 414     ShenandoahHeapRegion* r = _ordered_regions->get(idx);
 415     if (r->is_committed() && !is_bitmap_clear_range(r->bottom(), r->end())) {
 416       return false;
 417     }
 418   }
 419   return true;
 420 }
 421 
 422 bool ShenandoahHeap::is_bitmap_clear_range(HeapWord* start, HeapWord* end) {
 423   return _mark_bit_map.getNextMarkedWordAddress(start, end) == end;
 424 }
 425 
 426 void ShenandoahHeap::print_on(outputStream* st) const {
 427   st->print_cr("Shenandoah Heap");
 428   st->print_cr(" " SIZE_FORMAT "K total, " SIZE_FORMAT "K committed, " SIZE_FORMAT "K used",
 429                capacity() / K, committed() / K, used() / K);
 430   st->print_cr(" " SIZE_FORMAT " x " SIZE_FORMAT"K regions",
 431                num_regions(), ShenandoahHeapRegion::region_size_bytes() / K);
 432 
 433   st->print("Status: ");
 434   if (concurrent_mark_in_progress()) {
 435     st->print("marking ");
 436   } else if (is_evacuation_in_progress()) {
 437     st->print("evacuating ");
 438   } else if (is_update_refs_in_progress()) {
 439     st->print("updating refs ");
 440   } else {
 441     st->print("idle ");
 442   }
 443   if (cancelled_concgc()) {
 444     st->print("cancelled ");
 445   }
 446   st->cr();
 447 
 448   st->print_cr("Reserved region:");
 449   st->print_cr(" - [" PTR_FORMAT ", " PTR_FORMAT ") ",
 450                p2i(reserved_region().start()),
 451                p2i(reserved_region().end()));
 452 
 453   if (UseShenandoahMatrix) {
 454     st->print_cr("Matrix:");
 455 
 456     ShenandoahConnectionMatrix* matrix = connection_matrix();
 457     if (matrix != NULL) {
 458       st->print_cr(" - base: " PTR_FORMAT, p2i(matrix->matrix_addr()));
 459       st->print_cr(" - stride: " SIZE_FORMAT, matrix->stride());
 460       st->print_cr(" - magic: " PTR_FORMAT, matrix->magic_offset());
 461     } else {
 462       st->print_cr(" No matrix.");
 463     }
 464   }
 465 
 466   if (Verbose) {
 467     print_heap_regions_on(st);
 468   }
 469 }
 470 
 471 class ShenandoahInitGCLABClosure : public ThreadClosure {
 472 public:
 473   void do_thread(Thread* thread) {
 474     thread->gclab().initialize(true);
 475   }
 476 };
 477 
 478 void ShenandoahHeap::post_initialize() {
 479   if (UseTLAB) {
 480     MutexLocker ml(Threads_lock);
 481 
 482     ShenandoahInitGCLABClosure init_gclabs;
 483     Threads::java_threads_do(&init_gclabs);
 484     gc_threads_do(&init_gclabs);
 485 
 486     // gclab can not be initialized early during VM startup, as it can not determinate its max_size.
 487     // Now, we will let WorkGang to initialize gclab when new worker is created.
 488     _workers->set_initialize_gclab();
 489   }
 490 
 491   _scm->initialize(_max_workers);
 492 
 493   ref_processing_init();
 494 
 495   _shenandoah_policy->post_heap_initialize();
 496 }
 497 
 498 size_t ShenandoahHeap::used() const {
 499   OrderAccess::acquire();
 500   return _used;
 501 }
 502 
 503 size_t ShenandoahHeap::committed() const {
 504   OrderAccess::acquire();
 505   return _committed;
 506 }
 507 
 508 void ShenandoahHeap::increase_committed(size_t bytes) {
 509   assert_heaplock_or_safepoint();
 510   _committed += bytes;
 511 }
 512 
 513 void ShenandoahHeap::decrease_committed(size_t bytes) {
 514   assert_heaplock_or_safepoint();
 515   _committed -= bytes;
 516 }
 517 
 518 void ShenandoahHeap::increase_used(size_t bytes) {
 519   assert_heaplock_or_safepoint();
 520   _used += bytes;
 521 }
 522 
 523 void ShenandoahHeap::set_used(size_t bytes) {
 524   assert_heaplock_or_safepoint();
 525   _used = bytes;
 526 }
 527 
 528 void ShenandoahHeap::decrease_used(size_t bytes) {
 529   assert_heaplock_or_safepoint();
 530   assert(_used >= bytes, "never decrease heap size by more than we've left");
 531   _used -= bytes;
 532 }
 533 
 534 size_t ShenandoahHeap::capacity() const {
 535   return num_regions() * ShenandoahHeapRegion::region_size_bytes();
 536 }
 537 
 538 bool ShenandoahHeap::is_maximal_no_gc() const {
 539   Unimplemented();
 540   return true;
 541 }
 542 
 543 size_t ShenandoahHeap::max_capacity() const {
 544   return _num_regions * ShenandoahHeapRegion::region_size_bytes();
 545 }
 546 
 547 size_t ShenandoahHeap::initial_capacity() const {
 548   return _initial_size;
 549 }
 550 
 551 bool ShenandoahHeap::is_in(const void* p) const {
 552   HeapWord* heap_base = (HeapWord*) base();
 553   HeapWord* last_region_end = heap_base + ShenandoahHeapRegion::region_size_words() * num_regions();
 554   return p >= heap_base && p < last_region_end;
 555 }
 556 
 557 bool ShenandoahHeap::is_scavengable(const void* p) {
 558   return true;
 559 }
 560 
 561 void ShenandoahHeap::handle_heap_shrinkage() {
 562   ShenandoahHeapLocker locker(lock());
 563 
 564   ShenandoahHeapRegionSet* set = regions();
 565 
 566   size_t count = 0;
 567   double current = os::elapsedTime();
 568   for (size_t i = 0; i < num_regions(); i++) {
 569     ShenandoahHeapRegion* r = set->get(i);
 570     if (r->is_empty_committed() &&
 571             (current - r->empty_time()) * 1000 > ShenandoahUncommitDelay &&
 572             r->make_empty_uncommitted()) {
 573       count++;
 574     }
 575   }
 576 
 577   if (count > 0) {
 578     log_info(gc)("Uncommitted " SIZE_FORMAT "M. Heap: " SIZE_FORMAT "M reserved, " SIZE_FORMAT "M committed, " SIZE_FORMAT "M used",
 579                  count * ShenandoahHeapRegion::region_size_bytes() / M, capacity() / M, committed() / M, used() / M);
 580   }
 581 }
 582 
 583 HeapWord* ShenandoahHeap::allocate_from_gclab_slow(Thread* thread, size_t size) {
 584   // Retain tlab and allocate object in shared space if
 585   // the amount free in the tlab is too large to discard.
 586   if (thread->gclab().free() > thread->gclab().refill_waste_limit()) {
 587     thread->gclab().record_slow_allocation(size);
 588     return NULL;
 589   }
 590 
 591   // Discard gclab and allocate a new one.
 592   // To minimize fragmentation, the last GCLAB may be smaller than the rest.
 593   size_t new_gclab_size = thread->gclab().compute_size(size);
 594 
 595   thread->gclab().clear_before_allocation();
 596 
 597   if (new_gclab_size == 0) {
 598     return NULL;
 599   }
 600 
 601   // Allocate a new GCLAB...
 602   HeapWord* obj = allocate_new_gclab(new_gclab_size);
 603   if (obj == NULL) {
 604     return NULL;
 605   }
 606 
 607   if (ZeroTLAB) {
 608     // ..and clear it.
 609     Copy::zero_to_words(obj, new_gclab_size);
 610   } else {
 611     // ...and zap just allocated object.
 612 #ifdef ASSERT
 613     // Skip mangling the space corresponding to the object header to
 614     // ensure that the returned space is not considered parsable by
 615     // any concurrent GC thread.
 616     size_t hdr_size = oopDesc::header_size();
 617     Copy::fill_to_words(obj + hdr_size, new_gclab_size - hdr_size, badHeapWordVal);
 618 #endif // ASSERT
 619   }
 620   thread->gclab().fill(obj, obj + size, new_gclab_size);
 621   return obj;
 622 }
 623 
 624 HeapWord* ShenandoahHeap::allocate_new_tlab(size_t word_size) {
 625 #ifdef ASSERT
 626   log_debug(gc, alloc)("Allocate new tlab, requested size = " SIZE_FORMAT " bytes", word_size * HeapWordSize);
 627 #endif
 628   return allocate_new_lab(word_size, _alloc_tlab);
 629 }
 630 
 631 HeapWord* ShenandoahHeap::allocate_new_gclab(size_t word_size) {
 632 #ifdef ASSERT
 633   log_debug(gc, alloc)("Allocate new gclab, requested size = " SIZE_FORMAT " bytes", word_size * HeapWordSize);
 634 #endif
 635   return allocate_new_lab(word_size, _alloc_gclab);
 636 }
 637 
 638 HeapWord* ShenandoahHeap::allocate_new_lab(size_t word_size, AllocType type) {
 639   HeapWord* result = allocate_memory(word_size, type);
 640 
 641   if (result != NULL) {
 642     assert(! in_collection_set(result), "Never allocate in collection set");
 643     _bytes_allocated_since_cm += word_size * HeapWordSize;
 644 
 645     log_develop_trace(gc, tlab)("allocating new tlab of size "SIZE_FORMAT" at addr "PTR_FORMAT, word_size, p2i(result));
 646 
 647   }
 648   return result;
 649 }
 650 
 651 ShenandoahHeap* ShenandoahHeap::heap() {
 652   CollectedHeap* heap = Universe::heap();
 653   assert(heap != NULL, "Unitialized access to ShenandoahHeap::heap()");
 654   assert(heap->kind() == CollectedHeap::ShenandoahHeap, "not a shenandoah heap");
 655   return (ShenandoahHeap*) heap;
 656 }
 657 
 658 ShenandoahHeap* ShenandoahHeap::heap_no_check() {
 659   CollectedHeap* heap = Universe::heap();
 660   return (ShenandoahHeap*) heap;
 661 }
 662 
 663 HeapWord* ShenandoahHeap::allocate_memory(size_t word_size, AllocType type) {
 664   ShenandoahAllocTrace trace_alloc(word_size, type);
 665 
 666   bool in_new_region = false;
 667   HeapWord* result = allocate_memory_under_lock(word_size, type, in_new_region);
 668 
 669   if (type == _alloc_tlab || type == _alloc_shared) {
 670     // Allocation failed, try full-GC, then retry allocation.
 671     //
 672     // It might happen that one of the threads requesting allocation would unblock
 673     // way later after full-GC happened, only to fail the second allocation, because
 674     // other threads have already depleted the free storage. In this case, a better
 675     // strategy would be to try full-GC again.
 676     //
 677     // Lacking the way to detect progress from "collect" call, we are left with blindly
 678     // retrying for some bounded number of times.
 679     // TODO: Poll if Full GC made enough progress to warrant retry.
 680     int tries = 0;
 681     while ((result == NULL) && (tries++ < ShenandoahFullGCTries)) {
 682       log_debug(gc)("[" PTR_FORMAT " Failed to allocate " SIZE_FORMAT " bytes, doing full GC, try %d",
 683                     p2i(Thread::current()), word_size * HeapWordSize, tries);
 684       collect(GCCause::_allocation_failure);
 685       result = allocate_memory_under_lock(word_size, type, in_new_region);
 686     }
 687   }
 688 
 689   if (in_new_region) {
 690     // Update monitoring counters when we took a new region. This amortizes the
 691     // update costs on slow path.
 692     concurrent_thread()->trigger_counters_update();
 693   }
 694 
 695   log_develop_trace(gc, alloc)("allocate memory chunk of size "SIZE_FORMAT" at addr "PTR_FORMAT " by thread %d ",
 696                                word_size, p2i(result), Thread::current()->osthread()->thread_id());
 697 
 698   return result;
 699 }
 700 
 701 HeapWord* ShenandoahHeap::allocate_memory_under_lock(size_t word_size, AllocType type, bool& in_new_region) {
 702   ShenandoahHeapLocker locker(lock());
 703   return _free_regions->allocate(word_size, type, in_new_region);
 704 }
 705 
 706 HeapWord*  ShenandoahHeap::mem_allocate(size_t size,
 707                                         bool*  gc_overhead_limit_was_exceeded) {
 708   HeapWord* filler = allocate_memory(size + BrooksPointer::word_size(), _alloc_shared);
 709   HeapWord* result = filler + BrooksPointer::word_size();
 710   if (filler != NULL) {
 711     BrooksPointer::initialize(oop(result));
 712     _bytes_allocated_since_cm += size * HeapWordSize;
 713 
 714     assert(! in_collection_set(result), "never allocate in targetted region");
 715     return result;
 716   } else {
 717     return NULL;
 718   }
 719 }
 720 
 721 class ShenandoahEvacuateUpdateRootsClosure: public ExtendedOopClosure {
 722 private:
 723   ShenandoahHeap* _heap;
 724   Thread* _thread;
 725 public:
 726   ShenandoahEvacuateUpdateRootsClosure() :
 727           _heap(ShenandoahHeap::heap()), _thread(Thread::current()) {
 728   }
 729 
 730 private:
 731   template <class T>
 732   void do_oop_work(T* p) {
 733     assert(_heap->is_evacuation_in_progress(), "Only do this when evacuation is in progress");
 734 
 735     T o = oopDesc::load_heap_oop(p);
 736     if (! oopDesc::is_null(o)) {
 737       oop obj = oopDesc::decode_heap_oop_not_null(o);
 738       if (_heap->in_collection_set(obj)) {
 739         assert(_heap->is_marked(obj), "only evacuate marked objects %d %d",
 740                _heap->is_marked(obj), _heap->is_marked(ShenandoahBarrierSet::resolve_oop_static_not_null(obj)));
 741         oop resolved = ShenandoahBarrierSet::resolve_oop_static_not_null(obj);
 742         if (oopDesc::unsafe_equals(resolved, obj)) {
 743           bool evac;
 744           resolved = _heap->evacuate_object(obj, _thread, evac);
 745         }
 746         oopDesc::encode_store_heap_oop(p, resolved);
 747       }
 748     }
 749   }
 750 
 751 public:
 752   void do_oop(oop* p) {
 753     do_oop_work(p);
 754   }
 755   void do_oop(narrowOop* p) {
 756     do_oop_work(p);
 757   }
 758 };
 759 
 760 class ShenandoahEvacuateRootsClosure: public ExtendedOopClosure {
 761 private:
 762   ShenandoahHeap* _heap;
 763   Thread* _thread;
 764 public:
 765   ShenandoahEvacuateRootsClosure() :
 766           _heap(ShenandoahHeap::heap()), _thread(Thread::current()) {
 767   }
 768 
 769 private:
 770   template <class T>
 771   void do_oop_work(T* p) {
 772     T o = oopDesc::load_heap_oop(p);
 773     if (! oopDesc::is_null(o)) {
 774       oop obj = oopDesc::decode_heap_oop_not_null(o);
 775       if (_heap->in_collection_set(obj)) {
 776         oop resolved = ShenandoahBarrierSet::resolve_oop_static_not_null(obj);
 777         if (oopDesc::unsafe_equals(resolved, obj)) {
 778           bool evac;
 779           _heap->evacuate_object(obj, _thread, evac);
 780         }
 781       }
 782     }
 783   }
 784 
 785 public:
 786   void do_oop(oop* p) {
 787     do_oop_work(p);
 788   }
 789   void do_oop(narrowOop* p) {
 790     do_oop_work(p);
 791   }
 792 };
 793 
 794 class ShenandoahParallelEvacuateRegionObjectClosure : public ObjectClosure {
 795 private:
 796   ShenandoahHeap* const _heap;
 797   Thread* const _thread;
 798 public:
 799   ShenandoahParallelEvacuateRegionObjectClosure(ShenandoahHeap* heap) :
 800     _heap(heap), _thread(Thread::current()) {}
 801 
 802   void do_object(oop p) {
 803     assert(_heap->is_marked(p), "expect only marked objects");
 804     if (oopDesc::unsafe_equals(p, ShenandoahBarrierSet::resolve_oop_static_not_null(p))) {
 805       bool evac;
 806       _heap->evacuate_object(p, _thread, evac);
 807     }
 808   }
 809 };
 810 
 811 class ShenandoahParallelEvacuationTask : public AbstractGangTask {
 812 private:
 813   ShenandoahHeap* const _sh;
 814   ShenandoahCollectionSet* const _cs;
 815   volatile jbyte _claimed_codecache;
 816 
 817   bool claim_codecache() {
 818     jbyte old = Atomic::cmpxchg((jbyte)1, &_claimed_codecache, (jbyte)0);
 819     return old == 0;
 820   }
 821 public:
 822   ShenandoahParallelEvacuationTask(ShenandoahHeap* sh,
 823                          ShenandoahCollectionSet* cs) :
 824     AbstractGangTask("Parallel Evacuation Task"),
 825     _cs(cs),
 826     _sh(sh),
 827     _claimed_codecache(0)
 828   {}
 829 
 830   void work(uint worker_id) {
 831 
 832     SuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers);
 833 
 834     // If concurrent code cache evac is enabled, evacuate it here.
 835     // Note we cannot update the roots here, because we risk non-atomic stores to the alive
 836     // nmethods. The update would be handled elsewhere.
 837     if (ShenandoahConcurrentEvacCodeRoots && claim_codecache()) {
 838       ShenandoahEvacuateRootsClosure cl;
 839       MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
 840       CodeBlobToOopClosure blobs(&cl, !CodeBlobToOopClosure::FixRelocations);
 841       CodeCache::blobs_do(&blobs);
 842     }
 843 
 844     ShenandoahParallelEvacuateRegionObjectClosure cl(_sh);
 845     ShenandoahHeapRegion* r;
 846     while ((r =_cs->claim_next()) != NULL) {
 847       log_develop_trace(gc, region)("Thread "INT32_FORMAT" claimed Heap Region "SIZE_FORMAT,
 848                                     worker_id,
 849                                     r->region_number());
 850 
 851       assert(r->has_live(), "all-garbage regions are reclaimed early");
 852       _sh->marked_object_iterate(r, &cl);
 853 
 854       if (_sh->check_cancelled_concgc_and_yield()) {
 855         log_develop_trace(gc, region)("Cancelled concgc while evacuating region " SIZE_FORMAT, r->region_number());
 856         break;
 857       }
 858     }
 859   }
 860 };
 861 
 862 void ShenandoahHeap::trash_cset_regions() {
 863   ShenandoahHeapLocker locker(lock());
 864 
 865   ShenandoahCollectionSet* set = collection_set();
 866   ShenandoahHeapRegion* r;
 867   set->clear_current_index();
 868   while ((r = set->next()) != NULL) {
 869     r->make_trash();
 870   }
 871   collection_set()->clear();
 872 }
 873 
 874 void ShenandoahHeap::print_heap_regions_on(outputStream* st) const {
 875   st->print_cr("Heap Regions:");
 876   st->print_cr("EU=empty-uncommitted, EC=empty-committed, R=regular, H=humongous start, HC=humongous continuation, CS=collection set, T=trash, P=pinned");
 877   st->print_cr("BTE=bottom/top/end, U=used, T=TLAB allocs, G=GCLAB allocs, S=shared allocs, L=live data");
 878   st->print_cr("R=root, CP=critical pins, TAMS=top-at-mark-start (previous, next)");
 879   st->print_cr("FTS=first use timestamp, LTS=last use timestamp");
 880 
 881   _ordered_regions->print_on(st);
 882 }
 883 
 884 size_t ShenandoahHeap::trash_humongous_region_at(ShenandoahHeapRegion* start) {
 885   assert(start->is_humongous_start(), "reclaim regions starting with the first one");
 886 
 887   oop humongous_obj = oop(start->bottom() + BrooksPointer::word_size());
 888   size_t size = humongous_obj->size() + BrooksPointer::word_size();
 889   size_t required_regions = ShenandoahHeapRegion::required_regions(size * HeapWordSize);
 890   size_t index = start->region_number() + required_regions - 1;
 891 
 892   assert(!start->has_live(), "liveness must be zero");
 893   log_trace(gc, humongous)("Reclaiming "SIZE_FORMAT" humongous regions for object of size: "SIZE_FORMAT" words", required_regions, size);
 894 
 895   for(size_t i = 0; i < required_regions; i++) {
 896     // Reclaim from tail. Otherwise, assertion fails when printing region to trace log,
 897     // as it expects that every region belongs to a humongous region starting with a humongous start region.
 898     ShenandoahHeapRegion* region = _ordered_regions->get(index --);
 899 
 900     LogTarget(Trace, gc, humongous) lt;
 901     if (lt.is_enabled()) {
 902       ResourceMark rm;
 903       LogStream ls(lt);
 904       region->print_on(&ls);
 905     }
 906 
 907     assert(region->is_humongous(), "expect correct humongous start or continuation");
 908     assert(!in_collection_set(region), "Humongous region should not be in collection set");
 909 
 910     region->make_trash();
 911   }
 912   return required_regions;
 913 }
 914 
 915 #ifdef ASSERT
 916 class ShenandoahCheckCollectionSetClosure: public ShenandoahHeapRegionClosure {
 917   bool heap_region_do(ShenandoahHeapRegion* r) {
 918     assert(! ShenandoahHeap::heap()->in_collection_set(r), "Should have been cleared by now");
 919     return false;
 920   }
 921 };
 922 #endif
 923 
 924 void ShenandoahHeap::prepare_for_concurrent_evacuation() {
 925   assert(_ordered_regions->get(0)->region_number() == 0, "FIXME CHF. FIXME CHF!");
 926 
 927   log_develop_trace(gc)("Thread %d started prepare_for_concurrent_evacuation", Thread::current()->osthread()->thread_id());
 928 
 929   if (!cancelled_concgc()) {
 930     // Allocations might have happened before we STWed here, record peak:
 931     shenandoahPolicy()->record_peak_occupancy();
 932 
 933     make_tlabs_parsable(true);
 934 
 935     if (ShenandoahVerify) {
 936       verifier()->verify_after_concmark();
 937     }
 938 
 939     trash_cset_regions();
 940 
 941     // NOTE: This needs to be done during a stop the world pause, because
 942     // putting regions into the collection set concurrently with Java threads
 943     // will create a race. In particular, acmp could fail because when we
 944     // resolve the first operand, the containing region might not yet be in
 945     // the collection set, and thus return the original oop. When the 2nd
 946     // operand gets resolved, the region could be in the collection set
 947     // and the oop gets evacuated. If both operands have originally been
 948     // the same, we get false negatives.
 949 
 950     {
 951       ShenandoahHeapLocker locker(lock());
 952       _collection_set->clear();
 953       _free_regions->clear();
 954 
 955 #ifdef ASSERT
 956       ShenandoahCheckCollectionSetClosure ccsc;
 957       _ordered_regions->heap_region_iterate(&ccsc);
 958 #endif
 959 
 960       _shenandoah_policy->choose_collection_set(_collection_set);
 961 
 962       _shenandoah_policy->choose_free_set(_free_regions);
 963     }
 964 
 965     _bytes_allocated_since_cm = 0;
 966 
 967     Universe::update_heap_info_at_gc();
 968 
 969     if (ShenandoahVerify) {
 970       verifier()->verify_before_evacuation();
 971     }
 972   }
 973 }
 974 
 975 
 976 class ShenandoahRetireTLABClosure : public ThreadClosure {
 977 private:
 978   bool _retire;
 979 
 980 public:
 981   ShenandoahRetireTLABClosure(bool retire) : _retire(retire) {}
 982 
 983   void do_thread(Thread* thread) {
 984     assert(thread->gclab().is_initialized(), "GCLAB should be initialized for %s", thread->name());
 985     thread->gclab().make_parsable(_retire);
 986   }
 987 };
 988 
 989 void ShenandoahHeap::make_tlabs_parsable(bool retire_tlabs) {
 990   if (UseTLAB) {
 991     CollectedHeap::ensure_parsability(retire_tlabs);
 992     ShenandoahRetireTLABClosure cl(retire_tlabs);
 993     Threads::java_threads_do(&cl);
 994     gc_threads_do(&cl);
 995   }
 996 }
 997 
 998 
 999 class ShenandoahEvacuateUpdateRootsTask : public AbstractGangTask {
1000   ShenandoahRootEvacuator* _rp;
1001 public:
1002 
1003   ShenandoahEvacuateUpdateRootsTask(ShenandoahRootEvacuator* rp) :
1004     AbstractGangTask("Shenandoah evacuate and update roots"),
1005     _rp(rp)
1006   {
1007     // Nothing else to do.
1008   }
1009 
1010   void work(uint worker_id) {
1011     ShenandoahEvacuateUpdateRootsClosure cl;
1012 
1013     if (ShenandoahConcurrentEvacCodeRoots) {
1014       _rp->process_evacuate_roots(&cl, NULL, worker_id);
1015     } else {
1016       MarkingCodeBlobClosure blobsCl(&cl, CodeBlobToOopClosure::FixRelocations);
1017       _rp->process_evacuate_roots(&cl, &blobsCl, worker_id);
1018     }
1019   }
1020 };
1021 
1022 class ShenandoahFixRootsTask : public AbstractGangTask {
1023   ShenandoahRootEvacuator* _rp;
1024 public:
1025 
1026   ShenandoahFixRootsTask(ShenandoahRootEvacuator* rp) :
1027     AbstractGangTask("Shenandoah update roots"),
1028     _rp(rp)
1029   {
1030     // Nothing else to do.
1031   }
1032 
1033   void work(uint worker_id) {
1034     ShenandoahUpdateRefsClosure cl;
1035     MarkingCodeBlobClosure blobsCl(&cl, CodeBlobToOopClosure::FixRelocations);
1036 
1037     _rp->process_evacuate_roots(&cl, &blobsCl, worker_id);
1038   }
1039 };
1040 
1041 void ShenandoahHeap::evacuate_and_update_roots() {
1042 
1043 #if defined(COMPILER2) || INCLUDE_JVMCI
1044   DerivedPointerTable::clear();
1045 #endif
1046   assert(SafepointSynchronize::is_at_safepoint(), "Only iterate roots while world is stopped");
1047 
1048   {
1049     ShenandoahRootEvacuator rp(this, workers()->active_workers(), ShenandoahPhaseTimings::init_evac);
1050     ShenandoahEvacuateUpdateRootsTask roots_task(&rp);
1051     workers()->run_task(&roots_task);
1052   }
1053 
1054 #if defined(COMPILER2) || INCLUDE_JVMCI
1055   DerivedPointerTable::update_pointers();
1056 #endif
1057   if (cancelled_concgc()) {
1058     fixup_roots();
1059   }
1060 }
1061 
1062 
1063 void ShenandoahHeap::fixup_roots() {
1064     assert(cancelled_concgc(), "Only after concurrent cycle failed");
1065 
1066     // If initial evacuation has been cancelled, we need to update all references
1067     // after all workers have finished. Otherwise we might run into the following problem:
1068     // GC thread 1 cannot allocate anymore, thus evacuation fails, leaves from-space ptr of object X.
1069     // GC thread 2 evacuates the same object X to to-space
1070     // which leaves a truly dangling from-space reference in the first root oop*. This must not happen.
1071     // clear() and update_pointers() must always be called in pairs,
1072     // cannot nest with above clear()/update_pointers().
1073 #if defined(COMPILER2) || INCLUDE_JVMCI
1074     DerivedPointerTable::clear();
1075 #endif
1076     ShenandoahRootEvacuator rp(this, workers()->active_workers(), ShenandoahPhaseTimings::init_evac);
1077     ShenandoahFixRootsTask update_roots_task(&rp);
1078     workers()->run_task(&update_roots_task);
1079 #if defined(COMPILER2) || INCLUDE_JVMCI
1080     DerivedPointerTable::update_pointers();
1081 #endif
1082 }
1083 
1084 void ShenandoahHeap::do_evacuation() {
1085   ShenandoahGCPhase conc_evac_phase(ShenandoahPhaseTimings::conc_evac);
1086 
1087   LogTarget(Trace, gc, region) lt_region;
1088   LogTarget(Trace, gc, cset) lt_cset;
1089 
1090   if (lt_region.is_enabled()) {
1091     ResourceMark rm;
1092     LogStream ls(lt_region);
1093     ls.print_cr("All available regions:");
1094     print_heap_regions_on(&ls);
1095   }
1096 
1097   if (lt_cset.is_enabled()) {
1098     ResourceMark rm;
1099     LogStream ls(lt_cset);
1100     ls.print_cr("Collection set ("SIZE_FORMAT" regions):", _collection_set->count());
1101     _collection_set->print_on(&ls);
1102 
1103     ls.print_cr("Free set:");
1104     _free_regions->print_on(&ls);
1105   }
1106 
1107   ShenandoahParallelEvacuationTask task(this, _collection_set);
1108   workers()->run_task(&task);
1109 
1110   if (lt_cset.is_enabled()) {
1111     ResourceMark rm;
1112     LogStream ls(lt_cset);
1113     ls.print_cr("After evacuation collection set ("SIZE_FORMAT" regions):",
1114                _collection_set->count());
1115     _collection_set->print_on(&ls);
1116 
1117     ls.print_cr("After evacuation free set:");
1118     _free_regions->print_on(&ls);
1119   }
1120 
1121   if (lt_region.is_enabled()) {
1122     ResourceMark rm;
1123     LogStream ls(lt_region);
1124     ls.print_cr("All regions after evacuation:");
1125     print_heap_regions_on(&ls);
1126   }
1127 }
1128 
1129 void ShenandoahHeap::roots_iterate(OopClosure* cl) {
1130   assert(SafepointSynchronize::is_at_safepoint(), "Only iterate roots while world is stopped");
1131 
1132   CodeBlobToOopClosure blobsCl(cl, false);
1133   CLDToOopClosure cldCl(cl);
1134 
1135   ShenandoahRootProcessor rp(this, 1, ShenandoahPhaseTimings::_num_phases);
1136   rp.process_all_roots(cl, NULL, &cldCl, &blobsCl, 0);
1137 }
1138 
1139 bool ShenandoahHeap::supports_tlab_allocation() const {
1140   return true;
1141 }
1142 
1143 size_t  ShenandoahHeap::unsafe_max_tlab_alloc(Thread *thread) const {
1144   return MIN2(_free_regions->unsafe_peek_free(), max_tlab_size());
1145 }
1146 
1147 size_t ShenandoahHeap::max_tlab_size() const {
1148   return ShenandoahHeapRegion::max_tlab_size_bytes();
1149 }
1150 
1151 class ShenandoahResizeGCLABClosure : public ThreadClosure {
1152 public:
1153   void do_thread(Thread* thread) {
1154     assert(thread->gclab().is_initialized(), "GCLAB should be initialized for %s", thread->name());
1155     thread->gclab().resize();
1156   }
1157 };
1158 
1159 void ShenandoahHeap::resize_all_tlabs() {
1160   CollectedHeap::resize_all_tlabs();
1161 
1162   ShenandoahResizeGCLABClosure cl;
1163   Threads::java_threads_do(&cl);
1164   gc_threads_do(&cl);
1165 }
1166 
1167 class ShenandoahAccumulateStatisticsGCLABClosure : public ThreadClosure {
1168 public:
1169   void do_thread(Thread* thread) {
1170     assert(thread->gclab().is_initialized(), "GCLAB should be initialized for %s", thread->name());
1171     thread->gclab().accumulate_statistics();
1172     thread->gclab().initialize_statistics();
1173   }
1174 };
1175 
1176 void ShenandoahHeap::accumulate_statistics_all_gclabs() {
1177   ShenandoahAccumulateStatisticsGCLABClosure cl;
1178   Threads::java_threads_do(&cl);
1179   gc_threads_do(&cl);
1180 }
1181 
1182 bool  ShenandoahHeap::can_elide_tlab_store_barriers() const {
1183   return true;
1184 }
1185 
1186 oop ShenandoahHeap::new_store_pre_barrier(JavaThread* thread, oop new_obj) {
1187   // Overridden to do nothing.
1188   return new_obj;
1189 }
1190 
1191 bool  ShenandoahHeap::can_elide_initializing_store_barrier(oop new_obj) {
1192   return true;
1193 }
1194 
1195 bool ShenandoahHeap::card_mark_must_follow_store() const {
1196   return false;
1197 }
1198 
1199 void ShenandoahHeap::collect(GCCause::Cause cause) {
1200   assert(cause != GCCause::_gc_locker, "no JNI critical callback");
1201   if (GCCause::is_user_requested_gc(cause)) {
1202     if (!DisableExplicitGC) {
1203       if (ExplicitGCInvokesConcurrent) {
1204         _concurrent_gc_thread->do_conc_gc();
1205       } else {
1206         _concurrent_gc_thread->do_full_gc(cause);
1207       }
1208     }
1209   } else if (cause == GCCause::_allocation_failure) {
1210     collector_policy()->set_should_clear_all_soft_refs(true);
1211     _concurrent_gc_thread->do_full_gc(cause);
1212   }
1213 }
1214 
1215 void ShenandoahHeap::do_full_collection(bool clear_all_soft_refs) {
1216   //assert(false, "Shouldn't need to do full collections");
1217 }
1218 
1219 AdaptiveSizePolicy* ShenandoahHeap::size_policy() {
1220   Unimplemented();
1221   return NULL;
1222 
1223 }
1224 
1225 CollectorPolicy* ShenandoahHeap::collector_policy() const {
1226   return _shenandoah_policy;
1227 }
1228 
1229 
1230 HeapWord* ShenandoahHeap::block_start(const void* addr) const {
1231   Space* sp = heap_region_containing(addr);
1232   if (sp != NULL) {
1233     return sp->block_start(addr);
1234   }
1235   return NULL;
1236 }
1237 
1238 size_t ShenandoahHeap::block_size(const HeapWord* addr) const {
1239   Space* sp = heap_region_containing(addr);
1240   assert(sp != NULL, "block_size of address outside of heap");
1241   return sp->block_size(addr);
1242 }
1243 
1244 bool ShenandoahHeap::block_is_obj(const HeapWord* addr) const {
1245   Space* sp = heap_region_containing(addr);
1246   return sp->block_is_obj(addr);
1247 }
1248 
1249 jlong ShenandoahHeap::millis_since_last_gc() {
1250   return 0;
1251 }
1252 
1253 void ShenandoahHeap::prepare_for_verify() {
1254   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
1255     make_tlabs_parsable(false);
1256   }
1257 }
1258 
1259 void ShenandoahHeap::print_gc_threads_on(outputStream* st) const {
1260   workers()->print_worker_threads_on(st);
1261 }
1262 
1263 void ShenandoahHeap::gc_threads_do(ThreadClosure* tcl) const {
1264   workers()->threads_do(tcl);
1265 }
1266 
1267 void ShenandoahHeap::print_tracing_info() const {
1268   LogTarget(Info, gc, stats) lt;
1269   if (lt.is_enabled()) {
1270     ResourceMark rm;
1271     LogStream ls(lt);
1272 
1273     phase_timings()->print_on(&ls);
1274 
1275     ls.cr();
1276     ls.cr();
1277 
1278     shenandoahPolicy()->print_gc_stats(&ls);
1279 
1280     ls.cr();
1281     ls.cr();
1282 
1283     if (ShenandoahAllocationTrace) {
1284       assert(alloc_tracker() != NULL, "Must be");
1285       alloc_tracker()->print_on(&ls);
1286     } else {
1287       ls.print_cr("  Allocation tracing is disabled, use -XX:+ShenandoahAllocationTrace to enable.");
1288     }
1289   }
1290 }
1291 
1292 void ShenandoahHeap::verify(VerifyOption vo) {
1293   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
1294     if (ShenandoahVerify) {
1295       verifier()->verify_generic(vo);
1296     } else {
1297       // TODO: Consider allocating verification bitmaps on demand,
1298       // and turn this on unconditionally.
1299     }
1300   }
1301 }
1302 size_t ShenandoahHeap::tlab_capacity(Thread *thr) const {
1303   return _free_regions->capacity();
1304 }
1305 
1306 class ShenandoahIterateObjectClosureRegionClosure: public ShenandoahHeapRegionClosure {
1307   ObjectClosure* _cl;
1308 public:
1309   ShenandoahIterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
1310   bool heap_region_do(ShenandoahHeapRegion* r) {
1311     ShenandoahHeap::heap()->marked_object_iterate(r, _cl);
1312     return false;
1313   }
1314 };
1315 
1316 class ObjectIterateScanRootClosure : public ExtendedOopClosure {
1317 private:
1318   MarkBitMap* _bitmap;
1319   Stack<oop,mtGC>* _oop_stack;
1320 
1321   template <class T>
1322   void do_oop_work(T* p) {
1323     T o = oopDesc::load_heap_oop(p);
1324     if (!oopDesc::is_null(o)) {
1325       oop obj = oopDesc::decode_heap_oop_not_null(o);
1326       obj = ShenandoahBarrierSet::resolve_oop_static_not_null(obj);
1327       assert(oopDesc::is_oop(obj), "must be a valid oop");
1328       if (!_bitmap->isMarked((HeapWord*) obj)) {
1329         _bitmap->mark((HeapWord*) obj);
1330         _oop_stack->push(obj);
1331       }
1332     }
1333   }
1334 
1335 public:
1336   ObjectIterateScanRootClosure(MarkBitMap* bitmap, Stack<oop,mtGC>* oop_stack) :
1337     _bitmap(bitmap), _oop_stack(oop_stack) {}
1338   void do_oop(oop* p)       { do_oop_work(p); }
1339   void do_oop(narrowOop* p) { do_oop_work(p); }
1340 };
1341 
1342 /*
1343  * This is public API, used in preparation of object_iterate().
1344  * Since we don't do linear scan of heap in object_iterate() (see comment below), we don't
1345  * need to make the heap parsable. For Shenandoah-internal linear heap scans that we can
1346  * control, we call SH::make_tlabs_parsable().
1347  */
1348 void ShenandoahHeap::ensure_parsability(bool retire_tlabs) {
1349   // No-op.
1350 }
1351 
1352 
1353 /*
1354  * Iterates objects in the heap. This is public API, used for, e.g., heap dumping.
1355  *
1356  * We cannot safely iterate objects by doing a linear scan at random points in time. Linear
1357  * scanning needs to deal with dead objects, which may have dead Klass* pointers (e.g.
1358  * calling oopDesc::size() would crash) or dangling reference fields (crashes) etc. Linear
1359  * scanning therefore depends on having a valid marking bitmap to support it. However, we only
1360  * have a valid marking bitmap after successful marking. In particular, we *don't* have a valid
1361  * marking bitmap during marking, after aborted marking or during/after cleanup (when we just
1362  * wiped the bitmap in preparation for next marking).
1363  *
1364  * For all those reasons, we implement object iteration as a single marking traversal, reporting
1365  * objects as we mark+traverse through the heap, starting from GC roots. This is ok. JVMTI
1366  * IterateThroughHeap is allowed to report dead objects, but is not required to do so.
1367  */
1368 void ShenandoahHeap::object_iterate(ObjectClosure* cl) {
1369   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1370   if (!os::commit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size(), false)) {
1371     log_warning(gc)("Could not commit native memory for auxiliary marking bitmap for heap iteration");
1372     return;
1373   }
1374 
1375   Stack<oop,mtGC> oop_stack;
1376 
1377   // First, we process all GC roots. This populates the work stack with initial objects.
1378   ShenandoahRootProcessor rp(this, 1, ShenandoahPhaseTimings::_num_phases);
1379   ObjectIterateScanRootClosure oops(&_aux_bit_map, &oop_stack);
1380   CLDToOopClosure clds(&oops, false);
1381   CodeBlobToOopClosure blobs(&oops, false);
1382   rp.process_all_roots(&oops, &oops, &clds, &blobs, 0);
1383 
1384   // Work through the oop stack to traverse heap.
1385   while (! oop_stack.is_empty()) {
1386     oop obj = oop_stack.pop();
1387     assert(oopDesc::is_oop(obj), "must be a valid oop");
1388     cl->do_object(obj);
1389     obj->oop_iterate(&oops);
1390   }
1391 
1392   assert(oop_stack.is_empty(), "should be empty");
1393 
1394   if (!os::uncommit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size())) {
1395     log_warning(gc)("Could not uncommit native memory for auxiliary marking bitmap for heap iteration");
1396   }
1397 }
1398 
1399 void ShenandoahHeap::safe_object_iterate(ObjectClosure* cl) {
1400   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1401   object_iterate(cl);
1402 }
1403 
1404 // Apply blk->heap_region_do() on all committed regions in address order,
1405 // terminating the iteration early if heap_region_do() returns true.
1406 void ShenandoahHeap::heap_region_iterate(ShenandoahHeapRegionClosure* blk, bool skip_cset_regions, bool skip_humongous_continuation) const {
1407   for (size_t i = 0; i < num_regions(); i++) {
1408     ShenandoahHeapRegion* current  = _ordered_regions->get(i);
1409     if (skip_humongous_continuation && current->is_humongous_continuation()) {
1410       continue;
1411     }
1412     if (skip_cset_regions && in_collection_set(current)) {
1413       continue;
1414     }
1415     if (blk->heap_region_do(current)) {
1416       return;
1417     }
1418   }
1419 }
1420 
1421 class ShenandoahClearLivenessClosure : public ShenandoahHeapRegionClosure {
1422 private:
1423   ShenandoahHeap* sh;
1424 public:
1425   ShenandoahClearLivenessClosure(ShenandoahHeap* heap) : sh(heap) {}
1426 
1427   bool heap_region_do(ShenandoahHeapRegion* r) {
1428     r->clear_live_data();
1429     sh->set_top_at_mark_start(r->bottom(), r->top());
1430     return false;
1431   }
1432 };
1433 
1434 void ShenandoahHeap::start_concurrent_marking() {
1435   if (ShenandoahVerify) {
1436     verifier()->verify_before_concmark();
1437   }
1438 
1439   {
1440     ShenandoahGCPhase phase(ShenandoahPhaseTimings::accumulate_stats);
1441     accumulate_statistics_all_tlabs();
1442   }
1443 
1444   set_concurrent_mark_in_progress(true);
1445   // We need to reset all TLABs because we'd lose marks on all objects allocated in them.
1446   if (UseTLAB) {
1447     ShenandoahGCPhase phase(ShenandoahPhaseTimings::make_parsable);
1448     make_tlabs_parsable(true);
1449   }
1450 
1451   _shenandoah_policy->record_bytes_allocated(_bytes_allocated_since_cm);
1452   _used_start_gc = used();
1453 
1454   {
1455     ShenandoahGCPhase phase(ShenandoahPhaseTimings::clear_liveness);
1456     ShenandoahClearLivenessClosure clc(this);
1457     heap_region_iterate(&clc);
1458   }
1459 
1460   // Make above changes visible to worker threads
1461   OrderAccess::fence();
1462 
1463   concurrentMark()->init_mark_roots();
1464 
1465   if (UseTLAB) {
1466     ShenandoahGCPhase phase(ShenandoahPhaseTimings::resize_tlabs);
1467     resize_all_tlabs();
1468   }
1469 }
1470 
1471 void ShenandoahHeap::stop_concurrent_marking() {
1472   assert(concurrent_mark_in_progress(), "How else could we get here?");
1473   if (! cancelled_concgc()) {
1474     // If we needed to update refs, and concurrent marking has been cancelled,
1475     // we need to finish updating references.
1476     set_need_update_refs(false);
1477   }
1478   set_concurrent_mark_in_progress(false);
1479 
1480   LogTarget(Trace, gc, region) lt;
1481   if (lt.is_enabled()) {
1482     ResourceMark rm;
1483     LogStream ls(lt);
1484     ls.print_cr("Regions at stopping the concurrent mark:");
1485     print_heap_regions_on(&ls);
1486   }
1487 }
1488 
1489 void ShenandoahHeap::set_concurrent_mark_in_progress(bool in_progress) {
1490   _concurrent_mark_in_progress = in_progress ? 1 : 0;
1491   JavaThread::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
1492 }
1493 
1494 void ShenandoahHeap::set_concurrent_partial_in_progress(bool in_progress) {
1495   _concurrent_partial_in_progress = in_progress;
1496   JavaThread::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
1497   set_evacuation_in_progress_at_safepoint(in_progress);
1498 }
1499 
1500 void ShenandoahHeap::set_evacuation_in_progress_concurrently(bool in_progress) {
1501   // Note: it is important to first release the _evacuation_in_progress flag here,
1502   // so that Java threads can get out of oom_during_evacuation() and reach a safepoint,
1503   // in case a VM task is pending.
1504   set_evacuation_in_progress(in_progress);
1505   MutexLocker mu(Threads_lock);
1506   JavaThread::set_evacuation_in_progress_all_threads(in_progress);
1507 }
1508 
1509 void ShenandoahHeap::set_evacuation_in_progress_at_safepoint(bool in_progress) {
1510   assert(SafepointSynchronize::is_at_safepoint(), "Only call this at safepoint");
1511   set_evacuation_in_progress(in_progress);
1512   JavaThread::set_evacuation_in_progress_all_threads(in_progress);
1513 }
1514 
1515 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {
1516   _evacuation_in_progress = in_progress ? 1 : 0;
1517   OrderAccess::fence();
1518 }
1519 
1520 void ShenandoahHeap::oom_during_evacuation() {
1521   log_develop_trace(gc)("Out of memory during evacuation, cancel evacuation, schedule full GC by thread %d",
1522                         Thread::current()->osthread()->thread_id());
1523 
1524   // We ran out of memory during evacuation. Cancel evacuation, and schedule a full-GC.
1525   collector_policy()->set_should_clear_all_soft_refs(true);
1526   concurrent_thread()->try_set_full_gc();
1527   cancel_concgc(_oom_evacuation);
1528 
1529   if ((! Thread::current()->is_GC_task_thread()) && (! Thread::current()->is_ConcurrentGC_thread())) {
1530     assert(! Threads_lock->owned_by_self()
1531            || SafepointSynchronize::is_at_safepoint(), "must not hold Threads_lock here");
1532     log_warning(gc)("OOM during evacuation. Let Java thread wait until evacuation finishes.");
1533     while (_evacuation_in_progress) { // wait.
1534       Thread::current()->_ParkEvent->park(1);
1535     }
1536   }
1537 
1538 }
1539 
1540 HeapWord* ShenandoahHeap::tlab_post_allocation_setup(HeapWord* obj) {
1541   // Initialize Brooks pointer for the next object
1542   HeapWord* result = obj + BrooksPointer::word_size();
1543   BrooksPointer::initialize(oop(result));
1544   return result;
1545 }
1546 
1547 uint ShenandoahHeap::oop_extra_words() {
1548   return BrooksPointer::word_size();
1549 }
1550 
1551 ShenandoahForwardedIsAliveClosure::ShenandoahForwardedIsAliveClosure() :
1552   _heap(ShenandoahHeap::heap_no_check()) {
1553 }
1554 
1555 bool ShenandoahForwardedIsAliveClosure::do_object_b(oop obj) {
1556   assert(_heap != NULL, "sanity");
1557   obj = ShenandoahBarrierSet::resolve_oop_static_not_null(obj);
1558 #ifdef ASSERT
1559   if (_heap->concurrent_mark_in_progress()) {
1560     assert(oopDesc::unsafe_equals(obj, ShenandoahBarrierSet::resolve_oop_static_not_null(obj)), "only query to-space");
1561   }
1562 #endif
1563   assert(!oopDesc::is_null(obj), "null");
1564   return _heap->is_marked(obj);
1565 }
1566 
1567 ShenandoahIsAliveClosure::ShenandoahIsAliveClosure() :
1568   _heap(ShenandoahHeap::heap_no_check()) {
1569 }
1570 
1571 bool ShenandoahIsAliveClosure::do_object_b(oop obj) {
1572   assert(_heap != NULL, "sanity");
1573   assert(!oopDesc::is_null(obj), "null");
1574   assert(oopDesc::unsafe_equals(obj, ShenandoahBarrierSet::resolve_oop_static_not_null(obj)), "only query to-space");
1575   return _heap->is_marked(obj);
1576 }
1577 
1578 BoolObjectClosure* ShenandoahHeap::is_alive_closure() {
1579   return need_update_refs() ?
1580          (BoolObjectClosure*) &_forwarded_is_alive :
1581          (BoolObjectClosure*) &_is_alive;
1582 }
1583 
1584 void ShenandoahHeap::ref_processing_init() {
1585   MemRegion mr = reserved_region();
1586 
1587   _forwarded_is_alive.init(ShenandoahHeap::heap());
1588   _is_alive.init(ShenandoahHeap::heap());
1589   assert(_max_workers > 0, "Sanity");
1590 
1591   _ref_processor =
1592     new ReferenceProcessor(mr,    // span
1593                            ParallelRefProcEnabled,  // MT processing
1594                            _max_workers,            // Degree of MT processing
1595                            true,                    // MT discovery
1596                            _max_workers,            // Degree of MT discovery
1597                            false,                   // Reference discovery is not atomic
1598                            &_forwarded_is_alive);   // Pessimistically assume "forwarded"
1599 }
1600 
1601 
1602 GCTracer* ShenandoahHeap::tracer() {
1603   return shenandoahPolicy()->tracer();
1604 }
1605 
1606 size_t ShenandoahHeap::tlab_used(Thread* thread) const {
1607   return _free_regions->used();
1608 }
1609 
1610 void ShenandoahHeap::cancel_concgc(GCCause::Cause cause) {
1611   if (try_cancel_concgc()) {
1612     log_info(gc)("Cancelling concurrent GC: %s", GCCause::to_string(cause));
1613     _shenandoah_policy->report_concgc_cancelled();
1614   }
1615 }
1616 
1617 void ShenandoahHeap::cancel_concgc(ShenandoahCancelCause cause) {
1618   if (try_cancel_concgc()) {
1619     log_info(gc)("Cancelling concurrent GC: %s", cancel_cause_to_string(cause));
1620     _shenandoah_policy->report_concgc_cancelled();
1621   }
1622 }
1623 
1624 const char* ShenandoahHeap::cancel_cause_to_string(ShenandoahCancelCause cause) {
1625   switch (cause) {
1626     case _oom_evacuation:
1627       return "Out of memory for evacuation";
1628     case _vm_stop:
1629       return "Stopping VM";
1630     default:
1631       return "Unknown";
1632   }
1633 }
1634 
1635 uint ShenandoahHeap::max_workers() {
1636   return _max_workers;
1637 }
1638 
1639 void ShenandoahHeap::stop() {
1640   // The shutdown sequence should be able to terminate when GC is running.
1641 
1642   // Step 0. Notify policy to disable event recording.
1643   _shenandoah_policy->record_shutdown();
1644 
1645   // Step 1. Notify control thread that we are in shutdown.
1646   // Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown.
1647   // Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below.
1648   _concurrent_gc_thread->prepare_for_graceful_shutdown();
1649 
1650   // Step 2. Notify GC workers that we are cancelling GC.
1651   cancel_concgc(_vm_stop);
1652 
1653   // Step 3. Wait until GC worker exits normally.
1654   _concurrent_gc_thread->stop();
1655 }
1656 
1657 void ShenandoahHeap::unload_classes_and_cleanup_tables(bool full_gc) {
1658   ShenandoahPhaseTimings::Phase phase_root =
1659           full_gc ?
1660           ShenandoahPhaseTimings::full_gc_purge :
1661           ShenandoahPhaseTimings::purge;
1662 
1663   ShenandoahPhaseTimings::Phase phase_unload =
1664           full_gc ?
1665           ShenandoahPhaseTimings::full_gc_purge_class_unload :
1666           ShenandoahPhaseTimings::purge_class_unload;
1667 
1668   ShenandoahPhaseTimings::Phase phase_cldg =
1669           full_gc ?
1670           ShenandoahPhaseTimings::full_gc_purge_cldg :
1671           ShenandoahPhaseTimings::purge_cldg;
1672 
1673   ShenandoahPhaseTimings::Phase phase_par =
1674           full_gc ?
1675           ShenandoahPhaseTimings::full_gc_purge_par :
1676           ShenandoahPhaseTimings::purge_par;
1677 
1678   ShenandoahPhaseTimings::Phase phase_par_classes =
1679           full_gc ?
1680           ShenandoahPhaseTimings::full_gc_purge_par_classes :
1681           ShenandoahPhaseTimings::purge_par_classes;
1682 
1683   ShenandoahPhaseTimings::Phase phase_par_codecache =
1684           full_gc ?
1685           ShenandoahPhaseTimings::full_gc_purge_par_codecache :
1686           ShenandoahPhaseTimings::purge_par_codecache;
1687 
1688   ShenandoahPhaseTimings::Phase phase_par_rmt =
1689           full_gc ?
1690           ShenandoahPhaseTimings::full_gc_purge_par_rmt :
1691           ShenandoahPhaseTimings::purge_par_rmt;
1692 
1693   ShenandoahPhaseTimings::Phase phase_par_symbstring =
1694           full_gc ?
1695           ShenandoahPhaseTimings::full_gc_purge_par_symbstring :
1696           ShenandoahPhaseTimings::purge_par_symbstring;
1697 
1698   ShenandoahPhaseTimings::Phase phase_par_sync =
1699           full_gc ?
1700           ShenandoahPhaseTimings::full_gc_purge_par_sync :
1701           ShenandoahPhaseTimings::purge_par_sync;
1702 
1703   ShenandoahGCPhase root_phase(phase_root);
1704 
1705   BoolObjectClosure* is_alive = is_alive_closure();
1706 
1707   bool purged_class;
1708 
1709   // Unload classes and purge SystemDictionary.
1710   {
1711     ShenandoahGCPhase phase(phase_unload);
1712     purged_class = SystemDictionary::do_unloading(is_alive,
1713                                                   full_gc ? ShenandoahMarkCompact::gc_timer() : gc_timer(),
1714                                                   true);
1715   }
1716 
1717   {
1718     ShenandoahGCPhase phase(phase_par);
1719     uint active = _workers->active_workers();
1720     ParallelCleaningTask unlink_task(is_alive, true, true, active, purged_class);
1721     _workers->run_task(&unlink_task);
1722 
1723     ShenandoahPhaseTimings* p = ShenandoahHeap::heap()->phase_timings();
1724     ParallelCleaningTimes times = unlink_task.times();
1725 
1726     // "times" report total time, phase_tables_cc reports wall time. Divide total times
1727     // by active workers to get average time per worker, that would add up to wall time.
1728     p->record_phase_time(phase_par_classes,    times.klass_work_us() / active);
1729     p->record_phase_time(phase_par_codecache,  times.codecache_work_us() / active);
1730     p->record_phase_time(phase_par_rmt,        times.rmt_work_us() / active);
1731     p->record_phase_time(phase_par_symbstring, times.tables_work_us() / active);
1732     p->record_phase_time(phase_par_sync,       times.sync_us() / active);
1733   }
1734 
1735   {
1736     ShenandoahGCPhase phase(phase_cldg);
1737     ClassLoaderDataGraph::purge();
1738   }
1739 }
1740 
1741 void ShenandoahHeap::set_need_update_refs(bool need_update_refs) {
1742   _need_update_refs = need_update_refs;
1743 }
1744 
1745 //fixme this should be in heapregionset
1746 ShenandoahHeapRegion* ShenandoahHeap::next_compaction_region(const ShenandoahHeapRegion* r) {
1747   size_t region_idx = r->region_number() + 1;
1748   ShenandoahHeapRegion* next = _ordered_regions->get(region_idx);
1749   guarantee(next->region_number() == region_idx, "region number must match");
1750   while (next->is_humongous()) {
1751     region_idx = next->region_number() + 1;
1752     next = _ordered_regions->get(region_idx);
1753     guarantee(next->region_number() == region_idx, "region number must match");
1754   }
1755   return next;
1756 }
1757 
1758 ShenandoahMonitoringSupport* ShenandoahHeap::monitoring_support() {
1759   return _monitoring_support;
1760 }
1761 
1762 MarkBitMap* ShenandoahHeap::mark_bit_map() {
1763   return &_mark_bit_map;
1764 }
1765 
1766 void ShenandoahHeap::add_free_region(ShenandoahHeapRegion* r) {
1767   _free_regions->add_region(r);
1768 }
1769 
1770 void ShenandoahHeap::clear_free_regions() {
1771   _free_regions->clear();
1772 }
1773 
1774 address ShenandoahHeap::in_cset_fast_test_addr() {
1775   ShenandoahHeap* heap = ShenandoahHeap::heap();
1776   assert(heap->collection_set() != NULL, "Sanity");
1777   return (address) heap->collection_set()->biased_map_address();
1778 }
1779 
1780 address ShenandoahHeap::cancelled_concgc_addr() {
1781   return (address) &(ShenandoahHeap::heap()->_cancelled_concgc);
1782 }
1783 
1784 
1785 size_t ShenandoahHeap::conservative_max_heap_alignment() {
1786   return ShenandoahMaxRegionSize;
1787 }
1788 
1789 size_t ShenandoahHeap::bytes_allocated_since_cm() {
1790   return _bytes_allocated_since_cm;
1791 }
1792 
1793 void ShenandoahHeap::set_bytes_allocated_since_cm(size_t bytes) {
1794   _bytes_allocated_since_cm = bytes;
1795 }
1796 
1797 void ShenandoahHeap::set_top_at_mark_start(HeapWord* region_base, HeapWord* addr) {
1798   uintx index = ((uintx) region_base) >> ShenandoahHeapRegion::region_size_bytes_shift();
1799   _top_at_mark_starts[index] = addr;
1800 }
1801 
1802 HeapWord* ShenandoahHeap::top_at_mark_start(HeapWord* region_base) {
1803   uintx index = ((uintx) region_base) >> ShenandoahHeapRegion::region_size_bytes_shift();
1804   return _top_at_mark_starts[index];
1805 }
1806 
1807 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {
1808   _full_gc_in_progress = in_progress;
1809 }
1810 
1811 bool ShenandoahHeap::is_full_gc_in_progress() const {
1812   return _full_gc_in_progress;
1813 }
1814 
1815 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {
1816   _update_refs_in_progress = in_progress;
1817 }
1818 
1819 bool ShenandoahHeap::is_update_refs_in_progress() const {
1820   return _update_refs_in_progress;
1821 }
1822 
1823 void ShenandoahHeap::register_nmethod(nmethod* nm) {
1824   ShenandoahCodeRoots::add_nmethod(nm);
1825 }
1826 
1827 void ShenandoahHeap::unregister_nmethod(nmethod* nm) {
1828   ShenandoahCodeRoots::remove_nmethod(nm);
1829 }
1830 
1831 void ShenandoahHeap::pin_object(oop o) {
1832   ShenandoahHeapLocker locker(lock());
1833   heap_region_containing(o)->make_pinned();
1834 }
1835 
1836 void ShenandoahHeap::unpin_object(oop o) {
1837   ShenandoahHeapLocker locker(lock());
1838   heap_region_containing(o)->make_unpinned();
1839 }
1840 
1841 GCTimer* ShenandoahHeap::gc_timer() const {
1842   return _gc_timer;
1843 }
1844 
1845 #ifdef ASSERT
1846 void ShenandoahHeap::assert_gc_workers(uint nworkers) {
1847   assert(nworkers > 0 && nworkers <= max_workers(), "Sanity");
1848 
1849   if (SafepointSynchronize::is_at_safepoint()) {
1850     if (UseDynamicNumberOfGCThreads ||
1851         (FLAG_IS_DEFAULT(ParallelGCThreads) && ForceDynamicNumberOfGCThreads)) {
1852       assert(nworkers <= ParallelGCThreads, "Cannot use more than it has");
1853     } else {
1854       // Use ParallelGCThreads inside safepoints
1855       assert(nworkers == ParallelGCThreads, "Use ParalleGCThreads within safepoints");
1856     }
1857   } else {
1858     if (UseDynamicNumberOfGCThreads ||
1859         (FLAG_IS_DEFAULT(ConcGCThreads) && ForceDynamicNumberOfGCThreads)) {
1860       assert(nworkers <= ConcGCThreads, "Cannot use more than it has");
1861     } else {
1862       // Use ConcGCThreads outside safepoints
1863       assert(nworkers == ConcGCThreads, "Use ConcGCThreads outside safepoints");
1864     }
1865   }
1866 }
1867 #endif
1868 
1869 class ShenandoahCountGarbageClosure : public ShenandoahHeapRegionClosure {
1870 private:
1871   size_t            _garbage;
1872 public:
1873   ShenandoahCountGarbageClosure() : _garbage(0) {
1874   }
1875 
1876   bool heap_region_do(ShenandoahHeapRegion* r) {
1877     if (r->is_regular()) {
1878       _garbage += r->garbage();
1879     }
1880     return false;
1881   }
1882 
1883   size_t garbage() {
1884     return _garbage;
1885   }
1886 };
1887 
1888 size_t ShenandoahHeap::garbage() {
1889   ShenandoahCountGarbageClosure cl;
1890   heap_region_iterate(&cl);
1891   return cl.garbage();
1892 }
1893 
1894 ShenandoahConnectionMatrix* ShenandoahHeap::connection_matrix() const {
1895   return _connection_matrix;
1896 }
1897 
1898 ShenandoahPartialGC* ShenandoahHeap::partial_gc() {
1899   return _partial_gc;
1900 }
1901 
1902 ShenandoahVerifier* ShenandoahHeap::verifier() {
1903   guarantee(ShenandoahVerify, "Should be enabled");
1904   assert (_verifier != NULL, "sanity");
1905   return _verifier;
1906 }
1907 
1908 template<class T>
1909 class ShenandoahUpdateHeapRefsTask : public AbstractGangTask {
1910 private:
1911   T cl;
1912   ShenandoahHeap* _heap;
1913   ShenandoahHeapRegionSet* _regions;
1914   bool _concurrent;
1915 public:
1916   ShenandoahUpdateHeapRefsTask(ShenandoahHeapRegionSet* regions, bool concurrent) :
1917     AbstractGangTask("Concurrent Update References Task"),
1918     cl(T()),
1919     _heap(ShenandoahHeap::heap()),
1920     _regions(regions),
1921     _concurrent(concurrent) {
1922   }
1923 
1924   void work(uint worker_id) {
1925     SuspendibleThreadSetJoiner stsj(_concurrent && ShenandoahSuspendibleWorkers);
1926     ShenandoahHeapRegion* r = _regions->claim_next();
1927     while (r != NULL) {
1928       if (_heap->in_collection_set(r)) {
1929         HeapWord* bottom = r->bottom();
1930         HeapWord* top = _heap->top_at_mark_start(r->bottom());
1931         if (top > bottom) {
1932           _heap->mark_bit_map()->clear_range_large(MemRegion(bottom, top));
1933         }
1934       } else {
1935         if (r->is_active()) {
1936           _heap->marked_object_oop_safe_iterate(r, &cl);
1937         }
1938       }
1939       if (_heap->check_cancelled_concgc_and_yield(_concurrent)) {
1940         return;
1941       }
1942       r = _regions->claim_next();
1943     }
1944   }
1945 };
1946 
1947 void ShenandoahHeap::update_heap_references(ShenandoahHeapRegionSet* update_regions, bool concurrent) {
1948   if (UseShenandoahMatrix) {
1949     ShenandoahUpdateHeapRefsTask<ShenandoahUpdateHeapRefsMatrixClosure> task(update_regions, concurrent);
1950     workers()->run_task(&task);
1951   } else {
1952     ShenandoahUpdateHeapRefsTask<ShenandoahUpdateHeapRefsClosure> task(update_regions, concurrent);
1953     workers()->run_task(&task);
1954   }
1955 }
1956 
1957 void ShenandoahHeap::concurrent_update_heap_references() {
1958   ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_update_refs);
1959   ShenandoahHeapRegionSet* update_regions = regions();
1960   update_regions->clear_current_index();
1961   update_heap_references(update_regions, true);
1962 }
1963 
1964 void ShenandoahHeap::prepare_update_refs() {
1965   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1966 
1967   if (ShenandoahVerify) {
1968     verifier()->verify_before_updaterefs();
1969   }
1970 
1971   set_evacuation_in_progress_at_safepoint(false);
1972   set_update_refs_in_progress(true);
1973   make_tlabs_parsable(true);
1974   if (UseShenandoahMatrix) {
1975     connection_matrix()->clear_all();
1976   }
1977   for (uint i = 0; i < num_regions(); i++) {
1978     ShenandoahHeapRegion* r = _ordered_regions->get(i);
1979     r->set_concurrent_iteration_safe_limit(r->top());
1980   }
1981 }
1982 
1983 void ShenandoahHeap::finish_update_refs() {
1984   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
1985 
1986   if (cancelled_concgc()) {
1987     ShenandoahGCPhase final_work(ShenandoahPhaseTimings::final_update_refs_finish_work);
1988 
1989     // Finish updating references where we left off.
1990     clear_cancelled_concgc();
1991     ShenandoahHeapRegionSet* update_regions = regions();
1992     update_heap_references(update_regions, false);
1993   }
1994 
1995   assert(! cancelled_concgc(), "Should have been done right before");
1996   concurrentMark()->update_roots(ShenandoahPhaseTimings::final_update_refs_roots);
1997 
1998   if (ShenandoahStringDedup::is_enabled()) {
1999     ShenandoahGCPhase final_str_dedup_table(ShenandoahPhaseTimings::final_update_refs_dedup_table);
2000     ShenandoahStringDedup::parallel_update_refs();
2001   }
2002 
2003   // Allocations might have happened before we STWed here, record peak:
2004   shenandoahPolicy()->record_peak_occupancy();
2005 
2006   ShenandoahGCPhase final_update_refs(ShenandoahPhaseTimings::final_update_refs_recycle);
2007 
2008   trash_cset_regions();
2009   set_need_update_refs(false);
2010 
2011   if (ShenandoahVerify) {
2012     verifier()->verify_after_updaterefs();
2013   }
2014 
2015   {
2016     // Rebuild the free set
2017     ShenandoahHeapLocker locker(lock());
2018     _free_regions->clear();
2019     size_t end = _ordered_regions->active_regions();
2020     for (size_t i = 0; i < end; i++) {
2021       ShenandoahHeapRegion* r = _ordered_regions->get(i);
2022       if (r->is_alloc_allowed()) {
2023         assert (!in_collection_set(r), "collection set should be clear");
2024         _free_regions->add_region(r);
2025       }
2026     }
2027   }
2028   set_update_refs_in_progress(false);
2029 }
2030 
2031 void ShenandoahHeap::set_alloc_seq_gc_start() {
2032   // Take next number, the start seq number is inclusive
2033   _alloc_seq_at_last_gc_start = ShenandoahHeapRegion::alloc_seq_num() + 1;
2034 }
2035 
2036 void ShenandoahHeap::set_alloc_seq_gc_end() {
2037   // Take current number, the end seq number is also inclusive
2038   _alloc_seq_at_last_gc_end = ShenandoahHeapRegion::alloc_seq_num();
2039 }
2040 
2041 
2042 #ifdef ASSERT
2043 void ShenandoahHeap::assert_heaplock_owned_by_current_thread() {
2044   _lock.assert_owned_by_current_thread();
2045 }
2046 
2047 void ShenandoahHeap::assert_heaplock_not_owned_by_current_thread() {
2048   _lock.assert_not_owned_by_current_thread();
2049 }
2050 
2051 void ShenandoahHeap::assert_heaplock_or_safepoint() {
2052   _lock.assert_owned_by_current_thread_or_safepoint();
2053 }
2054 #endif
2055 
2056 void ShenandoahHeap::recycle_trash_assist(size_t limit) {
2057   assert_heaplock_owned_by_current_thread();
2058 
2059   size_t count = 0;
2060   for (size_t i = 0; (i < num_regions()) && (count < limit); i++) {
2061     ShenandoahHeapRegion *r = _ordered_regions->get(i);
2062     if (r->is_trash()) {
2063       decrease_used(r->used());
2064       r->recycle();
2065       _free_regions->add_region(r);
2066       count++;
2067     }
2068   }
2069 }
2070 
2071 void ShenandoahHeap::recycle_trash() {
2072   // lock is not reentrable, check we don't have it
2073   assert_heaplock_not_owned_by_current_thread();
2074 
2075   size_t bytes_reclaimed = 0;
2076 
2077   if (UseShenandoahMatrix) {
2078     // The complication for matrix cleanup is that we want the batched update
2079     // to alleviate costs. We also cannot add regions to freeset until matrix
2080     // is clean, otherwise we race with the actual allocations.
2081 
2082     size_t count = 0;
2083     for (size_t i = 0; i < num_regions(); i++) {
2084       ShenandoahHeapRegion* r = _ordered_regions->get(i);
2085       if (r->is_trash()) {
2086         ShenandoahHeapLocker locker(lock());
2087         if (r->is_trash()) {
2088           bytes_reclaimed += r->used();
2089           decrease_used(r->used());
2090           r->recycle_no_matrix();
2091           _recycled_regions[count++] = r->region_number();
2092         }
2093       }
2094       SpinPause(); // allow allocators to barge the lock
2095     }
2096 
2097     connection_matrix()->clear_batched(_recycled_regions, count);
2098 
2099     {
2100       ShenandoahHeapLocker locker(lock());
2101       for (size_t i = 0; i < count; i++) {
2102         ShenandoahHeapRegion *r = _ordered_regions->get(_recycled_regions[i]);
2103         _free_regions->add_region(r);
2104       }
2105     }
2106 
2107   } else {
2108     for (size_t i = 0; i < num_regions(); i++) {
2109       ShenandoahHeapRegion* r = _ordered_regions->get(i);
2110       if (r->is_trash()) {
2111         ShenandoahHeapLocker locker(lock());
2112         if (r->is_trash()) {
2113           bytes_reclaimed += r->used();
2114           decrease_used(r->used());
2115           r->recycle();
2116           _free_regions->add_region(r);
2117         }
2118       }
2119       SpinPause(); // allow allocators to barge the lock
2120     }
2121   }
2122 
2123   _shenandoah_policy->record_bytes_reclaimed(bytes_reclaimed);
2124 }
2125 
2126 void ShenandoahHeap::print_extended_on(outputStream *st) const {
2127   print_on(st);
2128   print_heap_regions_on(st);
2129 }
2130 
2131 address ShenandoahHeap::concurrent_mark_in_progress_addr() {
2132   return (address) &(ShenandoahHeap::heap()->_concurrent_mark_in_progress);
2133 }
2134 
2135 bool ShenandoahHeap::commit_bitmaps(ShenandoahHeapRegion* r) {
2136   size_t len = _bitmap_words_per_region * HeapWordSize;
2137   size_t off = r->region_number() * _bitmap_words_per_region;
2138   if (!os::commit_memory((char*)(_bitmap_region.start() + off), len, false)) {
2139     return false;
2140   }
2141   return true;
2142 }
2143 
2144 bool ShenandoahHeap::uncommit_bitmaps(ShenandoahHeapRegion* r) {
2145   size_t len = _bitmap_words_per_region * HeapWordSize;
2146   size_t off = r->region_number() * _bitmap_words_per_region;
2147   if (!os::uncommit_memory((char*)(_bitmap_region.start() + off), len)) {
2148     return false;
2149   }
2150   return true;
2151 }