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