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