1 /*
   2  * Copyright (c) 2013, 2015, 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/shenandoahBarrierSet.hpp"
  33 #include "gc/shenandoah/shenandoahCollectionSet.hpp"
  34 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
  35 #include "gc/shenandoah/shenandoahConcurrentMark.hpp"
  36 #include "gc/shenandoah/shenandoahConcurrentMark.inline.hpp"
  37 #include "gc/shenandoah/shenandoahConcurrentThread.hpp"
  38 #include "gc/shenandoah/shenandoahFreeSet.hpp"
  39 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
  40 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
  41 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp"
  42 #include "gc/shenandoah/shenandoahHumongous.hpp"
  43 #include "gc/shenandoah/shenandoahMarkCompact.hpp"
  44 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
  45 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp"
  46 #include "gc/shenandoah/shenandoahPartialGC.hpp"
  47 #include "gc/shenandoah/shenandoahRootProcessor.hpp"
  48 #include "gc/shenandoah/vm_operations_shenandoah.hpp"
  49 
  50 #include "runtime/vmThread.hpp"
  51 #include "services/mallocTracker.hpp"
  52 
  53 SCMUpdateRefsClosure::SCMUpdateRefsClosure() : _heap(ShenandoahHeap::heap()) {}
  54 
  55 #ifdef ASSERT
  56 template <class T>
  57 void AssertToSpaceClosure::do_oop_nv(T* p) {
  58   T o = oopDesc::load_heap_oop(p);
  59   if (! oopDesc::is_null(o)) {
  60     oop obj = oopDesc::decode_heap_oop_not_null(o);
  61     assert(oopDesc::unsafe_equals(obj, ShenandoahBarrierSet::resolve_oop_static_not_null(obj)),
  62            "need to-space object here obj: "PTR_FORMAT" , rb(obj): "PTR_FORMAT", p: "PTR_FORMAT,
  63            p2i(obj), p2i(ShenandoahBarrierSet::resolve_oop_static_not_null(obj)), p2i(p));
  64   }
  65 }
  66 
  67 void AssertToSpaceClosure::do_oop(narrowOop* p) { do_oop_nv(p); }
  68 void AssertToSpaceClosure::do_oop(oop* p)       { do_oop_nv(p); }
  69 #endif
  70 
  71 const char* ShenandoahHeap::name() const {
  72   return "Shenandoah";
  73 }
  74 
  75 void ShenandoahHeap::print_heap_locations(HeapWord* start, HeapWord* end) {
  76   HeapWord* cur = NULL;
  77   for (cur = start; cur < end; cur++) {
  78     tty->print_cr(PTR_FORMAT" : "PTR_FORMAT, p2i(cur), p2i(*((HeapWord**) cur)));
  79   }
  80 }
  81 
  82 class ShenandoahPretouchTask : public AbstractGangTask {
  83 private:
  84   ShenandoahHeapRegionSet* _regions;
  85   const size_t _bitmap_size;
  86   const size_t _page_size;
  87   char* _bitmap0_base;
  88   char* _bitmap1_base;
  89 public:
  90   ShenandoahPretouchTask(ShenandoahHeapRegionSet* regions,
  91                          char* bitmap0_base, char* bitmap1_base, size_t bitmap_size,
  92                          size_t page_size) :
  93     AbstractGangTask("Shenandoah PreTouch",
  94                      Universe::is_fully_initialized() ? GCId::current_raw() :
  95                                                         // During VM initialization there is
  96                                                         // no GC cycle that this task can be
  97                                                         // associated with.
  98                                                         GCId::undefined()),
  99     _bitmap0_base(bitmap0_base),
 100     _bitmap1_base(bitmap1_base),
 101     _regions(regions),
 102     _bitmap_size(bitmap_size),
 103     _page_size(page_size) {
 104     _regions->clear_current_index();
 105   };
 106 
 107   virtual void work(uint worker_id) {
 108     ShenandoahHeapRegion* r = _regions->claim_next();
 109     while (r != NULL) {
 110       log_trace(gc, heap)("Pretouch region " SIZE_FORMAT ": " PTR_FORMAT " -> " PTR_FORMAT,
 111                           r->region_number(), p2i(r->bottom()), p2i(r->end()));
 112       os::pretouch_memory(r->bottom(), r->end(), _page_size);
 113 
 114       size_t start = r->region_number()       * ShenandoahHeapRegion::region_size_bytes() / CMBitMap::heap_map_factor();
 115       size_t end   = (r->region_number() + 1) * ShenandoahHeapRegion::region_size_bytes() / CMBitMap::heap_map_factor();
 116       assert (end <= _bitmap_size, "end is sane: " SIZE_FORMAT " < " SIZE_FORMAT, end, _bitmap_size);
 117 
 118       log_trace(gc, heap)("Pretouch bitmap under region " SIZE_FORMAT ": " PTR_FORMAT " -> " PTR_FORMAT,
 119                           r->region_number(), p2i(_bitmap0_base + start), p2i(_bitmap0_base + end));
 120       os::pretouch_memory(_bitmap0_base + start, _bitmap0_base + end, _page_size);
 121 
 122       log_trace(gc, heap)("Pretouch bitmap under region " SIZE_FORMAT ": " PTR_FORMAT " -> " PTR_FORMAT,
 123                           r->region_number(), p2i(_bitmap1_base + start), p2i(_bitmap1_base + end));
 124       os::pretouch_memory(_bitmap1_base + start, _bitmap1_base + end, _page_size);
 125 
 126       r = _regions->claim_next();
 127     }
 128   }
 129 };
 130 
 131 jint ShenandoahHeap::initialize() {
 132   CollectedHeap::pre_initialize();
 133 
 134   BrooksPointer::initial_checks();
 135 
 136   size_t init_byte_size = collector_policy()->initial_heap_byte_size();
 137   size_t max_byte_size = collector_policy()->max_heap_byte_size();
 138 
 139   Universe::check_alignment(max_byte_size,
 140                             ShenandoahHeapRegion::region_size_bytes(),
 141                             "shenandoah heap");
 142   Universe::check_alignment(init_byte_size,
 143                             ShenandoahHeapRegion::region_size_bytes(),
 144                             "shenandoah heap");
 145 
 146   ReservedSpace heap_rs = Universe::reserve_heap(max_byte_size,
 147                                                  Arguments::conservative_max_heap_alignment());
 148   initialize_reserved_region((HeapWord*)heap_rs.base(), (HeapWord*) (heap_rs.base() + heap_rs.size()));
 149 
 150   set_barrier_set(new ShenandoahBarrierSet(this));
 151   ReservedSpace pgc_rs = heap_rs.first_part(max_byte_size);
 152   _storage.initialize(pgc_rs, init_byte_size);
 153 
 154   _num_regions = init_byte_size / ShenandoahHeapRegion::region_size_bytes();
 155   _max_regions = max_byte_size / ShenandoahHeapRegion::region_size_bytes();
 156   _initialSize = _num_regions * ShenandoahHeapRegion::region_size_bytes();
 157   size_t regionSizeWords = ShenandoahHeapRegion::region_size_bytes() / HeapWordSize;
 158   assert(init_byte_size == _initialSize, "tautology");
 159   _ordered_regions = new ShenandoahHeapRegionSet(_max_regions);
 160   _collection_set = new ShenandoahCollectionSet(_max_regions);
 161   _free_regions = new ShenandoahFreeSet(_max_regions);
 162 
 163   // Initialize fast collection set test structure.
 164   _in_cset_fast_test_length = _max_regions;
 165   _in_cset_fast_test_base =
 166                    NEW_C_HEAP_ARRAY(bool, _in_cset_fast_test_length, mtGC);
 167   _in_cset_fast_test = _in_cset_fast_test_base -
 168                ((uintx) pgc_rs.base() >> ShenandoahHeapRegion::region_size_shift());
 169 
 170   _next_top_at_mark_starts_base =
 171                    NEW_C_HEAP_ARRAY(HeapWord*, _max_regions, mtGC);
 172   _next_top_at_mark_starts = _next_top_at_mark_starts_base -
 173                ((uintx) pgc_rs.base() >> ShenandoahHeapRegion::region_size_shift());
 174 
 175   _complete_top_at_mark_starts_base =
 176                    NEW_C_HEAP_ARRAY(HeapWord*, _max_regions, mtGC);
 177   _complete_top_at_mark_starts = _complete_top_at_mark_starts_base -
 178                ((uintx) pgc_rs.base() >> ShenandoahHeapRegion::region_size_shift());
 179 
 180   size_t i = 0;
 181   for (i = 0; i < _num_regions; i++) {
 182     _in_cset_fast_test_base[i] = false; // Not in cset
 183     HeapWord* bottom = (HeapWord*) pgc_rs.base() + regionSizeWords * i;
 184     _complete_top_at_mark_starts_base[i] = bottom;
 185     _next_top_at_mark_starts_base[i] = bottom;
 186   }
 187 
 188   {
 189     ShenandoahHeapLock lock(this);
 190     for (i = 0; i < _num_regions; i++) {
 191       ShenandoahHeapRegion* current = new ShenandoahHeapRegion(this, (HeapWord*) pgc_rs.base() +
 192                                                                regionSizeWords * i, regionSizeWords, i);
 193       _free_regions->add_region(current);
 194       _ordered_regions->add_region(current);
 195     }
 196   }
 197   assert(((size_t) _ordered_regions->active_regions()) == _num_regions, "");
 198   _first_region = _ordered_regions->get(0);
 199   assert((((size_t) base()) &
 200           (ShenandoahHeapRegion::region_size_bytes() - 1)) == 0,
 201          "misaligned heap: "PTR_FORMAT, p2i(base()));
 202 
 203   if (log_is_enabled(Trace, gc, region)) {
 204     ResourceMark rm;
 205     outputStream* out = Log(gc, region)::trace_stream();
 206     log_trace(gc, region)("All Regions");
 207     _ordered_regions->print(out);
 208     log_trace(gc, region)("Free Regions");
 209     _free_regions->print(out);
 210   }
 211 
 212   // The call below uses stuff (the SATB* things) that are in G1, but probably
 213   // belong into a shared location.
 214   JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon,
 215                                                SATB_Q_FL_lock,
 216                                                20 /*G1SATBProcessCompletedThreshold */,
 217                                                Shared_SATB_Q_lock);
 218 
 219   // Reserve space for prev and next bitmap.
 220   _bitmap_size = CMBitMap::compute_size(heap_rs.size());
 221   _heap_region = MemRegion((HeapWord*) heap_rs.base(), heap_rs.size() / HeapWordSize);
 222 
 223   size_t page_size = UseLargePages ? (size_t)os::large_page_size() : (size_t)os::vm_page_size();
 224 
 225   ReservedSpace bitmap0(_bitmap_size, page_size);
 226   os::commit_memory_or_exit(bitmap0.base(), bitmap0.size(), false, "couldn't allocate mark bitmap");
 227   MemTracker::record_virtual_memory_type(bitmap0.base(), mtGC);
 228   MemRegion bitmap_region0 = MemRegion((HeapWord*) bitmap0.base(), bitmap0.size() / HeapWordSize);
 229 
 230   ReservedSpace bitmap1(_bitmap_size, page_size);
 231   os::commit_memory_or_exit(bitmap1.base(), bitmap1.size(), false, "couldn't allocate mark bitmap");
 232   MemTracker::record_virtual_memory_type(bitmap1.base(), mtGC);
 233   MemRegion bitmap_region1 = MemRegion((HeapWord*) bitmap1.base(), bitmap1.size() / HeapWordSize);
 234 
 235   if (ShenandoahVerify || (UseShenandoahMatrix && VerifyShenandoahMatrix)) {
 236     ReservedSpace verify_bitmap(_bitmap_size, page_size);
 237     os::commit_memory_or_exit(verify_bitmap.base(), verify_bitmap.size(), false,
 238                               "couldn't allocate verification bitmap");
 239     MemTracker::record_virtual_memory_type(verify_bitmap.base(), mtGC);
 240     MemRegion verify_bitmap_region = MemRegion((HeapWord *) verify_bitmap.base(), verify_bitmap.size() / HeapWordSize);
 241     _verification_bit_map.initialize(_heap_region, verify_bitmap_region);
 242   }
 243 
 244   if (ShenandoahAlwaysPreTouch) {
 245     assert (!AlwaysPreTouch, "Should have been overridden");
 246 
 247     // For NUMA, it is important to pre-touch the storage under bitmaps with worker threads,
 248     // before initialize() below zeroes it with initializing thread. For any given region,
 249     // we touch the region and the corresponding bitmaps from the same thread.
 250 
 251     log_info(gc, heap)("Parallel pretouch " SIZE_FORMAT " regions with " SIZE_FORMAT " byte pages",
 252                        _ordered_regions->count(), page_size);
 253     ShenandoahPretouchTask cl(_ordered_regions, bitmap0.base(), bitmap1.base(), _bitmap_size, page_size);
 254     _workers->run_task(&cl);
 255   }
 256 
 257   _mark_bit_map0.initialize(_heap_region, bitmap_region0);
 258   _complete_mark_bit_map = &_mark_bit_map0;
 259 
 260   _mark_bit_map1.initialize(_heap_region, bitmap_region1);
 261   _next_mark_bit_map = &_mark_bit_map1;
 262 
 263   _connection_matrix = new ShenandoahConnectionMatrix(_max_regions);
 264   _partial_gc = new ShenandoahPartialGC(this, _max_regions);
 265 
 266   _monitoring_support = new ShenandoahMonitoringSupport(this);
 267 
 268   _concurrent_gc_thread = new ShenandoahConcurrentThread();
 269 
 270   ShenandoahMarkCompact::initialize();
 271 
 272   return JNI_OK;
 273 }
 274 
 275 ShenandoahHeap::ShenandoahHeap(ShenandoahCollectorPolicy* policy) :
 276   CollectedHeap(),
 277   _shenandoah_policy(policy),
 278   _concurrent_mark_in_progress(0),
 279   _evacuation_in_progress(0),
 280   _full_gc_in_progress(false),
 281   _update_refs_in_progress(false),
 282   _free_regions(NULL),
 283   _collection_set(NULL),
 284   _bytes_allocated_since_cm(0),
 285   _bytes_allocated_during_cm(0),
 286   _allocated_last_gc(0),
 287   _used_start_gc(0),
 288   _max_workers(MAX2(ConcGCThreads, ParallelGCThreads)),
 289   _ref_processor(NULL),
 290   _in_cset_fast_test(NULL),
 291   _in_cset_fast_test_base(NULL),
 292   _next_top_at_mark_starts(NULL),
 293   _next_top_at_mark_starts_base(NULL),
 294   _complete_top_at_mark_starts(NULL),
 295   _complete_top_at_mark_starts_base(NULL),
 296   _mark_bit_map0(),
 297   _mark_bit_map1(),
 298   _connection_matrix(NULL),
 299   _cancelled_concgc(false),
 300   _need_update_refs(false),
 301   _need_reset_bitmaps(false),
 302   _heap_lock(0),
 303 #ifdef ASSERT
 304   _heap_lock_owner(NULL),
 305 #endif
 306   _gc_timer(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer())
 307 
 308 {
 309   log_info(gc, init)("Parallel GC threads: "UINT32_FORMAT, ParallelGCThreads);
 310   log_info(gc, init)("Concurrent GC threads: "UINT32_FORMAT, ConcGCThreads);
 311   log_info(gc, init)("Parallel reference processing enabled: %s", BOOL_TO_STR(ParallelRefProcEnabled));
 312 
 313   _scm = new ShenandoahConcurrentMark();
 314   _used = 0;
 315 
 316   _max_workers = MAX2(_max_workers, 1U);
 317   _workers = new ShenandoahWorkGang("Shenandoah GC Threads", _max_workers,
 318                             /* are_GC_task_threads */true,
 319                             /* are_ConcurrentGC_threads */false);
 320   if (_workers == NULL) {
 321     vm_exit_during_initialization("Failed necessary allocation.");
 322   } else {
 323     _workers->initialize_workers();
 324   }
 325 }
 326 
 327 class ResetNextBitmapTask : public AbstractGangTask {
 328 private:
 329   ShenandoahHeapRegionSet* _regions;
 330 
 331 public:
 332   ResetNextBitmapTask(ShenandoahHeapRegionSet* regions) :
 333     AbstractGangTask("Parallel Reset Bitmap Task"),
 334     _regions(regions) {
 335     _regions->clear_current_index();
 336   }
 337 
 338   void work(uint worker_id) {
 339     ShenandoahHeapRegion* region = _regions->claim_next();
 340     ShenandoahHeap* heap = ShenandoahHeap::heap();
 341     while (region != NULL) {
 342       HeapWord* bottom = region->bottom();
 343       HeapWord* top = heap->next_top_at_mark_start(region->bottom());
 344       if (top > bottom) {
 345         heap->next_mark_bit_map()->clear_range_large(MemRegion(bottom, top));
 346       }
 347       region = _regions->claim_next();
 348     }
 349   }
 350 };
 351 
 352 void ShenandoahHeap::reset_next_mark_bitmap(WorkGang* workers) {
 353   ResetNextBitmapTask task = ResetNextBitmapTask(_ordered_regions);
 354   workers->run_task(&task);
 355 }
 356 
 357 class ResetCompleteBitmapTask : public AbstractGangTask {
 358 private:
 359   ShenandoahHeapRegionSet* _regions;
 360 
 361 public:
 362   ResetCompleteBitmapTask(ShenandoahHeapRegionSet* regions) :
 363     AbstractGangTask("Parallel Reset Bitmap Task"),
 364     _regions(regions) {
 365     _regions->clear_current_index();
 366   }
 367 
 368   void work(uint worker_id) {
 369     ShenandoahHeapRegion* region = _regions->claim_next();
 370     ShenandoahHeap* heap = ShenandoahHeap::heap();
 371     while (region != NULL) {
 372       HeapWord* bottom = region->bottom();
 373       HeapWord* top = heap->complete_top_at_mark_start(region->bottom());
 374       if (top > bottom) {
 375         heap->complete_mark_bit_map()->clear_range_large(MemRegion(bottom, top));
 376       }
 377       region = _regions->claim_next();
 378     }
 379   }
 380 };
 381 
 382 void ShenandoahHeap::reset_complete_mark_bitmap(WorkGang* workers) {
 383   ResetCompleteBitmapTask task = ResetCompleteBitmapTask(_ordered_regions);
 384   workers->run_task(&task);
 385 }
 386 
 387 bool ShenandoahHeap::is_next_bitmap_clear() {
 388   HeapWord* start = _ordered_regions->bottom();
 389   HeapWord* end = _ordered_regions->end();
 390   return _next_mark_bit_map->getNextMarkedWordAddress(start, end) == end;
 391 }
 392 
 393 bool ShenandoahHeap::is_complete_bitmap_clear_range(HeapWord* start, HeapWord* end) {
 394   return _complete_mark_bit_map->getNextMarkedWordAddress(start, end) == end;
 395 }
 396 
 397 void ShenandoahHeap::print_on(outputStream* st) const {
 398   st->print("Shenandoah Heap");
 399   st->print(" total = " SIZE_FORMAT " K, used " SIZE_FORMAT " K ", capacity()/ K, used() /K);
 400   st->print(" [" PTR_FORMAT ", " PTR_FORMAT ") ",
 401             p2i(reserved_region().start()),
 402             p2i(reserved_region().end()));
 403   st->print("Region size = " SIZE_FORMAT "K ", ShenandoahHeapRegion::region_size_bytes() / K);
 404   if (_concurrent_mark_in_progress) {
 405     st->print("marking ");
 406   }
 407   if (_evacuation_in_progress) {
 408     st->print("evacuating ");
 409   }
 410   if (cancelled_concgc()) {
 411     st->print("cancelled ");
 412   }
 413   st->print("\n");
 414 
 415   // Adapted from VirtualSpace::print_on(), which is non-PRODUCT only
 416   st->print   ("Virtual space:");
 417   if (_storage.special()) st->print(" (pinned in memory)");
 418   st->cr();
 419   st->print_cr(" - committed: " SIZE_FORMAT, _storage.committed_size());
 420   st->print_cr(" - reserved:  " SIZE_FORMAT, _storage.reserved_size());
 421   st->print_cr(" - [low, high]:     [" INTPTR_FORMAT ", " INTPTR_FORMAT "]",  p2i(_storage.low()), p2i(_storage.high()));
 422   st->print_cr(" - [low_b, high_b]: [" INTPTR_FORMAT ", " INTPTR_FORMAT "]",  p2i(_storage.low_boundary()), p2i(_storage.high_boundary()));
 423 
 424   if (Verbose) {
 425     print_heap_regions(st);
 426   }
 427 }
 428 
 429 class InitGCLABClosure : public ThreadClosure {
 430 public:
 431   void do_thread(Thread* thread) {
 432     thread->gclab().initialize(true);
 433   }
 434 };
 435 
 436 void ShenandoahHeap::post_initialize() {
 437   if (UseTLAB) {
 438     // This is a very tricky point in VM lifetime. We cannot easily call Threads::threads_do
 439     // here, because some system threads (VMThread, WatcherThread, etc) are not yet available.
 440     // Their initialization should be handled separately. Is we miss some threads here,
 441     // then any other TLAB-related activity would fail with asserts.
 442 
 443     InitGCLABClosure init_gclabs;
 444     {
 445       MutexLocker ml(Threads_lock);
 446       for (JavaThread *thread = Threads::first(); thread != NULL; thread = thread->next()) {
 447         init_gclabs.do_thread(thread);
 448       }
 449     }
 450     gc_threads_do(&init_gclabs);
 451 
 452     // gclab can not be initialized early during VM startup, as it can not determinate its max_size.
 453     // Now, we will let WorkGang to initialize gclab when new worker is created.
 454     _workers->set_initialize_gclab();
 455   }
 456 
 457   _scm->initialize(_max_workers);
 458 
 459   ref_processing_init();
 460 }
 461 
 462 class CalculateUsedRegionClosure : public ShenandoahHeapRegionClosure {
 463   size_t sum;
 464 public:
 465 
 466   CalculateUsedRegionClosure() {
 467     sum = 0;
 468   }
 469 
 470   bool doHeapRegion(ShenandoahHeapRegion* r) {
 471     sum = sum + r->used();
 472     return false;
 473   }
 474 
 475   size_t getResult() { return sum;}
 476 };
 477 
 478 size_t ShenandoahHeap::calculateUsed() {
 479   CalculateUsedRegionClosure cl;
 480   heap_region_iterate(&cl);
 481   return cl.getResult();
 482 }
 483 
 484 void ShenandoahHeap::verify_heap_size_consistency() {
 485 
 486   assert(calculateUsed() == used(),
 487          "heap used size must be consistent heap-used: "SIZE_FORMAT" regions-used: "SIZE_FORMAT, used(), calculateUsed());
 488 }
 489 
 490 size_t ShenandoahHeap::used() const {
 491   OrderAccess::acquire();
 492   return _used;
 493 }
 494 
 495 void ShenandoahHeap::increase_used(size_t bytes) {
 496   assert_heaplock_or_safepoint();
 497   _used += bytes;
 498 }
 499 
 500 void ShenandoahHeap::set_used(size_t bytes) {
 501   assert_heaplock_or_safepoint();
 502   _used = bytes;
 503 }
 504 
 505 void ShenandoahHeap::decrease_used(size_t bytes) {
 506   assert_heaplock_or_safepoint();
 507   assert(_used >= bytes, "never decrease heap size by more than we've left");
 508   _used -= bytes;
 509 }
 510 
 511 size_t ShenandoahHeap::capacity() const {
 512   return _num_regions * ShenandoahHeapRegion::region_size_bytes();
 513 }
 514 
 515 bool ShenandoahHeap::is_maximal_no_gc() const {
 516   Unimplemented();
 517   return true;
 518 }
 519 
 520 size_t ShenandoahHeap::max_capacity() const {
 521   return _max_regions * ShenandoahHeapRegion::region_size_bytes();
 522 }
 523 
 524 size_t ShenandoahHeap::min_capacity() const {
 525   return _initialSize;
 526 }
 527 
 528 VirtualSpace* ShenandoahHeap::storage() const {
 529   return (VirtualSpace*) &_storage;
 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_bytes() / HeapWordSize) * _num_regions;
 535   return p >= heap_base && p < last_region_end;
 536 }
 537 
 538 bool ShenandoahHeap::is_scavengable(const void* p) {
 539   return true;
 540 }
 541 
 542 HeapWord* ShenandoahHeap::allocate_from_gclab_slow(Thread* thread, size_t size) {
 543   // Retain tlab and allocate object in shared space if
 544   // the amount free in the tlab is too large to discard.
 545   if (thread->gclab().free() > thread->gclab().refill_waste_limit()) {
 546     thread->gclab().record_slow_allocation(size);
 547     return NULL;
 548   }
 549 
 550   // Discard gclab and allocate a new one.
 551   // To minimize fragmentation, the last GCLAB may be smaller than the rest.
 552   size_t new_gclab_size = thread->gclab().compute_size(size);
 553 
 554   thread->gclab().clear_before_allocation();
 555 
 556   if (new_gclab_size == 0) {
 557     return NULL;
 558   }
 559 
 560   // Allocate a new GCLAB...
 561   HeapWord* obj = allocate_new_gclab(new_gclab_size);
 562   if (obj == NULL) {
 563     return NULL;
 564   }
 565 
 566   if (ZeroTLAB) {
 567     // ..and clear it.
 568     Copy::zero_to_words(obj, new_gclab_size);
 569   } else {
 570     // ...and zap just allocated object.
 571 #ifdef ASSERT
 572     // Skip mangling the space corresponding to the object header to
 573     // ensure that the returned space is not considered parsable by
 574     // any concurrent GC thread.
 575     size_t hdr_size = oopDesc::header_size();
 576     Copy::fill_to_words(obj + hdr_size, new_gclab_size - hdr_size, badHeapWordVal);
 577 #endif // ASSERT
 578   }
 579   thread->gclab().fill(obj, obj + size, new_gclab_size);
 580   return obj;
 581 }
 582 
 583 HeapWord* ShenandoahHeap::allocate_new_tlab(size_t word_size) {
 584   return allocate_new_tlab(word_size, false);
 585 }
 586 
 587 HeapWord* ShenandoahHeap::allocate_new_gclab(size_t word_size) {
 588   return allocate_new_tlab(word_size, true);
 589 }
 590 
 591 HeapWord* ShenandoahHeap::allocate_new_tlab(size_t word_size, bool evacuating) {
 592   HeapWord* result = allocate_memory(word_size, evacuating);
 593 
 594   if (result != NULL) {
 595     assert(! in_collection_set(result), "Never allocate in dirty region");
 596     _bytes_allocated_since_cm += word_size * HeapWordSize;
 597 
 598     log_develop_trace(gc, tlab)("allocating new tlab of size "SIZE_FORMAT" at addr "PTR_FORMAT, word_size, p2i(result));
 599 
 600   }
 601   return result;
 602 }
 603 
 604 ShenandoahHeap* ShenandoahHeap::heap() {
 605   CollectedHeap* heap = Universe::heap();
 606   assert(heap != NULL, "Unitialized access to ShenandoahHeap::heap()");
 607   assert(heap->kind() == CollectedHeap::ShenandoahHeap, "not a shenandoah heap");
 608   return (ShenandoahHeap*) heap;
 609 }
 610 
 611 ShenandoahHeap* ShenandoahHeap::heap_no_check() {
 612   CollectedHeap* heap = Universe::heap();
 613   return (ShenandoahHeap*) heap;
 614 }
 615 
 616 HeapWord* ShenandoahHeap::allocate_memory_work(size_t word_size) {
 617 
 618   ShenandoahHeapLock heap_lock(this);
 619 
 620   HeapWord* result = allocate_memory_under_lock(word_size);
 621   size_t grow_by = (word_size * HeapWordSize + ShenandoahHeapRegion::region_size_bytes() - 1) / ShenandoahHeapRegion::region_size_bytes();
 622 
 623   while (result == NULL && _num_regions + grow_by <= _max_regions) {
 624     grow_heap_by(grow_by);
 625     result = allocate_memory_under_lock(word_size);
 626   }
 627 
 628   return result;
 629 }
 630 
 631 HeapWord* ShenandoahHeap::allocate_memory(size_t word_size, bool evacuating) {
 632   HeapWord* result = NULL;
 633   result = allocate_memory_work(word_size);
 634 
 635   if (!evacuating) {
 636     // Allocation failed, try full-GC, then retry allocation.
 637     //
 638     // It might happen that one of the threads requesting allocation would unblock
 639     // way later after full-GC happened, only to fail the second allocation, because
 640     // other threads have already depleted the free storage. In this case, a better
 641     // strategy would be to try full-GC again.
 642     //
 643     // Lacking the way to detect progress from "collect" call, we are left with blindly
 644     // retrying for some bounded number of times.
 645     // TODO: Poll if Full GC made enough progress to warrant retry.
 646     int tries = 0;
 647     while ((result == NULL) && (tries++ < ShenandoahFullGCTries)) {
 648       log_debug(gc)("[" PTR_FORMAT " Failed to allocate " SIZE_FORMAT " bytes, doing full GC, try %d",
 649                     p2i(Thread::current()), word_size * HeapWordSize, tries);
 650       collect(GCCause::_allocation_failure);
 651       result = allocate_memory_work(word_size);
 652     }
 653   }
 654 
 655   // Only update monitoring counters when not calling from a write-barrier.
 656   // Otherwise we might attempt to grab the Service_lock, which we must
 657   // not do when coming from a write-barrier (because the thread might
 658   // already hold the Compile_lock).
 659   if (! evacuating) {
 660     monitoring_support()->update_counters();
 661   }
 662 
 663   log_develop_trace(gc, alloc)("allocate memory chunk of size "SIZE_FORMAT" at addr "PTR_FORMAT " by thread %d ",
 664                                word_size, p2i(result), Thread::current()->osthread()->thread_id());
 665 
 666   return result;
 667 }
 668 
 669 HeapWord* ShenandoahHeap::allocate_memory_under_lock(size_t word_size) {
 670   assert_heaplock_owned_by_current_thread();
 671 
 672   if (word_size * HeapWordSize > ShenandoahHeapRegion::region_size_bytes()) {
 673     return allocate_large_memory(word_size);
 674   }
 675 
 676   // Not enough memory in free region set.
 677   // Coming out of full GC, it is possible that there is not
 678   // free region available, so current_index may not be valid.
 679   if (word_size * HeapWordSize > _free_regions->capacity()) return NULL;
 680 
 681   ShenandoahHeapRegion* my_current_region = _free_regions->current_no_humongous();
 682 
 683   if (my_current_region == NULL) {
 684     return NULL; // No more room to make a new region. OOM.
 685   }
 686   assert(my_current_region != NULL, "should have a region at this point");
 687 
 688 #ifdef ASSERT
 689   if (in_collection_set(my_current_region)) {
 690     print_heap_regions();
 691   }
 692 #endif
 693   assert(! in_collection_set(my_current_region), "never get targetted regions in free-lists");
 694   assert(! my_current_region->is_humongous(), "never attempt to allocate from humongous object regions");
 695 
 696   HeapWord* result = my_current_region->allocate(word_size);
 697 
 698   while (result == NULL) {
 699     // 2nd attempt. Try next region.
 700     _free_regions->increase_used(my_current_region->free());
 701     ShenandoahHeapRegion* next_region = _free_regions->next_no_humongous();
 702     assert(next_region != my_current_region, "must not get current again");
 703     my_current_region = next_region;
 704 
 705     if (my_current_region == NULL) {
 706       return NULL; // No more room to make a new region. OOM.
 707     }
 708     assert(my_current_region != NULL, "should have a region at this point");
 709     assert(! in_collection_set(my_current_region), "never get targetted regions in free-lists");
 710     assert(! my_current_region->is_humongous(), "never attempt to allocate from humongous object regions");
 711     result = my_current_region->allocate(word_size);
 712   }
 713 
 714   my_current_region->increase_live_data_words(word_size);
 715   increase_used(word_size * HeapWordSize);
 716   _free_regions->increase_used(word_size * HeapWordSize);
 717   return result;
 718 }
 719 
 720 HeapWord* ShenandoahHeap::allocate_large_memory(size_t words) {
 721   assert_heaplock_owned_by_current_thread();
 722 
 723   size_t required_regions = ShenandoahHumongous::required_regions(words * HeapWordSize);
 724   if (required_regions > _max_regions) return NULL;
 725 
 726   ShenandoahHeapRegion* r = _free_regions->allocate_contiguous(required_regions);
 727 
 728   HeapWord* result = NULL;
 729 
 730   if (r != NULL)  {
 731     result = r->bottom();
 732 
 733     log_debug(gc, humongous)("allocating humongous object of size: "SIZE_FORMAT" KB at location "PTR_FORMAT" in start region "SIZE_FORMAT,
 734                              (words * HeapWordSize) / K, p2i(result), r->region_number());
 735   } else {
 736     log_debug(gc, humongous)("allocating humongous object of size: "SIZE_FORMAT" KB at location "PTR_FORMAT" failed",
 737                              (words * HeapWordSize) / K, p2i(result));
 738   }
 739 
 740 
 741   return result;
 742 
 743 }
 744 
 745 HeapWord*  ShenandoahHeap::mem_allocate(size_t size,
 746                                         bool*  gc_overhead_limit_was_exceeded) {
 747 
 748   HeapWord* filler = allocate_memory(size + BrooksPointer::word_size(), false);
 749   HeapWord* result = filler + BrooksPointer::word_size();
 750   if (filler != NULL) {
 751     BrooksPointer::initialize(oop(result));
 752     _bytes_allocated_since_cm += size * HeapWordSize;
 753 
 754     assert(! in_collection_set(result), "never allocate in targetted region");
 755     return result;
 756   } else {
 757     /*
 758     tty->print_cr("Out of memory. Requested number of words: "SIZE_FORMAT" used heap: "INT64_FORMAT", bytes allocated since last CM: "INT64_FORMAT,
 759                   size, used(), _bytes_allocated_since_cm);
 760     {
 761       print_heap_regions();
 762       tty->print("Printing "SIZE_FORMAT" free regions:\n", _free_regions->count());
 763       _free_regions->print();
 764     }
 765     */
 766     return NULL;
 767   }
 768 }
 769 
 770 class ParallelEvacuateRegionObjectClosure : public ObjectClosure {
 771 private:
 772   ShenandoahHeap* _heap;
 773   Thread* _thread;
 774   public:
 775   ParallelEvacuateRegionObjectClosure(ShenandoahHeap* heap) :
 776     _heap(heap), _thread(Thread::current()) {
 777   }
 778 
 779   void do_object(oop p) {
 780 
 781     log_develop_trace(gc, compaction)("Calling ParallelEvacuateRegionObjectClosure on "PTR_FORMAT" of size %d\n", p2i((HeapWord*) p), p->size());
 782 
 783     assert(_heap->is_marked_complete(p), "expect only marked objects");
 784     if (oopDesc::unsafe_equals(p, ShenandoahBarrierSet::resolve_oop_static_not_null(p))) {
 785       bool evac;
 786       _heap->evacuate_object(p, _thread, evac);
 787     }
 788   }
 789 };
 790 
 791 #ifdef ASSERT
 792 class VerifyEvacuatedObjectClosure : public ObjectClosure {
 793 
 794 public:
 795 
 796   void do_object(oop p) {
 797     if (ShenandoahHeap::heap()->is_marked_complete(p)) {
 798       oop p_prime = oopDesc::bs()->read_barrier(p);
 799       assert(! oopDesc::unsafe_equals(p, p_prime), "Should point to evacuated copy");
 800       if (p->klass() != p_prime->klass()) {
 801         tty->print_cr("copy has different class than original:");
 802         p->klass()->print_on(tty);
 803         p_prime->klass()->print_on(tty);
 804       }
 805       assert(p->klass() == p_prime->klass(), "Should have the same class p: "PTR_FORMAT", p_prime: "PTR_FORMAT, p2i(p), p2i(p_prime));
 806       //      assert(p->mark() == p_prime->mark(), "Should have the same mark");
 807       assert(p->size() == p_prime->size(), "Should be the same size");
 808       assert(oopDesc::unsafe_equals(p_prime, oopDesc::bs()->read_barrier(p_prime)), "One forward once");
 809     }
 810   }
 811 };
 812 
 813 void ShenandoahHeap::verify_evacuated_region(ShenandoahHeapRegion* from_region) {
 814   VerifyEvacuatedObjectClosure verify_evacuation;
 815   marked_object_iterate(from_region, &verify_evacuation);
 816 }
 817 #endif
 818 
 819 void ShenandoahHeap::parallel_evacuate_region(ShenandoahHeapRegion* from_region) {
 820 
 821   assert(from_region->has_live(), "all-garbage regions are reclaimed earlier");
 822 
 823   ParallelEvacuateRegionObjectClosure evacuate_region(this);
 824 
 825   marked_object_iterate(from_region, &evacuate_region);
 826 
 827 #ifdef ASSERT
 828   if (ShenandoahVerify && ! cancelled_concgc()) {
 829     verify_evacuated_region(from_region);
 830   }
 831 #endif
 832 }
 833 
 834 class ParallelEvacuationTask : public AbstractGangTask {
 835 private:
 836   ShenandoahHeap* _sh;
 837   ShenandoahCollectionSet* _cs;
 838 
 839 public:
 840   ParallelEvacuationTask(ShenandoahHeap* sh,
 841                          ShenandoahCollectionSet* cs) :
 842     AbstractGangTask("Parallel Evacuation Task"),
 843     _cs(cs),
 844     _sh(sh) {}
 845 
 846   void work(uint worker_id) {
 847 
 848     ShenandoahHeapRegion* from_hr = _cs->claim_next();
 849 
 850     while (from_hr != NULL) {
 851       log_develop_trace(gc, region)("Thread "INT32_FORMAT" claimed Heap Region "SIZE_FORMAT,
 852                                     worker_id,
 853                                     from_hr->region_number());
 854 
 855       assert(from_hr->has_live(), "all-garbage regions are reclaimed early");
 856       _sh->parallel_evacuate_region(from_hr);
 857 
 858       if (_sh->cancelled_concgc()) {
 859         log_develop_trace(gc, region)("Cancelled concgc while evacuating region " SIZE_FORMAT "\n", from_hr->region_number());
 860         break;
 861       }
 862       from_hr = _cs->claim_next();
 863     }
 864   }
 865 };
 866 
 867 class RecycleDirtyRegionsClosure: public ShenandoahHeapRegionClosure {
 868 private:
 869   ShenandoahHeap* _heap;
 870   size_t _bytes_reclaimed;
 871 public:
 872   RecycleDirtyRegionsClosure() : _heap(ShenandoahHeap::heap()) {}
 873 
 874   bool doHeapRegion(ShenandoahHeapRegion* r) {
 875 
 876     assert (! _heap->cancelled_concgc(), "no recycling after cancelled marking");
 877 
 878     if (_heap->in_collection_set(r)) {
 879       log_develop_trace(gc, region)("Recycling region " SIZE_FORMAT ":", r->region_number());
 880       _heap->decrease_used(r->used());
 881       _bytes_reclaimed += r->used();
 882       r->recycle();
 883     }
 884 
 885     return false;
 886   }
 887   size_t bytes_reclaimed() { return _bytes_reclaimed;}
 888   void clear_bytes_reclaimed() {_bytes_reclaimed = 0;}
 889 };
 890 
 891 void ShenandoahHeap::recycle_dirty_regions() {
 892   RecycleDirtyRegionsClosure cl;
 893   cl.clear_bytes_reclaimed();
 894 
 895   heap_region_iterate(&cl);
 896 
 897   _shenandoah_policy->record_bytes_reclaimed(cl.bytes_reclaimed());
 898   if (! cancelled_concgc()) {
 899     clear_cset_fast_test();
 900   }
 901 }
 902 
 903 ShenandoahFreeSet* ShenandoahHeap::free_regions() {
 904   return _free_regions;
 905 }
 906 
 907 void ShenandoahHeap::print_heap_regions(outputStream* st) const {
 908   _ordered_regions->print(st);
 909 }
 910 
 911 class PrintAllRefsOopClosure: public ExtendedOopClosure {
 912 private:
 913   int _index;
 914   const char* _prefix;
 915 
 916 public:
 917   PrintAllRefsOopClosure(const char* prefix) : _index(0), _prefix(prefix) {}
 918 
 919 private:
 920   template <class T>
 921   inline void do_oop_work(T* p) {
 922     oop o = oopDesc::load_decode_heap_oop(p);
 923     if (o != NULL) {
 924       if (ShenandoahHeap::heap()->is_in(o) && o->is_oop()) {
 925         tty->print_cr("%s "INT32_FORMAT" ("PTR_FORMAT")-> "PTR_FORMAT" (marked: %s) (%s "PTR_FORMAT")",
 926                       _prefix, _index,
 927                       p2i(p), p2i(o),
 928                       BOOL_TO_STR(ShenandoahHeap::heap()->is_marked_complete(o)),
 929                       o->klass()->internal_name(), p2i(o->klass()));
 930       } else {
 931         tty->print_cr("%s "INT32_FORMAT" ("PTR_FORMAT" dirty -> "PTR_FORMAT" (not in heap, possibly corrupted or dirty)",
 932                       _prefix, _index,
 933                       p2i(p), p2i(o));
 934       }
 935     } else {
 936       tty->print_cr("%s "INT32_FORMAT" ("PTR_FORMAT") -> "PTR_FORMAT, _prefix, _index, p2i(p), p2i((HeapWord*) o));
 937     }
 938     _index++;
 939   }
 940 
 941 public:
 942   void do_oop(oop* p) {
 943     do_oop_work(p);
 944   }
 945 
 946   void do_oop(narrowOop* p) {
 947     do_oop_work(p);
 948   }
 949 
 950 };
 951 
 952 class PrintAllRefsObjectClosure : public ObjectClosure {
 953   const char* _prefix;
 954 
 955 public:
 956   PrintAllRefsObjectClosure(const char* prefix) : _prefix(prefix) {}
 957 
 958   void do_object(oop p) {
 959     if (ShenandoahHeap::heap()->is_in(p)) {
 960         tty->print_cr("%s object "PTR_FORMAT" (marked: %s) (%s "PTR_FORMAT") refers to:",
 961                       _prefix, p2i(p),
 962                       BOOL_TO_STR(ShenandoahHeap::heap()->is_marked_complete(p)),
 963                       p->klass()->internal_name(), p2i(p->klass()));
 964         PrintAllRefsOopClosure cl(_prefix);
 965         p->oop_iterate(&cl);
 966       }
 967   }
 968 };
 969 
 970 void ShenandoahHeap::print_all_refs(const char* prefix) {
 971   tty->print_cr("printing all references in the heap");
 972   tty->print_cr("root references:");
 973 
 974   ensure_parsability(false);
 975 
 976   PrintAllRefsOopClosure cl(prefix);
 977   roots_iterate(&cl);
 978 
 979   tty->print_cr("heap references:");
 980   PrintAllRefsObjectClosure cl2(prefix);
 981   object_iterate(&cl2);
 982 }
 983 
 984 class VerifyAfterMarkingOopClosure: public ExtendedOopClosure {
 985 private:
 986   ShenandoahHeap*  _heap;
 987 
 988 public:
 989   VerifyAfterMarkingOopClosure() :
 990     _heap(ShenandoahHeap::heap()) { }
 991 
 992 private:
 993   template <class T>
 994   inline void do_oop_work(T* p) {
 995     oop o = oopDesc::load_decode_heap_oop(p);
 996     if (o != NULL) {
 997       if (! _heap->is_marked_complete(o)) {
 998         _heap->print_heap_regions();
 999         _heap->print_all_refs("post-mark");
1000         tty->print_cr("oop not marked, although referrer is marked: "PTR_FORMAT": in_heap: %s, is_marked: %s",
1001                       p2i((HeapWord*) o), BOOL_TO_STR(_heap->is_in(o)), BOOL_TO_STR(_heap->is_marked_complete(o)));
1002         _heap->print_heap_locations((HeapWord*) o, (HeapWord*) o + o->size());
1003 
1004         tty->print_cr("oop class: %s", o->klass()->internal_name());
1005         if (_heap->is_in(p)) {
1006           oop referrer = oop(_heap->heap_region_containing(p)->block_start_const(p));
1007           tty->print_cr("Referrer starts at addr "PTR_FORMAT, p2i((HeapWord*) referrer));
1008           referrer->print();
1009           _heap->print_heap_locations((HeapWord*) referrer, (HeapWord*) referrer + referrer->size());
1010         }
1011         tty->print_cr("heap region containing object:");
1012         _heap->heap_region_containing(o)->print();
1013         tty->print_cr("heap region containing referrer:");
1014         _heap->heap_region_containing(p)->print();
1015         tty->print_cr("heap region containing forwardee:");
1016         _heap->heap_region_containing(oopDesc::bs()->read_barrier(o))->print();
1017       }
1018       assert(o->is_oop(), "oop must be an oop");
1019       assert(Metaspace::contains(o->klass()), "klass pointer must go to metaspace");
1020       if (! oopDesc::unsafe_equals(o, oopDesc::bs()->read_barrier(o))) {
1021         tty->print_cr("oops has forwardee: p: "PTR_FORMAT" (%s), o = "PTR_FORMAT" (%s), new-o: "PTR_FORMAT" (%s)",
1022                       p2i(p),
1023                       BOOL_TO_STR(_heap->in_collection_set(p)),
1024                       p2i(o),
1025                       BOOL_TO_STR(_heap->in_collection_set(o)),
1026                       p2i((HeapWord*) oopDesc::bs()->read_barrier(o)),
1027                       BOOL_TO_STR(_heap->in_collection_set(oopDesc::bs()->read_barrier(o))));
1028         tty->print_cr("oop class: %s", o->klass()->internal_name());
1029       }
1030       assert(oopDesc::unsafe_equals(o, oopDesc::bs()->read_barrier(o)), "oops must not be forwarded");
1031       assert(! _heap->in_collection_set(o), "references must not point to dirty heap regions");
1032       assert(_heap->is_marked_complete(o), "live oops must be marked current");
1033     }
1034   }
1035 
1036 public:
1037   void do_oop(oop* p) {
1038     do_oop_work(p);
1039   }
1040 
1041   void do_oop(narrowOop* p) {
1042     do_oop_work(p);
1043   }
1044 
1045 };
1046 
1047 void ShenandoahHeap::verify_heap_after_marking() {
1048 
1049   verify_heap_size_consistency();
1050 
1051   log_trace(gc)("verifying heap after marking");
1052 
1053   VerifyAfterMarkingOopClosure cl;
1054   roots_iterate(&cl);
1055   ObjectToOopClosure objs(&cl);
1056   object_iterate(&objs);
1057 }
1058 
1059 
1060 void ShenandoahHeap::reclaim_humongous_region_at(ShenandoahHeapRegion* r) {
1061   assert(r->is_humongous_start(), "reclaim regions starting with the first one");
1062 
1063   oop humongous_obj = oop(r->bottom() + BrooksPointer::word_size());
1064   size_t size = humongous_obj->size() + BrooksPointer::word_size();
1065   size_t required_regions = ShenandoahHumongous::required_regions(size * HeapWordSize);
1066   size_t index = r->region_number();
1067 
1068 
1069   assert(!r->has_live(), "liveness must be zero");
1070 
1071   for(size_t i = 0; i < required_regions; i++) {
1072 
1073     ShenandoahHeapRegion* region = _ordered_regions->get(index++);
1074 
1075     assert((region->is_humongous_start() || region->is_humongous_continuation()),
1076            "expect correct humongous start or continuation");
1077 
1078     if (log_is_enabled(Debug, gc, humongous)) {
1079       log_debug(gc, humongous)("reclaiming "SIZE_FORMAT" humongous regions for object of size: "SIZE_FORMAT" words", required_regions, size);
1080       ResourceMark rm;
1081       outputStream* out = Log(gc, humongous)::debug_stream();
1082       region->print_on(out);
1083     }
1084 
1085     region->recycle();
1086     ShenandoahHeap::heap()->decrease_used(ShenandoahHeapRegion::region_size_bytes());
1087   }
1088 }
1089 
1090 class ShenandoahReclaimHumongousRegionsClosure : public ShenandoahHeapRegionClosure {
1091 
1092   bool doHeapRegion(ShenandoahHeapRegion* r) {
1093     ShenandoahHeap* heap = ShenandoahHeap::heap();
1094 
1095     if (r->is_humongous_start()) {
1096       oop humongous_obj = oop(r->bottom() + BrooksPointer::word_size());
1097       if (! heap->is_marked_complete(humongous_obj)) {
1098 
1099         heap->reclaim_humongous_region_at(r);
1100       }
1101     }
1102     return false;
1103   }
1104 };
1105 
1106 #ifdef ASSERT
1107 class CheckCollectionSetClosure: public ShenandoahHeapRegionClosure {
1108   bool doHeapRegion(ShenandoahHeapRegion* r) {
1109     assert(! ShenandoahHeap::heap()->in_collection_set(r), "Should have been cleared by now");
1110     return false;
1111   }
1112 };
1113 #endif
1114 
1115 void ShenandoahHeap::prepare_for_concurrent_evacuation() {
1116   assert(_ordered_regions->get(0)->region_number() == 0, "FIXME CHF. FIXME CHF!");
1117 
1118   log_develop_trace(gc)("Thread %d started prepare_for_concurrent_evacuation", Thread::current()->osthread()->thread_id());
1119 
1120   if (!cancelled_concgc()) {
1121 
1122     recycle_dirty_regions();
1123 
1124     ensure_parsability(true);
1125 
1126     if (UseShenandoahMatrix && PrintShenandoahMatrix) {
1127       outputStream* log = Log(gc)::info_stream();
1128       connection_matrix()->print_on(log);
1129     }
1130 
1131     if (ShenandoahVerify || (UseShenandoahMatrix && VerifyShenandoahMatrix)) {
1132       verify_heap_reachable_at_safepoint();
1133     }
1134 
1135 #ifdef ASSERT
1136     if (ShenandoahVerify) {
1137       verify_heap_after_marking();
1138     }
1139 #endif
1140 
1141     // NOTE: This needs to be done during a stop the world pause, because
1142     // putting regions into the collection set concurrently with Java threads
1143     // will create a race. In particular, acmp could fail because when we
1144     // resolve the first operand, the containing region might not yet be in
1145     // the collection set, and thus return the original oop. When the 2nd
1146     // operand gets resolved, the region could be in the collection set
1147     // and the oop gets evacuated. If both operands have originally been
1148     // the same, we get false negatives.
1149 
1150     {
1151       ShenandoahHeapLock lock(this);
1152       _collection_set->clear();
1153       _free_regions->clear();
1154 
1155       ShenandoahReclaimHumongousRegionsClosure reclaim;
1156       heap_region_iterate(&reclaim);
1157 
1158 #ifdef ASSERT
1159       CheckCollectionSetClosure ccsc;
1160       _ordered_regions->heap_region_iterate(&ccsc);
1161 #endif
1162 
1163       _shenandoah_policy->choose_collection_set(_collection_set);
1164 
1165       _shenandoah_policy->choose_free_set(_free_regions);
1166     }
1167 
1168     _bytes_allocated_since_cm = 0;
1169 
1170     Universe::update_heap_info_at_gc();
1171   }
1172 }
1173 
1174 
1175 class RetireTLABClosure : public ThreadClosure {
1176 private:
1177   bool _retire;
1178 
1179 public:
1180   RetireTLABClosure(bool retire) : _retire(retire) {
1181   }
1182 
1183   void do_thread(Thread* thread) {
1184     thread->gclab().make_parsable(_retire);
1185   }
1186 };
1187 
1188 void ShenandoahHeap::ensure_parsability(bool retire_tlabs) {
1189   if (UseTLAB) {
1190     CollectedHeap::ensure_parsability(retire_tlabs);
1191     RetireTLABClosure cl(retire_tlabs);
1192     Threads::threads_do(&cl);
1193   }
1194 }
1195 
1196 class ShenandoahEvacuateUpdateRootsClosure: public ExtendedOopClosure {
1197 private:
1198   ShenandoahHeap* _heap;
1199   Thread* _thread;
1200 public:
1201   ShenandoahEvacuateUpdateRootsClosure() :
1202     _heap(ShenandoahHeap::heap()), _thread(Thread::current()) {
1203   }
1204 
1205 private:
1206   template <class T>
1207   void do_oop_work(T* p) {
1208     assert(_heap->is_evacuation_in_progress(), "Only do this when evacuation is in progress");
1209 
1210     T o = oopDesc::load_heap_oop(p);
1211     if (! oopDesc::is_null(o)) {
1212       oop obj = oopDesc::decode_heap_oop_not_null(o);
1213       if (_heap->in_collection_set(obj)) {
1214         assert(_heap->is_marked_complete(obj), "only evacuate marked objects %d %d",
1215                _heap->is_marked_complete(obj), _heap->is_marked_complete(ShenandoahBarrierSet::resolve_oop_static_not_null(obj)));
1216         oop resolved = ShenandoahBarrierSet::resolve_oop_static_not_null(obj);
1217         if (oopDesc::unsafe_equals(resolved, obj)) {
1218           bool evac;
1219           resolved = _heap->evacuate_object(obj, _thread, evac);
1220         }
1221         oopDesc::encode_store_heap_oop(p, resolved);
1222       }
1223     }
1224 #ifdef ASSERT
1225     else {
1226       // tty->print_cr("not updating root at: "PTR_FORMAT" with object: "PTR_FORMAT", is_in_heap: %s, is_in_cset: %s, is_marked: %s",
1227       //               p2i(p),
1228       //               p2i((HeapWord*) obj),
1229       //               BOOL_TO_STR(_heap->is_in(obj)),
1230       //               BOOL_TO_STR(_heap->in_cset_fast_test(obj)),
1231       //               BOOL_TO_STR(_heap->is_marked_complete(obj)));
1232     }
1233 #endif
1234   }
1235 
1236 public:
1237   void do_oop(oop* p) {
1238     do_oop_work(p);
1239   }
1240   void do_oop(narrowOop* p) {
1241     do_oop_work(p);
1242   }
1243 };
1244 
1245 class ShenandoahEvacuateUpdateRootsTask : public AbstractGangTask {
1246   ShenandoahRootEvacuator* _rp;
1247 public:
1248 
1249   ShenandoahEvacuateUpdateRootsTask(ShenandoahRootEvacuator* rp) :
1250     AbstractGangTask("Shenandoah evacuate and update roots"),
1251     _rp(rp)
1252   {
1253     // Nothing else to do.
1254   }
1255 
1256   void work(uint worker_id) {
1257     ShenandoahEvacuateUpdateRootsClosure cl;
1258     MarkingCodeBlobClosure blobsCl(&cl, CodeBlobToOopClosure::FixRelocations);
1259 
1260     _rp->process_evacuate_roots(&cl, &blobsCl, worker_id);
1261   }
1262 };
1263 
1264 class ShenandoahFixRootsTask : public AbstractGangTask {
1265   ShenandoahRootEvacuator* _rp;
1266 public:
1267 
1268   ShenandoahFixRootsTask(ShenandoahRootEvacuator* rp) :
1269     AbstractGangTask("Shenandoah update roots"),
1270     _rp(rp)
1271   {
1272     // Nothing else to do.
1273   }
1274 
1275   void work(uint worker_id) {
1276     SCMUpdateRefsClosure cl;
1277     MarkingCodeBlobClosure blobsCl(&cl, CodeBlobToOopClosure::FixRelocations);
1278 
1279     _rp->process_evacuate_roots(&cl, &blobsCl, worker_id);
1280   }
1281 };
1282 void ShenandoahHeap::evacuate_and_update_roots() {
1283 
1284   COMPILER2_PRESENT(DerivedPointerTable::clear());
1285 
1286   assert(SafepointSynchronize::is_at_safepoint(), "Only iterate roots while world is stopped");
1287 
1288   {
1289     ShenandoahRootEvacuator rp(this, workers()->active_workers(), ShenandoahCollectorPolicy::init_evac);
1290     ShenandoahEvacuateUpdateRootsTask roots_task(&rp);
1291     workers()->run_task(&roots_task);
1292   }
1293 
1294   COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
1295 
1296   if (cancelled_concgc()) {
1297     // If initial evacuation has been cancelled, we need to update all references
1298     // after all workers have finished. Otherwise we might run into the following problem:
1299     // GC thread 1 cannot allocate anymore, thus evacuation fails, leaves from-space ptr of object X.
1300     // GC thread 2 evacuates the same object X to to-space
1301     // which leaves a truly dangling from-space reference in the first root oop*. This must not happen.
1302     // clear() and update_pointers() must always be called in pairs,
1303     // cannot nest with above clear()/update_pointers().
1304     COMPILER2_PRESENT(DerivedPointerTable::clear());
1305     ShenandoahRootEvacuator rp(this, workers()->active_workers(), ShenandoahCollectorPolicy::init_evac);
1306     ShenandoahFixRootsTask update_roots_task(&rp);
1307     workers()->run_task(&update_roots_task);
1308     COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
1309   }
1310 
1311 #ifdef ASSERT
1312   {
1313     AssertToSpaceClosure cl;
1314     CodeBlobToOopClosure code_cl(&cl, !CodeBlobToOopClosure::FixRelocations);
1315     ShenandoahRootEvacuator rp(this, 1);
1316     rp.process_evacuate_roots(&cl, &code_cl, 0);
1317   }
1318 #endif
1319 }
1320 
1321 
1322 void ShenandoahHeap::do_evacuation() {
1323 
1324   parallel_evacuate();
1325 
1326   if (ShenandoahVerify && ! cancelled_concgc()) {
1327     VM_ShenandoahVerifyHeapAfterEvacuation verify_after_evacuation;
1328     if (Thread::current()->is_VM_thread()) {
1329       verify_after_evacuation.doit();
1330     } else {
1331       VMThread::execute(&verify_after_evacuation);
1332     }
1333   }
1334 
1335 }
1336 
1337 void ShenandoahHeap::parallel_evacuate() {
1338   log_develop_trace(gc)("starting parallel_evacuate");
1339 
1340   _shenandoah_policy->record_phase_start(ShenandoahCollectorPolicy::conc_evac);
1341 
1342   if (log_is_enabled(Trace, gc, region)) {
1343     ResourceMark rm;
1344     outputStream *out = Log(gc, region)::trace_stream();
1345     out->print("Printing all available regions");
1346     print_heap_regions(out);
1347   }
1348 
1349   if (log_is_enabled(Trace, gc, cset)) {
1350     ResourceMark rm;
1351     outputStream *out = Log(gc, cset)::trace_stream();
1352     out->print("Printing collection set which contains "SIZE_FORMAT" regions:\n", _collection_set->count());
1353     _collection_set->print(out);
1354 
1355     out->print("Printing free set which contains "SIZE_FORMAT" regions:\n", _free_regions->count());
1356     _free_regions->print(out);
1357   }
1358 
1359   ParallelEvacuationTask evacuationTask = ParallelEvacuationTask(this, _collection_set);
1360 
1361 
1362   workers()->run_task(&evacuationTask);
1363 
1364   if (log_is_enabled(Trace, gc, cset)) {
1365     ResourceMark rm;
1366     outputStream *out = Log(gc, cset)::trace_stream();
1367     out->print("Printing postgc collection set which contains "SIZE_FORMAT" regions:\n",
1368                _collection_set->count());
1369 
1370     _collection_set->print(out);
1371 
1372     out->print("Printing postgc free regions which contain "SIZE_FORMAT" free regions:\n",
1373                _free_regions->count());
1374     _free_regions->print(out);
1375 
1376   }
1377 
1378   if (log_is_enabled(Trace, gc, region)) {
1379     ResourceMark rm;
1380     outputStream *out = Log(gc, region)::trace_stream();
1381     out->print_cr("all regions after evacuation:");
1382     print_heap_regions(out);
1383   }
1384 
1385   _shenandoah_policy->record_phase_end(ShenandoahCollectorPolicy::conc_evac);
1386 }
1387 
1388 class VerifyEvacuationClosure: public ExtendedOopClosure {
1389 private:
1390   ShenandoahHeap*  _heap;
1391   ShenandoahHeapRegion* _from_region;
1392 
1393 public:
1394   VerifyEvacuationClosure(ShenandoahHeapRegion* from_region) :
1395     _heap(ShenandoahHeap::heap()), _from_region(from_region) { }
1396 private:
1397   template <class T>
1398   inline void do_oop_work(T* p) {
1399     oop heap_oop = oopDesc::load_decode_heap_oop(p);
1400     if (! oopDesc::is_null(heap_oop)) {
1401       guarantee(! _from_region->is_in(heap_oop), "no references to from-region allowed after evacuation: "PTR_FORMAT, p2i((HeapWord*) heap_oop));
1402     }
1403   }
1404 
1405 public:
1406   void do_oop(oop* p)       {
1407     do_oop_work(p);
1408   }
1409 
1410   void do_oop(narrowOop* p) {
1411     do_oop_work(p);
1412   }
1413 
1414 };
1415 
1416 void ShenandoahHeap::roots_iterate(OopClosure* cl) {
1417 
1418   assert(SafepointSynchronize::is_at_safepoint(), "Only iterate roots while world is stopped");
1419 
1420   CodeBlobToOopClosure blobsCl(cl, false);
1421   CLDToOopClosure cldCl(cl);
1422 
1423   ShenandoahRootProcessor rp(this, 1);
1424   rp.process_all_roots(cl, NULL, &cldCl, &blobsCl, 0);
1425 }
1426 
1427 void ShenandoahHeap::verify_evacuation(ShenandoahHeapRegion* from_region) {
1428 
1429   VerifyEvacuationClosure rootsCl(from_region);
1430   roots_iterate(&rootsCl);
1431 
1432 }
1433 
1434 bool ShenandoahHeap::supports_tlab_allocation() const {
1435   return true;
1436 }
1437 
1438 
1439 size_t  ShenandoahHeap::unsafe_max_tlab_alloc(Thread *thread) const {
1440   size_t idx = _free_regions->current_index();
1441   ShenandoahHeapRegion* current = _free_regions->get(idx);
1442   if (current == NULL) {
1443     return 0;
1444   } else if (current->free() > MinTLABSize) {
1445     // Current region has enough space left, can use it.
1446     return current->free();
1447   } else {
1448     // No more space in current region, we will take next free region
1449     // on the next TLAB allocation.
1450     return ShenandoahHeapRegion::region_size_bytes();
1451   }
1452 }
1453 
1454 size_t ShenandoahHeap::max_tlab_size() const {
1455   return ShenandoahHeapRegion::region_size_bytes();
1456 }
1457 
1458 class ResizeGCLABClosure : public ThreadClosure {
1459 public:
1460   void do_thread(Thread* thread) {
1461     thread->gclab().resize();
1462   }
1463 };
1464 
1465 void ShenandoahHeap::resize_all_tlabs() {
1466   CollectedHeap::resize_all_tlabs();
1467 
1468   ResizeGCLABClosure cl;
1469   Threads::threads_do(&cl);
1470 }
1471 
1472 class AccumulateStatisticsGCLABClosure : public ThreadClosure {
1473 public:
1474   void do_thread(Thread* thread) {
1475     thread->gclab().accumulate_statistics();
1476     thread->gclab().initialize_statistics();
1477   }
1478 };
1479 
1480 void ShenandoahHeap::accumulate_statistics_all_gclabs() {
1481   AccumulateStatisticsGCLABClosure cl;
1482   Threads::threads_do(&cl);
1483 }
1484 
1485 bool  ShenandoahHeap::can_elide_tlab_store_barriers() const {
1486   return true;
1487 }
1488 
1489 oop ShenandoahHeap::new_store_pre_barrier(JavaThread* thread, oop new_obj) {
1490   // Overridden to do nothing.
1491   return new_obj;
1492 }
1493 
1494 bool  ShenandoahHeap::can_elide_initializing_store_barrier(oop new_obj) {
1495   return true;
1496 }
1497 
1498 bool ShenandoahHeap::card_mark_must_follow_store() const {
1499   return false;
1500 }
1501 
1502 void ShenandoahHeap::collect(GCCause::Cause cause) {
1503   assert(cause != GCCause::_gc_locker, "no JNI critical callback");
1504   if (GCCause::is_user_requested_gc(cause)) {
1505     if (! DisableExplicitGC) {
1506       _concurrent_gc_thread->do_full_gc(cause);
1507     }
1508   } else if (cause == GCCause::_allocation_failure) {
1509     collector_policy()->set_should_clear_all_soft_refs(true);
1510     _concurrent_gc_thread->do_full_gc(cause);
1511   }
1512 }
1513 
1514 void ShenandoahHeap::do_full_collection(bool clear_all_soft_refs) {
1515   //assert(false, "Shouldn't need to do full collections");
1516 }
1517 
1518 AdaptiveSizePolicy* ShenandoahHeap::size_policy() {
1519   Unimplemented();
1520   return NULL;
1521 
1522 }
1523 
1524 CollectorPolicy* ShenandoahHeap::collector_policy() const {
1525   return _shenandoah_policy;
1526 }
1527 
1528 
1529 HeapWord* ShenandoahHeap::block_start(const void* addr) const {
1530   Space* sp = heap_region_containing(addr);
1531   if (sp != NULL) {
1532     return sp->block_start(addr);
1533   }
1534   return NULL;
1535 }
1536 
1537 size_t ShenandoahHeap::block_size(const HeapWord* addr) const {
1538   Space* sp = heap_region_containing(addr);
1539   assert(sp != NULL, "block_size of address outside of heap");
1540   return sp->block_size(addr);
1541 }
1542 
1543 bool ShenandoahHeap::block_is_obj(const HeapWord* addr) const {
1544   Space* sp = heap_region_containing(addr);
1545   return sp->block_is_obj(addr);
1546 }
1547 
1548 jlong ShenandoahHeap::millis_since_last_gc() {
1549   return 0;
1550 }
1551 
1552 void ShenandoahHeap::prepare_for_verify() {
1553   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
1554     ensure_parsability(false);
1555   }
1556 }
1557 
1558 void ShenandoahHeap::print_gc_threads_on(outputStream* st) const {
1559   workers()->print_worker_threads_on(st);
1560 }
1561 
1562 void ShenandoahHeap::gc_threads_do(ThreadClosure* tcl) const {
1563   workers()->threads_do(tcl);
1564 }
1565 
1566 void ShenandoahHeap::print_tracing_info() const {
1567   if (log_is_enabled(Info, gc, stats)) {
1568     ResourceMark rm;
1569     outputStream* out = Log(gc, stats)::info_stream();
1570     _shenandoah_policy->print_tracing_info(out);
1571   }
1572 }
1573 
1574 class ShenandoahVerifyRootsClosure: public ExtendedOopClosure {
1575 private:
1576   ShenandoahHeap*  _heap;
1577   VerifyOption     _vo;
1578   bool             _failures;
1579 public:
1580   // _vo == UsePrevMarking -> use "prev" marking information,
1581   // _vo == UseNextMarking -> use "next" marking information,
1582   // _vo == UseMarkWord    -> use mark word from object header.
1583   ShenandoahVerifyRootsClosure(VerifyOption vo) :
1584     _heap(ShenandoahHeap::heap()),
1585     _vo(vo),
1586     _failures(false) { }
1587 
1588   bool failures() { return _failures; }
1589 
1590 private:
1591   template <class T>
1592   inline void do_oop_work(T* p) {
1593     oop obj = oopDesc::load_decode_heap_oop(p);
1594     if (! oopDesc::is_null(obj) && ! obj->is_oop()) {
1595       { // Just for debugging.
1596         tty->print_cr("Root location "PTR_FORMAT
1597                       "verified "PTR_FORMAT, p2i(p), p2i((void*) obj));
1598         //      obj->print_on(tty);
1599       }
1600     }
1601     guarantee(obj->is_oop_or_null(), "is oop or null");
1602   }
1603 
1604 public:
1605   void do_oop(oop* p)       {
1606     do_oop_work(p);
1607   }
1608 
1609   void do_oop(narrowOop* p) {
1610     do_oop_work(p);
1611   }
1612 
1613 };
1614 
1615 class ShenandoahVerifyHeapClosure: public ObjectClosure {
1616 private:
1617   ShenandoahVerifyRootsClosure _rootsCl;
1618 public:
1619   ShenandoahVerifyHeapClosure(ShenandoahVerifyRootsClosure rc) :
1620     _rootsCl(rc) {};
1621 
1622   void do_object(oop p) {
1623     _rootsCl.do_oop(&p);
1624   }
1625 };
1626 
1627 void ShenandoahHeap::verify(VerifyOption vo) {
1628   if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
1629 
1630     ShenandoahVerifyRootsClosure rootsCl(vo);
1631 
1632     assert(Thread::current()->is_VM_thread(),
1633            "Expected to be executed serially by the VM thread at this point");
1634 
1635     roots_iterate(&rootsCl);
1636 
1637     bool failures = rootsCl.failures();
1638     log_trace(gc)("verify failures: %s", BOOL_TO_STR(failures));
1639 
1640     ShenandoahVerifyHeapClosure heapCl(rootsCl);
1641 
1642     object_iterate(&heapCl);
1643     // TODO: Implement rest of it.
1644   } else {
1645     tty->print("(SKIPPING roots, heapRegions, remset) ");
1646   }
1647 }
1648 size_t ShenandoahHeap::tlab_capacity(Thread *thr) const {
1649   return _free_regions->capacity();
1650 }
1651 
1652 class ShenandoahIterateObjectClosureRegionClosure: public ShenandoahHeapRegionClosure {
1653   ObjectClosure* _cl;
1654 public:
1655   ShenandoahIterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {}
1656   bool doHeapRegion(ShenandoahHeapRegion* r) {
1657     ShenandoahHeap::heap()->marked_object_iterate(r, _cl);
1658     return false;
1659   }
1660 };
1661 
1662 void ShenandoahHeap::object_iterate(ObjectClosure* cl) {
1663   ShenandoahIterateObjectClosureRegionClosure blk(cl);
1664   heap_region_iterate(&blk, false, true);
1665 }
1666 
1667 class ShenandoahSafeObjectIterateAdjustPtrsClosure : public MetadataAwareOopClosure {
1668 private:
1669   ShenandoahHeap* _heap;
1670 
1671 public:
1672   ShenandoahSafeObjectIterateAdjustPtrsClosure() : _heap(ShenandoahHeap::heap()) {}
1673 
1674 private:
1675   template <class T>
1676   inline void do_oop_work(T* p) {
1677     T o = oopDesc::load_heap_oop(p);
1678     if (!oopDesc::is_null(o)) {
1679       oop obj = oopDesc::decode_heap_oop_not_null(o);
1680       oopDesc::encode_store_heap_oop(p, BrooksPointer::forwardee(obj));
1681     }
1682   }
1683 public:
1684   void do_oop(oop* p) {
1685     do_oop_work(p);
1686   }
1687   void do_oop(narrowOop* p) {
1688     do_oop_work(p);
1689   }
1690 };
1691 
1692 class ShenandoahSafeObjectIterateAndUpdate : public ObjectClosure {
1693 private:
1694   ObjectClosure* _cl;
1695 public:
1696   ShenandoahSafeObjectIterateAndUpdate(ObjectClosure *cl) : _cl(cl) {}
1697 
1698   virtual void do_object(oop obj) {
1699     assert (oopDesc::unsafe_equals(obj, BrooksPointer::forwardee(obj)),
1700             "avoid double-counting: only non-forwarded objects here");
1701 
1702     // Fix up the ptrs.
1703     ShenandoahSafeObjectIterateAdjustPtrsClosure adjust_ptrs;
1704     obj->oop_iterate(&adjust_ptrs);
1705 
1706     // Can reply the object now:
1707     _cl->do_object(obj);
1708   }
1709 };
1710 
1711 void ShenandoahHeap::safe_object_iterate(ObjectClosure* cl) {
1712   assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints");
1713 
1714   // Safe iteration does objects only with correct references.
1715   // This is why we skip dirty regions that have stale copies of objects,
1716   // and fix up the pointers in the returned objects.
1717 
1718   ShenandoahSafeObjectIterateAndUpdate safe_cl(cl);
1719   ShenandoahIterateObjectClosureRegionClosure blk(&safe_cl);
1720   heap_region_iterate(&blk,
1721                       /* skip_dirty_regions = */ true,
1722                       /* skip_humongous_continuations = */ true);
1723 
1724   _need_update_refs = false; // already updated the references
1725 }
1726 
1727 // Apply blk->doHeapRegion() on all committed regions in address order,
1728 // terminating the iteration early if doHeapRegion() returns true.
1729 void ShenandoahHeap::heap_region_iterate(ShenandoahHeapRegionClosure* blk, bool skip_dirty_regions, bool skip_humongous_continuation) const {
1730   for (size_t i = 0; i < _num_regions; i++) {
1731     ShenandoahHeapRegion* current  = _ordered_regions->get(i);
1732     if (skip_humongous_continuation && current->is_humongous_continuation()) {
1733       continue;
1734     }
1735     if (skip_dirty_regions && in_collection_set(current)) {
1736       continue;
1737     }
1738     if (blk->doHeapRegion(current)) {
1739       return;
1740     }
1741   }
1742 }
1743 
1744 class ClearLivenessClosure : public ShenandoahHeapRegionClosure {
1745   ShenandoahHeap* sh;
1746 public:
1747   ClearLivenessClosure(ShenandoahHeap* heap) : sh(heap) { }
1748 
1749   bool doHeapRegion(ShenandoahHeapRegion* r) {
1750     r->clear_live_data();
1751     sh->set_next_top_at_mark_start(r->bottom(), r->top());
1752     return false;
1753   }
1754 };
1755 
1756 void ShenandoahHeap::start_concurrent_marking() {
1757 
1758   shenandoahPolicy()->record_phase_start(ShenandoahCollectorPolicy::accumulate_stats);
1759   accumulate_statistics_all_tlabs();
1760   shenandoahPolicy()->record_phase_end(ShenandoahCollectorPolicy::accumulate_stats);
1761 
1762   set_concurrent_mark_in_progress(true);
1763   // We need to reset all TLABs because we'd lose marks on all objects allocated in them.
1764   if (UseTLAB) {
1765     shenandoahPolicy()->record_phase_start(ShenandoahCollectorPolicy::make_parsable);
1766     ensure_parsability(true);
1767     shenandoahPolicy()->record_phase_end(ShenandoahCollectorPolicy::make_parsable);
1768   }
1769 
1770   _shenandoah_policy->record_bytes_allocated(_bytes_allocated_since_cm);
1771   _used_start_gc = used();
1772 
1773 #ifdef ASSERT
1774   if (ShenandoahDumpHeapBeforeConcurrentMark) {
1775     ensure_parsability(false);
1776     print_all_refs("pre-mark");
1777   }
1778 #endif
1779 
1780   shenandoahPolicy()->record_phase_start(ShenandoahCollectorPolicy::clear_liveness);
1781   ClearLivenessClosure clc(this);
1782   heap_region_iterate(&clc);
1783   shenandoahPolicy()->record_phase_end(ShenandoahCollectorPolicy::clear_liveness);
1784 
1785   if (UseShenandoahMatrix) {
1786     connection_matrix()->clear_all();
1787   }
1788   // print_all_refs("pre -mark");
1789 
1790   // oopDesc::_debug = true;
1791 
1792   // Make above changes visible to worker threads
1793   OrderAccess::fence();
1794 
1795   shenandoahPolicy()->record_phase_start(ShenandoahCollectorPolicy::scan_roots);
1796   concurrentMark()->init_mark_roots();
1797   shenandoahPolicy()->record_phase_end(ShenandoahCollectorPolicy::scan_roots);
1798 
1799   //  print_all_refs("pre-mark2");
1800 }
1801 
1802 class VerifyAfterEvacuationClosure : public ExtendedOopClosure {
1803 
1804   ShenandoahHeap* _sh;
1805 
1806 public:
1807   VerifyAfterEvacuationClosure() : _sh ( ShenandoahHeap::heap() ) {}
1808 
1809   template<class T> void do_oop_nv(T* p) {
1810     T heap_oop = oopDesc::load_heap_oop(p);
1811     if (!oopDesc::is_null(heap_oop)) {
1812       oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
1813       guarantee(_sh->in_collection_set(obj) == (! oopDesc::unsafe_equals(obj, oopDesc::bs()->read_barrier(obj))),
1814                 "forwarded objects can only exist in dirty (from-space) regions is_dirty: %s, is_forwarded: %s obj-klass: %s, marked: %s",
1815                 BOOL_TO_STR(_sh->in_collection_set(obj)),
1816                 BOOL_TO_STR(! oopDesc::unsafe_equals(obj, oopDesc::bs()->read_barrier(obj))),
1817                 obj->klass()->external_name(),
1818                 BOOL_TO_STR(_sh->is_marked_complete(obj))
1819                 );
1820       obj = oopDesc::bs()->read_barrier(obj);
1821       guarantee(! _sh->in_collection_set(obj), "forwarded oops must not point to dirty regions");
1822       guarantee(obj->is_oop(), "is_oop");
1823       guarantee(Metaspace::contains(obj->klass()), "klass pointer must go to metaspace");
1824     }
1825   }
1826 
1827   void do_oop(oop* p)       { do_oop_nv(p); }
1828   void do_oop(narrowOop* p) { do_oop_nv(p); }
1829 
1830 };
1831 
1832 void ShenandoahHeap::verify_heap_after_evacuation() {
1833 
1834   verify_heap_size_consistency();
1835 
1836   ensure_parsability(false);
1837 
1838   VerifyAfterEvacuationClosure cl;
1839   roots_iterate(&cl);
1840 
1841   ObjectToOopClosure objs(&cl);
1842   object_iterate(&objs);
1843 
1844 }
1845 
1846 void ShenandoahHeap::swap_mark_bitmaps() {
1847   // Swap bitmaps.
1848   CMBitMap* tmp1 = _complete_mark_bit_map;
1849   _complete_mark_bit_map = _next_mark_bit_map;
1850   _next_mark_bit_map = tmp1;
1851 
1852   // Swap top-at-mark-start pointers
1853   HeapWord** tmp2 = _complete_top_at_mark_starts;
1854   _complete_top_at_mark_starts = _next_top_at_mark_starts;
1855   _next_top_at_mark_starts = tmp2;
1856 
1857   HeapWord** tmp3 = _complete_top_at_mark_starts_base;
1858   _complete_top_at_mark_starts_base = _next_top_at_mark_starts_base;
1859   _next_top_at_mark_starts_base = tmp3;
1860 }
1861 
1862 class VerifyReachableHeapClosure : public ExtendedOopClosure {
1863 private:
1864   SCMObjToScanQueue* _queue;
1865   ShenandoahHeap* _heap;
1866   CMBitMap* _map;
1867   bool _check_matrix;
1868   oop _obj;
1869 public:
1870   VerifyReachableHeapClosure(SCMObjToScanQueue* queue, CMBitMap* map, bool check_matrix) :
1871           _queue(queue), _heap(ShenandoahHeap::heap()), _map(map), _check_matrix(check_matrix) {};
1872   template <class T>
1873   void do_oop_work(T* p) {
1874     T o = oopDesc::load_heap_oop(p);
1875     if (!oopDesc::is_null(o)) {
1876       oop obj = oopDesc::decode_heap_oop_not_null(o);
1877       guarantee(check_obj_alignment(obj), "sanity");
1878 
1879       guarantee(!oopDesc::is_null(obj), "sanity");
1880       guarantee(_heap->is_in(obj), "sanity");
1881 
1882       oop forw = BrooksPointer::forwardee(obj);
1883       guarantee(!oopDesc::is_null(forw), "sanity");
1884       guarantee(_heap->is_in(forw), "sanity");
1885 
1886       guarantee(oopDesc::unsafe_equals(obj, forw), "should not be forwarded");
1887 
1888       if (_check_matrix) {
1889         size_t from_idx = _heap->heap_region_index_containing(p);
1890         size_t to_idx = _heap->heap_region_index_containing(obj);
1891         if (!_heap->connection_matrix()->is_connected(from_idx, to_idx)) {
1892           tty->print_cr("from-obj: ");
1893           _obj->print_on(tty);
1894           tty->print_cr("to-obj:");
1895           obj->print_on(tty);
1896           tty->print_cr("from-obj allocated after mark: %s", BOOL_TO_STR(_heap->allocated_after_complete_mark_start((HeapWord*) _obj)));
1897           tty->print_cr("to-obj allocated after mark: %s", BOOL_TO_STR(_heap->allocated_after_complete_mark_start((HeapWord*) obj)));
1898           tty->print_cr("from-obj marked: %s", BOOL_TO_STR(_heap->is_marked_complete(_obj)));
1899           tty->print_cr("to-obj marked: %s", BOOL_TO_STR(_heap->is_marked_complete(obj)));
1900           tty->print_cr("from-idx: " SIZE_FORMAT ", to-idx: " SIZE_FORMAT, from_idx, to_idx);
1901 
1902           oop fwd_from = BrooksPointer::forwardee(_obj);
1903           oop fwd_to = BrooksPointer::forwardee(obj);
1904           tty->print_cr("from-obj forwardee: " PTR_FORMAT, p2i(fwd_from));
1905           tty->print_cr("to-obj forwardee: " PTR_FORMAT, p2i(fwd_to));
1906           tty->print_cr("forward(from-obj) marked: %s", BOOL_TO_STR(_heap->is_marked_complete(fwd_from)));
1907           tty->print_cr("forward(to-obj) marked: %s", BOOL_TO_STR(_heap->is_marked_complete(fwd_to)));
1908           size_t fwd_from_idx = _heap->heap_region_index_containing(fwd_from);
1909           size_t fwd_to_idx = _heap->heap_region_index_containing(fwd_to);
1910           tty->print_cr("forward(from-idx): " SIZE_FORMAT ", forward(to-idx): " SIZE_FORMAT, fwd_from_idx, fwd_to_idx);
1911           tty->print_cr("forward(from) connected with forward(to)? %s", BOOL_TO_STR(_heap->connection_matrix()->is_connected(fwd_from_idx, fwd_to_idx)));
1912         }
1913         guarantee(oopDesc::unsafe_equals(ShenandoahBarrierSet::resolve_oop_static_not_null(obj), obj), "polizeilich verboten");
1914         guarantee(_heap->connection_matrix()->is_connected(from_idx, to_idx), "must be connected");
1915       }
1916 
1917       if (_map->parMark((HeapWord*) obj)) {
1918         _queue->push(SCMTask(obj));
1919       }
1920     }
1921   }
1922 
1923   void do_oop(oop* p) { do_oop_work(p); }
1924   void do_oop(narrowOop* p) { do_oop_work(p); }
1925   void set_obj(oop o) { _obj = o; }
1926 };
1927 
1928 void ShenandoahHeap::verify_heap_reachable_at_safepoint() {
1929   guarantee(SafepointSynchronize::is_at_safepoint(), "only when nothing else happens");
1930   guarantee(ShenandoahVerify || (UseShenandoahMatrix && VerifyShenandoahMatrix),
1931             "only when these are enabled, and bitmap is initialized in ShenandoahHeap::initialize");
1932 
1933   OrderAccess::fence();
1934   ensure_parsability(false);
1935 
1936   // Allocate temporary bitmap for storing marking wavefront:
1937   MemRegion mr = MemRegion(_verification_bit_map.startWord(), _verification_bit_map.endWord());
1938   _verification_bit_map.clear_range_large(mr);
1939 
1940   // Initialize a single queue
1941   SCMObjToScanQueue* q = new SCMObjToScanQueue();
1942   q->initialize();
1943 
1944   // Scan root set
1945   ShenandoahRootProcessor rp(this, 1);
1946 
1947   {
1948     VerifyReachableHeapClosure cl(q, &_verification_bit_map, false);
1949     CLDToOopClosure cld_cl(&cl);
1950     CodeBlobToOopClosure code_cl(&cl, ! CodeBlobToOopClosure::FixRelocations);
1951     rp.process_all_roots(&cl, &cl, &cld_cl, &code_cl, 0);
1952   }
1953 
1954   // Finish the scan
1955   {
1956     VerifyReachableHeapClosure cl(q, &_verification_bit_map, UseShenandoahMatrix && VerifyShenandoahMatrix);
1957     SCMTask task;
1958     while ((q->pop_buffer(task) ||
1959             q->pop_local(task) ||
1960             q->pop_overflow(task))) {
1961       oop obj = task.obj();
1962       assert(!oopDesc::is_null(obj), "must not be null");
1963       cl.set_obj(obj);
1964       obj->oop_iterate(&cl);
1965     }
1966   }
1967 
1968   // Clean up!
1969   delete(q);
1970 }
1971 
1972 void ShenandoahHeap::stop_concurrent_marking() {
1973   assert(concurrent_mark_in_progress(), "How else could we get here?");
1974   if (! cancelled_concgc()) {
1975     // If we needed to update refs, and concurrent marking has been cancelled,
1976     // we need to finish updating references.
1977     set_need_update_refs(false);
1978     swap_mark_bitmaps();
1979   }
1980   set_concurrent_mark_in_progress(false);
1981 
1982   if (log_is_enabled(Trace, gc, region)) {
1983     ResourceMark rm;
1984     outputStream* out = Log(gc, region)::trace_stream();
1985     print_heap_regions(out);
1986   }
1987 
1988 }
1989 
1990 void ShenandoahHeap::set_concurrent_mark_in_progress(bool in_progress) {
1991   _concurrent_mark_in_progress = in_progress ? 1 : 0;
1992   JavaThread::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress);
1993 }
1994 
1995 void ShenandoahHeap::set_evacuation_in_progress_concurrently(bool in_progress) {
1996   // Note: it is important to first release the _evacuation_in_progress flag here,
1997   // so that Java threads can get out of oom_during_evacuation() and reach a safepoint,
1998   // in case a VM task is pending.
1999   set_evacuation_in_progress(in_progress);
2000   MutexLocker mu(Threads_lock);
2001   JavaThread::set_evacuation_in_progress_all_threads(in_progress);
2002 }
2003 
2004 void ShenandoahHeap::set_evacuation_in_progress_at_safepoint(bool in_progress) {
2005   assert(SafepointSynchronize::is_at_safepoint(), "Only call this at safepoint");
2006   set_evacuation_in_progress(in_progress);
2007   JavaThread::set_evacuation_in_progress_all_threads(in_progress);
2008 }
2009 
2010 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) {
2011   _evacuation_in_progress = in_progress ? 1 : 0;
2012   OrderAccess::fence();
2013 }
2014 
2015 void ShenandoahHeap::verify_copy(oop p,oop c){
2016     assert(! oopDesc::unsafe_equals(p, oopDesc::bs()->read_barrier(p)), "forwarded correctly");
2017     assert(oopDesc::unsafe_equals(oopDesc::bs()->read_barrier(p), c), "verify pointer is correct");
2018     if (p->klass() != c->klass()) {
2019       print_heap_regions();
2020     }
2021     assert(p->klass() == c->klass(), "verify class p-size: "INT32_FORMAT" c-size: "INT32_FORMAT, p->size(), c->size());
2022     assert(p->size() == c->size(), "verify size");
2023     // Object may have been locked between copy and verification
2024     //    assert(p->mark() == c->mark(), "verify mark");
2025     assert(oopDesc::unsafe_equals(c, oopDesc::bs()->read_barrier(c)), "verify only forwarded once");
2026   }
2027 
2028 void ShenandoahHeap::oom_during_evacuation() {
2029   log_develop_trace(gc)("Out of memory during evacuation, cancel evacuation, schedule full GC by thread %d",
2030                         Thread::current()->osthread()->thread_id());
2031 
2032   // We ran out of memory during evacuation. Cancel evacuation, and schedule a full-GC.
2033   collector_policy()->set_should_clear_all_soft_refs(true);
2034   concurrent_thread()->try_set_full_gc();
2035   cancel_concgc(_oom_evacuation);
2036 
2037   if ((! Thread::current()->is_GC_task_thread()) && (! Thread::current()->is_ConcurrentGC_thread())) {
2038     assert(! Threads_lock->owned_by_self()
2039            || SafepointSynchronize::is_at_safepoint(), "must not hold Threads_lock here");
2040     log_warning(gc)("OOM during evacuation. Let Java thread wait until evacuation finishes.");
2041     while (_evacuation_in_progress) { // wait.
2042       Thread::current()->_ParkEvent->park(1);
2043     }
2044   }
2045 
2046 }
2047 
2048 HeapWord* ShenandoahHeap::tlab_post_allocation_setup(HeapWord* obj) {
2049   // Initialize Brooks pointer for the next object
2050   HeapWord* result = obj + BrooksPointer::word_size();
2051   BrooksPointer::initialize(oop(result));
2052   return result;
2053 }
2054 
2055 uint ShenandoahHeap::oop_extra_words() {
2056   return BrooksPointer::word_size();
2057 }
2058 
2059 void ShenandoahHeap::grow_heap_by(size_t num_regions) {
2060   size_t old_num_regions = _num_regions;
2061   ensure_new_regions(num_regions);
2062   for (size_t i = 0; i < num_regions; i++) {
2063     size_t new_region_index = i + old_num_regions;
2064     HeapWord* start = ((HeapWord*) base()) + (ShenandoahHeapRegion::region_size_bytes() / HeapWordSize) * new_region_index;
2065     ShenandoahHeapRegion* new_region = new ShenandoahHeapRegion(this, start, ShenandoahHeapRegion::region_size_bytes() / HeapWordSize, new_region_index);
2066 
2067     if (log_is_enabled(Trace, gc, region)) {
2068       ResourceMark rm;
2069       outputStream* out = Log(gc, region)::trace_stream();
2070       out->print_cr("allocating new region at index: "SIZE_FORMAT, new_region_index);
2071       new_region->print_on(out);
2072     }
2073 
2074     assert(_ordered_regions->active_regions() == new_region->region_number(), "must match");
2075     _ordered_regions->add_region(new_region);
2076     _in_cset_fast_test_base[new_region_index] = false; // Not in cset
2077     _next_top_at_mark_starts_base[new_region_index] = new_region->bottom();
2078     _complete_top_at_mark_starts_base[new_region_index] = new_region->bottom();
2079 
2080     _free_regions->add_region(new_region);
2081   }
2082 }
2083 
2084 void ShenandoahHeap::ensure_new_regions(size_t new_regions) {
2085 
2086   size_t num_regions = _num_regions;
2087   size_t new_num_regions = num_regions + new_regions;
2088   assert(new_num_regions <= _max_regions, "we checked this earlier");
2089 
2090   size_t expand_size = new_regions * ShenandoahHeapRegion::region_size_bytes();
2091   log_trace(gc, region)("expanding storage by "SIZE_FORMAT_HEX" bytes, for "SIZE_FORMAT" new regions", expand_size, new_regions);
2092   bool success = _storage.expand_by(expand_size, ShenandoahAlwaysPreTouch);
2093   assert(success, "should always be able to expand by requested size");
2094 
2095   _num_regions = new_num_regions;
2096 
2097 }
2098 
2099 ShenandoahForwardedIsAliveClosure::ShenandoahForwardedIsAliveClosure() :
2100   _heap(ShenandoahHeap::heap_no_check()) {
2101 }
2102 
2103 void ShenandoahForwardedIsAliveClosure::init(ShenandoahHeap* heap) {
2104   _heap = heap;
2105 }
2106 
2107 bool ShenandoahForwardedIsAliveClosure::do_object_b(oop obj) {
2108 
2109   assert(_heap != NULL, "sanity");
2110   obj = ShenandoahBarrierSet::resolve_oop_static_not_null(obj);
2111 #ifdef ASSERT
2112   if (_heap->concurrent_mark_in_progress()) {
2113     assert(oopDesc::unsafe_equals(obj, ShenandoahBarrierSet::resolve_oop_static_not_null(obj)), "only query to-space");
2114   }
2115 #endif
2116   assert(!oopDesc::is_null(obj), "null");
2117   return _heap->is_marked_next(obj);
2118 }
2119 
2120 void ShenandoahHeap::ref_processing_init() {
2121   MemRegion mr = reserved_region();
2122 
2123   isAlive.init(ShenandoahHeap::heap());
2124   assert(_max_workers > 0, "Sanity");
2125 
2126   _ref_processor =
2127     new ReferenceProcessor(mr,    // span
2128                            ParallelRefProcEnabled,
2129                            // mt processing
2130                            _max_workers,
2131                            // degree of mt processing
2132                            true,
2133                            // mt discovery
2134                            _max_workers,
2135                            // degree of mt discovery
2136                            false,
2137                            // Reference discovery is not atomic
2138                            &isAlive);
2139 }
2140 
2141 size_t ShenandoahHeap::num_regions() {
2142   return _num_regions;
2143 }
2144 
2145 size_t ShenandoahHeap::max_regions() {
2146   return _max_regions;
2147 }
2148 
2149 GCTracer* ShenandoahHeap::tracer() {
2150   return shenandoahPolicy()->tracer();
2151 }
2152 
2153 size_t ShenandoahHeap::tlab_used(Thread* thread) const {
2154   return _free_regions->used();
2155 }
2156 
2157 void ShenandoahHeap::cancel_concgc(GCCause::Cause cause) {
2158   if (try_cancel_concgc()) {
2159     log_info(gc)("Cancelling concurrent GC: %s", GCCause::to_string(cause));
2160     _shenandoah_policy->report_concgc_cancelled();
2161   }
2162 }
2163 
2164 void ShenandoahHeap::cancel_concgc(ShenandoahCancelCause cause) {
2165   if (try_cancel_concgc()) {
2166     log_info(gc)("Cancelling concurrent GC: %s", cancel_cause_to_string(cause));
2167     _shenandoah_policy->report_concgc_cancelled();
2168   }
2169 }
2170 
2171 const char* ShenandoahHeap::cancel_cause_to_string(ShenandoahCancelCause cause) {
2172   switch (cause) {
2173     case _oom_evacuation:
2174       return "Out of memory for evacuation";
2175     case _vm_stop:
2176       return "Stopping VM";
2177     default:
2178       return "Unknown";
2179   }
2180 }
2181 
2182 uint ShenandoahHeap::max_workers() {
2183   return _max_workers;
2184 }
2185 
2186 void ShenandoahHeap::stop() {
2187   // The shutdown sequence should be able to terminate when GC is running.
2188 
2189   // Step 1. Notify control thread that we are in shutdown.
2190   // Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown.
2191   // Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below.
2192   _concurrent_gc_thread->prepare_for_graceful_shutdown();
2193 
2194   // Step 2. Notify GC workers that we are cancelling GC.
2195   cancel_concgc(_vm_stop);
2196 
2197   // Step 3. Wait until GC worker exits normally.
2198   _concurrent_gc_thread->stop();
2199 }
2200 
2201 void ShenandoahHeap::unload_classes_and_cleanup_tables() {
2202   ShenandoahForwardedIsAliveClosure is_alive;
2203   // Unload classes and purge SystemDictionary.
2204   bool purged_class = SystemDictionary::do_unloading(&is_alive, true);
2205   ParallelCleaningTask unlink_task(&is_alive, true, true, _workers->active_workers(), purged_class);
2206   _workers->run_task(&unlink_task);
2207   ClassLoaderDataGraph::purge();
2208 }
2209 
2210 void ShenandoahHeap::set_need_update_refs(bool need_update_refs) {
2211   _need_update_refs = need_update_refs;
2212 }
2213 
2214 //fixme this should be in heapregionset
2215 ShenandoahHeapRegion* ShenandoahHeap::next_compaction_region(const ShenandoahHeapRegion* r) {
2216   size_t region_idx = r->region_number() + 1;
2217   ShenandoahHeapRegion* next = _ordered_regions->get(region_idx);
2218   guarantee(next->region_number() == region_idx, "region number must match");
2219   while (next->is_humongous()) {
2220     region_idx = next->region_number() + 1;
2221     next = _ordered_regions->get(region_idx);
2222     guarantee(next->region_number() == region_idx, "region number must match");
2223   }
2224   return next;
2225 }
2226 
2227 void ShenandoahHeap::set_region_in_collection_set(size_t region_index, bool b) {
2228   _in_cset_fast_test_base[region_index] = b;
2229 }
2230 
2231 ShenandoahMonitoringSupport* ShenandoahHeap::monitoring_support() {
2232   return _monitoring_support;
2233 }
2234 
2235 CMBitMap* ShenandoahHeap::complete_mark_bit_map() {
2236   return _complete_mark_bit_map;
2237 }
2238 
2239 CMBitMap* ShenandoahHeap::next_mark_bit_map() {
2240   return _next_mark_bit_map;
2241 }
2242 
2243 void ShenandoahHeap::add_free_region(ShenandoahHeapRegion* r) {
2244   _free_regions->add_region(r);
2245 }
2246 
2247 void ShenandoahHeap::clear_free_regions() {
2248   _free_regions->clear();
2249 }
2250 
2251 address ShenandoahHeap::in_cset_fast_test_addr() {
2252   return (address) (ShenandoahHeap::heap()->_in_cset_fast_test);
2253 }
2254 
2255 address ShenandoahHeap::cancelled_concgc_addr() {
2256   return (address) &(ShenandoahHeap::heap()->_cancelled_concgc);
2257 }
2258 
2259 void ShenandoahHeap::clear_cset_fast_test() {
2260   assert(_in_cset_fast_test_base != NULL, "sanity");
2261   memset(_in_cset_fast_test_base, false,
2262          _in_cset_fast_test_length * sizeof(bool));
2263 }
2264 
2265 size_t ShenandoahHeap::conservative_max_heap_alignment() {
2266   return ShenandoahMaxRegionSize;
2267 }
2268 
2269 size_t ShenandoahHeap::bytes_allocated_since_cm() {
2270   return _bytes_allocated_since_cm;
2271 }
2272 
2273 void ShenandoahHeap::set_bytes_allocated_since_cm(size_t bytes) {
2274   _bytes_allocated_since_cm = bytes;
2275 }
2276 
2277 void ShenandoahHeap::set_next_top_at_mark_start(HeapWord* region_base, HeapWord* addr) {
2278   uintx index = ((uintx) region_base) >> ShenandoahHeapRegion::region_size_shift();
2279   _next_top_at_mark_starts[index] = addr;
2280 }
2281 
2282 HeapWord* ShenandoahHeap::next_top_at_mark_start(HeapWord* region_base) {
2283   uintx index = ((uintx) region_base) >> ShenandoahHeapRegion::region_size_shift();
2284   return _next_top_at_mark_starts[index];
2285 }
2286 
2287 void ShenandoahHeap::set_complete_top_at_mark_start(HeapWord* region_base, HeapWord* addr) {
2288   uintx index = ((uintx) region_base) >> ShenandoahHeapRegion::region_size_shift();
2289   _complete_top_at_mark_starts[index] = addr;
2290 }
2291 
2292 HeapWord* ShenandoahHeap::complete_top_at_mark_start(HeapWord* region_base) {
2293   uintx index = ((uintx) region_base) >> ShenandoahHeapRegion::region_size_shift();
2294   return _complete_top_at_mark_starts[index];
2295 }
2296 
2297 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) {
2298   _full_gc_in_progress = in_progress;
2299 }
2300 
2301 bool ShenandoahHeap::is_full_gc_in_progress() const {
2302   return _full_gc_in_progress;
2303 }
2304 
2305 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) {
2306   _update_refs_in_progress = in_progress;
2307 }
2308 
2309 bool ShenandoahHeap::is_update_refs_in_progress() const {
2310   return _update_refs_in_progress;
2311 }
2312 
2313 class NMethodOopInitializer : public OopClosure {
2314 private:
2315   ShenandoahHeap* _heap;
2316 public:
2317   NMethodOopInitializer() : _heap(ShenandoahHeap::heap()) {
2318   }
2319 
2320 private:
2321   template <class T>
2322   inline void do_oop_work(T* p) {
2323     T o = oopDesc::load_heap_oop(p);
2324     if (! oopDesc::is_null(o)) {
2325       oop obj1 = oopDesc::decode_heap_oop_not_null(o);
2326       oop obj2 = oopDesc::bs()->write_barrier(obj1);
2327       if (! oopDesc::unsafe_equals(obj1, obj2)) {
2328         oopDesc::encode_store_heap_oop(p, obj2);
2329       }
2330     }
2331   }
2332 
2333 public:
2334   void do_oop(oop* o) {
2335     do_oop_work(o);
2336   }
2337   void do_oop(narrowOop* o) {
2338     do_oop_work(o);
2339   }
2340 };
2341 
2342 void ShenandoahHeap::register_nmethod(nmethod* nm) {
2343   NMethodOopInitializer init;
2344   nm->oops_do(&init);
2345   nm->fix_oop_relocations();
2346 }
2347 
2348 void ShenandoahHeap::unregister_nmethod(nmethod* nm) {
2349 }
2350 
2351 void ShenandoahHeap::pin_object(oop o) {
2352   heap_region_containing(o)->pin();
2353 }
2354 
2355 void ShenandoahHeap::unpin_object(oop o) {
2356   heap_region_containing(o)->unpin();
2357 }
2358 
2359 
2360 GCTimer* ShenandoahHeap::gc_timer() const {
2361   return _gc_timer;
2362 }
2363 
2364 class ShenandoahCountGarbageClosure : public ShenandoahHeapRegionClosure {
2365 private:
2366   size_t _garbage;
2367 public:
2368   ShenandoahCountGarbageClosure() : _garbage(0) {
2369   }
2370 
2371   bool doHeapRegion(ShenandoahHeapRegion* r) {
2372     if (! r->is_humongous() && ! r->is_pinned() && ! r->in_collection_set()) {
2373       _garbage += r->garbage();
2374     }
2375     return false;
2376   }
2377 
2378   size_t garbage() {
2379     return _garbage;
2380   }
2381 };
2382 
2383 size_t ShenandoahHeap::garbage() {
2384   ShenandoahCountGarbageClosure cl;
2385   heap_region_iterate(&cl);
2386   return cl.garbage();
2387 }
2388 
2389 ShenandoahConnectionMatrix* ShenandoahHeap::connection_matrix() {
2390   return _connection_matrix;
2391 }
2392 
2393 ShenandoahPartialGC* ShenandoahHeap::partial_gc() {
2394   return _partial_gc;
2395 }
2396 
2397 void ShenandoahHeap::do_partial_collection() {
2398   partial_gc()->do_partial_collection();
2399 }
2400 
2401 template<class T>
2402 class ShenandoahUpdateHeapRefsTask : public AbstractGangTask {
2403 private:
2404   T cl;
2405   ShenandoahHeap* _heap;
2406   ShenandoahHeapRegionSet* _regions;
2407 
2408 public:
2409   ShenandoahUpdateHeapRefsTask() :
2410     AbstractGangTask("Concurrent Update References Task"),
2411     cl(T()),
2412     _heap(ShenandoahHeap::heap()),
2413     _regions(ShenandoahHeap::heap()->regions()) {
2414     _regions->clear_current_index();
2415   }
2416 
2417   void work(uint worker_id) {
2418     ShenandoahHeapRegion* r = _regions->claim_next();
2419     while (r != NULL && ! _heap->cancelled_concgc()) {
2420       if (! _heap->in_collection_set(r) &&
2421           ! r->is_empty()) {
2422         _heap->marked_object_oop_safe_iterate(r, &cl);
2423       } else if (_heap->in_collection_set(r)) {
2424         HeapWord* bottom = r->bottom();
2425         HeapWord* top = _heap->complete_top_at_mark_start(r->bottom());
2426         if (top > bottom) {
2427           _heap->complete_mark_bit_map()->clear_range_large(MemRegion(bottom, top));
2428         }
2429       }
2430       r = _regions->claim_next();
2431     }
2432   }
2433 };
2434 
2435 void ShenandoahHeap::concurrent_update_heap_references() {
2436   _shenandoah_policy->record_phase_start(ShenandoahCollectorPolicy::conc_update_refs);
2437   if (UseShenandoahMatrix) {
2438     ShenandoahUpdateHeapRefsTask<ShenandoahUpdateHeapRefsMatrixClosure> task;
2439     workers()->run_task(&task);
2440   } else {
2441     ShenandoahUpdateHeapRefsTask<ShenandoahUpdateHeapRefsClosure> task;
2442     workers()->run_task(&task);
2443   }
2444   _shenandoah_policy->record_phase_end(ShenandoahCollectorPolicy::conc_update_refs);
2445 }
2446 
2447 void ShenandoahHeap::prepare_update_refs() {
2448   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2449   set_evacuation_in_progress_at_safepoint(false);
2450   set_update_refs_in_progress(true);
2451   ensure_parsability(true);
2452   connection_matrix()->clear_all();
2453   for (uint i = 0; i < _num_regions; i++) {
2454     ShenandoahHeapRegion* r = _ordered_regions->get(i);
2455     r->set_concurrent_iteration_safe_limit(r->top());
2456   }
2457 }
2458 
2459 void ShenandoahHeap::finish_update_refs() {
2460   assert(SafepointSynchronize::is_at_safepoint(), "must be at safepoint");
2461 
2462   if (! cancelled_concgc()) {
2463     concurrentMark()->update_roots(ShenandoahCollectorPolicy::final_update_refs_roots);
2464     recycle_dirty_regions();
2465     set_need_update_refs(false);
2466 
2467     if (ShenandoahVerify) {
2468       verify_update_refs();
2469     }
2470 
2471     {
2472       // Rebuild the free set
2473       ShenandoahHeapLock hl(this);
2474       _free_regions->clear();
2475       size_t end = _ordered_regions->active_regions();
2476       for (size_t i = 0; i < end; i++) {
2477         ShenandoahHeapRegion* r = _ordered_regions->get(i);
2478         if (!r->is_humongous()) {
2479           assert (!in_collection_set(r), "collection set should be clear");
2480           _free_regions->add_region(r);
2481         }
2482       }
2483     }
2484   }
2485   set_update_refs_in_progress(false);
2486 }
2487 
2488 class ShenandoahVerifyUpdateRefsClosure : public ExtendedOopClosure {
2489 private:
2490   template <class T>
2491   void do_oop_work(T* p) {
2492     T o = oopDesc::load_heap_oop(p);
2493     if (! oopDesc::is_null(o)) {
2494       oop obj = oopDesc::decode_heap_oop_not_null(o);
2495       guarantee(oopDesc::unsafe_equals(obj, ShenandoahBarrierSet::resolve_oop_static_not_null(obj)),
2496                 "must not be forwarded");
2497     }
2498   }
2499 public:
2500   void do_oop(oop* p) { do_oop_work(p); }
2501   void do_oop(narrowOop* p) { do_oop_work(p); }
2502 };
2503 
2504 void ShenandoahHeap::verify_update_refs() {
2505 
2506   ensure_parsability(false);
2507 
2508   ShenandoahVerifyUpdateRefsClosure cl;
2509 
2510   // Verify roots.
2511   {
2512     CodeBlobToOopClosure blobsCl(&cl, false);
2513     CLDToOopClosure cldCl(&cl);
2514     ShenandoahRootProcessor rp(this, 1);
2515     rp.process_all_roots(&cl, &cl, &cldCl, &blobsCl, 0);
2516   }
2517 
2518   // Verify heap.
2519   for (uint i = 0; i < num_regions(); i++) {
2520     ShenandoahHeapRegion* r = regions()->get(i);
2521     marked_object_oop_iterate(r, &cl);
2522   }
2523 }
2524 
2525 #ifdef ASSERT
2526 void ShenandoahHeap::assert_heaplock_owned_by_current_thread() {
2527   assert(_heap_lock == locked, "must be locked");
2528   assert(_heap_lock_owner == Thread::current(), "must be owned by current thread");
2529 }
2530 
2531 void ShenandoahHeap::assert_heaplock_or_safepoint() {
2532   Thread* thr = Thread::current();
2533   assert((_heap_lock == locked && _heap_lock_owner == thr) ||
2534          (SafepointSynchronize::is_at_safepoint() && thr->is_VM_thread()),
2535   "must own heap lock or by VM thread at safepoint");
2536 }
2537 
2538 #endif