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 1388 if (ShenandoahVerify) { 1389 verifier()->verify_before_concmark(); 1390 } 1391 1392 if (VerifyBeforeGC) { 1393 Universe::verify(); 1394 } 1395 1396 set_concurrent_mark_in_progress(true); 1397 // We need to reset all TLABs because we'd lose marks on all objects allocated in them. 1398 { 1399 ShenandoahGCPhase phase(ShenandoahPhaseTimings::make_parsable); 1400 make_parsable(true); 1401 } 1402 1403 { 1404 ShenandoahGCPhase phase(ShenandoahPhaseTimings::clear_liveness); 1405 ShenandoahClearLivenessClosure clc; 1406 parallel_heap_region_iterate(&clc); 1407 } 1408 1409 // Make above changes visible to worker threads 1410 OrderAccess::fence(); 1411 1412 concurrent_mark()->mark_roots(ShenandoahPhaseTimings::scan_roots); 1413 1414 if (UseTLAB) { 1415 ShenandoahGCPhase phase(ShenandoahPhaseTimings::resize_tlabs); 1416 resize_tlabs(); 1417 } 1418 1419 if (ShenandoahPacing) { 1420 pacer()->setup_for_mark(); 1421 } 1422 } 1423 1424 void ShenandoahHeap::op_mark() { 1425 concurrent_mark()->mark_from_roots(); 1426 } 1427 1428 class ShenandoahCompleteLivenessClosure : public ShenandoahHeapRegionClosure { 1429 private: 1430 ShenandoahMarkingContext* const _ctx; 1431 public: 1432 ShenandoahCompleteLivenessClosure() : _ctx(ShenandoahHeap::heap()->complete_marking_context()) {} 1433 1434 void heap_region_do(ShenandoahHeapRegion* r) { 1435 if (r->is_active()) { 1436 HeapWord *tams = _ctx->top_at_mark_start(r); 1437 HeapWord *top = r->top(); 1438 if (top > tams) { 1439 r->increase_live_data_alloc_words(pointer_delta(top, tams)); 1440 } 1441 } else { 1442 assert(!r->has_live(), "Region " SIZE_FORMAT " should have no live data", r->region_number()); 1443 assert(_ctx->top_at_mark_start(r) == r->top(), 1444 "Region " SIZE_FORMAT " should have correct TAMS", r->region_number()); 1445 } 1446 } 1447 1448 bool is_thread_safe() { return true; } 1449 }; 1450 1451 void ShenandoahHeap::op_final_mark() { 1452 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint"); 1453 1454 // It is critical that we 1455 // evacuate roots right after finishing marking, so that we don't 1456 // get unmarked objects in the roots. 1457 1458 if (!cancelled_gc()) { 1459 concurrent_mark()->finish_mark_from_roots(/* full_gc = */ false); 1460 1461 // Marking is completed, deactivate SATB barrier 1462 set_concurrent_mark_in_progress(false); 1463 mark_complete_marking_context(); 1464 1465 parallel_cleaning(false /* full gc*/); 1466 1467 if (has_forwarded_objects()) { 1468 // Degen may be caused by failed evacuation of roots 1469 if (is_degenerated_gc_in_progress()) { 1470 concurrent_mark()->update_roots(ShenandoahPhaseTimings::degen_gc_update_roots); 1471 } else { 1472 concurrent_mark()->update_thread_roots(ShenandoahPhaseTimings::update_roots); 1473 } 1474 set_has_forwarded_objects(false); 1475 } 1476 1477 if (ShenandoahVerify) { 1478 verifier()->verify_roots_no_forwarded(); 1479 } 1480 // All allocations past TAMS are implicitly live, adjust the region data. 1481 // Bitmaps/TAMS are swapped at this point, so we need to poll complete bitmap. 1482 { 1483 ShenandoahGCPhase phase(ShenandoahPhaseTimings::complete_liveness); 1484 ShenandoahCompleteLivenessClosure cl; 1485 parallel_heap_region_iterate(&cl); 1486 } 1487 1488 // Force the threads to reacquire their TLABs outside the collection set. 1489 { 1490 ShenandoahGCPhase phase(ShenandoahPhaseTimings::retire_tlabs); 1491 make_parsable(true); 1492 } 1493 1494 // We are about to select the collection set, make sure it knows about 1495 // current pinning status. Also, this allows trashing more regions that 1496 // now have their pinning status dropped. 1497 { 1498 ShenandoahGCPhase phase(ShenandoahPhaseTimings::sync_pinned); 1499 sync_pinned_region_status(); 1500 } 1501 1502 // Trash the collection set left over from previous cycle, if any. 1503 { 1504 ShenandoahGCPhase phase(ShenandoahPhaseTimings::trash_cset); 1505 trash_cset_regions(); 1506 } 1507 1508 { 1509 ShenandoahGCPhase phase(ShenandoahPhaseTimings::prepare_evac); 1510 1511 ShenandoahHeapLocker locker(lock()); 1512 _collection_set->clear(); 1513 _free_set->clear(); 1514 1515 heuristics()->choose_collection_set(_collection_set); 1516 1517 _free_set->rebuild(); 1518 } 1519 1520 if (!is_degenerated_gc_in_progress()) { 1521 prepare_concurrent_roots(); 1522 prepare_concurrent_unloading(); 1523 } 1524 1525 // If collection set has candidates, start evacuation. 1526 // Otherwise, bypass the rest of the cycle. 1527 if (!collection_set()->is_empty()) { 1528 ShenandoahGCPhase init_evac(ShenandoahPhaseTimings::init_evac); 1529 1530 if (ShenandoahVerify) { 1531 verifier()->verify_before_evacuation(); 1532 } 1533 1534 // Remember limit for updating refs. It's guaranteed that we get no from-space-refs written 1535 // from here on. 1536 for (uint i = 0; i < num_regions(); i++) { 1537 ShenandoahHeapRegion* r = get_region(i); 1538 r->set_update_watermark(r->top()); 1539 } 1540 1541 set_evacuation_in_progress(true); 1542 // From here on, we need to update references. 1543 set_has_forwarded_objects(true); 1544 1545 if (!is_degenerated_gc_in_progress()) { 1546 if (ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) { 1547 ShenandoahCodeRoots::arm_nmethods(); 1548 } 1549 evacuate_and_update_roots(); 1550 } 1551 1552 if (ShenandoahPacing) { 1553 pacer()->setup_for_evac(); 1554 } 1555 1556 if (ShenandoahVerify) { 1557 ShenandoahRootVerifier::RootTypes types = ShenandoahRootVerifier::None; 1558 if (ShenandoahConcurrentRoots::should_do_concurrent_roots()) { 1559 types = ShenandoahRootVerifier::combine(ShenandoahRootVerifier::JNIHandleRoots, ShenandoahRootVerifier::WeakRoots); 1560 types = ShenandoahRootVerifier::combine(types, ShenandoahRootVerifier::CLDGRoots); 1561 types = ShenandoahRootVerifier::combine(types, ShenandoahRootVerifier::StringDedupRoots); 1562 } 1563 1564 if (ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) { 1565 types = ShenandoahRootVerifier::combine(types, ShenandoahRootVerifier::CodeRoots); 1566 } 1567 verifier()->verify_roots_no_forwarded_except(types); 1568 verifier()->verify_during_evacuation(); 1569 } 1570 } else { 1571 if (ShenandoahVerify) { 1572 verifier()->verify_after_concmark(); 1573 } 1574 1575 if (VerifyAfterGC) { 1576 Universe::verify(); 1577 } 1578 } 1579 1580 } else { 1581 // If this cycle was updating references, we need to keep the has_forwarded_objects 1582 // flag on, for subsequent phases to deal with it. 1583 concurrent_mark()->cancel(); 1584 set_concurrent_mark_in_progress(false); 1585 1586 if (process_references()) { 1587 // Abandon reference processing right away: pre-cleaning must have failed. 1588 ReferenceProcessor *rp = ref_processor(); 1589 rp->disable_discovery(); 1590 rp->abandon_partial_discovery(); 1591 rp->verify_no_references_recorded(); 1592 } 1593 } 1594 } 1595 1596 void ShenandoahHeap::op_final_evac() { 1597 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should be at safepoint"); 1598 1599 set_evacuation_in_progress(false); 1600 1601 { 1602 ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac_retire_gclabs); 1603 retire_and_reset_gclabs(); 1604 } 1605 1606 if (ShenandoahVerify) { 1607 verifier()->verify_after_evacuation(); 1608 } 1609 1610 if (VerifyAfterGC) { 1611 Universe::verify(); 1612 } 1613 } 1614 1615 void ShenandoahHeap::op_conc_evac() { 1616 ShenandoahEvacuationTask task(this, _collection_set, true); 1617 workers()->run_task(&task); 1618 } 1619 1620 void ShenandoahHeap::op_stw_evac() { 1621 ShenandoahEvacuationTask task(this, _collection_set, false); 1622 workers()->run_task(&task); 1623 } 1624 1625 void ShenandoahHeap::op_updaterefs() { 1626 update_heap_references(true); 1627 } 1628 1629 void ShenandoahHeap::op_cleanup() { 1630 free_set()->recycle_trash(); 1631 } 1632 1633 class ShenandoahConcurrentRootsEvacUpdateTask : public AbstractGangTask { 1634 private: 1635 ShenandoahVMRoots<true /*concurrent*/> _vm_roots; 1636 ShenandoahWeakRoots<true /*concurrent*/> _weak_roots; 1637 ShenandoahClassLoaderDataRoots<true /*concurrent*/, false /*single threaded*/> _cld_roots; 1638 ShenandoahConcurrentStringDedupRoots _dedup_roots; 1639 bool _include_weak_roots; 1640 1641 public: 1642 ShenandoahConcurrentRootsEvacUpdateTask(bool include_weak_roots) : 1643 AbstractGangTask("Shenandoah Evacuate/Update Concurrent Roots Task"), 1644 _include_weak_roots(include_weak_roots) { 1645 } 1646 1647 void work(uint worker_id) { 1648 ShenandoahEvacOOMScope oom; 1649 { 1650 // vm_roots and weak_roots are OopStorage backed roots, concurrent iteration 1651 // may race against OopStorage::release() calls. 1652 ShenandoahEvacUpdateOopStorageRootsClosure cl; 1653 _vm_roots.oops_do<ShenandoahEvacUpdateOopStorageRootsClosure>(&cl); 1654 1655 if (_include_weak_roots) { 1656 _weak_roots.oops_do<ShenandoahEvacUpdateOopStorageRootsClosure>(&cl); 1657 } 1658 } 1659 1660 { 1661 ShenandoahEvacuateUpdateRootsClosure<> cl; 1662 CLDToOopClosure clds(&cl, ClassLoaderData::_claim_strong); 1663 _cld_roots.cld_do(&clds); 1664 } 1665 1666 { 1667 ShenandoahForwardedIsAliveClosure is_alive; 1668 ShenandoahEvacuateUpdateRootsClosure<MO_RELEASE> keep_alive; 1669 _dedup_roots.oops_do(&is_alive, &keep_alive, worker_id); 1670 } 1671 } 1672 }; 1673 1674 class ShenandoahEvacUpdateCleanupOopStorageRootsClosure : public BasicOopIterateClosure { 1675 private: 1676 ShenandoahHeap* const _heap; 1677 ShenandoahMarkingContext* const _mark_context; 1678 bool _evac_in_progress; 1679 Thread* const _thread; 1680 size_t _dead_counter; 1681 1682 public: 1683 ShenandoahEvacUpdateCleanupOopStorageRootsClosure(); 1684 void do_oop(oop* p); 1685 void do_oop(narrowOop* p); 1686 1687 size_t dead_counter() const; 1688 void reset_dead_counter(); 1689 }; 1690 1691 ShenandoahEvacUpdateCleanupOopStorageRootsClosure::ShenandoahEvacUpdateCleanupOopStorageRootsClosure() : 1692 _heap(ShenandoahHeap::heap()), 1693 _mark_context(ShenandoahHeap::heap()->marking_context()), 1694 _evac_in_progress(ShenandoahHeap::heap()->is_evacuation_in_progress()), 1695 _thread(Thread::current()), 1696 _dead_counter(0) { 1697 } 1698 1699 void ShenandoahEvacUpdateCleanupOopStorageRootsClosure::do_oop(oop* p) { 1700 const oop obj = RawAccess<>::oop_load(p); 1701 if (!CompressedOops::is_null(obj)) { 1702 if (!_mark_context->is_marked(obj)) { 1703 shenandoah_assert_correct(p, obj); 1704 oop old = Atomic::cmpxchg(p, obj, oop(NULL)); 1705 if (obj == old) { 1706 _dead_counter ++; 1707 } 1708 } else if (_evac_in_progress && _heap->in_collection_set(obj)) { 1709 oop resolved = ShenandoahBarrierSet::resolve_forwarded_not_null(obj); 1710 if (resolved == obj) { 1711 resolved = _heap->evacuate_object(obj, _thread); 1712 } 1713 Atomic::cmpxchg(p, obj, resolved); 1714 assert(_heap->cancelled_gc() || 1715 _mark_context->is_marked(resolved) && !_heap->in_collection_set(resolved), 1716 "Sanity"); 1717 } 1718 } 1719 } 1720 1721 void ShenandoahEvacUpdateCleanupOopStorageRootsClosure::do_oop(narrowOop* p) { 1722 ShouldNotReachHere(); 1723 } 1724 1725 size_t ShenandoahEvacUpdateCleanupOopStorageRootsClosure::dead_counter() const { 1726 return _dead_counter; 1727 } 1728 1729 void ShenandoahEvacUpdateCleanupOopStorageRootsClosure::reset_dead_counter() { 1730 _dead_counter = 0; 1731 } 1732 1733 // This task not only evacuates/updates marked weak roots, but also "NULL" 1734 // dead weak roots. 1735 class ShenandoahConcurrentWeakRootsEvacUpdateTask : public AbstractGangTask { 1736 private: 1737 ShenandoahWeakRoot<true /*concurrent*/> _jni_roots; 1738 ShenandoahWeakRoot<true /*concurrent*/> _string_table_roots; 1739 ShenandoahWeakRoot<true /*concurrent*/> _resolved_method_table_roots; 1740 ShenandoahWeakRoot<true /*concurrent*/> _vm_roots; 1741 1742 public: 1743 ShenandoahConcurrentWeakRootsEvacUpdateTask() : 1744 AbstractGangTask("Shenandoah Concurrent Weak Root Task"), 1745 _jni_roots(OopStorageSet::jni_weak(), ShenandoahPhaseTimings::JNIWeakRoots), 1746 _string_table_roots(OopStorageSet::string_table_weak(), ShenandoahPhaseTimings::StringTableRoots), 1747 _resolved_method_table_roots(OopStorageSet::resolved_method_table_weak(), ShenandoahPhaseTimings::ResolvedMethodTableRoots), 1748 _vm_roots(OopStorageSet::vm_weak(), ShenandoahPhaseTimings::VMWeakRoots) { 1749 StringTable::reset_dead_counter(); 1750 ResolvedMethodTable::reset_dead_counter(); 1751 } 1752 1753 ~ShenandoahConcurrentWeakRootsEvacUpdateTask() { 1754 StringTable::finish_dead_counter(); 1755 ResolvedMethodTable::finish_dead_counter(); 1756 } 1757 1758 void work(uint worker_id) { 1759 ShenandoahEvacOOMScope oom; 1760 // jni_roots and weak_roots are OopStorage backed roots, concurrent iteration 1761 // may race against OopStorage::release() calls. 1762 ShenandoahEvacUpdateCleanupOopStorageRootsClosure cl; 1763 _jni_roots.oops_do(&cl, worker_id); 1764 _vm_roots.oops_do(&cl, worker_id); 1765 1766 cl.reset_dead_counter(); 1767 _string_table_roots.oops_do(&cl, worker_id); 1768 StringTable::inc_dead_counter(cl.dead_counter()); 1769 1770 cl.reset_dead_counter(); 1771 _resolved_method_table_roots.oops_do(&cl, worker_id); 1772 ResolvedMethodTable::inc_dead_counter(cl.dead_counter()); 1773 } 1774 }; 1775 1776 void ShenandoahHeap::op_roots() { 1777 if (is_concurrent_root_in_progress()) { 1778 if (ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) { 1779 // Concurrent weak root processing 1780 ShenandoahConcurrentWeakRootsEvacUpdateTask task; 1781 workers()->run_task(&task); 1782 1783 _unloader.unload(); 1784 } 1785 1786 if (ShenandoahConcurrentRoots::should_do_concurrent_roots()) { 1787 ShenandoahConcurrentRootsEvacUpdateTask task(!ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()); 1788 workers()->run_task(&task); 1789 } 1790 } 1791 1792 set_concurrent_root_in_progress(false); 1793 } 1794 1795 void ShenandoahHeap::op_reset() { 1796 if (ShenandoahPacing) { 1797 pacer()->setup_for_reset(); 1798 } 1799 reset_mark_bitmap(); 1800 } 1801 1802 void ShenandoahHeap::op_preclean() { 1803 if (ShenandoahPacing) { 1804 pacer()->setup_for_preclean(); 1805 } 1806 concurrent_mark()->preclean_weak_refs(); 1807 } 1808 1809 void ShenandoahHeap::op_init_traversal() { 1810 traversal_gc()->init_traversal_collection(); 1811 } 1812 1813 void ShenandoahHeap::op_traversal() { 1814 traversal_gc()->concurrent_traversal_collection(); 1815 } 1816 1817 void ShenandoahHeap::op_final_traversal() { 1818 traversal_gc()->final_traversal_collection(); 1819 } 1820 1821 void ShenandoahHeap::op_full(GCCause::Cause cause) { 1822 ShenandoahMetricsSnapshot metrics; 1823 metrics.snap_before(); 1824 1825 full_gc()->do_it(cause); 1826 if (UseTLAB) { 1827 ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_resize_tlabs); 1828 resize_all_tlabs(); 1829 } 1830 1831 metrics.snap_after(); 1832 1833 if (metrics.is_good_progress()) { 1834 _progress_last_gc.set(); 1835 } else { 1836 // Nothing to do. Tell the allocation path that we have failed to make 1837 // progress, and it can finally fail. 1838 _progress_last_gc.unset(); 1839 } 1840 } 1841 1842 void ShenandoahHeap::op_degenerated(ShenandoahDegenPoint point) { 1843 // Degenerated GC is STW, but it can also fail. Current mechanics communicates 1844 // GC failure via cancelled_concgc() flag. So, if we detect the failure after 1845 // some phase, we have to upgrade the Degenerate GC to Full GC. 1846 1847 clear_cancelled_gc(); 1848 1849 ShenandoahMetricsSnapshot metrics; 1850 metrics.snap_before(); 1851 1852 switch (point) { 1853 case _degenerated_traversal: 1854 { 1855 // Drop the collection set. Note: this leaves some already forwarded objects 1856 // behind, which may be problematic, see comments for ShenandoahEvacAssist 1857 // workarounds in ShenandoahTraversalHeuristics. 1858 1859 ShenandoahHeapLocker locker(lock()); 1860 collection_set()->clear_current_index(); 1861 for (size_t i = 0; i < collection_set()->count(); i++) { 1862 ShenandoahHeapRegion* r = collection_set()->next(); 1863 r->make_regular_bypass(); 1864 } 1865 collection_set()->clear(); 1866 } 1867 op_final_traversal(); 1868 op_cleanup(); 1869 return; 1870 1871 // The cases below form the Duff's-like device: it describes the actual GC cycle, 1872 // but enters it at different points, depending on which concurrent phase had 1873 // degenerated. 1874 1875 case _degenerated_outside_cycle: 1876 // We have degenerated from outside the cycle, which means something is bad with 1877 // the heap, most probably heavy humongous fragmentation, or we are very low on free 1878 // space. It makes little sense to wait for Full GC to reclaim as much as it can, when 1879 // we can do the most aggressive degen cycle, which includes processing references and 1880 // class unloading, unless those features are explicitly disabled. 1881 // 1882 // Note that we can only do this for "outside-cycle" degens, otherwise we would risk 1883 // changing the cycle parameters mid-cycle during concurrent -> degenerated handover. 1884 set_process_references(heuristics()->can_process_references()); 1885 set_unload_classes(heuristics()->can_unload_classes()); 1886 1887 if (is_traversal_mode()) { 1888 // Not possible to degenerate from here, upgrade to Full GC right away. 1889 cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc); 1890 op_degenerated_fail(); 1891 return; 1892 } 1893 1894 op_reset(); 1895 1896 op_init_mark(); 1897 if (cancelled_gc()) { 1898 op_degenerated_fail(); 1899 return; 1900 } 1901 1902 case _degenerated_mark: 1903 op_final_mark(); 1904 if (cancelled_gc()) { 1905 op_degenerated_fail(); 1906 return; 1907 } 1908 1909 op_cleanup(); 1910 1911 case _degenerated_evac: 1912 // If heuristics thinks we should do the cycle, this flag would be set, 1913 // and we can do evacuation. Otherwise, it would be the shortcut cycle. 1914 if (is_evacuation_in_progress()) { 1915 1916 // Degeneration under oom-evac protocol might have left some objects in 1917 // collection set un-evacuated. Restart evacuation from the beginning to 1918 // capture all objects. For all the objects that are already evacuated, 1919 // it would be a simple check, which is supposed to be fast. This is also 1920 // safe to do even without degeneration, as CSet iterator is at beginning 1921 // in preparation for evacuation anyway. 1922 // 1923 // Before doing that, we need to make sure we never had any cset-pinned 1924 // regions. This may happen if allocation failure happened when evacuating 1925 // the about-to-be-pinned object, oom-evac protocol left the object in 1926 // the collection set, and then the pin reached the cset region. If we continue 1927 // the cycle here, we would trash the cset and alive objects in it. To avoid 1928 // it, we fail degeneration right away and slide into Full GC to recover. 1929 1930 { 1931 sync_pinned_region_status(); 1932 collection_set()->clear_current_index(); 1933 1934 ShenandoahHeapRegion* r; 1935 while ((r = collection_set()->next()) != NULL) { 1936 if (r->is_pinned()) { 1937 cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc); 1938 op_degenerated_fail(); 1939 return; 1940 } 1941 } 1942 1943 collection_set()->clear_current_index(); 1944 } 1945 1946 op_stw_evac(); 1947 if (cancelled_gc()) { 1948 op_degenerated_fail(); 1949 return; 1950 } 1951 } 1952 1953 // If heuristics thinks we should do the cycle, this flag would be set, 1954 // and we need to do update-refs. Otherwise, it would be the shortcut cycle. 1955 if (has_forwarded_objects()) { 1956 op_init_updaterefs(); 1957 if (cancelled_gc()) { 1958 op_degenerated_fail(); 1959 return; 1960 } 1961 } 1962 1963 case _degenerated_updaterefs: 1964 if (has_forwarded_objects()) { 1965 op_final_updaterefs(); 1966 if (cancelled_gc()) { 1967 op_degenerated_fail(); 1968 return; 1969 } 1970 } 1971 1972 op_cleanup(); 1973 break; 1974 1975 default: 1976 ShouldNotReachHere(); 1977 } 1978 1979 if (ShenandoahVerify) { 1980 verifier()->verify_after_degenerated(); 1981 } 1982 1983 if (VerifyAfterGC) { 1984 Universe::verify(); 1985 } 1986 1987 metrics.snap_after(); 1988 1989 // Check for futility and fail. There is no reason to do several back-to-back Degenerated cycles, 1990 // because that probably means the heap is overloaded and/or fragmented. 1991 if (!metrics.is_good_progress()) { 1992 _progress_last_gc.unset(); 1993 cancel_gc(GCCause::_shenandoah_upgrade_to_full_gc); 1994 op_degenerated_futile(); 1995 } else { 1996 _progress_last_gc.set(); 1997 } 1998 } 1999 2000 void ShenandoahHeap::op_degenerated_fail() { 2001 log_info(gc)("Cannot finish degeneration, upgrading to Full GC"); 2002 shenandoah_policy()->record_degenerated_upgrade_to_full(); 2003 op_full(GCCause::_shenandoah_upgrade_to_full_gc); 2004 } 2005 2006 void ShenandoahHeap::op_degenerated_futile() { 2007 shenandoah_policy()->record_degenerated_upgrade_to_full(); 2008 op_full(GCCause::_shenandoah_upgrade_to_full_gc); 2009 } 2010 2011 void ShenandoahHeap::force_satb_flush_all_threads() { 2012 if (!is_concurrent_mark_in_progress() && !is_concurrent_traversal_in_progress()) { 2013 // No need to flush SATBs 2014 return; 2015 } 2016 2017 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) { 2018 ShenandoahThreadLocalData::set_force_satb_flush(t, true); 2019 } 2020 // The threads are not "acquiring" their thread-local data, but it does not 2021 // hurt to "release" the updates here anyway. 2022 OrderAccess::fence(); 2023 } 2024 2025 void ShenandoahHeap::set_gc_state_all_threads(char state) { 2026 for (JavaThreadIteratorWithHandle jtiwh; JavaThread *t = jtiwh.next(); ) { 2027 ShenandoahThreadLocalData::set_gc_state(t, state); 2028 } 2029 } 2030 2031 void ShenandoahHeap::set_gc_state_mask(uint mask, bool value) { 2032 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Should really be Shenandoah safepoint"); 2033 _gc_state.set_cond(mask, value); 2034 set_gc_state_all_threads(_gc_state.raw_value()); 2035 } 2036 2037 void ShenandoahHeap::set_concurrent_mark_in_progress(bool in_progress) { 2038 if (has_forwarded_objects()) { 2039 set_gc_state_mask(MARKING | UPDATEREFS, in_progress); 2040 } else { 2041 set_gc_state_mask(MARKING, in_progress); 2042 } 2043 ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress); 2044 } 2045 2046 void ShenandoahHeap::set_concurrent_traversal_in_progress(bool in_progress) { 2047 set_gc_state_mask(TRAVERSAL, in_progress); 2048 ShenandoahBarrierSet::satb_mark_queue_set().set_active_all_threads(in_progress, !in_progress); 2049 } 2050 2051 void ShenandoahHeap::set_evacuation_in_progress(bool in_progress) { 2052 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "Only call this at safepoint"); 2053 set_gc_state_mask(EVACUATION, in_progress); 2054 } 2055 2056 void ShenandoahHeap::set_concurrent_root_in_progress(bool in_progress) { 2057 assert(ShenandoahConcurrentRoots::can_do_concurrent_roots(), "Why set the flag?"); 2058 if (in_progress) { 2059 _concurrent_root_in_progress.set(); 2060 } else { 2061 _concurrent_root_in_progress.unset(); 2062 } 2063 } 2064 2065 void ShenandoahHeap::ref_processing_init() { 2066 assert(_max_workers > 0, "Sanity"); 2067 2068 _ref_processor = 2069 new ReferenceProcessor(&_subject_to_discovery, // is_subject_to_discovery 2070 ParallelRefProcEnabled, // MT processing 2071 _max_workers, // Degree of MT processing 2072 true, // MT discovery 2073 _max_workers, // Degree of MT discovery 2074 false, // Reference discovery is not atomic 2075 NULL, // No closure, should be installed before use 2076 true); // Scale worker threads 2077 2078 shenandoah_assert_rp_isalive_not_installed(); 2079 } 2080 2081 GCTracer* ShenandoahHeap::tracer() { 2082 return shenandoah_policy()->tracer(); 2083 } 2084 2085 size_t ShenandoahHeap::tlab_used(Thread* thread) const { 2086 return _free_set->used(); 2087 } 2088 2089 bool ShenandoahHeap::try_cancel_gc() { 2090 while (true) { 2091 jbyte prev = _cancelled_gc.cmpxchg(CANCELLED, CANCELLABLE); 2092 if (prev == CANCELLABLE) return true; 2093 else if (prev == CANCELLED) return false; 2094 assert(ShenandoahSuspendibleWorkers, "should not get here when not using suspendible workers"); 2095 assert(prev == NOT_CANCELLED, "must be NOT_CANCELLED"); 2096 if (Thread::current()->is_Java_thread()) { 2097 // We need to provide a safepoint here, otherwise we might 2098 // spin forever if a SP is pending. 2099 ThreadBlockInVM sp(JavaThread::current()); 2100 SpinPause(); 2101 } 2102 } 2103 } 2104 2105 void ShenandoahHeap::cancel_gc(GCCause::Cause cause) { 2106 if (try_cancel_gc()) { 2107 FormatBuffer<> msg("Cancelling GC: %s", GCCause::to_string(cause)); 2108 log_info(gc)("%s", msg.buffer()); 2109 Events::log(Thread::current(), "%s", msg.buffer()); 2110 } 2111 } 2112 2113 uint ShenandoahHeap::max_workers() { 2114 return _max_workers; 2115 } 2116 2117 void ShenandoahHeap::stop() { 2118 // The shutdown sequence should be able to terminate when GC is running. 2119 2120 // Step 0. Notify policy to disable event recording. 2121 _shenandoah_policy->record_shutdown(); 2122 2123 // Step 1. Notify control thread that we are in shutdown. 2124 // Note that we cannot do that with stop(), because stop() is blocking and waits for the actual shutdown. 2125 // Doing stop() here would wait for the normal GC cycle to complete, never falling through to cancel below. 2126 control_thread()->prepare_for_graceful_shutdown(); 2127 2128 // Step 2. Notify GC workers that we are cancelling GC. 2129 cancel_gc(GCCause::_shenandoah_stop_vm); 2130 2131 // Step 3. Wait until GC worker exits normally. 2132 control_thread()->stop(); 2133 2134 // Step 4. Stop String Dedup thread if it is active 2135 if (ShenandoahStringDedup::is_enabled()) { 2136 ShenandoahStringDedup::stop(); 2137 } 2138 } 2139 2140 void ShenandoahHeap::stw_unload_classes(bool full_gc) { 2141 if (!unload_classes()) return; 2142 bool purged_class; 2143 2144 // Unload classes and purge SystemDictionary. 2145 { 2146 ShenandoahGCPhase phase(full_gc ? 2147 ShenandoahPhaseTimings::full_gc_purge_class_unload : 2148 ShenandoahPhaseTimings::purge_class_unload); 2149 purged_class = SystemDictionary::do_unloading(gc_timer()); 2150 } 2151 2152 { 2153 ShenandoahGCPhase phase(full_gc ? 2154 ShenandoahPhaseTimings::full_gc_purge_par : 2155 ShenandoahPhaseTimings::purge_par); 2156 ShenandoahIsAliveSelector is_alive; 2157 uint num_workers = _workers->active_workers(); 2158 ShenandoahClassUnloadingTask unlink_task(is_alive.is_alive_closure(), num_workers, purged_class); 2159 _workers->run_task(&unlink_task); 2160 } 2161 2162 { 2163 ShenandoahGCPhase phase(full_gc ? 2164 ShenandoahPhaseTimings::full_gc_purge_cldg : 2165 ShenandoahPhaseTimings::purge_cldg); 2166 ClassLoaderDataGraph::purge(); 2167 } 2168 // Resize and verify metaspace 2169 MetaspaceGC::compute_new_size(); 2170 MetaspaceUtils::verify_metrics(); 2171 } 2172 2173 // Weak roots are either pre-evacuated (final mark) or updated (final updaterefs), 2174 // so they should not have forwarded oops. 2175 // However, we do need to "null" dead oops in the roots, if can not be done 2176 // in concurrent cycles. 2177 void ShenandoahHeap::stw_process_weak_roots(bool full_gc) { 2178 ShenandoahGCPhase root_phase(full_gc ? 2179 ShenandoahPhaseTimings::full_gc_purge : 2180 ShenandoahPhaseTimings::purge); 2181 uint num_workers = _workers->active_workers(); 2182 ShenandoahPhaseTimings::Phase timing_phase = full_gc ? 2183 ShenandoahPhaseTimings::full_gc_purge_par : 2184 ShenandoahPhaseTimings::purge_par; 2185 ShenandoahGCPhase phase(timing_phase); 2186 ShenandoahGCWorkerPhase worker_phase(timing_phase); 2187 2188 // Cleanup weak roots 2189 if (has_forwarded_objects()) { 2190 ShenandoahForwardedIsAliveClosure is_alive; 2191 ShenandoahUpdateRefsClosure keep_alive; 2192 ShenandoahParallelWeakRootsCleaningTask<ShenandoahForwardedIsAliveClosure, ShenandoahUpdateRefsClosure> 2193 cleaning_task(&is_alive, &keep_alive, num_workers, !ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()); 2194 _workers->run_task(&cleaning_task); 2195 } else { 2196 ShenandoahIsAliveClosure is_alive; 2197 #ifdef ASSERT 2198 ShenandoahAssertNotForwardedClosure verify_cl; 2199 ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, ShenandoahAssertNotForwardedClosure> 2200 cleaning_task(&is_alive, &verify_cl, num_workers, !ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()); 2201 #else 2202 ShenandoahParallelWeakRootsCleaningTask<ShenandoahIsAliveClosure, DoNothingClosure> 2203 cleaning_task(&is_alive, &do_nothing_cl, num_workers, !ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()); 2204 #endif 2205 _workers->run_task(&cleaning_task); 2206 } 2207 } 2208 2209 void ShenandoahHeap::parallel_cleaning(bool full_gc) { 2210 assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint"); 2211 stw_process_weak_roots(full_gc); 2212 if (!ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) { 2213 stw_unload_classes(full_gc); 2214 } 2215 } 2216 2217 void ShenandoahHeap::set_has_forwarded_objects(bool cond) { 2218 if (is_traversal_mode()) { 2219 set_gc_state_mask(HAS_FORWARDED | UPDATEREFS, cond); 2220 } else { 2221 set_gc_state_mask(HAS_FORWARDED, cond); 2222 } 2223 2224 } 2225 2226 void ShenandoahHeap::set_process_references(bool pr) { 2227 _process_references.set_cond(pr); 2228 } 2229 2230 void ShenandoahHeap::set_unload_classes(bool uc) { 2231 _unload_classes.set_cond(uc); 2232 } 2233 2234 bool ShenandoahHeap::process_references() const { 2235 return _process_references.is_set(); 2236 } 2237 2238 bool ShenandoahHeap::unload_classes() const { 2239 return _unload_classes.is_set(); 2240 } 2241 2242 address ShenandoahHeap::in_cset_fast_test_addr() { 2243 ShenandoahHeap* heap = ShenandoahHeap::heap(); 2244 assert(heap->collection_set() != NULL, "Sanity"); 2245 return (address) heap->collection_set()->biased_map_address(); 2246 } 2247 2248 address ShenandoahHeap::cancelled_gc_addr() { 2249 return (address) ShenandoahHeap::heap()->_cancelled_gc.addr_of(); 2250 } 2251 2252 address ShenandoahHeap::gc_state_addr() { 2253 return (address) ShenandoahHeap::heap()->_gc_state.addr_of(); 2254 } 2255 2256 size_t ShenandoahHeap::bytes_allocated_since_gc_start() { 2257 return Atomic::load_acquire(&_bytes_allocated_since_gc_start); 2258 } 2259 2260 void ShenandoahHeap::reset_bytes_allocated_since_gc_start() { 2261 Atomic::release_store_fence(&_bytes_allocated_since_gc_start, (size_t)0); 2262 } 2263 2264 void ShenandoahHeap::set_degenerated_gc_in_progress(bool in_progress) { 2265 _degenerated_gc_in_progress.set_cond(in_progress); 2266 } 2267 2268 void ShenandoahHeap::set_full_gc_in_progress(bool in_progress) { 2269 _full_gc_in_progress.set_cond(in_progress); 2270 } 2271 2272 void ShenandoahHeap::set_full_gc_move_in_progress(bool in_progress) { 2273 assert (is_full_gc_in_progress(), "should be"); 2274 _full_gc_move_in_progress.set_cond(in_progress); 2275 } 2276 2277 void ShenandoahHeap::set_update_refs_in_progress(bool in_progress) { 2278 set_gc_state_mask(UPDATEREFS, in_progress); 2279 } 2280 2281 void ShenandoahHeap::register_nmethod(nmethod* nm) { 2282 ShenandoahCodeRoots::register_nmethod(nm); 2283 } 2284 2285 void ShenandoahHeap::unregister_nmethod(nmethod* nm) { 2286 ShenandoahCodeRoots::unregister_nmethod(nm); 2287 } 2288 2289 void ShenandoahHeap::flush_nmethod(nmethod* nm) { 2290 ShenandoahCodeRoots::flush_nmethod(nm); 2291 } 2292 2293 oop ShenandoahHeap::pin_object(JavaThread* thr, oop o) { 2294 heap_region_containing(o)->record_pin(); 2295 return o; 2296 } 2297 2298 void ShenandoahHeap::unpin_object(JavaThread* thr, oop o) { 2299 heap_region_containing(o)->record_unpin(); 2300 } 2301 2302 void ShenandoahHeap::sync_pinned_region_status() { 2303 ShenandoahHeapLocker locker(lock()); 2304 2305 for (size_t i = 0; i < num_regions(); i++) { 2306 ShenandoahHeapRegion *r = get_region(i); 2307 if (r->is_active()) { 2308 if (r->is_pinned()) { 2309 if (r->pin_count() == 0) { 2310 r->make_unpinned(); 2311 } 2312 } else { 2313 if (r->pin_count() > 0) { 2314 r->make_pinned(); 2315 } 2316 } 2317 } 2318 } 2319 2320 assert_pinned_region_status(); 2321 } 2322 2323 #ifdef ASSERT 2324 void ShenandoahHeap::assert_pinned_region_status() { 2325 for (size_t i = 0; i < num_regions(); i++) { 2326 ShenandoahHeapRegion* r = get_region(i); 2327 assert((r->is_pinned() && r->pin_count() > 0) || (!r->is_pinned() && r->pin_count() == 0), 2328 "Region " SIZE_FORMAT " pinning status is inconsistent", i); 2329 } 2330 } 2331 #endif 2332 2333 GCTimer* ShenandoahHeap::gc_timer() const { 2334 return _gc_timer; 2335 } 2336 2337 void ShenandoahHeap::prepare_concurrent_roots() { 2338 assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint"); 2339 if (ShenandoahConcurrentRoots::should_do_concurrent_roots()) { 2340 set_concurrent_root_in_progress(true); 2341 } 2342 } 2343 2344 void ShenandoahHeap::prepare_concurrent_unloading() { 2345 assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint"); 2346 if (ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) { 2347 _unloader.prepare(); 2348 } 2349 } 2350 2351 void ShenandoahHeap::finish_concurrent_unloading() { 2352 assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint"); 2353 if (ShenandoahConcurrentRoots::should_do_concurrent_class_unloading()) { 2354 _unloader.finish(); 2355 } 2356 } 2357 2358 #ifdef ASSERT 2359 void ShenandoahHeap::assert_gc_workers(uint nworkers) { 2360 assert(nworkers > 0 && nworkers <= max_workers(), "Sanity"); 2361 2362 if (ShenandoahSafepoint::is_at_shenandoah_safepoint()) { 2363 if (UseDynamicNumberOfGCThreads || 2364 (FLAG_IS_DEFAULT(ParallelGCThreads) && ForceDynamicNumberOfGCThreads)) { 2365 assert(nworkers <= ParallelGCThreads, "Cannot use more than it has"); 2366 } else { 2367 // Use ParallelGCThreads inside safepoints 2368 assert(nworkers == ParallelGCThreads, "Use ParalleGCThreads within safepoints"); 2369 } 2370 } else { 2371 if (UseDynamicNumberOfGCThreads || 2372 (FLAG_IS_DEFAULT(ConcGCThreads) && ForceDynamicNumberOfGCThreads)) { 2373 assert(nworkers <= ConcGCThreads, "Cannot use more than it has"); 2374 } else { 2375 // Use ConcGCThreads outside safepoints 2376 assert(nworkers == ConcGCThreads, "Use ConcGCThreads outside safepoints"); 2377 } 2378 } 2379 } 2380 #endif 2381 2382 ShenandoahVerifier* ShenandoahHeap::verifier() { 2383 guarantee(ShenandoahVerify, "Should be enabled"); 2384 assert (_verifier != NULL, "sanity"); 2385 return _verifier; 2386 } 2387 2388 template<class T> 2389 class ShenandoahUpdateHeapRefsTask : public AbstractGangTask { 2390 private: 2391 T cl; 2392 ShenandoahHeap* _heap; 2393 ShenandoahRegionIterator* _regions; 2394 bool _concurrent; 2395 public: 2396 ShenandoahUpdateHeapRefsTask(ShenandoahRegionIterator* regions, bool concurrent) : 2397 AbstractGangTask("Concurrent Update References Task"), 2398 cl(T()), 2399 _heap(ShenandoahHeap::heap()), 2400 _regions(regions), 2401 _concurrent(concurrent) { 2402 } 2403 2404 void work(uint worker_id) { 2405 if (_concurrent) { 2406 ShenandoahConcurrentWorkerSession worker_session(worker_id); 2407 ShenandoahSuspendibleThreadSetJoiner stsj(ShenandoahSuspendibleWorkers); 2408 do_work(); 2409 } else { 2410 ShenandoahParallelWorkerSession worker_session(worker_id); 2411 do_work(); 2412 } 2413 } 2414 2415 private: 2416 void do_work() { 2417 ShenandoahHeapRegion* r = _regions->next(); 2418 ShenandoahMarkingContext* const ctx = _heap->complete_marking_context(); 2419 while (r != NULL) { 2420 HeapWord* update_watermark = r->get_update_watermark(); 2421 assert (update_watermark >= r->bottom(), "sanity"); 2422 if (r->is_active() && !r->is_cset()) { 2423 _heap->marked_object_oop_iterate(r, &cl, update_watermark); 2424 } 2425 if (ShenandoahPacing) { 2426 _heap->pacer()->report_updaterefs(pointer_delta(update_watermark, r->bottom())); 2427 } 2428 if (_heap->check_cancelled_gc_and_yield(_concurrent)) { 2429 return; 2430 } 2431 r = _regions->next(); 2432 } 2433 } 2434 }; 2435 2436 void ShenandoahHeap::update_heap_references(bool concurrent) { 2437 ShenandoahUpdateHeapRefsTask<ShenandoahUpdateHeapRefsClosure> task(&_update_refs_iterator, concurrent); 2438 workers()->run_task(&task); 2439 } 2440 2441 void ShenandoahHeap::op_init_updaterefs() { 2442 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint"); 2443 2444 set_evacuation_in_progress(false); 2445 2446 { 2447 ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs_retire_gclabs); 2448 retire_and_reset_gclabs(); 2449 } 2450 2451 if (ShenandoahVerify) { 2452 if (!is_degenerated_gc_in_progress()) { 2453 verifier()->verify_roots_in_to_space_except(ShenandoahRootVerifier::ThreadRoots); 2454 } 2455 verifier()->verify_before_updaterefs(); 2456 } 2457 2458 set_update_refs_in_progress(true); 2459 2460 { 2461 ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs_prepare); 2462 2463 make_parsable(true); 2464 2465 // Reset iterator. 2466 _update_refs_iterator.reset(); 2467 } 2468 2469 if (ShenandoahPacing) { 2470 pacer()->setup_for_updaterefs(); 2471 } 2472 } 2473 2474 void ShenandoahHeap::op_final_updaterefs() { 2475 assert(ShenandoahSafepoint::is_at_shenandoah_safepoint(), "must be at safepoint"); 2476 2477 finish_concurrent_unloading(); 2478 2479 // Check if there is left-over work, and finish it 2480 if (_update_refs_iterator.has_next()) { 2481 ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_finish_work); 2482 2483 // Finish updating references where we left off. 2484 clear_cancelled_gc(); 2485 update_heap_references(false); 2486 } 2487 2488 // Clear cancelled GC, if set. On cancellation path, the block before would handle 2489 // everything. On degenerated paths, cancelled gc would not be set anyway. 2490 if (cancelled_gc()) { 2491 clear_cancelled_gc(); 2492 } 2493 assert(!cancelled_gc(), "Should have been done right before"); 2494 2495 if (ShenandoahVerify && !is_degenerated_gc_in_progress()) { 2496 verifier()->verify_roots_in_to_space_except(ShenandoahRootVerifier::ThreadRoots); 2497 } 2498 2499 if (is_degenerated_gc_in_progress()) { 2500 concurrent_mark()->update_roots(ShenandoahPhaseTimings::degen_gc_update_roots); 2501 } else { 2502 concurrent_mark()->update_thread_roots(ShenandoahPhaseTimings::final_update_refs_roots); 2503 } 2504 2505 // Has to be done before cset is clear 2506 if (ShenandoahVerify) { 2507 verifier()->verify_roots_in_to_space(); 2508 } 2509 2510 // Drop unnecessary "pinned" state from regions that does not have CP marks 2511 // anymore, as this would allow trashing them below. 2512 { 2513 ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_sync_pinned); 2514 sync_pinned_region_status(); 2515 } 2516 2517 { 2518 ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_trash_cset); 2519 trash_cset_regions(); 2520 } 2521 2522 set_has_forwarded_objects(false); 2523 set_update_refs_in_progress(false); 2524 2525 if (ShenandoahVerify) { 2526 verifier()->verify_after_updaterefs(); 2527 } 2528 2529 if (VerifyAfterGC) { 2530 Universe::verify(); 2531 } 2532 2533 { 2534 ShenandoahHeapLocker locker(lock()); 2535 _free_set->rebuild(); 2536 } 2537 } 2538 2539 #ifdef ASSERT 2540 void ShenandoahHeap::assert_heaplock_owned_by_current_thread() { 2541 _lock.assert_owned_by_current_thread(); 2542 } 2543 2544 void ShenandoahHeap::assert_heaplock_not_owned_by_current_thread() { 2545 _lock.assert_not_owned_by_current_thread(); 2546 } 2547 2548 void ShenandoahHeap::assert_heaplock_or_safepoint() { 2549 _lock.assert_owned_by_current_thread_or_safepoint(); 2550 } 2551 #endif 2552 2553 void ShenandoahHeap::print_extended_on(outputStream *st) const { 2554 print_on(st); 2555 print_heap_regions_on(st); 2556 } 2557 2558 bool ShenandoahHeap::is_bitmap_slice_committed(ShenandoahHeapRegion* r, bool skip_self) { 2559 size_t slice = r->region_number() / _bitmap_regions_per_slice; 2560 2561 size_t regions_from = _bitmap_regions_per_slice * slice; 2562 size_t regions_to = MIN2(num_regions(), _bitmap_regions_per_slice * (slice + 1)); 2563 for (size_t g = regions_from; g < regions_to; g++) { 2564 assert (g / _bitmap_regions_per_slice == slice, "same slice"); 2565 if (skip_self && g == r->region_number()) continue; 2566 if (get_region(g)->is_committed()) { 2567 return true; 2568 } 2569 } 2570 return false; 2571 } 2572 2573 bool ShenandoahHeap::commit_bitmap_slice(ShenandoahHeapRegion* r) { 2574 assert_heaplock_owned_by_current_thread(); 2575 2576 // Bitmaps in special regions do not need commits 2577 if (_bitmap_region_special) { 2578 return true; 2579 } 2580 2581 if (is_bitmap_slice_committed(r, true)) { 2582 // Some other region from the group is already committed, meaning the bitmap 2583 // slice is already committed, we exit right away. 2584 return true; 2585 } 2586 2587 // Commit the bitmap slice: 2588 size_t slice = r->region_number() / _bitmap_regions_per_slice; 2589 size_t off = _bitmap_bytes_per_slice * slice; 2590 size_t len = _bitmap_bytes_per_slice; 2591 if (!os::commit_memory((char*)_bitmap_region.start() + off, len, false)) { 2592 return false; 2593 } 2594 return true; 2595 } 2596 2597 bool ShenandoahHeap::uncommit_bitmap_slice(ShenandoahHeapRegion *r) { 2598 assert_heaplock_owned_by_current_thread(); 2599 2600 // Bitmaps in special regions do not need uncommits 2601 if (_bitmap_region_special) { 2602 return true; 2603 } 2604 2605 if (is_bitmap_slice_committed(r, true)) { 2606 // Some other region from the group is still committed, meaning the bitmap 2607 // slice is should stay committed, exit right away. 2608 return true; 2609 } 2610 2611 // Uncommit the bitmap slice: 2612 size_t slice = r->region_number() / _bitmap_regions_per_slice; 2613 size_t off = _bitmap_bytes_per_slice * slice; 2614 size_t len = _bitmap_bytes_per_slice; 2615 if (!os::uncommit_memory((char*)_bitmap_region.start() + off, len)) { 2616 return false; 2617 } 2618 return true; 2619 } 2620 2621 void ShenandoahHeap::safepoint_synchronize_begin() { 2622 if (ShenandoahSuspendibleWorkers || UseStringDeduplication) { 2623 SuspendibleThreadSet::synchronize(); 2624 } 2625 } 2626 2627 void ShenandoahHeap::safepoint_synchronize_end() { 2628 if (ShenandoahSuspendibleWorkers || UseStringDeduplication) { 2629 SuspendibleThreadSet::desynchronize(); 2630 } 2631 } 2632 2633 void ShenandoahHeap::vmop_entry_init_mark() { 2634 TraceCollectorStats tcs(monitoring_support()->stw_collection_counters()); 2635 ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross); 2636 ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_mark_gross); 2637 2638 try_inject_alloc_failure(); 2639 VM_ShenandoahInitMark op; 2640 VMThread::execute(&op); // jump to entry_init_mark() under safepoint 2641 } 2642 2643 void ShenandoahHeap::vmop_entry_final_mark() { 2644 TraceCollectorStats tcs(monitoring_support()->stw_collection_counters()); 2645 ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross); 2646 ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_mark_gross); 2647 2648 try_inject_alloc_failure(); 2649 VM_ShenandoahFinalMarkStartEvac op; 2650 VMThread::execute(&op); // jump to entry_final_mark under safepoint 2651 } 2652 2653 void ShenandoahHeap::vmop_entry_final_evac() { 2654 TraceCollectorStats tcs(monitoring_support()->stw_collection_counters()); 2655 ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross); 2656 ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac_gross); 2657 2658 VM_ShenandoahFinalEvac op; 2659 VMThread::execute(&op); // jump to entry_final_evac under safepoint 2660 } 2661 2662 void ShenandoahHeap::vmop_entry_init_updaterefs() { 2663 TraceCollectorStats tcs(monitoring_support()->stw_collection_counters()); 2664 ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross); 2665 ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs_gross); 2666 2667 try_inject_alloc_failure(); 2668 VM_ShenandoahInitUpdateRefs op; 2669 VMThread::execute(&op); 2670 } 2671 2672 void ShenandoahHeap::vmop_entry_final_updaterefs() { 2673 TraceCollectorStats tcs(monitoring_support()->stw_collection_counters()); 2674 ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross); 2675 ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs_gross); 2676 2677 try_inject_alloc_failure(); 2678 VM_ShenandoahFinalUpdateRefs op; 2679 VMThread::execute(&op); 2680 } 2681 2682 void ShenandoahHeap::vmop_entry_init_traversal() { 2683 TraceCollectorStats tcs(monitoring_support()->stw_collection_counters()); 2684 ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross); 2685 ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_traversal_gc_gross); 2686 2687 try_inject_alloc_failure(); 2688 VM_ShenandoahInitTraversalGC op; 2689 VMThread::execute(&op); 2690 } 2691 2692 void ShenandoahHeap::vmop_entry_final_traversal() { 2693 TraceCollectorStats tcs(monitoring_support()->stw_collection_counters()); 2694 ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross); 2695 ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_traversal_gc_gross); 2696 2697 try_inject_alloc_failure(); 2698 VM_ShenandoahFinalTraversalGC op; 2699 VMThread::execute(&op); 2700 } 2701 2702 void ShenandoahHeap::vmop_entry_full(GCCause::Cause cause) { 2703 TraceCollectorStats tcs(monitoring_support()->full_stw_collection_counters()); 2704 ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross); 2705 ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc_gross); 2706 2707 try_inject_alloc_failure(); 2708 VM_ShenandoahFullGC op(cause); 2709 VMThread::execute(&op); 2710 } 2711 2712 void ShenandoahHeap::vmop_degenerated(ShenandoahDegenPoint point) { 2713 TraceCollectorStats tcs(monitoring_support()->full_stw_collection_counters()); 2714 ShenandoahGCPhase total(ShenandoahPhaseTimings::total_pause_gross); 2715 ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_gross); 2716 2717 VM_ShenandoahDegeneratedGC degenerated_gc((int)point); 2718 VMThread::execute(°enerated_gc); 2719 } 2720 2721 void ShenandoahHeap::entry_init_mark() { 2722 ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause); 2723 ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_mark); 2724 const char* msg = init_mark_event_message(); 2725 GCTraceTime(Info, gc) time(msg, gc_timer()); 2726 EventMark em("%s", msg); 2727 2728 ShenandoahWorkerScope scope(workers(), 2729 ShenandoahWorkerPolicy::calc_workers_for_init_marking(), 2730 "init marking"); 2731 2732 op_init_mark(); 2733 } 2734 2735 void ShenandoahHeap::entry_final_mark() { 2736 ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause); 2737 ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_mark); 2738 const char* msg = final_mark_event_message(); 2739 GCTraceTime(Info, gc) time(msg, gc_timer()); 2740 EventMark em("%s", msg); 2741 2742 ShenandoahWorkerScope scope(workers(), 2743 ShenandoahWorkerPolicy::calc_workers_for_final_marking(), 2744 "final marking"); 2745 2746 op_final_mark(); 2747 } 2748 2749 void ShenandoahHeap::entry_final_evac() { 2750 ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause); 2751 ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_evac); 2752 static const char* msg = "Pause Final Evac"; 2753 GCTraceTime(Info, gc) time(msg, gc_timer()); 2754 EventMark em("%s", msg); 2755 2756 op_final_evac(); 2757 } 2758 2759 void ShenandoahHeap::entry_init_updaterefs() { 2760 ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause); 2761 ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_update_refs); 2762 2763 static const char* msg = "Pause Init Update Refs"; 2764 GCTraceTime(Info, gc) time(msg, gc_timer()); 2765 EventMark em("%s", msg); 2766 2767 // No workers used in this phase, no setup required 2768 2769 op_init_updaterefs(); 2770 } 2771 2772 void ShenandoahHeap::entry_final_updaterefs() { 2773 ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause); 2774 ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_update_refs); 2775 2776 static const char* msg = "Pause Final Update Refs"; 2777 GCTraceTime(Info, gc) time(msg, gc_timer()); 2778 EventMark em("%s", msg); 2779 2780 ShenandoahWorkerScope scope(workers(), 2781 ShenandoahWorkerPolicy::calc_workers_for_final_update_ref(), 2782 "final reference update"); 2783 2784 op_final_updaterefs(); 2785 } 2786 2787 void ShenandoahHeap::entry_init_traversal() { 2788 ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause); 2789 ShenandoahGCPhase phase(ShenandoahPhaseTimings::init_traversal_gc); 2790 2791 static const char* msg = init_traversal_event_message(); 2792 GCTraceTime(Info, gc) time(msg, gc_timer()); 2793 EventMark em("%s", msg); 2794 2795 ShenandoahWorkerScope scope(workers(), 2796 ShenandoahWorkerPolicy::calc_workers_for_stw_traversal(), 2797 "init traversal"); 2798 2799 op_init_traversal(); 2800 } 2801 2802 void ShenandoahHeap::entry_final_traversal() { 2803 ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause); 2804 ShenandoahGCPhase phase(ShenandoahPhaseTimings::final_traversal_gc); 2805 2806 static const char* msg = final_traversal_event_message(); 2807 GCTraceTime(Info, gc) time(msg, gc_timer()); 2808 EventMark em("%s", msg); 2809 2810 ShenandoahWorkerScope scope(workers(), 2811 ShenandoahWorkerPolicy::calc_workers_for_stw_traversal(), 2812 "final traversal"); 2813 2814 op_final_traversal(); 2815 } 2816 2817 void ShenandoahHeap::entry_full(GCCause::Cause cause) { 2818 ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause); 2819 ShenandoahGCPhase phase(ShenandoahPhaseTimings::full_gc); 2820 2821 static const char* msg = "Pause Full"; 2822 GCTraceTime(Info, gc) time(msg, gc_timer(), cause, true); 2823 EventMark em("%s", msg); 2824 2825 ShenandoahWorkerScope scope(workers(), 2826 ShenandoahWorkerPolicy::calc_workers_for_fullgc(), 2827 "full gc"); 2828 2829 op_full(cause); 2830 } 2831 2832 void ShenandoahHeap::entry_degenerated(int point) { 2833 ShenandoahGCPhase total_phase(ShenandoahPhaseTimings::total_pause); 2834 ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc); 2835 2836 ShenandoahDegenPoint dpoint = (ShenandoahDegenPoint)point; 2837 const char* msg = degen_event_message(dpoint); 2838 GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true); 2839 EventMark em("%s", msg); 2840 2841 ShenandoahWorkerScope scope(workers(), 2842 ShenandoahWorkerPolicy::calc_workers_for_stw_degenerated(), 2843 "stw degenerated gc"); 2844 2845 set_degenerated_gc_in_progress(true); 2846 op_degenerated(dpoint); 2847 set_degenerated_gc_in_progress(false); 2848 } 2849 2850 void ShenandoahHeap::entry_mark() { 2851 TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters()); 2852 2853 const char* msg = conc_mark_event_message(); 2854 GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true); 2855 EventMark em("%s", msg); 2856 2857 ShenandoahWorkerScope scope(workers(), 2858 ShenandoahWorkerPolicy::calc_workers_for_conc_marking(), 2859 "concurrent marking"); 2860 2861 try_inject_alloc_failure(); 2862 op_mark(); 2863 } 2864 2865 void ShenandoahHeap::entry_evac() { 2866 ShenandoahGCPhase conc_evac_phase(ShenandoahPhaseTimings::conc_evac); 2867 TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters()); 2868 2869 static const char* msg = "Concurrent evacuation"; 2870 GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true); 2871 EventMark em("%s", msg); 2872 2873 ShenandoahWorkerScope scope(workers(), 2874 ShenandoahWorkerPolicy::calc_workers_for_conc_evac(), 2875 "concurrent evacuation"); 2876 2877 try_inject_alloc_failure(); 2878 op_conc_evac(); 2879 } 2880 2881 void ShenandoahHeap::entry_updaterefs() { 2882 ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_update_refs); 2883 2884 static const char* msg = "Concurrent update references"; 2885 GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true); 2886 EventMark em("%s", msg); 2887 2888 ShenandoahWorkerScope scope(workers(), 2889 ShenandoahWorkerPolicy::calc_workers_for_conc_update_ref(), 2890 "concurrent reference update"); 2891 2892 try_inject_alloc_failure(); 2893 op_updaterefs(); 2894 } 2895 2896 void ShenandoahHeap::entry_roots() { 2897 ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_roots); 2898 2899 static const char* msg = "Concurrent roots processing"; 2900 GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true); 2901 EventMark em("%s", msg); 2902 2903 ShenandoahWorkerScope scope(workers(), 2904 ShenandoahWorkerPolicy::calc_workers_for_conc_root_processing(), 2905 "concurrent root processing"); 2906 2907 try_inject_alloc_failure(); 2908 op_roots(); 2909 } 2910 2911 void ShenandoahHeap::entry_cleanup() { 2912 ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_cleanup); 2913 2914 static const char* msg = "Concurrent cleanup"; 2915 GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true); 2916 EventMark em("%s", msg); 2917 2918 // This phase does not use workers, no need for setup 2919 2920 try_inject_alloc_failure(); 2921 op_cleanup(); 2922 } 2923 2924 void ShenandoahHeap::entry_reset() { 2925 ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_reset); 2926 2927 static const char* msg = "Concurrent reset"; 2928 GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true); 2929 EventMark em("%s", msg); 2930 2931 ShenandoahWorkerScope scope(workers(), 2932 ShenandoahWorkerPolicy::calc_workers_for_conc_reset(), 2933 "concurrent reset"); 2934 2935 try_inject_alloc_failure(); 2936 op_reset(); 2937 } 2938 2939 void ShenandoahHeap::entry_preclean() { 2940 if (ShenandoahPreclean && process_references()) { 2941 static const char* msg = "Concurrent precleaning"; 2942 GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true); 2943 EventMark em("%s", msg); 2944 2945 ShenandoahGCPhase conc_preclean(ShenandoahPhaseTimings::conc_preclean); 2946 2947 ShenandoahWorkerScope scope(workers(), 2948 ShenandoahWorkerPolicy::calc_workers_for_conc_preclean(), 2949 "concurrent preclean", 2950 /* check_workers = */ false); 2951 2952 try_inject_alloc_failure(); 2953 op_preclean(); 2954 } 2955 } 2956 2957 void ShenandoahHeap::entry_traversal() { 2958 static const char* msg = conc_traversal_event_message(); 2959 GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true); 2960 EventMark em("%s", msg); 2961 2962 TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters()); 2963 2964 ShenandoahWorkerScope scope(workers(), 2965 ShenandoahWorkerPolicy::calc_workers_for_conc_traversal(), 2966 "concurrent traversal"); 2967 2968 try_inject_alloc_failure(); 2969 op_traversal(); 2970 } 2971 2972 void ShenandoahHeap::entry_uncommit(double shrink_before) { 2973 static const char *msg = "Concurrent uncommit"; 2974 GCTraceTime(Info, gc) time(msg, NULL, GCCause::_no_gc, true); 2975 EventMark em("%s", msg); 2976 2977 ShenandoahGCPhase phase(ShenandoahPhaseTimings::conc_uncommit); 2978 2979 op_uncommit(shrink_before); 2980 } 2981 2982 void ShenandoahHeap::try_inject_alloc_failure() { 2983 if (ShenandoahAllocFailureALot && !cancelled_gc() && ((os::random() % 1000) > 950)) { 2984 _inject_alloc_failure.set(); 2985 os::naked_short_sleep(1); 2986 if (cancelled_gc()) { 2987 log_info(gc)("Allocation failure was successfully injected"); 2988 } 2989 } 2990 } 2991 2992 bool ShenandoahHeap::should_inject_alloc_failure() { 2993 return _inject_alloc_failure.is_set() && _inject_alloc_failure.try_unset(); 2994 } 2995 2996 void ShenandoahHeap::initialize_serviceability() { 2997 _memory_pool = new ShenandoahMemoryPool(this); 2998 _cycle_memory_manager.add_pool(_memory_pool); 2999 _stw_memory_manager.add_pool(_memory_pool); 3000 } 3001 3002 GrowableArray<GCMemoryManager*> ShenandoahHeap::memory_managers() { 3003 GrowableArray<GCMemoryManager*> memory_managers(2); 3004 memory_managers.append(&_cycle_memory_manager); 3005 memory_managers.append(&_stw_memory_manager); 3006 return memory_managers; 3007 } 3008 3009 GrowableArray<MemoryPool*> ShenandoahHeap::memory_pools() { 3010 GrowableArray<MemoryPool*> memory_pools(1); 3011 memory_pools.append(_memory_pool); 3012 return memory_pools; 3013 } 3014 3015 MemoryUsage ShenandoahHeap::memory_usage() { 3016 return _memory_pool->get_memory_usage(); 3017 } 3018 3019 void ShenandoahHeap::enter_evacuation() { 3020 _oom_evac_handler.enter_evacuation(); 3021 } 3022 3023 void ShenandoahHeap::leave_evacuation() { 3024 _oom_evac_handler.leave_evacuation(); 3025 } 3026 3027 ShenandoahRegionIterator::ShenandoahRegionIterator() : 3028 _heap(ShenandoahHeap::heap()), 3029 _index(0) {} 3030 3031 ShenandoahRegionIterator::ShenandoahRegionIterator(ShenandoahHeap* heap) : 3032 _heap(heap), 3033 _index(0) {} 3034 3035 void ShenandoahRegionIterator::reset() { 3036 _index = 0; 3037 } 3038 3039 bool ShenandoahRegionIterator::has_next() const { 3040 return _index < _heap->num_regions(); 3041 } 3042 3043 char ShenandoahHeap::gc_state() const { 3044 return _gc_state.raw_value(); 3045 } 3046 3047 void ShenandoahHeap::deduplicate_string(oop str) { 3048 assert(java_lang_String::is_instance(str), "invariant"); 3049 3050 if (ShenandoahStringDedup::is_enabled()) { 3051 ShenandoahStringDedup::deduplicate(str); 3052 } 3053 } 3054 3055 const char* ShenandoahHeap::init_mark_event_message() const { 3056 bool update_refs = has_forwarded_objects(); 3057 bool proc_refs = process_references(); 3058 bool unload_cls = unload_classes(); 3059 3060 if (update_refs && proc_refs && unload_cls) { 3061 return "Pause Init Mark (update refs) (process weakrefs) (unload classes)"; 3062 } else if (update_refs && proc_refs) { 3063 return "Pause Init Mark (update refs) (process weakrefs)"; 3064 } else if (update_refs && unload_cls) { 3065 return "Pause Init Mark (update refs) (unload classes)"; 3066 } else if (proc_refs && unload_cls) { 3067 return "Pause Init Mark (process weakrefs) (unload classes)"; 3068 } else if (update_refs) { 3069 return "Pause Init Mark (update refs)"; 3070 } else if (proc_refs) { 3071 return "Pause Init Mark (process weakrefs)"; 3072 } else if (unload_cls) { 3073 return "Pause Init Mark (unload classes)"; 3074 } else { 3075 return "Pause Init Mark"; 3076 } 3077 } 3078 3079 const char* ShenandoahHeap::final_mark_event_message() const { 3080 bool update_refs = has_forwarded_objects(); 3081 bool proc_refs = process_references(); 3082 bool unload_cls = unload_classes(); 3083 3084 if (update_refs && proc_refs && unload_cls) { 3085 return "Pause Final Mark (update refs) (process weakrefs) (unload classes)"; 3086 } else if (update_refs && proc_refs) { 3087 return "Pause Final Mark (update refs) (process weakrefs)"; 3088 } else if (update_refs && unload_cls) { 3089 return "Pause Final Mark (update refs) (unload classes)"; 3090 } else if (proc_refs && unload_cls) { 3091 return "Pause Final Mark (process weakrefs) (unload classes)"; 3092 } else if (update_refs) { 3093 return "Pause Final Mark (update refs)"; 3094 } else if (proc_refs) { 3095 return "Pause Final Mark (process weakrefs)"; 3096 } else if (unload_cls) { 3097 return "Pause Final Mark (unload classes)"; 3098 } else { 3099 return "Pause Final Mark"; 3100 } 3101 } 3102 3103 const char* ShenandoahHeap::conc_mark_event_message() const { 3104 bool update_refs = has_forwarded_objects(); 3105 bool proc_refs = process_references(); 3106 bool unload_cls = unload_classes(); 3107 3108 if (update_refs && proc_refs && unload_cls) { 3109 return "Concurrent marking (update refs) (process weakrefs) (unload classes)"; 3110 } else if (update_refs && proc_refs) { 3111 return "Concurrent marking (update refs) (process weakrefs)"; 3112 } else if (update_refs && unload_cls) { 3113 return "Concurrent marking (update refs) (unload classes)"; 3114 } else if (proc_refs && unload_cls) { 3115 return "Concurrent marking (process weakrefs) (unload classes)"; 3116 } else if (update_refs) { 3117 return "Concurrent marking (update refs)"; 3118 } else if (proc_refs) { 3119 return "Concurrent marking (process weakrefs)"; 3120 } else if (unload_cls) { 3121 return "Concurrent marking (unload classes)"; 3122 } else { 3123 return "Concurrent marking"; 3124 } 3125 } 3126 3127 const char* ShenandoahHeap::init_traversal_event_message() const { 3128 bool proc_refs = process_references(); 3129 bool unload_cls = unload_classes(); 3130 3131 if (proc_refs && unload_cls) { 3132 return "Pause Init Traversal (process weakrefs) (unload classes)"; 3133 } else if (proc_refs) { 3134 return "Pause Init Traversal (process weakrefs)"; 3135 } else if (unload_cls) { 3136 return "Pause Init Traversal (unload classes)"; 3137 } else { 3138 return "Pause Init Traversal"; 3139 } 3140 } 3141 3142 const char* ShenandoahHeap::final_traversal_event_message() const { 3143 bool proc_refs = process_references(); 3144 bool unload_cls = unload_classes(); 3145 3146 if (proc_refs && unload_cls) { 3147 return "Pause Final Traversal (process weakrefs) (unload classes)"; 3148 } else if (proc_refs) { 3149 return "Pause Final Traversal (process weakrefs)"; 3150 } else if (unload_cls) { 3151 return "Pause Final Traversal (unload classes)"; 3152 } else { 3153 return "Pause Final Traversal"; 3154 } 3155 } 3156 3157 const char* ShenandoahHeap::conc_traversal_event_message() const { 3158 bool proc_refs = process_references(); 3159 bool unload_cls = unload_classes(); 3160 3161 if (proc_refs && unload_cls) { 3162 return "Concurrent Traversal (process weakrefs) (unload classes)"; 3163 } else if (proc_refs) { 3164 return "Concurrent Traversal (process weakrefs)"; 3165 } else if (unload_cls) { 3166 return "Concurrent Traversal (unload classes)"; 3167 } else { 3168 return "Concurrent Traversal"; 3169 } 3170 } 3171 3172 const char* ShenandoahHeap::degen_event_message(ShenandoahDegenPoint point) const { 3173 switch (point) { 3174 case _degenerated_unset: 3175 return "Pause Degenerated GC (<UNSET>)"; 3176 case _degenerated_traversal: 3177 return "Pause Degenerated GC (Traversal)"; 3178 case _degenerated_outside_cycle: 3179 return "Pause Degenerated GC (Outside of Cycle)"; 3180 case _degenerated_mark: 3181 return "Pause Degenerated GC (Mark)"; 3182 case _degenerated_evac: 3183 return "Pause Degenerated GC (Evacuation)"; 3184 case _degenerated_updaterefs: 3185 return "Pause Degenerated GC (Update Refs)"; 3186 default: 3187 ShouldNotReachHere(); 3188 return "ERROR"; 3189 } 3190 } 3191 3192 jushort* ShenandoahHeap::get_liveness_cache(uint worker_id) { 3193 #ifdef ASSERT 3194 assert(_liveness_cache != NULL, "sanity"); 3195 assert(worker_id < _max_workers, "sanity"); 3196 for (uint i = 0; i < num_regions(); i++) { 3197 assert(_liveness_cache[worker_id][i] == 0, "liveness cache should be empty"); 3198 } 3199 #endif 3200 return _liveness_cache[worker_id]; 3201 } 3202 3203 void ShenandoahHeap::flush_liveness_cache(uint worker_id) { 3204 assert(worker_id < _max_workers, "sanity"); 3205 assert(_liveness_cache != NULL, "sanity"); 3206 jushort* ld = _liveness_cache[worker_id]; 3207 for (uint i = 0; i < num_regions(); i++) { 3208 ShenandoahHeapRegion* r = get_region(i); 3209 jushort live = ld[i]; 3210 if (live > 0) { 3211 r->increase_live_data_gc_words(live); 3212 ld[i] = 0; 3213 } 3214 } 3215 }