1 /* 2 * Copyright (c) 2001, 2020, 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 "gc/g1/g1Allocator.inline.hpp" 32 #include "gc/g1/g1Arguments.hpp" 33 #include "gc/g1/g1BarrierSet.hpp" 34 #include "gc/g1/g1CardTableEntryClosure.hpp" 35 #include "gc/g1/g1CollectedHeap.inline.hpp" 36 #include "gc/g1/g1CollectionSet.hpp" 37 #include "gc/g1/g1CollectorState.hpp" 38 #include "gc/g1/g1ConcurrentRefine.hpp" 39 #include "gc/g1/g1ConcurrentRefineThread.hpp" 40 #include "gc/g1/g1ConcurrentMarkThread.inline.hpp" 41 #include "gc/g1/g1DirtyCardQueue.hpp" 42 #include "gc/g1/g1EvacStats.inline.hpp" 43 #include "gc/g1/g1FullCollector.hpp" 44 #include "gc/g1/g1GCParPhaseTimesTracker.hpp" 45 #include "gc/g1/g1GCPhaseTimes.hpp" 46 #include "gc/g1/g1HeapSizingPolicy.hpp" 47 #include "gc/g1/g1HeapTransition.hpp" 48 #include "gc/g1/g1HeapVerifier.hpp" 49 #include "gc/g1/g1HotCardCache.hpp" 50 #include "gc/g1/g1InitLogger.hpp" 51 #include "gc/g1/g1MemoryPool.hpp" 52 #include "gc/g1/g1OopClosures.inline.hpp" 53 #include "gc/g1/g1ParallelCleaning.hpp" 54 #include "gc/g1/g1ParScanThreadState.inline.hpp" 55 #include "gc/g1/g1Policy.hpp" 56 #include "gc/g1/g1RedirtyCardsQueue.hpp" 57 #include "gc/g1/g1RegionToSpaceMapper.hpp" 58 #include "gc/g1/g1RemSet.hpp" 59 #include "gc/g1/g1RootClosures.hpp" 60 #include "gc/g1/g1RootProcessor.hpp" 61 #include "gc/g1/g1SATBMarkQueueSet.hpp" 62 #include "gc/g1/g1StringDedup.hpp" 63 #include "gc/g1/g1ThreadLocalData.hpp" 64 #include "gc/g1/g1Trace.hpp" 65 #include "gc/g1/g1YCTypes.hpp" 66 #include "gc/g1/g1ServiceThread.hpp" 67 #include "gc/g1/g1VMOperations.hpp" 68 #include "gc/g1/heapRegion.inline.hpp" 69 #include "gc/g1/heapRegionRemSet.hpp" 70 #include "gc/g1/heapRegionSet.inline.hpp" 71 #include "gc/shared/concurrentGCBreakpoints.hpp" 72 #include "gc/shared/gcBehaviours.hpp" 73 #include "gc/shared/gcHeapSummary.hpp" 74 #include "gc/shared/gcId.hpp" 75 #include "gc/shared/gcLocker.hpp" 76 #include "gc/shared/gcTimer.hpp" 77 #include "gc/shared/gcTraceTime.inline.hpp" 78 #include "gc/shared/generationSpec.hpp" 79 #include "gc/shared/isGCActiveMark.hpp" 80 #include "gc/shared/locationPrinter.inline.hpp" 81 #include "gc/shared/oopStorageParState.hpp" 82 #include "gc/shared/preservedMarks.inline.hpp" 83 #include "gc/shared/suspendibleThreadSet.hpp" 84 #include "gc/shared/referenceProcessor.inline.hpp" 85 #include "gc/shared/taskTerminator.hpp" 86 #include "gc/shared/taskqueue.inline.hpp" 87 #include "gc/shared/weakProcessor.inline.hpp" 88 #include "gc/shared/workerPolicy.hpp" 89 #include "logging/log.hpp" 90 #include "memory/allocation.hpp" 91 #include "memory/iterator.hpp" 92 #include "memory/heapInspection.hpp" 93 #include "memory/resourceArea.hpp" 94 #include "memory/universe.hpp" 95 #include "oops/access.inline.hpp" 96 #include "oops/compressedOops.inline.hpp" 97 #include "oops/oop.inline.hpp" 98 #include "runtime/atomic.hpp" 99 #include "runtime/handles.inline.hpp" 100 #include "runtime/init.hpp" 101 #include "runtime/orderAccess.hpp" 102 #include "runtime/threadSMR.hpp" 103 #include "runtime/vmThread.hpp" 104 #include "utilities/align.hpp" 105 #include "utilities/autoRestore.hpp" 106 #include "utilities/bitMap.inline.hpp" 107 #include "utilities/globalDefinitions.hpp" 108 #include "utilities/stack.inline.hpp" 109 110 size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0; 111 112 // INVARIANTS/NOTES 113 // 114 // All allocation activity covered by the G1CollectedHeap interface is 115 // serialized by acquiring the HeapLock. This happens in mem_allocate 116 // and allocate_new_tlab, which are the "entry" points to the 117 // allocation code from the rest of the JVM. (Note that this does not 118 // apply to TLAB allocation, which is not part of this interface: it 119 // is done by clients of this interface.) 120 121 class RedirtyLoggedCardTableEntryClosure : public G1CardTableEntryClosure { 122 private: 123 size_t _num_dirtied; 124 G1CollectedHeap* _g1h; 125 G1CardTable* _g1_ct; 126 127 HeapRegion* region_for_card(CardValue* card_ptr) const { 128 return _g1h->heap_region_containing(_g1_ct->addr_for(card_ptr)); 129 } 130 131 bool will_become_free(HeapRegion* hr) const { 132 // A region will be freed by free_collection_set if the region is in the 133 // collection set and has not had an evacuation failure. 134 return _g1h->is_in_cset(hr) && !hr->evacuation_failed(); 135 } 136 137 public: 138 RedirtyLoggedCardTableEntryClosure(G1CollectedHeap* g1h) : G1CardTableEntryClosure(), 139 _num_dirtied(0), _g1h(g1h), _g1_ct(g1h->card_table()) { } 140 141 void do_card_ptr(CardValue* card_ptr, uint worker_id) { 142 HeapRegion* hr = region_for_card(card_ptr); 143 144 // Should only dirty cards in regions that won't be freed. 145 if (!will_become_free(hr)) { 146 *card_ptr = G1CardTable::dirty_card_val(); 147 _num_dirtied++; 148 } 149 } 150 151 size_t num_dirtied() const { return _num_dirtied; } 152 }; 153 154 155 void G1RegionMappingChangedListener::reset_from_card_cache(uint start_idx, size_t num_regions) { 156 HeapRegionRemSet::invalidate_from_card_cache(start_idx, num_regions); 157 } 158 159 void G1RegionMappingChangedListener::on_commit(uint start_idx, size_t num_regions, bool zero_filled) { 160 // The from card cache is not the memory that is actually committed. So we cannot 161 // take advantage of the zero_filled parameter. 162 reset_from_card_cache(start_idx, num_regions); 163 } 164 165 Tickspan G1CollectedHeap::run_task_timed(AbstractGangTask* task) { 166 Ticks start = Ticks::now(); 167 workers()->run_task(task); 168 return Ticks::now() - start; 169 } 170 171 HeapRegion* G1CollectedHeap::new_heap_region(uint hrs_index, 172 MemRegion mr) { 173 return new HeapRegion(hrs_index, bot(), mr); 174 } 175 176 // Private methods. 177 178 HeapRegion* G1CollectedHeap::new_region(size_t word_size, 179 HeapRegionType type, 180 bool do_expand, 181 uint node_index) { 182 assert(!is_humongous(word_size) || word_size <= HeapRegion::GrainWords, 183 "the only time we use this to allocate a humongous region is " 184 "when we are allocating a single humongous region"); 185 186 HeapRegion* res = _hrm->allocate_free_region(type, node_index); 187 188 if (res == NULL && do_expand && _expand_heap_after_alloc_failure) { 189 // Currently, only attempts to allocate GC alloc regions set 190 // do_expand to true. So, we should only reach here during a 191 // safepoint. If this assumption changes we might have to 192 // reconsider the use of _expand_heap_after_alloc_failure. 193 assert(SafepointSynchronize::is_at_safepoint(), "invariant"); 194 195 log_debug(gc, ergo, heap)("Attempt heap expansion (region allocation request failed). Allocation request: " SIZE_FORMAT "B", 196 word_size * HeapWordSize); 197 198 assert(word_size * HeapWordSize < HeapRegion::GrainBytes, 199 "This kind of expansion should never be more than one region. Size: " SIZE_FORMAT, 200 word_size * HeapWordSize); 201 if (expand_single_region(node_index)) { 202 // Given that expand_single_region() succeeded in expanding the heap, and we 203 // always expand the heap by an amount aligned to the heap 204 // region size, the free list should in theory not be empty. 205 // In either case allocate_free_region() will check for NULL. 206 res = _hrm->allocate_free_region(type, node_index); 207 } else { 208 _expand_heap_after_alloc_failure = false; 209 } 210 } 211 return res; 212 } 213 214 HeapWord* 215 G1CollectedHeap::humongous_obj_allocate_initialize_regions(HeapRegion* first_hr, 216 uint num_regions, 217 size_t word_size) { 218 assert(first_hr != NULL, "pre-condition"); 219 assert(is_humongous(word_size), "word_size should be humongous"); 220 assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition"); 221 222 // Index of last region in the series. 223 uint first = first_hr->hrm_index(); 224 uint last = first + num_regions - 1; 225 226 // We need to initialize the region(s) we just discovered. This is 227 // a bit tricky given that it can happen concurrently with 228 // refinement threads refining cards on these regions and 229 // potentially wanting to refine the BOT as they are scanning 230 // those cards (this can happen shortly after a cleanup; see CR 231 // 6991377). So we have to set up the region(s) carefully and in 232 // a specific order. 233 234 // The word size sum of all the regions we will allocate. 235 size_t word_size_sum = (size_t) num_regions * HeapRegion::GrainWords; 236 assert(word_size <= word_size_sum, "sanity"); 237 238 // The passed in hr will be the "starts humongous" region. The header 239 // of the new object will be placed at the bottom of this region. 240 HeapWord* new_obj = first_hr->bottom(); 241 // This will be the new top of the new object. 242 HeapWord* obj_top = new_obj + word_size; 243 244 // First, we need to zero the header of the space that we will be 245 // allocating. When we update top further down, some refinement 246 // threads might try to scan the region. By zeroing the header we 247 // ensure that any thread that will try to scan the region will 248 // come across the zero klass word and bail out. 249 // 250 // NOTE: It would not have been correct to have used 251 // CollectedHeap::fill_with_object() and make the space look like 252 // an int array. The thread that is doing the allocation will 253 // later update the object header to a potentially different array 254 // type and, for a very short period of time, the klass and length 255 // fields will be inconsistent. This could cause a refinement 256 // thread to calculate the object size incorrectly. 257 Copy::fill_to_words(new_obj, oopDesc::header_size(), 0); 258 259 // Next, pad out the unused tail of the last region with filler 260 // objects, for improved usage accounting. 261 // How many words we use for filler objects. 262 size_t word_fill_size = word_size_sum - word_size; 263 264 // How many words memory we "waste" which cannot hold a filler object. 265 size_t words_not_fillable = 0; 266 267 if (word_fill_size >= min_fill_size()) { 268 fill_with_objects(obj_top, word_fill_size); 269 } else if (word_fill_size > 0) { 270 // We have space to fill, but we cannot fit an object there. 271 words_not_fillable = word_fill_size; 272 word_fill_size = 0; 273 } 274 275 // We will set up the first region as "starts humongous". This 276 // will also update the BOT covering all the regions to reflect 277 // that there is a single object that starts at the bottom of the 278 // first region. 279 first_hr->set_starts_humongous(obj_top, word_fill_size); 280 _policy->remset_tracker()->update_at_allocate(first_hr); 281 // Then, if there are any, we will set up the "continues 282 // humongous" regions. 283 HeapRegion* hr = NULL; 284 for (uint i = first + 1; i <= last; ++i) { 285 hr = region_at(i); 286 hr->set_continues_humongous(first_hr); 287 _policy->remset_tracker()->update_at_allocate(hr); 288 } 289 290 // Up to this point no concurrent thread would have been able to 291 // do any scanning on any region in this series. All the top 292 // fields still point to bottom, so the intersection between 293 // [bottom,top] and [card_start,card_end] will be empty. Before we 294 // update the top fields, we'll do a storestore to make sure that 295 // no thread sees the update to top before the zeroing of the 296 // object header and the BOT initialization. 297 OrderAccess::storestore(); 298 299 // Now, we will update the top fields of the "continues humongous" 300 // regions except the last one. 301 for (uint i = first; i < last; ++i) { 302 hr = region_at(i); 303 hr->set_top(hr->end()); 304 } 305 306 hr = region_at(last); 307 // If we cannot fit a filler object, we must set top to the end 308 // of the humongous object, otherwise we cannot iterate the heap 309 // and the BOT will not be complete. 310 hr->set_top(hr->end() - words_not_fillable); 311 312 assert(hr->bottom() < obj_top && obj_top <= hr->end(), 313 "obj_top should be in last region"); 314 315 _verifier->check_bitmaps("Humongous Region Allocation", first_hr); 316 317 assert(words_not_fillable == 0 || 318 first_hr->bottom() + word_size_sum - words_not_fillable == hr->top(), 319 "Miscalculation in humongous allocation"); 320 321 increase_used((word_size_sum - words_not_fillable) * HeapWordSize); 322 323 for (uint i = first; i <= last; ++i) { 324 hr = region_at(i); 325 _humongous_set.add(hr); 326 _hr_printer.alloc(hr); 327 } 328 329 return new_obj; 330 } 331 332 size_t G1CollectedHeap::humongous_obj_size_in_regions(size_t word_size) { 333 assert(is_humongous(word_size), "Object of size " SIZE_FORMAT " must be humongous here", word_size); 334 return align_up(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords; 335 } 336 337 // If could fit into free regions w/o expansion, try. 338 // Otherwise, if can expand, do so. 339 // Otherwise, if using ex regions might help, try with ex given back. 340 HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size) { 341 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */); 342 343 _verifier->verify_region_sets_optional(); 344 345 uint obj_regions = (uint) humongous_obj_size_in_regions(word_size); 346 347 // Policy: First try to allocate a humongous object in the free list. 348 HeapRegion* humongous_start = _hrm->allocate_humongous(obj_regions); 349 if (humongous_start == NULL) { 350 // Policy: We could not find enough regions for the humongous object in the 351 // free list. Look through the heap to find a mix of free and uncommitted regions. 352 // If so, expand the heap and allocate the humongous object. 353 humongous_start = _hrm->expand_and_allocate_humongous(obj_regions); 354 if (humongous_start != NULL) { 355 // We managed to find a region by expanding the heap. 356 log_debug(gc, ergo, heap)("Heap expansion (humongous allocation request). Allocation request: " SIZE_FORMAT "B", 357 word_size * HeapWordSize); 358 policy()->record_new_heap_size(num_regions()); 359 } else { 360 // Policy: Potentially trigger a defragmentation GC. 361 } 362 } 363 364 HeapWord* result = NULL; 365 if (humongous_start != NULL) { 366 result = humongous_obj_allocate_initialize_regions(humongous_start, obj_regions, word_size); 367 assert(result != NULL, "it should always return a valid result"); 368 369 // A successful humongous object allocation changes the used space 370 // information of the old generation so we need to recalculate the 371 // sizes and update the jstat counters here. 372 g1mm()->update_sizes(); 373 } 374 375 _verifier->verify_region_sets_optional(); 376 377 return result; 378 } 379 380 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t min_size, 381 size_t requested_size, 382 size_t* actual_size) { 383 assert_heap_not_locked_and_not_at_safepoint(); 384 assert(!is_humongous(requested_size), "we do not allow humongous TLABs"); 385 386 return attempt_allocation(min_size, requested_size, actual_size); 387 } 388 389 HeapWord* 390 G1CollectedHeap::mem_allocate(size_t word_size, 391 bool* gc_overhead_limit_was_exceeded) { 392 assert_heap_not_locked_and_not_at_safepoint(); 393 394 if (is_humongous(word_size)) { 395 return attempt_allocation_humongous(word_size); 396 } 397 size_t dummy = 0; 398 return attempt_allocation(word_size, word_size, &dummy); 399 } 400 401 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size) { 402 ResourceMark rm; // For retrieving the thread names in log messages. 403 404 // Make sure you read the note in attempt_allocation_humongous(). 405 406 assert_heap_not_locked_and_not_at_safepoint(); 407 assert(!is_humongous(word_size), "attempt_allocation_slow() should not " 408 "be called for humongous allocation requests"); 409 410 // We should only get here after the first-level allocation attempt 411 // (attempt_allocation()) failed to allocate. 412 413 // We will loop until a) we manage to successfully perform the 414 // allocation or b) we successfully schedule a collection which 415 // fails to perform the allocation. b) is the only case when we'll 416 // return NULL. 417 HeapWord* result = NULL; 418 for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) { 419 bool should_try_gc; 420 uint gc_count_before; 421 422 { 423 MutexLocker x(Heap_lock); 424 result = _allocator->attempt_allocation_locked(word_size); 425 if (result != NULL) { 426 return result; 427 } 428 429 // If the GCLocker is active and we are bound for a GC, try expanding young gen. 430 // This is different to when only GCLocker::needs_gc() is set: try to avoid 431 // waiting because the GCLocker is active to not wait too long. 432 if (GCLocker::is_active_and_needs_gc() && policy()->can_expand_young_list()) { 433 // No need for an ergo message here, can_expand_young_list() does this when 434 // it returns true. 435 result = _allocator->attempt_allocation_force(word_size); 436 if (result != NULL) { 437 return result; 438 } 439 } 440 // Only try a GC if the GCLocker does not signal the need for a GC. Wait until 441 // the GCLocker initiated GC has been performed and then retry. This includes 442 // the case when the GC Locker is not active but has not been performed. 443 should_try_gc = !GCLocker::needs_gc(); 444 // Read the GC count while still holding the Heap_lock. 445 gc_count_before = total_collections(); 446 } 447 448 if (should_try_gc) { 449 bool succeeded; 450 result = do_collection_pause(word_size, gc_count_before, &succeeded, 451 GCCause::_g1_inc_collection_pause); 452 if (result != NULL) { 453 assert(succeeded, "only way to get back a non-NULL result"); 454 log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT, 455 Thread::current()->name(), p2i(result)); 456 return result; 457 } 458 459 if (succeeded) { 460 // We successfully scheduled a collection which failed to allocate. No 461 // point in trying to allocate further. We'll just return NULL. 462 log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate " 463 SIZE_FORMAT " words", Thread::current()->name(), word_size); 464 return NULL; 465 } 466 log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT " words", 467 Thread::current()->name(), word_size); 468 } else { 469 // Failed to schedule a collection. 470 if (gclocker_retry_count > GCLockerRetryAllocationCount) { 471 log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating " 472 SIZE_FORMAT " words", Thread::current()->name(), word_size); 473 return NULL; 474 } 475 log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name()); 476 // The GCLocker is either active or the GCLocker initiated 477 // GC has not yet been performed. Stall until it is and 478 // then retry the allocation. 479 GCLocker::stall_until_clear(); 480 gclocker_retry_count += 1; 481 } 482 483 // We can reach here if we were unsuccessful in scheduling a 484 // collection (because another thread beat us to it) or if we were 485 // stalled due to the GC locker. In either can we should retry the 486 // allocation attempt in case another thread successfully 487 // performed a collection and reclaimed enough space. We do the 488 // first attempt (without holding the Heap_lock) here and the 489 // follow-on attempt will be at the start of the next loop 490 // iteration (after taking the Heap_lock). 491 size_t dummy = 0; 492 result = _allocator->attempt_allocation(word_size, word_size, &dummy); 493 if (result != NULL) { 494 return result; 495 } 496 497 // Give a warning if we seem to be looping forever. 498 if ((QueuedAllocationWarningCount > 0) && 499 (try_count % QueuedAllocationWarningCount == 0)) { 500 log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words", 501 Thread::current()->name(), try_count, word_size); 502 } 503 } 504 505 ShouldNotReachHere(); 506 return NULL; 507 } 508 509 void G1CollectedHeap::begin_archive_alloc_range(bool open) { 510 assert_at_safepoint_on_vm_thread(); 511 if (_archive_allocator == NULL) { 512 _archive_allocator = G1ArchiveAllocator::create_allocator(this, open); 513 } 514 } 515 516 bool G1CollectedHeap::is_archive_alloc_too_large(size_t word_size) { 517 // Allocations in archive regions cannot be of a size that would be considered 518 // humongous even for a minimum-sized region, because G1 region sizes/boundaries 519 // may be different at archive-restore time. 520 return word_size >= humongous_threshold_for(HeapRegion::min_region_size_in_words()); 521 } 522 523 HeapWord* G1CollectedHeap::archive_mem_allocate(size_t word_size) { 524 assert_at_safepoint_on_vm_thread(); 525 assert(_archive_allocator != NULL, "_archive_allocator not initialized"); 526 if (is_archive_alloc_too_large(word_size)) { 527 return NULL; 528 } 529 return _archive_allocator->archive_mem_allocate(word_size); 530 } 531 532 void G1CollectedHeap::end_archive_alloc_range(GrowableArray<MemRegion>* ranges, 533 size_t end_alignment_in_bytes) { 534 assert_at_safepoint_on_vm_thread(); 535 assert(_archive_allocator != NULL, "_archive_allocator not initialized"); 536 537 // Call complete_archive to do the real work, filling in the MemRegion 538 // array with the archive regions. 539 _archive_allocator->complete_archive(ranges, end_alignment_in_bytes); 540 delete _archive_allocator; 541 _archive_allocator = NULL; 542 } 543 544 bool G1CollectedHeap::check_archive_addresses(MemRegion* ranges, size_t count) { 545 assert(ranges != NULL, "MemRegion array NULL"); 546 assert(count != 0, "No MemRegions provided"); 547 MemRegion reserved = _hrm->reserved(); 548 for (size_t i = 0; i < count; i++) { 549 if (!reserved.contains(ranges[i].start()) || !reserved.contains(ranges[i].last())) { 550 return false; 551 } 552 } 553 return true; 554 } 555 556 bool G1CollectedHeap::alloc_archive_regions(MemRegion* ranges, 557 size_t count, 558 bool open) { 559 assert(!is_init_completed(), "Expect to be called at JVM init time"); 560 assert(ranges != NULL, "MemRegion array NULL"); 561 assert(count != 0, "No MemRegions provided"); 562 MutexLocker x(Heap_lock); 563 564 MemRegion reserved = _hrm->reserved(); 565 HeapWord* prev_last_addr = NULL; 566 HeapRegion* prev_last_region = NULL; 567 568 // Temporarily disable pretouching of heap pages. This interface is used 569 // when mmap'ing archived heap data in, so pre-touching is wasted. 570 FlagSetting fs(AlwaysPreTouch, false); 571 572 // Enable archive object checking used by G1MarkSweep. We have to let it know 573 // about each archive range, so that objects in those ranges aren't marked. 574 G1ArchiveAllocator::enable_archive_object_check(); 575 576 // For each specified MemRegion range, allocate the corresponding G1 577 // regions and mark them as archive regions. We expect the ranges 578 // in ascending starting address order, without overlap. 579 for (size_t i = 0; i < count; i++) { 580 MemRegion curr_range = ranges[i]; 581 HeapWord* start_address = curr_range.start(); 582 size_t word_size = curr_range.word_size(); 583 HeapWord* last_address = curr_range.last(); 584 size_t commits = 0; 585 586 guarantee(reserved.contains(start_address) && reserved.contains(last_address), 587 "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]", 588 p2i(start_address), p2i(last_address)); 589 guarantee(start_address > prev_last_addr, 590 "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT , 591 p2i(start_address), p2i(prev_last_addr)); 592 prev_last_addr = last_address; 593 594 // Check for ranges that start in the same G1 region in which the previous 595 // range ended, and adjust the start address so we don't try to allocate 596 // the same region again. If the current range is entirely within that 597 // region, skip it, just adjusting the recorded top. 598 HeapRegion* start_region = _hrm->addr_to_region(start_address); 599 if ((prev_last_region != NULL) && (start_region == prev_last_region)) { 600 start_address = start_region->end(); 601 if (start_address > last_address) { 602 increase_used(word_size * HeapWordSize); 603 start_region->set_top(last_address + 1); 604 continue; 605 } 606 start_region->set_top(start_address); 607 curr_range = MemRegion(start_address, last_address + 1); 608 start_region = _hrm->addr_to_region(start_address); 609 } 610 611 // Perform the actual region allocation, exiting if it fails. 612 // Then note how much new space we have allocated. 613 if (!_hrm->allocate_containing_regions(curr_range, &commits, workers())) { 614 return false; 615 } 616 increase_used(word_size * HeapWordSize); 617 if (commits != 0) { 618 log_debug(gc, ergo, heap)("Attempt heap expansion (allocate archive regions). Total size: " SIZE_FORMAT "B", 619 HeapRegion::GrainWords * HeapWordSize * commits); 620 621 } 622 623 // Mark each G1 region touched by the range as archive, add it to 624 // the old set, and set top. 625 HeapRegion* curr_region = _hrm->addr_to_region(start_address); 626 HeapRegion* last_region = _hrm->addr_to_region(last_address); 627 prev_last_region = last_region; 628 629 while (curr_region != NULL) { 630 assert(curr_region->is_empty() && !curr_region->is_pinned(), 631 "Region already in use (index %u)", curr_region->hrm_index()); 632 if (open) { 633 curr_region->set_open_archive(); 634 } else { 635 curr_region->set_closed_archive(); 636 } 637 _hr_printer.alloc(curr_region); 638 _archive_set.add(curr_region); 639 HeapWord* top; 640 HeapRegion* next_region; 641 if (curr_region != last_region) { 642 top = curr_region->end(); 643 next_region = _hrm->next_region_in_heap(curr_region); 644 } else { 645 top = last_address + 1; 646 next_region = NULL; 647 } 648 curr_region->set_top(top); 649 curr_region = next_region; 650 } 651 652 // Notify mark-sweep of the archive 653 G1ArchiveAllocator::set_range_archive(curr_range, open); 654 } 655 return true; 656 } 657 658 void G1CollectedHeap::fill_archive_regions(MemRegion* ranges, size_t count) { 659 assert(!is_init_completed(), "Expect to be called at JVM init time"); 660 assert(ranges != NULL, "MemRegion array NULL"); 661 assert(count != 0, "No MemRegions provided"); 662 MemRegion reserved = _hrm->reserved(); 663 HeapWord *prev_last_addr = NULL; 664 HeapRegion* prev_last_region = NULL; 665 666 // For each MemRegion, create filler objects, if needed, in the G1 regions 667 // that contain the address range. The address range actually within the 668 // MemRegion will not be modified. That is assumed to have been initialized 669 // elsewhere, probably via an mmap of archived heap data. 670 MutexLocker x(Heap_lock); 671 for (size_t i = 0; i < count; i++) { 672 HeapWord* start_address = ranges[i].start(); 673 HeapWord* last_address = ranges[i].last(); 674 675 assert(reserved.contains(start_address) && reserved.contains(last_address), 676 "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]", 677 p2i(start_address), p2i(last_address)); 678 assert(start_address > prev_last_addr, 679 "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT , 680 p2i(start_address), p2i(prev_last_addr)); 681 682 HeapRegion* start_region = _hrm->addr_to_region(start_address); 683 HeapRegion* last_region = _hrm->addr_to_region(last_address); 684 HeapWord* bottom_address = start_region->bottom(); 685 686 // Check for a range beginning in the same region in which the 687 // previous one ended. 688 if (start_region == prev_last_region) { 689 bottom_address = prev_last_addr + 1; 690 } 691 692 // Verify that the regions were all marked as archive regions by 693 // alloc_archive_regions. 694 HeapRegion* curr_region = start_region; 695 while (curr_region != NULL) { 696 guarantee(curr_region->is_archive(), 697 "Expected archive region at index %u", curr_region->hrm_index()); 698 if (curr_region != last_region) { 699 curr_region = _hrm->next_region_in_heap(curr_region); 700 } else { 701 curr_region = NULL; 702 } 703 } 704 705 prev_last_addr = last_address; 706 prev_last_region = last_region; 707 708 // Fill the memory below the allocated range with dummy object(s), 709 // if the region bottom does not match the range start, or if the previous 710 // range ended within the same G1 region, and there is a gap. 711 if (start_address != bottom_address) { 712 size_t fill_size = pointer_delta(start_address, bottom_address); 713 G1CollectedHeap::fill_with_objects(bottom_address, fill_size); 714 increase_used(fill_size * HeapWordSize); 715 } 716 } 717 } 718 719 inline HeapWord* G1CollectedHeap::attempt_allocation(size_t min_word_size, 720 size_t desired_word_size, 721 size_t* actual_word_size) { 722 assert_heap_not_locked_and_not_at_safepoint(); 723 assert(!is_humongous(desired_word_size), "attempt_allocation() should not " 724 "be called for humongous allocation requests"); 725 726 HeapWord* result = _allocator->attempt_allocation(min_word_size, desired_word_size, actual_word_size); 727 728 if (result == NULL) { 729 *actual_word_size = desired_word_size; 730 result = attempt_allocation_slow(desired_word_size); 731 } 732 733 assert_heap_not_locked(); 734 if (result != NULL) { 735 assert(*actual_word_size != 0, "Actual size must have been set here"); 736 dirty_young_block(result, *actual_word_size); 737 } else { 738 *actual_word_size = 0; 739 } 740 741 return result; 742 } 743 744 void G1CollectedHeap::dealloc_archive_regions(MemRegion* ranges, size_t count) { 745 assert(!is_init_completed(), "Expect to be called at JVM init time"); 746 assert(ranges != NULL, "MemRegion array NULL"); 747 assert(count != 0, "No MemRegions provided"); 748 MemRegion reserved = _hrm->reserved(); 749 HeapWord* prev_last_addr = NULL; 750 HeapRegion* prev_last_region = NULL; 751 size_t size_used = 0; 752 size_t uncommitted_regions = 0; 753 754 // For each Memregion, free the G1 regions that constitute it, and 755 // notify mark-sweep that the range is no longer to be considered 'archive.' 756 MutexLocker x(Heap_lock); 757 for (size_t i = 0; i < count; i++) { 758 HeapWord* start_address = ranges[i].start(); 759 HeapWord* last_address = ranges[i].last(); 760 761 assert(reserved.contains(start_address) && reserved.contains(last_address), 762 "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]", 763 p2i(start_address), p2i(last_address)); 764 assert(start_address > prev_last_addr, 765 "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT , 766 p2i(start_address), p2i(prev_last_addr)); 767 size_used += ranges[i].byte_size(); 768 prev_last_addr = last_address; 769 770 HeapRegion* start_region = _hrm->addr_to_region(start_address); 771 HeapRegion* last_region = _hrm->addr_to_region(last_address); 772 773 // Check for ranges that start in the same G1 region in which the previous 774 // range ended, and adjust the start address so we don't try to free 775 // the same region again. If the current range is entirely within that 776 // region, skip it. 777 if (start_region == prev_last_region) { 778 start_address = start_region->end(); 779 if (start_address > last_address) { 780 continue; 781 } 782 start_region = _hrm->addr_to_region(start_address); 783 } 784 prev_last_region = last_region; 785 786 // After verifying that each region was marked as an archive region by 787 // alloc_archive_regions, set it free and empty and uncommit it. 788 HeapRegion* curr_region = start_region; 789 while (curr_region != NULL) { 790 guarantee(curr_region->is_archive(), 791 "Expected archive region at index %u", curr_region->hrm_index()); 792 uint curr_index = curr_region->hrm_index(); 793 _archive_set.remove(curr_region); 794 curr_region->set_free(); 795 curr_region->set_top(curr_region->bottom()); 796 if (curr_region != last_region) { 797 curr_region = _hrm->next_region_in_heap(curr_region); 798 } else { 799 curr_region = NULL; 800 } 801 _hrm->shrink_at(curr_index, 1); 802 uncommitted_regions++; 803 } 804 805 // Notify mark-sweep that this is no longer an archive range. 806 G1ArchiveAllocator::clear_range_archive(ranges[i]); 807 } 808 809 if (uncommitted_regions != 0) { 810 log_debug(gc, ergo, heap)("Attempt heap shrinking (uncommitted archive regions). Total size: " SIZE_FORMAT "B", 811 HeapRegion::GrainWords * HeapWordSize * uncommitted_regions); 812 } 813 decrease_used(size_used); 814 } 815 816 oop G1CollectedHeap::materialize_archived_object(oop obj) { 817 assert(obj != NULL, "archived obj is NULL"); 818 assert(G1ArchiveAllocator::is_archived_object(obj), "must be archived object"); 819 820 // Loading an archived object makes it strongly reachable. If it is 821 // loaded during concurrent marking, it must be enqueued to the SATB 822 // queue, shading the previously white object gray. 823 G1BarrierSet::enqueue(obj); 824 825 return obj; 826 } 827 828 HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size) { 829 ResourceMark rm; // For retrieving the thread names in log messages. 830 831 // The structure of this method has a lot of similarities to 832 // attempt_allocation_slow(). The reason these two were not merged 833 // into a single one is that such a method would require several "if 834 // allocation is not humongous do this, otherwise do that" 835 // conditional paths which would obscure its flow. In fact, an early 836 // version of this code did use a unified method which was harder to 837 // follow and, as a result, it had subtle bugs that were hard to 838 // track down. So keeping these two methods separate allows each to 839 // be more readable. It will be good to keep these two in sync as 840 // much as possible. 841 842 assert_heap_not_locked_and_not_at_safepoint(); 843 assert(is_humongous(word_size), "attempt_allocation_humongous() " 844 "should only be called for humongous allocations"); 845 846 // Humongous objects can exhaust the heap quickly, so we should check if we 847 // need to start a marking cycle at each humongous object allocation. We do 848 // the check before we do the actual allocation. The reason for doing it 849 // before the allocation is that we avoid having to keep track of the newly 850 // allocated memory while we do a GC. 851 if (policy()->need_to_start_conc_mark("concurrent humongous allocation", 852 word_size)) { 853 collect(GCCause::_g1_humongous_allocation); 854 } 855 856 // We will loop until a) we manage to successfully perform the 857 // allocation or b) we successfully schedule a collection which 858 // fails to perform the allocation. b) is the only case when we'll 859 // return NULL. 860 HeapWord* result = NULL; 861 for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) { 862 bool should_try_gc; 863 uint gc_count_before; 864 865 866 { 867 MutexLocker x(Heap_lock); 868 869 // Given that humongous objects are not allocated in young 870 // regions, we'll first try to do the allocation without doing a 871 // collection hoping that there's enough space in the heap. 872 result = humongous_obj_allocate(word_size); 873 if (result != NULL) { 874 size_t size_in_regions = humongous_obj_size_in_regions(word_size); 875 policy()->old_gen_alloc_tracker()-> 876 add_allocated_humongous_bytes_since_last_gc(size_in_regions * HeapRegion::GrainBytes); 877 return result; 878 } 879 880 // Only try a GC if the GCLocker does not signal the need for a GC. Wait until 881 // the GCLocker initiated GC has been performed and then retry. This includes 882 // the case when the GC Locker is not active but has not been performed. 883 should_try_gc = !GCLocker::needs_gc(); 884 // Read the GC count while still holding the Heap_lock. 885 gc_count_before = total_collections(); 886 } 887 888 if (should_try_gc) { 889 bool succeeded; 890 result = do_collection_pause(word_size, gc_count_before, &succeeded, 891 GCCause::_g1_humongous_allocation); 892 if (result != NULL) { 893 assert(succeeded, "only way to get back a non-NULL result"); 894 log_trace(gc, alloc)("%s: Successfully scheduled collection returning " PTR_FORMAT, 895 Thread::current()->name(), p2i(result)); 896 size_t size_in_regions = humongous_obj_size_in_regions(word_size); 897 policy()->old_gen_alloc_tracker()-> 898 record_collection_pause_humongous_allocation(size_in_regions * HeapRegion::GrainBytes); 899 return result; 900 } 901 902 if (succeeded) { 903 // We successfully scheduled a collection which failed to allocate. No 904 // point in trying to allocate further. We'll just return NULL. 905 log_trace(gc, alloc)("%s: Successfully scheduled collection failing to allocate " 906 SIZE_FORMAT " words", Thread::current()->name(), word_size); 907 return NULL; 908 } 909 log_trace(gc, alloc)("%s: Unsuccessfully scheduled collection allocating " SIZE_FORMAT "", 910 Thread::current()->name(), word_size); 911 } else { 912 // Failed to schedule a collection. 913 if (gclocker_retry_count > GCLockerRetryAllocationCount) { 914 log_warning(gc, alloc)("%s: Retried waiting for GCLocker too often allocating " 915 SIZE_FORMAT " words", Thread::current()->name(), word_size); 916 return NULL; 917 } 918 log_trace(gc, alloc)("%s: Stall until clear", Thread::current()->name()); 919 // The GCLocker is either active or the GCLocker initiated 920 // GC has not yet been performed. Stall until it is and 921 // then retry the allocation. 922 GCLocker::stall_until_clear(); 923 gclocker_retry_count += 1; 924 } 925 926 927 // We can reach here if we were unsuccessful in scheduling a 928 // collection (because another thread beat us to it) or if we were 929 // stalled due to the GC locker. In either can we should retry the 930 // allocation attempt in case another thread successfully 931 // performed a collection and reclaimed enough space. 932 // Humongous object allocation always needs a lock, so we wait for the retry 933 // in the next iteration of the loop, unlike for the regular iteration case. 934 // Give a warning if we seem to be looping forever. 935 936 if ((QueuedAllocationWarningCount > 0) && 937 (try_count % QueuedAllocationWarningCount == 0)) { 938 log_warning(gc, alloc)("%s: Retried allocation %u times for " SIZE_FORMAT " words", 939 Thread::current()->name(), try_count, word_size); 940 } 941 } 942 943 ShouldNotReachHere(); 944 return NULL; 945 } 946 947 HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size, 948 bool expect_null_mutator_alloc_region) { 949 assert_at_safepoint_on_vm_thread(); 950 assert(!_allocator->has_mutator_alloc_region() || !expect_null_mutator_alloc_region, 951 "the current alloc region was unexpectedly found to be non-NULL"); 952 953 if (!is_humongous(word_size)) { 954 return _allocator->attempt_allocation_locked(word_size); 955 } else { 956 HeapWord* result = humongous_obj_allocate(word_size); 957 if (result != NULL && policy()->need_to_start_conc_mark("STW humongous allocation")) { 958 collector_state()->set_initiate_conc_mark_if_possible(true); 959 } 960 return result; 961 } 962 963 ShouldNotReachHere(); 964 } 965 966 class PostCompactionPrinterClosure: public HeapRegionClosure { 967 private: 968 G1HRPrinter* _hr_printer; 969 public: 970 bool do_heap_region(HeapRegion* hr) { 971 assert(!hr->is_young(), "not expecting to find young regions"); 972 _hr_printer->post_compaction(hr); 973 return false; 974 } 975 976 PostCompactionPrinterClosure(G1HRPrinter* hr_printer) 977 : _hr_printer(hr_printer) { } 978 }; 979 980 void G1CollectedHeap::print_hrm_post_compaction() { 981 if (_hr_printer.is_active()) { 982 PostCompactionPrinterClosure cl(hr_printer()); 983 heap_region_iterate(&cl); 984 } 985 } 986 987 void G1CollectedHeap::abort_concurrent_cycle() { 988 // If we start the compaction before the CM threads finish 989 // scanning the root regions we might trip them over as we'll 990 // be moving objects / updating references. So let's wait until 991 // they are done. By telling them to abort, they should complete 992 // early. 993 _cm->root_regions()->abort(); 994 _cm->root_regions()->wait_until_scan_finished(); 995 996 // Disable discovery and empty the discovered lists 997 // for the CM ref processor. 998 _ref_processor_cm->disable_discovery(); 999 _ref_processor_cm->abandon_partial_discovery(); 1000 _ref_processor_cm->verify_no_references_recorded(); 1001 1002 // Abandon current iterations of concurrent marking and concurrent 1003 // refinement, if any are in progress. 1004 concurrent_mark()->concurrent_cycle_abort(); 1005 } 1006 1007 void G1CollectedHeap::prepare_heap_for_full_collection() { 1008 // Make sure we'll choose a new allocation region afterwards. 1009 _allocator->release_mutator_alloc_regions(); 1010 _allocator->abandon_gc_alloc_regions(); 1011 1012 // We may have added regions to the current incremental collection 1013 // set between the last GC or pause and now. We need to clear the 1014 // incremental collection set and then start rebuilding it afresh 1015 // after this full GC. 1016 abandon_collection_set(collection_set()); 1017 1018 tear_down_region_sets(false /* free_list_only */); 1019 1020 hrm()->prepare_for_full_collection_start(); 1021 } 1022 1023 void G1CollectedHeap::verify_before_full_collection(bool explicit_gc) { 1024 assert(!GCCause::is_user_requested_gc(gc_cause()) || explicit_gc, "invariant"); 1025 assert_used_and_recalculate_used_equal(this); 1026 _verifier->verify_region_sets_optional(); 1027 _verifier->verify_before_gc(G1HeapVerifier::G1VerifyFull); 1028 _verifier->check_bitmaps("Full GC Start"); 1029 } 1030 1031 void G1CollectedHeap::prepare_heap_for_mutators() { 1032 hrm()->prepare_for_full_collection_end(); 1033 1034 // Delete metaspaces for unloaded class loaders and clean up loader_data graph 1035 ClassLoaderDataGraph::purge(); 1036 MetaspaceUtils::verify_metrics(); 1037 1038 // Prepare heap for normal collections. 1039 assert(num_free_regions() == 0, "we should not have added any free regions"); 1040 rebuild_region_sets(false /* free_list_only */); 1041 abort_refinement(); 1042 resize_heap_if_necessary(); 1043 1044 // Rebuild the strong code root lists for each region 1045 rebuild_strong_code_roots(); 1046 1047 // Purge code root memory 1048 purge_code_root_memory(); 1049 1050 // Start a new incremental collection set for the next pause 1051 start_new_collection_set(); 1052 1053 _allocator->init_mutator_alloc_regions(); 1054 1055 // Post collection state updates. 1056 MetaspaceGC::compute_new_size(); 1057 } 1058 1059 void G1CollectedHeap::abort_refinement() { 1060 if (_hot_card_cache->use_cache()) { 1061 _hot_card_cache->reset_hot_cache(); 1062 } 1063 1064 // Discard all remembered set updates and reset refinement statistics. 1065 G1BarrierSet::dirty_card_queue_set().abandon_logs(); 1066 assert(G1BarrierSet::dirty_card_queue_set().num_cards() == 0, 1067 "DCQS should be empty"); 1068 concurrent_refine()->get_and_reset_refinement_stats(); 1069 } 1070 1071 void G1CollectedHeap::verify_after_full_collection() { 1072 _hrm->verify_optional(); 1073 _verifier->verify_region_sets_optional(); 1074 _verifier->verify_after_gc(G1HeapVerifier::G1VerifyFull); 1075 // Clear the previous marking bitmap, if needed for bitmap verification. 1076 // Note we cannot do this when we clear the next marking bitmap in 1077 // G1ConcurrentMark::abort() above since VerifyDuringGC verifies the 1078 // objects marked during a full GC against the previous bitmap. 1079 // But we need to clear it before calling check_bitmaps below since 1080 // the full GC has compacted objects and updated TAMS but not updated 1081 // the prev bitmap. 1082 if (G1VerifyBitmaps) { 1083 GCTraceTime(Debug, gc) tm("Clear Prev Bitmap for Verification"); 1084 _cm->clear_prev_bitmap(workers()); 1085 } 1086 // This call implicitly verifies that the next bitmap is clear after Full GC. 1087 _verifier->check_bitmaps("Full GC End"); 1088 1089 // At this point there should be no regions in the 1090 // entire heap tagged as young. 1091 assert(check_young_list_empty(), "young list should be empty at this point"); 1092 1093 // Note: since we've just done a full GC, concurrent 1094 // marking is no longer active. Therefore we need not 1095 // re-enable reference discovery for the CM ref processor. 1096 // That will be done at the start of the next marking cycle. 1097 // We also know that the STW processor should no longer 1098 // discover any new references. 1099 assert(!_ref_processor_stw->discovery_enabled(), "Postcondition"); 1100 assert(!_ref_processor_cm->discovery_enabled(), "Postcondition"); 1101 _ref_processor_stw->verify_no_references_recorded(); 1102 _ref_processor_cm->verify_no_references_recorded(); 1103 } 1104 1105 void G1CollectedHeap::print_heap_after_full_collection(G1HeapTransition* heap_transition) { 1106 // Post collection logging. 1107 // We should do this after we potentially resize the heap so 1108 // that all the COMMIT / UNCOMMIT events are generated before 1109 // the compaction events. 1110 print_hrm_post_compaction(); 1111 heap_transition->print(); 1112 print_heap_after_gc(); 1113 print_heap_regions(); 1114 } 1115 1116 bool G1CollectedHeap::do_full_collection(bool explicit_gc, 1117 bool clear_all_soft_refs) { 1118 assert_at_safepoint_on_vm_thread(); 1119 1120 if (GCLocker::check_active_before_gc()) { 1121 // Full GC was not completed. 1122 return false; 1123 } 1124 1125 const bool do_clear_all_soft_refs = clear_all_soft_refs || 1126 soft_ref_policy()->should_clear_all_soft_refs(); 1127 1128 G1FullCollector collector(this, explicit_gc, do_clear_all_soft_refs); 1129 GCTraceTime(Info, gc) tm("Pause Full", NULL, gc_cause(), true); 1130 1131 collector.prepare_collection(); 1132 collector.collect(); 1133 collector.complete_collection(); 1134 1135 // Full collection was successfully completed. 1136 return true; 1137 } 1138 1139 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) { 1140 // Currently, there is no facility in the do_full_collection(bool) API to notify 1141 // the caller that the collection did not succeed (e.g., because it was locked 1142 // out by the GC locker). So, right now, we'll ignore the return value. 1143 bool dummy = do_full_collection(true, /* explicit_gc */ 1144 clear_all_soft_refs); 1145 } 1146 1147 void G1CollectedHeap::resize_heap_if_necessary() { 1148 assert_at_safepoint_on_vm_thread(); 1149 1150 bool should_expand; 1151 size_t resize_amount = _heap_sizing_policy->full_collection_resize_amount(should_expand); 1152 1153 if (resize_amount == 0) { 1154 return; 1155 } else if (should_expand) { 1156 expand(resize_amount, _workers); 1157 } else { 1158 shrink(resize_amount); 1159 } 1160 } 1161 1162 HeapWord* G1CollectedHeap::satisfy_failed_allocation_helper(size_t word_size, 1163 bool do_gc, 1164 bool clear_all_soft_refs, 1165 bool expect_null_mutator_alloc_region, 1166 bool* gc_succeeded) { 1167 *gc_succeeded = true; 1168 // Let's attempt the allocation first. 1169 HeapWord* result = 1170 attempt_allocation_at_safepoint(word_size, 1171 expect_null_mutator_alloc_region); 1172 if (result != NULL) { 1173 return result; 1174 } 1175 1176 // In a G1 heap, we're supposed to keep allocation from failing by 1177 // incremental pauses. Therefore, at least for now, we'll favor 1178 // expansion over collection. (This might change in the future if we can 1179 // do something smarter than full collection to satisfy a failed alloc.) 1180 result = expand_and_allocate(word_size); 1181 if (result != NULL) { 1182 return result; 1183 } 1184 1185 if (do_gc) { 1186 // Expansion didn't work, we'll try to do a Full GC. 1187 *gc_succeeded = do_full_collection(false, /* explicit_gc */ 1188 clear_all_soft_refs); 1189 } 1190 1191 return NULL; 1192 } 1193 1194 HeapWord* G1CollectedHeap::satisfy_failed_allocation(size_t word_size, 1195 bool* succeeded) { 1196 assert_at_safepoint_on_vm_thread(); 1197 1198 // Attempts to allocate followed by Full GC. 1199 HeapWord* result = 1200 satisfy_failed_allocation_helper(word_size, 1201 true, /* do_gc */ 1202 false, /* clear_all_soft_refs */ 1203 false, /* expect_null_mutator_alloc_region */ 1204 succeeded); 1205 1206 if (result != NULL || !*succeeded) { 1207 return result; 1208 } 1209 1210 // Attempts to allocate followed by Full GC that will collect all soft references. 1211 result = satisfy_failed_allocation_helper(word_size, 1212 true, /* do_gc */ 1213 true, /* clear_all_soft_refs */ 1214 true, /* expect_null_mutator_alloc_region */ 1215 succeeded); 1216 1217 if (result != NULL || !*succeeded) { 1218 return result; 1219 } 1220 1221 // Attempts to allocate, no GC 1222 result = satisfy_failed_allocation_helper(word_size, 1223 false, /* do_gc */ 1224 false, /* clear_all_soft_refs */ 1225 true, /* expect_null_mutator_alloc_region */ 1226 succeeded); 1227 1228 if (result != NULL) { 1229 return result; 1230 } 1231 1232 assert(!soft_ref_policy()->should_clear_all_soft_refs(), 1233 "Flag should have been handled and cleared prior to this point"); 1234 1235 // What else? We might try synchronous finalization later. If the total 1236 // space available is large enough for the allocation, then a more 1237 // complete compaction phase than we've tried so far might be 1238 // appropriate. 1239 return NULL; 1240 } 1241 1242 // Attempting to expand the heap sufficiently 1243 // to support an allocation of the given "word_size". If 1244 // successful, perform the allocation and return the address of the 1245 // allocated block, or else "NULL". 1246 1247 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) { 1248 assert_at_safepoint_on_vm_thread(); 1249 1250 _verifier->verify_region_sets_optional(); 1251 1252 size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes); 1253 log_debug(gc, ergo, heap)("Attempt heap expansion (allocation request failed). Allocation request: " SIZE_FORMAT "B", 1254 word_size * HeapWordSize); 1255 1256 1257 if (expand(expand_bytes, _workers)) { 1258 _hrm->verify_optional(); 1259 _verifier->verify_region_sets_optional(); 1260 return attempt_allocation_at_safepoint(word_size, 1261 false /* expect_null_mutator_alloc_region */); 1262 } 1263 return NULL; 1264 } 1265 1266 bool G1CollectedHeap::expand(size_t expand_bytes, WorkGang* pretouch_workers, double* expand_time_ms) { 1267 size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes); 1268 aligned_expand_bytes = align_up(aligned_expand_bytes, 1269 HeapRegion::GrainBytes); 1270 1271 log_debug(gc, ergo, heap)("Expand the heap. requested expansion amount: " SIZE_FORMAT "B expansion amount: " SIZE_FORMAT "B", 1272 expand_bytes, aligned_expand_bytes); 1273 1274 if (is_maximal_no_gc()) { 1275 log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)"); 1276 return false; 1277 } 1278 1279 double expand_heap_start_time_sec = os::elapsedTime(); 1280 uint regions_to_expand = (uint)(aligned_expand_bytes / HeapRegion::GrainBytes); 1281 assert(regions_to_expand > 0, "Must expand by at least one region"); 1282 1283 uint expanded_by = _hrm->expand_by(regions_to_expand, pretouch_workers); 1284 if (expand_time_ms != NULL) { 1285 *expand_time_ms = (os::elapsedTime() - expand_heap_start_time_sec) * MILLIUNITS; 1286 } 1287 1288 if (expanded_by > 0) { 1289 size_t actual_expand_bytes = expanded_by * HeapRegion::GrainBytes; 1290 assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition"); 1291 policy()->record_new_heap_size(num_regions()); 1292 } else { 1293 log_debug(gc, ergo, heap)("Did not expand the heap (heap expansion operation failed)"); 1294 1295 // The expansion of the virtual storage space was unsuccessful. 1296 // Let's see if it was because we ran out of swap. 1297 if (G1ExitOnExpansionFailure && 1298 _hrm->available() >= regions_to_expand) { 1299 // We had head room... 1300 vm_exit_out_of_memory(aligned_expand_bytes, OOM_MMAP_ERROR, "G1 heap expansion"); 1301 } 1302 } 1303 return regions_to_expand > 0; 1304 } 1305 1306 bool G1CollectedHeap::expand_single_region(uint node_index) { 1307 uint expanded_by = _hrm->expand_on_preferred_node(node_index); 1308 1309 if (expanded_by == 0) { 1310 assert(is_maximal_no_gc(), "Should be no regions left, available: %u", _hrm->available()); 1311 log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)"); 1312 return false; 1313 } 1314 1315 policy()->record_new_heap_size(num_regions()); 1316 return true; 1317 } 1318 1319 void G1CollectedHeap::shrink_helper(size_t shrink_bytes) { 1320 size_t aligned_shrink_bytes = 1321 ReservedSpace::page_align_size_down(shrink_bytes); 1322 aligned_shrink_bytes = align_down(aligned_shrink_bytes, 1323 HeapRegion::GrainBytes); 1324 uint num_regions_to_remove = (uint)(shrink_bytes / HeapRegion::GrainBytes); 1325 1326 uint num_regions_removed = _hrm->shrink_by(num_regions_to_remove); 1327 size_t shrunk_bytes = num_regions_removed * HeapRegion::GrainBytes; 1328 1329 log_debug(gc, ergo, heap)("Shrink the heap. requested shrinking amount: " SIZE_FORMAT "B aligned shrinking amount: " SIZE_FORMAT "B attempted shrinking amount: " SIZE_FORMAT "B", 1330 shrink_bytes, aligned_shrink_bytes, shrunk_bytes); 1331 if (num_regions_removed > 0) { 1332 policy()->record_new_heap_size(num_regions()); 1333 } else { 1334 log_debug(gc, ergo, heap)("Did not expand the heap (heap shrinking operation failed)"); 1335 } 1336 } 1337 1338 void G1CollectedHeap::shrink(size_t shrink_bytes) { 1339 _verifier->verify_region_sets_optional(); 1340 1341 // We should only reach here at the end of a Full GC or during Remark which 1342 // means we should not not be holding to any GC alloc regions. The method 1343 // below will make sure of that and do any remaining clean up. 1344 _allocator->abandon_gc_alloc_regions(); 1345 1346 // Instead of tearing down / rebuilding the free lists here, we 1347 // could instead use the remove_all_pending() method on free_list to 1348 // remove only the ones that we need to remove. 1349 tear_down_region_sets(true /* free_list_only */); 1350 shrink_helper(shrink_bytes); 1351 rebuild_region_sets(true /* free_list_only */); 1352 1353 _hrm->verify_optional(); 1354 _verifier->verify_region_sets_optional(); 1355 } 1356 1357 class OldRegionSetChecker : public HeapRegionSetChecker { 1358 public: 1359 void check_mt_safety() { 1360 // Master Old Set MT safety protocol: 1361 // (a) If we're at a safepoint, operations on the master old set 1362 // should be invoked: 1363 // - by the VM thread (which will serialize them), or 1364 // - by the GC workers while holding the FreeList_lock, if we're 1365 // at a safepoint for an evacuation pause (this lock is taken 1366 // anyway when an GC alloc region is retired so that a new one 1367 // is allocated from the free list), or 1368 // - by the GC workers while holding the OldSets_lock, if we're at a 1369 // safepoint for a cleanup pause. 1370 // (b) If we're not at a safepoint, operations on the master old set 1371 // should be invoked while holding the Heap_lock. 1372 1373 if (SafepointSynchronize::is_at_safepoint()) { 1374 guarantee(Thread::current()->is_VM_thread() || 1375 FreeList_lock->owned_by_self() || OldSets_lock->owned_by_self(), 1376 "master old set MT safety protocol at a safepoint"); 1377 } else { 1378 guarantee(Heap_lock->owned_by_self(), "master old set MT safety protocol outside a safepoint"); 1379 } 1380 } 1381 bool is_correct_type(HeapRegion* hr) { return hr->is_old(); } 1382 const char* get_description() { return "Old Regions"; } 1383 }; 1384 1385 class ArchiveRegionSetChecker : public HeapRegionSetChecker { 1386 public: 1387 void check_mt_safety() { 1388 guarantee(!Universe::is_fully_initialized() || SafepointSynchronize::is_at_safepoint(), 1389 "May only change archive regions during initialization or safepoint."); 1390 } 1391 bool is_correct_type(HeapRegion* hr) { return hr->is_archive(); } 1392 const char* get_description() { return "Archive Regions"; } 1393 }; 1394 1395 class HumongousRegionSetChecker : public HeapRegionSetChecker { 1396 public: 1397 void check_mt_safety() { 1398 // Humongous Set MT safety protocol: 1399 // (a) If we're at a safepoint, operations on the master humongous 1400 // set should be invoked by either the VM thread (which will 1401 // serialize them) or by the GC workers while holding the 1402 // OldSets_lock. 1403 // (b) If we're not at a safepoint, operations on the master 1404 // humongous set should be invoked while holding the Heap_lock. 1405 1406 if (SafepointSynchronize::is_at_safepoint()) { 1407 guarantee(Thread::current()->is_VM_thread() || 1408 OldSets_lock->owned_by_self(), 1409 "master humongous set MT safety protocol at a safepoint"); 1410 } else { 1411 guarantee(Heap_lock->owned_by_self(), 1412 "master humongous set MT safety protocol outside a safepoint"); 1413 } 1414 } 1415 bool is_correct_type(HeapRegion* hr) { return hr->is_humongous(); } 1416 const char* get_description() { return "Humongous Regions"; } 1417 }; 1418 1419 G1CollectedHeap::G1CollectedHeap() : 1420 CollectedHeap(), 1421 _service_thread(NULL), 1422 _workers(NULL), 1423 _card_table(NULL), 1424 _collection_pause_end(Ticks::now()), 1425 _soft_ref_policy(), 1426 _old_set("Old Region Set", new OldRegionSetChecker()), 1427 _archive_set("Archive Region Set", new ArchiveRegionSetChecker()), 1428 _humongous_set("Humongous Region Set", new HumongousRegionSetChecker()), 1429 _bot(NULL), 1430 _listener(), 1431 _numa(G1NUMA::create()), 1432 _hrm(NULL), 1433 _allocator(NULL), 1434 _verifier(NULL), 1435 _summary_bytes_used(0), 1436 _bytes_used_during_gc(0), 1437 _archive_allocator(NULL), 1438 _survivor_evac_stats("Young", YoungPLABSize, PLABWeight), 1439 _old_evac_stats("Old", OldPLABSize, PLABWeight), 1440 _expand_heap_after_alloc_failure(true), 1441 _g1mm(NULL), 1442 _humongous_reclaim_candidates(), 1443 _has_humongous_reclaim_candidates(false), 1444 _hr_printer(), 1445 _collector_state(), 1446 _old_marking_cycles_started(0), 1447 _old_marking_cycles_completed(0), 1448 _eden(), 1449 _survivor(), 1450 _gc_timer_stw(new (ResourceObj::C_HEAP, mtGC) STWGCTimer()), 1451 _gc_tracer_stw(new (ResourceObj::C_HEAP, mtGC) G1NewTracer()), 1452 _policy(G1Policy::create_policy(_gc_timer_stw)), 1453 _heap_sizing_policy(NULL), 1454 _collection_set(this, _policy), 1455 _hot_card_cache(NULL), 1456 _rem_set(NULL), 1457 _cm(NULL), 1458 _cm_thread(NULL), 1459 _cr(NULL), 1460 _task_queues(NULL), 1461 _evacuation_failed(false), 1462 _evacuation_failed_info_array(NULL), 1463 _preserved_marks_set(true /* in_c_heap */), 1464 #ifndef PRODUCT 1465 _evacuation_failure_alot_for_current_gc(false), 1466 _evacuation_failure_alot_gc_number(0), 1467 _evacuation_failure_alot_count(0), 1468 #endif 1469 _ref_processor_stw(NULL), 1470 _is_alive_closure_stw(this), 1471 _is_subject_to_discovery_stw(this), 1472 _ref_processor_cm(NULL), 1473 _is_alive_closure_cm(this), 1474 _is_subject_to_discovery_cm(this), 1475 _region_attr() { 1476 1477 _verifier = new G1HeapVerifier(this); 1478 1479 _allocator = new G1Allocator(this); 1480 1481 _heap_sizing_policy = G1HeapSizingPolicy::create(this, _policy->analytics()); 1482 1483 _humongous_object_threshold_in_words = humongous_threshold_for(HeapRegion::GrainWords); 1484 1485 // Override the default _filler_array_max_size so that no humongous filler 1486 // objects are created. 1487 _filler_array_max_size = _humongous_object_threshold_in_words; 1488 1489 uint n_queues = ParallelGCThreads; 1490 _task_queues = new G1ScannerTasksQueueSet(n_queues); 1491 1492 _evacuation_failed_info_array = NEW_C_HEAP_ARRAY(EvacuationFailedInfo, n_queues, mtGC); 1493 1494 for (uint i = 0; i < n_queues; i++) { 1495 G1ScannerTasksQueue* q = new G1ScannerTasksQueue(); 1496 q->initialize(); 1497 _task_queues->register_queue(i, q); 1498 ::new (&_evacuation_failed_info_array[i]) EvacuationFailedInfo(); 1499 } 1500 1501 // Initialize the G1EvacuationFailureALot counters and flags. 1502 NOT_PRODUCT(reset_evacuation_should_fail();) 1503 _gc_tracer_stw->initialize(); 1504 1505 guarantee(_task_queues != NULL, "task_queues allocation failure."); 1506 } 1507 1508 static size_t actual_reserved_page_size(ReservedSpace rs) { 1509 size_t page_size = os::vm_page_size(); 1510 if (UseLargePages) { 1511 // There are two ways to manage large page memory. 1512 // 1. OS supports committing large page memory. 1513 // 2. OS doesn't support committing large page memory so ReservedSpace manages it. 1514 // And ReservedSpace calls it 'special'. If we failed to set 'special', 1515 // we reserved memory without large page. 1516 if (os::can_commit_large_page_memory() || rs.special()) { 1517 // An alignment at ReservedSpace comes from preferred page size or 1518 // heap alignment, and if the alignment came from heap alignment, it could be 1519 // larger than large pages size. So need to cap with the large page size. 1520 page_size = MIN2(rs.alignment(), os::large_page_size()); 1521 } 1522 } 1523 1524 return page_size; 1525 } 1526 1527 G1RegionToSpaceMapper* G1CollectedHeap::create_aux_memory_mapper(const char* description, 1528 size_t size, 1529 size_t translation_factor) { 1530 size_t preferred_page_size = os::page_size_for_region_unaligned(size, 1); 1531 // Allocate a new reserved space, preferring to use large pages. 1532 ReservedSpace rs(size, preferred_page_size); 1533 size_t page_size = actual_reserved_page_size(rs); 1534 G1RegionToSpaceMapper* result = 1535 G1RegionToSpaceMapper::create_mapper(rs, 1536 size, 1537 page_size, 1538 HeapRegion::GrainBytes, 1539 translation_factor, 1540 mtGC); 1541 1542 os::trace_page_sizes_for_requested_size(description, 1543 size, 1544 preferred_page_size, 1545 page_size, 1546 rs.base(), 1547 rs.size()); 1548 1549 return result; 1550 } 1551 1552 jint G1CollectedHeap::initialize_concurrent_refinement() { 1553 jint ecode = JNI_OK; 1554 _cr = G1ConcurrentRefine::create(&ecode); 1555 return ecode; 1556 } 1557 1558 jint G1CollectedHeap::initialize_service_thread() { 1559 _service_thread = new G1ServiceThread(); 1560 if (_service_thread->osthread() == NULL) { 1561 vm_shutdown_during_initialization("Could not create G1ServiceThread"); 1562 return JNI_ENOMEM; 1563 } 1564 return JNI_OK; 1565 } 1566 1567 jint G1CollectedHeap::initialize() { 1568 1569 // Necessary to satisfy locking discipline assertions. 1570 1571 MutexLocker x(Heap_lock); 1572 1573 // While there are no constraints in the GC code that HeapWordSize 1574 // be any particular value, there are multiple other areas in the 1575 // system which believe this to be true (e.g. oop->object_size in some 1576 // cases incorrectly returns the size in wordSize units rather than 1577 // HeapWordSize). 1578 guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize"); 1579 1580 size_t init_byte_size = InitialHeapSize; 1581 size_t reserved_byte_size = G1Arguments::heap_reserved_size_bytes(); 1582 1583 // Ensure that the sizes are properly aligned. 1584 Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap"); 1585 Universe::check_alignment(reserved_byte_size, HeapRegion::GrainBytes, "g1 heap"); 1586 Universe::check_alignment(reserved_byte_size, HeapAlignment, "g1 heap"); 1587 1588 // Reserve the maximum. 1589 1590 // When compressed oops are enabled, the preferred heap base 1591 // is calculated by subtracting the requested size from the 1592 // 32Gb boundary and using the result as the base address for 1593 // heap reservation. If the requested size is not aligned to 1594 // HeapRegion::GrainBytes (i.e. the alignment that is passed 1595 // into the ReservedHeapSpace constructor) then the actual 1596 // base of the reserved heap may end up differing from the 1597 // address that was requested (i.e. the preferred heap base). 1598 // If this happens then we could end up using a non-optimal 1599 // compressed oops mode. 1600 1601 ReservedHeapSpace heap_rs = Universe::reserve_heap(reserved_byte_size, 1602 HeapAlignment); 1603 1604 initialize_reserved_region(heap_rs); 1605 1606 // Create the barrier set for the entire reserved region. 1607 G1CardTable* ct = new G1CardTable(heap_rs.region()); 1608 ct->initialize(); 1609 G1BarrierSet* bs = new G1BarrierSet(ct); 1610 bs->initialize(); 1611 assert(bs->is_a(BarrierSet::G1BarrierSet), "sanity"); 1612 BarrierSet::set_barrier_set(bs); 1613 _card_table = ct; 1614 1615 { 1616 G1SATBMarkQueueSet& satbqs = bs->satb_mark_queue_set(); 1617 satbqs.set_process_completed_buffers_threshold(G1SATBProcessCompletedThreshold); 1618 satbqs.set_buffer_enqueue_threshold_percentage(G1SATBBufferEnqueueingThresholdPercent); 1619 } 1620 1621 // Create the hot card cache. 1622 _hot_card_cache = new G1HotCardCache(this); 1623 1624 // Create space mappers. 1625 size_t page_size = actual_reserved_page_size(heap_rs); 1626 G1RegionToSpaceMapper* heap_storage = 1627 G1RegionToSpaceMapper::create_heap_mapper(heap_rs, 1628 heap_rs.size(), 1629 page_size, 1630 HeapRegion::GrainBytes, 1631 1, 1632 mtJavaHeap); 1633 if(heap_storage == NULL) { 1634 vm_shutdown_during_initialization("Could not initialize G1 heap"); 1635 return JNI_ERR; 1636 } 1637 1638 os::trace_page_sizes("Heap", 1639 MinHeapSize, 1640 reserved_byte_size, 1641 page_size, 1642 heap_rs.base(), 1643 heap_rs.size()); 1644 heap_storage->set_mapping_changed_listener(&_listener); 1645 1646 // Create storage for the BOT, card table, card counts table (hot card cache) and the bitmaps. 1647 G1RegionToSpaceMapper* bot_storage = 1648 create_aux_memory_mapper("Block Offset Table", 1649 G1BlockOffsetTable::compute_size(heap_rs.size() / HeapWordSize), 1650 G1BlockOffsetTable::heap_map_factor()); 1651 1652 G1RegionToSpaceMapper* cardtable_storage = 1653 create_aux_memory_mapper("Card Table", 1654 G1CardTable::compute_size(heap_rs.size() / HeapWordSize), 1655 G1CardTable::heap_map_factor()); 1656 1657 G1RegionToSpaceMapper* card_counts_storage = 1658 create_aux_memory_mapper("Card Counts Table", 1659 G1CardCounts::compute_size(heap_rs.size() / HeapWordSize), 1660 G1CardCounts::heap_map_factor()); 1661 1662 size_t bitmap_size = G1CMBitMap::compute_size(heap_rs.size()); 1663 G1RegionToSpaceMapper* prev_bitmap_storage = 1664 create_aux_memory_mapper("Prev Bitmap", bitmap_size, G1CMBitMap::heap_map_factor()); 1665 G1RegionToSpaceMapper* next_bitmap_storage = 1666 create_aux_memory_mapper("Next Bitmap", bitmap_size, G1CMBitMap::heap_map_factor()); 1667 1668 _hrm = HeapRegionManager::create_manager(this); 1669 1670 _hrm->initialize(heap_storage, prev_bitmap_storage, next_bitmap_storage, bot_storage, cardtable_storage, card_counts_storage); 1671 _card_table->initialize(cardtable_storage); 1672 1673 // Do later initialization work for concurrent refinement. 1674 _hot_card_cache->initialize(card_counts_storage); 1675 1676 // 6843694 - ensure that the maximum region index can fit 1677 // in the remembered set structures. 1678 const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1; 1679 guarantee((max_regions() - 1) <= max_region_idx, "too many regions"); 1680 1681 // The G1FromCardCache reserves card with value 0 as "invalid", so the heap must not 1682 // start within the first card. 1683 guarantee(heap_rs.base() >= (char*)G1CardTable::card_size, "Java heap must not start within the first card."); 1684 // Also create a G1 rem set. 1685 _rem_set = new G1RemSet(this, _card_table, _hot_card_cache); 1686 _rem_set->initialize(max_reserved_capacity(), max_regions()); 1687 1688 size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1; 1689 guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized"); 1690 guarantee(HeapRegion::CardsPerRegion < max_cards_per_region, 1691 "too many cards per region"); 1692 1693 FreeRegionList::set_unrealistically_long_length(max_expandable_regions() + 1); 1694 1695 _bot = new G1BlockOffsetTable(reserved_region(), bot_storage); 1696 1697 { 1698 HeapWord* start = _hrm->reserved().start(); 1699 HeapWord* end = _hrm->reserved().end(); 1700 size_t granularity = HeapRegion::GrainBytes; 1701 1702 _region_attr.initialize(start, end, granularity); 1703 _humongous_reclaim_candidates.initialize(start, end, granularity); 1704 } 1705 1706 _workers = new WorkGang("GC Thread", ParallelGCThreads, 1707 true /* are_GC_task_threads */, 1708 false /* are_ConcurrentGC_threads */); 1709 if (_workers == NULL) { 1710 return JNI_ENOMEM; 1711 } 1712 _workers->initialize_workers(); 1713 1714 _numa->set_region_info(HeapRegion::GrainBytes, page_size); 1715 1716 // Create the G1ConcurrentMark data structure and thread. 1717 // (Must do this late, so that "max_regions" is defined.) 1718 _cm = new G1ConcurrentMark(this, prev_bitmap_storage, next_bitmap_storage); 1719 _cm_thread = _cm->cm_thread(); 1720 1721 // Now expand into the initial heap size. 1722 if (!expand(init_byte_size, _workers)) { 1723 vm_shutdown_during_initialization("Failed to allocate initial heap."); 1724 return JNI_ENOMEM; 1725 } 1726 1727 // Perform any initialization actions delegated to the policy. 1728 policy()->init(this, &_collection_set); 1729 1730 jint ecode = initialize_concurrent_refinement(); 1731 if (ecode != JNI_OK) { 1732 return ecode; 1733 } 1734 1735 ecode = initialize_service_thread(); 1736 if (ecode != JNI_OK) { 1737 return ecode; 1738 } 1739 1740 { 1741 G1DirtyCardQueueSet& dcqs = G1BarrierSet::dirty_card_queue_set(); 1742 dcqs.set_process_cards_threshold(concurrent_refine()->yellow_zone()); 1743 dcqs.set_max_cards(concurrent_refine()->red_zone()); 1744 } 1745 1746 // Here we allocate the dummy HeapRegion that is required by the 1747 // G1AllocRegion class. 1748 HeapRegion* dummy_region = _hrm->get_dummy_region(); 1749 1750 // We'll re-use the same region whether the alloc region will 1751 // require BOT updates or not and, if it doesn't, then a non-young 1752 // region will complain that it cannot support allocations without 1753 // BOT updates. So we'll tag the dummy region as eden to avoid that. 1754 dummy_region->set_eden(); 1755 // Make sure it's full. 1756 dummy_region->set_top(dummy_region->end()); 1757 G1AllocRegion::setup(this, dummy_region); 1758 1759 _allocator->init_mutator_alloc_regions(); 1760 1761 // Do create of the monitoring and management support so that 1762 // values in the heap have been properly initialized. 1763 _g1mm = new G1MonitoringSupport(this); 1764 1765 G1StringDedup::initialize(); 1766 1767 _preserved_marks_set.init(ParallelGCThreads); 1768 1769 _collection_set.initialize(max_regions()); 1770 1771 G1InitLogger::print(); 1772 1773 return JNI_OK; 1774 } 1775 1776 void G1CollectedHeap::stop() { 1777 // Stop all concurrent threads. We do this to make sure these threads 1778 // do not continue to execute and access resources (e.g. logging) 1779 // that are destroyed during shutdown. 1780 _cr->stop(); 1781 _service_thread->stop(); 1782 _cm_thread->stop(); 1783 if (G1StringDedup::is_enabled()) { 1784 G1StringDedup::stop(); 1785 } 1786 } 1787 1788 void G1CollectedHeap::safepoint_synchronize_begin() { 1789 SuspendibleThreadSet::synchronize(); 1790 } 1791 1792 void G1CollectedHeap::safepoint_synchronize_end() { 1793 SuspendibleThreadSet::desynchronize(); 1794 } 1795 1796 void G1CollectedHeap::post_initialize() { 1797 CollectedHeap::post_initialize(); 1798 ref_processing_init(); 1799 } 1800 1801 void G1CollectedHeap::ref_processing_init() { 1802 // Reference processing in G1 currently works as follows: 1803 // 1804 // * There are two reference processor instances. One is 1805 // used to record and process discovered references 1806 // during concurrent marking; the other is used to 1807 // record and process references during STW pauses 1808 // (both full and incremental). 1809 // * Both ref processors need to 'span' the entire heap as 1810 // the regions in the collection set may be dotted around. 1811 // 1812 // * For the concurrent marking ref processor: 1813 // * Reference discovery is enabled at concurrent start. 1814 // * Reference discovery is disabled and the discovered 1815 // references processed etc during remarking. 1816 // * Reference discovery is MT (see below). 1817 // * Reference discovery requires a barrier (see below). 1818 // * Reference processing may or may not be MT 1819 // (depending on the value of ParallelRefProcEnabled 1820 // and ParallelGCThreads). 1821 // * A full GC disables reference discovery by the CM 1822 // ref processor and abandons any entries on it's 1823 // discovered lists. 1824 // 1825 // * For the STW processor: 1826 // * Non MT discovery is enabled at the start of a full GC. 1827 // * Processing and enqueueing during a full GC is non-MT. 1828 // * During a full GC, references are processed after marking. 1829 // 1830 // * Discovery (may or may not be MT) is enabled at the start 1831 // of an incremental evacuation pause. 1832 // * References are processed near the end of a STW evacuation pause. 1833 // * For both types of GC: 1834 // * Discovery is atomic - i.e. not concurrent. 1835 // * Reference discovery will not need a barrier. 1836 1837 bool mt_processing = ParallelRefProcEnabled && (ParallelGCThreads > 1); 1838 1839 // Concurrent Mark ref processor 1840 _ref_processor_cm = 1841 new ReferenceProcessor(&_is_subject_to_discovery_cm, 1842 mt_processing, // mt processing 1843 ParallelGCThreads, // degree of mt processing 1844 (ParallelGCThreads > 1) || (ConcGCThreads > 1), // mt discovery 1845 MAX2(ParallelGCThreads, ConcGCThreads), // degree of mt discovery 1846 false, // Reference discovery is not atomic 1847 &_is_alive_closure_cm, // is alive closure 1848 true); // allow changes to number of processing threads 1849 1850 // STW ref processor 1851 _ref_processor_stw = 1852 new ReferenceProcessor(&_is_subject_to_discovery_stw, 1853 mt_processing, // mt processing 1854 ParallelGCThreads, // degree of mt processing 1855 (ParallelGCThreads > 1), // mt discovery 1856 ParallelGCThreads, // degree of mt discovery 1857 true, // Reference discovery is atomic 1858 &_is_alive_closure_stw, // is alive closure 1859 true); // allow changes to number of processing threads 1860 } 1861 1862 SoftRefPolicy* G1CollectedHeap::soft_ref_policy() { 1863 return &_soft_ref_policy; 1864 } 1865 1866 size_t G1CollectedHeap::capacity() const { 1867 return _hrm->length() * HeapRegion::GrainBytes; 1868 } 1869 1870 size_t G1CollectedHeap::unused_committed_regions_in_bytes() const { 1871 return _hrm->total_free_bytes(); 1872 } 1873 1874 void G1CollectedHeap::iterate_hcc_closure(G1CardTableEntryClosure* cl, uint worker_id) { 1875 _hot_card_cache->drain(cl, worker_id); 1876 } 1877 1878 // Computes the sum of the storage used by the various regions. 1879 size_t G1CollectedHeap::used() const { 1880 size_t result = _summary_bytes_used + _allocator->used_in_alloc_regions(); 1881 if (_archive_allocator != NULL) { 1882 result += _archive_allocator->used(); 1883 } 1884 return result; 1885 } 1886 1887 size_t G1CollectedHeap::used_unlocked() const { 1888 return _summary_bytes_used; 1889 } 1890 1891 class SumUsedClosure: public HeapRegionClosure { 1892 size_t _used; 1893 public: 1894 SumUsedClosure() : _used(0) {} 1895 bool do_heap_region(HeapRegion* r) { 1896 _used += r->used(); 1897 return false; 1898 } 1899 size_t result() { return _used; } 1900 }; 1901 1902 size_t G1CollectedHeap::recalculate_used() const { 1903 SumUsedClosure blk; 1904 heap_region_iterate(&blk); 1905 return blk.result(); 1906 } 1907 1908 bool G1CollectedHeap::is_user_requested_concurrent_full_gc(GCCause::Cause cause) { 1909 switch (cause) { 1910 case GCCause::_java_lang_system_gc: return ExplicitGCInvokesConcurrent; 1911 case GCCause::_dcmd_gc_run: return ExplicitGCInvokesConcurrent; 1912 case GCCause::_wb_conc_mark: return true; 1913 default : return false; 1914 } 1915 } 1916 1917 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) { 1918 switch (cause) { 1919 case GCCause::_g1_humongous_allocation: return true; 1920 case GCCause::_g1_periodic_collection: return G1PeriodicGCInvokesConcurrent; 1921 case GCCause::_wb_breakpoint: return true; 1922 default: return is_user_requested_concurrent_full_gc(cause); 1923 } 1924 } 1925 1926 bool G1CollectedHeap::should_upgrade_to_full_gc(GCCause::Cause cause) { 1927 if (policy()->force_upgrade_to_full()) { 1928 return true; 1929 } else if (should_do_concurrent_full_gc(_gc_cause)) { 1930 return false; 1931 } else if (has_regions_left_for_allocation()) { 1932 return false; 1933 } else { 1934 return true; 1935 } 1936 } 1937 1938 #ifndef PRODUCT 1939 void G1CollectedHeap::allocate_dummy_regions() { 1940 // Let's fill up most of the region 1941 size_t word_size = HeapRegion::GrainWords - 1024; 1942 // And as a result the region we'll allocate will be humongous. 1943 guarantee(is_humongous(word_size), "sanity"); 1944 1945 // _filler_array_max_size is set to humongous object threshold 1946 // but temporarily change it to use CollectedHeap::fill_with_object(). 1947 AutoModifyRestore<size_t> temporarily(_filler_array_max_size, word_size); 1948 1949 for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) { 1950 // Let's use the existing mechanism for the allocation 1951 HeapWord* dummy_obj = humongous_obj_allocate(word_size); 1952 if (dummy_obj != NULL) { 1953 MemRegion mr(dummy_obj, word_size); 1954 CollectedHeap::fill_with_object(mr); 1955 } else { 1956 // If we can't allocate once, we probably cannot allocate 1957 // again. Let's get out of the loop. 1958 break; 1959 } 1960 } 1961 } 1962 #endif // !PRODUCT 1963 1964 void G1CollectedHeap::increment_old_marking_cycles_started() { 1965 assert(_old_marking_cycles_started == _old_marking_cycles_completed || 1966 _old_marking_cycles_started == _old_marking_cycles_completed + 1, 1967 "Wrong marking cycle count (started: %d, completed: %d)", 1968 _old_marking_cycles_started, _old_marking_cycles_completed); 1969 1970 _old_marking_cycles_started++; 1971 } 1972 1973 void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent, 1974 bool whole_heap_examined) { 1975 MonitorLocker ml(G1OldGCCount_lock, Mutex::_no_safepoint_check_flag); 1976 1977 // We assume that if concurrent == true, then the caller is a 1978 // concurrent thread that was joined the Suspendible Thread 1979 // Set. If there's ever a cheap way to check this, we should add an 1980 // assert here. 1981 1982 // Given that this method is called at the end of a Full GC or of a 1983 // concurrent cycle, and those can be nested (i.e., a Full GC can 1984 // interrupt a concurrent cycle), the number of full collections 1985 // completed should be either one (in the case where there was no 1986 // nesting) or two (when a Full GC interrupted a concurrent cycle) 1987 // behind the number of full collections started. 1988 1989 // This is the case for the inner caller, i.e. a Full GC. 1990 assert(concurrent || 1991 (_old_marking_cycles_started == _old_marking_cycles_completed + 1) || 1992 (_old_marking_cycles_started == _old_marking_cycles_completed + 2), 1993 "for inner caller (Full GC): _old_marking_cycles_started = %u " 1994 "is inconsistent with _old_marking_cycles_completed = %u", 1995 _old_marking_cycles_started, _old_marking_cycles_completed); 1996 1997 // This is the case for the outer caller, i.e. the concurrent cycle. 1998 assert(!concurrent || 1999 (_old_marking_cycles_started == _old_marking_cycles_completed + 1), 2000 "for outer caller (concurrent cycle): " 2001 "_old_marking_cycles_started = %u " 2002 "is inconsistent with _old_marking_cycles_completed = %u", 2003 _old_marking_cycles_started, _old_marking_cycles_completed); 2004 2005 _old_marking_cycles_completed += 1; 2006 if (whole_heap_examined) { 2007 // Signal that we have completed a visit to all live objects. 2008 record_whole_heap_examined_timestamp(); 2009 } 2010 2011 // We need to clear the "in_progress" flag in the CM thread before 2012 // we wake up any waiters (especially when ExplicitInvokesConcurrent 2013 // is set) so that if a waiter requests another System.gc() it doesn't 2014 // incorrectly see that a marking cycle is still in progress. 2015 if (concurrent) { 2016 _cm_thread->set_idle(); 2017 } 2018 2019 // Notify threads waiting in System.gc() (with ExplicitGCInvokesConcurrent) 2020 // for a full GC to finish that their wait is over. 2021 ml.notify_all(); 2022 } 2023 2024 void G1CollectedHeap::collect(GCCause::Cause cause) { 2025 try_collect(cause); 2026 } 2027 2028 // Return true if (x < y) with allowance for wraparound. 2029 static bool gc_counter_less_than(uint x, uint y) { 2030 return (x - y) > (UINT_MAX/2); 2031 } 2032 2033 // LOG_COLLECT_CONCURRENTLY(cause, msg, args...) 2034 // Macro so msg printing is format-checked. 2035 #define LOG_COLLECT_CONCURRENTLY(cause, ...) \ 2036 do { \ 2037 LogTarget(Trace, gc) LOG_COLLECT_CONCURRENTLY_lt; \ 2038 if (LOG_COLLECT_CONCURRENTLY_lt.is_enabled()) { \ 2039 ResourceMark rm; /* For thread name. */ \ 2040 LogStream LOG_COLLECT_CONCURRENTLY_s(&LOG_COLLECT_CONCURRENTLY_lt); \ 2041 LOG_COLLECT_CONCURRENTLY_s.print("%s: Try Collect Concurrently (%s): ", \ 2042 Thread::current()->name(), \ 2043 GCCause::to_string(cause)); \ 2044 LOG_COLLECT_CONCURRENTLY_s.print(__VA_ARGS__); \ 2045 } \ 2046 } while (0) 2047 2048 #define LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, result) \ 2049 LOG_COLLECT_CONCURRENTLY(cause, "complete %s", BOOL_TO_STR(result)) 2050 2051 bool G1CollectedHeap::try_collect_concurrently(GCCause::Cause cause, 2052 uint gc_counter, 2053 uint old_marking_started_before) { 2054 assert_heap_not_locked(); 2055 assert(should_do_concurrent_full_gc(cause), 2056 "Non-concurrent cause %s", GCCause::to_string(cause)); 2057 2058 for (uint i = 1; true; ++i) { 2059 // Try to schedule concurrent start evacuation pause that will 2060 // start a concurrent cycle. 2061 LOG_COLLECT_CONCURRENTLY(cause, "attempt %u", i); 2062 VM_G1TryInitiateConcMark op(gc_counter, 2063 cause, 2064 policy()->max_pause_time_ms()); 2065 VMThread::execute(&op); 2066 2067 // Request is trivially finished. 2068 if (cause == GCCause::_g1_periodic_collection) { 2069 LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, op.gc_succeeded()); 2070 return op.gc_succeeded(); 2071 } 2072 2073 // If VMOp skipped initiating concurrent marking cycle because 2074 // we're terminating, then we're done. 2075 if (op.terminating()) { 2076 LOG_COLLECT_CONCURRENTLY(cause, "skipped: terminating"); 2077 return false; 2078 } 2079 2080 // Lock to get consistent set of values. 2081 uint old_marking_started_after; 2082 uint old_marking_completed_after; 2083 { 2084 MutexLocker ml(Heap_lock); 2085 // Update gc_counter for retrying VMOp if needed. Captured here to be 2086 // consistent with the values we use below for termination tests. If 2087 // a retry is needed after a possible wait, and another collection 2088 // occurs in the meantime, it will cause our retry to be skipped and 2089 // we'll recheck for termination with updated conditions from that 2090 // more recent collection. That's what we want, rather than having 2091 // our retry possibly perform an unnecessary collection. 2092 gc_counter = total_collections(); 2093 old_marking_started_after = _old_marking_cycles_started; 2094 old_marking_completed_after = _old_marking_cycles_completed; 2095 } 2096 2097 if (cause == GCCause::_wb_breakpoint) { 2098 if (op.gc_succeeded()) { 2099 LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true); 2100 return true; 2101 } 2102 // When _wb_breakpoint there can't be another cycle or deferred. 2103 assert(!op.cycle_already_in_progress(), "invariant"); 2104 assert(!op.whitebox_attached(), "invariant"); 2105 // Concurrent cycle attempt might have been cancelled by some other 2106 // collection, so retry. Unlike other cases below, we want to retry 2107 // even if cancelled by a STW full collection, because we really want 2108 // to start a concurrent cycle. 2109 if (old_marking_started_before != old_marking_started_after) { 2110 LOG_COLLECT_CONCURRENTLY(cause, "ignoring STW full GC"); 2111 old_marking_started_before = old_marking_started_after; 2112 } 2113 } else if (!GCCause::is_user_requested_gc(cause)) { 2114 // For an "automatic" (not user-requested) collection, we just need to 2115 // ensure that progress is made. 2116 // 2117 // Request is finished if any of 2118 // (1) the VMOp successfully performed a GC, 2119 // (2) a concurrent cycle was already in progress, 2120 // (3) whitebox is controlling concurrent cycles, 2121 // (4) a new cycle was started (by this thread or some other), or 2122 // (5) a Full GC was performed. 2123 // Cases (4) and (5) are detected together by a change to 2124 // _old_marking_cycles_started. 2125 // 2126 // Note that (1) does not imply (4). If we're still in the mixed 2127 // phase of an earlier concurrent collection, the request to make the 2128 // collection a concurrent start won't be honored. If we don't check for 2129 // both conditions we'll spin doing back-to-back collections. 2130 if (op.gc_succeeded() || 2131 op.cycle_already_in_progress() || 2132 op.whitebox_attached() || 2133 (old_marking_started_before != old_marking_started_after)) { 2134 LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true); 2135 return true; 2136 } 2137 } else { // User-requested GC. 2138 // For a user-requested collection, we want to ensure that a complete 2139 // full collection has been performed before returning, but without 2140 // waiting for more than needed. 2141 2142 // For user-requested GCs (unlike non-UR), a successful VMOp implies a 2143 // new cycle was started. That's good, because it's not clear what we 2144 // should do otherwise. Trying again just does back to back GCs. 2145 // Can't wait for someone else to start a cycle. And returning fails 2146 // to meet the goal of ensuring a full collection was performed. 2147 assert(!op.gc_succeeded() || 2148 (old_marking_started_before != old_marking_started_after), 2149 "invariant: succeeded %s, started before %u, started after %u", 2150 BOOL_TO_STR(op.gc_succeeded()), 2151 old_marking_started_before, old_marking_started_after); 2152 2153 // Request is finished if a full collection (concurrent or stw) 2154 // was started after this request and has completed, e.g. 2155 // started_before < completed_after. 2156 if (gc_counter_less_than(old_marking_started_before, 2157 old_marking_completed_after)) { 2158 LOG_COLLECT_CONCURRENTLY_COMPLETE(cause, true); 2159 return true; 2160 } 2161 2162 if (old_marking_started_after != old_marking_completed_after) { 2163 // If there is an in-progress cycle (possibly started by us), then 2164 // wait for that cycle to complete, e.g. 2165 // while completed_now < started_after. 2166 LOG_COLLECT_CONCURRENTLY(cause, "wait"); 2167 MonitorLocker ml(G1OldGCCount_lock); 2168 while (gc_counter_less_than(_old_marking_cycles_completed, 2169 old_marking_started_after)) { 2170 ml.wait(); 2171 } 2172 // Request is finished if the collection we just waited for was 2173 // started after this request. 2174 if (old_marking_started_before != old_marking_started_after) { 2175 LOG_COLLECT_CONCURRENTLY(cause, "complete after wait"); 2176 return true; 2177 } 2178 } 2179 2180 // If VMOp was successful then it started a new cycle that the above 2181 // wait &etc should have recognized as finishing this request. This 2182 // differs from a non-user-request, where gc_succeeded does not imply 2183 // a new cycle was started. 2184 assert(!op.gc_succeeded(), "invariant"); 2185 2186 if (op.cycle_already_in_progress()) { 2187 // If VMOp failed because a cycle was already in progress, it 2188 // is now complete. But it didn't finish this user-requested 2189 // GC, so try again. 2190 LOG_COLLECT_CONCURRENTLY(cause, "retry after in-progress"); 2191 continue; 2192 } else if (op.whitebox_attached()) { 2193 // If WhiteBox wants control, wait for notification of a state 2194 // change in the controller, then try again. Don't wait for 2195 // release of control, since collections may complete while in 2196 // control. Note: This won't recognize a STW full collection 2197 // while waiting; we can't wait on multiple monitors. 2198 LOG_COLLECT_CONCURRENTLY(cause, "whitebox control stall"); 2199 MonitorLocker ml(ConcurrentGCBreakpoints::monitor()); 2200 if (ConcurrentGCBreakpoints::is_controlled()) { 2201 ml.wait(); 2202 } 2203 continue; 2204 } 2205 } 2206 2207 // Collection failed and should be retried. 2208 assert(op.transient_failure(), "invariant"); 2209 2210 if (GCLocker::is_active_and_needs_gc()) { 2211 // If GCLocker is active, wait until clear before retrying. 2212 LOG_COLLECT_CONCURRENTLY(cause, "gc-locker stall"); 2213 GCLocker::stall_until_clear(); 2214 } 2215 2216 LOG_COLLECT_CONCURRENTLY(cause, "retry"); 2217 } 2218 } 2219 2220 bool G1CollectedHeap::try_collect(GCCause::Cause cause) { 2221 assert_heap_not_locked(); 2222 2223 // Lock to get consistent set of values. 2224 uint gc_count_before; 2225 uint full_gc_count_before; 2226 uint old_marking_started_before; 2227 { 2228 MutexLocker ml(Heap_lock); 2229 gc_count_before = total_collections(); 2230 full_gc_count_before = total_full_collections(); 2231 old_marking_started_before = _old_marking_cycles_started; 2232 } 2233 2234 if (should_do_concurrent_full_gc(cause)) { 2235 return try_collect_concurrently(cause, 2236 gc_count_before, 2237 old_marking_started_before); 2238 } else if (GCLocker::should_discard(cause, gc_count_before)) { 2239 // Indicate failure to be consistent with VMOp failure due to 2240 // another collection slipping in after our gc_count but before 2241 // our request is processed. 2242 return false; 2243 } else if (cause == GCCause::_gc_locker || cause == GCCause::_wb_young_gc 2244 DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) { 2245 2246 // Schedule a standard evacuation pause. We're setting word_size 2247 // to 0 which means that we are not requesting a post-GC allocation. 2248 VM_G1CollectForAllocation op(0, /* word_size */ 2249 gc_count_before, 2250 cause, 2251 policy()->max_pause_time_ms()); 2252 VMThread::execute(&op); 2253 return op.gc_succeeded(); 2254 } else { 2255 // Schedule a Full GC. 2256 VM_G1CollectFull op(gc_count_before, full_gc_count_before, cause); 2257 VMThread::execute(&op); 2258 return op.gc_succeeded(); 2259 } 2260 } 2261 2262 bool G1CollectedHeap::is_in(const void* p) const { 2263 if (_hrm->reserved().contains(p)) { 2264 // Given that we know that p is in the reserved space, 2265 // heap_region_containing() should successfully 2266 // return the containing region. 2267 HeapRegion* hr = heap_region_containing(p); 2268 return hr->is_in(p); 2269 } else { 2270 return false; 2271 } 2272 } 2273 2274 #ifdef ASSERT 2275 bool G1CollectedHeap::is_in_exact(const void* p) const { 2276 bool contains = reserved_region().contains(p); 2277 bool available = _hrm->is_available(addr_to_region((HeapWord*)p)); 2278 if (contains && available) { 2279 return true; 2280 } else { 2281 return false; 2282 } 2283 } 2284 #endif 2285 2286 // Iteration functions. 2287 2288 // Iterates an ObjectClosure over all objects within a HeapRegion. 2289 2290 class IterateObjectClosureRegionClosure: public HeapRegionClosure { 2291 ObjectClosure* _cl; 2292 public: 2293 IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {} 2294 bool do_heap_region(HeapRegion* r) { 2295 if (!r->is_continues_humongous()) { 2296 r->object_iterate(_cl); 2297 } 2298 return false; 2299 } 2300 }; 2301 2302 void G1CollectedHeap::object_iterate(ObjectClosure* cl) { 2303 IterateObjectClosureRegionClosure blk(cl); 2304 heap_region_iterate(&blk); 2305 } 2306 2307 class G1ParallelObjectIterator : public ParallelObjectIterator { 2308 private: 2309 G1CollectedHeap* _heap; 2310 HeapRegionClaimer _claimer; 2311 2312 public: 2313 G1ParallelObjectIterator(uint thread_num) : 2314 _heap(G1CollectedHeap::heap()), 2315 _claimer(thread_num == 0 ? G1CollectedHeap::heap()->workers()->active_workers() : thread_num) {} 2316 2317 virtual void object_iterate(ObjectClosure* cl, uint worker_id) { 2318 _heap->object_iterate_parallel(cl, worker_id, &_claimer); 2319 } 2320 }; 2321 2322 ParallelObjectIterator* G1CollectedHeap::parallel_object_iterator(uint thread_num) { 2323 return new G1ParallelObjectIterator(thread_num); 2324 } 2325 2326 void G1CollectedHeap::object_iterate_parallel(ObjectClosure* cl, uint worker_id, HeapRegionClaimer* claimer) { 2327 IterateObjectClosureRegionClosure blk(cl); 2328 heap_region_par_iterate_from_worker_offset(&blk, claimer, worker_id); 2329 } 2330 2331 void G1CollectedHeap::keep_alive(oop obj) { 2332 G1BarrierSet::enqueue(obj); 2333 } 2334 2335 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const { 2336 _hrm->iterate(cl); 2337 } 2338 2339 void G1CollectedHeap::heap_region_par_iterate_from_worker_offset(HeapRegionClosure* cl, 2340 HeapRegionClaimer *hrclaimer, 2341 uint worker_id) const { 2342 _hrm->par_iterate(cl, hrclaimer, hrclaimer->offset_for_worker(worker_id)); 2343 } 2344 2345 void G1CollectedHeap::heap_region_par_iterate_from_start(HeapRegionClosure* cl, 2346 HeapRegionClaimer *hrclaimer) const { 2347 _hrm->par_iterate(cl, hrclaimer, 0); 2348 } 2349 2350 void G1CollectedHeap::collection_set_iterate_all(HeapRegionClosure* cl) { 2351 _collection_set.iterate(cl); 2352 } 2353 2354 void G1CollectedHeap::collection_set_par_iterate_all(HeapRegionClosure* cl, HeapRegionClaimer* hr_claimer, uint worker_id) { 2355 _collection_set.par_iterate(cl, hr_claimer, worker_id, workers()->active_workers()); 2356 } 2357 2358 void G1CollectedHeap::collection_set_iterate_increment_from(HeapRegionClosure *cl, HeapRegionClaimer* hr_claimer, uint worker_id) { 2359 _collection_set.iterate_incremental_part_from(cl, hr_claimer, worker_id, workers()->active_workers()); 2360 } 2361 2362 HeapWord* G1CollectedHeap::block_start(const void* addr) const { 2363 HeapRegion* hr = heap_region_containing(addr); 2364 return hr->block_start(addr); 2365 } 2366 2367 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const { 2368 HeapRegion* hr = heap_region_containing(addr); 2369 return hr->block_is_obj(addr); 2370 } 2371 2372 bool G1CollectedHeap::supports_tlab_allocation() const { 2373 return true; 2374 } 2375 2376 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const { 2377 return (_policy->young_list_target_length() - _survivor.length()) * HeapRegion::GrainBytes; 2378 } 2379 2380 size_t G1CollectedHeap::tlab_used(Thread* ignored) const { 2381 return _eden.length() * HeapRegion::GrainBytes; 2382 } 2383 2384 // For G1 TLABs should not contain humongous objects, so the maximum TLAB size 2385 // must be equal to the humongous object limit. 2386 size_t G1CollectedHeap::max_tlab_size() const { 2387 return align_down(_humongous_object_threshold_in_words, MinObjAlignment); 2388 } 2389 2390 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const { 2391 return _allocator->unsafe_max_tlab_alloc(); 2392 } 2393 2394 size_t G1CollectedHeap::max_capacity() const { 2395 return _hrm->max_expandable_length() * HeapRegion::GrainBytes; 2396 } 2397 2398 size_t G1CollectedHeap::max_reserved_capacity() const { 2399 return _hrm->max_length() * HeapRegion::GrainBytes; 2400 } 2401 2402 void G1CollectedHeap::deduplicate_string(oop str) { 2403 assert(java_lang_String::is_instance(str), "invariant"); 2404 2405 if (G1StringDedup::is_enabled()) { 2406 G1StringDedup::deduplicate(str); 2407 } 2408 } 2409 2410 void G1CollectedHeap::prepare_for_verify() { 2411 _verifier->prepare_for_verify(); 2412 } 2413 2414 void G1CollectedHeap::verify(VerifyOption vo) { 2415 _verifier->verify(vo); 2416 } 2417 2418 bool G1CollectedHeap::supports_concurrent_gc_breakpoints() const { 2419 return true; 2420 } 2421 2422 bool G1CollectedHeap::is_heterogeneous_heap() const { 2423 return G1Arguments::is_heterogeneous_heap(); 2424 } 2425 2426 class PrintRegionClosure: public HeapRegionClosure { 2427 outputStream* _st; 2428 public: 2429 PrintRegionClosure(outputStream* st) : _st(st) {} 2430 bool do_heap_region(HeapRegion* r) { 2431 r->print_on(_st); 2432 return false; 2433 } 2434 }; 2435 2436 bool G1CollectedHeap::is_obj_dead_cond(const oop obj, 2437 const HeapRegion* hr, 2438 const VerifyOption vo) const { 2439 switch (vo) { 2440 case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj, hr); 2441 case VerifyOption_G1UseNextMarking: return is_obj_ill(obj, hr); 2442 case VerifyOption_G1UseFullMarking: return is_obj_dead_full(obj, hr); 2443 default: ShouldNotReachHere(); 2444 } 2445 return false; // keep some compilers happy 2446 } 2447 2448 bool G1CollectedHeap::is_obj_dead_cond(const oop obj, 2449 const VerifyOption vo) const { 2450 switch (vo) { 2451 case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj); 2452 case VerifyOption_G1UseNextMarking: return is_obj_ill(obj); 2453 case VerifyOption_G1UseFullMarking: return is_obj_dead_full(obj); 2454 default: ShouldNotReachHere(); 2455 } 2456 return false; // keep some compilers happy 2457 } 2458 2459 void G1CollectedHeap::print_heap_regions() const { 2460 LogTarget(Trace, gc, heap, region) lt; 2461 if (lt.is_enabled()) { 2462 LogStream ls(lt); 2463 print_regions_on(&ls); 2464 } 2465 } 2466 2467 void G1CollectedHeap::print_on(outputStream* st) const { 2468 st->print(" %-20s", "garbage-first heap"); 2469 if (_hrm != NULL) { 2470 st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K", 2471 capacity()/K, used_unlocked()/K); 2472 st->print(" [" PTR_FORMAT ", " PTR_FORMAT ")", 2473 p2i(_hrm->reserved().start()), 2474 p2i(_hrm->reserved().end())); 2475 } 2476 st->cr(); 2477 st->print(" region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K); 2478 uint young_regions = young_regions_count(); 2479 st->print("%u young (" SIZE_FORMAT "K), ", young_regions, 2480 (size_t) young_regions * HeapRegion::GrainBytes / K); 2481 uint survivor_regions = survivor_regions_count(); 2482 st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions, 2483 (size_t) survivor_regions * HeapRegion::GrainBytes / K); 2484 st->cr(); 2485 if (_numa->is_enabled()) { 2486 uint num_nodes = _numa->num_active_nodes(); 2487 st->print(" remaining free region(s) on each NUMA node: "); 2488 const int* node_ids = _numa->node_ids(); 2489 for (uint node_index = 0; node_index < num_nodes; node_index++) { 2490 uint num_free_regions = (_hrm != NULL ? _hrm->num_free_regions(node_index) : 0); 2491 st->print("%d=%u ", node_ids[node_index], num_free_regions); 2492 } 2493 st->cr(); 2494 } 2495 MetaspaceUtils::print_on(st); 2496 } 2497 2498 void G1CollectedHeap::print_regions_on(outputStream* st) const { 2499 if (_hrm == NULL) { 2500 return; 2501 } 2502 2503 st->print_cr("Heap Regions: E=young(eden), S=young(survivor), O=old, " 2504 "HS=humongous(starts), HC=humongous(continues), " 2505 "CS=collection set, F=free, " 2506 "OA=open archive, CA=closed archive, " 2507 "TAMS=top-at-mark-start (previous, next)"); 2508 PrintRegionClosure blk(st); 2509 heap_region_iterate(&blk); 2510 } 2511 2512 void G1CollectedHeap::print_extended_on(outputStream* st) const { 2513 print_on(st); 2514 2515 // Print the per-region information. 2516 if (_hrm != NULL) { 2517 st->cr(); 2518 print_regions_on(st); 2519 } 2520 } 2521 2522 void G1CollectedHeap::print_on_error(outputStream* st) const { 2523 this->CollectedHeap::print_on_error(st); 2524 2525 if (_cm != NULL) { 2526 st->cr(); 2527 _cm->print_on_error(st); 2528 } 2529 } 2530 2531 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const { 2532 workers()->threads_do(tc); 2533 tc->do_thread(_cm_thread); 2534 _cm->threads_do(tc); 2535 _cr->threads_do(tc); 2536 tc->do_thread(_service_thread); 2537 if (G1StringDedup::is_enabled()) { 2538 G1StringDedup::threads_do(tc); 2539 } 2540 } 2541 2542 void G1CollectedHeap::print_tracing_info() const { 2543 rem_set()->print_summary_info(); 2544 concurrent_mark()->print_summary_info(); 2545 } 2546 2547 #ifndef PRODUCT 2548 // Helpful for debugging RSet issues. 2549 2550 class PrintRSetsClosure : public HeapRegionClosure { 2551 private: 2552 const char* _msg; 2553 size_t _occupied_sum; 2554 2555 public: 2556 bool do_heap_region(HeapRegion* r) { 2557 HeapRegionRemSet* hrrs = r->rem_set(); 2558 size_t occupied = hrrs->occupied(); 2559 _occupied_sum += occupied; 2560 2561 tty->print_cr("Printing RSet for region " HR_FORMAT, HR_FORMAT_PARAMS(r)); 2562 if (occupied == 0) { 2563 tty->print_cr(" RSet is empty"); 2564 } else { 2565 hrrs->print(); 2566 } 2567 tty->print_cr("----------"); 2568 return false; 2569 } 2570 2571 PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) { 2572 tty->cr(); 2573 tty->print_cr("========================================"); 2574 tty->print_cr("%s", msg); 2575 tty->cr(); 2576 } 2577 2578 ~PrintRSetsClosure() { 2579 tty->print_cr("Occupied Sum: " SIZE_FORMAT, _occupied_sum); 2580 tty->print_cr("========================================"); 2581 tty->cr(); 2582 } 2583 }; 2584 2585 void G1CollectedHeap::print_cset_rsets() { 2586 PrintRSetsClosure cl("Printing CSet RSets"); 2587 collection_set_iterate_all(&cl); 2588 } 2589 2590 void G1CollectedHeap::print_all_rsets() { 2591 PrintRSetsClosure cl("Printing All RSets");; 2592 heap_region_iterate(&cl); 2593 } 2594 #endif // PRODUCT 2595 2596 bool G1CollectedHeap::print_location(outputStream* st, void* addr) const { 2597 return BlockLocationPrinter<G1CollectedHeap>::print_location(st, addr); 2598 } 2599 2600 G1HeapSummary G1CollectedHeap::create_g1_heap_summary() { 2601 2602 size_t eden_used_bytes = _eden.used_bytes(); 2603 size_t survivor_used_bytes = _survivor.used_bytes(); 2604 size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked(); 2605 2606 size_t eden_capacity_bytes = 2607 (policy()->young_list_target_length() * HeapRegion::GrainBytes) - survivor_used_bytes; 2608 2609 VirtualSpaceSummary heap_summary = create_heap_space_summary(); 2610 return G1HeapSummary(heap_summary, heap_used, eden_used_bytes, 2611 eden_capacity_bytes, survivor_used_bytes, num_regions()); 2612 } 2613 2614 G1EvacSummary G1CollectedHeap::create_g1_evac_summary(G1EvacStats* stats) { 2615 return G1EvacSummary(stats->allocated(), stats->wasted(), stats->undo_wasted(), 2616 stats->unused(), stats->used(), stats->region_end_waste(), 2617 stats->regions_filled(), stats->direct_allocated(), 2618 stats->failure_used(), stats->failure_waste()); 2619 } 2620 2621 void G1CollectedHeap::trace_heap(GCWhen::Type when, const GCTracer* gc_tracer) { 2622 const G1HeapSummary& heap_summary = create_g1_heap_summary(); 2623 gc_tracer->report_gc_heap_summary(when, heap_summary); 2624 2625 const MetaspaceSummary& metaspace_summary = create_metaspace_summary(); 2626 gc_tracer->report_metaspace_summary(when, metaspace_summary); 2627 } 2628 2629 void G1CollectedHeap::gc_prologue(bool full) { 2630 assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer"); 2631 2632 // This summary needs to be printed before incrementing total collections. 2633 rem_set()->print_periodic_summary_info("Before GC RS summary", total_collections()); 2634 2635 // Update common counters. 2636 increment_total_collections(full /* full gc */); 2637 if (full || collector_state()->in_concurrent_start_gc()) { 2638 increment_old_marking_cycles_started(); 2639 } 2640 2641 // Fill TLAB's and such 2642 { 2643 Ticks start = Ticks::now(); 2644 ensure_parsability(true); 2645 Tickspan dt = Ticks::now() - start; 2646 phase_times()->record_prepare_tlab_time_ms(dt.seconds() * MILLIUNITS); 2647 } 2648 2649 if (!full) { 2650 // Flush dirty card queues to qset, so later phases don't need to account 2651 // for partially filled per-thread queues and such. Not needed for full 2652 // collections, which ignore those logs. 2653 Ticks start = Ticks::now(); 2654 G1BarrierSet::dirty_card_queue_set().concatenate_logs(); 2655 Tickspan dt = Ticks::now() - start; 2656 phase_times()->record_concatenate_dirty_card_logs_time_ms(dt.seconds() * MILLIUNITS); 2657 } 2658 } 2659 2660 void G1CollectedHeap::gc_epilogue(bool full) { 2661 // Update common counters. 2662 if (full) { 2663 // Update the number of full collections that have been completed. 2664 increment_old_marking_cycles_completed(false /* concurrent */, true /* liveness_completed */); 2665 } 2666 2667 // We are at the end of the GC. Total collections has already been increased. 2668 rem_set()->print_periodic_summary_info("After GC RS summary", total_collections() - 1); 2669 2670 // FIXME: what is this about? 2671 // I'm ignoring the "fill_newgen()" call if "alloc_event_enabled" 2672 // is set. 2673 #if COMPILER2_OR_JVMCI 2674 assert(DerivedPointerTable::is_empty(), "derived pointer present"); 2675 #endif 2676 2677 double start = os::elapsedTime(); 2678 resize_all_tlabs(); 2679 phase_times()->record_resize_tlab_time_ms((os::elapsedTime() - start) * 1000.0); 2680 2681 MemoryService::track_memory_usage(); 2682 // We have just completed a GC. Update the soft reference 2683 // policy with the new heap occupancy 2684 Universe::update_heap_info_at_gc(); 2685 2686 // Print NUMA statistics. 2687 _numa->print_statistics(); 2688 2689 _collection_pause_end = Ticks::now(); 2690 } 2691 2692 void G1CollectedHeap::verify_numa_regions(const char* desc) { 2693 LogTarget(Trace, gc, heap, verify) lt; 2694 2695 if (lt.is_enabled()) { 2696 LogStream ls(lt); 2697 // Iterate all heap regions to print matching between preferred numa id and actual numa id. 2698 G1NodeIndexCheckClosure cl(desc, _numa, &ls); 2699 heap_region_iterate(&cl); 2700 } 2701 } 2702 2703 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size, 2704 uint gc_count_before, 2705 bool* succeeded, 2706 GCCause::Cause gc_cause) { 2707 assert_heap_not_locked_and_not_at_safepoint(); 2708 VM_G1CollectForAllocation op(word_size, 2709 gc_count_before, 2710 gc_cause, 2711 policy()->max_pause_time_ms()); 2712 VMThread::execute(&op); 2713 2714 HeapWord* result = op.result(); 2715 bool ret_succeeded = op.prologue_succeeded() && op.gc_succeeded(); 2716 assert(result == NULL || ret_succeeded, 2717 "the result should be NULL if the VM did not succeed"); 2718 *succeeded = ret_succeeded; 2719 2720 assert_heap_not_locked(); 2721 return result; 2722 } 2723 2724 void G1CollectedHeap::do_concurrent_mark() { 2725 MutexLocker x(CGC_lock, Mutex::_no_safepoint_check_flag); 2726 if (!_cm_thread->in_progress()) { 2727 _cm_thread->set_started(); 2728 CGC_lock->notify(); 2729 } 2730 } 2731 2732 bool G1CollectedHeap::is_potential_eager_reclaim_candidate(HeapRegion* r) const { 2733 // We don't nominate objects with many remembered set entries, on 2734 // the assumption that such objects are likely still live. 2735 HeapRegionRemSet* rem_set = r->rem_set(); 2736 2737 return G1EagerReclaimHumongousObjectsWithStaleRefs ? 2738 rem_set->occupancy_less_or_equal_than(G1RSetSparseRegionEntries) : 2739 G1EagerReclaimHumongousObjects && rem_set->is_empty(); 2740 } 2741 2742 #ifndef PRODUCT 2743 void G1CollectedHeap::verify_region_attr_remset_update() { 2744 class VerifyRegionAttrRemSet : public HeapRegionClosure { 2745 public: 2746 virtual bool do_heap_region(HeapRegion* r) { 2747 G1CollectedHeap* g1h = G1CollectedHeap::heap(); 2748 bool const needs_remset_update = g1h->region_attr(r->bottom()).needs_remset_update(); 2749 assert(r->rem_set()->is_tracked() == needs_remset_update, 2750 "Region %u remset tracking status (%s) different to region attribute (%s)", 2751 r->hrm_index(), BOOL_TO_STR(r->rem_set()->is_tracked()), BOOL_TO_STR(needs_remset_update)); 2752 return false; 2753 } 2754 } cl; 2755 heap_region_iterate(&cl); 2756 } 2757 #endif 2758 2759 class VerifyRegionRemSetClosure : public HeapRegionClosure { 2760 public: 2761 bool do_heap_region(HeapRegion* hr) { 2762 if (!hr->is_archive() && !hr->is_continues_humongous()) { 2763 hr->verify_rem_set(); 2764 } 2765 return false; 2766 } 2767 }; 2768 2769 uint G1CollectedHeap::num_task_queues() const { 2770 return _task_queues->size(); 2771 } 2772 2773 #if TASKQUEUE_STATS 2774 void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) { 2775 st->print_raw_cr("GC Task Stats"); 2776 st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr(); 2777 st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr(); 2778 } 2779 2780 void G1CollectedHeap::print_taskqueue_stats() const { 2781 if (!log_is_enabled(Trace, gc, task, stats)) { 2782 return; 2783 } 2784 Log(gc, task, stats) log; 2785 ResourceMark rm; 2786 LogStream ls(log.trace()); 2787 outputStream* st = &ls; 2788 2789 print_taskqueue_stats_hdr(st); 2790 2791 TaskQueueStats totals; 2792 const uint n = num_task_queues(); 2793 for (uint i = 0; i < n; ++i) { 2794 st->print("%3u ", i); task_queue(i)->stats.print(st); st->cr(); 2795 totals += task_queue(i)->stats; 2796 } 2797 st->print_raw("tot "); totals.print(st); st->cr(); 2798 2799 DEBUG_ONLY(totals.verify()); 2800 } 2801 2802 void G1CollectedHeap::reset_taskqueue_stats() { 2803 const uint n = num_task_queues(); 2804 for (uint i = 0; i < n; ++i) { 2805 task_queue(i)->stats.reset(); 2806 } 2807 } 2808 #endif // TASKQUEUE_STATS 2809 2810 void G1CollectedHeap::wait_for_root_region_scanning() { 2811 double scan_wait_start = os::elapsedTime(); 2812 // We have to wait until the CM threads finish scanning the 2813 // root regions as it's the only way to ensure that all the 2814 // objects on them have been correctly scanned before we start 2815 // moving them during the GC. 2816 bool waited = _cm->root_regions()->wait_until_scan_finished(); 2817 double wait_time_ms = 0.0; 2818 if (waited) { 2819 double scan_wait_end = os::elapsedTime(); 2820 wait_time_ms = (scan_wait_end - scan_wait_start) * 1000.0; 2821 } 2822 phase_times()->record_root_region_scan_wait_time(wait_time_ms); 2823 } 2824 2825 class G1PrintCollectionSetClosure : public HeapRegionClosure { 2826 private: 2827 G1HRPrinter* _hr_printer; 2828 public: 2829 G1PrintCollectionSetClosure(G1HRPrinter* hr_printer) : HeapRegionClosure(), _hr_printer(hr_printer) { } 2830 2831 virtual bool do_heap_region(HeapRegion* r) { 2832 _hr_printer->cset(r); 2833 return false; 2834 } 2835 }; 2836 2837 void G1CollectedHeap::start_new_collection_set() { 2838 double start = os::elapsedTime(); 2839 2840 collection_set()->start_incremental_building(); 2841 2842 clear_region_attr(); 2843 2844 guarantee(_eden.length() == 0, "eden should have been cleared"); 2845 policy()->transfer_survivors_to_cset(survivor()); 2846 2847 // We redo the verification but now wrt to the new CSet which 2848 // has just got initialized after the previous CSet was freed. 2849 _cm->verify_no_collection_set_oops(); 2850 2851 phase_times()->record_start_new_cset_time_ms((os::elapsedTime() - start) * 1000.0); 2852 } 2853 2854 void G1CollectedHeap::calculate_collection_set(G1EvacuationInfo& evacuation_info, double target_pause_time_ms) { 2855 2856 _collection_set.finalize_initial_collection_set(target_pause_time_ms, &_survivor); 2857 evacuation_info.set_collectionset_regions(collection_set()->region_length() + 2858 collection_set()->optional_region_length()); 2859 2860 _cm->verify_no_collection_set_oops(); 2861 2862 if (_hr_printer.is_active()) { 2863 G1PrintCollectionSetClosure cl(&_hr_printer); 2864 _collection_set.iterate(&cl); 2865 _collection_set.iterate_optional(&cl); 2866 } 2867 } 2868 2869 G1HeapVerifier::G1VerifyType G1CollectedHeap::young_collection_verify_type() const { 2870 if (collector_state()->in_concurrent_start_gc()) { 2871 return G1HeapVerifier::G1VerifyConcurrentStart; 2872 } else if (collector_state()->in_young_only_phase()) { 2873 return G1HeapVerifier::G1VerifyYoungNormal; 2874 } else { 2875 return G1HeapVerifier::G1VerifyMixed; 2876 } 2877 } 2878 2879 void G1CollectedHeap::verify_before_young_collection(G1HeapVerifier::G1VerifyType type) { 2880 if (VerifyRememberedSets) { 2881 log_info(gc, verify)("[Verifying RemSets before GC]"); 2882 VerifyRegionRemSetClosure v_cl; 2883 heap_region_iterate(&v_cl); 2884 } 2885 _verifier->verify_before_gc(type); 2886 _verifier->check_bitmaps("GC Start"); 2887 verify_numa_regions("GC Start"); 2888 } 2889 2890 void G1CollectedHeap::verify_after_young_collection(G1HeapVerifier::G1VerifyType type) { 2891 if (VerifyRememberedSets) { 2892 log_info(gc, verify)("[Verifying RemSets after GC]"); 2893 VerifyRegionRemSetClosure v_cl; 2894 heap_region_iterate(&v_cl); 2895 } 2896 _verifier->verify_after_gc(type); 2897 _verifier->check_bitmaps("GC End"); 2898 verify_numa_regions("GC End"); 2899 } 2900 2901 void G1CollectedHeap::expand_heap_after_young_collection(){ 2902 size_t expand_bytes = _heap_sizing_policy->young_collection_expansion_amount(); 2903 if (expand_bytes > 0) { 2904 // No need for an ergo logging here, 2905 // expansion_amount() does this when it returns a value > 0. 2906 double expand_ms; 2907 if (!expand(expand_bytes, _workers, &expand_ms)) { 2908 // We failed to expand the heap. Cannot do anything about it. 2909 } 2910 phase_times()->record_expand_heap_time(expand_ms); 2911 } 2912 } 2913 2914 const char* G1CollectedHeap::young_gc_name() const { 2915 if (collector_state()->in_concurrent_start_gc()) { 2916 return "Pause Young (Concurrent Start)"; 2917 } else if (collector_state()->in_young_only_phase()) { 2918 if (collector_state()->in_young_gc_before_mixed()) { 2919 return "Pause Young (Prepare Mixed)"; 2920 } else { 2921 return "Pause Young (Normal)"; 2922 } 2923 } else { 2924 return "Pause Young (Mixed)"; 2925 } 2926 } 2927 2928 bool G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) { 2929 assert_at_safepoint_on_vm_thread(); 2930 guarantee(!is_gc_active(), "collection is not reentrant"); 2931 2932 if (GCLocker::check_active_before_gc()) { 2933 return false; 2934 } 2935 2936 do_collection_pause_at_safepoint_helper(target_pause_time_ms); 2937 if (should_upgrade_to_full_gc(gc_cause())) { 2938 log_info(gc, ergo)("Attempting maximally compacting collection"); 2939 bool result = do_full_collection(false /* explicit gc */, 2940 true /* clear_all_soft_refs */); 2941 // do_full_collection only fails if blocked by GC locker, but 2942 // we've already checked for that above. 2943 assert(result, "invariant"); 2944 } 2945 return true; 2946 } 2947 2948 void G1CollectedHeap::do_collection_pause_at_safepoint_helper(double target_pause_time_ms) { 2949 GCIdMark gc_id_mark; 2950 2951 SvcGCMarker sgcm(SvcGCMarker::MINOR); 2952 ResourceMark rm; 2953 2954 policy()->note_gc_start(); 2955 2956 _gc_timer_stw->register_gc_start(); 2957 _gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start()); 2958 2959 wait_for_root_region_scanning(); 2960 2961 print_heap_before_gc(); 2962 print_heap_regions(); 2963 trace_heap_before_gc(_gc_tracer_stw); 2964 2965 _verifier->verify_region_sets_optional(); 2966 _verifier->verify_dirty_young_regions(); 2967 2968 // We should not be doing concurrent start unless the concurrent mark thread is running 2969 if (!_cm_thread->should_terminate()) { 2970 // This call will decide whether this pause is a concurrent start 2971 // pause. If it is, in_concurrent_start_gc() will return true 2972 // for the duration of this pause. 2973 policy()->decide_on_conc_mark_initiation(); 2974 } 2975 2976 // We do not allow concurrent start to be piggy-backed on a mixed GC. 2977 assert(!collector_state()->in_concurrent_start_gc() || 2978 collector_state()->in_young_only_phase(), "sanity"); 2979 // We also do not allow mixed GCs during marking. 2980 assert(!collector_state()->mark_or_rebuild_in_progress() || collector_state()->in_young_only_phase(), "sanity"); 2981 2982 // Record whether this pause is a concurrent start. When the current 2983 // thread has completed its logging output and it's safe to signal 2984 // the CM thread, the flag's value in the policy has been reset. 2985 bool should_start_conc_mark = collector_state()->in_concurrent_start_gc(); 2986 if (should_start_conc_mark) { 2987 _cm->gc_tracer_cm()->set_gc_cause(gc_cause()); 2988 } 2989 2990 // Inner scope for scope based logging, timers, and stats collection 2991 { 2992 G1EvacuationInfo evacuation_info; 2993 2994 _gc_tracer_stw->report_yc_type(collector_state()->yc_type()); 2995 2996 GCTraceCPUTime tcpu; 2997 2998 GCTraceTime(Info, gc) tm(young_gc_name(), NULL, gc_cause(), true); 2999 3000 uint active_workers = WorkerPolicy::calc_active_workers(workers()->total_workers(), 3001 workers()->active_workers(), 3002 Threads::number_of_non_daemon_threads()); 3003 active_workers = workers()->update_active_workers(active_workers); 3004 log_info(gc,task)("Using %u workers of %u for evacuation", active_workers, workers()->total_workers()); 3005 3006 G1MonitoringScope ms(g1mm(), 3007 false /* full_gc */, 3008 collector_state()->yc_type() == Mixed /* all_memory_pools_affected */); 3009 3010 G1HeapTransition heap_transition(this); 3011 3012 { 3013 IsGCActiveMark x; 3014 3015 gc_prologue(false); 3016 3017 G1HeapVerifier::G1VerifyType verify_type = young_collection_verify_type(); 3018 verify_before_young_collection(verify_type); 3019 3020 { 3021 // The elapsed time induced by the start time below deliberately elides 3022 // the possible verification above. 3023 double sample_start_time_sec = os::elapsedTime(); 3024 3025 // Please see comment in g1CollectedHeap.hpp and 3026 // G1CollectedHeap::ref_processing_init() to see how 3027 // reference processing currently works in G1. 3028 _ref_processor_stw->enable_discovery(); 3029 3030 // We want to temporarily turn off discovery by the 3031 // CM ref processor, if necessary, and turn it back on 3032 // on again later if we do. Using a scoped 3033 // NoRefDiscovery object will do this. 3034 NoRefDiscovery no_cm_discovery(_ref_processor_cm); 3035 3036 policy()->record_collection_pause_start(sample_start_time_sec); 3037 3038 // Forget the current allocation region (we might even choose it to be part 3039 // of the collection set!). 3040 _allocator->release_mutator_alloc_regions(); 3041 3042 calculate_collection_set(evacuation_info, target_pause_time_ms); 3043 3044 G1RedirtyCardsQueueSet rdcqs(G1BarrierSet::dirty_card_queue_set().allocator()); 3045 G1ParScanThreadStateSet per_thread_states(this, 3046 &rdcqs, 3047 workers()->active_workers(), 3048 collection_set()->young_region_length(), 3049 collection_set()->optional_region_length()); 3050 pre_evacuate_collection_set(evacuation_info, &per_thread_states); 3051 3052 // Actually do the work... 3053 evacuate_initial_collection_set(&per_thread_states); 3054 3055 if (_collection_set.optional_region_length() != 0) { 3056 evacuate_optional_collection_set(&per_thread_states); 3057 } 3058 post_evacuate_collection_set(evacuation_info, &rdcqs, &per_thread_states); 3059 3060 start_new_collection_set(); 3061 3062 _survivor_evac_stats.adjust_desired_plab_sz(); 3063 _old_evac_stats.adjust_desired_plab_sz(); 3064 3065 if (should_start_conc_mark) { 3066 // We have to do this before we notify the CM threads that 3067 // they can start working to make sure that all the 3068 // appropriate initialization is done on the CM object. 3069 concurrent_mark()->post_concurrent_start(); 3070 // Note that we don't actually trigger the CM thread at 3071 // this point. We do that later when we're sure that 3072 // the current thread has completed its logging output. 3073 } 3074 3075 allocate_dummy_regions(); 3076 3077 _allocator->init_mutator_alloc_regions(); 3078 3079 expand_heap_after_young_collection(); 3080 3081 double sample_end_time_sec = os::elapsedTime(); 3082 double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS; 3083 policy()->record_collection_pause_end(pause_time_ms); 3084 } 3085 3086 verify_after_young_collection(verify_type); 3087 3088 gc_epilogue(false); 3089 } 3090 3091 // Print the remainder of the GC log output. 3092 if (evacuation_failed()) { 3093 log_info(gc)("To-space exhausted"); 3094 } 3095 3096 policy()->print_phases(); 3097 heap_transition.print(); 3098 3099 _hrm->verify_optional(); 3100 _verifier->verify_region_sets_optional(); 3101 3102 TASKQUEUE_STATS_ONLY(print_taskqueue_stats()); 3103 TASKQUEUE_STATS_ONLY(reset_taskqueue_stats()); 3104 3105 print_heap_after_gc(); 3106 print_heap_regions(); 3107 trace_heap_after_gc(_gc_tracer_stw); 3108 3109 // We must call G1MonitoringSupport::update_sizes() in the same scoping level 3110 // as an active TraceMemoryManagerStats object (i.e. before the destructor for the 3111 // TraceMemoryManagerStats is called) so that the G1 memory pools are updated 3112 // before any GC notifications are raised. 3113 g1mm()->update_sizes(); 3114 3115 _gc_tracer_stw->report_evacuation_info(&evacuation_info); 3116 _gc_tracer_stw->report_tenuring_threshold(_policy->tenuring_threshold()); 3117 _gc_timer_stw->register_gc_end(); 3118 _gc_tracer_stw->report_gc_end(_gc_timer_stw->gc_end(), _gc_timer_stw->time_partitions()); 3119 } 3120 // It should now be safe to tell the concurrent mark thread to start 3121 // without its logging output interfering with the logging output 3122 // that came from the pause. 3123 3124 if (should_start_conc_mark) { 3125 // CAUTION: after the doConcurrentMark() call below, the concurrent marking 3126 // thread(s) could be running concurrently with us. Make sure that anything 3127 // after this point does not assume that we are the only GC thread running. 3128 // Note: of course, the actual marking work will not start until the safepoint 3129 // itself is released in SuspendibleThreadSet::desynchronize(). 3130 do_concurrent_mark(); 3131 ConcurrentGCBreakpoints::notify_idle_to_active(); 3132 } 3133 } 3134 3135 void G1CollectedHeap::remove_self_forwarding_pointers(G1RedirtyCardsQueueSet* rdcqs) { 3136 G1ParRemoveSelfForwardPtrsTask rsfp_task(rdcqs); 3137 workers()->run_task(&rsfp_task); 3138 } 3139 3140 void G1CollectedHeap::restore_after_evac_failure(G1RedirtyCardsQueueSet* rdcqs) { 3141 double remove_self_forwards_start = os::elapsedTime(); 3142 3143 remove_self_forwarding_pointers(rdcqs); 3144 _preserved_marks_set.restore(workers()); 3145 3146 phase_times()->record_evac_fail_remove_self_forwards((os::elapsedTime() - remove_self_forwards_start) * 1000.0); 3147 } 3148 3149 void G1CollectedHeap::preserve_mark_during_evac_failure(uint worker_id, oop obj, markWord m) { 3150 if (!_evacuation_failed) { 3151 _evacuation_failed = true; 3152 } 3153 3154 _evacuation_failed_info_array[worker_id].register_copy_failure(obj->size()); 3155 _preserved_marks_set.get(worker_id)->push_if_necessary(obj, m); 3156 } 3157 3158 bool G1ParEvacuateFollowersClosure::offer_termination() { 3159 EventGCPhaseParallel event; 3160 G1ParScanThreadState* const pss = par_scan_state(); 3161 start_term_time(); 3162 const bool res = terminator()->offer_termination(); 3163 end_term_time(); 3164 event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(G1GCPhaseTimes::Termination)); 3165 return res; 3166 } 3167 3168 void G1ParEvacuateFollowersClosure::do_void() { 3169 EventGCPhaseParallel event; 3170 G1ParScanThreadState* const pss = par_scan_state(); 3171 pss->trim_queue(); 3172 event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase)); 3173 do { 3174 EventGCPhaseParallel event; 3175 pss->steal_and_trim_queue(queues()); 3176 event.commit(GCId::current(), pss->worker_id(), G1GCPhaseTimes::phase_name(_phase)); 3177 } while (!offer_termination()); 3178 } 3179 3180 void G1CollectedHeap::complete_cleaning(BoolObjectClosure* is_alive, 3181 bool class_unloading_occurred) { 3182 uint num_workers = workers()->active_workers(); 3183 G1ParallelCleaningTask unlink_task(is_alive, num_workers, class_unloading_occurred, false); 3184 workers()->run_task(&unlink_task); 3185 } 3186 3187 // Clean string dedup data structures. 3188 // Ideally we would prefer to use a StringDedupCleaningTask here, but we want to 3189 // record the durations of the phases. Hence the almost-copy. 3190 class G1StringDedupCleaningTask : public AbstractGangTask { 3191 BoolObjectClosure* _is_alive; 3192 OopClosure* _keep_alive; 3193 G1GCPhaseTimes* _phase_times; 3194 3195 public: 3196 G1StringDedupCleaningTask(BoolObjectClosure* is_alive, 3197 OopClosure* keep_alive, 3198 G1GCPhaseTimes* phase_times) : 3199 AbstractGangTask("Partial Cleaning Task"), 3200 _is_alive(is_alive), 3201 _keep_alive(keep_alive), 3202 _phase_times(phase_times) 3203 { 3204 assert(G1StringDedup::is_enabled(), "String deduplication disabled."); 3205 StringDedup::gc_prologue(true); 3206 } 3207 3208 ~G1StringDedupCleaningTask() { 3209 StringDedup::gc_epilogue(); 3210 } 3211 3212 void work(uint worker_id) { 3213 StringDedupUnlinkOrOopsDoClosure cl(_is_alive, _keep_alive); 3214 { 3215 G1GCParPhaseTimesTracker x(_phase_times, G1GCPhaseTimes::StringDedupQueueFixup, worker_id); 3216 StringDedupQueue::unlink_or_oops_do(&cl); 3217 } 3218 { 3219 G1GCParPhaseTimesTracker x(_phase_times, G1GCPhaseTimes::StringDedupTableFixup, worker_id); 3220 StringDedupTable::unlink_or_oops_do(&cl, worker_id); 3221 } 3222 } 3223 }; 3224 3225 void G1CollectedHeap::string_dedup_cleaning(BoolObjectClosure* is_alive, 3226 OopClosure* keep_alive, 3227 G1GCPhaseTimes* phase_times) { 3228 G1StringDedupCleaningTask cl(is_alive, keep_alive, phase_times); 3229 workers()->run_task(&cl); 3230 } 3231 3232 class G1RedirtyLoggedCardsTask : public AbstractGangTask { 3233 private: 3234 G1RedirtyCardsQueueSet* _qset; 3235 G1CollectedHeap* _g1h; 3236 BufferNode* volatile _nodes; 3237 3238 void par_apply(RedirtyLoggedCardTableEntryClosure* cl, uint worker_id) { 3239 size_t buffer_size = _qset->buffer_size(); 3240 BufferNode* next = Atomic::load(&_nodes); 3241 while (next != NULL) { 3242 BufferNode* node = next; 3243 next = Atomic::cmpxchg(&_nodes, node, node->next()); 3244 if (next == node) { 3245 cl->apply_to_buffer(node, buffer_size, worker_id); 3246 next = node->next(); 3247 } 3248 } 3249 } 3250 3251 public: 3252 G1RedirtyLoggedCardsTask(G1RedirtyCardsQueueSet* qset, G1CollectedHeap* g1h) : 3253 AbstractGangTask("Redirty Cards"), 3254 _qset(qset), _g1h(g1h), _nodes(qset->all_completed_buffers()) { } 3255 3256 virtual void work(uint worker_id) { 3257 G1GCPhaseTimes* p = _g1h->phase_times(); 3258 G1GCParPhaseTimesTracker x(p, G1GCPhaseTimes::RedirtyCards, worker_id); 3259 3260 RedirtyLoggedCardTableEntryClosure cl(_g1h); 3261 par_apply(&cl, worker_id); 3262 3263 p->record_thread_work_item(G1GCPhaseTimes::RedirtyCards, worker_id, cl.num_dirtied()); 3264 } 3265 }; 3266 3267 void G1CollectedHeap::redirty_logged_cards(G1RedirtyCardsQueueSet* rdcqs) { 3268 double redirty_logged_cards_start = os::elapsedTime(); 3269 3270 G1RedirtyLoggedCardsTask redirty_task(rdcqs, this); 3271 workers()->run_task(&redirty_task); 3272 3273 G1DirtyCardQueueSet& dcq = G1BarrierSet::dirty_card_queue_set(); 3274 dcq.merge_bufferlists(rdcqs); 3275 3276 phase_times()->record_redirty_logged_cards_time_ms((os::elapsedTime() - redirty_logged_cards_start) * 1000.0); 3277 } 3278 3279 // Weak Reference Processing support 3280 3281 bool G1STWIsAliveClosure::do_object_b(oop p) { 3282 // An object is reachable if it is outside the collection set, 3283 // or is inside and copied. 3284 return !_g1h->is_in_cset(p) || p->is_forwarded(); 3285 } 3286 3287 bool G1STWSubjectToDiscoveryClosure::do_object_b(oop obj) { 3288 assert(obj != NULL, "must not be NULL"); 3289 assert(_g1h->is_in_reserved(obj), "Trying to discover obj " PTR_FORMAT " not in heap", p2i(obj)); 3290 // The areas the CM and STW ref processor manage must be disjoint. The is_in_cset() below 3291 // may falsely indicate that this is not the case here: however the collection set only 3292 // contains old regions when concurrent mark is not running. 3293 return _g1h->is_in_cset(obj) || _g1h->heap_region_containing(obj)->is_survivor(); 3294 } 3295 3296 // Non Copying Keep Alive closure 3297 class G1KeepAliveClosure: public OopClosure { 3298 G1CollectedHeap*_g1h; 3299 public: 3300 G1KeepAliveClosure(G1CollectedHeap* g1h) :_g1h(g1h) {} 3301 void do_oop(narrowOop* p) { guarantee(false, "Not needed"); } 3302 void do_oop(oop* p) { 3303 oop obj = *p; 3304 assert(obj != NULL, "the caller should have filtered out NULL values"); 3305 3306 const G1HeapRegionAttr region_attr =_g1h->region_attr(obj); 3307 if (!region_attr.is_in_cset_or_humongous()) { 3308 return; 3309 } 3310 if (region_attr.is_in_cset()) { 3311 assert( obj->is_forwarded(), "invariant" ); 3312 *p = obj->forwardee(); 3313 } else { 3314 assert(!obj->is_forwarded(), "invariant" ); 3315 assert(region_attr.is_humongous(), 3316 "Only allowed G1HeapRegionAttr state is IsHumongous, but is %d", region_attr.type()); 3317 _g1h->set_humongous_is_live(obj); 3318 } 3319 } 3320 }; 3321 3322 // Copying Keep Alive closure - can be called from both 3323 // serial and parallel code as long as different worker 3324 // threads utilize different G1ParScanThreadState instances 3325 // and different queues. 3326 3327 class G1CopyingKeepAliveClosure: public OopClosure { 3328 G1CollectedHeap* _g1h; 3329 G1ParScanThreadState* _par_scan_state; 3330 3331 public: 3332 G1CopyingKeepAliveClosure(G1CollectedHeap* g1h, 3333 G1ParScanThreadState* pss): 3334 _g1h(g1h), 3335 _par_scan_state(pss) 3336 {} 3337 3338 virtual void do_oop(narrowOop* p) { do_oop_work(p); } 3339 virtual void do_oop( oop* p) { do_oop_work(p); } 3340 3341 template <class T> void do_oop_work(T* p) { 3342 oop obj = RawAccess<>::oop_load(p); 3343 3344 if (_g1h->is_in_cset_or_humongous(obj)) { 3345 // If the referent object has been forwarded (either copied 3346 // to a new location or to itself in the event of an 3347 // evacuation failure) then we need to update the reference 3348 // field and, if both reference and referent are in the G1 3349 // heap, update the RSet for the referent. 3350 // 3351 // If the referent has not been forwarded then we have to keep 3352 // it alive by policy. Therefore we have copy the referent. 3353 // 3354 // When the queue is drained (after each phase of reference processing) 3355 // the object and it's followers will be copied, the reference field set 3356 // to point to the new location, and the RSet updated. 3357 _par_scan_state->push_on_queue(ScannerTask(p)); 3358 } 3359 } 3360 }; 3361 3362 // Serial drain queue closure. Called as the 'complete_gc' 3363 // closure for each discovered list in some of the 3364 // reference processing phases. 3365 3366 class G1STWDrainQueueClosure: public VoidClosure { 3367 protected: 3368 G1CollectedHeap* _g1h; 3369 G1ParScanThreadState* _par_scan_state; 3370 3371 G1ParScanThreadState* par_scan_state() { return _par_scan_state; } 3372 3373 public: 3374 G1STWDrainQueueClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) : 3375 _g1h(g1h), 3376 _par_scan_state(pss) 3377 { } 3378 3379 void do_void() { 3380 G1ParScanThreadState* const pss = par_scan_state(); 3381 pss->trim_queue(); 3382 } 3383 }; 3384 3385 // Parallel Reference Processing closures 3386 3387 // Implementation of AbstractRefProcTaskExecutor for parallel reference 3388 // processing during G1 evacuation pauses. 3389 3390 class G1STWRefProcTaskExecutor: public AbstractRefProcTaskExecutor { 3391 private: 3392 G1CollectedHeap* _g1h; 3393 G1ParScanThreadStateSet* _pss; 3394 G1ScannerTasksQueueSet* _queues; 3395 WorkGang* _workers; 3396 3397 public: 3398 G1STWRefProcTaskExecutor(G1CollectedHeap* g1h, 3399 G1ParScanThreadStateSet* per_thread_states, 3400 WorkGang* workers, 3401 G1ScannerTasksQueueSet *task_queues) : 3402 _g1h(g1h), 3403 _pss(per_thread_states), 3404 _queues(task_queues), 3405 _workers(workers) 3406 { 3407 g1h->ref_processor_stw()->set_active_mt_degree(workers->active_workers()); 3408 } 3409 3410 // Executes the given task using concurrent marking worker threads. 3411 virtual void execute(ProcessTask& task, uint ergo_workers); 3412 }; 3413 3414 // Gang task for possibly parallel reference processing 3415 3416 class G1STWRefProcTaskProxy: public AbstractGangTask { 3417 typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask; 3418 ProcessTask& _proc_task; 3419 G1CollectedHeap* _g1h; 3420 G1ParScanThreadStateSet* _pss; 3421 G1ScannerTasksQueueSet* _task_queues; 3422 TaskTerminator* _terminator; 3423 3424 public: 3425 G1STWRefProcTaskProxy(ProcessTask& proc_task, 3426 G1CollectedHeap* g1h, 3427 G1ParScanThreadStateSet* per_thread_states, 3428 G1ScannerTasksQueueSet *task_queues, 3429 TaskTerminator* terminator) : 3430 AbstractGangTask("Process reference objects in parallel"), 3431 _proc_task(proc_task), 3432 _g1h(g1h), 3433 _pss(per_thread_states), 3434 _task_queues(task_queues), 3435 _terminator(terminator) 3436 {} 3437 3438 virtual void work(uint worker_id) { 3439 // The reference processing task executed by a single worker. 3440 ResourceMark rm; 3441 3442 G1STWIsAliveClosure is_alive(_g1h); 3443 3444 G1ParScanThreadState* pss = _pss->state_for_worker(worker_id); 3445 pss->set_ref_discoverer(NULL); 3446 3447 // Keep alive closure. 3448 G1CopyingKeepAliveClosure keep_alive(_g1h, pss); 3449 3450 // Complete GC closure 3451 G1ParEvacuateFollowersClosure drain_queue(_g1h, pss, _task_queues, _terminator, G1GCPhaseTimes::ObjCopy); 3452 3453 // Call the reference processing task's work routine. 3454 _proc_task.work(worker_id, is_alive, keep_alive, drain_queue); 3455 3456 // Note we cannot assert that the refs array is empty here as not all 3457 // of the processing tasks (specifically phase2 - pp2_work) execute 3458 // the complete_gc closure (which ordinarily would drain the queue) so 3459 // the queue may not be empty. 3460 } 3461 }; 3462 3463 // Driver routine for parallel reference processing. 3464 // Creates an instance of the ref processing gang 3465 // task and has the worker threads execute it. 3466 void G1STWRefProcTaskExecutor::execute(ProcessTask& proc_task, uint ergo_workers) { 3467 assert(_workers != NULL, "Need parallel worker threads."); 3468 3469 assert(_workers->active_workers() >= ergo_workers, 3470 "Ergonomically chosen workers (%u) should be less than or equal to active workers (%u)", 3471 ergo_workers, _workers->active_workers()); 3472 TaskTerminator terminator(ergo_workers, _queues); 3473 G1STWRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _pss, _queues, &terminator); 3474 3475 _workers->run_task(&proc_task_proxy, ergo_workers); 3476 } 3477 3478 // End of weak reference support closures 3479 3480 void G1CollectedHeap::process_discovered_references(G1ParScanThreadStateSet* per_thread_states) { 3481 double ref_proc_start = os::elapsedTime(); 3482 3483 ReferenceProcessor* rp = _ref_processor_stw; 3484 assert(rp->discovery_enabled(), "should have been enabled"); 3485 3486 // Closure to test whether a referent is alive. 3487 G1STWIsAliveClosure is_alive(this); 3488 3489 // Even when parallel reference processing is enabled, the processing 3490 // of JNI refs is serial and performed serially by the current thread 3491 // rather than by a worker. The following PSS will be used for processing 3492 // JNI refs. 3493 3494 // Use only a single queue for this PSS. 3495 G1ParScanThreadState* pss = per_thread_states->state_for_worker(0); 3496 pss->set_ref_discoverer(NULL); 3497 assert(pss->queue_is_empty(), "pre-condition"); 3498 3499 // Keep alive closure. 3500 G1CopyingKeepAliveClosure keep_alive(this, pss); 3501 3502 // Serial Complete GC closure 3503 G1STWDrainQueueClosure drain_queue(this, pss); 3504 3505 // Setup the soft refs policy... 3506 rp->setup_policy(false); 3507 3508 ReferenceProcessorPhaseTimes* pt = phase_times()->ref_phase_times(); 3509 3510 ReferenceProcessorStats stats; 3511 if (!rp->processing_is_mt()) { 3512 // Serial reference processing... 3513 stats = rp->process_discovered_references(&is_alive, 3514 &keep_alive, 3515 &drain_queue, 3516 NULL, 3517 pt); 3518 } else { 3519 uint no_of_gc_workers = workers()->active_workers(); 3520 3521 // Parallel reference processing 3522 assert(no_of_gc_workers <= rp->max_num_queues(), 3523 "Mismatch between the number of GC workers %u and the maximum number of Reference process queues %u", 3524 no_of_gc_workers, rp->max_num_queues()); 3525 3526 G1STWRefProcTaskExecutor par_task_executor(this, per_thread_states, workers(), _task_queues); 3527 stats = rp->process_discovered_references(&is_alive, 3528 &keep_alive, 3529 &drain_queue, 3530 &par_task_executor, 3531 pt); 3532 } 3533 3534 _gc_tracer_stw->report_gc_reference_stats(stats); 3535 3536 // We have completed copying any necessary live referent objects. 3537 assert(pss->queue_is_empty(), "both queue and overflow should be empty"); 3538 3539 make_pending_list_reachable(); 3540 3541 assert(!rp->discovery_enabled(), "Postcondition"); 3542 rp->verify_no_references_recorded(); 3543 3544 double ref_proc_time = os::elapsedTime() - ref_proc_start; 3545 phase_times()->record_ref_proc_time(ref_proc_time * 1000.0); 3546 } 3547 3548 void G1CollectedHeap::make_pending_list_reachable() { 3549 if (collector_state()->in_concurrent_start_gc()) { 3550 oop pll_head = Universe::reference_pending_list(); 3551 if (pll_head != NULL) { 3552 // Any valid worker id is fine here as we are in the VM thread and single-threaded. 3553 _cm->mark_in_next_bitmap(0 /* worker_id */, pll_head); 3554 } 3555 } 3556 } 3557 3558 void G1CollectedHeap::merge_per_thread_state_info(G1ParScanThreadStateSet* per_thread_states) { 3559 Ticks start = Ticks::now(); 3560 per_thread_states->flush(); 3561 phase_times()->record_or_add_time_secs(G1GCPhaseTimes::MergePSS, 0 /* worker_id */, (Ticks::now() - start).seconds()); 3562 } 3563 3564 class G1PrepareEvacuationTask : public AbstractGangTask { 3565 class G1PrepareRegionsClosure : public HeapRegionClosure { 3566 G1CollectedHeap* _g1h; 3567 G1PrepareEvacuationTask* _parent_task; 3568 size_t _worker_humongous_total; 3569 size_t _worker_humongous_candidates; 3570 3571 bool humongous_region_is_candidate(HeapRegion* region) const { 3572 assert(region->is_starts_humongous(), "Must start a humongous object"); 3573 3574 oop obj = oop(region->bottom()); 3575 3576 // Dead objects cannot be eager reclaim candidates. Due to class 3577 // unloading it is unsafe to query their classes so we return early. 3578 if (_g1h->is_obj_dead(obj, region)) { 3579 return false; 3580 } 3581 3582 // If we do not have a complete remembered set for the region, then we can 3583 // not be sure that we have all references to it. 3584 if (!region->rem_set()->is_complete()) { 3585 return false; 3586 } 3587 // Candidate selection must satisfy the following constraints 3588 // while concurrent marking is in progress: 3589 // 3590 // * In order to maintain SATB invariants, an object must not be 3591 // reclaimed if it was allocated before the start of marking and 3592 // has not had its references scanned. Such an object must have 3593 // its references (including type metadata) scanned to ensure no 3594 // live objects are missed by the marking process. Objects 3595 // allocated after the start of concurrent marking don't need to 3596 // be scanned. 3597 // 3598 // * An object must not be reclaimed if it is on the concurrent 3599 // mark stack. Objects allocated after the start of concurrent 3600 // marking are never pushed on the mark stack. 3601 // 3602 // Nominating only objects allocated after the start of concurrent 3603 // marking is sufficient to meet both constraints. This may miss 3604 // some objects that satisfy the constraints, but the marking data 3605 // structures don't support efficiently performing the needed 3606 // additional tests or scrubbing of the mark stack. 3607 // 3608 // However, we presently only nominate is_typeArray() objects. 3609 // A humongous object containing references induces remembered 3610 // set entries on other regions. In order to reclaim such an 3611 // object, those remembered sets would need to be cleaned up. 3612 // 3613 // We also treat is_typeArray() objects specially, allowing them 3614 // to be reclaimed even if allocated before the start of 3615 // concurrent mark. For this we rely on mark stack insertion to 3616 // exclude is_typeArray() objects, preventing reclaiming an object 3617 // that is in the mark stack. We also rely on the metadata for 3618 // such objects to be built-in and so ensured to be kept live. 3619 // Frequent allocation and drop of large binary blobs is an 3620 // important use case for eager reclaim, and this special handling 3621 // may reduce needed headroom. 3622 3623 return obj->is_typeArray() && 3624 _g1h->is_potential_eager_reclaim_candidate(region); 3625 } 3626 3627 public: 3628 G1PrepareRegionsClosure(G1CollectedHeap* g1h, G1PrepareEvacuationTask* parent_task) : 3629 _g1h(g1h), 3630 _parent_task(parent_task), 3631 _worker_humongous_total(0), 3632 _worker_humongous_candidates(0) { } 3633 3634 ~G1PrepareRegionsClosure() { 3635 _parent_task->add_humongous_candidates(_worker_humongous_candidates); 3636 _parent_task->add_humongous_total(_worker_humongous_total); 3637 } 3638 3639 virtual bool do_heap_region(HeapRegion* hr) { 3640 // First prepare the region for scanning 3641 _g1h->rem_set()->prepare_region_for_scan(hr); 3642 3643 // Now check if region is a humongous candidate 3644 if (!hr->is_starts_humongous()) { 3645 _g1h->register_region_with_region_attr(hr); 3646 return false; 3647 } 3648 3649 uint index = hr->hrm_index(); 3650 if (humongous_region_is_candidate(hr)) { 3651 _g1h->set_humongous_reclaim_candidate(index, true); 3652 _g1h->register_humongous_region_with_region_attr(index); 3653 _worker_humongous_candidates++; 3654 // We will later handle the remembered sets of these regions. 3655 } else { 3656 _g1h->set_humongous_reclaim_candidate(index, false); 3657 _g1h->register_region_with_region_attr(hr); 3658 } 3659 _worker_humongous_total++; 3660 3661 return false; 3662 } 3663 }; 3664 3665 G1CollectedHeap* _g1h; 3666 HeapRegionClaimer _claimer; 3667 volatile size_t _humongous_total; 3668 volatile size_t _humongous_candidates; 3669 public: 3670 G1PrepareEvacuationTask(G1CollectedHeap* g1h) : 3671 AbstractGangTask("Prepare Evacuation"), 3672 _g1h(g1h), 3673 _claimer(_g1h->workers()->active_workers()), 3674 _humongous_total(0), 3675 _humongous_candidates(0) { } 3676 3677 ~G1PrepareEvacuationTask() { 3678 _g1h->set_has_humongous_reclaim_candidate(_humongous_candidates > 0); 3679 } 3680 3681 void work(uint worker_id) { 3682 G1PrepareRegionsClosure cl(_g1h, this); 3683 _g1h->heap_region_par_iterate_from_worker_offset(&cl, &_claimer, worker_id); 3684 } 3685 3686 void add_humongous_candidates(size_t candidates) { 3687 Atomic::add(&_humongous_candidates, candidates); 3688 } 3689 3690 void add_humongous_total(size_t total) { 3691 Atomic::add(&_humongous_total, total); 3692 } 3693 3694 size_t humongous_candidates() { 3695 return _humongous_candidates; 3696 } 3697 3698 size_t humongous_total() { 3699 return _humongous_total; 3700 } 3701 }; 3702 3703 void G1CollectedHeap::pre_evacuate_collection_set(G1EvacuationInfo& evacuation_info, G1ParScanThreadStateSet* per_thread_states) { 3704 _bytes_used_during_gc = 0; 3705 3706 _expand_heap_after_alloc_failure = true; 3707 _evacuation_failed = false; 3708 3709 // Disable the hot card cache. 3710 _hot_card_cache->reset_hot_cache_claimed_index(); 3711 _hot_card_cache->set_use_cache(false); 3712 3713 // Initialize the GC alloc regions. 3714 _allocator->init_gc_alloc_regions(evacuation_info); 3715 3716 { 3717 Ticks start = Ticks::now(); 3718 rem_set()->prepare_for_scan_heap_roots(); 3719 phase_times()->record_prepare_heap_roots_time_ms((Ticks::now() - start).seconds() * 1000.0); 3720 } 3721 3722 { 3723 G1PrepareEvacuationTask g1_prep_task(this); 3724 Tickspan task_time = run_task_timed(&g1_prep_task); 3725 3726 phase_times()->record_register_regions(task_time.seconds() * 1000.0, 3727 g1_prep_task.humongous_total(), 3728 g1_prep_task.humongous_candidates()); 3729 } 3730 3731 assert(_verifier->check_region_attr_table(), "Inconsistency in the region attributes table."); 3732 _preserved_marks_set.assert_empty(); 3733 3734 #if COMPILER2_OR_JVMCI 3735 DerivedPointerTable::clear(); 3736 #endif 3737 3738 // Concurrent start needs claim bits to keep track of the marked-through CLDs. 3739 if (collector_state()->in_concurrent_start_gc()) { 3740 concurrent_mark()->pre_concurrent_start(); 3741 3742 double start_clear_claimed_marks = os::elapsedTime(); 3743 3744 ClassLoaderDataGraph::clear_claimed_marks(); 3745 3746 double recorded_clear_claimed_marks_time_ms = (os::elapsedTime() - start_clear_claimed_marks) * 1000.0; 3747 phase_times()->record_clear_claimed_marks_time_ms(recorded_clear_claimed_marks_time_ms); 3748 } 3749 3750 // Should G1EvacuationFailureALot be in effect for this GC? 3751 NOT_PRODUCT(set_evacuation_failure_alot_for_current_gc();) 3752 } 3753 3754 class G1EvacuateRegionsBaseTask : public AbstractGangTask { 3755 protected: 3756 G1CollectedHeap* _g1h; 3757 G1ParScanThreadStateSet* _per_thread_states; 3758 G1ScannerTasksQueueSet* _task_queues; 3759 TaskTerminator _terminator; 3760 uint _num_workers; 3761 3762 void evacuate_live_objects(G1ParScanThreadState* pss, 3763 uint worker_id, 3764 G1GCPhaseTimes::GCParPhases objcopy_phase, 3765 G1GCPhaseTimes::GCParPhases termination_phase) { 3766 G1GCPhaseTimes* p = _g1h->phase_times(); 3767 3768 Ticks start = Ticks::now(); 3769 G1ParEvacuateFollowersClosure cl(_g1h, pss, _task_queues, &_terminator, objcopy_phase); 3770 cl.do_void(); 3771 3772 assert(pss->queue_is_empty(), "should be empty"); 3773 3774 Tickspan evac_time = (Ticks::now() - start); 3775 p->record_or_add_time_secs(objcopy_phase, worker_id, evac_time.seconds() - cl.term_time()); 3776 3777 if (termination_phase == G1GCPhaseTimes::Termination) { 3778 p->record_time_secs(termination_phase, worker_id, cl.term_time()); 3779 p->record_thread_work_item(termination_phase, worker_id, cl.term_attempts()); 3780 } else { 3781 p->record_or_add_time_secs(termination_phase, worker_id, cl.term_time()); 3782 p->record_or_add_thread_work_item(termination_phase, worker_id, cl.term_attempts()); 3783 } 3784 assert(pss->trim_ticks().seconds() == 0.0, "Unexpected partial trimming during evacuation"); 3785 } 3786 3787 virtual void start_work(uint worker_id) { } 3788 3789 virtual void end_work(uint worker_id) { } 3790 3791 virtual void scan_roots(G1ParScanThreadState* pss, uint worker_id) = 0; 3792 3793 virtual void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) = 0; 3794 3795 public: 3796 G1EvacuateRegionsBaseTask(const char* name, 3797 G1ParScanThreadStateSet* per_thread_states, 3798 G1ScannerTasksQueueSet* task_queues, 3799 uint num_workers) : 3800 AbstractGangTask(name), 3801 _g1h(G1CollectedHeap::heap()), 3802 _per_thread_states(per_thread_states), 3803 _task_queues(task_queues), 3804 _terminator(num_workers, _task_queues), 3805 _num_workers(num_workers) 3806 { } 3807 3808 void work(uint worker_id) { 3809 start_work(worker_id); 3810 3811 { 3812 ResourceMark rm; 3813 3814 G1ParScanThreadState* pss = _per_thread_states->state_for_worker(worker_id); 3815 pss->set_ref_discoverer(_g1h->ref_processor_stw()); 3816 3817 scan_roots(pss, worker_id); 3818 evacuate_live_objects(pss, worker_id); 3819 } 3820 3821 end_work(worker_id); 3822 } 3823 }; 3824 3825 class G1EvacuateRegionsTask : public G1EvacuateRegionsBaseTask { 3826 G1RootProcessor* _root_processor; 3827 3828 void scan_roots(G1ParScanThreadState* pss, uint worker_id) { 3829 _root_processor->evacuate_roots(pss, worker_id); 3830 _g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::ScanHR, G1GCPhaseTimes::ObjCopy); 3831 _g1h->rem_set()->scan_collection_set_regions(pss, worker_id, G1GCPhaseTimes::ScanHR, G1GCPhaseTimes::CodeRoots, G1GCPhaseTimes::ObjCopy); 3832 } 3833 3834 void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) { 3835 G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::ObjCopy, G1GCPhaseTimes::Termination); 3836 } 3837 3838 void start_work(uint worker_id) { 3839 _g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerStart, worker_id, Ticks::now().seconds()); 3840 } 3841 3842 void end_work(uint worker_id) { 3843 _g1h->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerEnd, worker_id, Ticks::now().seconds()); 3844 } 3845 3846 public: 3847 G1EvacuateRegionsTask(G1CollectedHeap* g1h, 3848 G1ParScanThreadStateSet* per_thread_states, 3849 G1ScannerTasksQueueSet* task_queues, 3850 G1RootProcessor* root_processor, 3851 uint num_workers) : 3852 G1EvacuateRegionsBaseTask("G1 Evacuate Regions", per_thread_states, task_queues, num_workers), 3853 _root_processor(root_processor) 3854 { } 3855 }; 3856 3857 void G1CollectedHeap::evacuate_initial_collection_set(G1ParScanThreadStateSet* per_thread_states) { 3858 G1GCPhaseTimes* p = phase_times(); 3859 3860 { 3861 Ticks start = Ticks::now(); 3862 rem_set()->merge_heap_roots(true /* initial_evacuation */); 3863 p->record_merge_heap_roots_time((Ticks::now() - start).seconds() * 1000.0); 3864 } 3865 3866 Tickspan task_time; 3867 const uint num_workers = workers()->active_workers(); 3868 3869 Ticks start_processing = Ticks::now(); 3870 { 3871 G1RootProcessor root_processor(this, num_workers); 3872 G1EvacuateRegionsTask g1_par_task(this, per_thread_states, _task_queues, &root_processor, num_workers); 3873 task_time = run_task_timed(&g1_par_task); 3874 // Closing the inner scope will execute the destructor for the G1RootProcessor object. 3875 // To extract its code root fixup time we measure total time of this scope and 3876 // subtract from the time the WorkGang task took. 3877 } 3878 Tickspan total_processing = Ticks::now() - start_processing; 3879 3880 p->record_initial_evac_time(task_time.seconds() * 1000.0); 3881 p->record_or_add_code_root_fixup_time((total_processing - task_time).seconds() * 1000.0); 3882 } 3883 3884 class G1EvacuateOptionalRegionsTask : public G1EvacuateRegionsBaseTask { 3885 3886 void scan_roots(G1ParScanThreadState* pss, uint worker_id) { 3887 _g1h->rem_set()->scan_heap_roots(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::OptObjCopy); 3888 _g1h->rem_set()->scan_collection_set_regions(pss, worker_id, G1GCPhaseTimes::OptScanHR, G1GCPhaseTimes::OptCodeRoots, G1GCPhaseTimes::OptObjCopy); 3889 } 3890 3891 void evacuate_live_objects(G1ParScanThreadState* pss, uint worker_id) { 3892 G1EvacuateRegionsBaseTask::evacuate_live_objects(pss, worker_id, G1GCPhaseTimes::OptObjCopy, G1GCPhaseTimes::OptTermination); 3893 } 3894 3895 public: 3896 G1EvacuateOptionalRegionsTask(G1ParScanThreadStateSet* per_thread_states, 3897 G1ScannerTasksQueueSet* queues, 3898 uint num_workers) : 3899 G1EvacuateRegionsBaseTask("G1 Evacuate Optional Regions", per_thread_states, queues, num_workers) { 3900 } 3901 }; 3902 3903 void G1CollectedHeap::evacuate_next_optional_regions(G1ParScanThreadStateSet* per_thread_states) { 3904 class G1MarkScope : public MarkScope { }; 3905 3906 Tickspan task_time; 3907 3908 Ticks start_processing = Ticks::now(); 3909 { 3910 G1MarkScope code_mark_scope; 3911 G1EvacuateOptionalRegionsTask task(per_thread_states, _task_queues, workers()->active_workers()); 3912 task_time = run_task_timed(&task); 3913 // See comment in evacuate_collection_set() for the reason of the scope. 3914 } 3915 Tickspan total_processing = Ticks::now() - start_processing; 3916 3917 G1GCPhaseTimes* p = phase_times(); 3918 p->record_or_add_code_root_fixup_time((total_processing - task_time).seconds() * 1000.0); 3919 } 3920 3921 void G1CollectedHeap::evacuate_optional_collection_set(G1ParScanThreadStateSet* per_thread_states) { 3922 const double gc_start_time_ms = phase_times()->cur_collection_start_sec() * 1000.0; 3923 3924 while (!evacuation_failed() && _collection_set.optional_region_length() > 0) { 3925 3926 double time_used_ms = os::elapsedTime() * 1000.0 - gc_start_time_ms; 3927 double time_left_ms = MaxGCPauseMillis - time_used_ms; 3928 3929 if (time_left_ms < 0 || 3930 !_collection_set.finalize_optional_for_evacuation(time_left_ms * policy()->optional_evacuation_fraction())) { 3931 log_trace(gc, ergo, cset)("Skipping evacuation of %u optional regions, no more regions can be evacuated in %.3fms", 3932 _collection_set.optional_region_length(), time_left_ms); 3933 break; 3934 } 3935 3936 { 3937 Ticks start = Ticks::now(); 3938 rem_set()->merge_heap_roots(false /* initial_evacuation */); 3939 phase_times()->record_or_add_optional_merge_heap_roots_time((Ticks::now() - start).seconds() * 1000.0); 3940 } 3941 3942 { 3943 Ticks start = Ticks::now(); 3944 evacuate_next_optional_regions(per_thread_states); 3945 phase_times()->record_or_add_optional_evac_time((Ticks::now() - start).seconds() * 1000.0); 3946 } 3947 } 3948 3949 _collection_set.abandon_optional_collection_set(per_thread_states); 3950 } 3951 3952 void G1CollectedHeap::post_evacuate_collection_set(G1EvacuationInfo& evacuation_info, 3953 G1RedirtyCardsQueueSet* rdcqs, 3954 G1ParScanThreadStateSet* per_thread_states) { 3955 G1GCPhaseTimes* p = phase_times(); 3956 3957 rem_set()->cleanup_after_scan_heap_roots(); 3958 3959 // Process any discovered reference objects - we have 3960 // to do this _before_ we retire the GC alloc regions 3961 // as we may have to copy some 'reachable' referent 3962 // objects (and their reachable sub-graphs) that were 3963 // not copied during the pause. 3964 process_discovered_references(per_thread_states); 3965 3966 G1STWIsAliveClosure is_alive(this); 3967 G1KeepAliveClosure keep_alive(this); 3968 3969 WeakProcessor::weak_oops_do(workers(), &is_alive, &keep_alive, p->weak_phase_times()); 3970 3971 if (G1StringDedup::is_enabled()) { 3972 double string_dedup_time_ms = os::elapsedTime(); 3973 3974 string_dedup_cleaning(&is_alive, &keep_alive, p); 3975 3976 double string_cleanup_time_ms = (os::elapsedTime() - string_dedup_time_ms) * 1000.0; 3977 p->record_string_deduplication_time(string_cleanup_time_ms); 3978 } 3979 3980 _allocator->release_gc_alloc_regions(evacuation_info); 3981 3982 if (evacuation_failed()) { 3983 restore_after_evac_failure(rdcqs); 3984 3985 // Reset the G1EvacuationFailureALot counters and flags 3986 NOT_PRODUCT(reset_evacuation_should_fail();) 3987 3988 double recalculate_used_start = os::elapsedTime(); 3989 set_used(recalculate_used()); 3990 p->record_evac_fail_recalc_used_time((os::elapsedTime() - recalculate_used_start) * 1000.0); 3991 3992 if (_archive_allocator != NULL) { 3993 _archive_allocator->clear_used(); 3994 } 3995 for (uint i = 0; i < ParallelGCThreads; i++) { 3996 if (_evacuation_failed_info_array[i].has_failed()) { 3997 _gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]); 3998 } 3999 } 4000 } else { 4001 // The "used" of the the collection set have already been subtracted 4002 // when they were freed. Add in the bytes used. 4003 increase_used(_bytes_used_during_gc); 4004 } 4005 4006 _preserved_marks_set.assert_empty(); 4007 4008 merge_per_thread_state_info(per_thread_states); 4009 4010 // Reset and re-enable the hot card cache. 4011 // Note the counts for the cards in the regions in the 4012 // collection set are reset when the collection set is freed. 4013 _hot_card_cache->reset_hot_cache(); 4014 _hot_card_cache->set_use_cache(true); 4015 4016 purge_code_root_memory(); 4017 4018 redirty_logged_cards(rdcqs); 4019 4020 free_collection_set(&_collection_set, evacuation_info, per_thread_states->surviving_young_words()); 4021 4022 eagerly_reclaim_humongous_regions(); 4023 4024 record_obj_copy_mem_stats(); 4025 4026 evacuation_info.set_collectionset_used_before(collection_set()->bytes_used_before()); 4027 evacuation_info.set_bytes_used(_bytes_used_during_gc); 4028 4029 #if COMPILER2_OR_JVMCI 4030 double start = os::elapsedTime(); 4031 DerivedPointerTable::update_pointers(); 4032 phase_times()->record_derived_pointer_table_update_time((os::elapsedTime() - start) * 1000.0); 4033 #endif 4034 policy()->print_age_table(); 4035 } 4036 4037 void G1CollectedHeap::record_obj_copy_mem_stats() { 4038 policy()->old_gen_alloc_tracker()-> 4039 add_allocated_bytes_since_last_gc(_old_evac_stats.allocated() * HeapWordSize); 4040 4041 _gc_tracer_stw->report_evacuation_statistics(create_g1_evac_summary(&_survivor_evac_stats), 4042 create_g1_evac_summary(&_old_evac_stats)); 4043 } 4044 4045 void G1CollectedHeap::free_region(HeapRegion* hr, FreeRegionList* free_list) { 4046 assert(!hr->is_free(), "the region should not be free"); 4047 assert(!hr->is_empty(), "the region should not be empty"); 4048 assert(_hrm->is_available(hr->hrm_index()), "region should be committed"); 4049 4050 if (G1VerifyBitmaps) { 4051 MemRegion mr(hr->bottom(), hr->end()); 4052 concurrent_mark()->clear_range_in_prev_bitmap(mr); 4053 } 4054 4055 // Clear the card counts for this region. 4056 // Note: we only need to do this if the region is not young 4057 // (since we don't refine cards in young regions). 4058 if (!hr->is_young()) { 4059 _hot_card_cache->reset_card_counts(hr); 4060 } 4061 4062 // Reset region metadata to allow reuse. 4063 hr->hr_clear(true /* clear_space */); 4064 _policy->remset_tracker()->update_at_free(hr); 4065 4066 if (free_list != NULL) { 4067 free_list->add_ordered(hr); 4068 } 4069 } 4070 4071 void G1CollectedHeap::free_humongous_region(HeapRegion* hr, 4072 FreeRegionList* free_list) { 4073 assert(hr->is_humongous(), "this is only for humongous regions"); 4074 assert(free_list != NULL, "pre-condition"); 4075 hr->clear_humongous(); 4076 free_region(hr, free_list); 4077 } 4078 4079 void G1CollectedHeap::remove_from_old_sets(const uint old_regions_removed, 4080 const uint humongous_regions_removed) { 4081 if (old_regions_removed > 0 || humongous_regions_removed > 0) { 4082 MutexLocker x(OldSets_lock, Mutex::_no_safepoint_check_flag); 4083 _old_set.bulk_remove(old_regions_removed); 4084 _humongous_set.bulk_remove(humongous_regions_removed); 4085 } 4086 4087 } 4088 4089 void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) { 4090 assert(list != NULL, "list can't be null"); 4091 if (!list->is_empty()) { 4092 MutexLocker x(FreeList_lock, Mutex::_no_safepoint_check_flag); 4093 _hrm->insert_list_into_free_list(list); 4094 } 4095 } 4096 4097 void G1CollectedHeap::decrement_summary_bytes(size_t bytes) { 4098 decrease_used(bytes); 4099 } 4100 4101 class G1FreeCollectionSetTask : public AbstractGangTask { 4102 // Helper class to keep statistics for the collection set freeing 4103 class FreeCSetStats { 4104 size_t _before_used_bytes; // Usage in regions successfully evacutate 4105 size_t _after_used_bytes; // Usage in regions failing evacuation 4106 size_t _bytes_allocated_in_old_since_last_gc; // Size of young regions turned into old 4107 size_t _failure_used_words; // Live size in failed regions 4108 size_t _failure_waste_words; // Wasted size in failed regions 4109 size_t _rs_length; // Remembered set size 4110 uint _regions_freed; // Number of regions freed 4111 public: 4112 FreeCSetStats() : 4113 _before_used_bytes(0), 4114 _after_used_bytes(0), 4115 _bytes_allocated_in_old_since_last_gc(0), 4116 _failure_used_words(0), 4117 _failure_waste_words(0), 4118 _rs_length(0), 4119 _regions_freed(0) { } 4120 4121 void merge_stats(FreeCSetStats* other) { 4122 assert(other != NULL, "invariant"); 4123 _before_used_bytes += other->_before_used_bytes; 4124 _after_used_bytes += other->_after_used_bytes; 4125 _bytes_allocated_in_old_since_last_gc += other->_bytes_allocated_in_old_since_last_gc; 4126 _failure_used_words += other->_failure_used_words; 4127 _failure_waste_words += other->_failure_waste_words; 4128 _rs_length += other->_rs_length; 4129 _regions_freed += other->_regions_freed; 4130 } 4131 4132 void report(G1CollectedHeap* g1h, G1EvacuationInfo* evacuation_info) { 4133 evacuation_info->set_regions_freed(_regions_freed); 4134 evacuation_info->increment_collectionset_used_after(_after_used_bytes); 4135 4136 g1h->decrement_summary_bytes(_before_used_bytes); 4137 g1h->alloc_buffer_stats(G1HeapRegionAttr::Old)->add_failure_used_and_waste(_failure_used_words, _failure_waste_words); 4138 4139 G1Policy *policy = g1h->policy(); 4140 policy->old_gen_alloc_tracker()->add_allocated_bytes_since_last_gc(_bytes_allocated_in_old_since_last_gc); 4141 policy->record_rs_length(_rs_length); 4142 policy->cset_regions_freed(); 4143 } 4144 4145 void account_failed_region(HeapRegion* r) { 4146 size_t used_words = r->marked_bytes() / HeapWordSize; 4147 _failure_used_words += used_words; 4148 _failure_waste_words += HeapRegion::GrainWords - used_words; 4149 _after_used_bytes += r->used(); 4150 4151 // When moving a young gen region to old gen, we "allocate" that whole 4152 // region there. This is in addition to any already evacuated objects. 4153 // Notify the policy about that. Old gen regions do not cause an 4154 // additional allocation: both the objects still in the region and the 4155 // ones already moved are accounted for elsewhere. 4156 if (r->is_young()) { 4157 _bytes_allocated_in_old_since_last_gc += HeapRegion::GrainBytes; 4158 } 4159 } 4160 4161 void account_evacuated_region(HeapRegion* r) { 4162 _before_used_bytes += r->used(); 4163 _regions_freed += 1; 4164 } 4165 4166 void account_rs_length(HeapRegion* r) { 4167 _rs_length += r->rem_set()->occupied(); 4168 } 4169 }; 4170 4171 // Closure applied to all regions in the collection set. 4172 class FreeCSetClosure : public HeapRegionClosure { 4173 // Helper to send JFR events for regions. 4174 class JFREventForRegion { 4175 EventGCPhaseParallel _event; 4176 public: 4177 JFREventForRegion(HeapRegion* region, uint worker_id) : _event() { 4178 _event.set_gcId(GCId::current()); 4179 _event.set_gcWorkerId(worker_id); 4180 if (region->is_young()) { 4181 _event.set_name(G1GCPhaseTimes::phase_name(G1GCPhaseTimes::YoungFreeCSet)); 4182 } else { 4183 _event.set_name(G1GCPhaseTimes::phase_name(G1GCPhaseTimes::NonYoungFreeCSet)); 4184 } 4185 } 4186 4187 ~JFREventForRegion() { 4188 _event.commit(); 4189 } 4190 }; 4191 4192 // Helper to do timing for region work. 4193 class TimerForRegion { 4194 Tickspan& _time; 4195 Ticks _start_time; 4196 public: 4197 TimerForRegion(Tickspan& time) : _time(time), _start_time(Ticks::now()) { } 4198 ~TimerForRegion() { 4199 _time += Ticks::now() - _start_time; 4200 } 4201 }; 4202 4203 // FreeCSetClosure members 4204 G1CollectedHeap* _g1h; 4205 const size_t* _surviving_young_words; 4206 uint _worker_id; 4207 Tickspan _young_time; 4208 Tickspan _non_young_time; 4209 FreeCSetStats* _stats; 4210 4211 void assert_in_cset(HeapRegion* r) { 4212 assert(r->young_index_in_cset() != 0 && 4213 (uint)r->young_index_in_cset() <= _g1h->collection_set()->young_region_length(), 4214 "Young index %u is wrong for region %u of type %s with %u young regions", 4215 r->young_index_in_cset(), r->hrm_index(), r->get_type_str(), _g1h->collection_set()->young_region_length()); 4216 } 4217 4218 void handle_evacuated_region(HeapRegion* r) { 4219 assert(!r->is_empty(), "Region %u is an empty region in the collection set.", r->hrm_index()); 4220 stats()->account_evacuated_region(r); 4221 4222 // Free the region and and its remembered set. 4223 _g1h->free_region(r, NULL); 4224 } 4225 4226 void handle_failed_region(HeapRegion* r) { 4227 // Do some allocation statistics accounting. Regions that failed evacuation 4228 // are always made old, so there is no need to update anything in the young 4229 // gen statistics, but we need to update old gen statistics. 4230 stats()->account_failed_region(r); 4231 4232 // Update the region state due to the failed evacuation. 4233 r->handle_evacuation_failure(); 4234 4235 // Add region to old set, need to hold lock. 4236 MutexLocker x(OldSets_lock, Mutex::_no_safepoint_check_flag); 4237 _g1h->old_set_add(r); 4238 } 4239 4240 Tickspan& timer_for_region(HeapRegion* r) { 4241 return r->is_young() ? _young_time : _non_young_time; 4242 } 4243 4244 FreeCSetStats* stats() { 4245 return _stats; 4246 } 4247 public: 4248 FreeCSetClosure(const size_t* surviving_young_words, 4249 uint worker_id, 4250 FreeCSetStats* stats) : 4251 HeapRegionClosure(), 4252 _g1h(G1CollectedHeap::heap()), 4253 _surviving_young_words(surviving_young_words), 4254 _worker_id(worker_id), 4255 _young_time(), 4256 _non_young_time(), 4257 _stats(stats) { } 4258 4259 virtual bool do_heap_region(HeapRegion* r) { 4260 assert(r->in_collection_set(), "Invariant: %u missing from CSet", r->hrm_index()); 4261 JFREventForRegion event(r, _worker_id); 4262 TimerForRegion timer(timer_for_region(r)); 4263 4264 _g1h->clear_region_attr(r); 4265 stats()->account_rs_length(r); 4266 4267 if (r->is_young()) { 4268 assert_in_cset(r); 4269 r->record_surv_words_in_group(_surviving_young_words[r->young_index_in_cset()]); 4270 } 4271 4272 if (r->evacuation_failed()) { 4273 handle_failed_region(r); 4274 } else { 4275 handle_evacuated_region(r); 4276 } 4277 assert(!_g1h->is_on_master_free_list(r), "sanity"); 4278 4279 return false; 4280 } 4281 4282 void report_timing(Tickspan parallel_time) { 4283 G1GCPhaseTimes* pt = _g1h->phase_times(); 4284 pt->record_time_secs(G1GCPhaseTimes::ParFreeCSet, _worker_id, parallel_time.seconds()); 4285 if (_young_time.value() > 0) { 4286 pt->record_time_secs(G1GCPhaseTimes::YoungFreeCSet, _worker_id, _young_time.seconds()); 4287 } 4288 if (_non_young_time.value() > 0) { 4289 pt->record_time_secs(G1GCPhaseTimes::NonYoungFreeCSet, _worker_id, _non_young_time.seconds()); 4290 } 4291 } 4292 }; 4293 4294 // G1FreeCollectionSetTask members 4295 G1CollectedHeap* _g1h; 4296 G1EvacuationInfo* _evacuation_info; 4297 FreeCSetStats* _worker_stats; 4298 HeapRegionClaimer _claimer; 4299 const size_t* _surviving_young_words; 4300 uint _active_workers; 4301 4302 FreeCSetStats* worker_stats(uint worker) { 4303 return &_worker_stats[worker]; 4304 } 4305 4306 void report_statistics() { 4307 // Merge the accounting 4308 FreeCSetStats total_stats; 4309 for (uint worker = 0; worker < _active_workers; worker++) { 4310 total_stats.merge_stats(worker_stats(worker)); 4311 } 4312 total_stats.report(_g1h, _evacuation_info); 4313 } 4314 4315 public: 4316 G1FreeCollectionSetTask(G1EvacuationInfo* evacuation_info, const size_t* surviving_young_words, uint active_workers) : 4317 AbstractGangTask("G1 Free Collection Set"), 4318 _g1h(G1CollectedHeap::heap()), 4319 _evacuation_info(evacuation_info), 4320 _worker_stats(NEW_C_HEAP_ARRAY(FreeCSetStats, active_workers, mtGC)), 4321 _claimer(active_workers), 4322 _surviving_young_words(surviving_young_words), 4323 _active_workers(active_workers) { 4324 for (uint worker = 0; worker < active_workers; worker++) { 4325 ::new (&_worker_stats[worker]) FreeCSetStats(); 4326 } 4327 } 4328 4329 ~G1FreeCollectionSetTask() { 4330 Ticks serial_time = Ticks::now(); 4331 report_statistics(); 4332 for (uint worker = 0; worker < _active_workers; worker++) { 4333 _worker_stats[worker].~FreeCSetStats(); 4334 } 4335 FREE_C_HEAP_ARRAY(FreeCSetStats, _worker_stats); 4336 _g1h->phase_times()->record_serial_free_cset_time_ms((Ticks::now() - serial_time).seconds() * 1000.0); 4337 } 4338 4339 virtual void work(uint worker_id) { 4340 EventGCPhaseParallel event; 4341 Ticks start = Ticks::now(); 4342 FreeCSetClosure cl(_surviving_young_words, worker_id, worker_stats(worker_id)); 4343 _g1h->collection_set_par_iterate_all(&cl, &_claimer, worker_id); 4344 4345 // Report the total parallel time along with some more detailed metrics. 4346 cl.report_timing(Ticks::now() - start); 4347 event.commit(GCId::current(), worker_id, G1GCPhaseTimes::phase_name(G1GCPhaseTimes::ParFreeCSet)); 4348 } 4349 }; 4350 4351 void G1CollectedHeap::free_collection_set(G1CollectionSet* collection_set, G1EvacuationInfo& evacuation_info, const size_t* surviving_young_words) { 4352 _eden.clear(); 4353 4354 // The free collections set is split up in two tasks, the first 4355 // frees the collection set and records what regions are free, 4356 // and the second one rebuilds the free list. This proved to be 4357 // more efficient than adding a sorted list to another. 4358 4359 Ticks free_cset_start_time = Ticks::now(); 4360 { 4361 uint const num_cs_regions = _collection_set.region_length(); 4362 uint const num_workers = clamp(num_cs_regions, 1u, workers()->active_workers()); 4363 G1FreeCollectionSetTask cl(&evacuation_info, surviving_young_words, num_workers); 4364 4365 log_debug(gc, ergo)("Running %s using %u workers for collection set length %u (%u)", 4366 cl.name(), num_workers, num_cs_regions, num_regions()); 4367 workers()->run_task(&cl, num_workers); 4368 } 4369 4370 Ticks free_cset_end_time = Ticks::now(); 4371 phase_times()->record_total_free_cset_time_ms((free_cset_end_time - free_cset_start_time).seconds() * 1000.0); 4372 4373 // Now rebuild the free region list. 4374 hrm()->rebuild_free_list(workers()); 4375 phase_times()->record_total_rebuild_freelist_time_ms((Ticks::now() - free_cset_end_time).seconds() * 1000.0); 4376 4377 collection_set->clear(); 4378 } 4379 4380 class G1FreeHumongousRegionClosure : public HeapRegionClosure { 4381 private: 4382 FreeRegionList* _free_region_list; 4383 HeapRegionSet* _proxy_set; 4384 uint _humongous_objects_reclaimed; 4385 uint _humongous_regions_reclaimed; 4386 size_t _freed_bytes; 4387 public: 4388 4389 G1FreeHumongousRegionClosure(FreeRegionList* free_region_list) : 4390 _free_region_list(free_region_list), _proxy_set(NULL), _humongous_objects_reclaimed(0), _humongous_regions_reclaimed(0), _freed_bytes(0) { 4391 } 4392 4393 virtual bool do_heap_region(HeapRegion* r) { 4394 if (!r->is_starts_humongous()) { 4395 return false; 4396 } 4397 4398 G1CollectedHeap* g1h = G1CollectedHeap::heap(); 4399 4400 oop obj = (oop)r->bottom(); 4401 G1CMBitMap* next_bitmap = g1h->concurrent_mark()->next_mark_bitmap(); 4402 4403 // The following checks whether the humongous object is live are sufficient. 4404 // The main additional check (in addition to having a reference from the roots 4405 // or the young gen) is whether the humongous object has a remembered set entry. 4406 // 4407 // A humongous object cannot be live if there is no remembered set for it 4408 // because: 4409 // - there can be no references from within humongous starts regions referencing 4410 // the object because we never allocate other objects into them. 4411 // (I.e. there are no intra-region references that may be missed by the 4412 // remembered set) 4413 // - as soon there is a remembered set entry to the humongous starts region 4414 // (i.e. it has "escaped" to an old object) this remembered set entry will stay 4415 // until the end of a concurrent mark. 4416 // 4417 // It is not required to check whether the object has been found dead by marking 4418 // or not, in fact it would prevent reclamation within a concurrent cycle, as 4419 // all objects allocated during that time are considered live. 4420 // SATB marking is even more conservative than the remembered set. 4421 // So if at this point in the collection there is no remembered set entry, 4422 // nobody has a reference to it. 4423 // At the start of collection we flush all refinement logs, and remembered sets 4424 // are completely up-to-date wrt to references to the humongous object. 4425 // 4426 // Other implementation considerations: 4427 // - never consider object arrays at this time because they would pose 4428 // considerable effort for cleaning up the the remembered sets. This is 4429 // required because stale remembered sets might reference locations that 4430 // are currently allocated into. 4431 uint region_idx = r->hrm_index(); 4432 if (!g1h->is_humongous_reclaim_candidate(region_idx) || 4433 !r->rem_set()->is_empty()) { 4434 log_debug(gc, humongous)("Live humongous region %u object size " SIZE_FORMAT " start " PTR_FORMAT " with remset " SIZE_FORMAT " code roots " SIZE_FORMAT " is marked %d reclaim candidate %d type array %d", 4435 region_idx, 4436 (size_t)obj->size() * HeapWordSize, 4437 p2i(r->bottom()), 4438 r->rem_set()->occupied(), 4439 r->rem_set()->strong_code_roots_list_length(), 4440 next_bitmap->is_marked(r->bottom()), 4441 g1h->is_humongous_reclaim_candidate(region_idx), 4442 obj->is_typeArray() 4443 ); 4444 return false; 4445 } 4446 4447 guarantee(obj->is_typeArray(), 4448 "Only eagerly reclaiming type arrays is supported, but the object " 4449 PTR_FORMAT " is not.", p2i(r->bottom())); 4450 4451 log_debug(gc, humongous)("Dead humongous region %u object size " SIZE_FORMAT " start " PTR_FORMAT " with remset " SIZE_FORMAT " code roots " SIZE_FORMAT " is marked %d reclaim candidate %d type array %d", 4452 region_idx, 4453 (size_t)obj->size() * HeapWordSize, 4454 p2i(r->bottom()), 4455 r->rem_set()->occupied(), 4456 r->rem_set()->strong_code_roots_list_length(), 4457 next_bitmap->is_marked(r->bottom()), 4458 g1h->is_humongous_reclaim_candidate(region_idx), 4459 obj->is_typeArray() 4460 ); 4461 4462 G1ConcurrentMark* const cm = g1h->concurrent_mark(); 4463 cm->humongous_object_eagerly_reclaimed(r); 4464 assert(!cm->is_marked_in_prev_bitmap(obj) && !cm->is_marked_in_next_bitmap(obj), 4465 "Eagerly reclaimed humongous region %u should not be marked at all but is in prev %s next %s", 4466 region_idx, 4467 BOOL_TO_STR(cm->is_marked_in_prev_bitmap(obj)), 4468 BOOL_TO_STR(cm->is_marked_in_next_bitmap(obj))); 4469 _humongous_objects_reclaimed++; 4470 do { 4471 HeapRegion* next = g1h->next_region_in_humongous(r); 4472 _freed_bytes += r->used(); 4473 r->set_containing_set(NULL); 4474 _humongous_regions_reclaimed++; 4475 g1h->free_humongous_region(r, _free_region_list); 4476 r = next; 4477 } while (r != NULL); 4478 4479 return false; 4480 } 4481 4482 uint humongous_objects_reclaimed() { 4483 return _humongous_objects_reclaimed; 4484 } 4485 4486 uint humongous_regions_reclaimed() { 4487 return _humongous_regions_reclaimed; 4488 } 4489 4490 size_t bytes_freed() const { 4491 return _freed_bytes; 4492 } 4493 }; 4494 4495 void G1CollectedHeap::eagerly_reclaim_humongous_regions() { 4496 assert_at_safepoint_on_vm_thread(); 4497 4498 if (!G1EagerReclaimHumongousObjects || 4499 (!_has_humongous_reclaim_candidates && !log_is_enabled(Debug, gc, humongous))) { 4500 phase_times()->record_fast_reclaim_humongous_time_ms(0.0, 0); 4501 return; 4502 } 4503 4504 double start_time = os::elapsedTime(); 4505 4506 FreeRegionList local_cleanup_list("Local Humongous Cleanup List"); 4507 4508 G1FreeHumongousRegionClosure cl(&local_cleanup_list); 4509 heap_region_iterate(&cl); 4510 4511 remove_from_old_sets(0, cl.humongous_regions_reclaimed()); 4512 4513 G1HRPrinter* hrp = hr_printer(); 4514 if (hrp->is_active()) { 4515 FreeRegionListIterator iter(&local_cleanup_list); 4516 while (iter.more_available()) { 4517 HeapRegion* hr = iter.get_next(); 4518 hrp->cleanup(hr); 4519 } 4520 } 4521 4522 prepend_to_freelist(&local_cleanup_list); 4523 decrement_summary_bytes(cl.bytes_freed()); 4524 4525 phase_times()->record_fast_reclaim_humongous_time_ms((os::elapsedTime() - start_time) * 1000.0, 4526 cl.humongous_objects_reclaimed()); 4527 } 4528 4529 class G1AbandonCollectionSetClosure : public HeapRegionClosure { 4530 public: 4531 virtual bool do_heap_region(HeapRegion* r) { 4532 assert(r->in_collection_set(), "Region %u must have been in collection set", r->hrm_index()); 4533 G1CollectedHeap::heap()->clear_region_attr(r); 4534 r->clear_young_index_in_cset(); 4535 return false; 4536 } 4537 }; 4538 4539 void G1CollectedHeap::abandon_collection_set(G1CollectionSet* collection_set) { 4540 G1AbandonCollectionSetClosure cl; 4541 collection_set_iterate_all(&cl); 4542 4543 collection_set->clear(); 4544 collection_set->stop_incremental_building(); 4545 } 4546 4547 bool G1CollectedHeap::is_old_gc_alloc_region(HeapRegion* hr) { 4548 return _allocator->is_retained_old_region(hr); 4549 } 4550 4551 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) { 4552 _eden.add(hr); 4553 _policy->set_region_eden(hr); 4554 } 4555 4556 #ifdef ASSERT 4557 4558 class NoYoungRegionsClosure: public HeapRegionClosure { 4559 private: 4560 bool _success; 4561 public: 4562 NoYoungRegionsClosure() : _success(true) { } 4563 bool do_heap_region(HeapRegion* r) { 4564 if (r->is_young()) { 4565 log_error(gc, verify)("Region [" PTR_FORMAT ", " PTR_FORMAT ") tagged as young", 4566 p2i(r->bottom()), p2i(r->end())); 4567 _success = false; 4568 } 4569 return false; 4570 } 4571 bool success() { return _success; } 4572 }; 4573 4574 bool G1CollectedHeap::check_young_list_empty() { 4575 bool ret = (young_regions_count() == 0); 4576 4577 NoYoungRegionsClosure closure; 4578 heap_region_iterate(&closure); 4579 ret = ret && closure.success(); 4580 4581 return ret; 4582 } 4583 4584 #endif // ASSERT 4585 4586 class TearDownRegionSetsClosure : public HeapRegionClosure { 4587 HeapRegionSet *_old_set; 4588 4589 public: 4590 TearDownRegionSetsClosure(HeapRegionSet* old_set) : _old_set(old_set) { } 4591 4592 bool do_heap_region(HeapRegion* r) { 4593 if (r->is_old()) { 4594 _old_set->remove(r); 4595 } else if(r->is_young()) { 4596 r->uninstall_surv_rate_group(); 4597 } else { 4598 // We ignore free regions, we'll empty the free list afterwards. 4599 // We ignore humongous and archive regions, we're not tearing down these 4600 // sets. 4601 assert(r->is_archive() || r->is_free() || r->is_humongous(), 4602 "it cannot be another type"); 4603 } 4604 return false; 4605 } 4606 4607 ~TearDownRegionSetsClosure() { 4608 assert(_old_set->is_empty(), "post-condition"); 4609 } 4610 }; 4611 4612 void G1CollectedHeap::tear_down_region_sets(bool free_list_only) { 4613 assert_at_safepoint_on_vm_thread(); 4614 4615 if (!free_list_only) { 4616 TearDownRegionSetsClosure cl(&_old_set); 4617 heap_region_iterate(&cl); 4618 4619 // Note that emptying the _young_list is postponed and instead done as 4620 // the first step when rebuilding the regions sets again. The reason for 4621 // this is that during a full GC string deduplication needs to know if 4622 // a collected region was young or old when the full GC was initiated. 4623 } 4624 _hrm->remove_all_free_regions(); 4625 } 4626 4627 void G1CollectedHeap::increase_used(size_t bytes) { 4628 _summary_bytes_used += bytes; 4629 } 4630 4631 void G1CollectedHeap::decrease_used(size_t bytes) { 4632 assert(_summary_bytes_used >= bytes, 4633 "invariant: _summary_bytes_used: " SIZE_FORMAT " should be >= bytes: " SIZE_FORMAT, 4634 _summary_bytes_used, bytes); 4635 _summary_bytes_used -= bytes; 4636 } 4637 4638 void G1CollectedHeap::set_used(size_t bytes) { 4639 _summary_bytes_used = bytes; 4640 } 4641 4642 class RebuildRegionSetsClosure : public HeapRegionClosure { 4643 private: 4644 bool _free_list_only; 4645 4646 HeapRegionSet* _old_set; 4647 HeapRegionManager* _hrm; 4648 4649 size_t _total_used; 4650 4651 public: 4652 RebuildRegionSetsClosure(bool free_list_only, 4653 HeapRegionSet* old_set, 4654 HeapRegionManager* hrm) : 4655 _free_list_only(free_list_only), 4656 _old_set(old_set), _hrm(hrm), _total_used(0) { 4657 assert(_hrm->num_free_regions() == 0, "pre-condition"); 4658 if (!free_list_only) { 4659 assert(_old_set->is_empty(), "pre-condition"); 4660 } 4661 } 4662 4663 bool do_heap_region(HeapRegion* r) { 4664 if (r->is_empty()) { 4665 assert(r->rem_set()->is_empty(), "Empty regions should have empty remembered sets."); 4666 // Add free regions to the free list 4667 r->set_free(); 4668 _hrm->insert_into_free_list(r); 4669 } else if (!_free_list_only) { 4670 assert(r->rem_set()->is_empty(), "At this point remembered sets must have been cleared."); 4671 4672 if (r->is_archive() || r->is_humongous()) { 4673 // We ignore archive and humongous regions. We left these sets unchanged. 4674 } else { 4675 assert(r->is_young() || r->is_free() || r->is_old(), "invariant"); 4676 // We now move all (non-humongous, non-old, non-archive) regions to old gen, and register them as such. 4677 r->move_to_old(); 4678 _old_set->add(r); 4679 } 4680 _total_used += r->used(); 4681 } 4682 4683 return false; 4684 } 4685 4686 size_t total_used() { 4687 return _total_used; 4688 } 4689 }; 4690 4691 void G1CollectedHeap::rebuild_region_sets(bool free_list_only) { 4692 assert_at_safepoint_on_vm_thread(); 4693 4694 if (!free_list_only) { 4695 _eden.clear(); 4696 _survivor.clear(); 4697 } 4698 4699 RebuildRegionSetsClosure cl(free_list_only, &_old_set, _hrm); 4700 heap_region_iterate(&cl); 4701 4702 if (!free_list_only) { 4703 set_used(cl.total_used()); 4704 if (_archive_allocator != NULL) { 4705 _archive_allocator->clear_used(); 4706 } 4707 } 4708 assert_used_and_recalculate_used_equal(this); 4709 } 4710 4711 // Methods for the mutator alloc region 4712 4713 HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size, 4714 bool force, 4715 uint node_index) { 4716 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */); 4717 bool should_allocate = policy()->should_allocate_mutator_region(); 4718 if (force || should_allocate) { 4719 HeapRegion* new_alloc_region = new_region(word_size, 4720 HeapRegionType::Eden, 4721 false /* do_expand */, 4722 node_index); 4723 if (new_alloc_region != NULL) { 4724 set_region_short_lived_locked(new_alloc_region); 4725 _hr_printer.alloc(new_alloc_region, !should_allocate); 4726 _verifier->check_bitmaps("Mutator Region Allocation", new_alloc_region); 4727 _policy->remset_tracker()->update_at_allocate(new_alloc_region); 4728 return new_alloc_region; 4729 } 4730 } 4731 return NULL; 4732 } 4733 4734 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region, 4735 size_t allocated_bytes) { 4736 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */); 4737 assert(alloc_region->is_eden(), "all mutator alloc regions should be eden"); 4738 4739 collection_set()->add_eden_region(alloc_region); 4740 increase_used(allocated_bytes); 4741 _eden.add_used_bytes(allocated_bytes); 4742 _hr_printer.retire(alloc_region); 4743 4744 // We update the eden sizes here, when the region is retired, 4745 // instead of when it's allocated, since this is the point that its 4746 // used space has been recorded in _summary_bytes_used. 4747 g1mm()->update_eden_size(); 4748 } 4749 4750 // Methods for the GC alloc regions 4751 4752 bool G1CollectedHeap::has_more_regions(G1HeapRegionAttr dest) { 4753 if (dest.is_old()) { 4754 return true; 4755 } else { 4756 return survivor_regions_count() < policy()->max_survivor_regions(); 4757 } 4758 } 4759 4760 HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size, G1HeapRegionAttr dest, uint node_index) { 4761 assert(FreeList_lock->owned_by_self(), "pre-condition"); 4762 4763 if (!has_more_regions(dest)) { 4764 return NULL; 4765 } 4766 4767 HeapRegionType type; 4768 if (dest.is_young()) { 4769 type = HeapRegionType::Survivor; 4770 } else { 4771 type = HeapRegionType::Old; 4772 } 4773 4774 HeapRegion* new_alloc_region = new_region(word_size, 4775 type, 4776 true /* do_expand */, 4777 node_index); 4778 4779 if (new_alloc_region != NULL) { 4780 if (type.is_survivor()) { 4781 new_alloc_region->set_survivor(); 4782 _survivor.add(new_alloc_region); 4783 _verifier->check_bitmaps("Survivor Region Allocation", new_alloc_region); 4784 } else { 4785 new_alloc_region->set_old(); 4786 _verifier->check_bitmaps("Old Region Allocation", new_alloc_region); 4787 } 4788 _policy->remset_tracker()->update_at_allocate(new_alloc_region); 4789 register_region_with_region_attr(new_alloc_region); 4790 _hr_printer.alloc(new_alloc_region); 4791 return new_alloc_region; 4792 } 4793 return NULL; 4794 } 4795 4796 void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region, 4797 size_t allocated_bytes, 4798 G1HeapRegionAttr dest) { 4799 _bytes_used_during_gc += allocated_bytes; 4800 if (dest.is_old()) { 4801 old_set_add(alloc_region); 4802 } else { 4803 assert(dest.is_young(), "Retiring alloc region should be young (%d)", dest.type()); 4804 _survivor.add_used_bytes(allocated_bytes); 4805 } 4806 4807 bool const during_im = collector_state()->in_concurrent_start_gc(); 4808 if (during_im && allocated_bytes > 0) { 4809 _cm->root_regions()->add(alloc_region->next_top_at_mark_start(), alloc_region->top()); 4810 } 4811 _hr_printer.retire(alloc_region); 4812 } 4813 4814 HeapRegion* G1CollectedHeap::alloc_highest_free_region() { 4815 bool expanded = false; 4816 uint index = _hrm->find_highest_free(&expanded); 4817 4818 if (index != G1_NO_HRM_INDEX) { 4819 if (expanded) { 4820 log_debug(gc, ergo, heap)("Attempt heap expansion (requested address range outside heap bounds). region size: " SIZE_FORMAT "B", 4821 HeapRegion::GrainWords * HeapWordSize); 4822 } 4823 return _hrm->allocate_free_regions_starting_at(index, 1); 4824 } 4825 return NULL; 4826 } 4827 4828 // Optimized nmethod scanning 4829 4830 class RegisterNMethodOopClosure: public OopClosure { 4831 G1CollectedHeap* _g1h; 4832 nmethod* _nm; 4833 4834 template <class T> void do_oop_work(T* p) { 4835 T heap_oop = RawAccess<>::oop_load(p); 4836 if (!CompressedOops::is_null(heap_oop)) { 4837 oop obj = CompressedOops::decode_not_null(heap_oop); 4838 HeapRegion* hr = _g1h->heap_region_containing(obj); 4839 assert(!hr->is_continues_humongous(), 4840 "trying to add code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT 4841 " starting at " HR_FORMAT, 4842 p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())); 4843 4844 // HeapRegion::add_strong_code_root_locked() avoids adding duplicate entries. 4845 hr->add_strong_code_root_locked(_nm); 4846 } 4847 } 4848 4849 public: 4850 RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) : 4851 _g1h(g1h), _nm(nm) {} 4852 4853 void do_oop(oop* p) { do_oop_work(p); } 4854 void do_oop(narrowOop* p) { do_oop_work(p); } 4855 }; 4856 4857 class UnregisterNMethodOopClosure: public OopClosure { 4858 G1CollectedHeap* _g1h; 4859 nmethod* _nm; 4860 4861 template <class T> void do_oop_work(T* p) { 4862 T heap_oop = RawAccess<>::oop_load(p); 4863 if (!CompressedOops::is_null(heap_oop)) { 4864 oop obj = CompressedOops::decode_not_null(heap_oop); 4865 HeapRegion* hr = _g1h->heap_region_containing(obj); 4866 assert(!hr->is_continues_humongous(), 4867 "trying to remove code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT 4868 " starting at " HR_FORMAT, 4869 p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())); 4870 4871 hr->remove_strong_code_root(_nm); 4872 } 4873 } 4874 4875 public: 4876 UnregisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) : 4877 _g1h(g1h), _nm(nm) {} 4878 4879 void do_oop(oop* p) { do_oop_work(p); } 4880 void do_oop(narrowOop* p) { do_oop_work(p); } 4881 }; 4882 4883 void G1CollectedHeap::register_nmethod(nmethod* nm) { 4884 guarantee(nm != NULL, "sanity"); 4885 RegisterNMethodOopClosure reg_cl(this, nm); 4886 nm->oops_do(®_cl); 4887 } 4888 4889 void G1CollectedHeap::unregister_nmethod(nmethod* nm) { 4890 guarantee(nm != NULL, "sanity"); 4891 UnregisterNMethodOopClosure reg_cl(this, nm); 4892 nm->oops_do(®_cl, true); 4893 } 4894 4895 void G1CollectedHeap::purge_code_root_memory() { 4896 double purge_start = os::elapsedTime(); 4897 G1CodeRootSet::purge(); 4898 double purge_time_ms = (os::elapsedTime() - purge_start) * 1000.0; 4899 phase_times()->record_strong_code_root_purge_time(purge_time_ms); 4900 } 4901 4902 class RebuildStrongCodeRootClosure: public CodeBlobClosure { 4903 G1CollectedHeap* _g1h; 4904 4905 public: 4906 RebuildStrongCodeRootClosure(G1CollectedHeap* g1h) : 4907 _g1h(g1h) {} 4908 4909 void do_code_blob(CodeBlob* cb) { 4910 nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL; 4911 if (nm == NULL) { 4912 return; 4913 } 4914 4915 _g1h->register_nmethod(nm); 4916 } 4917 }; 4918 4919 void G1CollectedHeap::rebuild_strong_code_roots() { 4920 RebuildStrongCodeRootClosure blob_cl(this); 4921 CodeCache::blobs_do(&blob_cl); 4922 } 4923 4924 void G1CollectedHeap::initialize_serviceability() { 4925 _g1mm->initialize_serviceability(); 4926 } 4927 4928 MemoryUsage G1CollectedHeap::memory_usage() { 4929 return _g1mm->memory_usage(); 4930 } 4931 4932 GrowableArray<GCMemoryManager*> G1CollectedHeap::memory_managers() { 4933 return _g1mm->memory_managers(); 4934 } 4935 4936 GrowableArray<MemoryPool*> G1CollectedHeap::memory_pools() { 4937 return _g1mm->memory_pools(); 4938 }