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