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