1 /* 2 * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved. 3 * Copyright (c) 2013, 2022, Red Hat, Inc. All rights reserved. 4 * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. 5 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 6 * 7 * This code is free software; you can redistribute it and/or modify it 8 * under the terms of the GNU General Public License version 2 only, as 9 * published by the Free Software Foundation. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 * 25 */ 26 27 #include "precompiled.hpp" 28 #include "memory/allocation.hpp" 29 #include "memory/universe.hpp" 30 31 #include "gc/shared/classUnloadingContext.hpp" 32 #include "gc/shared/gcArguments.hpp" 33 #include "gc/shared/gcTimer.hpp" 34 #include "gc/shared/gcTraceTime.inline.hpp" 35 #include "gc/shared/locationPrinter.inline.hpp" 36 #include "gc/shared/memAllocator.hpp" 37 #include "gc/shared/plab.hpp" 38 #include "gc/shared/tlab_globals.hpp" 39 40 #include "gc/shenandoah/heuristics/shenandoahOldHeuristics.hpp" 41 #include "gc/shenandoah/heuristics/shenandoahYoungHeuristics.hpp" 42 #include "gc/shenandoah/shenandoahAllocRequest.hpp" 43 #include "gc/shenandoah/shenandoahBarrierSet.hpp" 44 #include "gc/shenandoah/shenandoahClosures.inline.hpp" 45 #include "gc/shenandoah/shenandoahCollectionSet.hpp" 46 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp" 47 #include "gc/shenandoah/shenandoahConcurrentMark.hpp" 48 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp" 49 #include "gc/shenandoah/shenandoahControlThread.hpp" 50 #include "gc/shenandoah/shenandoahFreeSet.hpp" 51 #include "gc/shenandoah/shenandoahGenerationalEvacuationTask.hpp" 52 #include "gc/shenandoah/shenandoahGenerationalHeap.hpp" 53 #include "gc/shenandoah/shenandoahGlobalGeneration.hpp" 54 #include "gc/shenandoah/shenandoahPhaseTimings.hpp" 55 #include "gc/shenandoah/shenandoahHeap.inline.hpp" 56 #include "gc/shenandoah/shenandoahHeapRegion.inline.hpp" 57 #include "gc/shenandoah/shenandoahHeapRegionSet.hpp" 58 #include "gc/shenandoah/shenandoahInitLogger.hpp" 59 #include "gc/shenandoah/shenandoahMarkingContext.inline.hpp" 60 #include "gc/shenandoah/shenandoahMemoryPool.hpp" 61 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp" 62 #include "gc/shenandoah/shenandoahOldGeneration.hpp" 63 #include "gc/shenandoah/shenandoahOopClosures.inline.hpp" 64 #include "gc/shenandoah/shenandoahPacer.inline.hpp" 65 #include "gc/shenandoah/shenandoahPadding.hpp" 66 #include "gc/shenandoah/shenandoahParallelCleaning.inline.hpp" 67 #include "gc/shenandoah/shenandoahReferenceProcessor.hpp" 68 #include "gc/shenandoah/shenandoahRootProcessor.inline.hpp" 69 #include "gc/shenandoah/shenandoahScanRemembered.inline.hpp" 70 #include "gc/shenandoah/shenandoahSTWMark.hpp" 71 #include "gc/shenandoah/shenandoahUtils.hpp" 72 #include "gc/shenandoah/shenandoahVerifier.hpp" 73 #include "gc/shenandoah/shenandoahCodeRoots.hpp" 74 #include "gc/shenandoah/shenandoahVMOperations.hpp" 75 #include "gc/shenandoah/shenandoahWorkGroup.hpp" 76 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp" 77 #include "gc/shenandoah/shenandoahYoungGeneration.hpp" 78 #include "gc/shenandoah/mode/shenandoahGenerationalMode.hpp" 79 #include "gc/shenandoah/mode/shenandoahIUMode.hpp" 80 #include "gc/shenandoah/mode/shenandoahPassiveMode.hpp" 81 #include "gc/shenandoah/mode/shenandoahSATBMode.hpp" 82 #include "utilities/globalDefinitions.hpp" 83 84 #if INCLUDE_JFR 85 #include "gc/shenandoah/shenandoahJfrSupport.hpp" 86 #endif 87 88 #include "classfile/systemDictionary.hpp" 89 #include "code/codeCache.hpp" 90 #include "memory/classLoaderMetaspace.hpp" 91 #include "memory/metaspaceUtils.hpp" 92 #include "oops/compressedOops.inline.hpp" 93 #include "prims/jvmtiTagMap.hpp" 94 #include "runtime/atomic.hpp" 95 #include "runtime/globals.hpp" 96 #include "runtime/interfaceSupport.inline.hpp" 97 #include "runtime/java.hpp" 98 #include "runtime/orderAccess.hpp" 99 #include "runtime/safepointMechanism.hpp" 100 #include "runtime/vmThread.hpp" 101 #include "services/mallocTracker.hpp" 102 #include "services/memTracker.hpp" 103 #include "utilities/events.hpp" 104 #include "utilities/powerOfTwo.hpp" 105 106 class ShenandoahPretouchHeapTask : public WorkerTask { 107 private: 108 ShenandoahRegionIterator _regions; 109 const size_t _page_size; 110 public: 111 ShenandoahPretouchHeapTask(size_t page_size) : 112 WorkerTask("Shenandoah Pretouch Heap"), 113 _page_size(page_size) {} 114 115 virtual void work(uint worker_id) { 116 ShenandoahHeapRegion* r = _regions.next(); 117 while (r != nullptr) { 118 if (r->is_committed()) { 119 os::pretouch_memory(r->bottom(), r->end(), _page_size); 120 } 121 r = _regions.next(); 122 } 123 } 124 }; 125 126 class ShenandoahPretouchBitmapTask : public WorkerTask { 127 private: 128 ShenandoahRegionIterator _regions; 129 char* _bitmap_base; 130 const size_t _bitmap_size; 131 const size_t _page_size; 132 public: 133 ShenandoahPretouchBitmapTask(char* bitmap_base, size_t bitmap_size, size_t page_size) : 134 WorkerTask("Shenandoah Pretouch Bitmap"), 135 _bitmap_base(bitmap_base), 136 _bitmap_size(bitmap_size), 137 _page_size(page_size) {} 138 139 virtual void work(uint worker_id) { 140 ShenandoahHeapRegion* r = _regions.next(); 141 while (r != nullptr) { 142 size_t start = r->index() * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor(); 143 size_t end = (r->index() + 1) * ShenandoahHeapRegion::region_size_bytes() / MarkBitMap::heap_map_factor(); 144 assert (end <= _bitmap_size, "end is sane: " SIZE_FORMAT " < " SIZE_FORMAT, end, _bitmap_size); 145 146 if (r->is_committed()) { 147 os::pretouch_memory(_bitmap_base + start, _bitmap_base + end, _page_size); 148 } 149 150 r = _regions.next(); 151 } 152 } 153 }; 154 155 jint ShenandoahHeap::initialize() { 156 // 157 // Figure out heap sizing 158 // 159 160 size_t init_byte_size = InitialHeapSize; 161 size_t min_byte_size = MinHeapSize; 162 size_t max_byte_size = MaxHeapSize; 163 size_t heap_alignment = HeapAlignment; 164 165 size_t reg_size_bytes = ShenandoahHeapRegion::region_size_bytes(); 166 167 Universe::check_alignment(max_byte_size, reg_size_bytes, "Shenandoah heap"); 168 Universe::check_alignment(init_byte_size, reg_size_bytes, "Shenandoah heap"); 169 170 _num_regions = ShenandoahHeapRegion::region_count(); 171 assert(_num_regions == (max_byte_size / reg_size_bytes), 172 "Regions should cover entire heap exactly: " SIZE_FORMAT " != " SIZE_FORMAT "/" SIZE_FORMAT, 173 _num_regions, max_byte_size, reg_size_bytes); 174 175 size_t num_committed_regions = init_byte_size / reg_size_bytes; 176 num_committed_regions = MIN2(num_committed_regions, _num_regions); 177 assert(num_committed_regions <= _num_regions, "sanity"); 178 _initial_size = num_committed_regions * reg_size_bytes; 179 180 size_t num_min_regions = min_byte_size / reg_size_bytes; 181 num_min_regions = MIN2(num_min_regions, _num_regions); 182 assert(num_min_regions <= _num_regions, "sanity"); 183 _minimum_size = num_min_regions * reg_size_bytes; 184 185 // Default to max heap size. 186 _soft_max_size = _num_regions * reg_size_bytes; 187 188 _committed = _initial_size; 189 190 size_t heap_page_size = UseLargePages ? os::large_page_size() : os::vm_page_size(); 191 size_t bitmap_page_size = UseLargePages ? os::large_page_size() : os::vm_page_size(); 192 size_t region_page_size = UseLargePages ? os::large_page_size() : os::vm_page_size(); 193 194 // 195 // Reserve and commit memory for heap 196 // 197 198 ReservedHeapSpace heap_rs = Universe::reserve_heap(max_byte_size, heap_alignment); 199 initialize_reserved_region(heap_rs); 200 _heap_region = MemRegion((HeapWord*)heap_rs.base(), heap_rs.size() / HeapWordSize); 201 _heap_region_special = heap_rs.special(); 202 203 assert((((size_t) base()) & ShenandoahHeapRegion::region_size_bytes_mask()) == 0, 204 "Misaligned heap: " PTR_FORMAT, p2i(base())); 205 os::trace_page_sizes_for_requested_size("Heap", 206 max_byte_size, heap_rs.page_size(), heap_alignment, 207 heap_rs.base(), heap_rs.size()); 208 209 #if SHENANDOAH_OPTIMIZED_MARKTASK 210 // The optimized ShenandoahMarkTask takes some bits away from the full object bits. 211 // Fail if we ever attempt to address more than we can. 212 if ((uintptr_t)heap_rs.end() >= ShenandoahMarkTask::max_addressable()) { 213 FormatBuffer<512> buf("Shenandoah reserved [" PTR_FORMAT ", " PTR_FORMAT") for the heap, \n" 214 "but max object address is " PTR_FORMAT ". Try to reduce heap size, or try other \n" 215 "VM options that allocate heap at lower addresses (HeapBaseMinAddress, AllocateHeapAt, etc).", 216 p2i(heap_rs.base()), p2i(heap_rs.end()), ShenandoahMarkTask::max_addressable()); 217 vm_exit_during_initialization("Fatal Error", buf); 218 } 219 #endif 220 221 ReservedSpace sh_rs = heap_rs.first_part(max_byte_size); 222 if (!_heap_region_special) { 223 os::commit_memory_or_exit(sh_rs.base(), _initial_size, heap_alignment, false, 224 "Cannot commit heap memory"); 225 } 226 227 BarrierSet::set_barrier_set(new ShenandoahBarrierSet(this, _heap_region)); 228 229 // Now we know the number of regions and heap sizes, initialize the heuristics. 230 initialize_heuristics(); 231 232 assert(_heap_region.byte_size() == heap_rs.size(), "Need to know reserved size for card table"); 233 234 // 235 // Worker threads must be initialized after the barrier is configured 236 // 237 _workers = new ShenandoahWorkerThreads("Shenandoah GC Threads", _max_workers); 238 if (_workers == nullptr) { 239 vm_exit_during_initialization("Failed necessary allocation."); 240 } else { 241 _workers->initialize_workers(); 242 } 243 244 if (ParallelGCThreads > 1) { 245 _safepoint_workers = new ShenandoahWorkerThreads("Safepoint Cleanup Thread", ParallelGCThreads); 246 _safepoint_workers->initialize_workers(); 247 } 248 249 // 250 // Reserve and commit memory for bitmap(s) 251 // 252 253 size_t bitmap_size_orig = ShenandoahMarkBitMap::compute_size(heap_rs.size()); 254 _bitmap_size = align_up(bitmap_size_orig, bitmap_page_size); 255 256 size_t bitmap_bytes_per_region = reg_size_bytes / ShenandoahMarkBitMap::heap_map_factor(); 257 258 guarantee(bitmap_bytes_per_region != 0, 259 "Bitmap bytes per region should not be zero"); 260 guarantee(is_power_of_2(bitmap_bytes_per_region), 261 "Bitmap bytes per region should be power of two: " SIZE_FORMAT, bitmap_bytes_per_region); 262 263 if (bitmap_page_size > bitmap_bytes_per_region) { 264 _bitmap_regions_per_slice = bitmap_page_size / bitmap_bytes_per_region; 265 _bitmap_bytes_per_slice = bitmap_page_size; 266 } else { 267 _bitmap_regions_per_slice = 1; 268 _bitmap_bytes_per_slice = bitmap_bytes_per_region; 269 } 270 271 guarantee(_bitmap_regions_per_slice >= 1, 272 "Should have at least one region per slice: " SIZE_FORMAT, 273 _bitmap_regions_per_slice); 274 275 guarantee(((_bitmap_bytes_per_slice) % bitmap_page_size) == 0, 276 "Bitmap slices should be page-granular: bps = " SIZE_FORMAT ", page size = " SIZE_FORMAT, 277 _bitmap_bytes_per_slice, bitmap_page_size); 278 279 ReservedSpace bitmap(_bitmap_size, bitmap_page_size); 280 os::trace_page_sizes_for_requested_size("Mark Bitmap", 281 bitmap_size_orig, bitmap.page_size(), bitmap_page_size, 282 bitmap.base(), 283 bitmap.size()); 284 MemTracker::record_virtual_memory_type(bitmap.base(), mtGC); 285 _bitmap_region = MemRegion((HeapWord*) bitmap.base(), bitmap.size() / HeapWordSize); 286 _bitmap_region_special = bitmap.special(); 287 288 size_t bitmap_init_commit = _bitmap_bytes_per_slice * 289 align_up(num_committed_regions, _bitmap_regions_per_slice) / _bitmap_regions_per_slice; 290 bitmap_init_commit = MIN2(_bitmap_size, bitmap_init_commit); 291 if (!_bitmap_region_special) { 292 os::commit_memory_or_exit((char *) _bitmap_region.start(), bitmap_init_commit, bitmap_page_size, false, 293 "Cannot commit bitmap memory"); 294 } 295 296 _marking_context = new ShenandoahMarkingContext(_heap_region, _bitmap_region, _num_regions); 297 298 if (ShenandoahVerify) { 299 ReservedSpace verify_bitmap(_bitmap_size, bitmap_page_size); 300 os::trace_page_sizes_for_requested_size("Verify Bitmap", 301 bitmap_size_orig, verify_bitmap.page_size(), bitmap_page_size, 302 verify_bitmap.base(), 303 verify_bitmap.size()); 304 if (!verify_bitmap.special()) { 305 os::commit_memory_or_exit(verify_bitmap.base(), verify_bitmap.size(), bitmap_page_size, false, 306 "Cannot commit verification bitmap memory"); 307 } 308 MemTracker::record_virtual_memory_type(verify_bitmap.base(), mtGC); 309 MemRegion verify_bitmap_region = MemRegion((HeapWord *) verify_bitmap.base(), verify_bitmap.size() / HeapWordSize); 310 _verification_bit_map.initialize(_heap_region, verify_bitmap_region); 311 _verifier = new ShenandoahVerifier(this, &_verification_bit_map); 312 } 313 314 // Reserve aux bitmap for use in object_iterate(). We don't commit it here. 315 size_t aux_bitmap_page_size = bitmap_page_size; 316 317 ReservedSpace aux_bitmap(_bitmap_size, aux_bitmap_page_size); 318 os::trace_page_sizes_for_requested_size("Aux Bitmap", 319 bitmap_size_orig, aux_bitmap.page_size(), aux_bitmap_page_size, 320 aux_bitmap.base(), aux_bitmap.size()); 321 MemTracker::record_virtual_memory_type(aux_bitmap.base(), mtGC); 322 _aux_bitmap_region = MemRegion((HeapWord*) aux_bitmap.base(), aux_bitmap.size() / HeapWordSize); 323 _aux_bitmap_region_special = aux_bitmap.special(); 324 _aux_bit_map.initialize(_heap_region, _aux_bitmap_region); 325 326 // 327 // Create regions and region sets 328 // 329 size_t region_align = align_up(sizeof(ShenandoahHeapRegion), SHENANDOAH_CACHE_LINE_SIZE); 330 size_t region_storage_size_orig = region_align * _num_regions; 331 size_t region_storage_size = align_up(region_storage_size_orig, 332 MAX2(region_page_size, os::vm_allocation_granularity())); 333 334 ReservedSpace region_storage(region_storage_size, region_page_size); 335 os::trace_page_sizes_for_requested_size("Region Storage", 336 region_storage_size_orig, region_storage.page_size(), region_page_size, 337 region_storage.base(), region_storage.size()); 338 MemTracker::record_virtual_memory_type(region_storage.base(), mtGC); 339 if (!region_storage.special()) { 340 os::commit_memory_or_exit(region_storage.base(), region_storage_size, region_page_size, false, 341 "Cannot commit region memory"); 342 } 343 344 // Try to fit the collection set bitmap at lower addresses. This optimizes code generation for cset checks. 345 // Go up until a sensible limit (subject to encoding constraints) and try to reserve the space there. 346 // If not successful, bite a bullet and allocate at whatever address. 347 { 348 const size_t cset_align = MAX2<size_t>(os::vm_page_size(), os::vm_allocation_granularity()); 349 const size_t cset_size = align_up(((size_t) sh_rs.base() + sh_rs.size()) >> ShenandoahHeapRegion::region_size_bytes_shift(), cset_align); 350 const size_t cset_page_size = os::vm_page_size(); 351 352 uintptr_t min = round_up_power_of_2(cset_align); 353 uintptr_t max = (1u << 30u); 354 ReservedSpace cset_rs; 355 356 for (uintptr_t addr = min; addr <= max; addr <<= 1u) { 357 char* req_addr = (char*)addr; 358 assert(is_aligned(req_addr, cset_align), "Should be aligned"); 359 cset_rs = ReservedSpace(cset_size, cset_align, cset_page_size, req_addr); 360 if (cset_rs.is_reserved()) { 361 assert(cset_rs.base() == req_addr, "Allocated where requested: " PTR_FORMAT ", " PTR_FORMAT, p2i(cset_rs.base()), addr); 362 _collection_set = new ShenandoahCollectionSet(this, cset_rs, sh_rs.base()); 363 break; 364 } 365 } 366 367 if (_collection_set == nullptr) { 368 cset_rs = ReservedSpace(cset_size, cset_align, os::vm_page_size()); 369 _collection_set = new ShenandoahCollectionSet(this, cset_rs, sh_rs.base()); 370 } 371 os::trace_page_sizes_for_requested_size("Collection Set", 372 cset_size, cset_rs.page_size(), cset_page_size, 373 cset_rs.base(), 374 cset_rs.size()); 375 } 376 377 _regions = NEW_C_HEAP_ARRAY(ShenandoahHeapRegion*, _num_regions, mtGC); 378 _affiliations = NEW_C_HEAP_ARRAY(uint8_t, _num_regions, mtGC); 379 _free_set = new ShenandoahFreeSet(this, _num_regions); 380 381 { 382 ShenandoahHeapLocker locker(lock()); 383 384 for (size_t i = 0; i < _num_regions; i++) { 385 HeapWord* start = (HeapWord*)sh_rs.base() + ShenandoahHeapRegion::region_size_words() * i; 386 bool is_committed = i < num_committed_regions; 387 void* loc = region_storage.base() + i * region_align; 388 389 ShenandoahHeapRegion* r = new (loc) ShenandoahHeapRegion(start, i, is_committed); 390 assert(is_aligned(r, SHENANDOAH_CACHE_LINE_SIZE), "Sanity"); 391 392 _marking_context->initialize_top_at_mark_start(r); 393 _regions[i] = r; 394 assert(!collection_set()->is_in(i), "New region should not be in collection set"); 395 396 _affiliations[i] = ShenandoahAffiliation::FREE; 397 } 398 399 // Initialize to complete 400 _marking_context->mark_complete(); 401 size_t young_cset_regions, old_cset_regions; 402 403 // We are initializing free set. We ignore cset region tallies. 404 size_t first_old, last_old, num_old; 405 _free_set->prepare_to_rebuild(young_cset_regions, old_cset_regions, first_old, last_old, num_old); 406 _free_set->finish_rebuild(young_cset_regions, old_cset_regions, num_old); 407 } 408 409 if (AlwaysPreTouch) { 410 // For NUMA, it is important to pre-touch the storage under bitmaps with worker threads, 411 // before initialize() below zeroes it with initializing thread. For any given region, 412 // we touch the region and the corresponding bitmaps from the same thread. 413 ShenandoahPushWorkerScope scope(workers(), _max_workers, false); 414 415 _pretouch_heap_page_size = heap_page_size; 416 _pretouch_bitmap_page_size = bitmap_page_size; 417 418 // OS memory managers may want to coalesce back-to-back pages. Make their jobs 419 // simpler by pre-touching continuous spaces (heap and bitmap) separately. 420 421 ShenandoahPretouchBitmapTask bcl(bitmap.base(), _bitmap_size, _pretouch_bitmap_page_size); 422 _workers->run_task(&bcl); 423 424 ShenandoahPretouchHeapTask hcl(_pretouch_heap_page_size); 425 _workers->run_task(&hcl); 426 } 427 428 // 429 // Initialize the rest of GC subsystems 430 // 431 432 _liveness_cache = NEW_C_HEAP_ARRAY(ShenandoahLiveData*, _max_workers, mtGC); 433 for (uint worker = 0; worker < _max_workers; worker++) { 434 _liveness_cache[worker] = NEW_C_HEAP_ARRAY(ShenandoahLiveData, _num_regions, mtGC); 435 Copy::fill_to_bytes(_liveness_cache[worker], _num_regions * sizeof(ShenandoahLiveData)); 436 } 437 438 // There should probably be Shenandoah-specific options for these, 439 // just as there are G1-specific options. 440 { 441 ShenandoahSATBMarkQueueSet& satbqs = ShenandoahBarrierSet::satb_mark_queue_set(); 442 satbqs.set_process_completed_buffers_threshold(20); // G1SATBProcessCompletedThreshold 443 satbqs.set_buffer_enqueue_threshold_percentage(60); // G1SATBBufferEnqueueingThresholdPercent 444 } 445 446 _monitoring_support = new ShenandoahMonitoringSupport(this); 447 _phase_timings = new ShenandoahPhaseTimings(max_workers()); 448 ShenandoahCodeRoots::initialize(); 449 450 if (ShenandoahPacing) { 451 _pacer = new ShenandoahPacer(this); 452 _pacer->setup_for_idle(); 453 } 454 455 initialize_controller(); 456 457 print_init_logger(); 458 459 return JNI_OK; 460 } 461 462 void ShenandoahHeap::initialize_controller() { 463 _control_thread = new ShenandoahControlThread(); 464 } 465 466 void ShenandoahHeap::print_init_logger() const { 467 ShenandoahInitLogger::print(); 468 } 469 470 void ShenandoahHeap::initialize_mode() { 471 if (ShenandoahGCMode != nullptr) { 472 if (strcmp(ShenandoahGCMode, "satb") == 0) { 473 _gc_mode = new ShenandoahSATBMode(); 474 } else if (strcmp(ShenandoahGCMode, "iu") == 0) { 475 _gc_mode = new ShenandoahIUMode(); 476 } else if (strcmp(ShenandoahGCMode, "passive") == 0) { 477 _gc_mode = new ShenandoahPassiveMode(); 478 } else if (strcmp(ShenandoahGCMode, "generational") == 0) { 479 _gc_mode = new ShenandoahGenerationalMode(); 480 } else { 481 vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option"); 482 } 483 } else { 484 vm_exit_during_initialization("Unknown -XX:ShenandoahGCMode option (null)"); 485 } 486 _gc_mode->initialize_flags(); 487 if (_gc_mode->is_diagnostic() && !UnlockDiagnosticVMOptions) { 488 vm_exit_during_initialization( 489 err_msg("GC mode \"%s\" is diagnostic, and must be enabled via -XX:+UnlockDiagnosticVMOptions.", 490 _gc_mode->name())); 491 } 492 if (_gc_mode->is_experimental() && !UnlockExperimentalVMOptions) { 493 vm_exit_during_initialization( 494 err_msg("GC mode \"%s\" is experimental, and must be enabled via -XX:+UnlockExperimentalVMOptions.", 495 _gc_mode->name())); 496 } 497 } 498 499 void ShenandoahHeap::initialize_heuristics() { 500 _global_generation = new ShenandoahGlobalGeneration(mode()->is_generational(), max_workers(), max_capacity(), max_capacity()); 501 _global_generation->initialize_heuristics(mode()); 502 } 503 504 #ifdef _MSC_VER 505 #pragma warning( push ) 506 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list 507 #endif 508 509 ShenandoahHeap::ShenandoahHeap(ShenandoahCollectorPolicy* policy) : 510 CollectedHeap(), 511 _gc_generation(nullptr), 512 _active_generation(nullptr), 513 _initial_size(0), 514 _committed(0), 515 _max_workers(MAX3(ConcGCThreads, ParallelGCThreads, 1U)), 516 _workers(nullptr), 517 _safepoint_workers(nullptr), 518 _heap_region_special(false), 519 _num_regions(0), 520 _regions(nullptr), 521 _affiliations(nullptr), 522 _gc_state_changed(false), 523 _gc_no_progress_count(0), 524 _cancel_requested_time(0), 525 _update_refs_iterator(this), 526 _global_generation(nullptr), 527 _control_thread(nullptr), 528 _young_generation(nullptr), 529 _old_generation(nullptr), 530 _shenandoah_policy(policy), 531 _gc_mode(nullptr), 532 _free_set(nullptr), 533 _pacer(nullptr), 534 _verifier(nullptr), 535 _phase_timings(nullptr), 536 _mmu_tracker(), 537 _monitoring_support(nullptr), 538 _memory_pool(nullptr), 539 _stw_memory_manager("Shenandoah Pauses"), 540 _cycle_memory_manager("Shenandoah Cycles"), 541 _gc_timer(new ConcurrentGCTimer()), 542 _soft_ref_policy(), 543 _log_min_obj_alignment_in_bytes(LogMinObjAlignmentInBytes), 544 _marking_context(nullptr), 545 _bitmap_size(0), 546 _bitmap_regions_per_slice(0), 547 _bitmap_bytes_per_slice(0), 548 _bitmap_region_special(false), 549 _aux_bitmap_region_special(false), 550 _liveness_cache(nullptr), 551 _collection_set(nullptr) 552 { 553 // Initialize GC mode early, many subsequent initialization procedures depend on it 554 initialize_mode(); 555 } 556 557 #ifdef _MSC_VER 558 #pragma warning( pop ) 559 #endif 560 561 void ShenandoahHeap::print_on(outputStream* st) const { 562 st->print_cr("Shenandoah Heap"); 563 st->print_cr(" " SIZE_FORMAT "%s max, " SIZE_FORMAT "%s soft max, " SIZE_FORMAT "%s committed, " SIZE_FORMAT "%s used", 564 byte_size_in_proper_unit(max_capacity()), proper_unit_for_byte_size(max_capacity()), 565 byte_size_in_proper_unit(soft_max_capacity()), proper_unit_for_byte_size(soft_max_capacity()), 566 byte_size_in_proper_unit(committed()), proper_unit_for_byte_size(committed()), 567 byte_size_in_proper_unit(used()), proper_unit_for_byte_size(used())); 568 st->print_cr(" " SIZE_FORMAT " x " SIZE_FORMAT"%s regions", 569 num_regions(), 570 byte_size_in_proper_unit(ShenandoahHeapRegion::region_size_bytes()), 571 proper_unit_for_byte_size(ShenandoahHeapRegion::region_size_bytes())); 572 573 st->print("Status: "); 574 if (has_forwarded_objects()) st->print("has forwarded objects, "); 575 if (is_concurrent_old_mark_in_progress()) st->print("old marking, "); 576 if (is_concurrent_young_mark_in_progress()) st->print("young marking, "); 577 if (is_evacuation_in_progress()) st->print("evacuating, "); 578 if (is_update_refs_in_progress()) st->print("updating refs, "); 579 if (is_degenerated_gc_in_progress()) st->print("degenerated gc, "); 580 if (is_full_gc_in_progress()) st->print("full gc, "); 581 if (is_full_gc_move_in_progress()) st->print("full gc move, "); 582 if (is_concurrent_weak_root_in_progress()) st->print("concurrent weak roots, "); 583 if (is_concurrent_strong_root_in_progress() && 584 !is_concurrent_weak_root_in_progress()) st->print("concurrent strong roots, "); 585 586 if (cancelled_gc()) { 587 st->print("cancelled"); 588 } else { 589 st->print("not cancelled"); 590 } 591 st->cr(); 592 593 st->print_cr("Reserved region:"); 594 st->print_cr(" - [" PTR_FORMAT ", " PTR_FORMAT ") ", 595 p2i(reserved_region().start()), 596 p2i(reserved_region().end())); 597 598 ShenandoahCollectionSet* cset = collection_set(); 599 st->print_cr("Collection set:"); 600 if (cset != nullptr) { 601 st->print_cr(" - map (vanilla): " PTR_FORMAT, p2i(cset->map_address())); 602 st->print_cr(" - map (biased): " PTR_FORMAT, p2i(cset->biased_map_address())); 603 } else { 604 st->print_cr(" (null)"); 605 } 606 607 st->cr(); 608 MetaspaceUtils::print_on(st); 609 610 if (Verbose) { 611 st->cr(); 612 print_heap_regions_on(st); 613 } 614 } 615 616 class ShenandoahInitWorkerGCLABClosure : public ThreadClosure { 617 public: 618 void do_thread(Thread* thread) { 619 assert(thread != nullptr, "Sanity"); 620 assert(thread->is_Worker_thread(), "Only worker thread expected"); 621 ShenandoahThreadLocalData::initialize_gclab(thread); 622 } 623 }; 624 625 void ShenandoahHeap::post_initialize() { 626 CollectedHeap::post_initialize(); 627 _mmu_tracker.initialize(); 628 629 MutexLocker ml(Threads_lock); 630 631 ShenandoahInitWorkerGCLABClosure init_gclabs; 632 _workers->threads_do(&init_gclabs); 633 634 // gclab can not be initialized early during VM startup, as it can not determinate its max_size. 635 // Now, we will let WorkerThreads to initialize gclab when new worker is created. 636 _workers->set_initialize_gclab(); 637 if (_safepoint_workers != nullptr) { 638 _safepoint_workers->threads_do(&init_gclabs); 639 _safepoint_workers->set_initialize_gclab(); 640 } 641 642 JFR_ONLY(ShenandoahJFRSupport::register_jfr_type_serializers()); 643 } 644 645 ShenandoahHeuristics* ShenandoahHeap::heuristics() { 646 return _global_generation->heuristics(); 647 } 648 649 size_t ShenandoahHeap::used() const { 650 return global_generation()->used(); 651 } 652 653 size_t ShenandoahHeap::committed() const { 654 return Atomic::load(&_committed); 655 } 656 657 void ShenandoahHeap::increase_committed(size_t bytes) { 658 shenandoah_assert_heaplocked_or_safepoint(); 659 _committed += bytes; 660 } 661 662 void ShenandoahHeap::decrease_committed(size_t bytes) { 663 shenandoah_assert_heaplocked_or_safepoint(); 664 _committed -= bytes; 665 } 666 667 // For tracking usage based on allocations, it should be the case that: 668 // * The sum of regions::used == heap::used 669 // * The sum of a generation's regions::used == generation::used 670 // * The sum of a generation's humongous regions::free == generation::humongous_waste 671 // These invariants are checked by the verifier on GC safepoints. 672 // 673 // Additional notes: 674 // * When a mutator's allocation request causes a region to be retired, the 675 // free memory left in that region is considered waste. It does not contribute 676 // to the usage, but it _does_ contribute to allocation rate. 677 // * The bottom of a PLAB must be aligned on card size. In some cases this will 678 // require padding in front of the PLAB (a filler object). Because this padding 679 // is included in the region's used memory we include the padding in the usage 680 // accounting as waste. 681 // * Mutator allocations are used to compute an allocation rate. They are also 682 // sent to the Pacer for those purposes. 683 // * There are three sources of waste: 684 // 1. The padding used to align a PLAB on card size 685 // 2. Region's free is less than minimum TLAB size and is retired 686 // 3. The unused portion of memory in the last region of a humongous object 687 void ShenandoahHeap::increase_used(const ShenandoahAllocRequest& req) { 688 size_t actual_bytes = req.actual_size() * HeapWordSize; 689 size_t wasted_bytes = req.waste() * HeapWordSize; 690 ShenandoahGeneration* generation = generation_for(req.affiliation()); 691 692 if (req.is_gc_alloc()) { 693 assert(wasted_bytes == 0 || req.type() == ShenandoahAllocRequest::_alloc_plab, "Only PLABs have waste"); 694 increase_used(generation, actual_bytes + wasted_bytes); 695 } else { 696 assert(req.is_mutator_alloc(), "Expected mutator alloc here"); 697 // padding and actual size both count towards allocation counter 698 generation->increase_allocated(actual_bytes + wasted_bytes); 699 700 // only actual size counts toward usage for mutator allocations 701 increase_used(generation, actual_bytes); 702 703 // notify pacer of both actual size and waste 704 notify_mutator_alloc_words(req.actual_size(), req.waste()); 705 706 if (wasted_bytes > 0 && ShenandoahHeapRegion::requires_humongous(req.actual_size())) { 707 increase_humongous_waste(generation,wasted_bytes); 708 } 709 } 710 } 711 712 void ShenandoahHeap::increase_humongous_waste(ShenandoahGeneration* generation, size_t bytes) { 713 generation->increase_humongous_waste(bytes); 714 if (!generation->is_global()) { 715 global_generation()->increase_humongous_waste(bytes); 716 } 717 } 718 719 void ShenandoahHeap::decrease_humongous_waste(ShenandoahGeneration* generation, size_t bytes) { 720 generation->decrease_humongous_waste(bytes); 721 if (!generation->is_global()) { 722 global_generation()->decrease_humongous_waste(bytes); 723 } 724 } 725 726 void ShenandoahHeap::increase_used(ShenandoahGeneration* generation, size_t bytes) { 727 generation->increase_used(bytes); 728 if (!generation->is_global()) { 729 global_generation()->increase_used(bytes); 730 } 731 } 732 733 void ShenandoahHeap::decrease_used(ShenandoahGeneration* generation, size_t bytes) { 734 generation->decrease_used(bytes); 735 if (!generation->is_global()) { 736 global_generation()->decrease_used(bytes); 737 } 738 } 739 740 void ShenandoahHeap::notify_mutator_alloc_words(size_t words, size_t waste) { 741 if (ShenandoahPacing) { 742 control_thread()->pacing_notify_alloc(words); 743 if (waste > 0) { 744 pacer()->claim_for_alloc<true>(waste); 745 } 746 } 747 } 748 749 size_t ShenandoahHeap::capacity() const { 750 return committed(); 751 } 752 753 size_t ShenandoahHeap::max_capacity() const { 754 return _num_regions * ShenandoahHeapRegion::region_size_bytes(); 755 } 756 757 size_t ShenandoahHeap::soft_max_capacity() const { 758 size_t v = Atomic::load(&_soft_max_size); 759 assert(min_capacity() <= v && v <= max_capacity(), 760 "Should be in bounds: " SIZE_FORMAT " <= " SIZE_FORMAT " <= " SIZE_FORMAT, 761 min_capacity(), v, max_capacity()); 762 return v; 763 } 764 765 void ShenandoahHeap::set_soft_max_capacity(size_t v) { 766 assert(min_capacity() <= v && v <= max_capacity(), 767 "Should be in bounds: " SIZE_FORMAT " <= " SIZE_FORMAT " <= " SIZE_FORMAT, 768 min_capacity(), v, max_capacity()); 769 Atomic::store(&_soft_max_size, v); 770 } 771 772 size_t ShenandoahHeap::min_capacity() const { 773 return _minimum_size; 774 } 775 776 size_t ShenandoahHeap::initial_capacity() const { 777 return _initial_size; 778 } 779 780 void ShenandoahHeap::maybe_uncommit(double shrink_before, size_t shrink_until) { 781 assert (ShenandoahUncommit, "should be enabled"); 782 783 // Determine if there is work to do. This avoids taking heap lock if there is 784 // no work available, avoids spamming logs with superfluous logging messages, 785 // and minimises the amount of work while locks are taken. 786 787 if (committed() <= shrink_until) return; 788 789 bool has_work = false; 790 for (size_t i = 0; i < num_regions(); i++) { 791 ShenandoahHeapRegion* r = get_region(i); 792 if (r->is_empty_committed() && (r->empty_time() < shrink_before)) { 793 has_work = true; 794 break; 795 } 796 } 797 798 if (has_work) { 799 static const char* msg = "Concurrent uncommit"; 800 ShenandoahConcurrentPhase gcPhase(msg, ShenandoahPhaseTimings::conc_uncommit, true /* log_heap_usage */); 801 EventMark em("%s", msg); 802 803 op_uncommit(shrink_before, shrink_until); 804 } 805 } 806 807 void ShenandoahHeap::op_uncommit(double shrink_before, size_t shrink_until) { 808 assert (ShenandoahUncommit, "should be enabled"); 809 810 // Application allocates from the beginning of the heap, and GC allocates at 811 // the end of it. It is more efficient to uncommit from the end, so that applications 812 // could enjoy the near committed regions. GC allocations are much less frequent, 813 // and therefore can accept the committing costs. 814 815 size_t count = 0; 816 for (size_t i = num_regions(); i > 0; i--) { // care about size_t underflow 817 ShenandoahHeapRegion* r = get_region(i - 1); 818 if (r->is_empty_committed() && (r->empty_time() < shrink_before)) { 819 ShenandoahHeapLocker locker(lock()); 820 if (r->is_empty_committed()) { 821 if (committed() < shrink_until + ShenandoahHeapRegion::region_size_bytes()) { 822 break; 823 } 824 825 r->make_uncommitted(); 826 count++; 827 } 828 } 829 SpinPause(); // allow allocators to take the lock 830 } 831 832 if (count > 0) { 833 notify_heap_changed(); 834 } 835 } 836 837 bool ShenandoahHeap::check_soft_max_changed() { 838 size_t new_soft_max = Atomic::load(&SoftMaxHeapSize); 839 size_t old_soft_max = soft_max_capacity(); 840 if (new_soft_max != old_soft_max) { 841 new_soft_max = MAX2(min_capacity(), new_soft_max); 842 new_soft_max = MIN2(max_capacity(), new_soft_max); 843 if (new_soft_max != old_soft_max) { 844 log_info(gc)("Soft Max Heap Size: " SIZE_FORMAT "%s -> " SIZE_FORMAT "%s", 845 byte_size_in_proper_unit(old_soft_max), proper_unit_for_byte_size(old_soft_max), 846 byte_size_in_proper_unit(new_soft_max), proper_unit_for_byte_size(new_soft_max) 847 ); 848 set_soft_max_capacity(new_soft_max); 849 return true; 850 } 851 } 852 return false; 853 } 854 855 void ShenandoahHeap::notify_heap_changed() { 856 // Update monitoring counters when we took a new region. This amortizes the 857 // update costs on slow path. 858 monitoring_support()->notify_heap_changed(); 859 _heap_changed.set(); 860 } 861 862 void ShenandoahHeap::set_forced_counters_update(bool value) { 863 monitoring_support()->set_forced_counters_update(value); 864 } 865 866 void ShenandoahHeap::handle_force_counters_update() { 867 monitoring_support()->handle_force_counters_update(); 868 } 869 870 HeapWord* ShenandoahHeap::allocate_from_gclab_slow(Thread* thread, size_t size) { 871 // New object should fit the GCLAB size 872 size_t min_size = MAX2(size, PLAB::min_size()); 873 874 // Figure out size of new GCLAB, looking back at heuristics. Expand aggressively. 875 size_t new_size = ShenandoahThreadLocalData::gclab_size(thread) * 2; 876 877 new_size = MIN2(new_size, PLAB::max_size()); 878 new_size = MAX2(new_size, PLAB::min_size()); 879 880 // Record new heuristic value even if we take any shortcut. This captures 881 // the case when moderately-sized objects always take a shortcut. At some point, 882 // heuristics should catch up with them. 883 log_debug(gc, free)("Set new GCLAB size: " SIZE_FORMAT, new_size); 884 ShenandoahThreadLocalData::set_gclab_size(thread, new_size); 885 886 if (new_size < size) { 887 // New size still does not fit the object. Fall back to shared allocation. 888 // This avoids retiring perfectly good GCLABs, when we encounter a large object. 889 log_debug(gc, free)("New gclab size (" SIZE_FORMAT ") is too small for " SIZE_FORMAT, new_size, size); 890 return nullptr; 891 } 892 893 // Retire current GCLAB, and allocate a new one. 894 PLAB* gclab = ShenandoahThreadLocalData::gclab(thread); 895 gclab->retire(); 896 897 size_t actual_size = 0; 898 HeapWord* gclab_buf = allocate_new_gclab(min_size, new_size, &actual_size); 899 if (gclab_buf == nullptr) { 900 return nullptr; 901 } 902 903 assert (size <= actual_size, "allocation should fit"); 904 905 // ...and clear or zap just allocated TLAB, if needed. 906 if (ZeroTLAB) { 907 Copy::zero_to_words(gclab_buf, actual_size); 908 } else if (ZapTLAB) { 909 // Skip mangling the space corresponding to the object header to 910 // ensure that the returned space is not considered parsable by 911 // any concurrent GC thread. 912 size_t hdr_size = oopDesc::header_size(); 913 Copy::fill_to_words(gclab_buf + hdr_size, actual_size - hdr_size, badHeapWordVal); 914 } 915 gclab->set_buf(gclab_buf, actual_size); 916 return gclab->allocate(size); 917 } 918 919 // Called from stubs in JIT code or interpreter 920 HeapWord* ShenandoahHeap::allocate_new_tlab(size_t min_size, 921 size_t requested_size, 922 size_t* actual_size) { 923 ShenandoahAllocRequest req = ShenandoahAllocRequest::for_tlab(min_size, requested_size); 924 HeapWord* res = allocate_memory(req); 925 if (res != nullptr) { 926 *actual_size = req.actual_size(); 927 } else { 928 *actual_size = 0; 929 } 930 return res; 931 } 932 933 HeapWord* ShenandoahHeap::allocate_new_gclab(size_t min_size, 934 size_t word_size, 935 size_t* actual_size) { 936 ShenandoahAllocRequest req = ShenandoahAllocRequest::for_gclab(min_size, word_size); 937 HeapWord* res = allocate_memory(req); 938 if (res != nullptr) { 939 *actual_size = req.actual_size(); 940 } else { 941 *actual_size = 0; 942 } 943 return res; 944 } 945 946 HeapWord* ShenandoahHeap::allocate_memory(ShenandoahAllocRequest& req) { 947 intptr_t pacer_epoch = 0; 948 bool in_new_region = false; 949 HeapWord* result = nullptr; 950 951 if (req.is_mutator_alloc()) { 952 if (ShenandoahPacing) { 953 pacer()->pace_for_alloc(req.size()); 954 pacer_epoch = pacer()->epoch(); 955 } 956 957 if (!ShenandoahAllocFailureALot || !should_inject_alloc_failure()) { 958 result = allocate_memory_under_lock(req, in_new_region); 959 } 960 961 // Check that gc overhead is not exceeded. 962 // 963 // Shenandoah will grind along for quite a while allocating one 964 // object at a time using shared (non-tlab) allocations. This check 965 // is testing that the GC overhead limit has not been exceeded. 966 // This will notify the collector to start a cycle, but will raise 967 // an OOME to the mutator if the last Full GCs have not made progress. 968 // gc_no_progress_count is incremented following each degen or full GC that fails to achieve is_good_progress(). 969 if ((result == nullptr) && !req.is_lab_alloc() && (get_gc_no_progress_count() > ShenandoahNoProgressThreshold)) { 970 control_thread()->handle_alloc_failure(req, false); 971 req.set_actual_size(0); 972 return nullptr; 973 } 974 975 if (result == nullptr) { 976 // Block until control thread reacted, then retry allocation. 977 // 978 // It might happen that one of the threads requesting allocation would unblock 979 // way later after GC happened, only to fail the second allocation, because 980 // other threads have already depleted the free storage. In this case, a better 981 // strategy is to try again, until at least one full GC has completed. 982 // 983 // Stop retrying and return nullptr to cause OOMError exception if our allocation failed even after: 984 // a) We experienced a GC that had good progress, or 985 // b) We experienced at least one Full GC (whether or not it had good progress) 986 987 size_t original_count = shenandoah_policy()->full_gc_count(); 988 while ((result == nullptr) && (original_count == shenandoah_policy()->full_gc_count())) { 989 control_thread()->handle_alloc_failure(req, true); 990 result = allocate_memory_under_lock(req, in_new_region); 991 } 992 if (result != nullptr) { 993 // If our allocation request has been satisifed after it initially failed, we count this as good gc progress 994 notify_gc_progress(); 995 } 996 if (log_develop_is_enabled(Debug, gc, alloc)) { 997 ResourceMark rm; 998 log_debug(gc, alloc)("Thread: %s, Result: " PTR_FORMAT ", Request: %s, Size: " SIZE_FORMAT 999 ", Original: " SIZE_FORMAT ", Latest: " SIZE_FORMAT, 1000 Thread::current()->name(), p2i(result), req.type_string(), req.size(), 1001 original_count, get_gc_no_progress_count()); 1002 } 1003 } 1004 } else { 1005 assert(req.is_gc_alloc(), "Can only accept GC allocs here"); 1006 result = allocate_memory_under_lock(req, in_new_region); 1007 // Do not call handle_alloc_failure() here, because we cannot block. 1008 // The allocation failure would be handled by the LRB slowpath with handle_alloc_failure_evac(). 1009 } 1010 1011 if (in_new_region) { 1012 notify_heap_changed(); 1013 } 1014 1015 if (result == nullptr) { 1016 req.set_actual_size(0); 1017 } 1018 1019 // This is called regardless of the outcome of the allocation to account 1020 // for any waste created by retiring regions with this request. 1021 increase_used(req); 1022 1023 if (result != nullptr) { 1024 size_t requested = req.size(); 1025 size_t actual = req.actual_size(); 1026 1027 assert (req.is_lab_alloc() || (requested == actual), 1028 "Only LAB allocations are elastic: %s, requested = " SIZE_FORMAT ", actual = " SIZE_FORMAT, 1029 ShenandoahAllocRequest::alloc_type_to_string(req.type()), requested, actual); 1030 1031 if (req.is_mutator_alloc()) { 1032 // If we requested more than we were granted, give the rest back to pacer. 1033 // This only matters if we are in the same pacing epoch: do not try to unpace 1034 // over the budget for the other phase. 1035 if (ShenandoahPacing && (pacer_epoch > 0) && (requested > actual)) { 1036 pacer()->unpace_for_alloc(pacer_epoch, requested - actual); 1037 } 1038 } 1039 } 1040 1041 return result; 1042 } 1043 1044 HeapWord* ShenandoahHeap::allocate_memory_under_lock(ShenandoahAllocRequest& req, bool& in_new_region) { 1045 // If we are dealing with mutator allocation, then we may need to block for safepoint. 1046 // We cannot block for safepoint for GC allocations, because there is a high chance 1047 // we are already running at safepoint or from stack watermark machinery, and we cannot 1048 // block again. 1049 ShenandoahHeapLocker locker(lock(), req.is_mutator_alloc()); 1050 1051 // Make sure the old generation has room for either evacuations or promotions before trying to allocate. 1052 if (req.is_old() && !old_generation()->can_allocate(req)) { 1053 return nullptr; 1054 } 1055 1056 // If TLAB request size is greater than available, allocate() will attempt to downsize request to fit within available 1057 // memory. 1058 HeapWord* result = _free_set->allocate(req, in_new_region); 1059 1060 // Record the plab configuration for this result and register the object. 1061 if (result != nullptr && req.is_old()) { 1062 old_generation()->configure_plab_for_current_thread(req); 1063 if (req.type() == ShenandoahAllocRequest::_alloc_shared_gc) { 1064 // Register the newly allocated object while we're holding the global lock since there's no synchronization 1065 // built in to the implementation of register_object(). There are potential races when multiple independent 1066 // threads are allocating objects, some of which might span the same card region. For example, consider 1067 // a card table's memory region within which three objects are being allocated by three different threads: 1068 // 1069 // objects being "concurrently" allocated: 1070 // [-----a------][-----b-----][--------------c------------------] 1071 // [---- card table memory range --------------] 1072 // 1073 // Before any objects are allocated, this card's memory range holds no objects. Note that allocation of object a 1074 // wants to set the starts-object, first-start, and last-start attributes of the preceding card region. 1075 // Allocation of object b wants to set the starts-object, first-start, and last-start attributes of this card region. 1076 // Allocation of object c also wants to set the starts-object, first-start, and last-start attributes of this 1077 // card region. 1078 // 1079 // The thread allocating b and the thread allocating c can "race" in various ways, resulting in confusion, such as 1080 // last-start representing object b while first-start represents object c. This is why we need to require all 1081 // register_object() invocations to be "mutually exclusive" with respect to each card's memory range. 1082 old_generation()->card_scan()->register_object(result); 1083 } 1084 } 1085 1086 return result; 1087 } 1088 1089 HeapWord* ShenandoahHeap::mem_allocate(size_t size, 1090 bool* gc_overhead_limit_was_exceeded) { 1091 ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared(size); 1092 return allocate_memory(req); 1093 } 1094 1095 MetaWord* ShenandoahHeap::satisfy_failed_metadata_allocation(ClassLoaderData* loader_data, 1096 size_t size, 1097 Metaspace::MetadataType mdtype) { 1098 MetaWord* result; 1099 1100 // Inform metaspace OOM to GC heuristics if class unloading is possible. 1101 ShenandoahHeuristics* h = global_generation()->heuristics(); 1102 if (h->can_unload_classes()) { 1103 h->record_metaspace_oom(); 1104 } 1105 1106 // Expand and retry allocation 1107 result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype); 1108 if (result != nullptr) { 1109 return result; 1110 } 1111 1112 // Start full GC 1113 collect(GCCause::_metadata_GC_clear_soft_refs); 1114 1115 // Retry allocation 1116 result = loader_data->metaspace_non_null()->allocate(size, mdtype); 1117 if (result != nullptr) { 1118 return result; 1119 } 1120 1121 // Expand and retry allocation 1122 result = loader_data->metaspace_non_null()->expand_and_allocate(size, mdtype); 1123 if (result != nullptr) { 1124 return result; 1125 } 1126 1127 // Out of memory 1128 return nullptr; 1129 } 1130 1131 class ShenandoahConcurrentEvacuateRegionObjectClosure : public ObjectClosure { 1132 private: 1133 ShenandoahHeap* const _heap; 1134 Thread* const _thread; 1135 public: 1136 ShenandoahConcurrentEvacuateRegionObjectClosure(ShenandoahHeap* heap) : 1137 _heap(heap), _thread(Thread::current()) {} 1138 1139 void do_object(oop p) { 1140 shenandoah_assert_marked(nullptr, p); 1141 if (!p->is_forwarded()) { 1142 _heap->evacuate_object(p, _thread); 1143 } 1144 } 1145 }; 1146 1147 class ShenandoahEvacuationTask : public WorkerTask { 1148 private: 1149 ShenandoahHeap* const _sh; 1150 ShenandoahCollectionSet* const _cs; 1151 bool _concurrent; 1152 public: 1153 ShenandoahEvacuationTask(ShenandoahHeap* sh, 1154 ShenandoahCollectionSet* cs, 1155 bool concurrent) : 1156 WorkerTask("Shenandoah Evacuation"), 1157 _sh(sh), 1158 _cs(cs), 1159 _concurrent(concurrent) 1160 {} 1161 1162 void work(uint worker_id) { 1163 if (_concurrent) { 1164 ShenandoahConcurrentWorkerSession worker_session(worker_id); 1165 ShenandoahSuspendibleThreadSetJoiner stsj; 1166 ShenandoahEvacOOMScope oom_evac_scope; 1167 do_work(); 1168 } else { 1169 ShenandoahParallelWorkerSession worker_session(worker_id); 1170 ShenandoahEvacOOMScope oom_evac_scope; 1171 do_work(); 1172 } 1173 } 1174 1175 private: 1176 void do_work() { 1177 ShenandoahConcurrentEvacuateRegionObjectClosure cl(_sh); 1178 ShenandoahHeapRegion* r; 1179 while ((r =_cs->claim_next()) != nullptr) { 1180 assert(r->has_live(), "Region " SIZE_FORMAT " should have been reclaimed early", r->index()); 1181 _sh->marked_object_iterate(r, &cl); 1182 1183 if (ShenandoahPacing) { 1184 _sh->pacer()->report_evac(r->used() >> LogHeapWordSize); 1185 } 1186 1187 if (_sh->check_cancelled_gc_and_yield(_concurrent)) { 1188 break; 1189 } 1190 } 1191 } 1192 }; 1193 1194 void ShenandoahHeap::evacuate_collection_set(bool concurrent) { 1195 ShenandoahEvacuationTask task(this, _collection_set, concurrent); 1196 workers()->run_task(&task); 1197 } 1198 1199 oop ShenandoahHeap::evacuate_object(oop p, Thread* thread) { 1200 assert(thread == Thread::current(), "Expected thread parameter to be current thread."); 1201 if (ShenandoahThreadLocalData::is_oom_during_evac(thread)) { 1202 // This thread went through the OOM during evac protocol. It is safe to return 1203 // the forward pointer. It must not attempt to evacuate any other objects. 1204 return ShenandoahBarrierSet::resolve_forwarded(p); 1205 } 1206 1207 assert(ShenandoahThreadLocalData::is_evac_allowed(thread), "must be enclosed in oom-evac scope"); 1208 1209 ShenandoahHeapRegion* r = heap_region_containing(p); 1210 assert(!r->is_humongous(), "never evacuate humongous objects"); 1211 1212 ShenandoahAffiliation target_gen = r->affiliation(); 1213 return try_evacuate_object(p, thread, r, target_gen); 1214 } 1215 1216 oop ShenandoahHeap::try_evacuate_object(oop p, Thread* thread, ShenandoahHeapRegion* from_region, 1217 ShenandoahAffiliation target_gen) { 1218 assert(target_gen == YOUNG_GENERATION, "Only expect evacuations to young in this mode"); 1219 assert(from_region->is_young(), "Only expect evacuations from young in this mode"); 1220 bool alloc_from_lab = true; 1221 HeapWord* copy = nullptr; 1222 size_t size = p->size(); 1223 1224 #ifdef ASSERT 1225 if (ShenandoahOOMDuringEvacALot && 1226 (os::random() & 1) == 0) { // Simulate OOM every ~2nd slow-path call 1227 copy = nullptr; 1228 } else { 1229 #endif 1230 if (UseTLAB) { 1231 copy = allocate_from_gclab(thread, size); 1232 } 1233 if (copy == nullptr) { 1234 // If we failed to allocate in LAB, we'll try a shared allocation. 1235 ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared_gc(size, target_gen); 1236 copy = allocate_memory(req); 1237 alloc_from_lab = false; 1238 } 1239 #ifdef ASSERT 1240 } 1241 #endif 1242 1243 if (copy == nullptr) { 1244 control_thread()->handle_alloc_failure_evac(size); 1245 1246 _oom_evac_handler.handle_out_of_memory_during_evacuation(); 1247 1248 return ShenandoahBarrierSet::resolve_forwarded(p); 1249 } 1250 1251 // Copy the object: 1252 Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(p), copy, size); 1253 1254 // Try to install the new forwarding pointer. 1255 oop copy_val = cast_to_oop(copy); 1256 oop result = ShenandoahForwarding::try_update_forwardee(p, copy_val); 1257 if (result == copy_val) { 1258 // Successfully evacuated. Our copy is now the public one! 1259 ContinuationGCSupport::relativize_stack_chunk(copy_val); 1260 shenandoah_assert_correct(nullptr, copy_val); 1261 return copy_val; 1262 } else { 1263 // Failed to evacuate. We need to deal with the object that is left behind. Since this 1264 // new allocation is certainly after TAMS, it will be considered live in the next cycle. 1265 // But if it happens to contain references to evacuated regions, those references would 1266 // not get updated for this stale copy during this cycle, and we will crash while scanning 1267 // it the next cycle. 1268 if (alloc_from_lab) { 1269 // For LAB allocations, it is enough to rollback the allocation ptr. Either the next 1270 // object will overwrite this stale copy, or the filler object on LAB retirement will 1271 // do this. 1272 ShenandoahThreadLocalData::gclab(thread)->undo_allocation(copy, size); 1273 } else { 1274 // For non-LAB allocations, we have no way to retract the allocation, and 1275 // have to explicitly overwrite the copy with the filler object. With that overwrite, 1276 // we have to keep the fwdptr initialized and pointing to our (stale) copy. 1277 assert(size >= ShenandoahHeap::min_fill_size(), "previously allocated object known to be larger than min_size"); 1278 fill_with_object(copy, size); 1279 shenandoah_assert_correct(nullptr, copy_val); 1280 // For non-LAB allocations, the object has already been registered 1281 } 1282 shenandoah_assert_correct(nullptr, result); 1283 return result; 1284 } 1285 } 1286 1287 void ShenandoahHeap::trash_cset_regions() { 1288 ShenandoahHeapLocker locker(lock()); 1289 1290 ShenandoahCollectionSet* set = collection_set(); 1291 ShenandoahHeapRegion* r; 1292 set->clear_current_index(); 1293 while ((r = set->next()) != nullptr) { 1294 r->make_trash(); 1295 } 1296 collection_set()->clear(); 1297 } 1298 1299 void ShenandoahHeap::print_heap_regions_on(outputStream* st) const { 1300 st->print_cr("Heap Regions:"); 1301 st->print_cr("Region state: EU=empty-uncommitted, EC=empty-committed, R=regular, H=humongous start, HP=pinned humongous start"); 1302 st->print_cr(" HC=humongous continuation, CS=collection set, TR=trash, P=pinned, CSP=pinned collection set"); 1303 st->print_cr("BTE=bottom/top/end, TAMS=top-at-mark-start"); 1304 st->print_cr("UWM=update watermark, U=used"); 1305 st->print_cr("T=TLAB allocs, G=GCLAB allocs"); 1306 st->print_cr("S=shared allocs, L=live data"); 1307 st->print_cr("CP=critical pins"); 1308 1309 for (size_t i = 0; i < num_regions(); i++) { 1310 get_region(i)->print_on(st); 1311 } 1312 } 1313 1314 size_t ShenandoahHeap::trash_humongous_region_at(ShenandoahHeapRegion* start) { 1315 assert(start->is_humongous_start(), "reclaim regions starting with the first one"); 1316 1317 oop humongous_obj = cast_to_oop(start->bottom()); 1318 size_t size = humongous_obj->size(); 1319 size_t required_regions = ShenandoahHeapRegion::required_regions(size * HeapWordSize); 1320 size_t index = start->index() + required_regions - 1; 1321 1322 assert(!start->has_live(), "liveness must be zero"); 1323 1324 for(size_t i = 0; i < required_regions; i++) { 1325 // Reclaim from tail. Otherwise, assertion fails when printing region to trace log, 1326 // as it expects that every region belongs to a humongous region starting with a humongous start region. 1327 ShenandoahHeapRegion* region = get_region(index --); 1328 1329 assert(region->is_humongous(), "expect correct humongous start or continuation"); 1330 assert(!region->is_cset(), "Humongous region should not be in collection set"); 1331 1332 region->make_trash_immediate(); 1333 } 1334 return required_regions; 1335 } 1336 1337 class ShenandoahCheckCleanGCLABClosure : public ThreadClosure { 1338 public: 1339 ShenandoahCheckCleanGCLABClosure() {} 1340 void do_thread(Thread* thread) { 1341 PLAB* gclab = ShenandoahThreadLocalData::gclab(thread); 1342 assert(gclab != nullptr, "GCLAB should be initialized for %s", thread->name()); 1343 assert(gclab->words_remaining() == 0, "GCLAB should not need retirement"); 1344 1345 if (ShenandoahHeap::heap()->mode()->is_generational()) { 1346 PLAB* plab = ShenandoahThreadLocalData::plab(thread); 1347 assert(plab != nullptr, "PLAB should be initialized for %s", thread->name()); 1348 assert(plab->words_remaining() == 0, "PLAB should not need retirement"); 1349 } 1350 } 1351 }; 1352 1353 class ShenandoahRetireGCLABClosure : public ThreadClosure { 1354 private: 1355 bool const _resize; 1356 public: 1357 ShenandoahRetireGCLABClosure(bool resize) : _resize(resize) {} 1358 void do_thread(Thread* thread) { 1359 PLAB* gclab = ShenandoahThreadLocalData::gclab(thread); 1360 assert(gclab != nullptr, "GCLAB should be initialized for %s", thread->name()); 1361 gclab->retire(); 1362 if (_resize && ShenandoahThreadLocalData::gclab_size(thread) > 0) { 1363 ShenandoahThreadLocalData::set_gclab_size(thread, 0); 1364 } 1365 1366 if (ShenandoahHeap::heap()->mode()->is_generational()) { 1367 PLAB* plab = ShenandoahThreadLocalData::plab(thread); 1368 assert(plab != nullptr, "PLAB should be initialized for %s", thread->name()); 1369 1370 // There are two reasons to retire all plabs between old-gen evacuation passes. 1371 // 1. We need to make the plab memory parsable by remembered-set scanning. 1372 // 2. We need to establish a trustworthy UpdateWaterMark value within each old-gen heap region 1373 ShenandoahGenerationalHeap::heap()->retire_plab(plab, thread); 1374 if (_resize && ShenandoahThreadLocalData::plab_size(thread) > 0) { 1375 ShenandoahThreadLocalData::set_plab_size(thread, 0); 1376 } 1377 } 1378 } 1379 }; 1380 1381 void ShenandoahHeap::labs_make_parsable() { 1382 assert(UseTLAB, "Only call with UseTLAB"); 1383 1384 ShenandoahRetireGCLABClosure cl(false); 1385 1386 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) { 1387 ThreadLocalAllocBuffer& tlab = t->tlab(); 1388 tlab.make_parsable(); 1389 cl.do_thread(t); 1390 } 1391 1392 workers()->threads_do(&cl); 1393 } 1394 1395 void ShenandoahHeap::tlabs_retire(bool resize) { 1396 assert(UseTLAB, "Only call with UseTLAB"); 1397 assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled"); 1398 1399 ThreadLocalAllocStats stats; 1400 1401 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) { 1402 ThreadLocalAllocBuffer& tlab = t->tlab(); 1403 tlab.retire(&stats); 1404 if (resize) { 1405 tlab.resize(); 1406 } 1407 } 1408 1409 stats.publish(); 1410 1411 #ifdef ASSERT 1412 ShenandoahCheckCleanGCLABClosure cl; 1413 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) { 1414 cl.do_thread(t); 1415 } 1416 workers()->threads_do(&cl); 1417 #endif 1418 } 1419 1420 void ShenandoahHeap::gclabs_retire(bool resize) { 1421 assert(UseTLAB, "Only call with UseTLAB"); 1422 assert(!resize || ResizeTLAB, "Only call for resize when ResizeTLAB is enabled"); 1423 1424 ShenandoahRetireGCLABClosure cl(resize); 1425 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) { 1426 cl.do_thread(t); 1427 } 1428 workers()->threads_do(&cl); 1429 1430 if (safepoint_workers() != nullptr) { 1431 safepoint_workers()->threads_do(&cl); 1432 } 1433 } 1434 1435 // Returns size in bytes 1436 size_t ShenandoahHeap::unsafe_max_tlab_alloc(Thread *thread) const { 1437 // Return the max allowed size, and let the allocation path 1438 // figure out the safe size for current allocation. 1439 return ShenandoahHeapRegion::max_tlab_size_bytes(); 1440 } 1441 1442 size_t ShenandoahHeap::max_tlab_size() const { 1443 // Returns size in words 1444 return ShenandoahHeapRegion::max_tlab_size_words(); 1445 } 1446 1447 void ShenandoahHeap::collect(GCCause::Cause cause) { 1448 control_thread()->request_gc(cause); 1449 } 1450 1451 void ShenandoahHeap::do_full_collection(bool clear_all_soft_refs) { 1452 //assert(false, "Shouldn't need to do full collections"); 1453 } 1454 1455 HeapWord* ShenandoahHeap::block_start(const void* addr) const { 1456 ShenandoahHeapRegion* r = heap_region_containing(addr); 1457 if (r != nullptr) { 1458 return r->block_start(addr); 1459 } 1460 return nullptr; 1461 } 1462 1463 bool ShenandoahHeap::block_is_obj(const HeapWord* addr) const { 1464 ShenandoahHeapRegion* r = heap_region_containing(addr); 1465 return r->block_is_obj(addr); 1466 } 1467 1468 bool ShenandoahHeap::print_location(outputStream* st, void* addr) const { 1469 return BlockLocationPrinter<ShenandoahHeap>::print_location(st, addr); 1470 } 1471 1472 void ShenandoahHeap::prepare_for_verify() { 1473 if (SafepointSynchronize::is_at_safepoint() && UseTLAB) { 1474 labs_make_parsable(); 1475 } 1476 } 1477 1478 void ShenandoahHeap::gc_threads_do(ThreadClosure* tcl) const { 1479 if (_shenandoah_policy->is_at_shutdown()) { 1480 return; 1481 } 1482 1483 if (_control_thread != nullptr) { 1484 tcl->do_thread(_control_thread); 1485 } 1486 1487 workers()->threads_do(tcl); 1488 if (_safepoint_workers != nullptr) { 1489 _safepoint_workers->threads_do(tcl); 1490 } 1491 } 1492 1493 void ShenandoahHeap::print_tracing_info() const { 1494 LogTarget(Info, gc, stats) lt; 1495 if (lt.is_enabled()) { 1496 ResourceMark rm; 1497 LogStream ls(lt); 1498 1499 phase_timings()->print_global_on(&ls); 1500 1501 ls.cr(); 1502 ls.cr(); 1503 1504 shenandoah_policy()->print_gc_stats(&ls); 1505 1506 ls.cr(); 1507 ls.cr(); 1508 } 1509 } 1510 1511 void ShenandoahHeap::set_gc_generation(ShenandoahGeneration* generation) { 1512 shenandoah_assert_control_or_vm_thread_at_safepoint(); 1513 _gc_generation = generation; 1514 } 1515 1516 // Active generation may only be set by the VM thread at a safepoint. 1517 void ShenandoahHeap::set_active_generation() { 1518 assert(Thread::current()->is_VM_thread(), "Only the VM Thread"); 1519 assert(SafepointSynchronize::is_at_safepoint(), "Only at a safepoint!"); 1520 assert(_gc_generation != nullptr, "Will set _active_generation to nullptr"); 1521 _active_generation = _gc_generation; 1522 } 1523 1524 void ShenandoahHeap::on_cycle_start(GCCause::Cause cause, ShenandoahGeneration* generation) { 1525 shenandoah_policy()->record_collection_cause(cause); 1526 1527 assert(gc_cause() == GCCause::_no_gc, "Over-writing cause"); 1528 assert(_gc_generation == nullptr, "Over-writing _gc_generation"); 1529 1530 set_gc_cause(cause); 1531 set_gc_generation(generation); 1532 1533 generation->heuristics()->record_cycle_start(); 1534 } 1535 1536 void ShenandoahHeap::on_cycle_end(ShenandoahGeneration* generation) { 1537 assert(gc_cause() != GCCause::_no_gc, "cause wasn't set"); 1538 assert(_gc_generation != nullptr, "_gc_generation wasn't set"); 1539 1540 generation->heuristics()->record_cycle_end(); 1541 if (mode()->is_generational() && generation->is_global()) { 1542 // If we just completed a GLOBAL GC, claim credit for completion of young-gen and old-gen GC as well 1543 young_generation()->heuristics()->record_cycle_end(); 1544 old_generation()->heuristics()->record_cycle_end(); 1545 } 1546 1547 set_gc_generation(nullptr); 1548 set_gc_cause(GCCause::_no_gc); 1549 } 1550 1551 void ShenandoahHeap::verify(VerifyOption vo) { 1552 if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) { 1553 if (ShenandoahVerify) { 1554 verifier()->verify_generic(vo); 1555 } else { 1556 // TODO: Consider allocating verification bitmaps on demand, 1557 // and turn this on unconditionally. 1558 } 1559 } 1560 } 1561 size_t ShenandoahHeap::tlab_capacity(Thread *thr) const { 1562 return _free_set->capacity(); 1563 } 1564 1565 class ObjectIterateScanRootClosure : public BasicOopIterateClosure { 1566 private: 1567 MarkBitMap* _bitmap; 1568 ShenandoahScanObjectStack* _oop_stack; 1569 ShenandoahHeap* const _heap; 1570 ShenandoahMarkingContext* const _marking_context; 1571 1572 template <class T> 1573 void do_oop_work(T* p) { 1574 T o = RawAccess<>::oop_load(p); 1575 if (!CompressedOops::is_null(o)) { 1576 oop obj = CompressedOops::decode_not_null(o); 1577 if (_heap->is_concurrent_weak_root_in_progress() && !_marking_context->is_marked(obj)) { 1578 // There may be dead oops in weak roots in concurrent root phase, do not touch them. 1579 return; 1580 } 1581 obj = ShenandoahBarrierSet::barrier_set()->load_reference_barrier(obj); 1582 1583 assert(oopDesc::is_oop(obj), "must be a valid oop"); 1584 if (!_bitmap->is_marked(obj)) { 1585 _bitmap->mark(obj); 1586 _oop_stack->push(obj); 1587 } 1588 } 1589 } 1590 public: 1591 ObjectIterateScanRootClosure(MarkBitMap* bitmap, ShenandoahScanObjectStack* oop_stack) : 1592 _bitmap(bitmap), _oop_stack(oop_stack), _heap(ShenandoahHeap::heap()), 1593 _marking_context(_heap->marking_context()) {} 1594 void do_oop(oop* p) { do_oop_work(p); } 1595 void do_oop(narrowOop* p) { do_oop_work(p); } 1596 }; 1597 1598 /* 1599 * This is public API, used in preparation of object_iterate(). 1600 * Since we don't do linear scan of heap in object_iterate() (see comment below), we don't 1601 * need to make the heap parsable. For Shenandoah-internal linear heap scans that we can 1602 * control, we call SH::tlabs_retire, SH::gclabs_retire. 1603 */ 1604 void ShenandoahHeap::ensure_parsability(bool retire_tlabs) { 1605 // No-op. 1606 } 1607 1608 /* 1609 * Iterates objects in the heap. This is public API, used for, e.g., heap dumping. 1610 * 1611 * We cannot safely iterate objects by doing a linear scan at random points in time. Linear 1612 * scanning needs to deal with dead objects, which may have dead Klass* pointers (e.g. 1613 * calling oopDesc::size() would crash) or dangling reference fields (crashes) etc. Linear 1614 * scanning therefore depends on having a valid marking bitmap to support it. However, we only 1615 * have a valid marking bitmap after successful marking. In particular, we *don't* have a valid 1616 * marking bitmap during marking, after aborted marking or during/after cleanup (when we just 1617 * wiped the bitmap in preparation for next marking). 1618 * 1619 * For all those reasons, we implement object iteration as a single marking traversal, reporting 1620 * objects as we mark+traverse through the heap, starting from GC roots. JVMTI IterateThroughHeap 1621 * is allowed to report dead objects, but is not required to do so. 1622 */ 1623 void ShenandoahHeap::object_iterate(ObjectClosure* cl) { 1624 // Reset bitmap 1625 if (!prepare_aux_bitmap_for_iteration()) 1626 return; 1627 1628 ShenandoahScanObjectStack oop_stack; 1629 ObjectIterateScanRootClosure oops(&_aux_bit_map, &oop_stack); 1630 // Seed the stack with root scan 1631 scan_roots_for_iteration(&oop_stack, &oops); 1632 1633 // Work through the oop stack to traverse heap 1634 while (! oop_stack.is_empty()) { 1635 oop obj = oop_stack.pop(); 1636 assert(oopDesc::is_oop(obj), "must be a valid oop"); 1637 cl->do_object(obj); 1638 obj->oop_iterate(&oops); 1639 } 1640 1641 assert(oop_stack.is_empty(), "should be empty"); 1642 // Reclaim bitmap 1643 reclaim_aux_bitmap_for_iteration(); 1644 } 1645 1646 bool ShenandoahHeap::prepare_aux_bitmap_for_iteration() { 1647 assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints"); 1648 1649 if (!_aux_bitmap_region_special && !os::commit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size(), false)) { 1650 log_warning(gc)("Could not commit native memory for auxiliary marking bitmap for heap iteration"); 1651 return false; 1652 } 1653 // Reset bitmap 1654 _aux_bit_map.clear(); 1655 return true; 1656 } 1657 1658 void ShenandoahHeap::scan_roots_for_iteration(ShenandoahScanObjectStack* oop_stack, ObjectIterateScanRootClosure* oops) { 1659 // Process GC roots according to current GC cycle 1660 // This populates the work stack with initial objects 1661 // It is important to relinquish the associated locks before diving 1662 // into heap dumper 1663 uint n_workers = safepoint_workers() != nullptr ? safepoint_workers()->active_workers() : 1; 1664 ShenandoahHeapIterationRootScanner rp(n_workers); 1665 rp.roots_do(oops); 1666 } 1667 1668 void ShenandoahHeap::reclaim_aux_bitmap_for_iteration() { 1669 if (!_aux_bitmap_region_special && !os::uncommit_memory((char*)_aux_bitmap_region.start(), _aux_bitmap_region.byte_size())) { 1670 log_warning(gc)("Could not uncommit native memory for auxiliary marking bitmap for heap iteration"); 1671 } 1672 } 1673 1674 // Closure for parallelly iterate objects 1675 class ShenandoahObjectIterateParScanClosure : public BasicOopIterateClosure { 1676 private: 1677 MarkBitMap* _bitmap; 1678 ShenandoahObjToScanQueue* _queue; 1679 ShenandoahHeap* const _heap; 1680 ShenandoahMarkingContext* const _marking_context; 1681 1682 template <class T> 1683 void do_oop_work(T* p) { 1684 T o = RawAccess<>::oop_load(p); 1685 if (!CompressedOops::is_null(o)) { 1686 oop obj = CompressedOops::decode_not_null(o); 1687 if (_heap->is_concurrent_weak_root_in_progress() && !_marking_context->is_marked(obj)) { 1688 // There may be dead oops in weak roots in concurrent root phase, do not touch them. 1689 return; 1690 } 1691 obj = ShenandoahBarrierSet::barrier_set()->load_reference_barrier(obj); 1692 1693 assert(oopDesc::is_oop(obj), "Must be a valid oop"); 1694 if (_bitmap->par_mark(obj)) { 1695 _queue->push(ShenandoahMarkTask(obj)); 1696 } 1697 } 1698 } 1699 public: 1700 ShenandoahObjectIterateParScanClosure(MarkBitMap* bitmap, ShenandoahObjToScanQueue* q) : 1701 _bitmap(bitmap), _queue(q), _heap(ShenandoahHeap::heap()), 1702 _marking_context(_heap->marking_context()) {} 1703 void do_oop(oop* p) { do_oop_work(p); } 1704 void do_oop(narrowOop* p) { do_oop_work(p); } 1705 }; 1706 1707 // Object iterator for parallel heap iteraion. 1708 // The root scanning phase happenes in construction as a preparation of 1709 // parallel marking queues. 1710 // Every worker processes it's own marking queue. work-stealing is used 1711 // to balance workload. 1712 class ShenandoahParallelObjectIterator : public ParallelObjectIteratorImpl { 1713 private: 1714 uint _num_workers; 1715 bool _init_ready; 1716 MarkBitMap* _aux_bit_map; 1717 ShenandoahHeap* _heap; 1718 ShenandoahScanObjectStack _roots_stack; // global roots stack 1719 ShenandoahObjToScanQueueSet* _task_queues; 1720 public: 1721 ShenandoahParallelObjectIterator(uint num_workers, MarkBitMap* bitmap) : 1722 _num_workers(num_workers), 1723 _init_ready(false), 1724 _aux_bit_map(bitmap), 1725 _heap(ShenandoahHeap::heap()) { 1726 // Initialize bitmap 1727 _init_ready = _heap->prepare_aux_bitmap_for_iteration(); 1728 if (!_init_ready) { 1729 return; 1730 } 1731 1732 ObjectIterateScanRootClosure oops(_aux_bit_map, &_roots_stack); 1733 _heap->scan_roots_for_iteration(&_roots_stack, &oops); 1734 1735 _init_ready = prepare_worker_queues(); 1736 } 1737 1738 ~ShenandoahParallelObjectIterator() { 1739 // Reclaim bitmap 1740 _heap->reclaim_aux_bitmap_for_iteration(); 1741 // Reclaim queue for workers 1742 if (_task_queues!= nullptr) { 1743 for (uint i = 0; i < _num_workers; ++i) { 1744 ShenandoahObjToScanQueue* q = _task_queues->queue(i); 1745 if (q != nullptr) { 1746 delete q; 1747 _task_queues->register_queue(i, nullptr); 1748 } 1749 } 1750 delete _task_queues; 1751 _task_queues = nullptr; 1752 } 1753 } 1754 1755 virtual void object_iterate(ObjectClosure* cl, uint worker_id) { 1756 if (_init_ready) { 1757 object_iterate_parallel(cl, worker_id, _task_queues); 1758 } 1759 } 1760 1761 private: 1762 // Divide global root_stack into worker queues 1763 bool prepare_worker_queues() { 1764 _task_queues = new ShenandoahObjToScanQueueSet((int) _num_workers); 1765 // Initialize queues for every workers 1766 for (uint i = 0; i < _num_workers; ++i) { 1767 ShenandoahObjToScanQueue* task_queue = new ShenandoahObjToScanQueue(); 1768 _task_queues->register_queue(i, task_queue); 1769 } 1770 // Divide roots among the workers. Assume that object referencing distribution 1771 // is related with root kind, use round-robin to make every worker have same chance 1772 // to process every kind of roots 1773 size_t roots_num = _roots_stack.size(); 1774 if (roots_num == 0) { 1775 // No work to do 1776 return false; 1777 } 1778 1779 for (uint j = 0; j < roots_num; j++) { 1780 uint stack_id = j % _num_workers; 1781 oop obj = _roots_stack.pop(); 1782 _task_queues->queue(stack_id)->push(ShenandoahMarkTask(obj)); 1783 } 1784 return true; 1785 } 1786 1787 void object_iterate_parallel(ObjectClosure* cl, 1788 uint worker_id, 1789 ShenandoahObjToScanQueueSet* queue_set) { 1790 assert(SafepointSynchronize::is_at_safepoint(), "safe iteration is only available during safepoints"); 1791 assert(queue_set != nullptr, "task queue must not be null"); 1792 1793 ShenandoahObjToScanQueue* q = queue_set->queue(worker_id); 1794 assert(q != nullptr, "object iterate queue must not be null"); 1795 1796 ShenandoahMarkTask t; 1797 ShenandoahObjectIterateParScanClosure oops(_aux_bit_map, q); 1798 1799 // Work through the queue to traverse heap. 1800 // Steal when there is no task in queue. 1801 while (q->pop(t) || queue_set->steal(worker_id, t)) { 1802 oop obj = t.obj(); 1803 assert(oopDesc::is_oop(obj), "must be a valid oop"); 1804 cl->do_object(obj); 1805 obj->oop_iterate(&oops); 1806 } 1807 assert(q->is_empty(), "should be empty"); 1808 } 1809 }; 1810 1811 ParallelObjectIteratorImpl* ShenandoahHeap::parallel_object_iterator(uint workers) { 1812 return new ShenandoahParallelObjectIterator(workers, &_aux_bit_map); 1813 } 1814 1815 // Keep alive an object that was loaded with AS_NO_KEEPALIVE. 1816 void ShenandoahHeap::keep_alive(oop obj) { 1817 if (is_concurrent_mark_in_progress() && (obj != nullptr)) { 1818 ShenandoahBarrierSet::barrier_set()->enqueue(obj); 1819 } 1820 } 1821 1822 void ShenandoahHeap::heap_region_iterate(ShenandoahHeapRegionClosure* blk) const { 1823 for (size_t i = 0; i < num_regions(); i++) { 1824 ShenandoahHeapRegion* current = get_region(i); 1825 blk->heap_region_do(current); 1826 } 1827 } 1828 1829 class ShenandoahParallelHeapRegionTask : public WorkerTask { 1830 private: 1831 ShenandoahHeap* const _heap; 1832 ShenandoahHeapRegionClosure* const _blk; 1833 size_t const _stride; 1834 1835 shenandoah_padding(0); 1836 volatile size_t _index; 1837 shenandoah_padding(1); 1838 1839 public: 1840 ShenandoahParallelHeapRegionTask(ShenandoahHeapRegionClosure* blk, size_t stride) : 1841 WorkerTask("Shenandoah Parallel Region Operation"), 1842 _heap(ShenandoahHeap::heap()), _blk(blk), _stride(stride), _index(0) {} 1843 1844 void work(uint worker_id) { 1845 ShenandoahParallelWorkerSession worker_session(worker_id); 1846 size_t stride = _stride; 1847 1848 size_t max = _heap->num_regions(); 1849 while (Atomic::load(&_index) < max) { 1850 size_t cur = Atomic::fetch_then_add(&_index, stride, memory_order_relaxed); 1851 size_t start = cur; 1852 size_t end = MIN2(cur + stride, max); 1853 if (start >= max) break; 1854 1855 for (size_t i = cur; i < end; i++) { 1856 ShenandoahHeapRegion* current = _heap->get_region(i); 1857 _blk->heap_region_do(current); 1858 } 1859 } 1860 } 1861 }; 1862 1863 void ShenandoahHeap::parallel_heap_region_iterate(ShenandoahHeapRegionClosure* blk) const { 1864 assert(blk->is_thread_safe(), "Only thread-safe closures here"); 1865 const uint active_workers = workers()->active_workers(); 1866 const size_t n_regions = num_regions(); 1867 size_t stride = ShenandoahParallelRegionStride; 1868 if (stride == 0 && active_workers > 1) { 1869 // Automatically derive the stride to balance the work between threads 1870 // evenly. Do not try to split work if below the reasonable threshold. 1871 constexpr size_t threshold = 4096; 1872 stride = n_regions <= threshold ? 1873 threshold : 1874 (n_regions + active_workers - 1) / active_workers; 1875 } 1876 1877 if (n_regions > stride && active_workers > 1) { 1878 ShenandoahParallelHeapRegionTask task(blk, stride); 1879 workers()->run_task(&task); 1880 } else { 1881 heap_region_iterate(blk); 1882 } 1883 } 1884 1885 class ShenandoahRendezvousClosure : public HandshakeClosure { 1886 public: 1887 inline ShenandoahRendezvousClosure() : HandshakeClosure("ShenandoahRendezvous") {} 1888 inline void do_thread(Thread* thread) {} 1889 }; 1890 1891 void ShenandoahHeap::rendezvous_threads() { 1892 ShenandoahRendezvousClosure cl; 1893 Handshake::execute(&cl); 1894 } 1895 1896 void ShenandoahHeap::recycle_trash() { 1897 free_set()->recycle_trash(); 1898 } 1899 1900 void ShenandoahHeap::do_class_unloading() { 1901 _unloader.unload(); 1902 if (mode()->is_generational()) { 1903 old_generation()->set_parsable(false); 1904 } 1905 } 1906 1907 void ShenandoahHeap::stw_weak_refs(bool full_gc) { 1908 // Weak refs processing 1909 ShenandoahPhaseTimings::Phase phase = full_gc ? ShenandoahPhaseTimings::full_gc_weakrefs 1910 : ShenandoahPhaseTimings::degen_gc_weakrefs; 1911 ShenandoahTimingsTracker t(phase); 1912 ShenandoahGCWorkerPhase worker_phase(phase); 1913 shenandoah_assert_generations_reconciled(); 1914 gc_generation()->ref_processor()->process_references(phase, workers(), false /* concurrent */); 1915 } 1916 1917 void ShenandoahHeap::prepare_update_heap_references(bool concurrent) { 1918 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint"); 1919 1920 // Evacuation is over, no GCLABs are needed anymore. GCLABs are under URWM, so we need to 1921 // make them parsable for update code to work correctly. Plus, we can compute new sizes 1922 // for future GCLABs here. 1923 if (UseTLAB) { 1924 ShenandoahGCPhase phase(concurrent ? 1925 ShenandoahPhaseTimings::init_update_refs_manage_gclabs : 1926 ShenandoahPhaseTimings::degen_gc_init_update_refs_manage_gclabs); 1927 gclabs_retire(ResizeTLAB); 1928 } 1929 1930 _update_refs_iterator.reset(); 1931 } 1932 1933 void ShenandoahHeap::propagate_gc_state_to_java_threads() { 1934 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at Shenandoah safepoint"); 1935 if (_gc_state_changed) { 1936 _gc_state_changed = false; 1937 char state = gc_state(); 1938 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) { 1939 ShenandoahThreadLocalData::set_gc_state(t, state); 1940 } 1941 } 1942 } 1943 1944 void ShenandoahHeap::set_gc_state(uint mask, bool value) { 1945 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Must be at Shenandoah safepoint"); 1946 _gc_state.set_cond(mask, value); 1947 _gc_state_changed = true; 1948 // Check that if concurrent weak root is set then active_gen isn't null 1949 assert(!is_concurrent_weak_root_in_progress() || active_generation() != nullptr, "Error"); 1950 shenandoah_assert_generations_reconciled(); 1951 } 1952 1953 void ShenandoahHeap::set_concurrent_young_mark_in_progress(bool in_progress) { 1954 uint mask; 1955 assert(!has_forwarded_objects(), "Young marking is not concurrent with evacuation"); 1956 if (!in_progress && is_concurrent_old_mark_in_progress()) { 1957 assert(mode()->is_generational(), "Only generational GC has old marking"); 1958 assert(_gc_state.is_set(MARKING), "concurrent_old_marking_in_progress implies MARKING"); 1959 // If old-marking is in progress when we turn off YOUNG_MARKING, leave MARKING (and OLD_MARKING) on 1960 mask = YOUNG_MARKING; 1961 } else { 1962 mask = MARKING | YOUNG_MARKING; 1963 } 1964 set_gc_state(mask, in_progress); 1965 manage_satb_barrier(in_progress); 1966 } 1967 1968 void ShenandoahHeap::set_concurrent_old_mark_in_progress(bool in_progress) { 1969 #ifdef ASSERT 1970 // has_forwarded_objects() iff UPDATEREFS or EVACUATION 1971 bool has_forwarded = has_forwarded_objects(); 1972 bool updating_or_evacuating = _gc_state.is_set(UPDATEREFS | EVACUATION); 1973 bool evacuating = _gc_state.is_set(EVACUATION); 1974 assert ((has_forwarded == updating_or_evacuating) || (evacuating && !has_forwarded && collection_set()->is_empty()), 1975 "Updating or evacuating iff has forwarded objects, or if evacuation phase is promoting in place without forwarding"); 1976 #endif 1977 if (!in_progress && is_concurrent_young_mark_in_progress()) { 1978 // If young-marking is in progress when we turn off OLD_MARKING, leave MARKING (and YOUNG_MARKING) on 1979 assert(_gc_state.is_set(MARKING), "concurrent_young_marking_in_progress implies MARKING"); 1980 set_gc_state(OLD_MARKING, in_progress); 1981 } else { 1982 set_gc_state(MARKING | OLD_MARKING, in_progress); 1983 } 1984 manage_satb_barrier(in_progress); 1985 } 1986 1987 bool ShenandoahHeap::is_prepare_for_old_mark_in_progress() const { 1988 return old_generation()->is_preparing_for_mark(); 1989 } 1990 1991 void ShenandoahHeap::manage_satb_barrier(bool active) { 1992 if (is_concurrent_mark_in_progress()) { 1993 // Ignore request to deactivate barrier while concurrent mark is in progress. 1994 // Do not attempt to re-activate the barrier if it is already active. 1995 if (active && !ShenandoahBarrierSet::satb_mark_queue_set().is_active()) { 1996 ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(active, !active); 1997 } 1998 } else { 1999 // No concurrent marking is in progress so honor request to deactivate, 2000 // but only if the barrier is already active. 2001 if (!active && ShenandoahBarrierSet::satb_mark_queue_set().is_active()) { 2002 ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(active, !active); 2003 } 2004 } 2005 } 2006 2007 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) { 2008 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint"); 2009 set_gc_state(EVACUATION, in_progress); 2010 } 2011 2012 void ShenandoahHeap::set_concurrent_strong_root_in_progress(bool in_progress) { 2013 if (in_progress) { 2014 _concurrent_strong_root_in_progress.set(); 2015 } else { 2016 _concurrent_strong_root_in_progress.unset(); 2017 } 2018 } 2019 2020 void ShenandoahHeap::set_concurrent_weak_root_in_progress(bool cond) { 2021 set_gc_state(WEAK_ROOTS, cond); 2022 } 2023 2024 GCTracer* ShenandoahHeap::tracer() { 2025 return shenandoah_policy()->tracer(); 2026 } 2027 2028 size_t ShenandoahHeap::tlab_used(Thread* thread) const { 2029 return _free_set->used(); 2030 } 2031 2032 bool ShenandoahHeap::try_cancel_gc() { 2033 jbyte prev = _cancelled_gc.cmpxchg(CANCELLED, CANCELLABLE); 2034 return prev == CANCELLABLE; 2035 } 2036 2037 void ShenandoahHeap::cancel_concurrent_mark() { 2038 if (mode()->is_generational()) { 2039 young_generation()->cancel_marking(); 2040 old_generation()->cancel_marking(); 2041 } 2042 2043 global_generation()->cancel_marking(); 2044 2045 ShenandoahBarrierSet::satb_mark_queue_set().abandon_partial_marking(); 2046 } 2047 2048 void ShenandoahHeap::cancel_gc(GCCause::Cause cause) { 2049 if (try_cancel_gc()) { 2050 FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause)); 2051 log_info(gc)("%s", msg.buffer()); 2052 Events::log(Thread::current(), "%s", msg.buffer()); 2053 _cancel_requested_time = os::elapsedTime(); 2054 } 2055 } 2056 2057 uint ShenandoahHeap::max_workers() { 2058 return _max_workers; 2059 } 2060 2061 void ShenandoahHeap::stop() { 2062 // The shutdown sequence should be able to terminate when GC is running. 2063 2064 // Step 0. Notify policy to disable event recording. 2065 _shenandoah_policy->record_shutdown(); 2066 2067 // Step 1. Notify control thread that we are in shutdown. 2068 // Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown. 2069 // Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below. 2070 control_thread()->prepare_for_graceful_shutdown(); 2071 2072 // Step 2. Notify GC workers that we are cancelling GC. 2073 cancel_gc(GCCause::_shenandoah_stop_vm); 2074 2075 // Step 3. Wait until GC worker exits normally. 2076 control_thread()->stop(); 2077 } 2078 2079 void ShenandoahHeap::stw_unload_classes(bool full_gc) { 2080 if (!unload_classes()) return; 2081 ClassUnloadingContext ctx(_workers->active_workers(), 2082 true /* unregister_nmethods_during_purge */, 2083 false /* lock_codeblob_free_separately */); 2084 2085 // Unload classes and purge SystemDictionary. 2086 { 2087 ShenandoahPhaseTimings::Phase phase = full_gc ? 2088 ShenandoahPhaseTimings::full_gc_purge_class_unload : 2089 ShenandoahPhaseTimings::degen_gc_purge_class_unload; 2090 ShenandoahIsAliveSelector is_alive; 2091 { 2092 CodeCache::UnlinkingScope scope(is_alive.is_alive_closure()); 2093 ShenandoahGCPhase gc_phase(phase); 2094 ShenandoahGCWorkerPhase worker_phase(phase); 2095 bool unloading_occurred = SystemDictionary::do_unloading(gc_timer()); 2096 2097 uint num_workers = _workers->active_workers(); 2098 ShenandoahClassUnloadingTask unlink_task(phase, num_workers, unloading_occurred); 2099 _workers->run_task(&unlink_task); 2100 } 2101 // Release unloaded nmethods's memory. 2102 ClassUnloadingContext::context()->purge_and_free_nmethods(); 2103 } 2104 2105 { 2106 ShenandoahGCPhase phase(full_gc ? 2107 ShenandoahPhaseTimings::full_gc_purge_cldg : 2108 ShenandoahPhaseTimings::degen_gc_purge_cldg); 2109 ClassLoaderDataGraph::purge(true /* at_safepoint */); 2110 } 2111 // Resize and verify metaspace 2112 MetaspaceGC::compute_new_size(); 2113 DEBUG_ONLY(MetaspaceUtils::verify();) 2114 } 2115 2116 // Weak roots are either pre-evacuated (final mark) or updated (final updaterefs), 2117 // so they should not have forwarded oops. 2118 // However, we do need to "null" dead oops in the roots, if can not be done 2119 // in concurrent cycles. 2120 void ShenandoahHeap::stw_process_weak_roots(bool full_gc) { 2121 uint num_workers = _workers->active_workers(); 2122 ShenandoahPhaseTimings::Phase timing_phase = full_gc ? 2123 ShenandoahPhaseTimings::full_gc_purge_weak_par : 2124 ShenandoahPhaseTimings::degen_gc_purge_weak_par; 2125 ShenandoahGCPhase phase(timing_phase); 2126 ShenandoahGCWorkerPhase worker_phase(timing_phase); 2127 // Cleanup weak roots 2128 if (has_forwarded_objects()) { 2129 ShenandoahForwardedIsAliveClosure is_alive; 2130 ShenandoahUpdateRefsClosure keep_alive; 2131 ShenandoahParallelWeakRootsCleaningTask<ShenandoahForwardedIsAliveClosure, ShenandoahUpdateRefsClosure> 2132 cleaning_task(timing_phase, &is_alive, &keep_alive, num_workers); 2133 _workers->run_task(&cleaning_task); 2134 } else { 2135 ShenandoahIsAliveClosure is_alive; 2136 #ifdef ASSERT 2137 ShenandoahAssertNotForwardedClosure verify_cl; 2138 ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, ShenandoahAssertNotForwardedClosure> 2139 cleaning_task(timing_phase, &is_alive, &verify_cl, num_workers); 2140 #else 2141 ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, DoNothingClosure> 2142 cleaning_task(timing_phase, &is_alive, &do_nothing_cl, num_workers); 2143 #endif 2144 _workers->run_task(&cleaning_task); 2145 } 2146 } 2147 2148 void ShenandoahHeap::parallel_cleaning(bool full_gc) { 2149 assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint"); 2150 assert(is_stw_gc_in_progress(), "Only for Degenerated and Full GC"); 2151 ShenandoahGCPhase phase(full_gc ? 2152 ShenandoahPhaseTimings::full_gc_purge : 2153 ShenandoahPhaseTimings::degen_gc_purge); 2154 stw_weak_refs(full_gc); 2155 stw_process_weak_roots(full_gc); 2156 stw_unload_classes(full_gc); 2157 } 2158 2159 void ShenandoahHeap::set_has_forwarded_objects(bool cond) { 2160 set_gc_state(HAS_FORWARDED, cond); 2161 } 2162 2163 void ShenandoahHeap::set_unload_classes(bool uc) { 2164 _unload_classes.set_cond(uc); 2165 } 2166 2167 bool ShenandoahHeap::unload_classes() const { 2168 return _unload_classes.is_set(); 2169 } 2170 2171 address ShenandoahHeap::in_cset_fast_test_addr() { 2172 ShenandoahHeap* heap = ShenandoahHeap::heap(); 2173 assert(heap->collection_set() != nullptr, "Sanity"); 2174 return (address) heap->collection_set()->biased_map_address(); 2175 } 2176 2177 void ShenandoahHeap::reset_bytes_allocated_since_gc_start() { 2178 if (mode()->is_generational()) { 2179 young_generation()->reset_bytes_allocated_since_gc_start(); 2180 old_generation()->reset_bytes_allocated_since_gc_start(); 2181 } 2182 2183 global_generation()->reset_bytes_allocated_since_gc_start(); 2184 } 2185 2186 void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) { 2187 _degenerated_gc_in_progress.set_cond(in_progress); 2188 } 2189 2190 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) { 2191 _full_gc_in_progress.set_cond(in_progress); 2192 } 2193 2194 void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) { 2195 assert (is_full_gc_in_progress(), "should be"); 2196 _full_gc_move_in_progress.set_cond(in_progress); 2197 } 2198 2199 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) { 2200 set_gc_state(UPDATEREFS, in_progress); 2201 } 2202 2203 void ShenandoahHeap::register_nmethod(nmethod* nm) { 2204 ShenandoahCodeRoots::register_nmethod(nm); 2205 } 2206 2207 void ShenandoahHeap::unregister_nmethod(nmethod* nm) { 2208 ShenandoahCodeRoots::unregister_nmethod(nm); 2209 } 2210 2211 void ShenandoahHeap::pin_object(JavaThread* thr, oop o) { 2212 heap_region_containing(o)->record_pin(); 2213 } 2214 2215 void ShenandoahHeap::unpin_object(JavaThread* thr, oop o) { 2216 ShenandoahHeapRegion* r = heap_region_containing(o); 2217 assert(r != nullptr, "Sanity"); 2218 assert(r->pin_count() > 0, "Region " SIZE_FORMAT " should have non-zero pins", r->index()); 2219 r->record_unpin(); 2220 } 2221 2222 void ShenandoahHeap::sync_pinned_region_status() { 2223 ShenandoahHeapLocker locker(lock()); 2224 2225 for (size_t i = 0; i < num_regions(); i++) { 2226 ShenandoahHeapRegion *r = get_region(i); 2227 if (r->is_active()) { 2228 if (r->is_pinned()) { 2229 if (r->pin_count() == 0) { 2230 r->make_unpinned(); 2231 } 2232 } else { 2233 if (r->pin_count() > 0) { 2234 r->make_pinned(); 2235 } 2236 } 2237 } 2238 } 2239 2240 assert_pinned_region_status(); 2241 } 2242 2243 #ifdef ASSERT 2244 void ShenandoahHeap::assert_pinned_region_status() { 2245 for (size_t i = 0; i < num_regions(); i++) { 2246 ShenandoahHeapRegion* r = get_region(i); 2247 shenandoah_assert_generations_reconciled(); 2248 if (gc_generation()->contains(r)) { 2249 assert((r->is_pinned() && r->pin_count() > 0) || (!r->is_pinned() && r->pin_count() == 0), 2250 "Region " SIZE_FORMAT " pinning status is inconsistent", i); 2251 } 2252 } 2253 } 2254 #endif 2255 2256 ConcurrentGCTimer* ShenandoahHeap::gc_timer() const { 2257 return _gc_timer; 2258 } 2259 2260 void ShenandoahHeap::prepare_concurrent_roots() { 2261 assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint"); 2262 assert(!is_stw_gc_in_progress(), "Only concurrent GC"); 2263 set_concurrent_strong_root_in_progress(!collection_set()->is_empty()); 2264 set_concurrent_weak_root_in_progress(true); 2265 if (unload_classes()) { 2266 _unloader.prepare(); 2267 } 2268 } 2269 2270 void ShenandoahHeap::finish_concurrent_roots() { 2271 assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint"); 2272 assert(!is_stw_gc_in_progress(), "Only concurrent GC"); 2273 if (unload_classes()) { 2274 _unloader.finish(); 2275 } 2276 } 2277 2278 #ifdef ASSERT 2279 void ShenandoahHeap::assert_gc_workers(uint nworkers) { 2280 assert(nworkers > 0 && nworkers <= max_workers(), "Sanity"); 2281 2282 if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) { 2283 // Use ParallelGCThreads inside safepoints 2284 assert(nworkers == ParallelGCThreads, "Use ParallelGCThreads (%u) within safepoint, not %u", 2285 ParallelGCThreads, nworkers); 2286 } else { 2287 // Use ConcGCThreads outside safepoints 2288 assert(nworkers == ConcGCThreads, "Use ConcGCThreads (%u) outside safepoints, %u", 2289 ConcGCThreads, nworkers); 2290 } 2291 } 2292 #endif 2293 2294 ShenandoahVerifier* ShenandoahHeap::verifier() { 2295 guarantee(ShenandoahVerify, "Should be enabled"); 2296 assert (_verifier != nullptr, "sanity"); 2297 return _verifier; 2298 } 2299 2300 template<bool CONCURRENT> 2301 class ShenandoahUpdateHeapRefsTask : public WorkerTask { 2302 private: 2303 ShenandoahHeap* _heap; 2304 ShenandoahRegionIterator* _regions; 2305 public: 2306 explicit ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions) : 2307 WorkerTask("Shenandoah Update References"), 2308 _heap(ShenandoahHeap::heap()), 2309 _regions(regions) { 2310 } 2311 2312 void work(uint worker_id) { 2313 if (CONCURRENT) { 2314 ShenandoahConcurrentWorkerSession worker_session(worker_id); 2315 ShenandoahSuspendibleThreadSetJoiner stsj; 2316 do_work<ShenandoahConcUpdateRefsClosure>(worker_id); 2317 } else { 2318 ShenandoahParallelWorkerSession worker_session(worker_id); 2319 do_work<ShenandoahSTWUpdateRefsClosure>(worker_id); 2320 } 2321 } 2322 2323 private: 2324 template<class T> 2325 void do_work(uint worker_id) { 2326 if (CONCURRENT && (worker_id == 0)) { 2327 // We ask the first worker to replenish the Mutator free set by moving regions previously reserved to hold the 2328 // results of evacuation. These reserves are no longer necessary because evacuation has completed. 2329 size_t cset_regions = _heap->collection_set()->count(); 2330 2331 // Now that evacuation is done, we can reassign any regions that had been reserved to hold the results of evacuation 2332 // to the mutator free set. At the end of GC, we will have cset_regions newly evacuated fully empty regions from 2333 // which we will be able to replenish the Collector free set and the OldCollector free set in preparation for the 2334 // next GC cycle. 2335 _heap->free_set()->move_regions_from_collector_to_mutator(cset_regions); 2336 } 2337 // If !CONCURRENT, there's no value in expanding Mutator free set 2338 T cl; 2339 ShenandoahHeapRegion* r = _regions->next(); 2340 while (r != nullptr) { 2341 HeapWord* update_watermark = r->get_update_watermark(); 2342 assert (update_watermark >= r->bottom(), "sanity"); 2343 if (r->is_active() && !r->is_cset()) { 2344 _heap->marked_object_oop_iterate(r, &cl, update_watermark); 2345 if (ShenandoahPacing) { 2346 _heap->pacer()->report_updaterefs(pointer_delta(update_watermark, r->bottom())); 2347 } 2348 } 2349 if (_heap->check_cancelled_gc_and_yield(CONCURRENT)) { 2350 return; 2351 } 2352 r = _regions->next(); 2353 } 2354 } 2355 }; 2356 2357 void ShenandoahHeap::update_heap_references(bool concurrent) { 2358 assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC"); 2359 2360 if (concurrent) { 2361 ShenandoahUpdateHeapRefsTask<true> task(&_update_refs_iterator); 2362 workers()->run_task(&task); 2363 } else { 2364 ShenandoahUpdateHeapRefsTask<false> task(&_update_refs_iterator); 2365 workers()->run_task(&task); 2366 } 2367 } 2368 2369 ShenandoahSynchronizePinnedRegionStates::ShenandoahSynchronizePinnedRegionStates() : _lock(ShenandoahHeap::heap()->lock()) { } 2370 2371 void ShenandoahSynchronizePinnedRegionStates::heap_region_do(ShenandoahHeapRegion* r) { 2372 // Drop "pinned" state from regions that no longer have a pinned count. Put 2373 // regions with a pinned count into the "pinned" state. 2374 if (r->is_active()) { 2375 if (r->is_pinned()) { 2376 if (r->pin_count() == 0) { 2377 ShenandoahHeapLocker locker(_lock); 2378 r->make_unpinned(); 2379 } 2380 } else { 2381 if (r->pin_count() > 0) { 2382 ShenandoahHeapLocker locker(_lock); 2383 r->make_pinned(); 2384 } 2385 } 2386 } 2387 } 2388 2389 void ShenandoahHeap::update_heap_region_states(bool concurrent) { 2390 assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint"); 2391 assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC"); 2392 2393 { 2394 ShenandoahGCPhase phase(concurrent ? 2395 ShenandoahPhaseTimings::final_update_refs_update_region_states : 2396 ShenandoahPhaseTimings::degen_gc_final_update_refs_update_region_states); 2397 2398 final_update_refs_update_region_states(); 2399 2400 assert_pinned_region_status(); 2401 } 2402 2403 { 2404 ShenandoahGCPhase phase(concurrent ? 2405 ShenandoahPhaseTimings::final_update_refs_trash_cset : 2406 ShenandoahPhaseTimings::degen_gc_final_update_refs_trash_cset); 2407 trash_cset_regions(); 2408 } 2409 } 2410 2411 void ShenandoahHeap::final_update_refs_update_region_states() { 2412 ShenandoahSynchronizePinnedRegionStates cl; 2413 parallel_heap_region_iterate(&cl); 2414 } 2415 2416 void ShenandoahHeap::rebuild_free_set(bool concurrent) { 2417 ShenandoahGCPhase phase(concurrent ? 2418 ShenandoahPhaseTimings::final_update_refs_rebuild_freeset : 2419 ShenandoahPhaseTimings::degen_gc_final_update_refs_rebuild_freeset); 2420 ShenandoahHeapLocker locker(lock()); 2421 size_t young_cset_regions, old_cset_regions; 2422 size_t first_old_region, last_old_region, old_region_count; 2423 _free_set->prepare_to_rebuild(young_cset_regions, old_cset_regions, first_old_region, last_old_region, old_region_count); 2424 // If there are no old regions, first_old_region will be greater than last_old_region 2425 assert((first_old_region > last_old_region) || 2426 ((last_old_region + 1 - first_old_region >= old_region_count) && 2427 get_region(first_old_region)->is_old() && get_region(last_old_region)->is_old()), 2428 "sanity: old_region_count: " SIZE_FORMAT ", first_old_region: " SIZE_FORMAT ", last_old_region: " SIZE_FORMAT, 2429 old_region_count, first_old_region, last_old_region); 2430 2431 if (mode()->is_generational()) { 2432 #ifdef ASSERT 2433 if (ShenandoahVerify) { 2434 verifier()->verify_before_rebuilding_free_set(); 2435 } 2436 #endif 2437 2438 // The computation of bytes_of_allocation_runway_before_gc_trigger is quite conservative so consider all of this 2439 // available for transfer to old. Note that transfer of humongous regions does not impact available. 2440 ShenandoahGenerationalHeap* gen_heap = ShenandoahGenerationalHeap::heap(); 2441 size_t allocation_runway = gen_heap->young_generation()->heuristics()->bytes_of_allocation_runway_before_gc_trigger(young_cset_regions); 2442 gen_heap->compute_old_generation_balance(allocation_runway, old_cset_regions); 2443 2444 // Total old_available may have been expanded to hold anticipated promotions. We trigger if the fragmented available 2445 // memory represents more than 16 regions worth of data. Note that fragmentation may increase when we promote regular 2446 // regions in place when many of these regular regions have an abundant amount of available memory within them. Fragmentation 2447 // will decrease as promote-by-copy consumes the available memory within these partially consumed regions. 2448 // 2449 // We consider old-gen to have excessive fragmentation if more than 12.5% of old-gen is free memory that resides 2450 // within partially consumed regions of memory. 2451 } 2452 // Rebuild free set based on adjusted generation sizes. 2453 _free_set->finish_rebuild(young_cset_regions, old_cset_regions, old_region_count); 2454 2455 if (mode()->is_generational()) { 2456 ShenandoahGenerationalHeap* gen_heap = ShenandoahGenerationalHeap::heap(); 2457 ShenandoahOldGeneration* old_gen = gen_heap->old_generation(); 2458 old_gen->heuristics()->evaluate_triggers(first_old_region, last_old_region, old_region_count, num_regions()); 2459 } 2460 } 2461 2462 void ShenandoahHeap::print_extended_on(outputStream *st) const { 2463 print_on(st); 2464 st->cr(); 2465 print_heap_regions_on(st); 2466 } 2467 2468 bool ShenandoahHeap::is_bitmap_slice_committed(ShenandoahHeapRegion* r, bool skip_self) { 2469 size_t slice = r->index() / _bitmap_regions_per_slice; 2470 2471 size_t regions_from = _bitmap_regions_per_slice * slice; 2472 size_t regions_to = MIN2(num_regions(), _bitmap_regions_per_slice * (slice + 1)); 2473 for (size_t g = regions_from; g < regions_to; g++) { 2474 assert (g / _bitmap_regions_per_slice == slice, "same slice"); 2475 if (skip_self && g == r->index()) continue; 2476 if (get_region(g)->is_committed()) { 2477 return true; 2478 } 2479 } 2480 return false; 2481 } 2482 2483 bool ShenandoahHeap::commit_bitmap_slice(ShenandoahHeapRegion* r) { 2484 shenandoah_assert_heaplocked(); 2485 2486 // Bitmaps in special regions do not need commits 2487 if (_bitmap_region_special) { 2488 return true; 2489 } 2490 2491 if (is_bitmap_slice_committed(r, true)) { 2492 // Some other region from the group is already committed, meaning the bitmap 2493 // slice is already committed, we exit right away. 2494 return true; 2495 } 2496 2497 // Commit the bitmap slice: 2498 size_t slice = r->index() / _bitmap_regions_per_slice; 2499 size_t off = _bitmap_bytes_per_slice * slice; 2500 size_t len = _bitmap_bytes_per_slice; 2501 char* start = (char*) _bitmap_region.start() + off; 2502 2503 if (!os::commit_memory(start, len, false)) { 2504 return false; 2505 } 2506 2507 if (AlwaysPreTouch) { 2508 os::pretouch_memory(start, start + len, _pretouch_bitmap_page_size); 2509 } 2510 2511 return true; 2512 } 2513 2514 bool ShenandoahHeap::uncommit_bitmap_slice(ShenandoahHeapRegion *r) { 2515 shenandoah_assert_heaplocked(); 2516 2517 // Bitmaps in special regions do not need uncommits 2518 if (_bitmap_region_special) { 2519 return true; 2520 } 2521 2522 if (is_bitmap_slice_committed(r, true)) { 2523 // Some other region from the group is still committed, meaning the bitmap 2524 // slice is should stay committed, exit right away. 2525 return true; 2526 } 2527 2528 // Uncommit the bitmap slice: 2529 size_t slice = r->index() / _bitmap_regions_per_slice; 2530 size_t off = _bitmap_bytes_per_slice * slice; 2531 size_t len = _bitmap_bytes_per_slice; 2532 if (!os::uncommit_memory((char*)_bitmap_region.start() + off, len)) { 2533 return false; 2534 } 2535 return true; 2536 } 2537 2538 void ShenandoahHeap::safepoint_synchronize_begin() { 2539 SuspendibleThreadSet::synchronize(); 2540 } 2541 2542 void ShenandoahHeap::safepoint_synchronize_end() { 2543 SuspendibleThreadSet::desynchronize(); 2544 } 2545 2546 void ShenandoahHeap::try_inject_alloc_failure() { 2547 if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) { 2548 _inject_alloc_failure.set(); 2549 os::naked_short_sleep(1); 2550 if (cancelled_gc()) { 2551 log_info(gc)("Allocation failure was successfully injected"); 2552 } 2553 } 2554 } 2555 2556 bool ShenandoahHeap::should_inject_alloc_failure() { 2557 return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset(); 2558 } 2559 2560 void ShenandoahHeap::initialize_serviceability() { 2561 _memory_pool = new ShenandoahMemoryPool(this); 2562 _cycle_memory_manager.add_pool(_memory_pool); 2563 _stw_memory_manager.add_pool(_memory_pool); 2564 } 2565 2566 GrowableArray<GCMemoryManager*> ShenandoahHeap::memory_managers() { 2567 GrowableArray<GCMemoryManager*> memory_managers(2); 2568 memory_managers.append(&_cycle_memory_manager); 2569 memory_managers.append(&_stw_memory_manager); 2570 return memory_managers; 2571 } 2572 2573 GrowableArray<MemoryPool*> ShenandoahHeap::memory_pools() { 2574 GrowableArray<MemoryPool*> memory_pools(1); 2575 memory_pools.append(_memory_pool); 2576 return memory_pools; 2577 } 2578 2579 MemoryUsage ShenandoahHeap::memory_usage() { 2580 return MemoryUsage(_initial_size, used(), committed(), max_capacity()); 2581 } 2582 2583 ShenandoahRegionIterator::ShenandoahRegionIterator() : 2584 _heap(ShenandoahHeap::heap()), 2585 _index(0) {} 2586 2587 ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) : 2588 _heap(heap), 2589 _index(0) {} 2590 2591 void ShenandoahRegionIterator::reset() { 2592 _index = 0; 2593 } 2594 2595 bool ShenandoahRegionIterator::has_next() const { 2596 return _index < _heap->num_regions(); 2597 } 2598 2599 char ShenandoahHeap::gc_state() const { 2600 return _gc_state.raw_value(); 2601 } 2602 2603 ShenandoahLiveData* ShenandoahHeap::get_liveness_cache(uint worker_id) { 2604 #ifdef ASSERT 2605 assert(_liveness_cache != nullptr, "sanity"); 2606 assert(worker_id < _max_workers, "sanity"); 2607 for (uint i = 0; i < num_regions(); i++) { 2608 assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty"); 2609 } 2610 #endif 2611 return _liveness_cache[worker_id]; 2612 } 2613 2614 void ShenandoahHeap::flush_liveness_cache(uint worker_id) { 2615 assert(worker_id < _max_workers, "sanity"); 2616 assert(_liveness_cache != nullptr, "sanity"); 2617 ShenandoahLiveData* ld = _liveness_cache[worker_id]; 2618 for (uint i = 0; i < num_regions(); i++) { 2619 ShenandoahLiveData live = ld[i]; 2620 if (live > 0) { 2621 ShenandoahHeapRegion* r = get_region(i); 2622 r->increase_live_data_gc_words(live); 2623 ld[i] = 0; 2624 } 2625 } 2626 } 2627 2628 bool ShenandoahHeap::requires_barriers(stackChunkOop obj) const { 2629 if (is_idle()) return false; 2630 2631 // Objects allocated after marking start are implicitly alive, don't need any barriers during 2632 // marking phase. 2633 if (is_concurrent_mark_in_progress() && 2634 !marking_context()->allocated_after_mark_start(obj)) { 2635 return true; 2636 } 2637 2638 // Can not guarantee obj is deeply good. 2639 if (has_forwarded_objects()) { 2640 return true; 2641 } 2642 2643 return false; 2644 } 2645 2646 ShenandoahGeneration* ShenandoahHeap::generation_for(ShenandoahAffiliation affiliation) const { 2647 if (!mode()->is_generational()) { 2648 return global_generation(); 2649 } else if (affiliation == YOUNG_GENERATION) { 2650 return young_generation(); 2651 } else if (affiliation == OLD_GENERATION) { 2652 return old_generation(); 2653 } 2654 2655 ShouldNotReachHere(); 2656 return nullptr; 2657 } 2658 2659 void ShenandoahHeap::log_heap_status(const char* msg) const { 2660 if (mode()->is_generational()) { 2661 young_generation()->log_status(msg); 2662 old_generation()->log_status(msg); 2663 } else { 2664 global_generation()->log_status(msg); 2665 } 2666 }