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