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