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