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