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