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