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