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