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