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