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