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