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