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