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