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