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