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