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