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