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