1 /* 2 * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "precompiled.hpp" 26 #include "classfile/classLoaderDataGraph.hpp" 27 #include "classfile/metadataOnStackMark.hpp" 28 #include "classfile/systemDictionary.hpp" 29 #include "code/codeCache.hpp" 30 #include "code/icBuffer.hpp" 31 #include "compiler/oopMap.hpp" 32 #include "gc/g1/g1Allocator.inline.hpp" 33 #include "gc/g1/g1Arguments.hpp" 34 #include "gc/g1/g1BarrierSet.hpp" 35 #include "gc/g1/g1BatchedTask.hpp" 36 #include "gc/g1/g1CollectedHeap.inline.hpp" 37 #include "gc/g1/g1CollectionSet.hpp" 38 #include "gc/g1/g1CollectionSetCandidates.hpp" 39 #include "gc/g1/g1CollectorState.hpp" 40 #include "gc/g1/g1ConcurrentRefine.hpp" 41 #include "gc/g1/g1ConcurrentRefineThread.hpp" 42 #include "gc/g1/g1ConcurrentMarkThread.inline.hpp" 43 #include "gc/g1/g1DirtyCardQueue.hpp" 44 #include "gc/g1/g1EvacStats.inline.hpp" 45 #include "gc/g1/g1FullCollector.hpp" 46 #include "gc/g1/g1GCCounters.hpp" 47 #include "gc/g1/g1GCParPhaseTimesTracker.hpp" 48 #include "gc/g1/g1GCPhaseTimes.hpp" 49 #include "gc/g1/g1GCPauseType.hpp" 50 #include "gc/g1/g1HeapSizingPolicy.hpp" 51 #include "gc/g1/g1HeapTransition.hpp" 52 #include "gc/g1/g1HeapVerifier.hpp" 53 #include "gc/g1/g1InitLogger.hpp" 54 #include "gc/g1/g1MemoryPool.hpp" 55 #include "gc/g1/g1MonotonicArenaFreeMemoryTask.hpp" 56 #include "gc/g1/g1OopClosures.inline.hpp" 57 #include "gc/g1/g1ParallelCleaning.hpp" 58 #include "gc/g1/g1ParScanThreadState.inline.hpp" 59 #include "gc/g1/g1PeriodicGCTask.hpp" 60 #include "gc/g1/g1Policy.hpp" 61 #include "gc/g1/g1RedirtyCardsQueue.hpp" 62 #include "gc/g1/g1RegionToSpaceMapper.hpp" 63 #include "gc/g1/g1RemSet.hpp" 64 #include "gc/g1/g1RootClosures.hpp" 65 #include "gc/g1/g1RootProcessor.hpp" 66 #include "gc/g1/g1SATBMarkQueueSet.hpp" 67 #include "gc/g1/g1ServiceThread.hpp" 68 #include "gc/g1/g1ThreadLocalData.hpp" 69 #include "gc/g1/g1Trace.hpp" 70 #include "gc/g1/g1UncommitRegionTask.hpp" 71 #include "gc/g1/g1VMOperations.hpp" 72 #include "gc/g1/g1YoungCollector.hpp" 73 #include "gc/g1/g1YoungGCEvacFailureInjector.hpp" 74 #include "gc/g1/heapRegion.inline.hpp" 75 #include "gc/g1/heapRegionRemSet.inline.hpp" 76 #include "gc/g1/heapRegionSet.inline.hpp" 77 #include "gc/shared/classUnloadingContext.hpp" 78 #include "gc/shared/concurrentGCBreakpoints.hpp" 79 #include "gc/shared/gcBehaviours.hpp" 80 #include "gc/shared/gcHeapSummary.hpp" 81 #include "gc/shared/gcId.hpp" 82 #include "gc/shared/gcLocker.inline.hpp" 83 #include "gc/shared/gcTimer.hpp" 84 #include "gc/shared/gcTraceTime.inline.hpp" 85 #include "gc/shared/generationSpec.hpp" 86 #include "gc/shared/isGCActiveMark.hpp" 87 #include "gc/shared/locationPrinter.inline.hpp" 88 #include "gc/shared/oopStorageParState.hpp" 89 #include "gc/shared/preservedMarks.inline.hpp" 90 #include "gc/shared/referenceProcessor.inline.hpp" 91 #include "gc/shared/suspendibleThreadSet.hpp" 92 #include "gc/shared/taskqueue.inline.hpp" 93 #include "gc/shared/taskTerminator.hpp" 94 #include "gc/shared/tlab_globals.hpp" 95 #include "gc/shared/workerPolicy.hpp" 96 #include "gc/shared/weakProcessor.inline.hpp" 97 #include "logging/log.hpp" 98 #include "memory/allocation.hpp" 99 #include "memory/heapInspection.hpp" 100 #include "memory/iterator.hpp" 101 #include "memory/metaspaceUtils.hpp" 102 #include "memory/resourceArea.hpp" 103 #include "memory/universe.hpp" 104 #include "oops/access.inline.hpp" 105 #include "oops/compressedOops.inline.hpp" 106 #include "oops/oop.inline.hpp" 107 #include "runtime/atomic.hpp" 108 #include "runtime/handles.inline.hpp" 109 #include "runtime/init.hpp" 110 #include "runtime/java.hpp" 111 #include "runtime/orderAccess.hpp" 112 #include "runtime/threadSMR.hpp" 113 #include "runtime/vmThread.hpp" 114 #include "utilities/align.hpp" 115 #include "utilities/autoRestore.hpp" 116 #include "utilities/bitMap.inline.hpp" 117 #include "utilities/globalDefinitions.hpp" 118 #include "utilities/stack.inline.hpp" 119 120 size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0; 121 122 // INVARIANTS/NOTES 123 // 124 // All allocation activity covered by the G1CollectedHeap interface is 125 // serialized by acquiring the HeapLock. This happens in mem_allocate 126 // and allocate_new_tlab, which are the "entry" points to the 127 // allocation code from the rest of the JVM. (Note that this does not 128 // apply to TLAB allocation, which is not part of this interface: it 129 // is done by clients of this interface.) 130 131 void G1RegionMappingChangedListener::reset_from_card_cache(uint start_idx, size_t num_regions) { 132 HeapRegionRemSet::invalidate_from_card_cache(start_idx, num_regions); 133 } 134 135 void G1RegionMappingChangedListener::on_commit(uint start_idx, size_t num_regions, bool zero_filled) { 136 // The from card cache is not the memory that is actually committed. So we cannot 137 // take advantage of the zero_filled parameter. 138 reset_from_card_cache(start_idx, num_regions); 139 } 140 141 void G1CollectedHeap::run_batch_task(G1BatchedTask* cl) { 142 uint num_workers = MAX2(1u, MIN2(cl->num_workers_estimate(), workers()->active_workers())); 143 cl->set_max_workers(num_workers); 144 workers()->run_task(cl, num_workers); 145 } 146 147 uint G1CollectedHeap::get_chunks_per_region() { 148 uint log_region_size = HeapRegion::LogOfHRGrainBytes; 149 // Limit the expected input values to current known possible values of the 150 // (log) region size. Adjust as necessary after testing if changing the permissible 151 // values for region size. 152 assert(log_region_size >= 20 && log_region_size <= 29, 153 "expected value in [20,29], but got %u", log_region_size); 154 return 1u << (log_region_size / 2 - 4); 155 } 156 157 HeapRegion* G1CollectedHeap::new_heap_region(uint hrs_index, 158 MemRegion mr) { 159 return new HeapRegion(hrs_index, bot(), mr, &_card_set_config); 160 } 161 162 // Private methods. 163 164 HeapRegion* G1CollectedHeap::new_region(size_t word_size, 165 HeapRegionType type, 166 bool do_expand, 167 uint node_index) { 168 assert(!is_humongous(word_size) || word_size <= HeapRegion::GrainWords, 169 "the only time we use this to allocate a humongous region is " 170 "when we are allocating a single humongous region"); 171 172 HeapRegion* res = _hrm.allocate_free_region(type, node_index); 173 174 if (res == nullptr && do_expand) { 175 // Currently, only attempts to allocate GC alloc regions set 176 // do_expand to true. So, we should only reach here during a 177 // safepoint. 178 assert(SafepointSynchronize::is_at_safepoint(), "invariant"); 179 180 log_debug(gc, ergo, heap)("Attempt heap expansion (region allocation request failed). Allocation request: " SIZE_FORMAT "B", 181 word_size * HeapWordSize); 182 183 assert(word_size * HeapWordSize < HeapRegion::GrainBytes, 184 "This kind of expansion should never be more than one region. Size: " SIZE_FORMAT, 185 word_size * HeapWordSize); 186 if (expand_single_region(node_index)) { 187 // Given that expand_single_region() succeeded in expanding the heap, and we 188 // always expand the heap by an amount aligned to the heap 189 // region size, the free list should in theory not be empty. 190 // In either case allocate_free_region() will check for null. 191 res = _hrm.allocate_free_region(type, node_index); 192 } 193 } 194 return res; 195 } 196 197 void G1CollectedHeap::set_humongous_metadata(HeapRegion* first_hr, 198 uint num_regions, 199 size_t word_size, 200 bool update_remsets) { 201 // Calculate the new top of the humongous object. 202 HeapWord* obj_top = first_hr->bottom() + word_size; 203 // The word size sum of all the regions used 204 size_t word_size_sum = num_regions * HeapRegion::GrainWords; 205 assert(word_size <= word_size_sum, "sanity"); 206 207 // How many words memory we "waste" which cannot hold a filler object. 208 size_t words_not_fillable = 0; 209 210 // Pad out the unused tail of the last region with filler 211 // objects, for improved usage accounting. 212 213 // How many words can we use for filler objects. 214 size_t words_fillable = word_size_sum - word_size; 215 216 if (words_fillable >= G1CollectedHeap::min_fill_size()) { 217 G1CollectedHeap::fill_with_objects(obj_top, words_fillable); 218 } else { 219 // We have space to fill, but we cannot fit an object there. 220 words_not_fillable = words_fillable; 221 words_fillable = 0; 222 } 223 224 // We will set up the first region as "starts humongous". This 225 // will also update the BOT covering all the regions to reflect 226 // that there is a single object that starts at the bottom of the 227 // first region. 228 first_hr->hr_clear(false /* clear_space */); 229 first_hr->set_starts_humongous(obj_top, words_fillable); 230 231 if (update_remsets) { 232 _policy->remset_tracker()->update_at_allocate(first_hr); 233 } 234 235 // Indices of first and last regions in the series. 236 uint first = first_hr->hrm_index(); 237 uint last = first + num_regions - 1; 238 239 HeapRegion* hr = nullptr; 240 for (uint i = first + 1; i <= last; ++i) { 241 hr = region_at(i); 242 hr->hr_clear(false /* clear_space */); 243 hr->set_continues_humongous(first_hr); 244 if (update_remsets) { 245 _policy->remset_tracker()->update_at_allocate(hr); 246 } 247 } 248 249 // Up to this point no concurrent thread would have been able to 250 // do any scanning on any region in this series. All the top 251 // fields still point to bottom, so the intersection between 252 // [bottom,top] and [card_start,card_end] will be empty. Before we 253 // update the top fields, we'll do a storestore to make sure that 254 // no thread sees the update to top before the zeroing of the 255 // object header and the BOT initialization. 256 OrderAccess::storestore(); 257 258 // Now, we will update the top fields of the "continues humongous" 259 // regions except the last one. 260 for (uint i = first; i < last; ++i) { 261 hr = region_at(i); 262 hr->set_top(hr->end()); 263 } 264 265 hr = region_at(last); 266 // If we cannot fit a filler object, we must set top to the end 267 // of the humongous object, otherwise we cannot iterate the heap 268 // and the BOT will not be complete. 269 hr->set_top(hr->end() - words_not_fillable); 270 271 assert(hr->bottom() < obj_top && obj_top <= hr->end(), 272 "obj_top should be in last region"); 273 274 assert(words_not_fillable == 0 || 275 first_hr->bottom() + word_size_sum - words_not_fillable == hr->top(), 276 "Miscalculation in humongous allocation"); 277 } 278 279 HeapWord* 280 G1CollectedHeap::humongous_obj_allocate_initialize_regions(HeapRegion* first_hr, 281 uint num_regions, 282 size_t word_size) { 283 assert(first_hr != nullptr, "pre-condition"); 284 assert(is_humongous(word_size), "word_size should be humongous"); 285 assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition"); 286 287 // Index of last region in the series. 288 uint first = first_hr->hrm_index(); 289 uint last = first + num_regions - 1; 290 291 // We need to initialize the region(s) we just discovered. This is 292 // a bit tricky given that it can happen concurrently with 293 // refinement threads refining cards on these regions and 294 // potentially wanting to refine the BOT as they are scanning 295 // those cards (this can happen shortly after a cleanup; see CR 296 // 6991377). So we have to set up the region(s) carefully and in 297 // a specific order. 298 299 // The passed in hr will be the "starts humongous" region. The header 300 // of the new object will be placed at the bottom of this region. 301 HeapWord* new_obj = first_hr->bottom(); 302 303 // First, we need to zero the header of the space that we will be 304 // allocating. When we update top further down, some refinement 305 // threads might try to scan the region. By zeroing the header we 306 // ensure that any thread that will try to scan the region will 307 // come across the zero klass word and bail out. 308 // 309 // NOTE: It would not have been correct to have used 310 // CollectedHeap::fill_with_object() and make the space look like 311 // an int array. The thread that is doing the allocation will 312 // later update the object header to a potentially different array 313 // type and, for a very short period of time, the klass and length 314 // fields will be inconsistent. This could cause a refinement 315 // thread to calculate the object size incorrectly. 316 Copy::fill_to_words(new_obj, oopDesc::header_size(), 0); 317 318 // Next, update the metadata for the regions. 319 set_humongous_metadata(first_hr, num_regions, word_size, true); 320 321 HeapRegion* last_hr = region_at(last); 322 size_t used = byte_size(first_hr->bottom(), last_hr->top()); 323 324 increase_used(used); 325 326 for (uint i = first; i <= last; ++i) { 327 HeapRegion *hr = region_at(i); 328 _humongous_set.add(hr); 329 _hr_printer.alloc(hr); 330 } 331 332 return new_obj; 333 } 334 335 size_t G1CollectedHeap::humongous_obj_size_in_regions(size_t word_size) { 336 assert(is_humongous(word_size), "Object of size " SIZE_FORMAT " must be humongous here", word_size); 337 return align_up(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords; 338 } 339 340 // If could fit into free regions w/o expansion, try. 341 // Otherwise, if can expand, do so. 342 // Otherwise, if using ex regions might help, try with ex given back. 343 HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size) { 344 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */); 345 346 _verifier->verify_region_sets_optional(); 347 348 uint obj_regions = (uint) humongous_obj_size_in_regions(word_size); 349 350 // Policy: First try to allocate a humongous object in the free list. 351 HeapRegion* humongous_start = _hrm.allocate_humongous(obj_regions); 352 if (humongous_start == nullptr) { 353 // Policy: We could not find enough regions for the humongous object in the 354 // free list. Look through the heap to find a mix of free and uncommitted regions. 355 // If so, expand the heap and allocate the humongous object. 356 humongous_start = _hrm.expand_and_allocate_humongous(obj_regions); 357 if (humongous_start != nullptr) { 358 // We managed to find a region by expanding the heap. 359 log_debug(gc, ergo, heap)("Heap expansion (humongous allocation request). Allocation request: " SIZE_FORMAT "B", 360 word_size * HeapWordSize); 361 policy()->record_new_heap_size(num_regions()); 362 } else { 363 // Policy: Potentially trigger a defragmentation GC. 364 } 365 } 366 367 HeapWord* result = nullptr; 368 if (humongous_start != nullptr) { 369 result = humongous_obj_allocate_initialize_regions(humongous_start, obj_regions, word_size); 370 assert(result != nullptr, "it should always return a valid result"); 371 372 // A successful humongous object allocation changes the used space 373 // information of the old generation so we need to recalculate the 374 // sizes and update the jstat counters here. 375 monitoring_support()->update_sizes(); 376 } 377 378 _verifier->verify_region_sets_optional(); 379 380 return result; 381 } 382 383 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t min_size, 384 size_t requested_size, 385 size_t* actual_size) { 386 assert_heap_not_locked_and_not_at_safepoint(); 387 assert(!is_humongous(requested_size), "we do not allow humongous TLABs"); 388 389 return attempt_allocation(min_size, requested_size, actual_size); 390 } 391 392 HeapWord* 393 G1CollectedHeap::mem_allocate(size_t word_size, 394 bool* gc_overhead_limit_was_exceeded) { 395 assert_heap_not_locked_and_not_at_safepoint(); 396 397 if (is_humongous(word_size)) { 398 return attempt_allocation_humongous(word_size); 399 } 400 size_t dummy = 0; 401 return attempt_allocation(word_size, word_size, &dummy); 402 } 403 404 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size) { 405 ResourceMark rm; // For retrieving the thread names in log messages. 406 407 // Make sure you read the note in attempt_allocation_humongous(). 408 409 assert_heap_not_locked_and_not_at_safepoint(); 410 assert(!is_humongous(word_size), "attempt_allocation_slow() should not " 411 "be called for humongous allocation requests"); 412 413 // We should only get here after the first-level allocation attempt 414 // (attempt_allocation()) failed to allocate. 415 416 // We will loop until a) we manage to successfully perform the 417 // allocation or b) we successfully schedule a collection which 418 // fails to perform the allocation. b) is the only case when we'll 419 // return null. 420 HeapWord* result = nullptr; 421 for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) { 422 bool should_try_gc; 423 uint gc_count_before; 424 425 { 426 MutexLocker x(Heap_lock); 427 428 // Now that we have the lock, we first retry the allocation in case another 429 // thread changed the region while we were waiting to acquire the lock. 430 result = _allocator->attempt_allocation_locked(word_size); 431 if (result != nullptr) { 432 return result; 433 } 434 435 // If the GCLocker is active and we are bound for a GC, try expanding young gen. 436 // This is different to when only GCLocker::needs_gc() is set: try to avoid 437 // waiting because the GCLocker is active to not wait too long. 438 if (GCLocker::is_active_and_needs_gc() && policy()->can_expand_young_list()) { 439 // No need for an ergo message here, can_expand_young_list() does this when 440 // it returns true. 441 result = _allocator->attempt_allocation_force(word_size); 442 if (result != nullptr) { 443 return result; 444 } 445 } 446 447 // Only try a GC if the GCLocker does not signal the need for a GC. Wait until 448 // the GCLocker initiated GC has been performed and then retry. This includes 449 // the case when the GC Locker is not active but has not been performed. 450 should_try_gc = !GCLocker::needs_gc(); 451 // Read the GC count while still holding the Heap_lock. 452 gc_count_before = total_collections(); 453 } 454 455 if (should_try_gc) { 456 bool succeeded; 457 result = do_collection_pause(word_size, gc_count_before, &succeeded, GCCause::_g1_inc_collection_pause); 458 if (result != nullptr) { 459 assert(succeeded, "only way to get back a non-null result"); 460 log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT, 461 Thread::current()->name(), p2i(result)); 462 return result; 463 } 464 465 if (succeeded) { 466 // We successfully scheduled a collection which failed to allocate. No 467 // point in trying to allocate further. We'll just return null. 468 log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate " 469 SIZE_FORMAT " words", Thread::current()->name(), word_size); 470 return nullptr; 471 } 472 log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT " words", 473 Thread::current()->name(), word_size); 474 } else { 475 // Failed to schedule a collection. 476 if (gclocker_retry_count > GCLockerRetryAllocationCount) { 477 log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating " 478 SIZE_FORMAT " words", Thread::current()->name(), word_size); 479 return nullptr; 480 } 481 log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name()); 482 // The GCLocker is either active or the GCLocker initiated 483 // GC has not yet been performed. Stall until it is and 484 // then retry the allocation. 485 GCLocker::stall_until_clear(); 486 gclocker_retry_count += 1; 487 } 488 489 // We can reach here if we were unsuccessful in scheduling a 490 // collection (because another thread beat us to it) or if we were 491 // stalled due to the GC locker. In either can we should retry the 492 // allocation attempt in case another thread successfully 493 // performed a collection and reclaimed enough space. We do the 494 // first attempt (without holding the Heap_lock) here and the 495 // follow-on attempt will be at the start of the next loop 496 // iteration (after taking the Heap_lock). 497 size_t dummy = 0; 498 result = _allocator->attempt_allocation(word_size, word_size, &dummy); 499 if (result != nullptr) { 500 return result; 501 } 502 503 // Give a warning if we seem to be looping forever. 504 if ((QueuedAllocationWarningCount > 0) && 505 (try_count % QueuedAllocationWarningCount == 0)) { 506 log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words", 507 Thread::current()->name(), try_count, word_size); 508 } 509 } 510 511 ShouldNotReachHere(); 512 return nullptr; 513 } 514 515 bool G1CollectedHeap::check_archive_addresses(MemRegion range) { 516 return _hrm.reserved().contains(range); 517 } 518 519 template <typename Func> 520 void G1CollectedHeap::iterate_regions_in_range(MemRegion range, const Func& func) { 521 // Mark each G1 region touched by the range as old, add it to 522 // the old set, and set top. 523 HeapRegion* curr_region = _hrm.addr_to_region(range.start()); 524 HeapRegion* end_region = _hrm.addr_to_region(range.last()); 525 526 while (curr_region != nullptr) { 527 bool is_last = curr_region == end_region; 528 HeapRegion* next_region = is_last ? nullptr : _hrm.next_region_in_heap(curr_region); 529 530 func(curr_region, is_last); 531 532 curr_region = next_region; 533 } 534 } 535 536 bool G1CollectedHeap::alloc_archive_regions(MemRegion range) { 537 assert(!is_init_completed(), "Expect to be called at JVM init time"); 538 MutexLocker x(Heap_lock); 539 540 MemRegion reserved = _hrm.reserved(); 541 542 // Temporarily disable pretouching of heap pages. This interface is used 543 // when mmap'ing archived heap data in, so pre-touching is wasted. 544 FlagSetting fs(AlwaysPreTouch, false); 545 546 // For the specified MemRegion range, allocate the corresponding G1 547 // region(s) and mark them as old region(s). 548 HeapWord* start_address = range.start(); 549 size_t word_size = range.word_size(); 550 HeapWord* last_address = range.last(); 551 size_t commits = 0; 552 553 guarantee(reserved.contains(start_address) && reserved.contains(last_address), 554 "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]", 555 p2i(start_address), p2i(last_address)); 556 557 // Perform the actual region allocation, exiting if it fails. 558 // Then note how much new space we have allocated. 559 if (!_hrm.allocate_containing_regions(range, &commits, workers())) { 560 return false; 561 } 562 increase_used(word_size * HeapWordSize); 563 if (commits != 0) { 564 log_debug(gc, ergo, heap)("Attempt heap expansion (allocate archive regions). Total size: " SIZE_FORMAT "B", 565 HeapRegion::GrainWords * HeapWordSize * commits); 566 567 } 568 569 // Mark each G1 region touched by the range as old, add it to 570 // the old set, and set top. 571 auto set_region_to_old = [&] (HeapRegion* r, bool is_last) { 572 assert(r->is_empty(), "Region already in use (%u)", r->hrm_index()); 573 574 HeapWord* top = is_last ? last_address + 1 : r->end(); 575 r->set_top(top); 576 577 r->set_old(); 578 _hr_printer.alloc(r); 579 _old_set.add(r); 580 }; 581 582 iterate_regions_in_range(range, set_region_to_old); 583 return true; 584 } 585 586 void G1CollectedHeap::populate_archive_regions_bot_part(MemRegion range) { 587 assert(!is_init_completed(), "Expect to be called at JVM init time"); 588 589 iterate_regions_in_range(range, 590 [&] (HeapRegion* r, bool is_last) { 591 r->update_bot(); 592 }); 593 } 594 595 void G1CollectedHeap::dealloc_archive_regions(MemRegion range) { 596 assert(!is_init_completed(), "Expect to be called at JVM init time"); 597 MemRegion reserved = _hrm.reserved(); 598 size_t size_used = 0; 599 uint shrink_count = 0; 600 601 // Free the G1 regions that are within the specified range. 602 MutexLocker x(Heap_lock); 603 HeapWord* start_address = range.start(); 604 HeapWord* last_address = range.last(); 605 606 assert(reserved.contains(start_address) && reserved.contains(last_address), 607 "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]", 608 p2i(start_address), p2i(last_address)); 609 size_used += range.byte_size(); 610 611 // Free, empty and uncommit regions with CDS archive content. 612 auto dealloc_archive_region = [&] (HeapRegion* r, bool is_last) { 613 guarantee(r->is_old(), "Expected old region at index %u", r->hrm_index()); 614 _old_set.remove(r); 615 r->set_free(); 616 r->set_top(r->bottom()); 617 _hrm.shrink_at(r->hrm_index(), 1); 618 shrink_count++; 619 }; 620 621 iterate_regions_in_range(range, dealloc_archive_region); 622 623 if (shrink_count != 0) { 624 log_debug(gc, ergo, heap)("Attempt heap shrinking (CDS archive regions). Total size: " SIZE_FORMAT "B", 625 HeapRegion::GrainWords * HeapWordSize * shrink_count); 626 // Explicit uncommit. 627 uncommit_regions(shrink_count); 628 } 629 decrease_used(size_used); 630 } 631 632 inline HeapWord* G1CollectedHeap::attempt_allocation(size_t min_word_size, 633 size_t desired_word_size, 634 size_t* actual_word_size) { 635 assert_heap_not_locked_and_not_at_safepoint(); 636 assert(!is_humongous(desired_word_size), "attempt_allocation() should not " 637 "be called for humongous allocation requests"); 638 639 HeapWord* result = _allocator->attempt_allocation(min_word_size, desired_word_size, actual_word_size); 640 641 if (result == nullptr) { 642 *actual_word_size = desired_word_size; 643 result = attempt_allocation_slow(desired_word_size); 644 } 645 646 assert_heap_not_locked(); 647 if (result != nullptr) { 648 assert(*actual_word_size != 0, "Actual size must have been set here"); 649 dirty_young_block(result, *actual_word_size); 650 } else { 651 *actual_word_size = 0; 652 } 653 654 return result; 655 } 656 657 HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size) { 658 ResourceMark rm; // For retrieving the thread names in log messages. 659 660 // The structure of this method has a lot of similarities to 661 // attempt_allocation_slow(). The reason these two were not merged 662 // into a single one is that such a method would require several "if 663 // allocation is not humongous do this, otherwise do that" 664 // conditional paths which would obscure its flow. In fact, an early 665 // version of this code did use a unified method which was harder to 666 // follow and, as a result, it had subtle bugs that were hard to 667 // track down. So keeping these two methods separate allows each to 668 // be more readable. It will be good to keep these two in sync as 669 // much as possible. 670 671 assert_heap_not_locked_and_not_at_safepoint(); 672 assert(is_humongous(word_size), "attempt_allocation_humongous() " 673 "should only be called for humongous allocations"); 674 675 // Humongous objects can exhaust the heap quickly, so we should check if we 676 // need to start a marking cycle at each humongous object allocation. We do 677 // the check before we do the actual allocation. The reason for doing it 678 // before the allocation is that we avoid having to keep track of the newly 679 // allocated memory while we do a GC. 680 if (policy()->need_to_start_conc_mark("concurrent humongous allocation", 681 word_size)) { 682 collect(GCCause::_g1_humongous_allocation); 683 } 684 685 // We will loop until a) we manage to successfully perform the 686 // allocation or b) we successfully schedule a collection which 687 // fails to perform the allocation. b) is the only case when we'll 688 // return null. 689 HeapWord* result = nullptr; 690 for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) { 691 bool should_try_gc; 692 uint gc_count_before; 693 694 695 { 696 MutexLocker x(Heap_lock); 697 698 size_t size_in_regions = humongous_obj_size_in_regions(word_size); 699 // Given that humongous objects are not allocated in young 700 // regions, we'll first try to do the allocation without doing a 701 // collection hoping that there's enough space in the heap. 702 result = humongous_obj_allocate(word_size); 703 if (result != nullptr) { 704 policy()->old_gen_alloc_tracker()-> 705 add_allocated_humongous_bytes_since_last_gc(size_in_regions * HeapRegion::GrainBytes); 706 return result; 707 } 708 709 // Only try a GC if the GCLocker does not signal the need for a GC. Wait until 710 // the GCLocker initiated GC has been performed and then retry. This includes 711 // the case when the GC Locker is not active but has not been performed. 712 should_try_gc = !GCLocker::needs_gc(); 713 // Read the GC count while still holding the Heap_lock. 714 gc_count_before = total_collections(); 715 } 716 717 if (should_try_gc) { 718 bool succeeded; 719 result = do_collection_pause(word_size, gc_count_before, &succeeded, GCCause::_g1_humongous_allocation); 720 if (result != nullptr) { 721 assert(succeeded, "only way to get back a non-null result"); 722 log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT, 723 Thread::current()->name(), p2i(result)); 724 size_t size_in_regions = humongous_obj_size_in_regions(word_size); 725 policy()->old_gen_alloc_tracker()-> 726 record_collection_pause_humongous_allocation(size_in_regions * HeapRegion::GrainBytes); 727 return result; 728 } 729 730 if (succeeded) { 731 // We successfully scheduled a collection which failed to allocate. No 732 // point in trying to allocate further. We'll just return null. 733 log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate " 734 SIZE_FORMAT " words", Thread::current()->name(), word_size); 735 return nullptr; 736 } 737 log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT "", 738 Thread::current()->name(), word_size); 739 } else { 740 // Failed to schedule a collection. 741 if (gclocker_retry_count > GCLockerRetryAllocationCount) { 742 log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating " 743 SIZE_FORMAT " words", Thread::current()->name(), word_size); 744 return nullptr; 745 } 746 log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name()); 747 // The GCLocker is either active or the GCLocker initiated 748 // GC has not yet been performed. Stall until it is and 749 // then retry the allocation. 750 GCLocker::stall_until_clear(); 751 gclocker_retry_count += 1; 752 } 753 754 755 // We can reach here if we were unsuccessful in scheduling a 756 // collection (because another thread beat us to it) or if we were 757 // stalled due to the GC locker. In either can we should retry the 758 // allocation attempt in case another thread successfully 759 // performed a collection and reclaimed enough space. 760 // Humongous object allocation always needs a lock, so we wait for the retry 761 // in the next iteration of the loop, unlike for the regular iteration case. 762 // Give a warning if we seem to be looping forever. 763 764 if ((QueuedAllocationWarningCount > 0) && 765 (try_count % QueuedAllocationWarningCount == 0)) { 766 log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words", 767 Thread::current()->name(), try_count, word_size); 768 } 769 } 770 771 ShouldNotReachHere(); 772 return nullptr; 773 } 774 775 HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size, 776 bool expect_null_mutator_alloc_region) { 777 assert_at_safepoint_on_vm_thread(); 778 assert(!_allocator->has_mutator_alloc_region() || !expect_null_mutator_alloc_region, 779 "the current alloc region was unexpectedly found to be non-null"); 780 781 if (!is_humongous(word_size)) { 782 return _allocator->attempt_allocation_locked(word_size); 783 } else { 784 HeapWord* result = humongous_obj_allocate(word_size); 785 if (result != nullptr && policy()->need_to_start_conc_mark("STW humongous allocation")) { 786 collector_state()->set_initiate_conc_mark_if_possible(true); 787 } 788 return result; 789 } 790 791 ShouldNotReachHere(); 792 } 793 794 class PostCompactionPrinterClosure: public HeapRegionClosure { 795 private: 796 G1HRPrinter* _hr_printer; 797 public: 798 bool do_heap_region(HeapRegion* hr) { 799 assert(!hr->is_young(), "not expecting to find young regions"); 800 _hr_printer->post_compaction(hr); 801 return false; 802 } 803 804 PostCompactionPrinterClosure(G1HRPrinter* hr_printer) 805 : _hr_printer(hr_printer) { } 806 }; 807 808 void G1CollectedHeap::print_heap_after_full_collection() { 809 // Post collection region logging. 810 // We should do this after we potentially resize the heap so 811 // that all the COMMIT / UNCOMMIT events are generated before 812 // the compaction events. 813 if (_hr_printer.is_active()) { 814 PostCompactionPrinterClosure cl(hr_printer()); 815 heap_region_iterate(&cl); 816 } 817 } 818 819 bool G1CollectedHeap::abort_concurrent_cycle() { 820 // Disable discovery and empty the discovered lists 821 // for the CM ref processor. 822 _ref_processor_cm->disable_discovery(); 823 _ref_processor_cm->abandon_partial_discovery(); 824 _ref_processor_cm->verify_no_references_recorded(); 825 826 // Abandon current iterations of concurrent marking and concurrent 827 // refinement, if any are in progress. 828 return concurrent_mark()->concurrent_cycle_abort(); 829 } 830 831 void G1CollectedHeap::prepare_heap_for_full_collection() { 832 // Make sure we'll choose a new allocation region afterwards. 833 _allocator->release_mutator_alloc_regions(); 834 _allocator->abandon_gc_alloc_regions(); 835 836 // We may have added regions to the current incremental collection 837 // set between the last GC or pause and now. We need to clear the 838 // incremental collection set and then start rebuilding it afresh 839 // after this full GC. 840 abandon_collection_set(collection_set()); 841 842 _hrm.remove_all_free_regions(); 843 } 844 845 void G1CollectedHeap::verify_before_full_collection() { 846 assert_used_and_recalculate_used_equal(this); 847 if (!VerifyBeforeGC) { 848 return; 849 } 850 if (!G1HeapVerifier::should_verify(G1HeapVerifier::G1VerifyFull)) { 851 return; 852 } 853 _verifier->verify_region_sets_optional(); 854 _verifier->verify_before_gc(); 855 _verifier->verify_bitmap_clear(true /* above_tams_only */); 856 } 857 858 void G1CollectedHeap::prepare_for_mutator_after_full_collection() { 859 // Prepare heap for normal collections. 860 assert(num_free_regions() == 0, "we should not have added any free regions"); 861 rebuild_region_sets(false /* free_list_only */); 862 abort_refinement(); 863 resize_heap_if_necessary(); 864 uncommit_regions_if_necessary(); 865 866 // Rebuild the code root lists for each region 867 rebuild_code_roots(); 868 869 start_new_collection_set(); 870 _allocator->init_mutator_alloc_regions(); 871 872 // Post collection state updates. 873 MetaspaceGC::compute_new_size(); 874 } 875 876 void G1CollectedHeap::abort_refinement() { 877 // Discard all remembered set updates and reset refinement statistics. 878 G1BarrierSet::dirty_card_queue_set().abandon_logs_and_stats(); 879 assert(G1BarrierSet::dirty_card_queue_set().num_cards() == 0, 880 "DCQS should be empty"); 881 concurrent_refine()->get_and_reset_refinement_stats(); 882 } 883 884 void G1CollectedHeap::verify_after_full_collection() { 885 if (!VerifyAfterGC) { 886 return; 887 } 888 if (!G1HeapVerifier::should_verify(G1HeapVerifier::G1VerifyFull)) { 889 return; 890 } 891 _hrm.verify_optional(); 892 _verifier->verify_region_sets_optional(); 893 _verifier->verify_after_gc(); 894 _verifier->verify_bitmap_clear(false /* above_tams_only */); 895 896 // At this point there should be no regions in the 897 // entire heap tagged as young. 898 assert(check_young_list_empty(), "young list should be empty at this point"); 899 900 // Note: since we've just done a full GC, concurrent 901 // marking is no longer active. Therefore we need not 902 // re-enable reference discovery for the CM ref processor. 903 // That will be done at the start of the next marking cycle. 904 // We also know that the STW processor should no longer 905 // discover any new references. 906 assert(!_ref_processor_stw->discovery_enabled(), "Postcondition"); 907 assert(!_ref_processor_cm->discovery_enabled(), "Postcondition"); 908 _ref_processor_stw->verify_no_references_recorded(); 909 _ref_processor_cm->verify_no_references_recorded(); 910 } 911 912 bool G1CollectedHeap::do_full_collection(bool clear_all_soft_refs, 913 bool do_maximal_compaction) { 914 assert_at_safepoint_on_vm_thread(); 915 916 if (GCLocker::check_active_before_gc()) { 917 // Full GC was not completed. 918 return false; 919 } 920 921 const bool do_clear_all_soft_refs = clear_all_soft_refs || 922 soft_ref_policy()->should_clear_all_soft_refs(); 923 924 G1FullGCMark gc_mark; 925 GCTraceTime(Info, gc) tm("Pause Full", nullptr, gc_cause(), true); 926 G1FullCollector collector(this, do_clear_all_soft_refs, do_maximal_compaction, gc_mark.tracer()); 927 928 collector.prepare_collection(); 929 collector.collect(); 930 collector.complete_collection(); 931 932 // Full collection was successfully completed. 933 return true; 934 } 935 936 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) { 937 // Currently, there is no facility in the do_full_collection(bool) API to notify 938 // the caller that the collection did not succeed (e.g., because it was locked 939 // out by the GC locker). So, right now, we'll ignore the return value. 940 941 do_full_collection(clear_all_soft_refs, 942 false /* do_maximal_compaction */); 943 } 944 945 bool G1CollectedHeap::upgrade_to_full_collection() { 946 GCCauseSetter compaction(this, GCCause::_g1_compaction_pause); 947 log_info(gc, ergo)("Attempting full compaction clearing soft references"); 948 bool success = do_full_collection(true /* clear_all_soft_refs */, 949 false /* do_maximal_compaction */); 950 // do_full_collection only fails if blocked by GC locker and that can't 951 // be the case here since we only call this when already completed one gc. 952 assert(success, "invariant"); 953 return success; 954 } 955 956 void G1CollectedHeap::resize_heap_if_necessary() { 957 assert_at_safepoint_on_vm_thread(); 958 959 bool should_expand; 960 size_t resize_amount = _heap_sizing_policy->full_collection_resize_amount(should_expand); 961 962 if (resize_amount == 0) { 963 return; 964 } else if (should_expand) { 965 expand(resize_amount, _workers); 966 } else { 967 shrink(resize_amount); 968 } 969 } 970 971 HeapWord* G1CollectedHeap::satisfy_failed_allocation_helper(size_t word_size, 972 bool do_gc, 973 bool maximal_compaction, 974 bool expect_null_mutator_alloc_region, 975 bool* gc_succeeded) { 976 *gc_succeeded = true; 977 // Let's attempt the allocation first. 978 HeapWord* result = 979 attempt_allocation_at_safepoint(word_size, 980 expect_null_mutator_alloc_region); 981 if (result != nullptr) { 982 return result; 983 } 984 985 // In a G1 heap, we're supposed to keep allocation from failing by 986 // incremental pauses. Therefore, at least for now, we'll favor 987 // expansion over collection. (This might change in the future if we can 988 // do something smarter than full collection to satisfy a failed alloc.) 989 result = expand_and_allocate(word_size); 990 if (result != nullptr) { 991 return result; 992 } 993 994 if (do_gc) { 995 GCCauseSetter compaction(this, GCCause::_g1_compaction_pause); 996 // Expansion didn't work, we'll try to do a Full GC. 997 // If maximal_compaction is set we clear all soft references and don't 998 // allow any dead wood to be left on the heap. 999 if (maximal_compaction) { 1000 log_info(gc, ergo)("Attempting maximal full compaction clearing soft references"); 1001 } else { 1002 log_info(gc, ergo)("Attempting full compaction"); 1003 } 1004 *gc_succeeded = do_full_collection(maximal_compaction /* clear_all_soft_refs */ , 1005 maximal_compaction /* do_maximal_compaction */); 1006 } 1007 1008 return nullptr; 1009 } 1010 1011 HeapWord* G1CollectedHeap::satisfy_failed_allocation(size_t word_size, 1012 bool* succeeded) { 1013 assert_at_safepoint_on_vm_thread(); 1014 1015 // Attempts to allocate followed by Full GC. 1016 HeapWord* result = 1017 satisfy_failed_allocation_helper(word_size, 1018 true, /* do_gc */ 1019 false, /* maximum_collection */ 1020 false, /* expect_null_mutator_alloc_region */ 1021 succeeded); 1022 1023 if (result != nullptr || !*succeeded) { 1024 return result; 1025 } 1026 1027 // Attempts to allocate followed by Full GC that will collect all soft references. 1028 result = satisfy_failed_allocation_helper(word_size, 1029 true, /* do_gc */ 1030 true, /* maximum_collection */ 1031 true, /* expect_null_mutator_alloc_region */ 1032 succeeded); 1033 1034 if (result != nullptr || !*succeeded) { 1035 return result; 1036 } 1037 1038 // Attempts to allocate, no GC 1039 result = satisfy_failed_allocation_helper(word_size, 1040 false, /* do_gc */ 1041 false, /* maximum_collection */ 1042 true, /* expect_null_mutator_alloc_region */ 1043 succeeded); 1044 1045 if (result != nullptr) { 1046 return result; 1047 } 1048 1049 assert(!soft_ref_policy()->should_clear_all_soft_refs(), 1050 "Flag should have been handled and cleared prior to this point"); 1051 1052 // What else? We might try synchronous finalization later. If the total 1053 // space available is large enough for the allocation, then a more 1054 // complete compaction phase than we've tried so far might be 1055 // appropriate. 1056 return nullptr; 1057 } 1058 1059 // Attempting to expand the heap sufficiently 1060 // to support an allocation of the given "word_size". If 1061 // successful, perform the allocation and return the address of the 1062 // allocated block, or else null. 1063 1064 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) { 1065 assert_at_safepoint_on_vm_thread(); 1066 1067 _verifier->verify_region_sets_optional(); 1068 1069 size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes); 1070 log_debug(gc, ergo, heap)("Attempt heap expansion (allocation request failed). Allocation request: " SIZE_FORMAT "B", 1071 word_size * HeapWordSize); 1072 1073 1074 if (expand(expand_bytes, _workers)) { 1075 _hrm.verify_optional(); 1076 _verifier->verify_region_sets_optional(); 1077 return attempt_allocation_at_safepoint(word_size, 1078 false /* expect_null_mutator_alloc_region */); 1079 } 1080 return nullptr; 1081 } 1082 1083 bool G1CollectedHeap::expand(size_t expand_bytes, WorkerThreads* pretouch_workers, double* expand_time_ms) { 1084 size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes); 1085 aligned_expand_bytes = align_up(aligned_expand_bytes, 1086 HeapRegion::GrainBytes); 1087 1088 log_debug(gc, ergo, heap)("Expand the heap. requested expansion amount: " SIZE_FORMAT "B expansion amount: " SIZE_FORMAT "B", 1089 expand_bytes, aligned_expand_bytes); 1090 1091 if (is_maximal_no_gc()) { 1092 log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)"); 1093 return false; 1094 } 1095 1096 double expand_heap_start_time_sec = os::elapsedTime(); 1097 uint regions_to_expand = (uint)(aligned_expand_bytes / HeapRegion::GrainBytes); 1098 assert(regions_to_expand > 0, "Must expand by at least one region"); 1099 1100 uint expanded_by = _hrm.expand_by(regions_to_expand, pretouch_workers); 1101 if (expand_time_ms != nullptr) { 1102 *expand_time_ms = (os::elapsedTime() - expand_heap_start_time_sec) * MILLIUNITS; 1103 } 1104 1105 assert(expanded_by > 0, "must have failed during commit."); 1106 1107 size_t actual_expand_bytes = expanded_by * HeapRegion::GrainBytes; 1108 assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition"); 1109 policy()->record_new_heap_size(num_regions()); 1110 1111 return true; 1112 } 1113 1114 bool G1CollectedHeap::expand_single_region(uint node_index) { 1115 uint expanded_by = _hrm.expand_on_preferred_node(node_index); 1116 1117 if (expanded_by == 0) { 1118 assert(is_maximal_no_gc(), "Should be no regions left, available: %u", _hrm.available()); 1119 log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)"); 1120 return false; 1121 } 1122 1123 policy()->record_new_heap_size(num_regions()); 1124 return true; 1125 } 1126 1127 void G1CollectedHeap::shrink_helper(size_t shrink_bytes) { 1128 size_t aligned_shrink_bytes = 1129 ReservedSpace::page_align_size_down(shrink_bytes); 1130 aligned_shrink_bytes = align_down(aligned_shrink_bytes, 1131 HeapRegion::GrainBytes); 1132 uint num_regions_to_remove = (uint)(shrink_bytes / HeapRegion::GrainBytes); 1133 1134 uint num_regions_removed = _hrm.shrink_by(num_regions_to_remove); 1135 size_t shrunk_bytes = num_regions_removed * HeapRegion::GrainBytes; 1136 1137 log_debug(gc, ergo, heap)("Shrink the heap. requested shrinking amount: " SIZE_FORMAT "B aligned shrinking amount: " SIZE_FORMAT "B actual amount shrunk: " SIZE_FORMAT "B", 1138 shrink_bytes, aligned_shrink_bytes, shrunk_bytes); 1139 if (num_regions_removed > 0) { 1140 log_debug(gc, heap)("Uncommittable regions after shrink: %u", num_regions_removed); 1141 policy()->record_new_heap_size(num_regions()); 1142 } else { 1143 log_debug(gc, ergo, heap)("Did not shrink the heap (heap shrinking operation failed)"); 1144 } 1145 } 1146 1147 void G1CollectedHeap::shrink(size_t shrink_bytes) { 1148 _verifier->verify_region_sets_optional(); 1149 1150 // We should only reach here at the end of a Full GC or during Remark which 1151 // means we should not not be holding to any GC alloc regions. The method 1152 // below will make sure of that and do any remaining clean up. 1153 _allocator->abandon_gc_alloc_regions(); 1154 1155 // Instead of tearing down / rebuilding the free lists here, we 1156 // could instead use the remove_all_pending() method on free_list to 1157 // remove only the ones that we need to remove. 1158 _hrm.remove_all_free_regions(); 1159 shrink_helper(shrink_bytes); 1160 rebuild_region_sets(true /* free_list_only */); 1161 1162 _hrm.verify_optional(); 1163 _verifier->verify_region_sets_optional(); 1164 } 1165 1166 class OldRegionSetChecker : public HeapRegionSetChecker { 1167 public: 1168 void check_mt_safety() { 1169 // Master Old Set MT safety protocol: 1170 // (a) If we're at a safepoint, operations on the master old set 1171 // should be invoked: 1172 // - by the VM thread (which will serialize them), or 1173 // - by the GC workers while holding the FreeList_lock, if we're 1174 // at a safepoint for an evacuation pause (this lock is taken 1175 // anyway when an GC alloc region is retired so that a new one 1176 // is allocated from the free list), or 1177 // - by the GC workers while holding the OldSets_lock, if we're at a 1178 // safepoint for a cleanup pause. 1179 // (b) If we're not at a safepoint, operations on the master old set 1180 // should be invoked while holding the Heap_lock. 1181 1182 if (SafepointSynchronize::is_at_safepoint()) { 1183 guarantee(Thread::current()->is_VM_thread() || 1184 FreeList_lock->owned_by_self() || OldSets_lock->owned_by_self(), 1185 "master old set MT safety protocol at a safepoint"); 1186 } else { 1187 guarantee(Heap_lock->owned_by_self(), "master old set MT safety protocol outside a safepoint"); 1188 } 1189 } 1190 bool is_correct_type(HeapRegion* hr) { return hr->is_old(); } 1191 const char* get_description() { return "Old Regions"; } 1192 }; 1193 1194 class HumongousRegionSetChecker : public HeapRegionSetChecker { 1195 public: 1196 void check_mt_safety() { 1197 // Humongous Set MT safety protocol: 1198 // (a) If we're at a safepoint, operations on the master humongous 1199 // set should be invoked by either the VM thread (which will 1200 // serialize them) or by the GC workers while holding the 1201 // OldSets_lock. 1202 // (b) If we're not at a safepoint, operations on the master 1203 // humongous set should be invoked while holding the Heap_lock. 1204 1205 if (SafepointSynchronize::is_at_safepoint()) { 1206 guarantee(Thread::current()->is_VM_thread() || 1207 OldSets_lock->owned_by_self(), 1208 "master humongous set MT safety protocol at a safepoint"); 1209 } else { 1210 guarantee(Heap_lock->owned_by_self(), 1211 "master humongous set MT safety protocol outside a safepoint"); 1212 } 1213 } 1214 bool is_correct_type(HeapRegion* hr) { return hr->is_humongous(); } 1215 const char* get_description() { return "Humongous Regions"; } 1216 }; 1217 1218 G1CollectedHeap::G1CollectedHeap() : 1219 CollectedHeap(), 1220 _service_thread(nullptr), 1221 _periodic_gc_task(nullptr), 1222 _free_arena_memory_task(nullptr), 1223 _workers(nullptr), 1224 _card_table(nullptr), 1225 _collection_pause_end(Ticks::now()), 1226 _soft_ref_policy(), 1227 _old_set("Old Region Set", new OldRegionSetChecker()), 1228 _humongous_set("Humongous Region Set", new HumongousRegionSetChecker()), 1229 _bot(nullptr), 1230 _listener(), 1231 _numa(G1NUMA::create()), 1232 _hrm(), 1233 _allocator(nullptr), 1234 _evac_failure_injector(), 1235 _verifier(nullptr), 1236 _summary_bytes_used(0), 1237 _bytes_used_during_gc(0), 1238 _survivor_evac_stats("Young", YoungPLABSize, PLABWeight), 1239 _old_evac_stats("Old", OldPLABSize, PLABWeight), 1240 _monitoring_support(nullptr), 1241 _num_humongous_objects(0), 1242 _num_humongous_reclaim_candidates(0), 1243 _hr_printer(), 1244 _collector_state(), 1245 _old_marking_cycles_started(0), 1246 _old_marking_cycles_completed(0), 1247 _eden(), 1248 _survivor(), 1249 _gc_timer_stw(new STWGCTimer()), 1250 _gc_tracer_stw(new G1NewTracer()), 1251 _policy(new G1Policy(_gc_timer_stw)), 1252 _heap_sizing_policy(nullptr), 1253 _collection_set(this, _policy), 1254 _rem_set(nullptr), 1255 _card_set_config(), 1256 _card_set_freelist_pool(G1CardSetConfiguration::num_mem_object_types()), 1257 _cm(nullptr), 1258 _cm_thread(nullptr), 1259 _cr(nullptr), 1260 _task_queues(nullptr), 1261 _ref_processor_stw(nullptr), 1262 _is_alive_closure_stw(this), 1263 _is_subject_to_discovery_stw(this), 1264 _ref_processor_cm(nullptr), 1265 _is_alive_closure_cm(this), 1266 _is_subject_to_discovery_cm(this), 1267 _region_attr() { 1268 1269 _verifier = new G1HeapVerifier(this); 1270 1271 _allocator = new G1Allocator(this); 1272 1273 _heap_sizing_policy = G1HeapSizingPolicy::create(this, _policy->analytics()); 1274 1275 _humongous_object_threshold_in_words = humongous_threshold_for(HeapRegion::GrainWords); 1276 1277 // Override the default _filler_array_max_size so that no humongous filler 1278 // objects are created. 1279 _filler_array_max_size = _humongous_object_threshold_in_words; 1280 1281 // Override the default _stack_chunk_max_size so that no humongous stack chunks are created 1282 _stack_chunk_max_size = _humongous_object_threshold_in_words; 1283 1284 uint n_queues = ParallelGCThreads; 1285 _task_queues = new G1ScannerTasksQueueSet(n_queues); 1286 1287 for (uint i = 0; i < n_queues; i++) { 1288 G1ScannerTasksQueue* q = new G1ScannerTasksQueue(); 1289 _task_queues->register_queue(i, q); 1290 } 1291 1292 _gc_tracer_stw->initialize(); 1293 1294 guarantee(_task_queues != nullptr, "task_queues allocation failure."); 1295 } 1296 1297 G1RegionToSpaceMapper* G1CollectedHeap::create_aux_memory_mapper(const char* description, 1298 size_t size, 1299 size_t translation_factor) { 1300 size_t preferred_page_size = os::page_size_for_region_unaligned(size, 1); 1301 // Allocate a new reserved space, preferring to use large pages. 1302 ReservedSpace rs(size, preferred_page_size); 1303 size_t page_size = rs.page_size(); 1304 G1RegionToSpaceMapper* result = 1305 G1RegionToSpaceMapper::create_mapper(rs, 1306 size, 1307 page_size, 1308 HeapRegion::GrainBytes, 1309 translation_factor, 1310 mtGC); 1311 1312 os::trace_page_sizes_for_requested_size(description, 1313 size, 1314 page_size, 1315 preferred_page_size, 1316 rs.base(), 1317 rs.size()); 1318 1319 return result; 1320 } 1321 1322 jint G1CollectedHeap::initialize_concurrent_refinement() { 1323 jint ecode = JNI_OK; 1324 _cr = G1ConcurrentRefine::create(policy(), &ecode); 1325 return ecode; 1326 } 1327 1328 jint G1CollectedHeap::initialize_service_thread() { 1329 _service_thread = new G1ServiceThread(); 1330 if (_service_thread->osthread() == nullptr) { 1331 vm_shutdown_during_initialization("Could not create G1ServiceThread"); 1332 return JNI_ENOMEM; 1333 } 1334 return JNI_OK; 1335 } 1336 1337 jint G1CollectedHeap::initialize() { 1338 1339 // Necessary to satisfy locking discipline assertions. 1340 1341 MutexLocker x(Heap_lock); 1342 1343 // While there are no constraints in the GC code that HeapWordSize 1344 // be any particular value, there are multiple other areas in the 1345 // system which believe this to be true (e.g. oop->object_size in some 1346 // cases incorrectly returns the size in wordSize units rather than 1347 // HeapWordSize). 1348 guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize"); 1349 1350 size_t init_byte_size = InitialHeapSize; 1351 size_t reserved_byte_size = G1Arguments::heap_reserved_size_bytes(); 1352 1353 // Ensure that the sizes are properly aligned. 1354 Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap"); 1355 Universe::check_alignment(reserved_byte_size, HeapRegion::GrainBytes, "g1 heap"); 1356 Universe::check_alignment(reserved_byte_size, HeapAlignment, "g1 heap"); 1357 1358 // Reserve the maximum. 1359 1360 // When compressed oops are enabled, the preferred heap base 1361 // is calculated by subtracting the requested size from the 1362 // 32Gb boundary and using the result as the base address for 1363 // heap reservation. If the requested size is not aligned to 1364 // HeapRegion::GrainBytes (i.e. the alignment that is passed 1365 // into the ReservedHeapSpace constructor) then the actual 1366 // base of the reserved heap may end up differing from the 1367 // address that was requested (i.e. the preferred heap base). 1368 // If this happens then we could end up using a non-optimal 1369 // compressed oops mode. 1370 1371 ReservedHeapSpace heap_rs = Universe::reserve_heap(reserved_byte_size, 1372 HeapAlignment); 1373 1374 initialize_reserved_region(heap_rs); 1375 1376 // Create the barrier set for the entire reserved region. 1377 G1CardTable* ct = new G1CardTable(heap_rs.region()); 1378 G1BarrierSet* bs = new G1BarrierSet(ct); 1379 bs->initialize(); 1380 assert(bs->is_a(BarrierSet::G1BarrierSet), "sanity"); 1381 BarrierSet::set_barrier_set(bs); 1382 _card_table = ct; 1383 1384 { 1385 G1SATBMarkQueueSet& satbqs = bs->satb_mark_queue_set(); 1386 satbqs.set_process_completed_buffers_threshold(G1SATBProcessCompletedThreshold); 1387 satbqs.set_buffer_enqueue_threshold_percentage(G1SATBBufferEnqueueingThresholdPercent); 1388 } 1389 1390 // Create space mappers. 1391 size_t page_size = heap_rs.page_size(); 1392 G1RegionToSpaceMapper* heap_storage = 1393 G1RegionToSpaceMapper::create_mapper(heap_rs, 1394 heap_rs.size(), 1395 page_size, 1396 HeapRegion::GrainBytes, 1397 1, 1398 mtJavaHeap); 1399 if(heap_storage == nullptr) { 1400 vm_shutdown_during_initialization("Could not initialize G1 heap"); 1401 return JNI_ERR; 1402 } 1403 1404 os::trace_page_sizes("Heap", 1405 MinHeapSize, 1406 reserved_byte_size, 1407 page_size, 1408 heap_rs.base(), 1409 heap_rs.size()); 1410 heap_storage->set_mapping_changed_listener(&_listener); 1411 1412 // Create storage for the BOT, card table and the bitmap. 1413 G1RegionToSpaceMapper* bot_storage = 1414 create_aux_memory_mapper("Block Offset Table", 1415 G1BlockOffsetTable::compute_size(heap_rs.size() / HeapWordSize), 1416 G1BlockOffsetTable::heap_map_factor()); 1417 1418 G1RegionToSpaceMapper* cardtable_storage = 1419 create_aux_memory_mapper("Card Table", 1420 G1CardTable::compute_size(heap_rs.size() / HeapWordSize), 1421 G1CardTable::heap_map_factor()); 1422 1423 size_t bitmap_size = G1CMBitMap::compute_size(heap_rs.size()); 1424 G1RegionToSpaceMapper* bitmap_storage = 1425 create_aux_memory_mapper("Mark Bitmap", bitmap_size, G1CMBitMap::heap_map_factor()); 1426 1427 _hrm.initialize(heap_storage, bitmap_storage, bot_storage, cardtable_storage); 1428 _card_table->initialize(cardtable_storage); 1429 1430 // 6843694 - ensure that the maximum region index can fit 1431 // in the remembered set structures. 1432 const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1; 1433 guarantee((max_reserved_regions() - 1) <= max_region_idx, "too many regions"); 1434 1435 // The G1FromCardCache reserves card with value 0 as "invalid", so the heap must not 1436 // start within the first card. 1437 guarantee((uintptr_t)(heap_rs.base()) >= G1CardTable::card_size(), "Java heap must not start within the first card."); 1438 G1FromCardCache::initialize(max_reserved_regions()); 1439 // Also create a G1 rem set. 1440 _rem_set = new G1RemSet(this, _card_table); 1441 _rem_set->initialize(max_reserved_regions()); 1442 1443 size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1; 1444 guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized"); 1445 guarantee(HeapRegion::CardsPerRegion < max_cards_per_region, 1446 "too many cards per region"); 1447 1448 HeapRegionRemSet::initialize(_reserved); 1449 1450 FreeRegionList::set_unrealistically_long_length(max_regions() + 1); 1451 1452 _bot = new G1BlockOffsetTable(reserved(), bot_storage); 1453 1454 { 1455 size_t granularity = HeapRegion::GrainBytes; 1456 1457 _region_attr.initialize(reserved(), granularity); 1458 } 1459 1460 _workers = new WorkerThreads("GC Thread", ParallelGCThreads); 1461 if (_workers == nullptr) { 1462 return JNI_ENOMEM; 1463 } 1464 _workers->initialize_workers(); 1465 1466 _numa->set_region_info(HeapRegion::GrainBytes, page_size); 1467 1468 // Create the G1ConcurrentMark data structure and thread. 1469 // (Must do this late, so that "max_[reserved_]regions" is defined.) 1470 _cm = new G1ConcurrentMark(this, bitmap_storage); 1471 _cm_thread = _cm->cm_thread(); 1472 1473 // Now expand into the initial heap size. 1474 if (!expand(init_byte_size, _workers)) { 1475 vm_shutdown_during_initialization("Failed to allocate initial heap."); 1476 return JNI_ENOMEM; 1477 } 1478 1479 // Perform any initialization actions delegated to the policy. 1480 policy()->init(this, &_collection_set); 1481 1482 jint ecode = initialize_concurrent_refinement(); 1483 if (ecode != JNI_OK) { 1484 return ecode; 1485 } 1486 1487 ecode = initialize_service_thread(); 1488 if (ecode != JNI_OK) { 1489 return ecode; 1490 } 1491 1492 // Create and schedule the periodic gc task on the service thread. 1493 _periodic_gc_task = new G1PeriodicGCTask("Periodic GC Task"); 1494 _service_thread->register_task(_periodic_gc_task); 1495 1496 _free_arena_memory_task = new G1MonotonicArenaFreeMemoryTask("Card Set Free Memory Task"); 1497 _service_thread->register_task(_free_arena_memory_task); 1498 1499 // Here we allocate the dummy HeapRegion that is required by the 1500 // G1AllocRegion class. 1501 HeapRegion* dummy_region = _hrm.get_dummy_region(); 1502 1503 // We'll re-use the same region whether the alloc region will 1504 // require BOT updates or not and, if it doesn't, then a non-young 1505 // region will complain that it cannot support allocations without 1506 // BOT updates. So we'll tag the dummy region as eden to avoid that. 1507 dummy_region->set_eden(); 1508 // Make sure it's full. 1509 dummy_region->set_top(dummy_region->end()); 1510 G1AllocRegion::setup(this, dummy_region); 1511 1512 _allocator->init_mutator_alloc_regions(); 1513 1514 // Do create of the monitoring and management support so that 1515 // values in the heap have been properly initialized. 1516 _monitoring_support = new G1MonitoringSupport(this); 1517 1518 _collection_set.initialize(max_reserved_regions()); 1519 1520 evac_failure_injector()->reset(); 1521 1522 G1InitLogger::print(); 1523 1524 return JNI_OK; 1525 } 1526 1527 bool G1CollectedHeap::concurrent_mark_is_terminating() const { 1528 return _cm_thread->should_terminate(); 1529 } 1530 1531 void G1CollectedHeap::stop() { 1532 // Stop all concurrent threads. We do this to make sure these threads 1533 // do not continue to execute and access resources (e.g. logging) 1534 // that are destroyed during shutdown. 1535 _cr->stop(); 1536 _service_thread->stop(); 1537 _cm_thread->stop(); 1538 } 1539 1540 void G1CollectedHeap::safepoint_synchronize_begin() { 1541 SuspendibleThreadSet::synchronize(); 1542 } 1543 1544 void G1CollectedHeap::safepoint_synchronize_end() { 1545 SuspendibleThreadSet::desynchronize(); 1546 } 1547 1548 void G1CollectedHeap::post_initialize() { 1549 CollectedHeap::post_initialize(); 1550 ref_processing_init(); 1551 } 1552 1553 void G1CollectedHeap::ref_processing_init() { 1554 // Reference processing in G1 currently works as follows: 1555 // 1556 // * There are two reference processor instances. One is 1557 // used to record and process discovered references 1558 // during concurrent marking; the other is used to 1559 // record and process references during STW pauses 1560 // (both full and incremental). 1561 // * Both ref processors need to 'span' the entire heap as 1562 // the regions in the collection set may be dotted around. 1563 // 1564 // * For the concurrent marking ref processor: 1565 // * Reference discovery is enabled at concurrent start. 1566 // * Reference discovery is disabled and the discovered 1567 // references processed etc during remarking. 1568 // * Reference discovery is MT (see below). 1569 // * Reference discovery requires a barrier (see below). 1570 // * Reference processing may or may not be MT 1571 // (depending on the value of ParallelRefProcEnabled 1572 // and ParallelGCThreads). 1573 // * A full GC disables reference discovery by the CM 1574 // ref processor and abandons any entries on it's 1575 // discovered lists. 1576 // 1577 // * For the STW processor: 1578 // * Non MT discovery is enabled at the start of a full GC. 1579 // * Processing and enqueueing during a full GC is non-MT. 1580 // * During a full GC, references are processed after marking. 1581 // 1582 // * Discovery (may or may not be MT) is enabled at the start 1583 // of an incremental evacuation pause. 1584 // * References are processed near the end of a STW evacuation pause. 1585 // * For both types of GC: 1586 // * Discovery is atomic - i.e. not concurrent. 1587 // * Reference discovery will not need a barrier. 1588 1589 // Concurrent Mark ref processor 1590 _ref_processor_cm = 1591 new ReferenceProcessor(&_is_subject_to_discovery_cm, 1592 ParallelGCThreads, // degree of mt processing 1593 // We discover with the gc worker threads during Remark, so both 1594 // thread counts must be considered for discovery. 1595 MAX2(ParallelGCThreads, ConcGCThreads), // degree of mt discovery 1596 true, // Reference discovery is concurrent 1597 &_is_alive_closure_cm); // is alive closure 1598 1599 // STW ref processor 1600 _ref_processor_stw = 1601 new ReferenceProcessor(&_is_subject_to_discovery_stw, 1602 ParallelGCThreads, // degree of mt processing 1603 ParallelGCThreads, // degree of mt discovery 1604 false, // Reference discovery is not concurrent 1605 &_is_alive_closure_stw); // is alive closure 1606 } 1607 1608 SoftRefPolicy* G1CollectedHeap::soft_ref_policy() { 1609 return &_soft_ref_policy; 1610 } 1611 1612 size_t G1CollectedHeap::capacity() const { 1613 return _hrm.length() * HeapRegion::GrainBytes; 1614 } 1615 1616 size_t G1CollectedHeap::unused_committed_regions_in_bytes() const { 1617 return _hrm.total_free_bytes(); 1618 } 1619 1620 // Computes the sum of the storage used by the various regions. 1621 size_t G1CollectedHeap::used() const { 1622 size_t result = _summary_bytes_used + _allocator->used_in_alloc_regions(); 1623 return result; 1624 } 1625 1626 size_t G1CollectedHeap::used_unlocked() const { 1627 return _summary_bytes_used; 1628 } 1629 1630 class SumUsedClosure: public HeapRegionClosure { 1631 size_t _used; 1632 public: 1633 SumUsedClosure() : _used(0) {} 1634 bool do_heap_region(HeapRegion* r) { 1635 _used += r->used(); 1636 return false; 1637 } 1638 size_t result() { return _used; } 1639 }; 1640 1641 size_t G1CollectedHeap::recalculate_used() const { 1642 SumUsedClosure blk; 1643 heap_region_iterate(&blk); 1644 return blk.result(); 1645 } 1646 1647 bool G1CollectedHeap::is_user_requested_concurrent_full_gc(GCCause::Cause cause) { 1648 return GCCause::is_user_requested_gc(cause) && ExplicitGCInvokesConcurrent; 1649 } 1650 1651 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) { 1652 switch (cause) { 1653 case GCCause::_g1_humongous_allocation: return true; 1654 case GCCause::_g1_periodic_collection: return G1PeriodicGCInvokesConcurrent; 1655 case GCCause::_wb_breakpoint: return true; 1656 case GCCause::_codecache_GC_aggressive: return true; 1657 case GCCause::_codecache_GC_threshold: return true; 1658 default: return is_user_requested_concurrent_full_gc(cause); 1659 } 1660 } 1661 1662 void G1CollectedHeap::increment_old_marking_cycles_started() { 1663 assert(_old_marking_cycles_started == _old_marking_cycles_completed || 1664 _old_marking_cycles_started == _old_marking_cycles_completed + 1, 1665 "Wrong marking cycle count (started: %d, completed: %d)", 1666 _old_marking_cycles_started, _old_marking_cycles_completed); 1667 1668 _old_marking_cycles_started++; 1669 } 1670 1671 void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent, 1672 bool whole_heap_examined) { 1673 MonitorLocker ml(G1OldGCCount_lock, Mutex::_no_safepoint_check_flag); 1674 1675 // We assume that if concurrent == true, then the caller is a 1676 // concurrent thread that was joined the Suspendible Thread 1677 // Set. If there's ever a cheap way to check this, we should add an 1678 // assert here. 1679 1680 // Given that this method is called at the end of a Full GC or of a 1681 // concurrent cycle, and those can be nested (i.e., a Full GC can 1682 // interrupt a concurrent cycle), the number of full collections 1683 // completed should be either one (in the case where there was no 1684 // nesting) or two (when a Full GC interrupted a concurrent cycle) 1685 // behind the number of full collections started. 1686 1687 // This is the case for the inner caller, i.e. a Full GC. 1688 assert(concurrent || 1689 (_old_marking_cycles_started == _old_marking_cycles_completed + 1) || 1690 (_old_marking_cycles_started == _old_marking_cycles_completed + 2), 1691 "for inner caller (Full GC): _old_marking_cycles_started = %u " 1692 "is inconsistent with _old_marking_cycles_completed = %u", 1693 _old_marking_cycles_started, _old_marking_cycles_completed); 1694 1695 // This is the case for the outer caller, i.e. the concurrent cycle. 1696 assert(!concurrent || 1697 (_old_marking_cycles_started == _old_marking_cycles_completed + 1), 1698 "for outer caller (concurrent cycle): " 1699 "_old_marking_cycles_started = %u " 1700 "is inconsistent with _old_marking_cycles_completed = %u", 1701 _old_marking_cycles_started, _old_marking_cycles_completed); 1702 1703 _old_marking_cycles_completed += 1; 1704 if (whole_heap_examined) { 1705 // Signal that we have completed a visit to all live objects. 1706 record_whole_heap_examined_timestamp(); 1707 } 1708 1709 // We need to clear the "in_progress" flag in the CM thread before 1710 // we wake up any waiters (especially when ExplicitInvokesConcurrent 1711 // is set) so that if a waiter requests another System.gc() it doesn't 1712 // incorrectly see that a marking cycle is still in progress. 1713 if (concurrent) { 1714 _cm_thread->set_idle(); 1715 } 1716 1717 // Notify threads waiting in System.gc() (with ExplicitGCInvokesConcurrent) 1718 // for a full GC to finish that their wait is over. 1719 ml.notify_all(); 1720 } 1721 1722 // Helper for collect(). 1723 static G1GCCounters collection_counters(G1CollectedHeap* g1h) { 1724 MutexLocker ml(Heap_lock); 1725 return G1GCCounters(g1h); 1726 } 1727 1728 void G1CollectedHeap::collect(GCCause::Cause cause) { 1729 try_collect(cause, collection_counters(this)); 1730 } 1731 1732 // Return true if (x < y) with allowance for wraparound. 1733 static bool gc_counter_less_than(uint x, uint y) { 1734 return (x - y) > (UINT_MAX/2); 1735 } 1736 1737 // LOG_COLLECT_CONCURRENTLY(cause, msg, args...) 1738 // Macro so msg printing is format-checked. 1739 #define LOG_COLLECT_CONCURRENTLY(cause, ...) \ 1740 do { \ 1741 LogTarget(Trace, gc) LOG_COLLECT_CONCURRENTLY_lt; \ 1742 if (LOG_COLLECT_CONCURRENTLY_lt.is_enabled()) { \ 1743 ResourceMark rm; /* For thread name. */ \ 1744 LogStream LOG_COLLECT_CONCURRENTLY_s(&LOG_COLLECT_CONCURRENTLY_lt); \ 1745 LOG_COLLECT_CONCURRENTLY_s.print("%s: Try Collect Concurrently (%s): ", \ 1746 Thread::current()->name(), \ 1747 GCCause::to_string(cause)); \ 1748 LOG_COLLECT_CONCURRENTLY_s.print(__VA_ARGS__); \ 1749 } \ 1750 } while (0) 1751 1752 #define LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, result) \ 1753 LOG_COLLECT_CONCURRENTLY(cause, "complete %s", BOOL_TO_STR(result)) 1754 1755 bool G1CollectedHeap::try_collect_concurrently(GCCause::Cause cause, 1756 uint gc_counter, 1757 uint old_marking_started_before) { 1758 assert_heap_not_locked(); 1759 assert(should_do_concurrent_full_gc(cause), 1760 "Non-concurrent cause %s", GCCause::to_string(cause)); 1761 1762 for (uint i = 1; true; ++i) { 1763 // Try to schedule concurrent start evacuation pause that will 1764 // start a concurrent cycle. 1765 LOG_COLLECT_CONCURRENTLY(cause, "attempt %u", i); 1766 VM_G1TryInitiateConcMark op(gc_counter, cause); 1767 VMThread::execute(&op); 1768 1769 // Request is trivially finished. 1770 if (cause == GCCause::_g1_periodic_collection) { 1771 LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, op.gc_succeeded()); 1772 return op.gc_succeeded(); 1773 } 1774 1775 // If VMOp skipped initiating concurrent marking cycle because 1776 // we're terminating, then we're done. 1777 if (op.terminating()) { 1778 LOG_COLLECT_CONCURRENTLY(cause, "skipped: terminating"); 1779 return false; 1780 } 1781 1782 // Lock to get consistent set of values. 1783 uint old_marking_started_after; 1784 uint old_marking_completed_after; 1785 { 1786 MutexLocker ml(Heap_lock); 1787 // Update gc_counter for retrying VMOp if needed. Captured here to be 1788 // consistent with the values we use below for termination tests. If 1789 // a retry is needed after a possible wait, and another collection 1790 // occurs in the meantime, it will cause our retry to be skipped and 1791 // we'll recheck for termination with updated conditions from that 1792 // more recent collection. That's what we want, rather than having 1793 // our retry possibly perform an unnecessary collection. 1794 gc_counter = total_collections(); 1795 old_marking_started_after = _old_marking_cycles_started; 1796 old_marking_completed_after = _old_marking_cycles_completed; 1797 } 1798 1799 if (cause == GCCause::_wb_breakpoint) { 1800 if (op.gc_succeeded()) { 1801 LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true); 1802 return true; 1803 } 1804 // When _wb_breakpoint there can't be another cycle or deferred. 1805 assert(!op.cycle_already_in_progress(), "invariant"); 1806 assert(!op.whitebox_attached(), "invariant"); 1807 // Concurrent cycle attempt might have been cancelled by some other 1808 // collection, so retry. Unlike other cases below, we want to retry 1809 // even if cancelled by a STW full collection, because we really want 1810 // to start a concurrent cycle. 1811 if (old_marking_started_before != old_marking_started_after) { 1812 LOG_COLLECT_CONCURRENTLY(cause, "ignoring STW full GC"); 1813 old_marking_started_before = old_marking_started_after; 1814 } 1815 } else if (!GCCause::is_user_requested_gc(cause)) { 1816 // For an "automatic" (not user-requested) collection, we just need to 1817 // ensure that progress is made. 1818 // 1819 // Request is finished if any of 1820 // (1) the VMOp successfully performed a GC, 1821 // (2) a concurrent cycle was already in progress, 1822 // (3) whitebox is controlling concurrent cycles, 1823 // (4) a new cycle was started (by this thread or some other), or 1824 // (5) a Full GC was performed. 1825 // Cases (4) and (5) are detected together by a change to 1826 // _old_marking_cycles_started. 1827 // 1828 // Note that (1) does not imply (4). If we're still in the mixed 1829 // phase of an earlier concurrent collection, the request to make the 1830 // collection a concurrent start won't be honored. If we don't check for 1831 // both conditions we'll spin doing back-to-back collections. 1832 if (op.gc_succeeded() || 1833 op.cycle_already_in_progress() || 1834 op.whitebox_attached() || 1835 (old_marking_started_before != old_marking_started_after)) { 1836 LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true); 1837 return true; 1838 } 1839 } else { // User-requested GC. 1840 // For a user-requested collection, we want to ensure that a complete 1841 // full collection has been performed before returning, but without 1842 // waiting for more than needed. 1843 1844 // For user-requested GCs (unlike non-UR), a successful VMOp implies a 1845 // new cycle was started. That's good, because it's not clear what we 1846 // should do otherwise. Trying again just does back to back GCs. 1847 // Can't wait for someone else to start a cycle. And returning fails 1848 // to meet the goal of ensuring a full collection was performed. 1849 assert(!op.gc_succeeded() || 1850 (old_marking_started_before != old_marking_started_after), 1851 "invariant: succeeded %s, started before %u, started after %u", 1852 BOOL_TO_STR(op.gc_succeeded()), 1853 old_marking_started_before, old_marking_started_after); 1854 1855 // Request is finished if a full collection (concurrent or stw) 1856 // was started after this request and has completed, e.g. 1857 // started_before < completed_after. 1858 if (gc_counter_less_than(old_marking_started_before, 1859 old_marking_completed_after)) { 1860 LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true); 1861 return true; 1862 } 1863 1864 if (old_marking_started_after != old_marking_completed_after) { 1865 // If there is an in-progress cycle (possibly started by us), then 1866 // wait for that cycle to complete, e.g. 1867 // while completed_now < started_after. 1868 LOG_COLLECT_CONCURRENTLY(cause, "wait"); 1869 MonitorLocker ml(G1OldGCCount_lock); 1870 while (gc_counter_less_than(_old_marking_cycles_completed, 1871 old_marking_started_after)) { 1872 ml.wait(); 1873 } 1874 // Request is finished if the collection we just waited for was 1875 // started after this request. 1876 if (old_marking_started_before != old_marking_started_after) { 1877 LOG_COLLECT_CONCURRENTLY(cause, "complete after wait"); 1878 return true; 1879 } 1880 } 1881 1882 // If VMOp was successful then it started a new cycle that the above 1883 // wait &etc should have recognized as finishing this request. This 1884 // differs from a non-user-request, where gc_succeeded does not imply 1885 // a new cycle was started. 1886 assert(!op.gc_succeeded(), "invariant"); 1887 1888 if (op.cycle_already_in_progress()) { 1889 // If VMOp failed because a cycle was already in progress, it 1890 // is now complete. But it didn't finish this user-requested 1891 // GC, so try again. 1892 LOG_COLLECT_CONCURRENTLY(cause, "retry after in-progress"); 1893 continue; 1894 } else if (op.whitebox_attached()) { 1895 // If WhiteBox wants control, wait for notification of a state 1896 // change in the controller, then try again. Don't wait for 1897 // release of control, since collections may complete while in 1898 // control. Note: This won't recognize a STW full collection 1899 // while waiting; we can't wait on multiple monitors. 1900 LOG_COLLECT_CONCURRENTLY(cause, "whitebox control stall"); 1901 MonitorLocker ml(ConcurrentGCBreakpoints::monitor()); 1902 if (ConcurrentGCBreakpoints::is_controlled()) { 1903 ml.wait(); 1904 } 1905 continue; 1906 } 1907 } 1908 1909 // Collection failed and should be retried. 1910 assert(op.transient_failure(), "invariant"); 1911 1912 if (GCLocker::is_active_and_needs_gc()) { 1913 // If GCLocker is active, wait until clear before retrying. 1914 LOG_COLLECT_CONCURRENTLY(cause, "gc-locker stall"); 1915 GCLocker::stall_until_clear(); 1916 } 1917 1918 LOG_COLLECT_CONCURRENTLY(cause, "retry"); 1919 } 1920 } 1921 1922 bool G1CollectedHeap::try_collect_fullgc(GCCause::Cause cause, 1923 const G1GCCounters& counters_before) { 1924 assert_heap_not_locked(); 1925 1926 while(true) { 1927 VM_G1CollectFull op(counters_before.total_collections(), 1928 counters_before.total_full_collections(), 1929 cause); 1930 VMThread::execute(&op); 1931 1932 // Request is trivially finished. 1933 if (!GCCause::is_explicit_full_gc(cause) || op.gc_succeeded()) { 1934 return op.gc_succeeded(); 1935 } 1936 1937 { 1938 MutexLocker ml(Heap_lock); 1939 if (counters_before.total_full_collections() != total_full_collections()) { 1940 return true; 1941 } 1942 } 1943 1944 if (GCLocker::is_active_and_needs_gc()) { 1945 // If GCLocker is active, wait until clear before retrying. 1946 GCLocker::stall_until_clear(); 1947 } 1948 } 1949 } 1950 1951 bool G1CollectedHeap::try_collect(GCCause::Cause cause, 1952 const G1GCCounters& counters_before) { 1953 if (should_do_concurrent_full_gc(cause)) { 1954 return try_collect_concurrently(cause, 1955 counters_before.total_collections(), 1956 counters_before.old_marking_cycles_started()); 1957 } else if (GCLocker::should_discard(cause, counters_before.total_collections())) { 1958 // Indicate failure to be consistent with VMOp failure due to 1959 // another collection slipping in after our gc_count but before 1960 // our request is processed. 1961 return false; 1962 } else if (cause == GCCause::_gc_locker || cause == GCCause::_wb_young_gc 1963 DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) { 1964 1965 // Schedule a standard evacuation pause. We're setting word_size 1966 // to 0 which means that we are not requesting a post-GC allocation. 1967 VM_G1CollectForAllocation op(0, /* word_size */ 1968 counters_before.total_collections(), 1969 cause); 1970 VMThread::execute(&op); 1971 return op.gc_succeeded(); 1972 } else { 1973 // Schedule a Full GC. 1974 return try_collect_fullgc(cause, counters_before); 1975 } 1976 } 1977 1978 void G1CollectedHeap::start_concurrent_gc_for_metadata_allocation(GCCause::Cause gc_cause) { 1979 GCCauseSetter x(this, gc_cause); 1980 1981 // At this point we are supposed to start a concurrent cycle. We 1982 // will do so if one is not already in progress. 1983 bool should_start = policy()->force_concurrent_start_if_outside_cycle(gc_cause); 1984 if (should_start) { 1985 do_collection_pause_at_safepoint(); 1986 } 1987 } 1988 1989 bool G1CollectedHeap::is_in(const void* p) const { 1990 return is_in_reserved(p) && _hrm.is_available(addr_to_region(p)); 1991 } 1992 1993 // Iteration functions. 1994 1995 // Iterates an ObjectClosure over all objects within a HeapRegion. 1996 1997 class IterateObjectClosureRegionClosure: public HeapRegionClosure { 1998 ObjectClosure* _cl; 1999 public: 2000 IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {} 2001 bool do_heap_region(HeapRegion* r) { 2002 if (!r->is_continues_humongous()) { 2003 r->object_iterate(_cl); 2004 } 2005 return false; 2006 } 2007 }; 2008 2009 void G1CollectedHeap::object_iterate(ObjectClosure* cl) { 2010 IterateObjectClosureRegionClosure blk(cl); 2011 heap_region_iterate(&blk); 2012 } 2013 2014 class G1ParallelObjectIterator : public ParallelObjectIteratorImpl { 2015 private: 2016 G1CollectedHeap* _heap; 2017 HeapRegionClaimer _claimer; 2018 2019 public: 2020 G1ParallelObjectIterator(uint thread_num) : 2021 _heap(G1CollectedHeap::heap()), 2022 _claimer(thread_num == 0 ? G1CollectedHeap::heap()->workers()->active_workers() : thread_num) {} 2023 2024 virtual void object_iterate(ObjectClosure* cl, uint worker_id) { 2025 _heap->object_iterate_parallel(cl, worker_id, &_claimer); 2026 } 2027 }; 2028 2029 ParallelObjectIteratorImpl* G1CollectedHeap::parallel_object_iterator(uint thread_num) { 2030 return new G1ParallelObjectIterator(thread_num); 2031 } 2032 2033 void G1CollectedHeap::object_iterate_parallel(ObjectClosure* cl, uint worker_id, HeapRegionClaimer* claimer) { 2034 IterateObjectClosureRegionClosure blk(cl); 2035 heap_region_par_iterate_from_worker_offset(&blk, claimer, worker_id); 2036 } 2037 2038 void G1CollectedHeap::keep_alive(oop obj) { 2039 G1BarrierSet::enqueue_preloaded(obj); 2040 } 2041 2042 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const { 2043 _hrm.iterate(cl); 2044 } 2045 2046 void G1CollectedHeap::heap_region_iterate(HeapRegionIndexClosure* cl) const { 2047 _hrm.iterate(cl); 2048 } 2049 2050 void G1CollectedHeap::heap_region_par_iterate_from_worker_offset(HeapRegionClosure* cl, 2051 HeapRegionClaimer *hrclaimer, 2052 uint worker_id) const { 2053 _hrm.par_iterate(cl, hrclaimer, hrclaimer->offset_for_worker(worker_id)); 2054 } 2055 2056 void G1CollectedHeap::heap_region_par_iterate_from_start(HeapRegionClosure* cl, 2057 HeapRegionClaimer *hrclaimer) const { 2058 _hrm.par_iterate(cl, hrclaimer, 0); 2059 } 2060 2061 void G1CollectedHeap::collection_set_iterate_all(HeapRegionClosure* cl) { 2062 _collection_set.iterate(cl); 2063 } 2064 2065 void G1CollectedHeap::collection_set_par_iterate_all(HeapRegionClosure* cl, 2066 HeapRegionClaimer* hr_claimer, 2067 uint worker_id) { 2068 _collection_set.par_iterate(cl, hr_claimer, worker_id); 2069 } 2070 2071 void G1CollectedHeap::collection_set_iterate_increment_from(HeapRegionClosure *cl, 2072 HeapRegionClaimer* hr_claimer, 2073 uint worker_id) { 2074 _collection_set.iterate_incremental_part_from(cl, hr_claimer, worker_id); 2075 } 2076 2077 void G1CollectedHeap::par_iterate_regions_array(HeapRegionClosure* cl, 2078 HeapRegionClaimer* hr_claimer, 2079 const uint regions[], 2080 size_t length, 2081 uint worker_id) const { 2082 assert_at_safepoint(); 2083 if (length == 0) { 2084 return; 2085 } 2086 uint total_workers = workers()->active_workers(); 2087 2088 size_t start_pos = (worker_id * length) / total_workers; 2089 size_t cur_pos = start_pos; 2090 2091 do { 2092 uint region_idx = regions[cur_pos]; 2093 if (hr_claimer == nullptr || hr_claimer->claim_region(region_idx)) { 2094 HeapRegion* r = region_at(region_idx); 2095 bool result = cl->do_heap_region(r); 2096 guarantee(!result, "Must not cancel iteration"); 2097 } 2098 2099 cur_pos++; 2100 if (cur_pos == length) { 2101 cur_pos = 0; 2102 } 2103 } while (cur_pos != start_pos); 2104 } 2105 2106 HeapWord* G1CollectedHeap::block_start(const void* addr) const { 2107 HeapRegion* hr = heap_region_containing(addr); 2108 // The CollectedHeap API requires us to not fail for any given address within 2109 // the heap. HeapRegion::block_start() has been optimized to not accept addresses 2110 // outside of the allocated area. 2111 if (addr >= hr->top()) { 2112 return nullptr; 2113 } 2114 return hr->block_start(addr); 2115 } 2116 2117 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const { 2118 HeapRegion* hr = heap_region_containing(addr); 2119 return hr->block_is_obj(addr, hr->parsable_bottom_acquire()); 2120 } 2121 2122 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const { 2123 return (_policy->young_list_target_length() - _survivor.length()) * HeapRegion::GrainBytes; 2124 } 2125 2126 size_t G1CollectedHeap::tlab_used(Thread* ignored) const { 2127 return _eden.length() * HeapRegion::GrainBytes; 2128 } 2129 2130 // For G1 TLABs should not contain humongous objects, so the maximum TLAB size 2131 // must be equal to the humongous object limit. 2132 size_t G1CollectedHeap::max_tlab_size() const { 2133 return align_down(_humongous_object_threshold_in_words, MinObjAlignment); 2134 } 2135 2136 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const { 2137 return _allocator->unsafe_max_tlab_alloc(); 2138 } 2139 2140 size_t G1CollectedHeap::max_capacity() const { 2141 return max_regions() * HeapRegion::GrainBytes; 2142 } 2143 2144 void G1CollectedHeap::prepare_for_verify() { 2145 _verifier->prepare_for_verify(); 2146 } 2147 2148 void G1CollectedHeap::verify(VerifyOption vo) { 2149 _verifier->verify(vo); 2150 } 2151 2152 bool G1CollectedHeap::supports_concurrent_gc_breakpoints() const { 2153 return true; 2154 } 2155 2156 class PrintRegionClosure: public HeapRegionClosure { 2157 outputStream* _st; 2158 public: 2159 PrintRegionClosure(outputStream* st) : _st(st) {} 2160 bool do_heap_region(HeapRegion* r) { 2161 r->print_on(_st); 2162 return false; 2163 } 2164 }; 2165 2166 bool G1CollectedHeap::is_obj_dead_cond(const oop obj, 2167 const HeapRegion* hr, 2168 const VerifyOption vo) const { 2169 switch (vo) { 2170 case VerifyOption::G1UseConcMarking: return is_obj_dead(obj, hr); 2171 case VerifyOption::G1UseFullMarking: return is_obj_dead_full(obj, hr); 2172 default: ShouldNotReachHere(); 2173 } 2174 return false; // keep some compilers happy 2175 } 2176 2177 bool G1CollectedHeap::is_obj_dead_cond(const oop obj, 2178 const VerifyOption vo) const { 2179 switch (vo) { 2180 case VerifyOption::G1UseConcMarking: return is_obj_dead(obj); 2181 case VerifyOption::G1UseFullMarking: return is_obj_dead_full(obj); 2182 default: ShouldNotReachHere(); 2183 } 2184 return false; // keep some compilers happy 2185 } 2186 2187 void G1CollectedHeap::pin_object(JavaThread* thread, oop obj) { 2188 GCLocker::lock_critical(thread); 2189 } 2190 2191 void G1CollectedHeap::unpin_object(JavaThread* thread, oop obj) { 2192 GCLocker::unlock_critical(thread); 2193 } 2194 2195 void G1CollectedHeap::print_heap_regions() const { 2196 LogTarget(Trace, gc, heap, region) lt; 2197 if (lt.is_enabled()) { 2198 LogStream ls(lt); 2199 print_regions_on(&ls); 2200 } 2201 } 2202 2203 void G1CollectedHeap::print_on(outputStream* st) const { 2204 size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked(); 2205 st->print(" %-20s", "garbage-first heap"); 2206 st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K", 2207 capacity()/K, heap_used/K); 2208 st->print(" [" PTR_FORMAT ", " PTR_FORMAT ")", 2209 p2i(_hrm.reserved().start()), 2210 p2i(_hrm.reserved().end())); 2211 st->cr(); 2212 st->print(" region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K); 2213 uint young_regions = young_regions_count(); 2214 st->print("%u young (" SIZE_FORMAT "K), ", young_regions, 2215 (size_t) young_regions * HeapRegion::GrainBytes / K); 2216 uint survivor_regions = survivor_regions_count(); 2217 st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions, 2218 (size_t) survivor_regions * HeapRegion::GrainBytes / K); 2219 st->cr(); 2220 if (_numa->is_enabled()) { 2221 uint num_nodes = _numa->num_active_nodes(); 2222 st->print(" remaining free region(s) on each NUMA node: "); 2223 const int* node_ids = _numa->node_ids(); 2224 for (uint node_index = 0; node_index < num_nodes; node_index++) { 2225 uint num_free_regions = _hrm.num_free_regions(node_index); 2226 st->print("%d=%u ", node_ids[node_index], num_free_regions); 2227 } 2228 st->cr(); 2229 } 2230 MetaspaceUtils::print_on(st); 2231 } 2232 2233 void G1CollectedHeap::print_regions_on(outputStream* st) const { 2234 st->print_cr("Heap Regions: E=young(eden), S=young(survivor), O=old, " 2235 "HS=humongous(starts), HC=humongous(continues), " 2236 "CS=collection set, F=free, " 2237 "TAMS=top-at-mark-start, " 2238 "PB=parsable bottom"); 2239 PrintRegionClosure blk(st); 2240 heap_region_iterate(&blk); 2241 } 2242 2243 void G1CollectedHeap::print_extended_on(outputStream* st) const { 2244 print_on(st); 2245 2246 // Print the per-region information. 2247 st->cr(); 2248 print_regions_on(st); 2249 } 2250 2251 void G1CollectedHeap::print_on_error(outputStream* st) const { 2252 this->CollectedHeap::print_on_error(st); 2253 2254 if (_cm != nullptr) { 2255 st->cr(); 2256 _cm->print_on_error(st); 2257 } 2258 } 2259 2260 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const { 2261 workers()->threads_do(tc); 2262 tc->do_thread(_cm_thread); 2263 _cm->threads_do(tc); 2264 _cr->threads_do(tc); 2265 tc->do_thread(_service_thread); 2266 } 2267 2268 void G1CollectedHeap::print_tracing_info() const { 2269 rem_set()->print_summary_info(); 2270 concurrent_mark()->print_summary_info(); 2271 } 2272 2273 bool G1CollectedHeap::print_location(outputStream* st, void* addr) const { 2274 return BlockLocationPrinter<G1CollectedHeap>::print_location(st, addr); 2275 } 2276 2277 G1HeapSummary G1CollectedHeap::create_g1_heap_summary() { 2278 2279 size_t eden_used_bytes = _monitoring_support->eden_space_used(); 2280 size_t survivor_used_bytes = _monitoring_support->survivor_space_used(); 2281 size_t old_gen_used_bytes = _monitoring_support->old_gen_used(); 2282 size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked(); 2283 2284 size_t eden_capacity_bytes = 2285 (policy()->young_list_target_length() * HeapRegion::GrainBytes) - survivor_used_bytes; 2286 2287 VirtualSpaceSummary heap_summary = create_heap_space_summary(); 2288 return G1HeapSummary(heap_summary, heap_used, eden_used_bytes, eden_capacity_bytes, 2289 survivor_used_bytes, old_gen_used_bytes, num_regions()); 2290 } 2291 2292 G1EvacSummary G1CollectedHeap::create_g1_evac_summary(G1EvacStats* stats) { 2293 return G1EvacSummary(stats->allocated(), stats->wasted(), stats->undo_wasted(), 2294 stats->unused(), stats->used(), stats->region_end_waste(), 2295 stats->regions_filled(), stats->num_plab_filled(), 2296 stats->direct_allocated(), stats->num_direct_allocated(), 2297 stats->failure_used(), stats->failure_waste()); 2298 } 2299 2300 void G1CollectedHeap::trace_heap(GCWhen::Type when, const GCTracer* gc_tracer) { 2301 const G1HeapSummary& heap_summary = create_g1_heap_summary(); 2302 gc_tracer->report_gc_heap_summary(when, heap_summary); 2303 2304 const MetaspaceSummary& metaspace_summary = create_metaspace_summary(); 2305 gc_tracer->report_metaspace_summary(when, metaspace_summary); 2306 } 2307 2308 void G1CollectedHeap::gc_prologue(bool full) { 2309 assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer"); 2310 2311 // Update common counters. 2312 increment_total_collections(full /* full gc */); 2313 if (full || collector_state()->in_concurrent_start_gc()) { 2314 increment_old_marking_cycles_started(); 2315 } 2316 } 2317 2318 void G1CollectedHeap::gc_epilogue(bool full) { 2319 // Update common counters. 2320 if (full) { 2321 // Update the number of full collections that have been completed. 2322 increment_old_marking_cycles_completed(false /* concurrent */, true /* liveness_completed */); 2323 } 2324 2325 #if COMPILER2_OR_JVMCI 2326 assert(DerivedPointerTable::is_empty(), "derived pointer present"); 2327 #endif 2328 2329 // We have just completed a GC. Update the soft reference 2330 // policy with the new heap occupancy 2331 Universe::heap()->update_capacity_and_used_at_gc(); 2332 2333 _collection_pause_end = Ticks::now(); 2334 2335 _free_arena_memory_task->notify_new_stats(&_young_gen_card_set_stats, 2336 &_collection_set_candidates_card_set_stats); 2337 } 2338 2339 uint G1CollectedHeap::uncommit_regions(uint region_limit) { 2340 return _hrm.uncommit_inactive_regions(region_limit); 2341 } 2342 2343 bool G1CollectedHeap::has_uncommittable_regions() { 2344 return _hrm.has_inactive_regions(); 2345 } 2346 2347 void G1CollectedHeap::uncommit_regions_if_necessary() { 2348 if (has_uncommittable_regions()) { 2349 G1UncommitRegionTask::enqueue(); 2350 } 2351 } 2352 2353 void G1CollectedHeap::verify_numa_regions(const char* desc) { 2354 LogTarget(Trace, gc, heap, verify) lt; 2355 2356 if (lt.is_enabled()) { 2357 LogStream ls(lt); 2358 // Iterate all heap regions to print matching between preferred numa id and actual numa id. 2359 G1NodeIndexCheckClosure cl(desc, _numa, &ls); 2360 heap_region_iterate(&cl); 2361 } 2362 } 2363 2364 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size, 2365 uint gc_count_before, 2366 bool* succeeded, 2367 GCCause::Cause gc_cause) { 2368 assert_heap_not_locked_and_not_at_safepoint(); 2369 VM_G1CollectForAllocation op(word_size, gc_count_before, gc_cause); 2370 VMThread::execute(&op); 2371 2372 HeapWord* result = op.result(); 2373 bool ret_succeeded = op.prologue_succeeded() && op.gc_succeeded(); 2374 assert(result == nullptr || ret_succeeded, 2375 "the result should be null if the VM did not succeed"); 2376 *succeeded = ret_succeeded; 2377 2378 assert_heap_not_locked(); 2379 return result; 2380 } 2381 2382 void G1CollectedHeap::start_concurrent_cycle(bool concurrent_operation_is_full_mark) { 2383 assert(!_cm_thread->in_progress(), "Can not start concurrent operation while in progress"); 2384 2385 MutexLocker x(CGC_lock, Mutex::_no_safepoint_check_flag); 2386 if (concurrent_operation_is_full_mark) { 2387 _cm->post_concurrent_mark_start(); 2388 _cm_thread->start_full_mark(); 2389 } else { 2390 _cm->post_concurrent_undo_start(); 2391 _cm_thread->start_undo_mark(); 2392 } 2393 CGC_lock->notify(); 2394 } 2395 2396 bool G1CollectedHeap::is_potential_eager_reclaim_candidate(HeapRegion* r) const { 2397 // We don't nominate objects with many remembered set entries, on 2398 // the assumption that such objects are likely still live. 2399 HeapRegionRemSet* rem_set = r->rem_set(); 2400 2401 return rem_set->occupancy_less_or_equal_than(G1EagerReclaimRemSetThreshold); 2402 } 2403 2404 #ifndef PRODUCT 2405 void G1CollectedHeap::verify_region_attr_remset_is_tracked() { 2406 class VerifyRegionAttrRemSet : public HeapRegionClosure { 2407 public: 2408 virtual bool do_heap_region(HeapRegion* r) { 2409 G1CollectedHeap* g1h = G1CollectedHeap::heap(); 2410 bool const remset_is_tracked = g1h->region_attr(r->bottom()).remset_is_tracked(); 2411 assert(r->rem_set()->is_tracked() == remset_is_tracked, 2412 "Region %u remset tracking status (%s) different to region attribute (%s)", 2413 r->hrm_index(), BOOL_TO_STR(r->rem_set()->is_tracked()), BOOL_TO_STR(remset_is_tracked)); 2414 return false; 2415 } 2416 } cl; 2417 heap_region_iterate(&cl); 2418 } 2419 #endif 2420 2421 void G1CollectedHeap::start_new_collection_set() { 2422 collection_set()->start_incremental_building(); 2423 2424 clear_region_attr(); 2425 2426 guarantee(_eden.length() == 0, "eden should have been cleared"); 2427 policy()->transfer_survivors_to_cset(survivor()); 2428 2429 // We redo the verification but now wrt to the new CSet which 2430 // has just got initialized after the previous CSet was freed. 2431 _cm->verify_no_collection_set_oops(); 2432 } 2433 2434 G1HeapVerifier::G1VerifyType G1CollectedHeap::young_collection_verify_type() const { 2435 if (collector_state()->in_concurrent_start_gc()) { 2436 return G1HeapVerifier::G1VerifyConcurrentStart; 2437 } else if (collector_state()->in_young_only_phase()) { 2438 return G1HeapVerifier::G1VerifyYoungNormal; 2439 } else { 2440 return G1HeapVerifier::G1VerifyMixed; 2441 } 2442 } 2443 2444 void G1CollectedHeap::verify_before_young_collection(G1HeapVerifier::G1VerifyType type) { 2445 if (!VerifyBeforeGC) { 2446 return; 2447 } 2448 if (!G1HeapVerifier::should_verify(type)) { 2449 return; 2450 } 2451 Ticks start = Ticks::now(); 2452 _verifier->prepare_for_verify(); 2453 _verifier->verify_region_sets_optional(); 2454 _verifier->verify_dirty_young_regions(); 2455 _verifier->verify_before_gc(); 2456 verify_numa_regions("GC Start"); 2457 phase_times()->record_verify_before_time_ms((Ticks::now() - start).seconds() * MILLIUNITS); 2458 } 2459 2460 void G1CollectedHeap::verify_after_young_collection(G1HeapVerifier::G1VerifyType type) { 2461 if (!VerifyAfterGC) { 2462 return; 2463 } 2464 if (!G1HeapVerifier::should_verify(type)) { 2465 return; 2466 } 2467 Ticks start = Ticks::now(); 2468 _verifier->verify_after_gc(); 2469 verify_numa_regions("GC End"); 2470 _verifier->verify_region_sets_optional(); 2471 phase_times()->record_verify_after_time_ms((Ticks::now() - start).seconds() * MILLIUNITS); 2472 } 2473 2474 void G1CollectedHeap::expand_heap_after_young_collection(){ 2475 size_t expand_bytes = _heap_sizing_policy->young_collection_expansion_amount(); 2476 if (expand_bytes > 0) { 2477 // No need for an ergo logging here, 2478 // expansion_amount() does this when it returns a value > 0. 2479 double expand_ms = 0.0; 2480 if (!expand(expand_bytes, _workers, &expand_ms)) { 2481 // We failed to expand the heap. Cannot do anything about it. 2482 } 2483 phase_times()->record_expand_heap_time(expand_ms); 2484 } 2485 } 2486 2487 bool G1CollectedHeap::do_collection_pause_at_safepoint() { 2488 assert_at_safepoint_on_vm_thread(); 2489 guarantee(!is_stw_gc_active(), "collection is not reentrant"); 2490 2491 if (GCLocker::check_active_before_gc()) { 2492 return false; 2493 } 2494 2495 do_collection_pause_at_safepoint_helper(); 2496 return true; 2497 } 2498 2499 G1HeapPrinterMark::G1HeapPrinterMark(G1CollectedHeap* g1h) : _g1h(g1h), _heap_transition(g1h) { 2500 // This summary needs to be printed before incrementing total collections. 2501 _g1h->rem_set()->print_periodic_summary_info("Before GC RS summary", 2502 _g1h->total_collections(), 2503 true /* show_thread_times */); 2504 _g1h->print_heap_before_gc(); 2505 _g1h->print_heap_regions(); 2506 } 2507 2508 G1HeapPrinterMark::~G1HeapPrinterMark() { 2509 _g1h->policy()->print_age_table(); 2510 _g1h->rem_set()->print_coarsen_stats(); 2511 // We are at the end of the GC. Total collections has already been increased. 2512 _g1h->rem_set()->print_periodic_summary_info("After GC RS summary", 2513 _g1h->total_collections() - 1, 2514 false /* show_thread_times */); 2515 2516 _heap_transition.print(); 2517 _g1h->print_heap_regions(); 2518 _g1h->print_heap_after_gc(); 2519 // Print NUMA statistics. 2520 _g1h->numa()->print_statistics(); 2521 } 2522 2523 G1JFRTracerMark::G1JFRTracerMark(STWGCTimer* timer, GCTracer* tracer) : 2524 _timer(timer), _tracer(tracer) { 2525 2526 _timer->register_gc_start(); 2527 _tracer->report_gc_start(G1CollectedHeap::heap()->gc_cause(), _timer->gc_start()); 2528 G1CollectedHeap::heap()->trace_heap_before_gc(_tracer); 2529 } 2530 2531 G1JFRTracerMark::~G1JFRTracerMark() { 2532 G1CollectedHeap::heap()->trace_heap_after_gc(_tracer); 2533 _timer->register_gc_end(); 2534 _tracer->report_gc_end(_timer->gc_end(), _timer->time_partitions()); 2535 } 2536 2537 void G1CollectedHeap::prepare_for_mutator_after_young_collection() { 2538 Ticks start = Ticks::now(); 2539 2540 _survivor_evac_stats.adjust_desired_plab_size(); 2541 _old_evac_stats.adjust_desired_plab_size(); 2542 2543 // Start a new incremental collection set for the mutator phase. 2544 start_new_collection_set(); 2545 _allocator->init_mutator_alloc_regions(); 2546 2547 phase_times()->record_prepare_for_mutator_time_ms((Ticks::now() - start).seconds() * 1000.0); 2548 } 2549 2550 void G1CollectedHeap::retire_tlabs() { 2551 ensure_parsability(true); 2552 } 2553 2554 void G1CollectedHeap::do_collection_pause_at_safepoint_helper() { 2555 ResourceMark rm; 2556 2557 IsSTWGCActiveMark active_gc_mark; 2558 GCIdMark gc_id_mark; 2559 SvcGCMarker sgcm(SvcGCMarker::MINOR); 2560 2561 GCTraceCPUTime tcpu(_gc_tracer_stw); 2562 2563 _bytes_used_during_gc = 0; 2564 2565 policy()->decide_on_concurrent_start_pause(); 2566 // Record whether this pause may need to trigger a concurrent operation. Later, 2567 // when we signal the G1ConcurrentMarkThread, the collector state has already 2568 // been reset for the next pause. 2569 bool should_start_concurrent_mark_operation = collector_state()->in_concurrent_start_gc(); 2570 2571 // Perform the collection. 2572 G1YoungCollector collector(gc_cause()); 2573 collector.collect(); 2574 2575 // It should now be safe to tell the concurrent mark thread to start 2576 // without its logging output interfering with the logging output 2577 // that came from the pause. 2578 if (should_start_concurrent_mark_operation) { 2579 verifier()->verify_bitmap_clear(true /* above_tams_only */); 2580 // CAUTION: after the start_concurrent_cycle() call below, the concurrent marking 2581 // thread(s) could be running concurrently with us. Make sure that anything 2582 // after this point does not assume that we are the only GC thread running. 2583 // Note: of course, the actual marking work will not start until the safepoint 2584 // itself is released in SuspendibleThreadSet::desynchronize(). 2585 start_concurrent_cycle(collector.concurrent_operation_is_full_mark()); 2586 ConcurrentGCBreakpoints::notify_idle_to_active(); 2587 } 2588 } 2589 2590 void G1CollectedHeap::complete_cleaning(bool class_unloading_occurred) { 2591 uint num_workers = workers()->active_workers(); 2592 G1ParallelCleaningTask unlink_task(num_workers, class_unloading_occurred); 2593 workers()->run_task(&unlink_task); 2594 } 2595 2596 void G1CollectedHeap::unload_classes_and_code(const char* description, BoolObjectClosure* is_alive, GCTimer* timer) { 2597 GCTraceTime(Debug, gc, phases) debug(description, timer); 2598 2599 ClassUnloadingContext ctx(workers()->active_workers(), 2600 false /* unregister_nmethods_during_purge */, 2601 false /* lock_codeblob_free_separately */); 2602 { 2603 CodeCache::UnlinkingScope scope(is_alive); 2604 bool unloading_occurred = SystemDictionary::do_unloading(timer); 2605 GCTraceTime(Debug, gc, phases) t("G1 Complete Cleaning", timer); 2606 complete_cleaning(unloading_occurred); 2607 } 2608 { 2609 GCTraceTime(Debug, gc, phases) t("Purge Unlinked NMethods", timer); 2610 ctx.purge_nmethods(); 2611 } 2612 { 2613 GCTraceTime(Debug, gc, phases) ur("Unregister NMethods", timer); 2614 G1CollectedHeap::heap()->bulk_unregister_nmethods(); 2615 } 2616 { 2617 GCTraceTime(Debug, gc, phases) t("Free Code Blobs", timer); 2618 ctx.free_code_blobs(); 2619 } 2620 { 2621 GCTraceTime(Debug, gc, phases) t("Purge Class Loader Data", timer); 2622 ClassLoaderDataGraph::purge(true /* at_safepoint */); 2623 DEBUG_ONLY(MetaspaceUtils::verify();) 2624 } 2625 } 2626 2627 class G1BulkUnregisterNMethodTask : public WorkerTask { 2628 HeapRegionClaimer _hrclaimer; 2629 2630 class UnregisterNMethodsHeapRegionClosure : public HeapRegionClosure { 2631 public: 2632 2633 bool do_heap_region(HeapRegion* hr) { 2634 hr->rem_set()->bulk_remove_code_roots(); 2635 return false; 2636 } 2637 } _cl; 2638 2639 public: 2640 G1BulkUnregisterNMethodTask(uint num_workers) 2641 : WorkerTask("G1 Remove Unlinked NMethods From Code Root Set Task"), 2642 _hrclaimer(num_workers) { } 2643 2644 void work(uint worker_id) { 2645 G1CollectedHeap::heap()->heap_region_par_iterate_from_worker_offset(&_cl, &_hrclaimer, worker_id); 2646 } 2647 }; 2648 2649 void G1CollectedHeap::bulk_unregister_nmethods() { 2650 uint num_workers = workers()->active_workers(); 2651 G1BulkUnregisterNMethodTask t(num_workers); 2652 workers()->run_task(&t); 2653 } 2654 2655 bool G1STWSubjectToDiscoveryClosure::do_object_b(oop obj) { 2656 assert(obj != nullptr, "must not be null"); 2657 assert(_g1h->is_in_reserved(obj), "Trying to discover obj " PTR_FORMAT " not in heap", p2i(obj)); 2658 // The areas the CM and STW ref processor manage must be disjoint. The is_in_cset() below 2659 // may falsely indicate that this is not the case here: however the collection set only 2660 // contains old regions when concurrent mark is not running. 2661 return _g1h->is_in_cset(obj) || _g1h->heap_region_containing(obj)->is_survivor(); 2662 } 2663 2664 void G1CollectedHeap::make_pending_list_reachable() { 2665 if (collector_state()->in_concurrent_start_gc()) { 2666 oop pll_head = Universe::reference_pending_list(); 2667 if (pll_head != nullptr) { 2668 // Any valid worker id is fine here as we are in the VM thread and single-threaded. 2669 _cm->mark_in_bitmap(0 /* worker_id */, pll_head); 2670 } 2671 } 2672 } 2673 2674 void G1CollectedHeap::set_humongous_stats(uint num_humongous_total, uint num_humongous_candidates) { 2675 _num_humongous_objects = num_humongous_total; 2676 _num_humongous_reclaim_candidates = num_humongous_candidates; 2677 } 2678 2679 bool G1CollectedHeap::should_sample_collection_set_candidates() const { 2680 const G1CollectionSetCandidates* candidates = collection_set()->candidates(); 2681 return !candidates->is_empty(); 2682 } 2683 2684 void G1CollectedHeap::set_collection_set_candidates_stats(G1MonotonicArenaMemoryStats& stats) { 2685 _collection_set_candidates_card_set_stats = stats; 2686 } 2687 2688 void G1CollectedHeap::set_young_gen_card_set_stats(const G1MonotonicArenaMemoryStats& stats) { 2689 _young_gen_card_set_stats = stats; 2690 } 2691 2692 void G1CollectedHeap::record_obj_copy_mem_stats() { 2693 policy()->old_gen_alloc_tracker()-> 2694 add_allocated_bytes_since_last_gc(_old_evac_stats.allocated() * HeapWordSize); 2695 2696 _gc_tracer_stw->report_evacuation_statistics(create_g1_evac_summary(&_survivor_evac_stats), 2697 create_g1_evac_summary(&_old_evac_stats)); 2698 } 2699 2700 void G1CollectedHeap::clear_bitmap_for_region(HeapRegion* hr) { 2701 concurrent_mark()->clear_bitmap_for_region(hr); 2702 } 2703 2704 void G1CollectedHeap::free_region(HeapRegion* hr, FreeRegionList* free_list) { 2705 assert(!hr->is_free(), "the region should not be free"); 2706 assert(!hr->is_empty(), "the region should not be empty"); 2707 assert(_hrm.is_available(hr->hrm_index()), "region should be committed"); 2708 2709 // Reset region metadata to allow reuse. 2710 hr->hr_clear(true /* clear_space */); 2711 _policy->remset_tracker()->update_at_free(hr); 2712 2713 if (free_list != nullptr) { 2714 free_list->add_ordered(hr); 2715 } 2716 } 2717 2718 void G1CollectedHeap::free_humongous_region(HeapRegion* hr, 2719 FreeRegionList* free_list) { 2720 assert(hr->is_humongous(), "this is only for humongous regions"); 2721 hr->clear_humongous(); 2722 free_region(hr, free_list); 2723 } 2724 2725 void G1CollectedHeap::remove_from_old_gen_sets(const uint old_regions_removed, 2726 const uint humongous_regions_removed) { 2727 if (old_regions_removed > 0 || humongous_regions_removed > 0) { 2728 MutexLocker x(OldSets_lock, Mutex::_no_safepoint_check_flag); 2729 _old_set.bulk_remove(old_regions_removed); 2730 _humongous_set.bulk_remove(humongous_regions_removed); 2731 } 2732 2733 } 2734 2735 void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) { 2736 assert(list != nullptr, "list can't be null"); 2737 if (!list->is_empty()) { 2738 MutexLocker x(FreeList_lock, Mutex::_no_safepoint_check_flag); 2739 _hrm.insert_list_into_free_list(list); 2740 } 2741 } 2742 2743 void G1CollectedHeap::decrement_summary_bytes(size_t bytes) { 2744 decrease_used(bytes); 2745 } 2746 2747 void G1CollectedHeap::clear_eden() { 2748 _eden.clear(); 2749 } 2750 2751 void G1CollectedHeap::clear_collection_set() { 2752 collection_set()->clear(); 2753 } 2754 2755 void G1CollectedHeap::rebuild_free_region_list() { 2756 Ticks start = Ticks::now(); 2757 _hrm.rebuild_free_list(workers()); 2758 phase_times()->record_total_rebuild_freelist_time_ms((Ticks::now() - start).seconds() * 1000.0); 2759 } 2760 2761 class G1AbandonCollectionSetClosure : public HeapRegionClosure { 2762 public: 2763 virtual bool do_heap_region(HeapRegion* r) { 2764 assert(r->in_collection_set(), "Region %u must have been in collection set", r->hrm_index()); 2765 G1CollectedHeap::heap()->clear_region_attr(r); 2766 r->clear_young_index_in_cset(); 2767 return false; 2768 } 2769 }; 2770 2771 void G1CollectedHeap::abandon_collection_set(G1CollectionSet* collection_set) { 2772 G1AbandonCollectionSetClosure cl; 2773 collection_set_iterate_all(&cl); 2774 2775 collection_set->clear(); 2776 collection_set->stop_incremental_building(); 2777 } 2778 2779 bool G1CollectedHeap::is_old_gc_alloc_region(HeapRegion* hr) { 2780 return _allocator->is_retained_old_region(hr); 2781 } 2782 2783 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) { 2784 _eden.add(hr); 2785 _policy->set_region_eden(hr); 2786 } 2787 2788 #ifdef ASSERT 2789 2790 class NoYoungRegionsClosure: public HeapRegionClosure { 2791 private: 2792 bool _success; 2793 public: 2794 NoYoungRegionsClosure() : _success(true) { } 2795 bool do_heap_region(HeapRegion* r) { 2796 if (r->is_young()) { 2797 log_error(gc, verify)("Region [" PTR_FORMAT ", " PTR_FORMAT ") tagged as young", 2798 p2i(r->bottom()), p2i(r->end())); 2799 _success = false; 2800 } 2801 return false; 2802 } 2803 bool success() { return _success; } 2804 }; 2805 2806 bool G1CollectedHeap::check_young_list_empty() { 2807 bool ret = (young_regions_count() == 0); 2808 2809 NoYoungRegionsClosure closure; 2810 heap_region_iterate(&closure); 2811 ret = ret && closure.success(); 2812 2813 return ret; 2814 } 2815 2816 #endif // ASSERT 2817 2818 // Remove the given HeapRegion from the appropriate region set. 2819 void G1CollectedHeap::prepare_region_for_full_compaction(HeapRegion* hr) { 2820 if (hr->is_humongous()) { 2821 _humongous_set.remove(hr); 2822 } else if (hr->is_old()) { 2823 _old_set.remove(hr); 2824 } else if (hr->is_young()) { 2825 // Note that emptying the eden and survivor lists is postponed and instead 2826 // done as the first step when rebuilding the regions sets again. The reason 2827 // for this is that during a full GC string deduplication needs to know if 2828 // a collected region was young or old when the full GC was initiated. 2829 hr->uninstall_surv_rate_group(); 2830 } else { 2831 // We ignore free regions, we'll empty the free list afterwards. 2832 assert(hr->is_free(), "it cannot be another type"); 2833 } 2834 } 2835 2836 void G1CollectedHeap::increase_used(size_t bytes) { 2837 _summary_bytes_used += bytes; 2838 } 2839 2840 void G1CollectedHeap::decrease_used(size_t bytes) { 2841 assert(_summary_bytes_used >= bytes, 2842 "invariant: _summary_bytes_used: " SIZE_FORMAT " should be >= bytes: " SIZE_FORMAT, 2843 _summary_bytes_used, bytes); 2844 _summary_bytes_used -= bytes; 2845 } 2846 2847 void G1CollectedHeap::set_used(size_t bytes) { 2848 _summary_bytes_used = bytes; 2849 } 2850 2851 class RebuildRegionSetsClosure : public HeapRegionClosure { 2852 private: 2853 bool _free_list_only; 2854 2855 HeapRegionSet* _old_set; 2856 HeapRegionSet* _humongous_set; 2857 2858 HeapRegionManager* _hrm; 2859 2860 size_t _total_used; 2861 2862 public: 2863 RebuildRegionSetsClosure(bool free_list_only, 2864 HeapRegionSet* old_set, 2865 HeapRegionSet* humongous_set, 2866 HeapRegionManager* hrm) : 2867 _free_list_only(free_list_only), _old_set(old_set), 2868 _humongous_set(humongous_set), _hrm(hrm), _total_used(0) { 2869 assert(_hrm->num_free_regions() == 0, "pre-condition"); 2870 if (!free_list_only) { 2871 assert(_old_set->is_empty(), "pre-condition"); 2872 assert(_humongous_set->is_empty(), "pre-condition"); 2873 } 2874 } 2875 2876 bool do_heap_region(HeapRegion* r) { 2877 if (r->is_empty()) { 2878 assert(r->rem_set()->is_empty(), "Empty regions should have empty remembered sets."); 2879 // Add free regions to the free list 2880 r->set_free(); 2881 _hrm->insert_into_free_list(r); 2882 } else if (!_free_list_only) { 2883 assert(r->rem_set()->is_empty(), "At this point remembered sets must have been cleared."); 2884 2885 if (r->is_humongous()) { 2886 _humongous_set->add(r); 2887 } else { 2888 assert(r->is_young() || r->is_free() || r->is_old(), "invariant"); 2889 // We now move all (non-humongous, non-old) regions to old gen, 2890 // and register them as such. 2891 r->move_to_old(); 2892 _old_set->add(r); 2893 } 2894 _total_used += r->used(); 2895 } 2896 2897 return false; 2898 } 2899 2900 size_t total_used() { 2901 return _total_used; 2902 } 2903 }; 2904 2905 void G1CollectedHeap::rebuild_region_sets(bool free_list_only) { 2906 assert_at_safepoint_on_vm_thread(); 2907 2908 if (!free_list_only) { 2909 _eden.clear(); 2910 _survivor.clear(); 2911 } 2912 2913 RebuildRegionSetsClosure cl(free_list_only, 2914 &_old_set, &_humongous_set, 2915 &_hrm); 2916 heap_region_iterate(&cl); 2917 2918 if (!free_list_only) { 2919 set_used(cl.total_used()); 2920 } 2921 assert_used_and_recalculate_used_equal(this); 2922 } 2923 2924 // Methods for the mutator alloc region 2925 2926 HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size, 2927 bool force, 2928 uint node_index) { 2929 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */); 2930 bool should_allocate = policy()->should_allocate_mutator_region(); 2931 if (force || should_allocate) { 2932 HeapRegion* new_alloc_region = new_region(word_size, 2933 HeapRegionType::Eden, 2934 false /* do_expand */, 2935 node_index); 2936 if (new_alloc_region != nullptr) { 2937 set_region_short_lived_locked(new_alloc_region); 2938 _hr_printer.alloc(new_alloc_region, !should_allocate); 2939 _policy->remset_tracker()->update_at_allocate(new_alloc_region); 2940 return new_alloc_region; 2941 } 2942 } 2943 return nullptr; 2944 } 2945 2946 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region, 2947 size_t allocated_bytes) { 2948 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */); 2949 assert(alloc_region->is_eden(), "all mutator alloc regions should be eden"); 2950 2951 collection_set()->add_eden_region(alloc_region); 2952 increase_used(allocated_bytes); 2953 _eden.add_used_bytes(allocated_bytes); 2954 _hr_printer.retire(alloc_region); 2955 2956 // We update the eden sizes here, when the region is retired, 2957 // instead of when it's allocated, since this is the point that its 2958 // used space has been recorded in _summary_bytes_used. 2959 monitoring_support()->update_eden_size(); 2960 } 2961 2962 // Methods for the GC alloc regions 2963 2964 bool G1CollectedHeap::has_more_regions(G1HeapRegionAttr dest) { 2965 if (dest.is_old()) { 2966 return true; 2967 } else { 2968 return survivor_regions_count() < policy()->max_survivor_regions(); 2969 } 2970 } 2971 2972 HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size, G1HeapRegionAttr dest, uint node_index) { 2973 assert(FreeList_lock->owned_by_self(), "pre-condition"); 2974 2975 if (!has_more_regions(dest)) { 2976 return nullptr; 2977 } 2978 2979 HeapRegionType type; 2980 if (dest.is_young()) { 2981 type = HeapRegionType::Survivor; 2982 } else { 2983 type = HeapRegionType::Old; 2984 } 2985 2986 HeapRegion* new_alloc_region = new_region(word_size, 2987 type, 2988 true /* do_expand */, 2989 node_index); 2990 2991 if (new_alloc_region != nullptr) { 2992 if (type.is_survivor()) { 2993 new_alloc_region->set_survivor(); 2994 _survivor.add(new_alloc_region); 2995 register_new_survivor_region_with_region_attr(new_alloc_region); 2996 } else { 2997 new_alloc_region->set_old(); 2998 } 2999 _policy->remset_tracker()->update_at_allocate(new_alloc_region); 3000 register_region_with_region_attr(new_alloc_region); 3001 _hr_printer.alloc(new_alloc_region); 3002 return new_alloc_region; 3003 } 3004 return nullptr; 3005 } 3006 3007 void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region, 3008 size_t allocated_bytes, 3009 G1HeapRegionAttr dest) { 3010 _bytes_used_during_gc += allocated_bytes; 3011 if (dest.is_old()) { 3012 old_set_add(alloc_region); 3013 } else { 3014 assert(dest.is_young(), "Retiring alloc region should be young (%d)", dest.type()); 3015 _survivor.add_used_bytes(allocated_bytes); 3016 } 3017 3018 bool const during_im = collector_state()->in_concurrent_start_gc(); 3019 if (during_im && allocated_bytes > 0) { 3020 _cm->add_root_region(alloc_region); 3021 } 3022 _hr_printer.retire(alloc_region); 3023 } 3024 3025 HeapRegion* G1CollectedHeap::alloc_highest_free_region() { 3026 bool expanded = false; 3027 uint index = _hrm.find_highest_free(&expanded); 3028 3029 if (index != G1_NO_HRM_INDEX) { 3030 if (expanded) { 3031 log_debug(gc, ergo, heap)("Attempt heap expansion (requested address range outside heap bounds). region size: " SIZE_FORMAT "B", 3032 HeapRegion::GrainWords * HeapWordSize); 3033 } 3034 return _hrm.allocate_free_regions_starting_at(index, 1); 3035 } 3036 return nullptr; 3037 } 3038 3039 void G1CollectedHeap::mark_evac_failure_object(uint worker_id, const oop obj, size_t obj_size) const { 3040 assert(!_cm->is_marked_in_bitmap(obj), "must be"); 3041 3042 _cm->raw_mark_in_bitmap(obj); 3043 if (collector_state()->in_concurrent_start_gc()) { 3044 _cm->add_to_liveness(worker_id, obj, obj_size); 3045 } 3046 } 3047 3048 // Optimized nmethod scanning 3049 class RegisterNMethodOopClosure: public OopClosure { 3050 G1CollectedHeap* _g1h; 3051 nmethod* _nm; 3052 3053 public: 3054 RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) : 3055 _g1h(g1h), _nm(nm) {} 3056 3057 void do_oop(oop* p) { 3058 oop heap_oop = RawAccess<>::oop_load(p); 3059 if (!CompressedOops::is_null(heap_oop)) { 3060 oop obj = CompressedOops::decode_not_null(heap_oop); 3061 HeapRegion* hr = _g1h->heap_region_containing(obj); 3062 assert(!hr->is_continues_humongous(), 3063 "trying to add code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT 3064 " starting at " HR_FORMAT, 3065 p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())); 3066 3067 hr->add_code_root(_nm); 3068 } 3069 } 3070 3071 void do_oop(narrowOop* p) { ShouldNotReachHere(); } 3072 }; 3073 3074 void G1CollectedHeap::register_nmethod(nmethod* nm) { 3075 guarantee(nm != nullptr, "sanity"); 3076 RegisterNMethodOopClosure reg_cl(this, nm); 3077 nm->oops_do(®_cl); 3078 } 3079 3080 void G1CollectedHeap::unregister_nmethod(nmethod* nm) { 3081 // We always unregister nmethods in bulk during code unloading only. 3082 ShouldNotReachHere(); 3083 } 3084 3085 void G1CollectedHeap::update_used_after_gc(bool evacuation_failed) { 3086 if (evacuation_failed) { 3087 // Reset the G1EvacuationFailureALot counters and flags 3088 evac_failure_injector()->reset(); 3089 3090 set_used(recalculate_used()); 3091 } else { 3092 // The "used" of the collection set have already been subtracted 3093 // when they were freed. Add in the bytes used. 3094 increase_used(_bytes_used_during_gc); 3095 } 3096 } 3097 3098 class RebuildCodeRootClosure: public CodeBlobClosure { 3099 G1CollectedHeap* _g1h; 3100 3101 public: 3102 RebuildCodeRootClosure(G1CollectedHeap* g1h) : 3103 _g1h(g1h) {} 3104 3105 void do_code_blob(CodeBlob* cb) { 3106 nmethod* nm = cb->as_nmethod_or_null(); 3107 if (nm != nullptr) { 3108 _g1h->register_nmethod(nm); 3109 } 3110 } 3111 }; 3112 3113 void G1CollectedHeap::rebuild_code_roots() { 3114 RebuildCodeRootClosure blob_cl(this); 3115 CodeCache::blobs_do(&blob_cl); 3116 } 3117 3118 void G1CollectedHeap::initialize_serviceability() { 3119 _monitoring_support->initialize_serviceability(); 3120 } 3121 3122 MemoryUsage G1CollectedHeap::memory_usage() { 3123 return _monitoring_support->memory_usage(); 3124 } 3125 3126 GrowableArray<GCMemoryManager*> G1CollectedHeap::memory_managers() { 3127 return _monitoring_support->memory_managers(); 3128 } 3129 3130 GrowableArray<MemoryPool*> G1CollectedHeap::memory_pools() { 3131 return _monitoring_support->memory_pools(); 3132 } 3133 3134 void G1CollectedHeap::fill_with_dummy_object(HeapWord* start, HeapWord* end, bool zap) { 3135 HeapRegion* region = heap_region_containing(start); 3136 region->fill_with_dummy_object(start, pointer_delta(end, start), zap); 3137 } 3138 3139 void G1CollectedHeap::start_codecache_marking_cycle_if_inactive(bool concurrent_mark_start) { 3140 // We can reach here with an active code cache marking cycle either because the 3141 // previous G1 concurrent marking cycle was undone (if heap occupancy after the 3142 // concurrent start young collection was below the threshold) or aborted. See 3143 // CodeCache::on_gc_marking_cycle_finish() why this is. We must not start a new code 3144 // cache cycle then. If we are about to start a new g1 concurrent marking cycle we 3145 // still have to arm all nmethod entry barriers. They are needed for adding oop 3146 // constants to the SATB snapshot. Full GC does not need nmethods to be armed. 3147 if (!CodeCache::is_gc_marking_cycle_active()) { 3148 CodeCache::on_gc_marking_cycle_start(); 3149 } 3150 if (concurrent_mark_start) { 3151 CodeCache::arm_all_nmethods(); 3152 } 3153 } 3154 3155 void G1CollectedHeap::finish_codecache_marking_cycle() { 3156 CodeCache::on_gc_marking_cycle_finish(); 3157 CodeCache::arm_all_nmethods(); 3158 }