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