1 /* 2 * Copyright (c) 2001, 2016, 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/metadataOnStackMark.hpp" 27 #include "classfile/stringTable.hpp" 28 #include "classfile/symbolTable.hpp" 29 #include "code/codeCache.hpp" 30 #include "code/icBuffer.hpp" 31 #include "gc/g1/bufferingOopClosure.hpp" 32 #include "gc/g1/concurrentG1Refine.hpp" 33 #include "gc/g1/concurrentG1RefineThread.hpp" 34 #include "gc/g1/concurrentMarkThread.inline.hpp" 35 #include "gc/g1/g1Allocator.inline.hpp" 36 #include "gc/g1/g1CollectedHeap.inline.hpp" 37 #include "gc/g1/g1CollectionSet.hpp" 38 #include "gc/g1/g1CollectorPolicy.hpp" 39 #include "gc/g1/g1CollectorState.hpp" 40 #include "gc/g1/g1EvacStats.inline.hpp" 41 #include "gc/g1/g1GCPhaseTimes.hpp" 42 #include "gc/g1/g1HeapSizingPolicy.hpp" 43 #include "gc/g1/g1HeapTransition.hpp" 44 #include "gc/g1/g1HeapVerifier.hpp" 45 #include "gc/g1/g1MarkSweep.hpp" 46 #include "gc/g1/g1OopClosures.inline.hpp" 47 #include "gc/g1/g1ParScanThreadState.inline.hpp" 48 #include "gc/g1/g1Policy.hpp" 49 #include "gc/g1/g1RegionToSpaceMapper.hpp" 50 #include "gc/g1/g1RemSet.inline.hpp" 51 #include "gc/g1/g1RootClosures.hpp" 52 #include "gc/g1/g1RootProcessor.hpp" 53 #include "gc/g1/g1StringDedup.hpp" 54 #include "gc/g1/g1YCTypes.hpp" 55 #include "gc/g1/heapRegion.inline.hpp" 56 #include "gc/g1/heapRegionRemSet.hpp" 57 #include "gc/g1/heapRegionSet.inline.hpp" 58 #include "gc/g1/suspendibleThreadSet.hpp" 59 #include "gc/g1/vm_operations_g1.hpp" 60 #include "gc/shared/gcHeapSummary.hpp" 61 #include "gc/shared/gcId.hpp" 62 #include "gc/shared/gcLocker.inline.hpp" 63 #include "gc/shared/gcTimer.hpp" 64 #include "gc/shared/gcTrace.hpp" 65 #include "gc/shared/gcTraceTime.inline.hpp" 66 #include "gc/shared/generationSpec.hpp" 67 #include "gc/shared/isGCActiveMark.hpp" 68 #include "gc/shared/preservedMarks.inline.hpp" 69 #include "gc/shared/referenceProcessor.inline.hpp" 70 #include "gc/shared/taskqueue.inline.hpp" 71 #include "logging/log.hpp" 72 #include "memory/allocation.hpp" 73 #include "memory/iterator.hpp" 74 #include "memory/resourceArea.hpp" 75 #include "oops/oop.inline.hpp" 76 #include "runtime/atomic.inline.hpp" 77 #include "runtime/init.hpp" 78 #include "runtime/orderAccess.inline.hpp" 79 #include "runtime/vmThread.hpp" 80 #include "utilities/globalDefinitions.hpp" 81 #include "utilities/stack.inline.hpp" 82 83 size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0; 84 85 // INVARIANTS/NOTES 86 // 87 // All allocation activity covered by the G1CollectedHeap interface is 88 // serialized by acquiring the HeapLock. This happens in mem_allocate 89 // and allocate_new_tlab, which are the "entry" points to the 90 // allocation code from the rest of the JVM. (Note that this does not 91 // apply to TLAB allocation, which is not part of this interface: it 92 // is done by clients of this interface.) 93 94 // Local to this file. 95 96 class RefineCardTableEntryClosure: public CardTableEntryClosure { 97 bool _concurrent; 98 public: 99 RefineCardTableEntryClosure() : _concurrent(true) { } 100 101 bool do_card_ptr(jbyte* card_ptr, uint worker_i) { 102 bool oops_into_cset = G1CollectedHeap::heap()->g1_rem_set()->refine_card(card_ptr, worker_i, NULL); 103 // This path is executed by the concurrent refine or mutator threads, 104 // concurrently, and so we do not care if card_ptr contains references 105 // that point into the collection set. 106 assert(!oops_into_cset, "should be"); 107 108 if (_concurrent && SuspendibleThreadSet::should_yield()) { 109 // Caller will actually yield. 110 return false; 111 } 112 // Otherwise, we finished successfully; return true. 113 return true; 114 } 115 116 void set_concurrent(bool b) { _concurrent = b; } 117 }; 118 119 120 class RedirtyLoggedCardTableEntryClosure : public CardTableEntryClosure { 121 private: 122 size_t _num_dirtied; 123 G1CollectedHeap* _g1h; 124 G1SATBCardTableLoggingModRefBS* _g1_bs; 125 126 HeapRegion* region_for_card(jbyte* card_ptr) const { 127 return _g1h->heap_region_containing(_g1_bs->addr_for(card_ptr)); 128 } 129 130 bool will_become_free(HeapRegion* hr) const { 131 // A region will be freed by free_collection_set if the region is in the 132 // collection set and has not had an evacuation failure. 133 return _g1h->is_in_cset(hr) && !hr->evacuation_failed(); 134 } 135 136 public: 137 RedirtyLoggedCardTableEntryClosure(G1CollectedHeap* g1h) : CardTableEntryClosure(), 138 _num_dirtied(0), _g1h(g1h), _g1_bs(g1h->g1_barrier_set()) { } 139 140 bool do_card_ptr(jbyte* card_ptr, uint worker_i) { 141 HeapRegion* hr = region_for_card(card_ptr); 142 143 // Should only dirty cards in regions that won't be freed. 144 if (!will_become_free(hr)) { 145 *card_ptr = CardTableModRefBS::dirty_card_val(); 146 _num_dirtied++; 147 } 148 149 return true; 150 } 151 152 size_t num_dirtied() const { return _num_dirtied; } 153 }; 154 155 156 void G1RegionMappingChangedListener::reset_from_card_cache(uint start_idx, size_t num_regions) { 157 HeapRegionRemSet::invalidate_from_card_cache(start_idx, num_regions); 158 } 159 160 void G1RegionMappingChangedListener::on_commit(uint start_idx, size_t num_regions, bool zero_filled) { 161 // The from card cache is not the memory that is actually committed. So we cannot 162 // take advantage of the zero_filled parameter. 163 reset_from_card_cache(start_idx, num_regions); 164 } 165 166 // Returns true if the reference points to an object that 167 // can move in an incremental collection. 168 bool G1CollectedHeap::is_scavengable(const void* p) { 169 HeapRegion* hr = heap_region_containing(p); 170 return !hr->is_pinned(); 171 } 172 173 // Private methods. 174 175 HeapRegion* 176 G1CollectedHeap::new_region_try_secondary_free_list(bool is_old) { 177 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag); 178 while (!_secondary_free_list.is_empty() || free_regions_coming()) { 179 if (!_secondary_free_list.is_empty()) { 180 log_develop_trace(gc, freelist)("G1ConcRegionFreeing [region alloc] : " 181 "secondary_free_list has %u entries", 182 _secondary_free_list.length()); 183 // It looks as if there are free regions available on the 184 // secondary_free_list. Let's move them to the free_list and try 185 // again to allocate from it. 186 append_secondary_free_list(); 187 188 assert(_hrm.num_free_regions() > 0, "if the secondary_free_list was not " 189 "empty we should have moved at least one entry to the free_list"); 190 HeapRegion* res = _hrm.allocate_free_region(is_old); 191 log_develop_trace(gc, freelist)("G1ConcRegionFreeing [region alloc] : " 192 "allocated " HR_FORMAT " from secondary_free_list", 193 HR_FORMAT_PARAMS(res)); 194 return res; 195 } 196 197 // Wait here until we get notified either when (a) there are no 198 // more free regions coming or (b) some regions have been moved on 199 // the secondary_free_list. 200 SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag); 201 } 202 203 log_develop_trace(gc, freelist)("G1ConcRegionFreeing [region alloc] : " 204 "could not allocate from secondary_free_list"); 205 return NULL; 206 } 207 208 HeapRegion* G1CollectedHeap::new_region(size_t word_size, bool is_old, bool do_expand) { 209 assert(!is_humongous(word_size) || word_size <= HeapRegion::GrainWords, 210 "the only time we use this to allocate a humongous region is " 211 "when we are allocating a single humongous region"); 212 213 HeapRegion* res; 214 if (G1StressConcRegionFreeing) { 215 if (!_secondary_free_list.is_empty()) { 216 log_develop_trace(gc, freelist)("G1ConcRegionFreeing [region alloc] : " 217 "forced to look at the secondary_free_list"); 218 res = new_region_try_secondary_free_list(is_old); 219 if (res != NULL) { 220 return res; 221 } 222 } 223 } 224 225 res = _hrm.allocate_free_region(is_old); 226 227 if (res == NULL) { 228 log_develop_trace(gc, freelist)("G1ConcRegionFreeing [region alloc] : " 229 "res == NULL, trying the secondary_free_list"); 230 res = new_region_try_secondary_free_list(is_old); 231 } 232 if (res == NULL && do_expand && _expand_heap_after_alloc_failure) { 233 // Currently, only attempts to allocate GC alloc regions set 234 // do_expand to true. So, we should only reach here during a 235 // safepoint. If this assumption changes we might have to 236 // reconsider the use of _expand_heap_after_alloc_failure. 237 assert(SafepointSynchronize::is_at_safepoint(), "invariant"); 238 239 log_debug(gc, ergo, heap)("Attempt heap expansion (region allocation request failed). Allocation request: " SIZE_FORMAT "B", 240 word_size * HeapWordSize); 241 242 if (expand(word_size * HeapWordSize)) { 243 // Given that expand() succeeded in expanding the heap, and we 244 // always expand the heap by an amount aligned to the heap 245 // region size, the free list should in theory not be empty. 246 // In either case allocate_free_region() will check for NULL. 247 res = _hrm.allocate_free_region(is_old); 248 } else { 249 _expand_heap_after_alloc_failure = false; 250 } 251 } 252 return res; 253 } 254 255 HeapWord* 256 G1CollectedHeap::humongous_obj_allocate_initialize_regions(uint first, 257 uint num_regions, 258 size_t word_size, 259 AllocationContext_t context) { 260 assert(first != G1_NO_HRM_INDEX, "pre-condition"); 261 assert(is_humongous(word_size), "word_size should be humongous"); 262 assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition"); 263 264 // Index of last region in the series. 265 uint last = first + num_regions - 1; 266 267 // We need to initialize the region(s) we just discovered. This is 268 // a bit tricky given that it can happen concurrently with 269 // refinement threads refining cards on these regions and 270 // potentially wanting to refine the BOT as they are scanning 271 // those cards (this can happen shortly after a cleanup; see CR 272 // 6991377). So we have to set up the region(s) carefully and in 273 // a specific order. 274 275 // The word size sum of all the regions we will allocate. 276 size_t word_size_sum = (size_t) num_regions * HeapRegion::GrainWords; 277 assert(word_size <= word_size_sum, "sanity"); 278 279 // This will be the "starts humongous" region. 280 HeapRegion* first_hr = region_at(first); 281 // The header of the new object will be placed at the bottom of 282 // the first region. 283 HeapWord* new_obj = first_hr->bottom(); 284 // This will be the new top of the new object. 285 HeapWord* obj_top = new_obj + word_size; 286 287 // First, we need to zero the header of the space that we will be 288 // allocating. When we update top further down, some refinement 289 // threads might try to scan the region. By zeroing the header we 290 // ensure that any thread that will try to scan the region will 291 // come across the zero klass word and bail out. 292 // 293 // NOTE: It would not have been correct to have used 294 // CollectedHeap::fill_with_object() and make the space look like 295 // an int array. The thread that is doing the allocation will 296 // later update the object header to a potentially different array 297 // type and, for a very short period of time, the klass and length 298 // fields will be inconsistent. This could cause a refinement 299 // thread to calculate the object size incorrectly. 300 Copy::fill_to_words(new_obj, oopDesc::header_size(), 0); 301 302 // How many words we use for filler objects. 303 size_t word_fill_size = word_size_sum - word_size; 304 305 // How many words memory we "waste" which cannot hold a filler object. 306 size_t words_not_fillable = 0; 307 308 if (word_fill_size >= min_fill_size()) { 309 fill_with_objects(obj_top, word_fill_size); 310 } else if (word_fill_size > 0) { 311 // We have space to fill, but we cannot fit an object there. 312 words_not_fillable = word_fill_size; 313 word_fill_size = 0; 314 } 315 316 // We will set up the first region as "starts humongous". This 317 // will also update the BOT covering all the regions to reflect 318 // that there is a single object that starts at the bottom of the 319 // first region. 320 first_hr->set_starts_humongous(obj_top, word_fill_size); 321 first_hr->set_allocation_context(context); 322 // Then, if there are any, we will set up the "continues 323 // humongous" regions. 324 HeapRegion* hr = NULL; 325 for (uint i = first + 1; i <= last; ++i) { 326 hr = region_at(i); 327 hr->set_continues_humongous(first_hr); 328 hr->set_allocation_context(context); 329 } 330 331 // Up to this point no concurrent thread would have been able to 332 // do any scanning on any region in this series. All the top 333 // fields still point to bottom, so the intersection between 334 // [bottom,top] and [card_start,card_end] will be empty. Before we 335 // update the top fields, we'll do a storestore to make sure that 336 // no thread sees the update to top before the zeroing of the 337 // object header and the BOT initialization. 338 OrderAccess::storestore(); 339 340 // Now, we will update the top fields of the "continues humongous" 341 // regions except the last one. 342 for (uint i = first; i < last; ++i) { 343 hr = region_at(i); 344 hr->set_top(hr->end()); 345 } 346 347 hr = region_at(last); 348 // If we cannot fit a filler object, we must set top to the end 349 // of the humongous object, otherwise we cannot iterate the heap 350 // and the BOT will not be complete. 351 hr->set_top(hr->end() - words_not_fillable); 352 353 assert(hr->bottom() < obj_top && obj_top <= hr->end(), 354 "obj_top should be in last region"); 355 356 _verifier->check_bitmaps("Humongous Region Allocation", first_hr); 357 358 assert(words_not_fillable == 0 || 359 first_hr->bottom() + word_size_sum - words_not_fillable == hr->top(), 360 "Miscalculation in humongous allocation"); 361 362 increase_used((word_size_sum - words_not_fillable) * HeapWordSize); 363 364 for (uint i = first; i <= last; ++i) { 365 hr = region_at(i); 366 _humongous_set.add(hr); 367 _hr_printer.alloc(hr); 368 } 369 370 return new_obj; 371 } 372 373 size_t G1CollectedHeap::humongous_obj_size_in_regions(size_t word_size) { 374 assert(is_humongous(word_size), "Object of size " SIZE_FORMAT " must be humongous here", word_size); 375 return align_size_up_(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords; 376 } 377 378 // If could fit into free regions w/o expansion, try. 379 // Otherwise, if can expand, do so. 380 // Otherwise, if using ex regions might help, try with ex given back. 381 HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size, AllocationContext_t context) { 382 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */); 383 384 _verifier->verify_region_sets_optional(); 385 386 uint first = G1_NO_HRM_INDEX; 387 uint obj_regions = (uint) humongous_obj_size_in_regions(word_size); 388 389 if (obj_regions == 1) { 390 // Only one region to allocate, try to use a fast path by directly allocating 391 // from the free lists. Do not try to expand here, we will potentially do that 392 // later. 393 HeapRegion* hr = new_region(word_size, true /* is_old */, false /* do_expand */); 394 if (hr != NULL) { 395 first = hr->hrm_index(); 396 } 397 } else { 398 // We can't allocate humongous regions spanning more than one region while 399 // cleanupComplete() is running, since some of the regions we find to be 400 // empty might not yet be added to the free list. It is not straightforward 401 // to know in which list they are on so that we can remove them. We only 402 // need to do this if we need to allocate more than one region to satisfy the 403 // current humongous allocation request. If we are only allocating one region 404 // we use the one-region region allocation code (see above), that already 405 // potentially waits for regions from the secondary free list. 406 wait_while_free_regions_coming(); 407 append_secondary_free_list_if_not_empty_with_lock(); 408 409 // Policy: Try only empty regions (i.e. already committed first). Maybe we 410 // are lucky enough to find some. 411 first = _hrm.find_contiguous_only_empty(obj_regions); 412 if (first != G1_NO_HRM_INDEX) { 413 _hrm.allocate_free_regions_starting_at(first, obj_regions); 414 } 415 } 416 417 if (first == G1_NO_HRM_INDEX) { 418 // Policy: We could not find enough regions for the humongous object in the 419 // free list. Look through the heap to find a mix of free and uncommitted regions. 420 // If so, try expansion. 421 first = _hrm.find_contiguous_empty_or_unavailable(obj_regions); 422 if (first != G1_NO_HRM_INDEX) { 423 // We found something. Make sure these regions are committed, i.e. expand 424 // the heap. Alternatively we could do a defragmentation GC. 425 log_debug(gc, ergo, heap)("Attempt heap expansion (humongous allocation request failed). Allocation request: " SIZE_FORMAT "B", 426 word_size * HeapWordSize); 427 428 429 _hrm.expand_at(first, obj_regions); 430 g1_policy()->record_new_heap_size(num_regions()); 431 432 #ifdef ASSERT 433 for (uint i = first; i < first + obj_regions; ++i) { 434 HeapRegion* hr = region_at(i); 435 assert(hr->is_free(), "sanity"); 436 assert(hr->is_empty(), "sanity"); 437 assert(is_on_master_free_list(hr), "sanity"); 438 } 439 #endif 440 _hrm.allocate_free_regions_starting_at(first, obj_regions); 441 } else { 442 // Policy: Potentially trigger a defragmentation GC. 443 } 444 } 445 446 HeapWord* result = NULL; 447 if (first != G1_NO_HRM_INDEX) { 448 result = humongous_obj_allocate_initialize_regions(first, obj_regions, 449 word_size, context); 450 assert(result != NULL, "it should always return a valid result"); 451 452 // A successful humongous object allocation changes the used space 453 // information of the old generation so we need to recalculate the 454 // sizes and update the jstat counters here. 455 g1mm()->update_sizes(); 456 } 457 458 _verifier->verify_region_sets_optional(); 459 460 return result; 461 } 462 463 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t word_size) { 464 assert_heap_not_locked_and_not_at_safepoint(); 465 assert(!is_humongous(word_size), "we do not allow humongous TLABs"); 466 467 uint dummy_gc_count_before; 468 uint dummy_gclocker_retry_count = 0; 469 return attempt_allocation(word_size, &dummy_gc_count_before, &dummy_gclocker_retry_count); 470 } 471 472 HeapWord* 473 G1CollectedHeap::mem_allocate(size_t word_size, 474 bool* gc_overhead_limit_was_exceeded) { 475 assert_heap_not_locked_and_not_at_safepoint(); 476 477 // Loop until the allocation is satisfied, or unsatisfied after GC. 478 for (uint try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) { 479 uint gc_count_before; 480 481 HeapWord* result = NULL; 482 if (!is_humongous(word_size)) { 483 result = attempt_allocation(word_size, &gc_count_before, &gclocker_retry_count); 484 } else { 485 result = attempt_allocation_humongous(word_size, &gc_count_before, &gclocker_retry_count); 486 } 487 if (result != NULL) { 488 return result; 489 } 490 491 // Create the garbage collection operation... 492 VM_G1CollectForAllocation op(gc_count_before, word_size); 493 op.set_allocation_context(AllocationContext::current()); 494 495 // ...and get the VM thread to execute it. 496 VMThread::execute(&op); 497 498 if (op.prologue_succeeded() && op.pause_succeeded()) { 499 // If the operation was successful we'll return the result even 500 // if it is NULL. If the allocation attempt failed immediately 501 // after a Full GC, it's unlikely we'll be able to allocate now. 502 HeapWord* result = op.result(); 503 if (result != NULL && !is_humongous(word_size)) { 504 // Allocations that take place on VM operations do not do any 505 // card dirtying and we have to do it here. We only have to do 506 // this for non-humongous allocations, though. 507 dirty_young_block(result, word_size); 508 } 509 return result; 510 } else { 511 if (gclocker_retry_count > GCLockerRetryAllocationCount) { 512 return NULL; 513 } 514 assert(op.result() == NULL, 515 "the result should be NULL if the VM op did not succeed"); 516 } 517 518 // Give a warning if we seem to be looping forever. 519 if ((QueuedAllocationWarningCount > 0) && 520 (try_count % QueuedAllocationWarningCount == 0)) { 521 log_warning(gc)("G1CollectedHeap::mem_allocate retries %d times", try_count); 522 } 523 } 524 525 ShouldNotReachHere(); 526 return NULL; 527 } 528 529 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size, 530 AllocationContext_t context, 531 uint* gc_count_before_ret, 532 uint* gclocker_retry_count_ret) { 533 // Make sure you read the note in attempt_allocation_humongous(). 534 535 assert_heap_not_locked_and_not_at_safepoint(); 536 assert(!is_humongous(word_size), "attempt_allocation_slow() should not " 537 "be called for humongous allocation requests"); 538 539 // We should only get here after the first-level allocation attempt 540 // (attempt_allocation()) failed to allocate. 541 542 // We will loop until a) we manage to successfully perform the 543 // allocation or b) we successfully schedule a collection which 544 // fails to perform the allocation. b) is the only case when we'll 545 // return NULL. 546 HeapWord* result = NULL; 547 for (int try_count = 1; /* we'll return */; try_count += 1) { 548 bool should_try_gc; 549 uint gc_count_before; 550 551 { 552 MutexLockerEx x(Heap_lock); 553 result = _allocator->attempt_allocation_locked(word_size, context); 554 if (result != NULL) { 555 return result; 556 } 557 558 if (GCLocker::is_active_and_needs_gc()) { 559 if (g1_policy()->can_expand_young_list()) { 560 // No need for an ergo verbose message here, 561 // can_expand_young_list() does this when it returns true. 562 result = _allocator->attempt_allocation_force(word_size, context); 563 if (result != NULL) { 564 return result; 565 } 566 } 567 should_try_gc = false; 568 } else { 569 // The GCLocker may not be active but the GCLocker initiated 570 // GC may not yet have been performed (GCLocker::needs_gc() 571 // returns true). In this case we do not try this GC and 572 // wait until the GCLocker initiated GC is performed, and 573 // then retry the allocation. 574 if (GCLocker::needs_gc()) { 575 should_try_gc = false; 576 } else { 577 // Read the GC count while still holding the Heap_lock. 578 gc_count_before = total_collections(); 579 should_try_gc = true; 580 } 581 } 582 } 583 584 if (should_try_gc) { 585 bool succeeded; 586 result = do_collection_pause(word_size, gc_count_before, &succeeded, 587 GCCause::_g1_inc_collection_pause); 588 if (result != NULL) { 589 assert(succeeded, "only way to get back a non-NULL result"); 590 return result; 591 } 592 593 if (succeeded) { 594 // If we get here we successfully scheduled a collection which 595 // failed to allocate. No point in trying to allocate 596 // further. We'll just return NULL. 597 MutexLockerEx x(Heap_lock); 598 *gc_count_before_ret = total_collections(); 599 return NULL; 600 } 601 } else { 602 if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) { 603 MutexLockerEx x(Heap_lock); 604 *gc_count_before_ret = total_collections(); 605 return NULL; 606 } 607 // The GCLocker is either active or the GCLocker initiated 608 // GC has not yet been performed. Stall until it is and 609 // then retry the allocation. 610 GCLocker::stall_until_clear(); 611 (*gclocker_retry_count_ret) += 1; 612 } 613 614 // We can reach here if we were unsuccessful in scheduling a 615 // collection (because another thread beat us to it) or if we were 616 // stalled due to the GC locker. In either can we should retry the 617 // allocation attempt in case another thread successfully 618 // performed a collection and reclaimed enough space. We do the 619 // first attempt (without holding the Heap_lock) here and the 620 // follow-on attempt will be at the start of the next loop 621 // iteration (after taking the Heap_lock). 622 result = _allocator->attempt_allocation(word_size, context); 623 if (result != NULL) { 624 return result; 625 } 626 627 // Give a warning if we seem to be looping forever. 628 if ((QueuedAllocationWarningCount > 0) && 629 (try_count % QueuedAllocationWarningCount == 0)) { 630 log_warning(gc)("G1CollectedHeap::attempt_allocation_slow() " 631 "retries %d times", try_count); 632 } 633 } 634 635 ShouldNotReachHere(); 636 return NULL; 637 } 638 639 void G1CollectedHeap::begin_archive_alloc_range() { 640 assert_at_safepoint(true /* should_be_vm_thread */); 641 if (_archive_allocator == NULL) { 642 _archive_allocator = G1ArchiveAllocator::create_allocator(this); 643 } 644 } 645 646 bool G1CollectedHeap::is_archive_alloc_too_large(size_t word_size) { 647 // Allocations in archive regions cannot be of a size that would be considered 648 // humongous even for a minimum-sized region, because G1 region sizes/boundaries 649 // may be different at archive-restore time. 650 return word_size >= humongous_threshold_for(HeapRegion::min_region_size_in_words()); 651 } 652 653 HeapWord* G1CollectedHeap::archive_mem_allocate(size_t word_size) { 654 assert_at_safepoint(true /* should_be_vm_thread */); 655 assert(_archive_allocator != NULL, "_archive_allocator not initialized"); 656 if (is_archive_alloc_too_large(word_size)) { 657 return NULL; 658 } 659 return _archive_allocator->archive_mem_allocate(word_size); 660 } 661 662 void G1CollectedHeap::end_archive_alloc_range(GrowableArray<MemRegion>* ranges, 663 size_t end_alignment_in_bytes) { 664 assert_at_safepoint(true /* should_be_vm_thread */); 665 assert(_archive_allocator != NULL, "_archive_allocator not initialized"); 666 667 // Call complete_archive to do the real work, filling in the MemRegion 668 // array with the archive regions. 669 _archive_allocator->complete_archive(ranges, end_alignment_in_bytes); 670 delete _archive_allocator; 671 _archive_allocator = NULL; 672 } 673 674 bool G1CollectedHeap::check_archive_addresses(MemRegion* ranges, size_t count) { 675 assert(ranges != NULL, "MemRegion array NULL"); 676 assert(count != 0, "No MemRegions provided"); 677 MemRegion reserved = _hrm.reserved(); 678 for (size_t i = 0; i < count; i++) { 679 if (!reserved.contains(ranges[i].start()) || !reserved.contains(ranges[i].last())) { 680 return false; 681 } 682 } 683 return true; 684 } 685 686 bool G1CollectedHeap::alloc_archive_regions(MemRegion* ranges, size_t count) { 687 assert(!is_init_completed(), "Expect to be called at JVM init time"); 688 assert(ranges != NULL, "MemRegion array NULL"); 689 assert(count != 0, "No MemRegions provided"); 690 MutexLockerEx x(Heap_lock); 691 692 MemRegion reserved = _hrm.reserved(); 693 HeapWord* prev_last_addr = NULL; 694 HeapRegion* prev_last_region = NULL; 695 696 // Temporarily disable pretouching of heap pages. This interface is used 697 // when mmap'ing archived heap data in, so pre-touching is wasted. 698 FlagSetting fs(AlwaysPreTouch, false); 699 700 // Enable archive object checking in G1MarkSweep. We have to let it know 701 // about each archive range, so that objects in those ranges aren't marked. 702 G1MarkSweep::enable_archive_object_check(); 703 704 // For each specified MemRegion range, allocate the corresponding G1 705 // regions and mark them as archive regions. We expect the ranges in 706 // ascending starting address order, without overlap. 707 for (size_t i = 0; i < count; i++) { 708 MemRegion curr_range = ranges[i]; 709 HeapWord* start_address = curr_range.start(); 710 size_t word_size = curr_range.word_size(); 711 HeapWord* last_address = curr_range.last(); 712 size_t commits = 0; 713 714 guarantee(reserved.contains(start_address) && reserved.contains(last_address), 715 "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]", 716 p2i(start_address), p2i(last_address)); 717 guarantee(start_address > prev_last_addr, 718 "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT , 719 p2i(start_address), p2i(prev_last_addr)); 720 prev_last_addr = last_address; 721 722 // Check for ranges that start in the same G1 region in which the previous 723 // range ended, and adjust the start address so we don't try to allocate 724 // the same region again. If the current range is entirely within that 725 // region, skip it, just adjusting the recorded top. 726 HeapRegion* start_region = _hrm.addr_to_region(start_address); 727 if ((prev_last_region != NULL) && (start_region == prev_last_region)) { 728 start_address = start_region->end(); 729 if (start_address > last_address) { 730 increase_used(word_size * HeapWordSize); 731 start_region->set_top(last_address + 1); 732 continue; 733 } 734 start_region->set_top(start_address); 735 curr_range = MemRegion(start_address, last_address + 1); 736 start_region = _hrm.addr_to_region(start_address); 737 } 738 739 // Perform the actual region allocation, exiting if it fails. 740 // Then note how much new space we have allocated. 741 if (!_hrm.allocate_containing_regions(curr_range, &commits)) { 742 return false; 743 } 744 increase_used(word_size * HeapWordSize); 745 if (commits != 0) { 746 log_debug(gc, ergo, heap)("Attempt heap expansion (allocate archive regions). Total size: " SIZE_FORMAT "B", 747 HeapRegion::GrainWords * HeapWordSize * commits); 748 749 } 750 751 // Mark each G1 region touched by the range as archive, add it to the old set, 752 // and set the allocation context and top. 753 HeapRegion* curr_region = _hrm.addr_to_region(start_address); 754 HeapRegion* last_region = _hrm.addr_to_region(last_address); 755 prev_last_region = last_region; 756 757 while (curr_region != NULL) { 758 assert(curr_region->is_empty() && !curr_region->is_pinned(), 759 "Region already in use (index %u)", curr_region->hrm_index()); 760 curr_region->set_allocation_context(AllocationContext::system()); 761 curr_region->set_archive(); 762 _hr_printer.alloc(curr_region); 763 _old_set.add(curr_region); 764 if (curr_region != last_region) { 765 curr_region->set_top(curr_region->end()); 766 curr_region = _hrm.next_region_in_heap(curr_region); 767 } else { 768 curr_region->set_top(last_address + 1); 769 curr_region = NULL; 770 } 771 } 772 773 // Notify mark-sweep of the archive range. 774 G1MarkSweep::set_range_archive(curr_range, true); 775 } 776 return true; 777 } 778 779 void G1CollectedHeap::fill_archive_regions(MemRegion* ranges, size_t count) { 780 assert(!is_init_completed(), "Expect to be called at JVM init time"); 781 assert(ranges != NULL, "MemRegion array NULL"); 782 assert(count != 0, "No MemRegions provided"); 783 MemRegion reserved = _hrm.reserved(); 784 HeapWord *prev_last_addr = NULL; 785 HeapRegion* prev_last_region = NULL; 786 787 // For each MemRegion, create filler objects, if needed, in the G1 regions 788 // that contain the address range. The address range actually within the 789 // MemRegion will not be modified. That is assumed to have been initialized 790 // elsewhere, probably via an mmap of archived heap data. 791 MutexLockerEx x(Heap_lock); 792 for (size_t i = 0; i < count; i++) { 793 HeapWord* start_address = ranges[i].start(); 794 HeapWord* last_address = ranges[i].last(); 795 796 assert(reserved.contains(start_address) && reserved.contains(last_address), 797 "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]", 798 p2i(start_address), p2i(last_address)); 799 assert(start_address > prev_last_addr, 800 "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT , 801 p2i(start_address), p2i(prev_last_addr)); 802 803 HeapRegion* start_region = _hrm.addr_to_region(start_address); 804 HeapRegion* last_region = _hrm.addr_to_region(last_address); 805 HeapWord* bottom_address = start_region->bottom(); 806 807 // Check for a range beginning in the same region in which the 808 // previous one ended. 809 if (start_region == prev_last_region) { 810 bottom_address = prev_last_addr + 1; 811 } 812 813 // Verify that the regions were all marked as archive regions by 814 // alloc_archive_regions. 815 HeapRegion* curr_region = start_region; 816 while (curr_region != NULL) { 817 guarantee(curr_region->is_archive(), 818 "Expected archive region at index %u", curr_region->hrm_index()); 819 if (curr_region != last_region) { 820 curr_region = _hrm.next_region_in_heap(curr_region); 821 } else { 822 curr_region = NULL; 823 } 824 } 825 826 prev_last_addr = last_address; 827 prev_last_region = last_region; 828 829 // Fill the memory below the allocated range with dummy object(s), 830 // if the region bottom does not match the range start, or if the previous 831 // range ended within the same G1 region, and there is a gap. 832 if (start_address != bottom_address) { 833 size_t fill_size = pointer_delta(start_address, bottom_address); 834 G1CollectedHeap::fill_with_objects(bottom_address, fill_size); 835 increase_used(fill_size * HeapWordSize); 836 } 837 } 838 } 839 840 inline HeapWord* G1CollectedHeap::attempt_allocation(size_t word_size, 841 uint* gc_count_before_ret, 842 uint* gclocker_retry_count_ret) { 843 assert_heap_not_locked_and_not_at_safepoint(); 844 assert(!is_humongous(word_size), "attempt_allocation() should not " 845 "be called for humongous allocation requests"); 846 847 AllocationContext_t context = AllocationContext::current(); 848 HeapWord* result = _allocator->attempt_allocation(word_size, context); 849 850 if (result == NULL) { 851 result = attempt_allocation_slow(word_size, 852 context, 853 gc_count_before_ret, 854 gclocker_retry_count_ret); 855 } 856 assert_heap_not_locked(); 857 if (result != NULL) { 858 dirty_young_block(result, word_size); 859 } 860 return result; 861 } 862 863 void G1CollectedHeap::dealloc_archive_regions(MemRegion* ranges, size_t count) { 864 assert(!is_init_completed(), "Expect to be called at JVM init time"); 865 assert(ranges != NULL, "MemRegion array NULL"); 866 assert(count != 0, "No MemRegions provided"); 867 MemRegion reserved = _hrm.reserved(); 868 HeapWord* prev_last_addr = NULL; 869 HeapRegion* prev_last_region = NULL; 870 size_t size_used = 0; 871 size_t uncommitted_regions = 0; 872 873 // For each Memregion, free the G1 regions that constitute it, and 874 // notify mark-sweep that the range is no longer to be considered 'archive.' 875 MutexLockerEx x(Heap_lock); 876 for (size_t i = 0; i < count; i++) { 877 HeapWord* start_address = ranges[i].start(); 878 HeapWord* last_address = ranges[i].last(); 879 880 assert(reserved.contains(start_address) && reserved.contains(last_address), 881 "MemRegion outside of heap [" PTR_FORMAT ", " PTR_FORMAT "]", 882 p2i(start_address), p2i(last_address)); 883 assert(start_address > prev_last_addr, 884 "Ranges not in ascending order: " PTR_FORMAT " <= " PTR_FORMAT , 885 p2i(start_address), p2i(prev_last_addr)); 886 size_used += ranges[i].byte_size(); 887 prev_last_addr = last_address; 888 889 HeapRegion* start_region = _hrm.addr_to_region(start_address); 890 HeapRegion* last_region = _hrm.addr_to_region(last_address); 891 892 // Check for ranges that start in the same G1 region in which the previous 893 // range ended, and adjust the start address so we don't try to free 894 // the same region again. If the current range is entirely within that 895 // region, skip it. 896 if (start_region == prev_last_region) { 897 start_address = start_region->end(); 898 if (start_address > last_address) { 899 continue; 900 } 901 start_region = _hrm.addr_to_region(start_address); 902 } 903 prev_last_region = last_region; 904 905 // After verifying that each region was marked as an archive region by 906 // alloc_archive_regions, set it free and empty and uncommit it. 907 HeapRegion* curr_region = start_region; 908 while (curr_region != NULL) { 909 guarantee(curr_region->is_archive(), 910 "Expected archive region at index %u", curr_region->hrm_index()); 911 uint curr_index = curr_region->hrm_index(); 912 _old_set.remove(curr_region); 913 curr_region->set_free(); 914 curr_region->set_top(curr_region->bottom()); 915 if (curr_region != last_region) { 916 curr_region = _hrm.next_region_in_heap(curr_region); 917 } else { 918 curr_region = NULL; 919 } 920 _hrm.shrink_at(curr_index, 1); 921 uncommitted_regions++; 922 } 923 924 // Notify mark-sweep that this is no longer an archive range. 925 G1MarkSweep::set_range_archive(ranges[i], false); 926 } 927 928 if (uncommitted_regions != 0) { 929 log_debug(gc, ergo, heap)("Attempt heap shrinking (uncommitted archive regions). Total size: " SIZE_FORMAT "B", 930 HeapRegion::GrainWords * HeapWordSize * uncommitted_regions); 931 } 932 decrease_used(size_used); 933 } 934 935 HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size, 936 uint* gc_count_before_ret, 937 uint* gclocker_retry_count_ret) { 938 // The structure of this method has a lot of similarities to 939 // attempt_allocation_slow(). The reason these two were not merged 940 // into a single one is that such a method would require several "if 941 // allocation is not humongous do this, otherwise do that" 942 // conditional paths which would obscure its flow. In fact, an early 943 // version of this code did use a unified method which was harder to 944 // follow and, as a result, it had subtle bugs that were hard to 945 // track down. So keeping these two methods separate allows each to 946 // be more readable. It will be good to keep these two in sync as 947 // much as possible. 948 949 assert_heap_not_locked_and_not_at_safepoint(); 950 assert(is_humongous(word_size), "attempt_allocation_humongous() " 951 "should only be called for humongous allocations"); 952 953 // Humongous objects can exhaust the heap quickly, so we should check if we 954 // need to start a marking cycle at each humongous object allocation. We do 955 // the check before we do the actual allocation. The reason for doing it 956 // before the allocation is that we avoid having to keep track of the newly 957 // allocated memory while we do a GC. 958 if (g1_policy()->need_to_start_conc_mark("concurrent humongous allocation", 959 word_size)) { 960 collect(GCCause::_g1_humongous_allocation); 961 } 962 963 // We will loop until a) we manage to successfully perform the 964 // allocation or b) we successfully schedule a collection which 965 // fails to perform the allocation. b) is the only case when we'll 966 // return NULL. 967 HeapWord* result = NULL; 968 for (int try_count = 1; /* we'll return */; try_count += 1) { 969 bool should_try_gc; 970 uint gc_count_before; 971 972 { 973 MutexLockerEx x(Heap_lock); 974 975 // Given that humongous objects are not allocated in young 976 // regions, we'll first try to do the allocation without doing a 977 // collection hoping that there's enough space in the heap. 978 result = humongous_obj_allocate(word_size, AllocationContext::current()); 979 if (result != NULL) { 980 size_t size_in_regions = humongous_obj_size_in_regions(word_size); 981 g1_policy()->add_bytes_allocated_in_old_since_last_gc(size_in_regions * HeapRegion::GrainBytes); 982 return result; 983 } 984 985 if (GCLocker::is_active_and_needs_gc()) { 986 should_try_gc = false; 987 } else { 988 // The GCLocker may not be active but the GCLocker initiated 989 // GC may not yet have been performed (GCLocker::needs_gc() 990 // returns true). In this case we do not try this GC and 991 // wait until the GCLocker initiated GC is performed, and 992 // then retry the allocation. 993 if (GCLocker::needs_gc()) { 994 should_try_gc = false; 995 } else { 996 // Read the GC count while still holding the Heap_lock. 997 gc_count_before = total_collections(); 998 should_try_gc = true; 999 } 1000 } 1001 } 1002 1003 if (should_try_gc) { 1004 // If we failed to allocate the humongous object, we should try to 1005 // do a collection pause (if we're allowed) in case it reclaims 1006 // enough space for the allocation to succeed after the pause. 1007 1008 bool succeeded; 1009 result = do_collection_pause(word_size, gc_count_before, &succeeded, 1010 GCCause::_g1_humongous_allocation); 1011 if (result != NULL) { 1012 assert(succeeded, "only way to get back a non-NULL result"); 1013 return result; 1014 } 1015 1016 if (succeeded) { 1017 // If we get here we successfully scheduled a collection which 1018 // failed to allocate. No point in trying to allocate 1019 // further. We'll just return NULL. 1020 MutexLockerEx x(Heap_lock); 1021 *gc_count_before_ret = total_collections(); 1022 return NULL; 1023 } 1024 } else { 1025 if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) { 1026 MutexLockerEx x(Heap_lock); 1027 *gc_count_before_ret = total_collections(); 1028 return NULL; 1029 } 1030 // The GCLocker is either active or the GCLocker initiated 1031 // GC has not yet been performed. Stall until it is and 1032 // then retry the allocation. 1033 GCLocker::stall_until_clear(); 1034 (*gclocker_retry_count_ret) += 1; 1035 } 1036 1037 // We can reach here if we were unsuccessful in scheduling a 1038 // collection (because another thread beat us to it) or if we were 1039 // stalled due to the GC locker. In either can we should retry the 1040 // allocation attempt in case another thread successfully 1041 // performed a collection and reclaimed enough space. Give a 1042 // warning if we seem to be looping forever. 1043 1044 if ((QueuedAllocationWarningCount > 0) && 1045 (try_count % QueuedAllocationWarningCount == 0)) { 1046 log_warning(gc)("G1CollectedHeap::attempt_allocation_humongous() " 1047 "retries %d times", try_count); 1048 } 1049 } 1050 1051 ShouldNotReachHere(); 1052 return NULL; 1053 } 1054 1055 HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size, 1056 AllocationContext_t context, 1057 bool expect_null_mutator_alloc_region) { 1058 assert_at_safepoint(true /* should_be_vm_thread */); 1059 assert(!_allocator->has_mutator_alloc_region(context) || !expect_null_mutator_alloc_region, 1060 "the current alloc region was unexpectedly found to be non-NULL"); 1061 1062 if (!is_humongous(word_size)) { 1063 return _allocator->attempt_allocation_locked(word_size, context); 1064 } else { 1065 HeapWord* result = humongous_obj_allocate(word_size, context); 1066 if (result != NULL && g1_policy()->need_to_start_conc_mark("STW humongous allocation")) { 1067 collector_state()->set_initiate_conc_mark_if_possible(true); 1068 } 1069 return result; 1070 } 1071 1072 ShouldNotReachHere(); 1073 } 1074 1075 class PostMCRemSetClearClosure: public HeapRegionClosure { 1076 G1CollectedHeap* _g1h; 1077 ModRefBarrierSet* _mr_bs; 1078 public: 1079 PostMCRemSetClearClosure(G1CollectedHeap* g1h, ModRefBarrierSet* mr_bs) : 1080 _g1h(g1h), _mr_bs(mr_bs) {} 1081 1082 bool doHeapRegion(HeapRegion* r) { 1083 HeapRegionRemSet* hrrs = r->rem_set(); 1084 1085 _g1h->reset_gc_time_stamps(r); 1086 1087 if (r->is_continues_humongous()) { 1088 // We'll assert that the strong code root list and RSet is empty 1089 assert(hrrs->strong_code_roots_list_length() == 0, "sanity"); 1090 assert(hrrs->occupied() == 0, "RSet should be empty"); 1091 } else { 1092 hrrs->clear(); 1093 } 1094 // You might think here that we could clear just the cards 1095 // corresponding to the used region. But no: if we leave a dirty card 1096 // in a region we might allocate into, then it would prevent that card 1097 // from being enqueued, and cause it to be missed. 1098 // Re: the performance cost: we shouldn't be doing full GC anyway! 1099 _mr_bs->clear(MemRegion(r->bottom(), r->end())); 1100 1101 return false; 1102 } 1103 }; 1104 1105 void G1CollectedHeap::clear_rsets_post_compaction() { 1106 PostMCRemSetClearClosure rs_clear(this, g1_barrier_set()); 1107 heap_region_iterate(&rs_clear); 1108 } 1109 1110 class RebuildRSOutOfRegionClosure: public HeapRegionClosure { 1111 G1CollectedHeap* _g1h; 1112 UpdateRSOopClosure _cl; 1113 public: 1114 RebuildRSOutOfRegionClosure(G1CollectedHeap* g1, uint worker_i = 0) : 1115 _cl(g1->g1_rem_set(), worker_i), 1116 _g1h(g1) 1117 { } 1118 1119 bool doHeapRegion(HeapRegion* r) { 1120 if (!r->is_continues_humongous()) { 1121 _cl.set_from(r); 1122 r->oop_iterate(&_cl); 1123 } 1124 return false; 1125 } 1126 }; 1127 1128 class ParRebuildRSTask: public AbstractGangTask { 1129 G1CollectedHeap* _g1; 1130 HeapRegionClaimer _hrclaimer; 1131 1132 public: 1133 ParRebuildRSTask(G1CollectedHeap* g1) : 1134 AbstractGangTask("ParRebuildRSTask"), _g1(g1), _hrclaimer(g1->workers()->active_workers()) {} 1135 1136 void work(uint worker_id) { 1137 RebuildRSOutOfRegionClosure rebuild_rs(_g1, worker_id); 1138 _g1->heap_region_par_iterate(&rebuild_rs, worker_id, &_hrclaimer); 1139 } 1140 }; 1141 1142 class PostCompactionPrinterClosure: public HeapRegionClosure { 1143 private: 1144 G1HRPrinter* _hr_printer; 1145 public: 1146 bool doHeapRegion(HeapRegion* hr) { 1147 assert(!hr->is_young(), "not expecting to find young regions"); 1148 _hr_printer->post_compaction(hr); 1149 return false; 1150 } 1151 1152 PostCompactionPrinterClosure(G1HRPrinter* hr_printer) 1153 : _hr_printer(hr_printer) { } 1154 }; 1155 1156 void G1CollectedHeap::print_hrm_post_compaction() { 1157 if (_hr_printer.is_active()) { 1158 PostCompactionPrinterClosure cl(hr_printer()); 1159 heap_region_iterate(&cl); 1160 } 1161 1162 } 1163 1164 bool G1CollectedHeap::do_full_collection(bool explicit_gc, 1165 bool clear_all_soft_refs) { 1166 assert_at_safepoint(true /* should_be_vm_thread */); 1167 1168 if (GCLocker::check_active_before_gc()) { 1169 return false; 1170 } 1171 1172 STWGCTimer* gc_timer = G1MarkSweep::gc_timer(); 1173 gc_timer->register_gc_start(); 1174 1175 SerialOldTracer* gc_tracer = G1MarkSweep::gc_tracer(); 1176 GCIdMark gc_id_mark; 1177 gc_tracer->report_gc_start(gc_cause(), gc_timer->gc_start()); 1178 1179 SvcGCMarker sgcm(SvcGCMarker::FULL); 1180 ResourceMark rm; 1181 1182 print_heap_before_gc(); 1183 print_heap_regions(); 1184 trace_heap_before_gc(gc_tracer); 1185 1186 size_t metadata_prev_used = MetaspaceAux::used_bytes(); 1187 1188 _verifier->verify_region_sets_optional(); 1189 1190 const bool do_clear_all_soft_refs = clear_all_soft_refs || 1191 collector_policy()->should_clear_all_soft_refs(); 1192 1193 ClearedAllSoftRefs casr(do_clear_all_soft_refs, collector_policy()); 1194 1195 { 1196 IsGCActiveMark x; 1197 1198 // Timing 1199 assert(!GCCause::is_user_requested_gc(gc_cause()) || explicit_gc, "invariant"); 1200 GCTraceCPUTime tcpu; 1201 1202 { 1203 GCTraceTime(Info, gc) tm("Pause Full", NULL, gc_cause(), true); 1204 TraceCollectorStats tcs(g1mm()->full_collection_counters()); 1205 TraceMemoryManagerStats tms(true /* fullGC */, gc_cause()); 1206 1207 G1HeapTransition heap_transition(this); 1208 g1_policy()->record_full_collection_start(); 1209 1210 // Note: When we have a more flexible GC logging framework that 1211 // allows us to add optional attributes to a GC log record we 1212 // could consider timing and reporting how long we wait in the 1213 // following two methods. 1214 wait_while_free_regions_coming(); 1215 // If we start the compaction before the CM threads finish 1216 // scanning the root regions we might trip them over as we'll 1217 // be moving objects / updating references. So let's wait until 1218 // they are done. By telling them to abort, they should complete 1219 // early. 1220 _cm->root_regions()->abort(); 1221 _cm->root_regions()->wait_until_scan_finished(); 1222 append_secondary_free_list_if_not_empty_with_lock(); 1223 1224 gc_prologue(true); 1225 increment_total_collections(true /* full gc */); 1226 increment_old_marking_cycles_started(); 1227 1228 assert(used() == recalculate_used(), "Should be equal"); 1229 1230 _verifier->verify_before_gc(); 1231 1232 _verifier->check_bitmaps("Full GC Start"); 1233 pre_full_gc_dump(gc_timer); 1234 1235 #if defined(COMPILER2) || INCLUDE_JVMCI 1236 DerivedPointerTable::clear(); 1237 #endif 1238 1239 // Disable discovery and empty the discovered lists 1240 // for the CM ref processor. 1241 ref_processor_cm()->disable_discovery(); 1242 ref_processor_cm()->abandon_partial_discovery(); 1243 ref_processor_cm()->verify_no_references_recorded(); 1244 1245 // Abandon current iterations of concurrent marking and concurrent 1246 // refinement, if any are in progress. 1247 concurrent_mark()->abort(); 1248 1249 // Make sure we'll choose a new allocation region afterwards. 1250 _allocator->release_mutator_alloc_region(); 1251 _allocator->abandon_gc_alloc_regions(); 1252 g1_rem_set()->cleanupHRRS(); 1253 1254 // We may have added regions to the current incremental collection 1255 // set between the last GC or pause and now. We need to clear the 1256 // incremental collection set and then start rebuilding it afresh 1257 // after this full GC. 1258 abandon_collection_set(collection_set()->inc_head()); 1259 collection_set()->clear_incremental(); 1260 collection_set()->stop_incremental_building(); 1261 1262 tear_down_region_sets(false /* free_list_only */); 1263 collector_state()->set_gcs_are_young(true); 1264 1265 // See the comments in g1CollectedHeap.hpp and 1266 // G1CollectedHeap::ref_processing_init() about 1267 // how reference processing currently works in G1. 1268 1269 // Temporarily make discovery by the STW ref processor single threaded (non-MT). 1270 ReferenceProcessorMTDiscoveryMutator stw_rp_disc_ser(ref_processor_stw(), false); 1271 1272 // Temporarily clear the STW ref processor's _is_alive_non_header field. 1273 ReferenceProcessorIsAliveMutator stw_rp_is_alive_null(ref_processor_stw(), NULL); 1274 1275 ref_processor_stw()->enable_discovery(); 1276 ref_processor_stw()->setup_policy(do_clear_all_soft_refs); 1277 1278 // Do collection work 1279 { 1280 HandleMark hm; // Discard invalid handles created during gc 1281 G1MarkSweep::invoke_at_safepoint(ref_processor_stw(), do_clear_all_soft_refs); 1282 } 1283 1284 assert(num_free_regions() == 0, "we should not have added any free regions"); 1285 rebuild_region_sets(false /* free_list_only */); 1286 1287 // Enqueue any discovered reference objects that have 1288 // not been removed from the discovered lists. 1289 ref_processor_stw()->enqueue_discovered_references(); 1290 1291 #if defined(COMPILER2) || INCLUDE_JVMCI 1292 DerivedPointerTable::update_pointers(); 1293 #endif 1294 1295 MemoryService::track_memory_usage(); 1296 1297 assert(!ref_processor_stw()->discovery_enabled(), "Postcondition"); 1298 ref_processor_stw()->verify_no_references_recorded(); 1299 1300 // Delete metaspaces for unloaded class loaders and clean up loader_data graph 1301 ClassLoaderDataGraph::purge(); 1302 MetaspaceAux::verify_metrics(); 1303 1304 // Note: since we've just done a full GC, concurrent 1305 // marking is no longer active. Therefore we need not 1306 // re-enable reference discovery for the CM ref processor. 1307 // That will be done at the start of the next marking cycle. 1308 assert(!ref_processor_cm()->discovery_enabled(), "Postcondition"); 1309 ref_processor_cm()->verify_no_references_recorded(); 1310 1311 reset_gc_time_stamp(); 1312 // Since everything potentially moved, we will clear all remembered 1313 // sets, and clear all cards. Later we will rebuild remembered 1314 // sets. We will also reset the GC time stamps of the regions. 1315 clear_rsets_post_compaction(); 1316 check_gc_time_stamps(); 1317 1318 resize_if_necessary_after_full_collection(); 1319 1320 // We should do this after we potentially resize the heap so 1321 // that all the COMMIT / UNCOMMIT events are generated before 1322 // the compaction events. 1323 print_hrm_post_compaction(); 1324 1325 G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache(); 1326 if (hot_card_cache->use_cache()) { 1327 hot_card_cache->reset_card_counts(); 1328 hot_card_cache->reset_hot_cache(); 1329 } 1330 1331 // Rebuild remembered sets of all regions. 1332 uint n_workers = 1333 AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(), 1334 workers()->active_workers(), 1335 Threads::number_of_non_daemon_threads()); 1336 workers()->set_active_workers(n_workers); 1337 1338 ParRebuildRSTask rebuild_rs_task(this); 1339 workers()->run_task(&rebuild_rs_task); 1340 1341 // Rebuild the strong code root lists for each region 1342 rebuild_strong_code_roots(); 1343 1344 if (true) { // FIXME 1345 MetaspaceGC::compute_new_size(); 1346 } 1347 1348 #ifdef TRACESPINNING 1349 ParallelTaskTerminator::print_termination_counts(); 1350 #endif 1351 1352 // Discard all rset updates 1353 JavaThread::dirty_card_queue_set().abandon_logs(); 1354 assert(dirty_card_queue_set().completed_buffers_num() == 0, "DCQS should be empty"); 1355 1356 // At this point there should be no regions in the 1357 // entire heap tagged as young. 1358 assert(check_young_list_empty(true /* check_heap */), 1359 "young list should be empty at this point"); 1360 1361 // Update the number of full collections that have been completed. 1362 increment_old_marking_cycles_completed(false /* concurrent */); 1363 1364 _hrm.verify_optional(); 1365 _verifier->verify_region_sets_optional(); 1366 1367 _verifier->verify_after_gc(); 1368 1369 // Clear the previous marking bitmap, if needed for bitmap verification. 1370 // Note we cannot do this when we clear the next marking bitmap in 1371 // G1ConcurrentMark::abort() above since VerifyDuringGC verifies the 1372 // objects marked during a full GC against the previous bitmap. 1373 // But we need to clear it before calling check_bitmaps below since 1374 // the full GC has compacted objects and updated TAMS but not updated 1375 // the prev bitmap. 1376 if (G1VerifyBitmaps) { 1377 GCTraceTime(Debug, gc)("Clear Bitmap for Verification"); 1378 _cm->clear_prev_bitmap(workers()); 1379 } 1380 _verifier->check_bitmaps("Full GC End"); 1381 1382 // Start a new incremental collection set for the next pause 1383 assert(collection_set()->head() == NULL, "must be"); 1384 collection_set()->start_incremental_building(); 1385 1386 clear_cset_fast_test(); 1387 1388 _allocator->init_mutator_alloc_region(); 1389 1390 g1_policy()->record_full_collection_end(); 1391 1392 // We must call G1MonitoringSupport::update_sizes() in the same scoping level 1393 // as an active TraceMemoryManagerStats object (i.e. before the destructor for the 1394 // TraceMemoryManagerStats is called) so that the G1 memory pools are updated 1395 // before any GC notifications are raised. 1396 g1mm()->update_sizes(); 1397 1398 gc_epilogue(true); 1399 1400 heap_transition.print(); 1401 1402 print_heap_after_gc(); 1403 print_heap_regions(); 1404 trace_heap_after_gc(gc_tracer); 1405 1406 post_full_gc_dump(gc_timer); 1407 } 1408 1409 gc_timer->register_gc_end(); 1410 gc_tracer->report_gc_end(gc_timer->gc_end(), gc_timer->time_partitions()); 1411 } 1412 1413 return true; 1414 } 1415 1416 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) { 1417 // Currently, there is no facility in the do_full_collection(bool) API to notify 1418 // the caller that the collection did not succeed (e.g., because it was locked 1419 // out by the GC locker). So, right now, we'll ignore the return value. 1420 bool dummy = do_full_collection(true, /* explicit_gc */ 1421 clear_all_soft_refs); 1422 } 1423 1424 void G1CollectedHeap::resize_if_necessary_after_full_collection() { 1425 // Include bytes that will be pre-allocated to support collections, as "used". 1426 const size_t used_after_gc = used(); 1427 const size_t capacity_after_gc = capacity(); 1428 const size_t free_after_gc = capacity_after_gc - used_after_gc; 1429 1430 // This is enforced in arguments.cpp. 1431 assert(MinHeapFreeRatio <= MaxHeapFreeRatio, 1432 "otherwise the code below doesn't make sense"); 1433 1434 // We don't have floating point command-line arguments 1435 const double minimum_free_percentage = (double) MinHeapFreeRatio / 100.0; 1436 const double maximum_used_percentage = 1.0 - minimum_free_percentage; 1437 const double maximum_free_percentage = (double) MaxHeapFreeRatio / 100.0; 1438 const double minimum_used_percentage = 1.0 - maximum_free_percentage; 1439 1440 const size_t min_heap_size = collector_policy()->min_heap_byte_size(); 1441 const size_t max_heap_size = collector_policy()->max_heap_byte_size(); 1442 1443 // We have to be careful here as these two calculations can overflow 1444 // 32-bit size_t's. 1445 double used_after_gc_d = (double) used_after_gc; 1446 double minimum_desired_capacity_d = used_after_gc_d / maximum_used_percentage; 1447 double maximum_desired_capacity_d = used_after_gc_d / minimum_used_percentage; 1448 1449 // Let's make sure that they are both under the max heap size, which 1450 // by default will make them fit into a size_t. 1451 double desired_capacity_upper_bound = (double) max_heap_size; 1452 minimum_desired_capacity_d = MIN2(minimum_desired_capacity_d, 1453 desired_capacity_upper_bound); 1454 maximum_desired_capacity_d = MIN2(maximum_desired_capacity_d, 1455 desired_capacity_upper_bound); 1456 1457 // We can now safely turn them into size_t's. 1458 size_t minimum_desired_capacity = (size_t) minimum_desired_capacity_d; 1459 size_t maximum_desired_capacity = (size_t) maximum_desired_capacity_d; 1460 1461 // This assert only makes sense here, before we adjust them 1462 // with respect to the min and max heap size. 1463 assert(minimum_desired_capacity <= maximum_desired_capacity, 1464 "minimum_desired_capacity = " SIZE_FORMAT ", " 1465 "maximum_desired_capacity = " SIZE_FORMAT, 1466 minimum_desired_capacity, maximum_desired_capacity); 1467 1468 // Should not be greater than the heap max size. No need to adjust 1469 // it with respect to the heap min size as it's a lower bound (i.e., 1470 // we'll try to make the capacity larger than it, not smaller). 1471 minimum_desired_capacity = MIN2(minimum_desired_capacity, max_heap_size); 1472 // Should not be less than the heap min size. No need to adjust it 1473 // with respect to the heap max size as it's an upper bound (i.e., 1474 // we'll try to make the capacity smaller than it, not greater). 1475 maximum_desired_capacity = MAX2(maximum_desired_capacity, min_heap_size); 1476 1477 if (capacity_after_gc < minimum_desired_capacity) { 1478 // Don't expand unless it's significant 1479 size_t expand_bytes = minimum_desired_capacity - capacity_after_gc; 1480 1481 log_debug(gc, ergo, heap)("Attempt heap expansion (capacity lower than min desired capacity after Full GC). " 1482 "Capacity: " SIZE_FORMAT "B occupancy: " SIZE_FORMAT "B min_desired_capacity: " SIZE_FORMAT "B (" UINTX_FORMAT " %%)", 1483 capacity_after_gc, used_after_gc, minimum_desired_capacity, MinHeapFreeRatio); 1484 1485 expand(expand_bytes); 1486 1487 // No expansion, now see if we want to shrink 1488 } else if (capacity_after_gc > maximum_desired_capacity) { 1489 // Capacity too large, compute shrinking size 1490 size_t shrink_bytes = capacity_after_gc - maximum_desired_capacity; 1491 1492 log_debug(gc, ergo, heap)("Attempt heap shrinking (capacity higher than max desired capacity after Full GC). " 1493 "Capacity: " SIZE_FORMAT "B occupancy: " SIZE_FORMAT "B min_desired_capacity: " SIZE_FORMAT "B (" UINTX_FORMAT " %%)", 1494 capacity_after_gc, used_after_gc, minimum_desired_capacity, MinHeapFreeRatio); 1495 1496 shrink(shrink_bytes); 1497 } 1498 } 1499 1500 HeapWord* G1CollectedHeap::satisfy_failed_allocation_helper(size_t word_size, 1501 AllocationContext_t context, 1502 bool do_gc, 1503 bool clear_all_soft_refs, 1504 bool expect_null_mutator_alloc_region, 1505 bool* gc_succeeded) { 1506 *gc_succeeded = true; 1507 // Let's attempt the allocation first. 1508 HeapWord* result = 1509 attempt_allocation_at_safepoint(word_size, 1510 context, 1511 expect_null_mutator_alloc_region); 1512 if (result != NULL) { 1513 assert(*gc_succeeded, "sanity"); 1514 return result; 1515 } 1516 1517 // In a G1 heap, we're supposed to keep allocation from failing by 1518 // incremental pauses. Therefore, at least for now, we'll favor 1519 // expansion over collection. (This might change in the future if we can 1520 // do something smarter than full collection to satisfy a failed alloc.) 1521 result = expand_and_allocate(word_size, context); 1522 if (result != NULL) { 1523 assert(*gc_succeeded, "sanity"); 1524 return result; 1525 } 1526 1527 if (do_gc) { 1528 // Expansion didn't work, we'll try to do a Full GC. 1529 *gc_succeeded = do_full_collection(false, /* explicit_gc */ 1530 clear_all_soft_refs); 1531 } 1532 1533 return NULL; 1534 } 1535 1536 HeapWord* G1CollectedHeap::satisfy_failed_allocation(size_t word_size, 1537 AllocationContext_t context, 1538 bool* succeeded) { 1539 assert_at_safepoint(true /* should_be_vm_thread */); 1540 1541 // Attempts to allocate followed by Full GC. 1542 HeapWord* result = 1543 satisfy_failed_allocation_helper(word_size, 1544 context, 1545 true, /* do_gc */ 1546 false, /* clear_all_soft_refs */ 1547 false, /* expect_null_mutator_alloc_region */ 1548 succeeded); 1549 1550 if (result != NULL || !*succeeded) { 1551 return result; 1552 } 1553 1554 // Attempts to allocate followed by Full GC that will collect all soft references. 1555 result = satisfy_failed_allocation_helper(word_size, 1556 context, 1557 true, /* do_gc */ 1558 true, /* clear_all_soft_refs */ 1559 true, /* expect_null_mutator_alloc_region */ 1560 succeeded); 1561 1562 if (result != NULL || !*succeeded) { 1563 return result; 1564 } 1565 1566 // Attempts to allocate, no GC 1567 result = satisfy_failed_allocation_helper(word_size, 1568 context, 1569 false, /* do_gc */ 1570 false, /* clear_all_soft_refs */ 1571 true, /* expect_null_mutator_alloc_region */ 1572 succeeded); 1573 1574 if (result != NULL) { 1575 assert(*succeeded, "sanity"); 1576 return result; 1577 } 1578 1579 assert(!collector_policy()->should_clear_all_soft_refs(), 1580 "Flag should have been handled and cleared prior to this point"); 1581 1582 // What else? We might try synchronous finalization later. If the total 1583 // space available is large enough for the allocation, then a more 1584 // complete compaction phase than we've tried so far might be 1585 // appropriate. 1586 assert(*succeeded, "sanity"); 1587 return NULL; 1588 } 1589 1590 // Attempting to expand the heap sufficiently 1591 // to support an allocation of the given "word_size". If 1592 // successful, perform the allocation and return the address of the 1593 // allocated block, or else "NULL". 1594 1595 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size, AllocationContext_t context) { 1596 assert_at_safepoint(true /* should_be_vm_thread */); 1597 1598 _verifier->verify_region_sets_optional(); 1599 1600 size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes); 1601 log_debug(gc, ergo, heap)("Attempt heap expansion (allocation request failed). Allocation request: " SIZE_FORMAT "B", 1602 word_size * HeapWordSize); 1603 1604 1605 if (expand(expand_bytes)) { 1606 _hrm.verify_optional(); 1607 _verifier->verify_region_sets_optional(); 1608 return attempt_allocation_at_safepoint(word_size, 1609 context, 1610 false /* expect_null_mutator_alloc_region */); 1611 } 1612 return NULL; 1613 } 1614 1615 bool G1CollectedHeap::expand(size_t expand_bytes, double* expand_time_ms) { 1616 size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes); 1617 aligned_expand_bytes = align_size_up(aligned_expand_bytes, 1618 HeapRegion::GrainBytes); 1619 1620 log_debug(gc, ergo, heap)("Expand the heap. requested expansion amount:" SIZE_FORMAT "B expansion amount:" SIZE_FORMAT "B", 1621 expand_bytes, aligned_expand_bytes); 1622 1623 if (is_maximal_no_gc()) { 1624 log_debug(gc, ergo, heap)("Did not expand the heap (heap already fully expanded)"); 1625 return false; 1626 } 1627 1628 double expand_heap_start_time_sec = os::elapsedTime(); 1629 uint regions_to_expand = (uint)(aligned_expand_bytes / HeapRegion::GrainBytes); 1630 assert(regions_to_expand > 0, "Must expand by at least one region"); 1631 1632 uint expanded_by = _hrm.expand_by(regions_to_expand); 1633 if (expand_time_ms != NULL) { 1634 *expand_time_ms = (os::elapsedTime() - expand_heap_start_time_sec) * MILLIUNITS; 1635 } 1636 1637 if (expanded_by > 0) { 1638 size_t actual_expand_bytes = expanded_by * HeapRegion::GrainBytes; 1639 assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition"); 1640 g1_policy()->record_new_heap_size(num_regions()); 1641 } else { 1642 log_debug(gc, ergo, heap)("Did not expand the heap (heap expansion operation failed)"); 1643 1644 // The expansion of the virtual storage space was unsuccessful. 1645 // Let's see if it was because we ran out of swap. 1646 if (G1ExitOnExpansionFailure && 1647 _hrm.available() >= regions_to_expand) { 1648 // We had head room... 1649 vm_exit_out_of_memory(aligned_expand_bytes, OOM_MMAP_ERROR, "G1 heap expansion"); 1650 } 1651 } 1652 return regions_to_expand > 0; 1653 } 1654 1655 void G1CollectedHeap::shrink_helper(size_t shrink_bytes) { 1656 size_t aligned_shrink_bytes = 1657 ReservedSpace::page_align_size_down(shrink_bytes); 1658 aligned_shrink_bytes = align_size_down(aligned_shrink_bytes, 1659 HeapRegion::GrainBytes); 1660 uint num_regions_to_remove = (uint)(shrink_bytes / HeapRegion::GrainBytes); 1661 1662 uint num_regions_removed = _hrm.shrink_by(num_regions_to_remove); 1663 size_t shrunk_bytes = num_regions_removed * HeapRegion::GrainBytes; 1664 1665 1666 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", 1667 shrink_bytes, aligned_shrink_bytes, shrunk_bytes); 1668 if (num_regions_removed > 0) { 1669 g1_policy()->record_new_heap_size(num_regions()); 1670 } else { 1671 log_debug(gc, ergo, heap)("Did not expand the heap (heap shrinking operation failed)"); 1672 } 1673 } 1674 1675 void G1CollectedHeap::shrink(size_t shrink_bytes) { 1676 _verifier->verify_region_sets_optional(); 1677 1678 // We should only reach here at the end of a Full GC which means we 1679 // should not not be holding to any GC alloc regions. The method 1680 // below will make sure of that and do any remaining clean up. 1681 _allocator->abandon_gc_alloc_regions(); 1682 1683 // Instead of tearing down / rebuilding the free lists here, we 1684 // could instead use the remove_all_pending() method on free_list to 1685 // remove only the ones that we need to remove. 1686 tear_down_region_sets(true /* free_list_only */); 1687 shrink_helper(shrink_bytes); 1688 rebuild_region_sets(true /* free_list_only */); 1689 1690 _hrm.verify_optional(); 1691 _verifier->verify_region_sets_optional(); 1692 } 1693 1694 // Public methods. 1695 1696 G1CollectedHeap::G1CollectedHeap(G1CollectorPolicy* collector_policy) : 1697 CollectedHeap(), 1698 _collector_policy(collector_policy), 1699 _g1_policy(create_g1_policy()), 1700 _collection_set(this, _g1_policy), 1701 _dirty_card_queue_set(false), 1702 _is_alive_closure_cm(this), 1703 _is_alive_closure_stw(this), 1704 _ref_processor_cm(NULL), 1705 _ref_processor_stw(NULL), 1706 _bot(NULL), 1707 _cg1r(NULL), 1708 _g1mm(NULL), 1709 _refine_cte_cl(NULL), 1710 _preserved_marks_set(true /* in_c_heap */), 1711 _secondary_free_list("Secondary Free List", new SecondaryFreeRegionListMtSafeChecker()), 1712 _old_set("Old Set", false /* humongous */, new OldRegionSetMtSafeChecker()), 1713 _humongous_set("Master Humongous Set", true /* humongous */, new HumongousRegionSetMtSafeChecker()), 1714 _humongous_reclaim_candidates(), 1715 _has_humongous_reclaim_candidates(false), 1716 _archive_allocator(NULL), 1717 _free_regions_coming(false), 1718 _young_list(new YoungList(this)), 1719 _gc_time_stamp(0), 1720 _summary_bytes_used(0), 1721 _survivor_evac_stats("Young", YoungPLABSize, PLABWeight), 1722 _old_evac_stats("Old", OldPLABSize, PLABWeight), 1723 _expand_heap_after_alloc_failure(true), 1724 _old_marking_cycles_started(0), 1725 _old_marking_cycles_completed(0), 1726 _in_cset_fast_test(), 1727 _worker_cset_start_region(NULL), 1728 _worker_cset_start_region_time_stamp(NULL), 1729 _gc_timer_stw(new (ResourceObj::C_HEAP, mtGC) STWGCTimer()), 1730 _gc_tracer_stw(new (ResourceObj::C_HEAP, mtGC) G1NewTracer()) { 1731 1732 _workers = new WorkGang("GC Thread", ParallelGCThreads, 1733 /* are_GC_task_threads */true, 1734 /* are_ConcurrentGC_threads */false); 1735 _workers->initialize_workers(); 1736 _verifier = new G1HeapVerifier(this); 1737 1738 _allocator = G1Allocator::create_allocator(this); 1739 1740 _heap_sizing_policy = G1HeapSizingPolicy::create(this, _g1_policy->analytics()); 1741 1742 _humongous_object_threshold_in_words = humongous_threshold_for(HeapRegion::GrainWords); 1743 1744 // Override the default _filler_array_max_size so that no humongous filler 1745 // objects are created. 1746 _filler_array_max_size = _humongous_object_threshold_in_words; 1747 1748 uint n_queues = ParallelGCThreads; 1749 _task_queues = new RefToScanQueueSet(n_queues); 1750 1751 _worker_cset_start_region = NEW_C_HEAP_ARRAY(HeapRegion*, n_queues, mtGC); 1752 _worker_cset_start_region_time_stamp = NEW_C_HEAP_ARRAY(uint, n_queues, mtGC); 1753 _evacuation_failed_info_array = NEW_C_HEAP_ARRAY(EvacuationFailedInfo, n_queues, mtGC); 1754 1755 for (uint i = 0; i < n_queues; i++) { 1756 RefToScanQueue* q = new RefToScanQueue(); 1757 q->initialize(); 1758 _task_queues->register_queue(i, q); 1759 ::new (&_evacuation_failed_info_array[i]) EvacuationFailedInfo(); 1760 } 1761 clear_cset_start_regions(); 1762 1763 // Initialize the G1EvacuationFailureALot counters and flags. 1764 NOT_PRODUCT(reset_evacuation_should_fail();) 1765 1766 guarantee(_task_queues != NULL, "task_queues allocation failure."); 1767 } 1768 1769 G1RegionToSpaceMapper* G1CollectedHeap::create_aux_memory_mapper(const char* description, 1770 size_t size, 1771 size_t translation_factor) { 1772 size_t preferred_page_size = os::page_size_for_region_unaligned(size, 1); 1773 // Allocate a new reserved space, preferring to use large pages. 1774 ReservedSpace rs(size, preferred_page_size); 1775 G1RegionToSpaceMapper* result = 1776 G1RegionToSpaceMapper::create_mapper(rs, 1777 size, 1778 rs.alignment(), 1779 HeapRegion::GrainBytes, 1780 translation_factor, 1781 mtGC); 1782 1783 os::trace_page_sizes_for_requested_size(description, 1784 size, 1785 preferred_page_size, 1786 rs.alignment(), 1787 rs.base(), 1788 rs.size()); 1789 1790 return result; 1791 } 1792 1793 jint G1CollectedHeap::initialize() { 1794 CollectedHeap::pre_initialize(); 1795 os::enable_vtime(); 1796 1797 // Necessary to satisfy locking discipline assertions. 1798 1799 MutexLocker x(Heap_lock); 1800 1801 // While there are no constraints in the GC code that HeapWordSize 1802 // be any particular value, there are multiple other areas in the 1803 // system which believe this to be true (e.g. oop->object_size in some 1804 // cases incorrectly returns the size in wordSize units rather than 1805 // HeapWordSize). 1806 guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize"); 1807 1808 size_t init_byte_size = collector_policy()->initial_heap_byte_size(); 1809 size_t max_byte_size = collector_policy()->max_heap_byte_size(); 1810 size_t heap_alignment = collector_policy()->heap_alignment(); 1811 1812 // Ensure that the sizes are properly aligned. 1813 Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap"); 1814 Universe::check_alignment(max_byte_size, HeapRegion::GrainBytes, "g1 heap"); 1815 Universe::check_alignment(max_byte_size, heap_alignment, "g1 heap"); 1816 1817 _refine_cte_cl = new RefineCardTableEntryClosure(); 1818 1819 jint ecode = JNI_OK; 1820 _cg1r = ConcurrentG1Refine::create(this, _refine_cte_cl, &ecode); 1821 if (_cg1r == NULL) { 1822 return ecode; 1823 } 1824 1825 // Reserve the maximum. 1826 1827 // When compressed oops are enabled, the preferred heap base 1828 // is calculated by subtracting the requested size from the 1829 // 32Gb boundary and using the result as the base address for 1830 // heap reservation. If the requested size is not aligned to 1831 // HeapRegion::GrainBytes (i.e. the alignment that is passed 1832 // into the ReservedHeapSpace constructor) then the actual 1833 // base of the reserved heap may end up differing from the 1834 // address that was requested (i.e. the preferred heap base). 1835 // If this happens then we could end up using a non-optimal 1836 // compressed oops mode. 1837 1838 ReservedSpace heap_rs = Universe::reserve_heap(max_byte_size, 1839 heap_alignment); 1840 1841 initialize_reserved_region((HeapWord*)heap_rs.base(), (HeapWord*)(heap_rs.base() + heap_rs.size())); 1842 1843 // Create the barrier set for the entire reserved region. 1844 G1SATBCardTableLoggingModRefBS* bs 1845 = new G1SATBCardTableLoggingModRefBS(reserved_region()); 1846 bs->initialize(); 1847 assert(bs->is_a(BarrierSet::G1SATBCTLogging), "sanity"); 1848 set_barrier_set(bs); 1849 1850 // Also create a G1 rem set. 1851 _g1_rem_set = new G1RemSet(this, g1_barrier_set()); 1852 1853 // Carve out the G1 part of the heap. 1854 ReservedSpace g1_rs = heap_rs.first_part(max_byte_size); 1855 size_t page_size = UseLargePages ? os::large_page_size() : os::vm_page_size(); 1856 G1RegionToSpaceMapper* heap_storage = 1857 G1RegionToSpaceMapper::create_mapper(g1_rs, 1858 g1_rs.size(), 1859 page_size, 1860 HeapRegion::GrainBytes, 1861 1, 1862 mtJavaHeap); 1863 os::trace_page_sizes("Heap", 1864 collector_policy()->min_heap_byte_size(), 1865 max_byte_size, 1866 page_size, 1867 heap_rs.base(), 1868 heap_rs.size()); 1869 heap_storage->set_mapping_changed_listener(&_listener); 1870 1871 // Create storage for the BOT, card table, card counts table (hot card cache) and the bitmaps. 1872 G1RegionToSpaceMapper* bot_storage = 1873 create_aux_memory_mapper("Block Offset Table", 1874 G1BlockOffsetTable::compute_size(g1_rs.size() / HeapWordSize), 1875 G1BlockOffsetTable::heap_map_factor()); 1876 1877 ReservedSpace cardtable_rs(G1SATBCardTableLoggingModRefBS::compute_size(g1_rs.size() / HeapWordSize)); 1878 G1RegionToSpaceMapper* cardtable_storage = 1879 create_aux_memory_mapper("Card Table", 1880 G1SATBCardTableLoggingModRefBS::compute_size(g1_rs.size() / HeapWordSize), 1881 G1SATBCardTableLoggingModRefBS::heap_map_factor()); 1882 1883 G1RegionToSpaceMapper* card_counts_storage = 1884 create_aux_memory_mapper("Card Counts Table", 1885 G1CardCounts::compute_size(g1_rs.size() / HeapWordSize), 1886 G1CardCounts::heap_map_factor()); 1887 1888 size_t bitmap_size = G1CMBitMap::compute_size(g1_rs.size()); 1889 G1RegionToSpaceMapper* prev_bitmap_storage = 1890 create_aux_memory_mapper("Prev Bitmap", bitmap_size, G1CMBitMap::heap_map_factor()); 1891 G1RegionToSpaceMapper* next_bitmap_storage = 1892 create_aux_memory_mapper("Next Bitmap", bitmap_size, G1CMBitMap::heap_map_factor()); 1893 1894 _hrm.initialize(heap_storage, prev_bitmap_storage, next_bitmap_storage, bot_storage, cardtable_storage, card_counts_storage); 1895 g1_barrier_set()->initialize(cardtable_storage); 1896 // Do later initialization work for concurrent refinement. 1897 _cg1r->init(card_counts_storage); 1898 1899 // 6843694 - ensure that the maximum region index can fit 1900 // in the remembered set structures. 1901 const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1; 1902 guarantee((max_regions() - 1) <= max_region_idx, "too many regions"); 1903 1904 g1_rem_set()->initialize(max_capacity(), max_regions()); 1905 1906 size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1; 1907 guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized"); 1908 guarantee(HeapRegion::CardsPerRegion < max_cards_per_region, 1909 "too many cards per region"); 1910 1911 FreeRegionList::set_unrealistically_long_length(max_regions() + 1); 1912 1913 _bot = new G1BlockOffsetTable(reserved_region(), bot_storage); 1914 1915 { 1916 HeapWord* start = _hrm.reserved().start(); 1917 HeapWord* end = _hrm.reserved().end(); 1918 size_t granularity = HeapRegion::GrainBytes; 1919 1920 _in_cset_fast_test.initialize(start, end, granularity); 1921 _humongous_reclaim_candidates.initialize(start, end, granularity); 1922 } 1923 1924 // Create the G1ConcurrentMark data structure and thread. 1925 // (Must do this late, so that "max_regions" is defined.) 1926 _cm = new G1ConcurrentMark(this, prev_bitmap_storage, next_bitmap_storage); 1927 if (_cm == NULL || !_cm->completed_initialization()) { 1928 vm_shutdown_during_initialization("Could not create/initialize G1ConcurrentMark"); 1929 return JNI_ENOMEM; 1930 } 1931 _cmThread = _cm->cmThread(); 1932 1933 // Now expand into the initial heap size. 1934 if (!expand(init_byte_size)) { 1935 vm_shutdown_during_initialization("Failed to allocate initial heap."); 1936 return JNI_ENOMEM; 1937 } 1938 1939 // Perform any initialization actions delegated to the policy. 1940 g1_policy()->init(this, &_collection_set); 1941 1942 JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon, 1943 SATB_Q_FL_lock, 1944 G1SATBProcessCompletedThreshold, 1945 Shared_SATB_Q_lock); 1946 1947 JavaThread::dirty_card_queue_set().initialize(_refine_cte_cl, 1948 DirtyCardQ_CBL_mon, 1949 DirtyCardQ_FL_lock, 1950 (int)concurrent_g1_refine()->yellow_zone(), 1951 (int)concurrent_g1_refine()->red_zone(), 1952 Shared_DirtyCardQ_lock, 1953 NULL, // fl_owner 1954 true); // init_free_ids 1955 1956 dirty_card_queue_set().initialize(NULL, // Should never be called by the Java code 1957 DirtyCardQ_CBL_mon, 1958 DirtyCardQ_FL_lock, 1959 -1, // never trigger processing 1960 -1, // no limit on length 1961 Shared_DirtyCardQ_lock, 1962 &JavaThread::dirty_card_queue_set()); 1963 1964 // Here we allocate the dummy HeapRegion that is required by the 1965 // G1AllocRegion class. 1966 HeapRegion* dummy_region = _hrm.get_dummy_region(); 1967 1968 // We'll re-use the same region whether the alloc region will 1969 // require BOT updates or not and, if it doesn't, then a non-young 1970 // region will complain that it cannot support allocations without 1971 // BOT updates. So we'll tag the dummy region as eden to avoid that. 1972 dummy_region->set_eden(); 1973 // Make sure it's full. 1974 dummy_region->set_top(dummy_region->end()); 1975 G1AllocRegion::setup(this, dummy_region); 1976 1977 _allocator->init_mutator_alloc_region(); 1978 1979 // Do create of the monitoring and management support so that 1980 // values in the heap have been properly initialized. 1981 _g1mm = new G1MonitoringSupport(this); 1982 1983 G1StringDedup::initialize(); 1984 1985 _preserved_marks_set.init(ParallelGCThreads); 1986 1987 return JNI_OK; 1988 } 1989 1990 void G1CollectedHeap::stop() { 1991 // Stop all concurrent threads. We do this to make sure these threads 1992 // do not continue to execute and access resources (e.g. logging) 1993 // that are destroyed during shutdown. 1994 _cg1r->stop(); 1995 _cmThread->stop(); 1996 if (G1StringDedup::is_enabled()) { 1997 G1StringDedup::stop(); 1998 } 1999 } 2000 2001 size_t G1CollectedHeap::conservative_max_heap_alignment() { 2002 return HeapRegion::max_region_size(); 2003 } 2004 2005 void G1CollectedHeap::post_initialize() { 2006 ref_processing_init(); 2007 } 2008 2009 void G1CollectedHeap::ref_processing_init() { 2010 // Reference processing in G1 currently works as follows: 2011 // 2012 // * There are two reference processor instances. One is 2013 // used to record and process discovered references 2014 // during concurrent marking; the other is used to 2015 // record and process references during STW pauses 2016 // (both full and incremental). 2017 // * Both ref processors need to 'span' the entire heap as 2018 // the regions in the collection set may be dotted around. 2019 // 2020 // * For the concurrent marking ref processor: 2021 // * Reference discovery is enabled at initial marking. 2022 // * Reference discovery is disabled and the discovered 2023 // references processed etc during remarking. 2024 // * Reference discovery is MT (see below). 2025 // * Reference discovery requires a barrier (see below). 2026 // * Reference processing may or may not be MT 2027 // (depending on the value of ParallelRefProcEnabled 2028 // and ParallelGCThreads). 2029 // * A full GC disables reference discovery by the CM 2030 // ref processor and abandons any entries on it's 2031 // discovered lists. 2032 // 2033 // * For the STW processor: 2034 // * Non MT discovery is enabled at the start of a full GC. 2035 // * Processing and enqueueing during a full GC is non-MT. 2036 // * During a full GC, references are processed after marking. 2037 // 2038 // * Discovery (may or may not be MT) is enabled at the start 2039 // of an incremental evacuation pause. 2040 // * References are processed near the end of a STW evacuation pause. 2041 // * For both types of GC: 2042 // * Discovery is atomic - i.e. not concurrent. 2043 // * Reference discovery will not need a barrier. 2044 2045 MemRegion mr = reserved_region(); 2046 2047 // Concurrent Mark ref processor 2048 _ref_processor_cm = 2049 new ReferenceProcessor(mr, // span 2050 ParallelRefProcEnabled && (ParallelGCThreads > 1), 2051 // mt processing 2052 ParallelGCThreads, 2053 // degree of mt processing 2054 (ParallelGCThreads > 1) || (ConcGCThreads > 1), 2055 // mt discovery 2056 MAX2(ParallelGCThreads, ConcGCThreads), 2057 // degree of mt discovery 2058 false, 2059 // Reference discovery is not atomic 2060 &_is_alive_closure_cm); 2061 // is alive closure 2062 // (for efficiency/performance) 2063 2064 // STW ref processor 2065 _ref_processor_stw = 2066 new ReferenceProcessor(mr, // span 2067 ParallelRefProcEnabled && (ParallelGCThreads > 1), 2068 // mt processing 2069 ParallelGCThreads, 2070 // degree of mt processing 2071 (ParallelGCThreads > 1), 2072 // mt discovery 2073 ParallelGCThreads, 2074 // degree of mt discovery 2075 true, 2076 // Reference discovery is atomic 2077 &_is_alive_closure_stw); 2078 // is alive closure 2079 // (for efficiency/performance) 2080 } 2081 2082 CollectorPolicy* G1CollectedHeap::collector_policy() const { 2083 return _collector_policy; 2084 } 2085 2086 size_t G1CollectedHeap::capacity() const { 2087 return _hrm.length() * HeapRegion::GrainBytes; 2088 } 2089 2090 void G1CollectedHeap::reset_gc_time_stamps(HeapRegion* hr) { 2091 hr->reset_gc_time_stamp(); 2092 } 2093 2094 #ifndef PRODUCT 2095 2096 class CheckGCTimeStampsHRClosure : public HeapRegionClosure { 2097 private: 2098 unsigned _gc_time_stamp; 2099 bool _failures; 2100 2101 public: 2102 CheckGCTimeStampsHRClosure(unsigned gc_time_stamp) : 2103 _gc_time_stamp(gc_time_stamp), _failures(false) { } 2104 2105 virtual bool doHeapRegion(HeapRegion* hr) { 2106 unsigned region_gc_time_stamp = hr->get_gc_time_stamp(); 2107 if (_gc_time_stamp != region_gc_time_stamp) { 2108 log_error(gc, verify)("Region " HR_FORMAT " has GC time stamp = %d, expected %d", HR_FORMAT_PARAMS(hr), 2109 region_gc_time_stamp, _gc_time_stamp); 2110 _failures = true; 2111 } 2112 return false; 2113 } 2114 2115 bool failures() { return _failures; } 2116 }; 2117 2118 void G1CollectedHeap::check_gc_time_stamps() { 2119 CheckGCTimeStampsHRClosure cl(_gc_time_stamp); 2120 heap_region_iterate(&cl); 2121 guarantee(!cl.failures(), "all GC time stamps should have been reset"); 2122 } 2123 #endif // PRODUCT 2124 2125 void G1CollectedHeap::iterate_hcc_closure(CardTableEntryClosure* cl, uint worker_i) { 2126 _cg1r->hot_card_cache()->drain(cl, worker_i); 2127 } 2128 2129 void G1CollectedHeap::iterate_dirty_card_closure(CardTableEntryClosure* cl, uint worker_i) { 2130 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set(); 2131 size_t n_completed_buffers = 0; 2132 while (dcqs.apply_closure_to_completed_buffer(cl, worker_i, 0, true)) { 2133 n_completed_buffers++; 2134 } 2135 g1_policy()->phase_times()->record_thread_work_item(G1GCPhaseTimes::UpdateRS, worker_i, n_completed_buffers); 2136 dcqs.clear_n_completed_buffers(); 2137 assert(!dcqs.completed_buffers_exist_dirty(), "Completed buffers exist!"); 2138 } 2139 2140 // Computes the sum of the storage used by the various regions. 2141 size_t G1CollectedHeap::used() const { 2142 size_t result = _summary_bytes_used + _allocator->used_in_alloc_regions(); 2143 if (_archive_allocator != NULL) { 2144 result += _archive_allocator->used(); 2145 } 2146 return result; 2147 } 2148 2149 size_t G1CollectedHeap::used_unlocked() const { 2150 return _summary_bytes_used; 2151 } 2152 2153 class SumUsedClosure: public HeapRegionClosure { 2154 size_t _used; 2155 public: 2156 SumUsedClosure() : _used(0) {} 2157 bool doHeapRegion(HeapRegion* r) { 2158 _used += r->used(); 2159 return false; 2160 } 2161 size_t result() { return _used; } 2162 }; 2163 2164 size_t G1CollectedHeap::recalculate_used() const { 2165 double recalculate_used_start = os::elapsedTime(); 2166 2167 SumUsedClosure blk; 2168 heap_region_iterate(&blk); 2169 2170 g1_policy()->phase_times()->record_evac_fail_recalc_used_time((os::elapsedTime() - recalculate_used_start) * 1000.0); 2171 return blk.result(); 2172 } 2173 2174 bool G1CollectedHeap::is_user_requested_concurrent_full_gc(GCCause::Cause cause) { 2175 switch (cause) { 2176 case GCCause::_java_lang_system_gc: return ExplicitGCInvokesConcurrent; 2177 case GCCause::_dcmd_gc_run: return ExplicitGCInvokesConcurrent; 2178 case GCCause::_update_allocation_context_stats_inc: return true; 2179 case GCCause::_wb_conc_mark: return true; 2180 default : return false; 2181 } 2182 } 2183 2184 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) { 2185 switch (cause) { 2186 case GCCause::_gc_locker: return GCLockerInvokesConcurrent; 2187 case GCCause::_g1_humongous_allocation: return true; 2188 default: return is_user_requested_concurrent_full_gc(cause); 2189 } 2190 } 2191 2192 #ifndef PRODUCT 2193 void G1CollectedHeap::allocate_dummy_regions() { 2194 // Let's fill up most of the region 2195 size_t word_size = HeapRegion::GrainWords - 1024; 2196 // And as a result the region we'll allocate will be humongous. 2197 guarantee(is_humongous(word_size), "sanity"); 2198 2199 // _filler_array_max_size is set to humongous object threshold 2200 // but temporarily change it to use CollectedHeap::fill_with_object(). 2201 SizeTFlagSetting fs(_filler_array_max_size, word_size); 2202 2203 for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) { 2204 // Let's use the existing mechanism for the allocation 2205 HeapWord* dummy_obj = humongous_obj_allocate(word_size, 2206 AllocationContext::system()); 2207 if (dummy_obj != NULL) { 2208 MemRegion mr(dummy_obj, word_size); 2209 CollectedHeap::fill_with_object(mr); 2210 } else { 2211 // If we can't allocate once, we probably cannot allocate 2212 // again. Let's get out of the loop. 2213 break; 2214 } 2215 } 2216 } 2217 #endif // !PRODUCT 2218 2219 void G1CollectedHeap::increment_old_marking_cycles_started() { 2220 assert(_old_marking_cycles_started == _old_marking_cycles_completed || 2221 _old_marking_cycles_started == _old_marking_cycles_completed + 1, 2222 "Wrong marking cycle count (started: %d, completed: %d)", 2223 _old_marking_cycles_started, _old_marking_cycles_completed); 2224 2225 _old_marking_cycles_started++; 2226 } 2227 2228 void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent) { 2229 MonitorLockerEx x(FullGCCount_lock, Mutex::_no_safepoint_check_flag); 2230 2231 // We assume that if concurrent == true, then the caller is a 2232 // concurrent thread that was joined the Suspendible Thread 2233 // Set. If there's ever a cheap way to check this, we should add an 2234 // assert here. 2235 2236 // Given that this method is called at the end of a Full GC or of a 2237 // concurrent cycle, and those can be nested (i.e., a Full GC can 2238 // interrupt a concurrent cycle), the number of full collections 2239 // completed should be either one (in the case where there was no 2240 // nesting) or two (when a Full GC interrupted a concurrent cycle) 2241 // behind the number of full collections started. 2242 2243 // This is the case for the inner caller, i.e. a Full GC. 2244 assert(concurrent || 2245 (_old_marking_cycles_started == _old_marking_cycles_completed + 1) || 2246 (_old_marking_cycles_started == _old_marking_cycles_completed + 2), 2247 "for inner caller (Full GC): _old_marking_cycles_started = %u " 2248 "is inconsistent with _old_marking_cycles_completed = %u", 2249 _old_marking_cycles_started, _old_marking_cycles_completed); 2250 2251 // This is the case for the outer caller, i.e. the concurrent cycle. 2252 assert(!concurrent || 2253 (_old_marking_cycles_started == _old_marking_cycles_completed + 1), 2254 "for outer caller (concurrent cycle): " 2255 "_old_marking_cycles_started = %u " 2256 "is inconsistent with _old_marking_cycles_completed = %u", 2257 _old_marking_cycles_started, _old_marking_cycles_completed); 2258 2259 _old_marking_cycles_completed += 1; 2260 2261 // We need to clear the "in_progress" flag in the CM thread before 2262 // we wake up any waiters (especially when ExplicitInvokesConcurrent 2263 // is set) so that if a waiter requests another System.gc() it doesn't 2264 // incorrectly see that a marking cycle is still in progress. 2265 if (concurrent) { 2266 _cmThread->set_idle(); 2267 } 2268 2269 // This notify_all() will ensure that a thread that called 2270 // System.gc() with (with ExplicitGCInvokesConcurrent set or not) 2271 // and it's waiting for a full GC to finish will be woken up. It is 2272 // waiting in VM_G1IncCollectionPause::doit_epilogue(). 2273 FullGCCount_lock->notify_all(); 2274 } 2275 2276 void G1CollectedHeap::collect(GCCause::Cause cause) { 2277 assert_heap_not_locked(); 2278 2279 uint gc_count_before; 2280 uint old_marking_count_before; 2281 uint full_gc_count_before; 2282 bool retry_gc; 2283 2284 do { 2285 retry_gc = false; 2286 2287 { 2288 MutexLocker ml(Heap_lock); 2289 2290 // Read the GC count while holding the Heap_lock 2291 gc_count_before = total_collections(); 2292 full_gc_count_before = total_full_collections(); 2293 old_marking_count_before = _old_marking_cycles_started; 2294 } 2295 2296 if (should_do_concurrent_full_gc(cause)) { 2297 // Schedule an initial-mark evacuation pause that will start a 2298 // concurrent cycle. We're setting word_size to 0 which means that 2299 // we are not requesting a post-GC allocation. 2300 VM_G1IncCollectionPause op(gc_count_before, 2301 0, /* word_size */ 2302 true, /* should_initiate_conc_mark */ 2303 g1_policy()->max_pause_time_ms(), 2304 cause); 2305 op.set_allocation_context(AllocationContext::current()); 2306 2307 VMThread::execute(&op); 2308 if (!op.pause_succeeded()) { 2309 if (old_marking_count_before == _old_marking_cycles_started) { 2310 retry_gc = op.should_retry_gc(); 2311 } else { 2312 // A Full GC happened while we were trying to schedule the 2313 // initial-mark GC. No point in starting a new cycle given 2314 // that the whole heap was collected anyway. 2315 } 2316 2317 if (retry_gc) { 2318 if (GCLocker::is_active_and_needs_gc()) { 2319 GCLocker::stall_until_clear(); 2320 } 2321 } 2322 } 2323 } else { 2324 if (cause == GCCause::_gc_locker || cause == GCCause::_wb_young_gc 2325 DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) { 2326 2327 // Schedule a standard evacuation pause. We're setting word_size 2328 // to 0 which means that we are not requesting a post-GC allocation. 2329 VM_G1IncCollectionPause op(gc_count_before, 2330 0, /* word_size */ 2331 false, /* should_initiate_conc_mark */ 2332 g1_policy()->max_pause_time_ms(), 2333 cause); 2334 VMThread::execute(&op); 2335 } else { 2336 // Schedule a Full GC. 2337 VM_G1CollectFull op(gc_count_before, full_gc_count_before, cause); 2338 VMThread::execute(&op); 2339 } 2340 } 2341 } while (retry_gc); 2342 } 2343 2344 bool G1CollectedHeap::is_in(const void* p) const { 2345 if (_hrm.reserved().contains(p)) { 2346 // Given that we know that p is in the reserved space, 2347 // heap_region_containing() should successfully 2348 // return the containing region. 2349 HeapRegion* hr = heap_region_containing(p); 2350 return hr->is_in(p); 2351 } else { 2352 return false; 2353 } 2354 } 2355 2356 #ifdef ASSERT 2357 bool G1CollectedHeap::is_in_exact(const void* p) const { 2358 bool contains = reserved_region().contains(p); 2359 bool available = _hrm.is_available(addr_to_region((HeapWord*)p)); 2360 if (contains && available) { 2361 return true; 2362 } else { 2363 return false; 2364 } 2365 } 2366 #endif 2367 2368 bool G1CollectedHeap::obj_in_cs(oop obj) { 2369 HeapRegion* r = _hrm.addr_to_region((HeapWord*) obj); 2370 return r != NULL && r->in_collection_set(); 2371 } 2372 2373 // Iteration functions. 2374 2375 // Applies an ExtendedOopClosure onto all references of objects within a HeapRegion. 2376 2377 class IterateOopClosureRegionClosure: public HeapRegionClosure { 2378 ExtendedOopClosure* _cl; 2379 public: 2380 IterateOopClosureRegionClosure(ExtendedOopClosure* cl) : _cl(cl) {} 2381 bool doHeapRegion(HeapRegion* r) { 2382 if (!r->is_continues_humongous()) { 2383 r->oop_iterate(_cl); 2384 } 2385 return false; 2386 } 2387 }; 2388 2389 // Iterates an ObjectClosure over all objects within a HeapRegion. 2390 2391 class IterateObjectClosureRegionClosure: public HeapRegionClosure { 2392 ObjectClosure* _cl; 2393 public: 2394 IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {} 2395 bool doHeapRegion(HeapRegion* r) { 2396 if (!r->is_continues_humongous()) { 2397 r->object_iterate(_cl); 2398 } 2399 return false; 2400 } 2401 }; 2402 2403 void G1CollectedHeap::object_iterate(ObjectClosure* cl) { 2404 IterateObjectClosureRegionClosure blk(cl); 2405 heap_region_iterate(&blk); 2406 } 2407 2408 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const { 2409 _hrm.iterate(cl); 2410 } 2411 2412 void 2413 G1CollectedHeap::heap_region_par_iterate(HeapRegionClosure* cl, 2414 uint worker_id, 2415 HeapRegionClaimer *hrclaimer, 2416 bool concurrent) const { 2417 _hrm.par_iterate(cl, worker_id, hrclaimer, concurrent); 2418 } 2419 2420 // Clear the cached CSet starting regions and (more importantly) 2421 // the time stamps. Called when we reset the GC time stamp. 2422 void G1CollectedHeap::clear_cset_start_regions() { 2423 assert(_worker_cset_start_region != NULL, "sanity"); 2424 assert(_worker_cset_start_region_time_stamp != NULL, "sanity"); 2425 2426 for (uint i = 0; i < ParallelGCThreads; i++) { 2427 _worker_cset_start_region[i] = NULL; 2428 _worker_cset_start_region_time_stamp[i] = 0; 2429 } 2430 } 2431 2432 // Given the id of a worker, obtain or calculate a suitable 2433 // starting region for iterating over the current collection set. 2434 HeapRegion* G1CollectedHeap::start_cset_region_for_worker(uint worker_i) { 2435 assert(get_gc_time_stamp() > 0, "should have been updated by now"); 2436 2437 HeapRegion* result = NULL; 2438 unsigned gc_time_stamp = get_gc_time_stamp(); 2439 2440 if (_worker_cset_start_region_time_stamp[worker_i] == gc_time_stamp) { 2441 // Cached starting region for current worker was set 2442 // during the current pause - so it's valid. 2443 // Note: the cached starting heap region may be NULL 2444 // (when the collection set is empty). 2445 result = _worker_cset_start_region[worker_i]; 2446 assert(result == NULL || result->in_collection_set(), "sanity"); 2447 return result; 2448 } 2449 2450 // The cached entry was not valid so let's calculate 2451 // a suitable starting heap region for this worker. 2452 2453 // We want the parallel threads to start their collection 2454 // set iteration at different collection set regions to 2455 // avoid contention. 2456 // If we have: 2457 // n collection set regions 2458 // p threads 2459 // Then thread t will start at region floor ((t * n) / p) 2460 2461 result = collection_set()->head(); 2462 uint cs_size = collection_set()->region_length(); 2463 uint active_workers = workers()->active_workers(); 2464 2465 uint end_ind = (cs_size * worker_i) / active_workers; 2466 uint start_ind = 0; 2467 2468 if (worker_i > 0 && 2469 _worker_cset_start_region_time_stamp[worker_i - 1] == gc_time_stamp) { 2470 // Previous workers starting region is valid 2471 // so let's iterate from there 2472 start_ind = (cs_size * (worker_i - 1)) / active_workers; 2473 OrderAccess::loadload(); 2474 result = _worker_cset_start_region[worker_i - 1]; 2475 } 2476 2477 for (uint i = start_ind; i < end_ind; i++) { 2478 result = result->next_in_collection_set(); 2479 } 2480 2481 // Note: the calculated starting heap region may be NULL 2482 // (when the collection set is empty). 2483 assert(result == NULL || result->in_collection_set(), "sanity"); 2484 assert(_worker_cset_start_region_time_stamp[worker_i] != gc_time_stamp, 2485 "should be updated only once per pause"); 2486 _worker_cset_start_region[worker_i] = result; 2487 OrderAccess::storestore(); 2488 _worker_cset_start_region_time_stamp[worker_i] = gc_time_stamp; 2489 return result; 2490 } 2491 2492 void G1CollectedHeap::collection_set_iterate(HeapRegionClosure* cl) { 2493 HeapRegion* r = collection_set()->head(); 2494 while (r != NULL) { 2495 HeapRegion* next = r->next_in_collection_set(); 2496 if (cl->doHeapRegion(r)) { 2497 cl->incomplete(); 2498 return; 2499 } 2500 r = next; 2501 } 2502 } 2503 2504 void G1CollectedHeap::collection_set_iterate_from(HeapRegion* r, 2505 HeapRegionClosure *cl) { 2506 if (r == NULL) { 2507 // The CSet is empty so there's nothing to do. 2508 return; 2509 } 2510 2511 assert(r->in_collection_set(), 2512 "Start region must be a member of the collection set."); 2513 HeapRegion* cur = r; 2514 while (cur != NULL) { 2515 HeapRegion* next = cur->next_in_collection_set(); 2516 if (cl->doHeapRegion(cur) && false) { 2517 cl->incomplete(); 2518 return; 2519 } 2520 cur = next; 2521 } 2522 cur = collection_set()->head(); 2523 while (cur != r) { 2524 HeapRegion* next = cur->next_in_collection_set(); 2525 if (cl->doHeapRegion(cur) && false) { 2526 cl->incomplete(); 2527 return; 2528 } 2529 cur = next; 2530 } 2531 } 2532 2533 HeapRegion* G1CollectedHeap::next_compaction_region(const HeapRegion* from) const { 2534 HeapRegion* result = _hrm.next_region_in_heap(from); 2535 while (result != NULL && result->is_pinned()) { 2536 result = _hrm.next_region_in_heap(result); 2537 } 2538 return result; 2539 } 2540 2541 HeapWord* G1CollectedHeap::block_start(const void* addr) const { 2542 HeapRegion* hr = heap_region_containing(addr); 2543 return hr->block_start(addr); 2544 } 2545 2546 size_t G1CollectedHeap::block_size(const HeapWord* addr) const { 2547 HeapRegion* hr = heap_region_containing(addr); 2548 return hr->block_size(addr); 2549 } 2550 2551 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const { 2552 HeapRegion* hr = heap_region_containing(addr); 2553 return hr->block_is_obj(addr); 2554 } 2555 2556 bool G1CollectedHeap::supports_tlab_allocation() const { 2557 return true; 2558 } 2559 2560 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const { 2561 return (_g1_policy->young_list_target_length() - young_list()->survivor_length()) * HeapRegion::GrainBytes; 2562 } 2563 2564 size_t G1CollectedHeap::tlab_used(Thread* ignored) const { 2565 return young_list()->eden_used_bytes(); 2566 } 2567 2568 // For G1 TLABs should not contain humongous objects, so the maximum TLAB size 2569 // must be equal to the humongous object limit. 2570 size_t G1CollectedHeap::max_tlab_size() const { 2571 return align_size_down(_humongous_object_threshold_in_words, MinObjAlignment); 2572 } 2573 2574 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const { 2575 AllocationContext_t context = AllocationContext::current(); 2576 return _allocator->unsafe_max_tlab_alloc(context); 2577 } 2578 2579 size_t G1CollectedHeap::max_capacity() const { 2580 return _hrm.reserved().byte_size(); 2581 } 2582 2583 jlong G1CollectedHeap::millis_since_last_gc() { 2584 // assert(false, "NYI"); 2585 return 0; 2586 } 2587 2588 void G1CollectedHeap::prepare_for_verify() { 2589 _verifier->prepare_for_verify(); 2590 } 2591 2592 void G1CollectedHeap::verify(VerifyOption vo) { 2593 _verifier->verify(vo); 2594 } 2595 2596 class PrintRegionClosure: public HeapRegionClosure { 2597 outputStream* _st; 2598 public: 2599 PrintRegionClosure(outputStream* st) : _st(st) {} 2600 bool doHeapRegion(HeapRegion* r) { 2601 r->print_on(_st); 2602 return false; 2603 } 2604 }; 2605 2606 bool G1CollectedHeap::is_obj_dead_cond(const oop obj, 2607 const HeapRegion* hr, 2608 const VerifyOption vo) const { 2609 switch (vo) { 2610 case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj, hr); 2611 case VerifyOption_G1UseNextMarking: return is_obj_ill(obj, hr); 2612 case VerifyOption_G1UseMarkWord: return !obj->is_gc_marked() && !hr->is_archive(); 2613 default: ShouldNotReachHere(); 2614 } 2615 return false; // keep some compilers happy 2616 } 2617 2618 bool G1CollectedHeap::is_obj_dead_cond(const oop obj, 2619 const VerifyOption vo) const { 2620 switch (vo) { 2621 case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj); 2622 case VerifyOption_G1UseNextMarking: return is_obj_ill(obj); 2623 case VerifyOption_G1UseMarkWord: { 2624 HeapRegion* hr = _hrm.addr_to_region((HeapWord*)obj); 2625 return !obj->is_gc_marked() && !hr->is_archive(); 2626 } 2627 default: ShouldNotReachHere(); 2628 } 2629 return false; // keep some compilers happy 2630 } 2631 2632 void G1CollectedHeap::print_heap_regions() const { 2633 Log(gc, heap, region) log; 2634 if (log.is_trace()) { 2635 ResourceMark rm; 2636 print_regions_on(log.trace_stream()); 2637 } 2638 } 2639 2640 void G1CollectedHeap::print_on(outputStream* st) const { 2641 st->print(" %-20s", "garbage-first heap"); 2642 st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K", 2643 capacity()/K, used_unlocked()/K); 2644 st->print(" [" PTR_FORMAT ", " PTR_FORMAT ", " PTR_FORMAT ")", 2645 p2i(_hrm.reserved().start()), 2646 p2i(_hrm.reserved().start() + _hrm.length() + HeapRegion::GrainWords), 2647 p2i(_hrm.reserved().end())); 2648 st->cr(); 2649 st->print(" region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K); 2650 uint young_regions = _young_list->length(); 2651 st->print("%u young (" SIZE_FORMAT "K), ", young_regions, 2652 (size_t) young_regions * HeapRegion::GrainBytes / K); 2653 uint survivor_regions = _young_list->survivor_length(); 2654 st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions, 2655 (size_t) survivor_regions * HeapRegion::GrainBytes / K); 2656 st->cr(); 2657 MetaspaceAux::print_on(st); 2658 } 2659 2660 void G1CollectedHeap::print_regions_on(outputStream* st) const { 2661 st->print_cr("Heap Regions: E=young(eden), S=young(survivor), O=old, " 2662 "HS=humongous(starts), HC=humongous(continues), " 2663 "CS=collection set, F=free, A=archive, TS=gc time stamp, " 2664 "AC=allocation context, " 2665 "TAMS=top-at-mark-start (previous, next)"); 2666 PrintRegionClosure blk(st); 2667 heap_region_iterate(&blk); 2668 } 2669 2670 void G1CollectedHeap::print_extended_on(outputStream* st) const { 2671 print_on(st); 2672 2673 // Print the per-region information. 2674 print_regions_on(st); 2675 } 2676 2677 void G1CollectedHeap::print_on_error(outputStream* st) const { 2678 this->CollectedHeap::print_on_error(st); 2679 2680 if (_cm != NULL) { 2681 st->cr(); 2682 _cm->print_on_error(st); 2683 } 2684 } 2685 2686 void G1CollectedHeap::print_gc_threads_on(outputStream* st) const { 2687 workers()->print_worker_threads_on(st); 2688 _cmThread->print_on(st); 2689 st->cr(); 2690 _cm->print_worker_threads_on(st); 2691 _cg1r->print_worker_threads_on(st); // also prints the sample thread 2692 if (G1StringDedup::is_enabled()) { 2693 G1StringDedup::print_worker_threads_on(st); 2694 } 2695 } 2696 2697 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const { 2698 workers()->threads_do(tc); 2699 tc->do_thread(_cmThread); 2700 _cm->threads_do(tc); 2701 _cg1r->threads_do(tc); // also iterates over the sample thread 2702 if (G1StringDedup::is_enabled()) { 2703 G1StringDedup::threads_do(tc); 2704 } 2705 } 2706 2707 void G1CollectedHeap::print_tracing_info() const { 2708 g1_rem_set()->print_summary_info(); 2709 concurrent_mark()->print_summary_info(); 2710 g1_policy()->print_yg_surv_rate_info(); 2711 } 2712 2713 #ifndef PRODUCT 2714 // Helpful for debugging RSet issues. 2715 2716 class PrintRSetsClosure : public HeapRegionClosure { 2717 private: 2718 const char* _msg; 2719 size_t _occupied_sum; 2720 2721 public: 2722 bool doHeapRegion(HeapRegion* r) { 2723 HeapRegionRemSet* hrrs = r->rem_set(); 2724 size_t occupied = hrrs->occupied(); 2725 _occupied_sum += occupied; 2726 2727 tty->print_cr("Printing RSet for region " HR_FORMAT, HR_FORMAT_PARAMS(r)); 2728 if (occupied == 0) { 2729 tty->print_cr(" RSet is empty"); 2730 } else { 2731 hrrs->print(); 2732 } 2733 tty->print_cr("----------"); 2734 return false; 2735 } 2736 2737 PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) { 2738 tty->cr(); 2739 tty->print_cr("========================================"); 2740 tty->print_cr("%s", msg); 2741 tty->cr(); 2742 } 2743 2744 ~PrintRSetsClosure() { 2745 tty->print_cr("Occupied Sum: " SIZE_FORMAT, _occupied_sum); 2746 tty->print_cr("========================================"); 2747 tty->cr(); 2748 } 2749 }; 2750 2751 void G1CollectedHeap::print_cset_rsets() { 2752 PrintRSetsClosure cl("Printing CSet RSets"); 2753 collection_set_iterate(&cl); 2754 } 2755 2756 void G1CollectedHeap::print_all_rsets() { 2757 PrintRSetsClosure cl("Printing All RSets");; 2758 heap_region_iterate(&cl); 2759 } 2760 #endif // PRODUCT 2761 2762 G1HeapSummary G1CollectedHeap::create_g1_heap_summary() { 2763 YoungList* young_list = heap()->young_list(); 2764 2765 size_t eden_used_bytes = young_list->eden_used_bytes(); 2766 size_t survivor_used_bytes = young_list->survivor_used_bytes(); 2767 size_t heap_used = Heap_lock->owned_by_self() ? used() : used_unlocked(); 2768 2769 size_t eden_capacity_bytes = 2770 (g1_policy()->young_list_target_length() * HeapRegion::GrainBytes) - survivor_used_bytes; 2771 2772 VirtualSpaceSummary heap_summary = create_heap_space_summary(); 2773 return G1HeapSummary(heap_summary, heap_used, eden_used_bytes, 2774 eden_capacity_bytes, survivor_used_bytes, num_regions()); 2775 } 2776 2777 G1EvacSummary G1CollectedHeap::create_g1_evac_summary(G1EvacStats* stats) { 2778 return G1EvacSummary(stats->allocated(), stats->wasted(), stats->undo_wasted(), 2779 stats->unused(), stats->used(), stats->region_end_waste(), 2780 stats->regions_filled(), stats->direct_allocated(), 2781 stats->failure_used(), stats->failure_waste()); 2782 } 2783 2784 void G1CollectedHeap::trace_heap(GCWhen::Type when, const GCTracer* gc_tracer) { 2785 const G1HeapSummary& heap_summary = create_g1_heap_summary(); 2786 gc_tracer->report_gc_heap_summary(when, heap_summary); 2787 2788 const MetaspaceSummary& metaspace_summary = create_metaspace_summary(); 2789 gc_tracer->report_metaspace_summary(when, metaspace_summary); 2790 } 2791 2792 G1CollectedHeap* G1CollectedHeap::heap() { 2793 CollectedHeap* heap = Universe::heap(); 2794 assert(heap != NULL, "Uninitialized access to G1CollectedHeap::heap()"); 2795 assert(heap->kind() == CollectedHeap::G1CollectedHeap, "Not a G1CollectedHeap"); 2796 return (G1CollectedHeap*)heap; 2797 } 2798 2799 void G1CollectedHeap::gc_prologue(bool full /* Ignored */) { 2800 // always_do_update_barrier = false; 2801 assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer"); 2802 // Fill TLAB's and such 2803 accumulate_statistics_all_tlabs(); 2804 ensure_parsability(true); 2805 2806 g1_rem_set()->print_periodic_summary_info("Before GC RS summary", total_collections()); 2807 } 2808 2809 void G1CollectedHeap::gc_epilogue(bool full) { 2810 // we are at the end of the GC. Total collections has already been increased. 2811 g1_rem_set()->print_periodic_summary_info("After GC RS summary", total_collections() - 1); 2812 2813 // FIXME: what is this about? 2814 // I'm ignoring the "fill_newgen()" call if "alloc_event_enabled" 2815 // is set. 2816 #if defined(COMPILER2) || INCLUDE_JVMCI 2817 assert(DerivedPointerTable::is_empty(), "derived pointer present"); 2818 #endif 2819 // always_do_update_barrier = true; 2820 2821 resize_all_tlabs(); 2822 allocation_context_stats().update(full); 2823 2824 // We have just completed a GC. Update the soft reference 2825 // policy with the new heap occupancy 2826 Universe::update_heap_info_at_gc(); 2827 } 2828 2829 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size, 2830 uint gc_count_before, 2831 bool* succeeded, 2832 GCCause::Cause gc_cause) { 2833 assert_heap_not_locked_and_not_at_safepoint(); 2834 VM_G1IncCollectionPause op(gc_count_before, 2835 word_size, 2836 false, /* should_initiate_conc_mark */ 2837 g1_policy()->max_pause_time_ms(), 2838 gc_cause); 2839 2840 op.set_allocation_context(AllocationContext::current()); 2841 VMThread::execute(&op); 2842 2843 HeapWord* result = op.result(); 2844 bool ret_succeeded = op.prologue_succeeded() && op.pause_succeeded(); 2845 assert(result == NULL || ret_succeeded, 2846 "the result should be NULL if the VM did not succeed"); 2847 *succeeded = ret_succeeded; 2848 2849 assert_heap_not_locked(); 2850 return result; 2851 } 2852 2853 void 2854 G1CollectedHeap::doConcurrentMark() { 2855 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag); 2856 if (!_cmThread->in_progress()) { 2857 _cmThread->set_started(); 2858 CGC_lock->notify(); 2859 } 2860 } 2861 2862 size_t G1CollectedHeap::pending_card_num() { 2863 size_t extra_cards = 0; 2864 JavaThread *curr = Threads::first(); 2865 while (curr != NULL) { 2866 DirtyCardQueue& dcq = curr->dirty_card_queue(); 2867 extra_cards += dcq.size(); 2868 curr = curr->next(); 2869 } 2870 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set(); 2871 size_t buffer_size = dcqs.buffer_size(); 2872 size_t buffer_num = dcqs.completed_buffers_num(); 2873 2874 // PtrQueueSet::buffer_size() and PtrQueue:size() return sizes 2875 // in bytes - not the number of 'entries'. We need to convert 2876 // into a number of cards. 2877 return (buffer_size * buffer_num + extra_cards) / oopSize; 2878 } 2879 2880 class RegisterHumongousWithInCSetFastTestClosure : public HeapRegionClosure { 2881 private: 2882 size_t _total_humongous; 2883 size_t _candidate_humongous; 2884 2885 DirtyCardQueue _dcq; 2886 2887 // We don't nominate objects with many remembered set entries, on 2888 // the assumption that such objects are likely still live. 2889 bool is_remset_small(HeapRegion* region) const { 2890 HeapRegionRemSet* const rset = region->rem_set(); 2891 return G1EagerReclaimHumongousObjectsWithStaleRefs 2892 ? rset->occupancy_less_or_equal_than(G1RSetSparseRegionEntries) 2893 : rset->is_empty(); 2894 } 2895 2896 bool humongous_region_is_candidate(G1CollectedHeap* heap, HeapRegion* region) const { 2897 assert(region->is_starts_humongous(), "Must start a humongous object"); 2898 2899 oop obj = oop(region->bottom()); 2900 2901 // Dead objects cannot be eager reclaim candidates. Due to class 2902 // unloading it is unsafe to query their classes so we return early. 2903 if (heap->is_obj_dead(obj, region)) { 2904 return false; 2905 } 2906 2907 // Candidate selection must satisfy the following constraints 2908 // while concurrent marking is in progress: 2909 // 2910 // * In order to maintain SATB invariants, an object must not be 2911 // reclaimed if it was allocated before the start of marking and 2912 // has not had its references scanned. Such an object must have 2913 // its references (including type metadata) scanned to ensure no 2914 // live objects are missed by the marking process. Objects 2915 // allocated after the start of concurrent marking don't need to 2916 // be scanned. 2917 // 2918 // * An object must not be reclaimed if it is on the concurrent 2919 // mark stack. Objects allocated after the start of concurrent 2920 // marking are never pushed on the mark stack. 2921 // 2922 // Nominating only objects allocated after the start of concurrent 2923 // marking is sufficient to meet both constraints. This may miss 2924 // some objects that satisfy the constraints, but the marking data 2925 // structures don't support efficiently performing the needed 2926 // additional tests or scrubbing of the mark stack. 2927 // 2928 // However, we presently only nominate is_typeArray() objects. 2929 // A humongous object containing references induces remembered 2930 // set entries on other regions. In order to reclaim such an 2931 // object, those remembered sets would need to be cleaned up. 2932 // 2933 // We also treat is_typeArray() objects specially, allowing them 2934 // to be reclaimed even if allocated before the start of 2935 // concurrent mark. For this we rely on mark stack insertion to 2936 // exclude is_typeArray() objects, preventing reclaiming an object 2937 // that is in the mark stack. We also rely on the metadata for 2938 // such objects to be built-in and so ensured to be kept live. 2939 // Frequent allocation and drop of large binary blobs is an 2940 // important use case for eager reclaim, and this special handling 2941 // may reduce needed headroom. 2942 2943 return obj->is_typeArray() && is_remset_small(region); 2944 } 2945 2946 public: 2947 RegisterHumongousWithInCSetFastTestClosure() 2948 : _total_humongous(0), 2949 _candidate_humongous(0), 2950 _dcq(&JavaThread::dirty_card_queue_set()) { 2951 } 2952 2953 virtual bool doHeapRegion(HeapRegion* r) { 2954 if (!r->is_starts_humongous()) { 2955 return false; 2956 } 2957 G1CollectedHeap* g1h = G1CollectedHeap::heap(); 2958 2959 bool is_candidate = humongous_region_is_candidate(g1h, r); 2960 uint rindex = r->hrm_index(); 2961 g1h->set_humongous_reclaim_candidate(rindex, is_candidate); 2962 if (is_candidate) { 2963 _candidate_humongous++; 2964 g1h->register_humongous_region_with_cset(rindex); 2965 // Is_candidate already filters out humongous object with large remembered sets. 2966 // If we have a humongous object with a few remembered sets, we simply flush these 2967 // remembered set entries into the DCQS. That will result in automatic 2968 // re-evaluation of their remembered set entries during the following evacuation 2969 // phase. 2970 if (!r->rem_set()->is_empty()) { 2971 guarantee(r->rem_set()->occupancy_less_or_equal_than(G1RSetSparseRegionEntries), 2972 "Found a not-small remembered set here. This is inconsistent with previous assumptions."); 2973 G1SATBCardTableLoggingModRefBS* bs = g1h->g1_barrier_set(); 2974 HeapRegionRemSetIterator hrrs(r->rem_set()); 2975 size_t card_index; 2976 while (hrrs.has_next(card_index)) { 2977 jbyte* card_ptr = (jbyte*)bs->byte_for_index(card_index); 2978 // The remembered set might contain references to already freed 2979 // regions. Filter out such entries to avoid failing card table 2980 // verification. 2981 if (g1h->is_in_closed_subset(bs->addr_for(card_ptr))) { 2982 if (*card_ptr != CardTableModRefBS::dirty_card_val()) { 2983 *card_ptr = CardTableModRefBS::dirty_card_val(); 2984 _dcq.enqueue(card_ptr); 2985 } 2986 } 2987 } 2988 assert(hrrs.n_yielded() == r->rem_set()->occupied(), 2989 "Remembered set hash maps out of sync, cur: " SIZE_FORMAT " entries, next: " SIZE_FORMAT " entries", 2990 hrrs.n_yielded(), r->rem_set()->occupied()); 2991 r->rem_set()->clear_locked(); 2992 } 2993 assert(r->rem_set()->is_empty(), "At this point any humongous candidate remembered set must be empty."); 2994 } 2995 _total_humongous++; 2996 2997 return false; 2998 } 2999 3000 size_t total_humongous() const { return _total_humongous; } 3001 size_t candidate_humongous() const { return _candidate_humongous; } 3002 3003 void flush_rem_set_entries() { _dcq.flush(); } 3004 }; 3005 3006 void G1CollectedHeap::register_humongous_regions_with_cset() { 3007 if (!G1EagerReclaimHumongousObjects) { 3008 g1_policy()->phase_times()->record_fast_reclaim_humongous_stats(0.0, 0, 0); 3009 return; 3010 } 3011 double time = os::elapsed_counter(); 3012 3013 // Collect reclaim candidate information and register candidates with cset. 3014 RegisterHumongousWithInCSetFastTestClosure cl; 3015 heap_region_iterate(&cl); 3016 3017 time = ((double)(os::elapsed_counter() - time) / os::elapsed_frequency()) * 1000.0; 3018 g1_policy()->phase_times()->record_fast_reclaim_humongous_stats(time, 3019 cl.total_humongous(), 3020 cl.candidate_humongous()); 3021 _has_humongous_reclaim_candidates = cl.candidate_humongous() > 0; 3022 3023 // Finally flush all remembered set entries to re-check into the global DCQS. 3024 cl.flush_rem_set_entries(); 3025 } 3026 3027 class VerifyRegionRemSetClosure : public HeapRegionClosure { 3028 public: 3029 bool doHeapRegion(HeapRegion* hr) { 3030 if (!hr->is_archive() && !hr->is_continues_humongous()) { 3031 hr->verify_rem_set(); 3032 } 3033 return false; 3034 } 3035 }; 3036 3037 uint G1CollectedHeap::num_task_queues() const { 3038 return _task_queues->size(); 3039 } 3040 3041 #if TASKQUEUE_STATS 3042 void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) { 3043 st->print_raw_cr("GC Task Stats"); 3044 st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr(); 3045 st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr(); 3046 } 3047 3048 void G1CollectedHeap::print_taskqueue_stats() const { 3049 if (!log_is_enabled(Trace, gc, task, stats)) { 3050 return; 3051 } 3052 Log(gc, task, stats) log; 3053 ResourceMark rm; 3054 outputStream* st = log.trace_stream(); 3055 3056 print_taskqueue_stats_hdr(st); 3057 3058 TaskQueueStats totals; 3059 const uint n = num_task_queues(); 3060 for (uint i = 0; i < n; ++i) { 3061 st->print("%3u ", i); task_queue(i)->stats.print(st); st->cr(); 3062 totals += task_queue(i)->stats; 3063 } 3064 st->print_raw("tot "); totals.print(st); st->cr(); 3065 3066 DEBUG_ONLY(totals.verify()); 3067 } 3068 3069 void G1CollectedHeap::reset_taskqueue_stats() { 3070 const uint n = num_task_queues(); 3071 for (uint i = 0; i < n; ++i) { 3072 task_queue(i)->stats.reset(); 3073 } 3074 } 3075 #endif // TASKQUEUE_STATS 3076 3077 void G1CollectedHeap::wait_for_root_region_scanning() { 3078 double scan_wait_start = os::elapsedTime(); 3079 // We have to wait until the CM threads finish scanning the 3080 // root regions as it's the only way to ensure that all the 3081 // objects on them have been correctly scanned before we start 3082 // moving them during the GC. 3083 bool waited = _cm->root_regions()->wait_until_scan_finished(); 3084 double wait_time_ms = 0.0; 3085 if (waited) { 3086 double scan_wait_end = os::elapsedTime(); 3087 wait_time_ms = (scan_wait_end - scan_wait_start) * 1000.0; 3088 } 3089 g1_policy()->phase_times()->record_root_region_scan_wait_time(wait_time_ms); 3090 } 3091 3092 bool 3093 G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) { 3094 assert_at_safepoint(true /* should_be_vm_thread */); 3095 guarantee(!is_gc_active(), "collection is not reentrant"); 3096 3097 if (GCLocker::check_active_before_gc()) { 3098 return false; 3099 } 3100 3101 _gc_timer_stw->register_gc_start(); 3102 3103 GCIdMark gc_id_mark; 3104 _gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start()); 3105 3106 SvcGCMarker sgcm(SvcGCMarker::MINOR); 3107 ResourceMark rm; 3108 3109 wait_for_root_region_scanning(); 3110 3111 print_heap_before_gc(); 3112 print_heap_regions(); 3113 trace_heap_before_gc(_gc_tracer_stw); 3114 3115 _verifier->verify_region_sets_optional(); 3116 _verifier->verify_dirty_young_regions(); 3117 3118 // We should not be doing initial mark unless the conc mark thread is running 3119 if (!_cmThread->should_terminate()) { 3120 // This call will decide whether this pause is an initial-mark 3121 // pause. If it is, during_initial_mark_pause() will return true 3122 // for the duration of this pause. 3123 g1_policy()->decide_on_conc_mark_initiation(); 3124 } 3125 3126 // We do not allow initial-mark to be piggy-backed on a mixed GC. 3127 assert(!collector_state()->during_initial_mark_pause() || 3128 collector_state()->gcs_are_young(), "sanity"); 3129 3130 // We also do not allow mixed GCs during marking. 3131 assert(!collector_state()->mark_in_progress() || collector_state()->gcs_are_young(), "sanity"); 3132 3133 // Record whether this pause is an initial mark. When the current 3134 // thread has completed its logging output and it's safe to signal 3135 // the CM thread, the flag's value in the policy has been reset. 3136 bool should_start_conc_mark = collector_state()->during_initial_mark_pause(); 3137 3138 // Inner scope for scope based logging, timers, and stats collection 3139 { 3140 EvacuationInfo evacuation_info; 3141 3142 if (collector_state()->during_initial_mark_pause()) { 3143 // We are about to start a marking cycle, so we increment the 3144 // full collection counter. 3145 increment_old_marking_cycles_started(); 3146 _cm->gc_tracer_cm()->set_gc_cause(gc_cause()); 3147 } 3148 3149 _gc_tracer_stw->report_yc_type(collector_state()->yc_type()); 3150 3151 GCTraceCPUTime tcpu; 3152 3153 FormatBuffer<> gc_string("Pause "); 3154 if (collector_state()->during_initial_mark_pause()) { 3155 gc_string.append("Initial Mark"); 3156 } else if (collector_state()->gcs_are_young()) { 3157 gc_string.append("Young"); 3158 } else { 3159 gc_string.append("Mixed"); 3160 } 3161 GCTraceTime(Info, gc) tm(gc_string, NULL, gc_cause(), true); 3162 3163 uint active_workers = AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(), 3164 workers()->active_workers(), 3165 Threads::number_of_non_daemon_threads()); 3166 workers()->set_active_workers(active_workers); 3167 3168 g1_policy()->note_gc_start(); 3169 3170 TraceCollectorStats tcs(g1mm()->incremental_collection_counters()); 3171 TraceMemoryManagerStats tms(false /* fullGC */, gc_cause()); 3172 3173 // If the secondary_free_list is not empty, append it to the 3174 // free_list. No need to wait for the cleanup operation to finish; 3175 // the region allocation code will check the secondary_free_list 3176 // and wait if necessary. If the G1StressConcRegionFreeing flag is 3177 // set, skip this step so that the region allocation code has to 3178 // get entries from the secondary_free_list. 3179 if (!G1StressConcRegionFreeing) { 3180 append_secondary_free_list_if_not_empty_with_lock(); 3181 } 3182 3183 G1HeapTransition heap_transition(this); 3184 size_t heap_used_bytes_before_gc = used(); 3185 3186 assert(check_young_list_well_formed(), "young list should be well formed"); 3187 3188 // Don't dynamically change the number of GC threads this early. A value of 3189 // 0 is used to indicate serial work. When parallel work is done, 3190 // it will be set. 3191 3192 { // Call to jvmpi::post_class_unload_events must occur outside of active GC 3193 IsGCActiveMark x; 3194 3195 gc_prologue(false); 3196 increment_total_collections(false /* full gc */); 3197 increment_gc_time_stamp(); 3198 3199 if (VerifyRememberedSets) { 3200 log_info(gc, verify)("[Verifying RemSets before GC]"); 3201 VerifyRegionRemSetClosure v_cl; 3202 heap_region_iterate(&v_cl); 3203 } 3204 3205 _verifier->verify_before_gc(); 3206 3207 _verifier->check_bitmaps("GC Start"); 3208 3209 #if defined(COMPILER2) || INCLUDE_JVMCI 3210 DerivedPointerTable::clear(); 3211 #endif 3212 3213 // Please see comment in g1CollectedHeap.hpp and 3214 // G1CollectedHeap::ref_processing_init() to see how 3215 // reference processing currently works in G1. 3216 3217 // Enable discovery in the STW reference processor 3218 if (g1_policy()->should_process_references()) { 3219 ref_processor_stw()->enable_discovery(); 3220 } else { 3221 ref_processor_stw()->disable_discovery(); 3222 } 3223 3224 { 3225 // We want to temporarily turn off discovery by the 3226 // CM ref processor, if necessary, and turn it back on 3227 // on again later if we do. Using a scoped 3228 // NoRefDiscovery object will do this. 3229 NoRefDiscovery no_cm_discovery(ref_processor_cm()); 3230 3231 // Forget the current alloc region (we might even choose it to be part 3232 // of the collection set!). 3233 _allocator->release_mutator_alloc_region(); 3234 3235 // This timing is only used by the ergonomics to handle our pause target. 3236 // It is unclear why this should not include the full pause. We will 3237 // investigate this in CR 7178365. 3238 // 3239 // Preserving the old comment here if that helps the investigation: 3240 // 3241 // The elapsed time induced by the start time below deliberately elides 3242 // the possible verification above. 3243 double sample_start_time_sec = os::elapsedTime(); 3244 3245 g1_policy()->record_collection_pause_start(sample_start_time_sec); 3246 3247 if (collector_state()->during_initial_mark_pause()) { 3248 concurrent_mark()->checkpointRootsInitialPre(); 3249 } 3250 3251 g1_policy()->finalize_collection_set(target_pause_time_ms); 3252 3253 evacuation_info.set_collectionset_regions(collection_set()->region_length()); 3254 3255 // Make sure the remembered sets are up to date. This needs to be 3256 // done before register_humongous_regions_with_cset(), because the 3257 // remembered sets are used there to choose eager reclaim candidates. 3258 // If the remembered sets are not up to date we might miss some 3259 // entries that need to be handled. 3260 g1_rem_set()->cleanupHRRS(); 3261 3262 register_humongous_regions_with_cset(); 3263 3264 assert(_verifier->check_cset_fast_test(), "Inconsistency in the InCSetState table."); 3265 3266 _cm->note_start_of_gc(); 3267 // We call this after finalize_cset() to 3268 // ensure that the CSet has been finalized. 3269 _cm->verify_no_cset_oops(); 3270 3271 if (_hr_printer.is_active()) { 3272 HeapRegion* hr = collection_set()->head(); 3273 while (hr != NULL) { 3274 _hr_printer.cset(hr); 3275 hr = hr->next_in_collection_set(); 3276 } 3277 } 3278 3279 // Initialize the GC alloc regions. 3280 _allocator->init_gc_alloc_regions(evacuation_info); 3281 3282 G1ParScanThreadStateSet per_thread_states(this, workers()->active_workers(), collection_set()->young_region_length()); 3283 pre_evacuate_collection_set(); 3284 3285 // Actually do the work... 3286 evacuate_collection_set(evacuation_info, &per_thread_states); 3287 3288 post_evacuate_collection_set(evacuation_info, &per_thread_states); 3289 3290 const size_t* surviving_young_words = per_thread_states.surviving_young_words(); 3291 free_collection_set(collection_set()->head(), evacuation_info, surviving_young_words); 3292 3293 eagerly_reclaim_humongous_regions(); 3294 3295 collection_set()->clear_head(); 3296 3297 record_obj_copy_mem_stats(); 3298 _survivor_evac_stats.adjust_desired_plab_sz(); 3299 _old_evac_stats.adjust_desired_plab_sz(); 3300 3301 // Start a new incremental collection set for the next pause. 3302 collection_set()->start_incremental_building(); 3303 3304 clear_cset_fast_test(); 3305 3306 // Don't check the whole heap at this point as the 3307 // GC alloc regions from this pause have been tagged 3308 // as survivors and moved on to the survivor list. 3309 // Survivor regions will fail the !is_young() check. 3310 assert(check_young_list_empty(false /* check_heap */), 3311 "young list should be empty"); 3312 3313 _young_list->reset_auxilary_lists(); 3314 3315 if (evacuation_failed()) { 3316 set_used(recalculate_used()); 3317 if (_archive_allocator != NULL) { 3318 _archive_allocator->clear_used(); 3319 } 3320 for (uint i = 0; i < ParallelGCThreads; i++) { 3321 if (_evacuation_failed_info_array[i].has_failed()) { 3322 _gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]); 3323 } 3324 } 3325 } else { 3326 // The "used" of the the collection set have already been subtracted 3327 // when they were freed. Add in the bytes evacuated. 3328 increase_used(g1_policy()->bytes_copied_during_gc()); 3329 } 3330 3331 if (collector_state()->during_initial_mark_pause()) { 3332 // We have to do this before we notify the CM threads that 3333 // they can start working to make sure that all the 3334 // appropriate initialization is done on the CM object. 3335 concurrent_mark()->checkpointRootsInitialPost(); 3336 collector_state()->set_mark_in_progress(true); 3337 // Note that we don't actually trigger the CM thread at 3338 // this point. We do that later when we're sure that 3339 // the current thread has completed its logging output. 3340 } 3341 3342 allocate_dummy_regions(); 3343 3344 _allocator->init_mutator_alloc_region(); 3345 3346 { 3347 size_t expand_bytes = _heap_sizing_policy->expansion_amount(); 3348 if (expand_bytes > 0) { 3349 size_t bytes_before = capacity(); 3350 // No need for an ergo logging here, 3351 // expansion_amount() does this when it returns a value > 0. 3352 double expand_ms; 3353 if (!expand(expand_bytes, &expand_ms)) { 3354 // We failed to expand the heap. Cannot do anything about it. 3355 } 3356 g1_policy()->phase_times()->record_expand_heap_time(expand_ms); 3357 } 3358 } 3359 3360 // We redo the verification but now wrt to the new CSet which 3361 // has just got initialized after the previous CSet was freed. 3362 _cm->verify_no_cset_oops(); 3363 _cm->note_end_of_gc(); 3364 3365 // This timing is only used by the ergonomics to handle our pause target. 3366 // It is unclear why this should not include the full pause. We will 3367 // investigate this in CR 7178365. 3368 double sample_end_time_sec = os::elapsedTime(); 3369 double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS; 3370 size_t total_cards_scanned = per_thread_states.total_cards_scanned(); 3371 g1_policy()->record_collection_pause_end(pause_time_ms, total_cards_scanned, heap_used_bytes_before_gc); 3372 3373 evacuation_info.set_collectionset_used_before(collection_set()->bytes_used_before()); 3374 evacuation_info.set_bytes_copied(g1_policy()->bytes_copied_during_gc()); 3375 3376 MemoryService::track_memory_usage(); 3377 3378 // In prepare_for_verify() below we'll need to scan the deferred 3379 // update buffers to bring the RSets up-to-date if 3380 // G1HRRSFlushLogBuffersOnVerify has been set. While scanning 3381 // the update buffers we'll probably need to scan cards on the 3382 // regions we just allocated to (i.e., the GC alloc 3383 // regions). However, during the last GC we called 3384 // set_saved_mark() on all the GC alloc regions, so card 3385 // scanning might skip the [saved_mark_word()...top()] area of 3386 // those regions (i.e., the area we allocated objects into 3387 // during the last GC). But it shouldn't. Given that 3388 // saved_mark_word() is conditional on whether the GC time stamp 3389 // on the region is current or not, by incrementing the GC time 3390 // stamp here we invalidate all the GC time stamps on all the 3391 // regions and saved_mark_word() will simply return top() for 3392 // all the regions. This is a nicer way of ensuring this rather 3393 // than iterating over the regions and fixing them. In fact, the 3394 // GC time stamp increment here also ensures that 3395 // saved_mark_word() will return top() between pauses, i.e., 3396 // during concurrent refinement. So we don't need the 3397 // is_gc_active() check to decided which top to use when 3398 // scanning cards (see CR 7039627). 3399 increment_gc_time_stamp(); 3400 3401 if (VerifyRememberedSets) { 3402 log_info(gc, verify)("[Verifying RemSets after GC]"); 3403 VerifyRegionRemSetClosure v_cl; 3404 heap_region_iterate(&v_cl); 3405 } 3406 3407 _verifier->verify_after_gc(); 3408 _verifier->check_bitmaps("GC End"); 3409 3410 assert(!ref_processor_stw()->discovery_enabled(), "Postcondition"); 3411 ref_processor_stw()->verify_no_references_recorded(); 3412 3413 // CM reference discovery will be re-enabled if necessary. 3414 } 3415 3416 #ifdef TRACESPINNING 3417 ParallelTaskTerminator::print_termination_counts(); 3418 #endif 3419 3420 gc_epilogue(false); 3421 } 3422 3423 // Print the remainder of the GC log output. 3424 if (evacuation_failed()) { 3425 log_info(gc)("To-space exhausted"); 3426 } 3427 3428 g1_policy()->print_phases(); 3429 heap_transition.print(); 3430 3431 // It is not yet to safe to tell the concurrent mark to 3432 // start as we have some optional output below. We don't want the 3433 // output from the concurrent mark thread interfering with this 3434 // logging output either. 3435 3436 _hrm.verify_optional(); 3437 _verifier->verify_region_sets_optional(); 3438 3439 TASKQUEUE_STATS_ONLY(print_taskqueue_stats()); 3440 TASKQUEUE_STATS_ONLY(reset_taskqueue_stats()); 3441 3442 print_heap_after_gc(); 3443 print_heap_regions(); 3444 trace_heap_after_gc(_gc_tracer_stw); 3445 3446 // We must call G1MonitoringSupport::update_sizes() in the same scoping level 3447 // as an active TraceMemoryManagerStats object (i.e. before the destructor for the 3448 // TraceMemoryManagerStats is called) so that the G1 memory pools are updated 3449 // before any GC notifications are raised. 3450 g1mm()->update_sizes(); 3451 3452 _gc_tracer_stw->report_evacuation_info(&evacuation_info); 3453 _gc_tracer_stw->report_tenuring_threshold(_g1_policy->tenuring_threshold()); 3454 _gc_timer_stw->register_gc_end(); 3455 _gc_tracer_stw->report_gc_end(_gc_timer_stw->gc_end(), _gc_timer_stw->time_partitions()); 3456 } 3457 // It should now be safe to tell the concurrent mark thread to start 3458 // without its logging output interfering with the logging output 3459 // that came from the pause. 3460 3461 if (should_start_conc_mark) { 3462 // CAUTION: after the doConcurrentMark() call below, 3463 // the concurrent marking thread(s) could be running 3464 // concurrently with us. Make sure that anything after 3465 // this point does not assume that we are the only GC thread 3466 // running. Note: of course, the actual marking work will 3467 // not start until the safepoint itself is released in 3468 // SuspendibleThreadSet::desynchronize(). 3469 doConcurrentMark(); 3470 } 3471 3472 return true; 3473 } 3474 3475 void G1CollectedHeap::remove_self_forwarding_pointers() { 3476 G1ParRemoveSelfForwardPtrsTask rsfp_task; 3477 workers()->run_task(&rsfp_task); 3478 } 3479 3480 void G1CollectedHeap::restore_after_evac_failure() { 3481 double remove_self_forwards_start = os::elapsedTime(); 3482 3483 remove_self_forwarding_pointers(); 3484 _preserved_marks_set.restore(workers()); 3485 3486 g1_policy()->phase_times()->record_evac_fail_remove_self_forwards((os::elapsedTime() - remove_self_forwards_start) * 1000.0); 3487 } 3488 3489 void G1CollectedHeap::preserve_mark_during_evac_failure(uint worker_id, oop obj, markOop m) { 3490 if (!_evacuation_failed) { 3491 _evacuation_failed = true; 3492 } 3493 3494 _evacuation_failed_info_array[worker_id].register_copy_failure(obj->size()); 3495 _preserved_marks_set.get(worker_id)->push_if_necessary(obj, m); 3496 } 3497 3498 bool G1ParEvacuateFollowersClosure::offer_termination() { 3499 G1ParScanThreadState* const pss = par_scan_state(); 3500 start_term_time(); 3501 const bool res = terminator()->offer_termination(); 3502 end_term_time(); 3503 return res; 3504 } 3505 3506 void G1ParEvacuateFollowersClosure::do_void() { 3507 G1ParScanThreadState* const pss = par_scan_state(); 3508 pss->trim_queue(); 3509 do { 3510 pss->steal_and_trim_queue(queues()); 3511 } while (!offer_termination()); 3512 } 3513 3514 class G1ParTask : public AbstractGangTask { 3515 protected: 3516 G1CollectedHeap* _g1h; 3517 G1ParScanThreadStateSet* _pss; 3518 RefToScanQueueSet* _queues; 3519 G1RootProcessor* _root_processor; 3520 ParallelTaskTerminator _terminator; 3521 uint _n_workers; 3522 3523 public: 3524 G1ParTask(G1CollectedHeap* g1h, G1ParScanThreadStateSet* per_thread_states, RefToScanQueueSet *task_queues, G1RootProcessor* root_processor, uint n_workers) 3525 : AbstractGangTask("G1 collection"), 3526 _g1h(g1h), 3527 _pss(per_thread_states), 3528 _queues(task_queues), 3529 _root_processor(root_processor), 3530 _terminator(n_workers, _queues), 3531 _n_workers(n_workers) 3532 {} 3533 3534 void work(uint worker_id) { 3535 if (worker_id >= _n_workers) return; // no work needed this round 3536 3537 double start_sec = os::elapsedTime(); 3538 _g1h->g1_policy()->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerStart, worker_id, start_sec); 3539 3540 { 3541 ResourceMark rm; 3542 HandleMark hm; 3543 3544 ReferenceProcessor* rp = _g1h->ref_processor_stw(); 3545 3546 G1ParScanThreadState* pss = _pss->state_for_worker(worker_id); 3547 pss->set_ref_processor(rp); 3548 3549 double start_strong_roots_sec = os::elapsedTime(); 3550 3551 _root_processor->evacuate_roots(pss->closures(), worker_id); 3552 3553 G1ParPushHeapRSClosure push_heap_rs_cl(_g1h, pss); 3554 3555 // We pass a weak code blobs closure to the remembered set scanning because we want to avoid 3556 // treating the nmethods visited to act as roots for concurrent marking. 3557 // We only want to make sure that the oops in the nmethods are adjusted with regard to the 3558 // objects copied by the current evacuation. 3559 size_t cards_scanned = _g1h->g1_rem_set()->oops_into_collection_set_do(&push_heap_rs_cl, 3560 pss->closures()->weak_codeblobs(), 3561 worker_id); 3562 3563 _pss->add_cards_scanned(worker_id, cards_scanned); 3564 3565 double strong_roots_sec = os::elapsedTime() - start_strong_roots_sec; 3566 3567 double term_sec = 0.0; 3568 size_t evac_term_attempts = 0; 3569 { 3570 double start = os::elapsedTime(); 3571 G1ParEvacuateFollowersClosure evac(_g1h, pss, _queues, &_terminator); 3572 evac.do_void(); 3573 3574 evac_term_attempts = evac.term_attempts(); 3575 term_sec = evac.term_time(); 3576 double elapsed_sec = os::elapsedTime() - start; 3577 _g1h->g1_policy()->phase_times()->add_time_secs(G1GCPhaseTimes::ObjCopy, worker_id, elapsed_sec - term_sec); 3578 _g1h->g1_policy()->phase_times()->record_time_secs(G1GCPhaseTimes::Termination, worker_id, term_sec); 3579 _g1h->g1_policy()->phase_times()->record_thread_work_item(G1GCPhaseTimes::Termination, worker_id, evac_term_attempts); 3580 } 3581 3582 assert(pss->queue_is_empty(), "should be empty"); 3583 3584 if (log_is_enabled(Debug, gc, task, stats)) { 3585 MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag); 3586 size_t lab_waste; 3587 size_t lab_undo_waste; 3588 pss->waste(lab_waste, lab_undo_waste); 3589 _g1h->print_termination_stats(worker_id, 3590 (os::elapsedTime() - start_sec) * 1000.0, /* elapsed time */ 3591 strong_roots_sec * 1000.0, /* strong roots time */ 3592 term_sec * 1000.0, /* evac term time */ 3593 evac_term_attempts, /* evac term attempts */ 3594 lab_waste, /* alloc buffer waste */ 3595 lab_undo_waste /* undo waste */ 3596 ); 3597 } 3598 3599 // Close the inner scope so that the ResourceMark and HandleMark 3600 // destructors are executed here and are included as part of the 3601 // "GC Worker Time". 3602 } 3603 _g1h->g1_policy()->phase_times()->record_time_secs(G1GCPhaseTimes::GCWorkerEnd, worker_id, os::elapsedTime()); 3604 } 3605 }; 3606 3607 void G1CollectedHeap::print_termination_stats_hdr() { 3608 log_debug(gc, task, stats)("GC Termination Stats"); 3609 log_debug(gc, task, stats)(" elapsed --strong roots-- -------termination------- ------waste (KiB)------"); 3610 log_debug(gc, task, stats)("thr ms ms %% ms %% attempts total alloc undo"); 3611 log_debug(gc, task, stats)("--- --------- --------- ------ --------- ------ -------- ------- ------- -------"); 3612 } 3613 3614 void G1CollectedHeap::print_termination_stats(uint worker_id, 3615 double elapsed_ms, 3616 double strong_roots_ms, 3617 double term_ms, 3618 size_t term_attempts, 3619 size_t alloc_buffer_waste, 3620 size_t undo_waste) const { 3621 log_debug(gc, task, stats) 3622 ("%3d %9.2f %9.2f %6.2f " 3623 "%9.2f %6.2f " SIZE_FORMAT_W(8) " " 3624 SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7), 3625 worker_id, elapsed_ms, strong_roots_ms, strong_roots_ms * 100 / elapsed_ms, 3626 term_ms, term_ms * 100 / elapsed_ms, term_attempts, 3627 (alloc_buffer_waste + undo_waste) * HeapWordSize / K, 3628 alloc_buffer_waste * HeapWordSize / K, 3629 undo_waste * HeapWordSize / K); 3630 } 3631 3632 class G1StringSymbolTableUnlinkTask : public AbstractGangTask { 3633 private: 3634 BoolObjectClosure* _is_alive; 3635 int _initial_string_table_size; 3636 int _initial_symbol_table_size; 3637 3638 bool _process_strings; 3639 int _strings_processed; 3640 int _strings_removed; 3641 3642 bool _process_symbols; 3643 int _symbols_processed; 3644 int _symbols_removed; 3645 3646 public: 3647 G1StringSymbolTableUnlinkTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols) : 3648 AbstractGangTask("String/Symbol Unlinking"), 3649 _is_alive(is_alive), 3650 _process_strings(process_strings), _strings_processed(0), _strings_removed(0), 3651 _process_symbols(process_symbols), _symbols_processed(0), _symbols_removed(0) { 3652 3653 _initial_string_table_size = StringTable::the_table()->table_size(); 3654 _initial_symbol_table_size = SymbolTable::the_table()->table_size(); 3655 if (process_strings) { 3656 StringTable::clear_parallel_claimed_index(); 3657 } 3658 if (process_symbols) { 3659 SymbolTable::clear_parallel_claimed_index(); 3660 } 3661 } 3662 3663 ~G1StringSymbolTableUnlinkTask() { 3664 guarantee(!_process_strings || StringTable::parallel_claimed_index() >= _initial_string_table_size, 3665 "claim value %d after unlink less than initial string table size %d", 3666 StringTable::parallel_claimed_index(), _initial_string_table_size); 3667 guarantee(!_process_symbols || SymbolTable::parallel_claimed_index() >= _initial_symbol_table_size, 3668 "claim value %d after unlink less than initial symbol table size %d", 3669 SymbolTable::parallel_claimed_index(), _initial_symbol_table_size); 3670 3671 log_info(gc, stringtable)( 3672 "Cleaned string and symbol table, " 3673 "strings: " SIZE_FORMAT " processed, " SIZE_FORMAT " removed, " 3674 "symbols: " SIZE_FORMAT " processed, " SIZE_FORMAT " removed", 3675 strings_processed(), strings_removed(), 3676 symbols_processed(), symbols_removed()); 3677 } 3678 3679 void work(uint worker_id) { 3680 int strings_processed = 0; 3681 int strings_removed = 0; 3682 int symbols_processed = 0; 3683 int symbols_removed = 0; 3684 if (_process_strings) { 3685 StringTable::possibly_parallel_unlink(_is_alive, &strings_processed, &strings_removed); 3686 Atomic::add(strings_processed, &_strings_processed); 3687 Atomic::add(strings_removed, &_strings_removed); 3688 } 3689 if (_process_symbols) { 3690 SymbolTable::possibly_parallel_unlink(&symbols_processed, &symbols_removed); 3691 Atomic::add(symbols_processed, &_symbols_processed); 3692 Atomic::add(symbols_removed, &_symbols_removed); 3693 } 3694 } 3695 3696 size_t strings_processed() const { return (size_t)_strings_processed; } 3697 size_t strings_removed() const { return (size_t)_strings_removed; } 3698 3699 size_t symbols_processed() const { return (size_t)_symbols_processed; } 3700 size_t symbols_removed() const { return (size_t)_symbols_removed; } 3701 }; 3702 3703 class G1CodeCacheUnloadingTask VALUE_OBJ_CLASS_SPEC { 3704 private: 3705 static Monitor* _lock; 3706 3707 BoolObjectClosure* const _is_alive; 3708 const bool _unloading_occurred; 3709 const uint _num_workers; 3710 3711 // Variables used to claim nmethods. 3712 nmethod* _first_nmethod; 3713 volatile nmethod* _claimed_nmethod; 3714 3715 // The list of nmethods that need to be processed by the second pass. 3716 volatile nmethod* _postponed_list; 3717 volatile uint _num_entered_barrier; 3718 3719 public: 3720 G1CodeCacheUnloadingTask(uint num_workers, BoolObjectClosure* is_alive, bool unloading_occurred) : 3721 _is_alive(is_alive), 3722 _unloading_occurred(unloading_occurred), 3723 _num_workers(num_workers), 3724 _first_nmethod(NULL), 3725 _claimed_nmethod(NULL), 3726 _postponed_list(NULL), 3727 _num_entered_barrier(0) 3728 { 3729 nmethod::increase_unloading_clock(); 3730 // Get first alive nmethod 3731 NMethodIterator iter = NMethodIterator(); 3732 if(iter.next_alive()) { 3733 _first_nmethod = iter.method(); 3734 } 3735 _claimed_nmethod = (volatile nmethod*)_first_nmethod; 3736 } 3737 3738 ~G1CodeCacheUnloadingTask() { 3739 CodeCache::verify_clean_inline_caches(); 3740 3741 CodeCache::set_needs_cache_clean(false); 3742 guarantee(CodeCache::scavenge_root_nmethods() == NULL, "Must be"); 3743 3744 CodeCache::verify_icholder_relocations(); 3745 } 3746 3747 private: 3748 void add_to_postponed_list(nmethod* nm) { 3749 nmethod* old; 3750 do { 3751 old = (nmethod*)_postponed_list; 3752 nm->set_unloading_next(old); 3753 } while ((nmethod*)Atomic::cmpxchg_ptr(nm, &_postponed_list, old) != old); 3754 } 3755 3756 void clean_nmethod(nmethod* nm) { 3757 bool postponed = nm->do_unloading_parallel(_is_alive, _unloading_occurred); 3758 3759 if (postponed) { 3760 // This nmethod referred to an nmethod that has not been cleaned/unloaded yet. 3761 add_to_postponed_list(nm); 3762 } 3763 3764 // Mark that this thread has been cleaned/unloaded. 3765 // After this call, it will be safe to ask if this nmethod was unloaded or not. 3766 nm->set_unloading_clock(nmethod::global_unloading_clock()); 3767 } 3768 3769 void clean_nmethod_postponed(nmethod* nm) { 3770 nm->do_unloading_parallel_postponed(_is_alive, _unloading_occurred); 3771 } 3772 3773 static const int MaxClaimNmethods = 16; 3774 3775 void claim_nmethods(nmethod** claimed_nmethods, int *num_claimed_nmethods) { 3776 nmethod* first; 3777 NMethodIterator last; 3778 3779 do { 3780 *num_claimed_nmethods = 0; 3781 3782 first = (nmethod*)_claimed_nmethod; 3783 last = NMethodIterator(first); 3784 3785 if (first != NULL) { 3786 3787 for (int i = 0; i < MaxClaimNmethods; i++) { 3788 if (!last.next_alive()) { 3789 break; 3790 } 3791 claimed_nmethods[i] = last.method(); 3792 (*num_claimed_nmethods)++; 3793 } 3794 } 3795 3796 } while ((nmethod*)Atomic::cmpxchg_ptr(last.method(), &_claimed_nmethod, first) != first); 3797 } 3798 3799 nmethod* claim_postponed_nmethod() { 3800 nmethod* claim; 3801 nmethod* next; 3802 3803 do { 3804 claim = (nmethod*)_postponed_list; 3805 if (claim == NULL) { 3806 return NULL; 3807 } 3808 3809 next = claim->unloading_next(); 3810 3811 } while ((nmethod*)Atomic::cmpxchg_ptr(next, &_postponed_list, claim) != claim); 3812 3813 return claim; 3814 } 3815 3816 public: 3817 // Mark that we're done with the first pass of nmethod cleaning. 3818 void barrier_mark(uint worker_id) { 3819 MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag); 3820 _num_entered_barrier++; 3821 if (_num_entered_barrier == _num_workers) { 3822 ml.notify_all(); 3823 } 3824 } 3825 3826 // See if we have to wait for the other workers to 3827 // finish their first-pass nmethod cleaning work. 3828 void barrier_wait(uint worker_id) { 3829 if (_num_entered_barrier < _num_workers) { 3830 MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag); 3831 while (_num_entered_barrier < _num_workers) { 3832 ml.wait(Mutex::_no_safepoint_check_flag, 0, false); 3833 } 3834 } 3835 } 3836 3837 // Cleaning and unloading of nmethods. Some work has to be postponed 3838 // to the second pass, when we know which nmethods survive. 3839 void work_first_pass(uint worker_id) { 3840 // The first nmethods is claimed by the first worker. 3841 if (worker_id == 0 && _first_nmethod != NULL) { 3842 clean_nmethod(_first_nmethod); 3843 _first_nmethod = NULL; 3844 } 3845 3846 int num_claimed_nmethods; 3847 nmethod* claimed_nmethods[MaxClaimNmethods]; 3848 3849 while (true) { 3850 claim_nmethods(claimed_nmethods, &num_claimed_nmethods); 3851 3852 if (num_claimed_nmethods == 0) { 3853 break; 3854 } 3855 3856 for (int i = 0; i < num_claimed_nmethods; i++) { 3857 clean_nmethod(claimed_nmethods[i]); 3858 } 3859 } 3860 } 3861 3862 void work_second_pass(uint worker_id) { 3863 nmethod* nm; 3864 // Take care of postponed nmethods. 3865 while ((nm = claim_postponed_nmethod()) != NULL) { 3866 clean_nmethod_postponed(nm); 3867 } 3868 } 3869 }; 3870 3871 Monitor* G1CodeCacheUnloadingTask::_lock = new Monitor(Mutex::leaf, "Code Cache Unload lock", false, Monitor::_safepoint_check_never); 3872 3873 class G1KlassCleaningTask : public StackObj { 3874 BoolObjectClosure* _is_alive; 3875 volatile jint _clean_klass_tree_claimed; 3876 ClassLoaderDataGraphKlassIteratorAtomic _klass_iterator; 3877 3878 public: 3879 G1KlassCleaningTask(BoolObjectClosure* is_alive) : 3880 _is_alive(is_alive), 3881 _clean_klass_tree_claimed(0), 3882 _klass_iterator() { 3883 } 3884 3885 private: 3886 bool claim_clean_klass_tree_task() { 3887 if (_clean_klass_tree_claimed) { 3888 return false; 3889 } 3890 3891 return Atomic::cmpxchg(1, (jint*)&_clean_klass_tree_claimed, 0) == 0; 3892 } 3893 3894 InstanceKlass* claim_next_klass() { 3895 Klass* klass; 3896 do { 3897 klass =_klass_iterator.next_klass(); 3898 } while (klass != NULL && !klass->is_instance_klass()); 3899 3900 // this can be null so don't call InstanceKlass::cast 3901 return static_cast<InstanceKlass*>(klass); 3902 } 3903 3904 public: 3905 3906 void clean_klass(InstanceKlass* ik) { 3907 ik->clean_weak_instanceklass_links(_is_alive); 3908 } 3909 3910 void work() { 3911 ResourceMark rm; 3912 3913 // One worker will clean the subklass/sibling klass tree. 3914 if (claim_clean_klass_tree_task()) { 3915 Klass::clean_subklass_tree(_is_alive); 3916 } 3917 3918 // All workers will help cleaning the classes, 3919 InstanceKlass* klass; 3920 while ((klass = claim_next_klass()) != NULL) { 3921 clean_klass(klass); 3922 } 3923 } 3924 }; 3925 3926 // To minimize the remark pause times, the tasks below are done in parallel. 3927 class G1ParallelCleaningTask : public AbstractGangTask { 3928 private: 3929 G1StringSymbolTableUnlinkTask _string_symbol_task; 3930 G1CodeCacheUnloadingTask _code_cache_task; 3931 G1KlassCleaningTask _klass_cleaning_task; 3932 3933 public: 3934 // The constructor is run in the VMThread. 3935 G1ParallelCleaningTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols, uint num_workers, bool unloading_occurred) : 3936 AbstractGangTask("Parallel Cleaning"), 3937 _string_symbol_task(is_alive, process_strings, process_symbols), 3938 _code_cache_task(num_workers, is_alive, unloading_occurred), 3939 _klass_cleaning_task(is_alive) { 3940 } 3941 3942 // The parallel work done by all worker threads. 3943 void work(uint worker_id) { 3944 // Do first pass of code cache cleaning. 3945 _code_cache_task.work_first_pass(worker_id); 3946 3947 // Let the threads mark that the first pass is done. 3948 _code_cache_task.barrier_mark(worker_id); 3949 3950 // Clean the Strings and Symbols. 3951 _string_symbol_task.work(worker_id); 3952 3953 // Wait for all workers to finish the first code cache cleaning pass. 3954 _code_cache_task.barrier_wait(worker_id); 3955 3956 // Do the second code cache cleaning work, which realize on 3957 // the liveness information gathered during the first pass. 3958 _code_cache_task.work_second_pass(worker_id); 3959 3960 // Clean all klasses that were not unloaded. 3961 _klass_cleaning_task.work(); 3962 } 3963 }; 3964 3965 3966 void G1CollectedHeap::parallel_cleaning(BoolObjectClosure* is_alive, 3967 bool process_strings, 3968 bool process_symbols, 3969 bool class_unloading_occurred) { 3970 uint n_workers = workers()->active_workers(); 3971 3972 G1ParallelCleaningTask g1_unlink_task(is_alive, process_strings, process_symbols, 3973 n_workers, class_unloading_occurred); 3974 workers()->run_task(&g1_unlink_task); 3975 } 3976 3977 void G1CollectedHeap::unlink_string_and_symbol_table(BoolObjectClosure* is_alive, 3978 bool process_strings, bool process_symbols) { 3979 { // Timing scope 3980 G1StringSymbolTableUnlinkTask g1_unlink_task(is_alive, process_strings, process_symbols); 3981 workers()->run_task(&g1_unlink_task); 3982 } 3983 } 3984 3985 class G1RedirtyLoggedCardsTask : public AbstractGangTask { 3986 private: 3987 DirtyCardQueueSet* _queue; 3988 G1CollectedHeap* _g1h; 3989 public: 3990 G1RedirtyLoggedCardsTask(DirtyCardQueueSet* queue, G1CollectedHeap* g1h) : AbstractGangTask("Redirty Cards"), 3991 _queue(queue), _g1h(g1h) { } 3992 3993 virtual void work(uint worker_id) { 3994 G1GCPhaseTimes* phase_times = _g1h->g1_policy()->phase_times(); 3995 G1GCParPhaseTimesTracker x(phase_times, G1GCPhaseTimes::RedirtyCards, worker_id); 3996 3997 RedirtyLoggedCardTableEntryClosure cl(_g1h); 3998 _queue->par_apply_closure_to_all_completed_buffers(&cl); 3999 4000 phase_times->record_thread_work_item(G1GCPhaseTimes::RedirtyCards, worker_id, cl.num_dirtied()); 4001 } 4002 }; 4003 4004 void G1CollectedHeap::redirty_logged_cards() { 4005 double redirty_logged_cards_start = os::elapsedTime(); 4006 4007 G1RedirtyLoggedCardsTask redirty_task(&dirty_card_queue_set(), this); 4008 dirty_card_queue_set().reset_for_par_iteration(); 4009 workers()->run_task(&redirty_task); 4010 4011 DirtyCardQueueSet& dcq = JavaThread::dirty_card_queue_set(); 4012 dcq.merge_bufferlists(&dirty_card_queue_set()); 4013 assert(dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed"); 4014 4015 g1_policy()->phase_times()->record_redirty_logged_cards_time_ms((os::elapsedTime() - redirty_logged_cards_start) * 1000.0); 4016 } 4017 4018 // Weak Reference Processing support 4019 4020 // An always "is_alive" closure that is used to preserve referents. 4021 // If the object is non-null then it's alive. Used in the preservation 4022 // of referent objects that are pointed to by reference objects 4023 // discovered by the CM ref processor. 4024 class G1AlwaysAliveClosure: public BoolObjectClosure { 4025 G1CollectedHeap* _g1; 4026 public: 4027 G1AlwaysAliveClosure(G1CollectedHeap* g1) : _g1(g1) {} 4028 bool do_object_b(oop p) { 4029 if (p != NULL) { 4030 return true; 4031 } 4032 return false; 4033 } 4034 }; 4035 4036 bool G1STWIsAliveClosure::do_object_b(oop p) { 4037 // An object is reachable if it is outside the collection set, 4038 // or is inside and copied. 4039 return !_g1->is_in_cset(p) || p->is_forwarded(); 4040 } 4041 4042 // Non Copying Keep Alive closure 4043 class G1KeepAliveClosure: public OopClosure { 4044 G1CollectedHeap* _g1; 4045 public: 4046 G1KeepAliveClosure(G1CollectedHeap* g1) : _g1(g1) {} 4047 void do_oop(narrowOop* p) { guarantee(false, "Not needed"); } 4048 void do_oop(oop* p) { 4049 oop obj = *p; 4050 assert(obj != NULL, "the caller should have filtered out NULL values"); 4051 4052 const InCSetState cset_state = _g1->in_cset_state(obj); 4053 if (!cset_state.is_in_cset_or_humongous()) { 4054 return; 4055 } 4056 if (cset_state.is_in_cset()) { 4057 assert( obj->is_forwarded(), "invariant" ); 4058 *p = obj->forwardee(); 4059 } else { 4060 assert(!obj->is_forwarded(), "invariant" ); 4061 assert(cset_state.is_humongous(), 4062 "Only allowed InCSet state is IsHumongous, but is %d", cset_state.value()); 4063 _g1->set_humongous_is_live(obj); 4064 } 4065 } 4066 }; 4067 4068 // Copying Keep Alive closure - can be called from both 4069 // serial and parallel code as long as different worker 4070 // threads utilize different G1ParScanThreadState instances 4071 // and different queues. 4072 4073 class G1CopyingKeepAliveClosure: public OopClosure { 4074 G1CollectedHeap* _g1h; 4075 OopClosure* _copy_non_heap_obj_cl; 4076 G1ParScanThreadState* _par_scan_state; 4077 4078 public: 4079 G1CopyingKeepAliveClosure(G1CollectedHeap* g1h, 4080 OopClosure* non_heap_obj_cl, 4081 G1ParScanThreadState* pss): 4082 _g1h(g1h), 4083 _copy_non_heap_obj_cl(non_heap_obj_cl), 4084 _par_scan_state(pss) 4085 {} 4086 4087 virtual void do_oop(narrowOop* p) { do_oop_work(p); } 4088 virtual void do_oop( oop* p) { do_oop_work(p); } 4089 4090 template <class T> void do_oop_work(T* p) { 4091 oop obj = oopDesc::load_decode_heap_oop(p); 4092 4093 if (_g1h->is_in_cset_or_humongous(obj)) { 4094 // If the referent object has been forwarded (either copied 4095 // to a new location or to itself in the event of an 4096 // evacuation failure) then we need to update the reference 4097 // field and, if both reference and referent are in the G1 4098 // heap, update the RSet for the referent. 4099 // 4100 // If the referent has not been forwarded then we have to keep 4101 // it alive by policy. Therefore we have copy the referent. 4102 // 4103 // If the reference field is in the G1 heap then we can push 4104 // on the PSS queue. When the queue is drained (after each 4105 // phase of reference processing) the object and it's followers 4106 // will be copied, the reference field set to point to the 4107 // new location, and the RSet updated. Otherwise we need to 4108 // use the the non-heap or metadata closures directly to copy 4109 // the referent object and update the pointer, while avoiding 4110 // updating the RSet. 4111 4112 if (_g1h->is_in_g1_reserved(p)) { 4113 _par_scan_state->push_on_queue(p); 4114 } else { 4115 assert(!Metaspace::contains((const void*)p), 4116 "Unexpectedly found a pointer from metadata: " PTR_FORMAT, p2i(p)); 4117 _copy_non_heap_obj_cl->do_oop(p); 4118 } 4119 } 4120 } 4121 }; 4122 4123 // Serial drain queue closure. Called as the 'complete_gc' 4124 // closure for each discovered list in some of the 4125 // reference processing phases. 4126 4127 class G1STWDrainQueueClosure: public VoidClosure { 4128 protected: 4129 G1CollectedHeap* _g1h; 4130 G1ParScanThreadState* _par_scan_state; 4131 4132 G1ParScanThreadState* par_scan_state() { return _par_scan_state; } 4133 4134 public: 4135 G1STWDrainQueueClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) : 4136 _g1h(g1h), 4137 _par_scan_state(pss) 4138 { } 4139 4140 void do_void() { 4141 G1ParScanThreadState* const pss = par_scan_state(); 4142 pss->trim_queue(); 4143 } 4144 }; 4145 4146 // Parallel Reference Processing closures 4147 4148 // Implementation of AbstractRefProcTaskExecutor for parallel reference 4149 // processing during G1 evacuation pauses. 4150 4151 class G1STWRefProcTaskExecutor: public AbstractRefProcTaskExecutor { 4152 private: 4153 G1CollectedHeap* _g1h; 4154 G1ParScanThreadStateSet* _pss; 4155 RefToScanQueueSet* _queues; 4156 WorkGang* _workers; 4157 uint _active_workers; 4158 4159 public: 4160 G1STWRefProcTaskExecutor(G1CollectedHeap* g1h, 4161 G1ParScanThreadStateSet* per_thread_states, 4162 WorkGang* workers, 4163 RefToScanQueueSet *task_queues, 4164 uint n_workers) : 4165 _g1h(g1h), 4166 _pss(per_thread_states), 4167 _queues(task_queues), 4168 _workers(workers), 4169 _active_workers(n_workers) 4170 { 4171 g1h->ref_processor_stw()->set_active_mt_degree(n_workers); 4172 } 4173 4174 // Executes the given task using concurrent marking worker threads. 4175 virtual void execute(ProcessTask& task); 4176 virtual void execute(EnqueueTask& task); 4177 }; 4178 4179 // Gang task for possibly parallel reference processing 4180 4181 class G1STWRefProcTaskProxy: public AbstractGangTask { 4182 typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask; 4183 ProcessTask& _proc_task; 4184 G1CollectedHeap* _g1h; 4185 G1ParScanThreadStateSet* _pss; 4186 RefToScanQueueSet* _task_queues; 4187 ParallelTaskTerminator* _terminator; 4188 4189 public: 4190 G1STWRefProcTaskProxy(ProcessTask& proc_task, 4191 G1CollectedHeap* g1h, 4192 G1ParScanThreadStateSet* per_thread_states, 4193 RefToScanQueueSet *task_queues, 4194 ParallelTaskTerminator* terminator) : 4195 AbstractGangTask("Process reference objects in parallel"), 4196 _proc_task(proc_task), 4197 _g1h(g1h), 4198 _pss(per_thread_states), 4199 _task_queues(task_queues), 4200 _terminator(terminator) 4201 {} 4202 4203 virtual void work(uint worker_id) { 4204 // The reference processing task executed by a single worker. 4205 ResourceMark rm; 4206 HandleMark hm; 4207 4208 G1STWIsAliveClosure is_alive(_g1h); 4209 4210 G1ParScanThreadState* pss = _pss->state_for_worker(worker_id); 4211 pss->set_ref_processor(NULL); 4212 4213 // Keep alive closure. 4214 G1CopyingKeepAliveClosure keep_alive(_g1h, pss->closures()->raw_strong_oops(), pss); 4215 4216 // Complete GC closure 4217 G1ParEvacuateFollowersClosure drain_queue(_g1h, pss, _task_queues, _terminator); 4218 4219 // Call the reference processing task's work routine. 4220 _proc_task.work(worker_id, is_alive, keep_alive, drain_queue); 4221 4222 // Note we cannot assert that the refs array is empty here as not all 4223 // of the processing tasks (specifically phase2 - pp2_work) execute 4224 // the complete_gc closure (which ordinarily would drain the queue) so 4225 // the queue may not be empty. 4226 } 4227 }; 4228 4229 // Driver routine for parallel reference processing. 4230 // Creates an instance of the ref processing gang 4231 // task and has the worker threads execute it. 4232 void G1STWRefProcTaskExecutor::execute(ProcessTask& proc_task) { 4233 assert(_workers != NULL, "Need parallel worker threads."); 4234 4235 ParallelTaskTerminator terminator(_active_workers, _queues); 4236 G1STWRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _pss, _queues, &terminator); 4237 4238 _workers->run_task(&proc_task_proxy); 4239 } 4240 4241 // Gang task for parallel reference enqueueing. 4242 4243 class G1STWRefEnqueueTaskProxy: public AbstractGangTask { 4244 typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask; 4245 EnqueueTask& _enq_task; 4246 4247 public: 4248 G1STWRefEnqueueTaskProxy(EnqueueTask& enq_task) : 4249 AbstractGangTask("Enqueue reference objects in parallel"), 4250 _enq_task(enq_task) 4251 { } 4252 4253 virtual void work(uint worker_id) { 4254 _enq_task.work(worker_id); 4255 } 4256 }; 4257 4258 // Driver routine for parallel reference enqueueing. 4259 // Creates an instance of the ref enqueueing gang 4260 // task and has the worker threads execute it. 4261 4262 void G1STWRefProcTaskExecutor::execute(EnqueueTask& enq_task) { 4263 assert(_workers != NULL, "Need parallel worker threads."); 4264 4265 G1STWRefEnqueueTaskProxy enq_task_proxy(enq_task); 4266 4267 _workers->run_task(&enq_task_proxy); 4268 } 4269 4270 // End of weak reference support closures 4271 4272 // Abstract task used to preserve (i.e. copy) any referent objects 4273 // that are in the collection set and are pointed to by reference 4274 // objects discovered by the CM ref processor. 4275 4276 class G1ParPreserveCMReferentsTask: public AbstractGangTask { 4277 protected: 4278 G1CollectedHeap* _g1h; 4279 G1ParScanThreadStateSet* _pss; 4280 RefToScanQueueSet* _queues; 4281 ParallelTaskTerminator _terminator; 4282 uint _n_workers; 4283 4284 public: 4285 G1ParPreserveCMReferentsTask(G1CollectedHeap* g1h, G1ParScanThreadStateSet* per_thread_states, int workers, RefToScanQueueSet *task_queues) : 4286 AbstractGangTask("ParPreserveCMReferents"), 4287 _g1h(g1h), 4288 _pss(per_thread_states), 4289 _queues(task_queues), 4290 _terminator(workers, _queues), 4291 _n_workers(workers) 4292 { 4293 g1h->ref_processor_cm()->set_active_mt_degree(workers); 4294 } 4295 4296 void work(uint worker_id) { 4297 G1GCParPhaseTimesTracker x(_g1h->g1_policy()->phase_times(), G1GCPhaseTimes::PreserveCMReferents, worker_id); 4298 4299 ResourceMark rm; 4300 HandleMark hm; 4301 4302 G1ParScanThreadState* pss = _pss->state_for_worker(worker_id); 4303 pss->set_ref_processor(NULL); 4304 assert(pss->queue_is_empty(), "both queue and overflow should be empty"); 4305 4306 // Is alive closure 4307 G1AlwaysAliveClosure always_alive(_g1h); 4308 4309 // Copying keep alive closure. Applied to referent objects that need 4310 // to be copied. 4311 G1CopyingKeepAliveClosure keep_alive(_g1h, pss->closures()->raw_strong_oops(), pss); 4312 4313 ReferenceProcessor* rp = _g1h->ref_processor_cm(); 4314 4315 uint limit = ReferenceProcessor::number_of_subclasses_of_ref() * rp->max_num_q(); 4316 uint stride = MIN2(MAX2(_n_workers, 1U), limit); 4317 4318 // limit is set using max_num_q() - which was set using ParallelGCThreads. 4319 // So this must be true - but assert just in case someone decides to 4320 // change the worker ids. 4321 assert(worker_id < limit, "sanity"); 4322 assert(!rp->discovery_is_atomic(), "check this code"); 4323 4324 // Select discovered lists [i, i+stride, i+2*stride,...,limit) 4325 for (uint idx = worker_id; idx < limit; idx += stride) { 4326 DiscoveredList& ref_list = rp->discovered_refs()[idx]; 4327 4328 DiscoveredListIterator iter(ref_list, &keep_alive, &always_alive); 4329 while (iter.has_next()) { 4330 // Since discovery is not atomic for the CM ref processor, we 4331 // can see some null referent objects. 4332 iter.load_ptrs(DEBUG_ONLY(true)); 4333 oop ref = iter.obj(); 4334 4335 // This will filter nulls. 4336 if (iter.is_referent_alive()) { 4337 iter.make_referent_alive(); 4338 } 4339 iter.move_to_next(); 4340 } 4341 } 4342 4343 // Drain the queue - which may cause stealing 4344 G1ParEvacuateFollowersClosure drain_queue(_g1h, pss, _queues, &_terminator); 4345 drain_queue.do_void(); 4346 // Allocation buffers were retired at the end of G1ParEvacuateFollowersClosure 4347 assert(pss->queue_is_empty(), "should be"); 4348 } 4349 }; 4350 4351 void G1CollectedHeap::process_weak_jni_handles() { 4352 double ref_proc_start = os::elapsedTime(); 4353 4354 G1STWIsAliveClosure is_alive(this); 4355 G1KeepAliveClosure keep_alive(this); 4356 JNIHandles::weak_oops_do(&is_alive, &keep_alive); 4357 4358 double ref_proc_time = os::elapsedTime() - ref_proc_start; 4359 g1_policy()->phase_times()->record_ref_proc_time(ref_proc_time * 1000.0); 4360 } 4361 4362 void G1CollectedHeap::preserve_cm_referents(G1ParScanThreadStateSet* per_thread_states) { 4363 // Any reference objects, in the collection set, that were 'discovered' 4364 // by the CM ref processor should have already been copied (either by 4365 // applying the external root copy closure to the discovered lists, or 4366 // by following an RSet entry). 4367 // 4368 // But some of the referents, that are in the collection set, that these 4369 // reference objects point to may not have been copied: the STW ref 4370 // processor would have seen that the reference object had already 4371 // been 'discovered' and would have skipped discovering the reference, 4372 // but would not have treated the reference object as a regular oop. 4373 // As a result the copy closure would not have been applied to the 4374 // referent object. 4375 // 4376 // We need to explicitly copy these referent objects - the references 4377 // will be processed at the end of remarking. 4378 // 4379 // We also need to do this copying before we process the reference 4380 // objects discovered by the STW ref processor in case one of these 4381 // referents points to another object which is also referenced by an 4382 // object discovered by the STW ref processor. 4383 double preserve_cm_referents_time = 0.0; 4384 4385 // To avoid spawning task when there is no work to do, check that 4386 // a concurrent cycle is active and that some references have been 4387 // discovered. 4388 if (concurrent_mark()->cmThread()->during_cycle() && 4389 ref_processor_cm()->has_discovered_references()) { 4390 double preserve_cm_referents_start = os::elapsedTime(); 4391 uint no_of_gc_workers = workers()->active_workers(); 4392 G1ParPreserveCMReferentsTask keep_cm_referents(this, 4393 per_thread_states, 4394 no_of_gc_workers, 4395 _task_queues); 4396 workers()->run_task(&keep_cm_referents); 4397 preserve_cm_referents_time = os::elapsedTime() - preserve_cm_referents_start; 4398 } 4399 4400 g1_policy()->phase_times()->record_preserve_cm_referents_time_ms(preserve_cm_referents_time * 1000.0); 4401 } 4402 4403 // Weak Reference processing during an evacuation pause (part 1). 4404 void G1CollectedHeap::process_discovered_references(G1ParScanThreadStateSet* per_thread_states) { 4405 double ref_proc_start = os::elapsedTime(); 4406 4407 ReferenceProcessor* rp = _ref_processor_stw; 4408 assert(rp->discovery_enabled(), "should have been enabled"); 4409 4410 // Closure to test whether a referent is alive. 4411 G1STWIsAliveClosure is_alive(this); 4412 4413 // Even when parallel reference processing is enabled, the processing 4414 // of JNI refs is serial and performed serially by the current thread 4415 // rather than by a worker. The following PSS will be used for processing 4416 // JNI refs. 4417 4418 // Use only a single queue for this PSS. 4419 G1ParScanThreadState* pss = per_thread_states->state_for_worker(0); 4420 pss->set_ref_processor(NULL); 4421 assert(pss->queue_is_empty(), "pre-condition"); 4422 4423 // Keep alive closure. 4424 G1CopyingKeepAliveClosure keep_alive(this, pss->closures()->raw_strong_oops(), pss); 4425 4426 // Serial Complete GC closure 4427 G1STWDrainQueueClosure drain_queue(this, pss); 4428 4429 // Setup the soft refs policy... 4430 rp->setup_policy(false); 4431 4432 ReferenceProcessorStats stats; 4433 if (!rp->processing_is_mt()) { 4434 // Serial reference processing... 4435 stats = rp->process_discovered_references(&is_alive, 4436 &keep_alive, 4437 &drain_queue, 4438 NULL, 4439 _gc_timer_stw); 4440 } else { 4441 uint no_of_gc_workers = workers()->active_workers(); 4442 4443 // Parallel reference processing 4444 assert(no_of_gc_workers <= rp->max_num_q(), 4445 "Mismatch between the number of GC workers %u and the maximum number of Reference process queues %u", 4446 no_of_gc_workers, rp->max_num_q()); 4447 4448 G1STWRefProcTaskExecutor par_task_executor(this, per_thread_states, workers(), _task_queues, no_of_gc_workers); 4449 stats = rp->process_discovered_references(&is_alive, 4450 &keep_alive, 4451 &drain_queue, 4452 &par_task_executor, 4453 _gc_timer_stw); 4454 } 4455 4456 _gc_tracer_stw->report_gc_reference_stats(stats); 4457 4458 // We have completed copying any necessary live referent objects. 4459 assert(pss->queue_is_empty(), "both queue and overflow should be empty"); 4460 4461 double ref_proc_time = os::elapsedTime() - ref_proc_start; 4462 g1_policy()->phase_times()->record_ref_proc_time(ref_proc_time * 1000.0); 4463 } 4464 4465 // Weak Reference processing during an evacuation pause (part 2). 4466 void G1CollectedHeap::enqueue_discovered_references(G1ParScanThreadStateSet* per_thread_states) { 4467 double ref_enq_start = os::elapsedTime(); 4468 4469 ReferenceProcessor* rp = _ref_processor_stw; 4470 assert(!rp->discovery_enabled(), "should have been disabled as part of processing"); 4471 4472 // Now enqueue any remaining on the discovered lists on to 4473 // the pending list. 4474 if (!rp->processing_is_mt()) { 4475 // Serial reference processing... 4476 rp->enqueue_discovered_references(); 4477 } else { 4478 // Parallel reference enqueueing 4479 4480 uint n_workers = workers()->active_workers(); 4481 4482 assert(n_workers <= rp->max_num_q(), 4483 "Mismatch between the number of GC workers %u and the maximum number of Reference process queues %u", 4484 n_workers, rp->max_num_q()); 4485 4486 G1STWRefProcTaskExecutor par_task_executor(this, per_thread_states, workers(), _task_queues, n_workers); 4487 rp->enqueue_discovered_references(&par_task_executor); 4488 } 4489 4490 rp->verify_no_references_recorded(); 4491 assert(!rp->discovery_enabled(), "should have been disabled"); 4492 4493 // FIXME 4494 // CM's reference processing also cleans up the string and symbol tables. 4495 // Should we do that here also? We could, but it is a serial operation 4496 // and could significantly increase the pause time. 4497 4498 double ref_enq_time = os::elapsedTime() - ref_enq_start; 4499 g1_policy()->phase_times()->record_ref_enq_time(ref_enq_time * 1000.0); 4500 } 4501 4502 void G1CollectedHeap::merge_per_thread_state_info(G1ParScanThreadStateSet* per_thread_states) { 4503 double merge_pss_time_start = os::elapsedTime(); 4504 per_thread_states->flush(); 4505 g1_policy()->phase_times()->record_merge_pss_time_ms((os::elapsedTime() - merge_pss_time_start) * 1000.0); 4506 } 4507 4508 void G1CollectedHeap::pre_evacuate_collection_set() { 4509 _expand_heap_after_alloc_failure = true; 4510 _evacuation_failed = false; 4511 4512 // Disable the hot card cache. 4513 G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache(); 4514 hot_card_cache->reset_hot_cache_claimed_index(); 4515 hot_card_cache->set_use_cache(false); 4516 4517 g1_rem_set()->prepare_for_oops_into_collection_set_do(); 4518 _preserved_marks_set.assert_empty(); 4519 } 4520 4521 void G1CollectedHeap::evacuate_collection_set(EvacuationInfo& evacuation_info, G1ParScanThreadStateSet* per_thread_states) { 4522 // Should G1EvacuationFailureALot be in effect for this GC? 4523 NOT_PRODUCT(set_evacuation_failure_alot_for_current_gc();) 4524 4525 assert(dirty_card_queue_set().completed_buffers_num() == 0, "Should be empty"); 4526 double start_par_time_sec = os::elapsedTime(); 4527 double end_par_time_sec; 4528 4529 { 4530 const uint n_workers = workers()->active_workers(); 4531 G1RootProcessor root_processor(this, n_workers); 4532 G1ParTask g1_par_task(this, per_thread_states, _task_queues, &root_processor, n_workers); 4533 // InitialMark needs claim bits to keep track of the marked-through CLDs. 4534 if (collector_state()->during_initial_mark_pause()) { 4535 ClassLoaderDataGraph::clear_claimed_marks(); 4536 } 4537 4538 print_termination_stats_hdr(); 4539 4540 workers()->run_task(&g1_par_task); 4541 end_par_time_sec = os::elapsedTime(); 4542 4543 // Closing the inner scope will execute the destructor 4544 // for the G1RootProcessor object. We record the current 4545 // elapsed time before closing the scope so that time 4546 // taken for the destructor is NOT included in the 4547 // reported parallel time. 4548 } 4549 4550 G1GCPhaseTimes* phase_times = g1_policy()->phase_times(); 4551 4552 double par_time_ms = (end_par_time_sec - start_par_time_sec) * 1000.0; 4553 phase_times->record_par_time(par_time_ms); 4554 4555 double code_root_fixup_time_ms = 4556 (os::elapsedTime() - end_par_time_sec) * 1000.0; 4557 phase_times->record_code_root_fixup_time(code_root_fixup_time_ms); 4558 } 4559 4560 void G1CollectedHeap::post_evacuate_collection_set(EvacuationInfo& evacuation_info, G1ParScanThreadStateSet* per_thread_states) { 4561 // Process any discovered reference objects - we have 4562 // to do this _before_ we retire the GC alloc regions 4563 // as we may have to copy some 'reachable' referent 4564 // objects (and their reachable sub-graphs) that were 4565 // not copied during the pause. 4566 if (g1_policy()->should_process_references()) { 4567 preserve_cm_referents(per_thread_states); 4568 process_discovered_references(per_thread_states); 4569 } else { 4570 ref_processor_stw()->verify_no_references_recorded(); 4571 process_weak_jni_handles(); 4572 } 4573 4574 if (G1StringDedup::is_enabled()) { 4575 double fixup_start = os::elapsedTime(); 4576 4577 G1STWIsAliveClosure is_alive(this); 4578 G1KeepAliveClosure keep_alive(this); 4579 G1StringDedup::unlink_or_oops_do(&is_alive, &keep_alive, true, g1_policy()->phase_times()); 4580 4581 double fixup_time_ms = (os::elapsedTime() - fixup_start) * 1000.0; 4582 g1_policy()->phase_times()->record_string_dedup_fixup_time(fixup_time_ms); 4583 } 4584 4585 g1_rem_set()->cleanup_after_oops_into_collection_set_do(); 4586 4587 if (evacuation_failed()) { 4588 restore_after_evac_failure(); 4589 4590 // Reset the G1EvacuationFailureALot counters and flags 4591 // Note: the values are reset only when an actual 4592 // evacuation failure occurs. 4593 NOT_PRODUCT(reset_evacuation_should_fail();) 4594 } 4595 4596 _preserved_marks_set.assert_empty(); 4597 4598 // Enqueue any remaining references remaining on the STW 4599 // reference processor's discovered lists. We need to do 4600 // this after the card table is cleaned (and verified) as 4601 // the act of enqueueing entries on to the pending list 4602 // will log these updates (and dirty their associated 4603 // cards). We need these updates logged to update any 4604 // RSets. 4605 if (g1_policy()->should_process_references()) { 4606 enqueue_discovered_references(per_thread_states); 4607 } else { 4608 g1_policy()->phase_times()->record_ref_enq_time(0); 4609 } 4610 4611 _allocator->release_gc_alloc_regions(evacuation_info); 4612 4613 merge_per_thread_state_info(per_thread_states); 4614 4615 // Reset and re-enable the hot card cache. 4616 // Note the counts for the cards in the regions in the 4617 // collection set are reset when the collection set is freed. 4618 G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache(); 4619 hot_card_cache->reset_hot_cache(); 4620 hot_card_cache->set_use_cache(true); 4621 4622 purge_code_root_memory(); 4623 4624 redirty_logged_cards(); 4625 #if defined(COMPILER2) || INCLUDE_JVMCI 4626 DerivedPointerTable::update_pointers(); 4627 #endif 4628 } 4629 4630 void G1CollectedHeap::record_obj_copy_mem_stats() { 4631 g1_policy()->add_bytes_allocated_in_old_since_last_gc(_old_evac_stats.allocated() * HeapWordSize); 4632 4633 _gc_tracer_stw->report_evacuation_statistics(create_g1_evac_summary(&_survivor_evac_stats), 4634 create_g1_evac_summary(&_old_evac_stats)); 4635 } 4636 4637 void G1CollectedHeap::free_region(HeapRegion* hr, 4638 FreeRegionList* free_list, 4639 bool par, 4640 bool locked) { 4641 assert(!hr->is_free(), "the region should not be free"); 4642 assert(!hr->is_empty(), "the region should not be empty"); 4643 assert(_hrm.is_available(hr->hrm_index()), "region should be committed"); 4644 assert(free_list != NULL, "pre-condition"); 4645 4646 if (G1VerifyBitmaps) { 4647 MemRegion mr(hr->bottom(), hr->end()); 4648 concurrent_mark()->clearRangePrevBitmap(mr); 4649 } 4650 4651 // Clear the card counts for this region. 4652 // Note: we only need to do this if the region is not young 4653 // (since we don't refine cards in young regions). 4654 if (!hr->is_young()) { 4655 _cg1r->hot_card_cache()->reset_card_counts(hr); 4656 } 4657 hr->hr_clear(par, true /* clear_space */, locked /* locked */); 4658 free_list->add_ordered(hr); 4659 } 4660 4661 void G1CollectedHeap::free_humongous_region(HeapRegion* hr, 4662 FreeRegionList* free_list, 4663 bool par) { 4664 assert(hr->is_humongous(), "this is only for humongous regions"); 4665 assert(free_list != NULL, "pre-condition"); 4666 hr->clear_humongous(); 4667 free_region(hr, free_list, par); 4668 } 4669 4670 void G1CollectedHeap::remove_from_old_sets(const uint old_regions_removed, 4671 const uint humongous_regions_removed) { 4672 if (old_regions_removed > 0 || humongous_regions_removed > 0) { 4673 MutexLockerEx x(OldSets_lock, Mutex::_no_safepoint_check_flag); 4674 _old_set.bulk_remove(old_regions_removed); 4675 _humongous_set.bulk_remove(humongous_regions_removed); 4676 } 4677 4678 } 4679 4680 void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) { 4681 assert(list != NULL, "list can't be null"); 4682 if (!list->is_empty()) { 4683 MutexLockerEx x(FreeList_lock, Mutex::_no_safepoint_check_flag); 4684 _hrm.insert_list_into_free_list(list); 4685 } 4686 } 4687 4688 void G1CollectedHeap::decrement_summary_bytes(size_t bytes) { 4689 decrease_used(bytes); 4690 } 4691 4692 class G1ParScrubRemSetTask: public AbstractGangTask { 4693 protected: 4694 G1RemSet* _g1rs; 4695 HeapRegionClaimer _hrclaimer; 4696 4697 public: 4698 G1ParScrubRemSetTask(G1RemSet* g1_rs, uint num_workers) : 4699 AbstractGangTask("G1 ScrubRS"), 4700 _g1rs(g1_rs), 4701 _hrclaimer(num_workers) { 4702 } 4703 4704 void work(uint worker_id) { 4705 _g1rs->scrub(worker_id, &_hrclaimer); 4706 } 4707 }; 4708 4709 void G1CollectedHeap::scrub_rem_set() { 4710 uint num_workers = workers()->active_workers(); 4711 G1ParScrubRemSetTask g1_par_scrub_rs_task(g1_rem_set(), num_workers); 4712 workers()->run_task(&g1_par_scrub_rs_task); 4713 } 4714 4715 void G1CollectedHeap::free_collection_set(HeapRegion* cs_head, EvacuationInfo& evacuation_info, const size_t* surviving_young_words) { 4716 size_t pre_used = 0; 4717 FreeRegionList local_free_list("Local List for CSet Freeing"); 4718 4719 double young_time_ms = 0.0; 4720 double non_young_time_ms = 0.0; 4721 4722 // Since the collection set is a superset of the the young list, 4723 // all we need to do to clear the young list is clear its 4724 // head and length, and unlink any young regions in the code below 4725 _young_list->clear(); 4726 4727 G1Policy* policy = g1_policy(); 4728 4729 double start_sec = os::elapsedTime(); 4730 bool non_young = true; 4731 4732 HeapRegion* cur = cs_head; 4733 int age_bound = -1; 4734 size_t rs_lengths = 0; 4735 4736 while (cur != NULL) { 4737 assert(!is_on_master_free_list(cur), "sanity"); 4738 if (non_young) { 4739 if (cur->is_young()) { 4740 double end_sec = os::elapsedTime(); 4741 double elapsed_ms = (end_sec - start_sec) * 1000.0; 4742 non_young_time_ms += elapsed_ms; 4743 4744 start_sec = os::elapsedTime(); 4745 non_young = false; 4746 } 4747 } else { 4748 if (!cur->is_young()) { 4749 double end_sec = os::elapsedTime(); 4750 double elapsed_ms = (end_sec - start_sec) * 1000.0; 4751 young_time_ms += elapsed_ms; 4752 4753 start_sec = os::elapsedTime(); 4754 non_young = true; 4755 } 4756 } 4757 4758 rs_lengths += cur->rem_set()->occupied_locked(); 4759 4760 HeapRegion* next = cur->next_in_collection_set(); 4761 assert(cur->in_collection_set(), "bad CS"); 4762 cur->set_next_in_collection_set(NULL); 4763 clear_in_cset(cur); 4764 4765 if (cur->is_young()) { 4766 int index = cur->young_index_in_cset(); 4767 assert(index != -1, "invariant"); 4768 assert((uint) index < collection_set()->young_region_length(), "invariant"); 4769 size_t words_survived = surviving_young_words[index]; 4770 cur->record_surv_words_in_group(words_survived); 4771 4772 // At this point the we have 'popped' cur from the collection set 4773 // (linked via next_in_collection_set()) but it is still in the 4774 // young list (linked via next_young_region()). Clear the 4775 // _next_young_region field. 4776 cur->set_next_young_region(NULL); 4777 } else { 4778 int index = cur->young_index_in_cset(); 4779 assert(index == -1, "invariant"); 4780 } 4781 4782 assert( (cur->is_young() && cur->young_index_in_cset() > -1) || 4783 (!cur->is_young() && cur->young_index_in_cset() == -1), 4784 "invariant" ); 4785 4786 if (!cur->evacuation_failed()) { 4787 MemRegion used_mr = cur->used_region(); 4788 4789 // And the region is empty. 4790 assert(!used_mr.is_empty(), "Should not have empty regions in a CS."); 4791 pre_used += cur->used(); 4792 free_region(cur, &local_free_list, false /* par */, true /* locked */); 4793 } else { 4794 cur->uninstall_surv_rate_group(); 4795 if (cur->is_young()) { 4796 cur->set_young_index_in_cset(-1); 4797 } 4798 cur->set_evacuation_failed(false); 4799 // When moving a young gen region to old gen, we "allocate" that whole region 4800 // there. This is in addition to any already evacuated objects. Notify the 4801 // policy about that. 4802 // Old gen regions do not cause an additional allocation: both the objects 4803 // still in the region and the ones already moved are accounted for elsewhere. 4804 if (cur->is_young()) { 4805 policy->add_bytes_allocated_in_old_since_last_gc(HeapRegion::GrainBytes); 4806 } 4807 // The region is now considered to be old. 4808 cur->set_old(); 4809 // Do some allocation statistics accounting. Regions that failed evacuation 4810 // are always made old, so there is no need to update anything in the young 4811 // gen statistics, but we need to update old gen statistics. 4812 size_t used_words = cur->marked_bytes() / HeapWordSize; 4813 _old_evac_stats.add_failure_used_and_waste(used_words, HeapRegion::GrainWords - used_words); 4814 _old_set.add(cur); 4815 evacuation_info.increment_collectionset_used_after(cur->used()); 4816 } 4817 cur = next; 4818 } 4819 4820 evacuation_info.set_regions_freed(local_free_list.length()); 4821 policy->record_max_rs_lengths(rs_lengths); 4822 policy->cset_regions_freed(); 4823 4824 double end_sec = os::elapsedTime(); 4825 double elapsed_ms = (end_sec - start_sec) * 1000.0; 4826 4827 if (non_young) { 4828 non_young_time_ms += elapsed_ms; 4829 } else { 4830 young_time_ms += elapsed_ms; 4831 } 4832 4833 prepend_to_freelist(&local_free_list); 4834 decrement_summary_bytes(pre_used); 4835 policy->phase_times()->record_young_free_cset_time_ms(young_time_ms); 4836 policy->phase_times()->record_non_young_free_cset_time_ms(non_young_time_ms); 4837 } 4838 4839 class G1FreeHumongousRegionClosure : public HeapRegionClosure { 4840 private: 4841 FreeRegionList* _free_region_list; 4842 HeapRegionSet* _proxy_set; 4843 uint _humongous_regions_removed; 4844 size_t _freed_bytes; 4845 public: 4846 4847 G1FreeHumongousRegionClosure(FreeRegionList* free_region_list) : 4848 _free_region_list(free_region_list), _humongous_regions_removed(0), _freed_bytes(0) { 4849 } 4850 4851 virtual bool doHeapRegion(HeapRegion* r) { 4852 if (!r->is_starts_humongous()) { 4853 return false; 4854 } 4855 4856 G1CollectedHeap* g1h = G1CollectedHeap::heap(); 4857 4858 oop obj = (oop)r->bottom(); 4859 G1CMBitMap* next_bitmap = g1h->concurrent_mark()->nextMarkBitMap(); 4860 4861 // The following checks whether the humongous object is live are sufficient. 4862 // The main additional check (in addition to having a reference from the roots 4863 // or the young gen) is whether the humongous object has a remembered set entry. 4864 // 4865 // A humongous object cannot be live if there is no remembered set for it 4866 // because: 4867 // - there can be no references from within humongous starts regions referencing 4868 // the object because we never allocate other objects into them. 4869 // (I.e. there are no intra-region references that may be missed by the 4870 // remembered set) 4871 // - as soon there is a remembered set entry to the humongous starts region 4872 // (i.e. it has "escaped" to an old object) this remembered set entry will stay 4873 // until the end of a concurrent mark. 4874 // 4875 // It is not required to check whether the object has been found dead by marking 4876 // or not, in fact it would prevent reclamation within a concurrent cycle, as 4877 // all objects allocated during that time are considered live. 4878 // SATB marking is even more conservative than the remembered set. 4879 // So if at this point in the collection there is no remembered set entry, 4880 // nobody has a reference to it. 4881 // At the start of collection we flush all refinement logs, and remembered sets 4882 // are completely up-to-date wrt to references to the humongous object. 4883 // 4884 // Other implementation considerations: 4885 // - never consider object arrays at this time because they would pose 4886 // considerable effort for cleaning up the the remembered sets. This is 4887 // required because stale remembered sets might reference locations that 4888 // are currently allocated into. 4889 uint region_idx = r->hrm_index(); 4890 if (!g1h->is_humongous_reclaim_candidate(region_idx) || 4891 !r->rem_set()->is_empty()) { 4892 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", 4893 region_idx, 4894 (size_t)obj->size() * HeapWordSize, 4895 p2i(r->bottom()), 4896 r->rem_set()->occupied(), 4897 r->rem_set()->strong_code_roots_list_length(), 4898 next_bitmap->isMarked(r->bottom()), 4899 g1h->is_humongous_reclaim_candidate(region_idx), 4900 obj->is_typeArray() 4901 ); 4902 return false; 4903 } 4904 4905 guarantee(obj->is_typeArray(), 4906 "Only eagerly reclaiming type arrays is supported, but the object " 4907 PTR_FORMAT " is not.", p2i(r->bottom())); 4908 4909 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", 4910 region_idx, 4911 (size_t)obj->size() * HeapWordSize, 4912 p2i(r->bottom()), 4913 r->rem_set()->occupied(), 4914 r->rem_set()->strong_code_roots_list_length(), 4915 next_bitmap->isMarked(r->bottom()), 4916 g1h->is_humongous_reclaim_candidate(region_idx), 4917 obj->is_typeArray() 4918 ); 4919 4920 // Need to clear mark bit of the humongous object if already set. 4921 if (next_bitmap->isMarked(r->bottom())) { 4922 next_bitmap->clear(r->bottom()); 4923 } 4924 do { 4925 HeapRegion* next = g1h->next_region_in_humongous(r); 4926 _freed_bytes += r->used(); 4927 r->set_containing_set(NULL); 4928 _humongous_regions_removed++; 4929 g1h->free_humongous_region(r, _free_region_list, false); 4930 r = next; 4931 } while (r != NULL); 4932 4933 return false; 4934 } 4935 4936 uint humongous_free_count() { 4937 return _humongous_regions_removed; 4938 } 4939 4940 size_t bytes_freed() const { 4941 return _freed_bytes; 4942 } 4943 }; 4944 4945 void G1CollectedHeap::eagerly_reclaim_humongous_regions() { 4946 assert_at_safepoint(true); 4947 4948 if (!G1EagerReclaimHumongousObjects || 4949 (!_has_humongous_reclaim_candidates && !log_is_enabled(Debug, gc, humongous))) { 4950 g1_policy()->phase_times()->record_fast_reclaim_humongous_time_ms(0.0, 0); 4951 return; 4952 } 4953 4954 double start_time = os::elapsedTime(); 4955 4956 FreeRegionList local_cleanup_list("Local Humongous Cleanup List"); 4957 4958 G1FreeHumongousRegionClosure cl(&local_cleanup_list); 4959 heap_region_iterate(&cl); 4960 4961 remove_from_old_sets(0, cl.humongous_free_count()); 4962 4963 G1HRPrinter* hrp = hr_printer(); 4964 if (hrp->is_active()) { 4965 FreeRegionListIterator iter(&local_cleanup_list); 4966 while (iter.more_available()) { 4967 HeapRegion* hr = iter.get_next(); 4968 hrp->cleanup(hr); 4969 } 4970 } 4971 4972 prepend_to_freelist(&local_cleanup_list); 4973 decrement_summary_bytes(cl.bytes_freed()); 4974 4975 g1_policy()->phase_times()->record_fast_reclaim_humongous_time_ms((os::elapsedTime() - start_time) * 1000.0, 4976 cl.humongous_free_count()); 4977 } 4978 4979 // This routine is similar to the above but does not record 4980 // any policy statistics or update free lists; we are abandoning 4981 // the current incremental collection set in preparation of a 4982 // full collection. After the full GC we will start to build up 4983 // the incremental collection set again. 4984 // This is only called when we're doing a full collection 4985 // and is immediately followed by the tearing down of the young list. 4986 4987 void G1CollectedHeap::abandon_collection_set(HeapRegion* cs_head) { 4988 HeapRegion* cur = cs_head; 4989 4990 while (cur != NULL) { 4991 HeapRegion* next = cur->next_in_collection_set(); 4992 assert(cur->in_collection_set(), "bad CS"); 4993 cur->set_next_in_collection_set(NULL); 4994 clear_in_cset(cur); 4995 cur->set_young_index_in_cset(-1); 4996 cur = next; 4997 } 4998 } 4999 5000 void G1CollectedHeap::set_free_regions_coming() { 5001 log_develop_trace(gc, freelist)("G1ConcRegionFreeing [cm thread] : setting free regions coming"); 5002 5003 assert(!free_regions_coming(), "pre-condition"); 5004 _free_regions_coming = true; 5005 } 5006 5007 void G1CollectedHeap::reset_free_regions_coming() { 5008 assert(free_regions_coming(), "pre-condition"); 5009 5010 { 5011 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag); 5012 _free_regions_coming = false; 5013 SecondaryFreeList_lock->notify_all(); 5014 } 5015 5016 log_develop_trace(gc, freelist)("G1ConcRegionFreeing [cm thread] : reset free regions coming"); 5017 } 5018 5019 void G1CollectedHeap::wait_while_free_regions_coming() { 5020 // Most of the time we won't have to wait, so let's do a quick test 5021 // first before we take the lock. 5022 if (!free_regions_coming()) { 5023 return; 5024 } 5025 5026 log_develop_trace(gc, freelist)("G1ConcRegionFreeing [other] : waiting for free regions"); 5027 5028 { 5029 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag); 5030 while (free_regions_coming()) { 5031 SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag); 5032 } 5033 } 5034 5035 log_develop_trace(gc, freelist)("G1ConcRegionFreeing [other] : done waiting for free regions"); 5036 } 5037 5038 bool G1CollectedHeap::is_old_gc_alloc_region(HeapRegion* hr) { 5039 return _allocator->is_retained_old_region(hr); 5040 } 5041 5042 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) { 5043 _young_list->push_region(hr); 5044 } 5045 5046 class NoYoungRegionsClosure: public HeapRegionClosure { 5047 private: 5048 bool _success; 5049 public: 5050 NoYoungRegionsClosure() : _success(true) { } 5051 bool doHeapRegion(HeapRegion* r) { 5052 if (r->is_young()) { 5053 log_error(gc, verify)("Region [" PTR_FORMAT ", " PTR_FORMAT ") tagged as young", 5054 p2i(r->bottom()), p2i(r->end())); 5055 _success = false; 5056 } 5057 return false; 5058 } 5059 bool success() { return _success; } 5060 }; 5061 5062 bool G1CollectedHeap::check_young_list_empty(bool check_heap) { 5063 bool ret = _young_list->check_list_empty(); 5064 5065 if (check_heap) { 5066 NoYoungRegionsClosure closure; 5067 heap_region_iterate(&closure); 5068 ret = ret && closure.success(); 5069 } 5070 5071 return ret; 5072 } 5073 5074 class TearDownRegionSetsClosure : public HeapRegionClosure { 5075 private: 5076 HeapRegionSet *_old_set; 5077 5078 public: 5079 TearDownRegionSetsClosure(HeapRegionSet* old_set) : _old_set(old_set) { } 5080 5081 bool doHeapRegion(HeapRegion* r) { 5082 if (r->is_old()) { 5083 _old_set->remove(r); 5084 } else { 5085 // We ignore free regions, we'll empty the free list afterwards. 5086 // We ignore young regions, we'll empty the young list afterwards. 5087 // We ignore humongous regions, we're not tearing down the 5088 // humongous regions set. 5089 assert(r->is_free() || r->is_young() || r->is_humongous(), 5090 "it cannot be another type"); 5091 } 5092 return false; 5093 } 5094 5095 ~TearDownRegionSetsClosure() { 5096 assert(_old_set->is_empty(), "post-condition"); 5097 } 5098 }; 5099 5100 void G1CollectedHeap::tear_down_region_sets(bool free_list_only) { 5101 assert_at_safepoint(true /* should_be_vm_thread */); 5102 5103 if (!free_list_only) { 5104 TearDownRegionSetsClosure cl(&_old_set); 5105 heap_region_iterate(&cl); 5106 5107 // Note that emptying the _young_list is postponed and instead done as 5108 // the first step when rebuilding the regions sets again. The reason for 5109 // this is that during a full GC string deduplication needs to know if 5110 // a collected region was young or old when the full GC was initiated. 5111 } 5112 _hrm.remove_all_free_regions(); 5113 } 5114 5115 void G1CollectedHeap::increase_used(size_t bytes) { 5116 _summary_bytes_used += bytes; 5117 } 5118 5119 void G1CollectedHeap::decrease_used(size_t bytes) { 5120 assert(_summary_bytes_used >= bytes, 5121 "invariant: _summary_bytes_used: " SIZE_FORMAT " should be >= bytes: " SIZE_FORMAT, 5122 _summary_bytes_used, bytes); 5123 _summary_bytes_used -= bytes; 5124 } 5125 5126 void G1CollectedHeap::set_used(size_t bytes) { 5127 _summary_bytes_used = bytes; 5128 } 5129 5130 class RebuildRegionSetsClosure : public HeapRegionClosure { 5131 private: 5132 bool _free_list_only; 5133 HeapRegionSet* _old_set; 5134 HeapRegionManager* _hrm; 5135 size_t _total_used; 5136 5137 public: 5138 RebuildRegionSetsClosure(bool free_list_only, 5139 HeapRegionSet* old_set, HeapRegionManager* hrm) : 5140 _free_list_only(free_list_only), 5141 _old_set(old_set), _hrm(hrm), _total_used(0) { 5142 assert(_hrm->num_free_regions() == 0, "pre-condition"); 5143 if (!free_list_only) { 5144 assert(_old_set->is_empty(), "pre-condition"); 5145 } 5146 } 5147 5148 bool doHeapRegion(HeapRegion* r) { 5149 if (r->is_empty()) { 5150 // Add free regions to the free list 5151 r->set_free(); 5152 r->set_allocation_context(AllocationContext::system()); 5153 _hrm->insert_into_free_list(r); 5154 } else if (!_free_list_only) { 5155 assert(!r->is_young(), "we should not come across young regions"); 5156 5157 if (r->is_humongous()) { 5158 // We ignore humongous regions. We left the humongous set unchanged. 5159 } else { 5160 // Objects that were compacted would have ended up on regions 5161 // that were previously old or free. Archive regions (which are 5162 // old) will not have been touched. 5163 assert(r->is_free() || r->is_old(), "invariant"); 5164 // We now consider them old, so register as such. Leave 5165 // archive regions set that way, however, while still adding 5166 // them to the old set. 5167 if (!r->is_archive()) { 5168 r->set_old(); 5169 } 5170 _old_set->add(r); 5171 } 5172 _total_used += r->used(); 5173 } 5174 5175 return false; 5176 } 5177 5178 size_t total_used() { 5179 return _total_used; 5180 } 5181 }; 5182 5183 void G1CollectedHeap::rebuild_region_sets(bool free_list_only) { 5184 assert_at_safepoint(true /* should_be_vm_thread */); 5185 5186 if (!free_list_only) { 5187 _young_list->empty_list(); 5188 } 5189 5190 RebuildRegionSetsClosure cl(free_list_only, &_old_set, &_hrm); 5191 heap_region_iterate(&cl); 5192 5193 if (!free_list_only) { 5194 set_used(cl.total_used()); 5195 if (_archive_allocator != NULL) { 5196 _archive_allocator->clear_used(); 5197 } 5198 } 5199 assert(used_unlocked() == recalculate_used(), 5200 "inconsistent used_unlocked(), " 5201 "value: " SIZE_FORMAT " recalculated: " SIZE_FORMAT, 5202 used_unlocked(), recalculate_used()); 5203 } 5204 5205 void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) { 5206 _refine_cte_cl->set_concurrent(concurrent); 5207 } 5208 5209 bool G1CollectedHeap::is_in_closed_subset(const void* p) const { 5210 HeapRegion* hr = heap_region_containing(p); 5211 return hr->is_in(p); 5212 } 5213 5214 // Methods for the mutator alloc region 5215 5216 HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size, 5217 bool force) { 5218 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */); 5219 assert(!force || g1_policy()->can_expand_young_list(), 5220 "if force is true we should be able to expand the young list"); 5221 bool should_allocate = g1_policy()->should_allocate_mutator_region(); 5222 if (force || should_allocate) { 5223 HeapRegion* new_alloc_region = new_region(word_size, 5224 false /* is_old */, 5225 false /* do_expand */); 5226 if (new_alloc_region != NULL) { 5227 set_region_short_lived_locked(new_alloc_region); 5228 _hr_printer.alloc(new_alloc_region, !should_allocate); 5229 _verifier->check_bitmaps("Mutator Region Allocation", new_alloc_region); 5230 return new_alloc_region; 5231 } 5232 } 5233 return NULL; 5234 } 5235 5236 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region, 5237 size_t allocated_bytes) { 5238 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */); 5239 assert(alloc_region->is_eden(), "all mutator alloc regions should be eden"); 5240 5241 collection_set()->add_eden_region(alloc_region); 5242 increase_used(allocated_bytes); 5243 _hr_printer.retire(alloc_region); 5244 // We update the eden sizes here, when the region is retired, 5245 // instead of when it's allocated, since this is the point that its 5246 // used space has been recored in _summary_bytes_used. 5247 g1mm()->update_eden_size(); 5248 } 5249 5250 // Methods for the GC alloc regions 5251 5252 bool G1CollectedHeap::has_more_regions(InCSetState dest) { 5253 if (dest.is_old()) { 5254 return true; 5255 } else { 5256 return young_list()->survivor_length() < g1_policy()->max_survivor_regions(); 5257 } 5258 } 5259 5260 HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size, InCSetState dest) { 5261 assert(FreeList_lock->owned_by_self(), "pre-condition"); 5262 5263 if (!has_more_regions(dest)) { 5264 return NULL; 5265 } 5266 5267 const bool is_survivor = dest.is_young(); 5268 5269 HeapRegion* new_alloc_region = new_region(word_size, 5270 !is_survivor, 5271 true /* do_expand */); 5272 if (new_alloc_region != NULL) { 5273 // We really only need to do this for old regions given that we 5274 // should never scan survivors. But it doesn't hurt to do it 5275 // for survivors too. 5276 new_alloc_region->record_timestamp(); 5277 if (is_survivor) { 5278 new_alloc_region->set_survivor(); 5279 young_list()->add_survivor_region(new_alloc_region); 5280 _verifier->check_bitmaps("Survivor Region Allocation", new_alloc_region); 5281 } else { 5282 new_alloc_region->set_old(); 5283 _verifier->check_bitmaps("Old Region Allocation", new_alloc_region); 5284 } 5285 _hr_printer.alloc(new_alloc_region); 5286 bool during_im = collector_state()->during_initial_mark_pause(); 5287 new_alloc_region->note_start_of_copying(during_im); 5288 return new_alloc_region; 5289 } 5290 return NULL; 5291 } 5292 5293 void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region, 5294 size_t allocated_bytes, 5295 InCSetState dest) { 5296 bool during_im = collector_state()->during_initial_mark_pause(); 5297 alloc_region->note_end_of_copying(during_im); 5298 g1_policy()->record_bytes_copied_during_gc(allocated_bytes); 5299 if (dest.is_old()) { 5300 _old_set.add(alloc_region); 5301 } 5302 _hr_printer.retire(alloc_region); 5303 } 5304 5305 HeapRegion* G1CollectedHeap::alloc_highest_free_region() { 5306 bool expanded = false; 5307 uint index = _hrm.find_highest_free(&expanded); 5308 5309 if (index != G1_NO_HRM_INDEX) { 5310 if (expanded) { 5311 log_debug(gc, ergo, heap)("Attempt heap expansion (requested address range outside heap bounds). region size: " SIZE_FORMAT "B", 5312 HeapRegion::GrainWords * HeapWordSize); 5313 } 5314 _hrm.allocate_free_regions_starting_at(index, 1); 5315 return region_at(index); 5316 } 5317 return NULL; 5318 } 5319 5320 // Optimized nmethod scanning 5321 5322 class RegisterNMethodOopClosure: public OopClosure { 5323 G1CollectedHeap* _g1h; 5324 nmethod* _nm; 5325 5326 template <class T> void do_oop_work(T* p) { 5327 T heap_oop = oopDesc::load_heap_oop(p); 5328 if (!oopDesc::is_null(heap_oop)) { 5329 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop); 5330 HeapRegion* hr = _g1h->heap_region_containing(obj); 5331 assert(!hr->is_continues_humongous(), 5332 "trying to add code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT 5333 " starting at " HR_FORMAT, 5334 p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())); 5335 5336 // HeapRegion::add_strong_code_root_locked() avoids adding duplicate entries. 5337 hr->add_strong_code_root_locked(_nm); 5338 } 5339 } 5340 5341 public: 5342 RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) : 5343 _g1h(g1h), _nm(nm) {} 5344 5345 void do_oop(oop* p) { do_oop_work(p); } 5346 void do_oop(narrowOop* p) { do_oop_work(p); } 5347 }; 5348 5349 class UnregisterNMethodOopClosure: public OopClosure { 5350 G1CollectedHeap* _g1h; 5351 nmethod* _nm; 5352 5353 template <class T> void do_oop_work(T* p) { 5354 T heap_oop = oopDesc::load_heap_oop(p); 5355 if (!oopDesc::is_null(heap_oop)) { 5356 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop); 5357 HeapRegion* hr = _g1h->heap_region_containing(obj); 5358 assert(!hr->is_continues_humongous(), 5359 "trying to remove code root " PTR_FORMAT " in continuation of humongous region " HR_FORMAT 5360 " starting at " HR_FORMAT, 5361 p2i(_nm), HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region())); 5362 5363 hr->remove_strong_code_root(_nm); 5364 } 5365 } 5366 5367 public: 5368 UnregisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) : 5369 _g1h(g1h), _nm(nm) {} 5370 5371 void do_oop(oop* p) { do_oop_work(p); } 5372 void do_oop(narrowOop* p) { do_oop_work(p); } 5373 }; 5374 5375 void G1CollectedHeap::register_nmethod(nmethod* nm) { 5376 CollectedHeap::register_nmethod(nm); 5377 5378 guarantee(nm != NULL, "sanity"); 5379 RegisterNMethodOopClosure reg_cl(this, nm); 5380 nm->oops_do(®_cl); 5381 } 5382 5383 void G1CollectedHeap::unregister_nmethod(nmethod* nm) { 5384 CollectedHeap::unregister_nmethod(nm); 5385 5386 guarantee(nm != NULL, "sanity"); 5387 UnregisterNMethodOopClosure reg_cl(this, nm); 5388 nm->oops_do(®_cl, true); 5389 } 5390 5391 void G1CollectedHeap::purge_code_root_memory() { 5392 double purge_start = os::elapsedTime(); 5393 G1CodeRootSet::purge(); 5394 double purge_time_ms = (os::elapsedTime() - purge_start) * 1000.0; 5395 g1_policy()->phase_times()->record_strong_code_root_purge_time(purge_time_ms); 5396 } 5397 5398 class RebuildStrongCodeRootClosure: public CodeBlobClosure { 5399 G1CollectedHeap* _g1h; 5400 5401 public: 5402 RebuildStrongCodeRootClosure(G1CollectedHeap* g1h) : 5403 _g1h(g1h) {} 5404 5405 void do_code_blob(CodeBlob* cb) { 5406 nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL; 5407 if (nm == NULL) { 5408 return; 5409 } 5410 5411 if (ScavengeRootsInCode) { 5412 _g1h->register_nmethod(nm); 5413 } 5414 } 5415 }; 5416 5417 void G1CollectedHeap::rebuild_strong_code_roots() { 5418 RebuildStrongCodeRootClosure blob_cl(this); 5419 CodeCache::blobs_do(&blob_cl); 5420 }