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