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