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