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