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