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