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