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