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