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