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