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