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