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