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