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