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