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