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 (unsigned int 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 void G1RegionMappingChangedListener::reset_from_card_cache(uint start_idx, size_t num_regions) { 355 HeapRegionRemSet::invalidate_from_card_cache(start_idx, num_regions); 356 } 357 358 void G1RegionMappingChangedListener::on_commit(uint start_idx, size_t num_regions, bool zero_filled) { 359 // The from card cache is not the memory that is actually committed. So we cannot 360 // take advantage of the zero_filled parameter. 361 reset_from_card_cache(start_idx, num_regions); 362 } 363 364 ////////////////////// G1CollectedHeap methods //////////////////////////////// 365 366 // Records the fact that a marking phase is no longer in progress. 367 void G1CollectedHeap::set_marking_complete() { 368 g1_policy()->collector_state()->set_marking_complete(); 369 } 370 371 // Records the fact that a marking phase has commenced. 372 void G1CollectedHeap::set_marking_started() { 373 g1_policy()->collector_state()->set_marking_started(); 374 } 375 376 // Returns whether a marking phase is currently in progress. 377 bool G1CollectedHeap::mark_in_progress() { 378 return g1_policy()->collector_state()->mark_in_progress(); 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 unsigned int dummy_gc_count_before; 786 int 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 (int try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) { 797 unsigned int 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 unsigned int *gc_count_before_ret, 850 int* 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 unsigned int 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 unsigned int * gc_count_before_ret, 966 int* 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 unsigned int 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()->collector_state()->set_initiate_conc_mark_if_possible(true); 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()->collector_state()->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 _cg1r(NULL), 1791 _g1mm(NULL), 1792 _refine_cte_cl(NULL), 1793 _full_collection(false), 1794 _secondary_free_list("Secondary Free List", new SecondaryFreeRegionListMtSafeChecker()), 1795 _old_set("Old Set", false /* humongous */, new OldRegionSetMtSafeChecker()), 1796 _humongous_set("Master Humongous Set", true /* humongous */, new HumongousRegionSetMtSafeChecker()), 1797 _humongous_is_live(), 1798 _has_humongous_reclaim_candidates(false), 1799 _free_regions_coming(false), 1800 _young_list(new YoungList(this)), 1801 _gc_time_stamp(0), 1802 _survivor_plab_stats(YoungPLABSize, PLABWeight), 1803 _old_plab_stats(OldPLABSize, PLABWeight), 1804 _expand_heap_after_alloc_failure(true), 1805 _surviving_young_words(NULL), 1806 _old_marking_cycles_started(0), 1807 _old_marking_cycles_completed(0), 1808 _concurrent_cycle_started(false), 1809 _heap_summary_sent(false), 1810 _in_cset_fast_test(), 1811 _dirty_cards_region_list(NULL), 1812 _worker_cset_start_region(NULL), 1813 _worker_cset_start_region_time_stamp(NULL), 1814 _gc_timer_stw(new (ResourceObj::C_HEAP, mtGC) STWGCTimer()), 1815 _gc_timer_cm(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()), 1816 _gc_tracer_stw(new (ResourceObj::C_HEAP, mtGC) G1NewTracer()), 1817 _gc_tracer_cm(new (ResourceObj::C_HEAP, mtGC) G1OldTracer()) { 1818 1819 _g1h = this; 1820 if (_process_strong_tasks == NULL || !_process_strong_tasks->valid()) { 1821 vm_exit_during_initialization("Failed necessary allocation."); 1822 } 1823 1824 _allocator = G1Allocator::create_allocator(_g1h); 1825 _humongous_object_threshold_in_words = HeapRegion::GrainWords / 2; 1826 1827 int n_queues = MAX2((int)ParallelGCThreads, 1); 1828 _task_queues = new RefToScanQueueSet(n_queues); 1829 1830 uint n_rem_sets = HeapRegionRemSet::num_par_rem_sets(); 1831 assert(n_rem_sets > 0, "Invariant."); 1832 1833 _worker_cset_start_region = NEW_C_HEAP_ARRAY(HeapRegion*, n_queues, mtGC); 1834 _worker_cset_start_region_time_stamp = NEW_C_HEAP_ARRAY(unsigned int, n_queues, mtGC); 1835 _evacuation_failed_info_array = NEW_C_HEAP_ARRAY(EvacuationFailedInfo, n_queues, mtGC); 1836 1837 for (int i = 0; i < n_queues; i++) { 1838 RefToScanQueue* q = new RefToScanQueue(); 1839 q->initialize(); 1840 _task_queues->register_queue(i, q); 1841 ::new (&_evacuation_failed_info_array[i]) EvacuationFailedInfo(); 1842 } 1843 clear_cset_start_regions(); 1844 1845 // Initialize the G1EvacuationFailureALot counters and flags. 1846 NOT_PRODUCT(reset_evacuation_should_fail();) 1847 1848 guarantee(_task_queues != NULL, "task_queues allocation failure."); 1849 } 1850 1851 jint G1CollectedHeap::initialize() { 1852 CollectedHeap::pre_initialize(); 1853 os::enable_vtime(); 1854 1855 G1Log::init(); 1856 1857 // Necessary to satisfy locking discipline assertions. 1858 1859 MutexLocker x(Heap_lock); 1860 1861 // We have to initialize the printer before committing the heap, as 1862 // it will be used then. 1863 _hr_printer.set_active(G1PrintHeapRegions); 1864 1865 // While there are no constraints in the GC code that HeapWordSize 1866 // be any particular value, there are multiple other areas in the 1867 // system which believe this to be true (e.g. oop->object_size in some 1868 // cases incorrectly returns the size in wordSize units rather than 1869 // HeapWordSize). 1870 guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize"); 1871 1872 size_t init_byte_size = collector_policy()->initial_heap_byte_size(); 1873 size_t max_byte_size = collector_policy()->max_heap_byte_size(); 1874 size_t heap_alignment = collector_policy()->heap_alignment(); 1875 1876 // Ensure that the sizes are properly aligned. 1877 Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap"); 1878 Universe::check_alignment(max_byte_size, HeapRegion::GrainBytes, "g1 heap"); 1879 Universe::check_alignment(max_byte_size, heap_alignment, "g1 heap"); 1880 1881 _refine_cte_cl = new RefineCardTableEntryClosure(); 1882 1883 _cg1r = new ConcurrentG1Refine(this, _refine_cte_cl); 1884 1885 // Reserve the maximum. 1886 1887 // When compressed oops are enabled, the preferred heap base 1888 // is calculated by subtracting the requested size from the 1889 // 32Gb boundary and using the result as the base address for 1890 // heap reservation. If the requested size is not aligned to 1891 // HeapRegion::GrainBytes (i.e. the alignment that is passed 1892 // into the ReservedHeapSpace constructor) then the actual 1893 // base of the reserved heap may end up differing from the 1894 // address that was requested (i.e. the preferred heap base). 1895 // If this happens then we could end up using a non-optimal 1896 // compressed oops mode. 1897 1898 ReservedSpace heap_rs = Universe::reserve_heap(max_byte_size, 1899 heap_alignment); 1900 1901 initialize_reserved_region((HeapWord*)heap_rs.base(), (HeapWord*)(heap_rs.base() + heap_rs.size())); 1902 1903 // Create the barrier set for the entire reserved region. 1904 G1SATBCardTableLoggingModRefBS* bs 1905 = new G1SATBCardTableLoggingModRefBS(reserved_region()); 1906 bs->initialize(); 1907 assert(bs->is_a(BarrierSet::G1SATBCTLogging), "sanity"); 1908 set_barrier_set(bs); 1909 1910 // Also create a G1 rem set. 1911 _g1_rem_set = new G1RemSet(this, g1_barrier_set()); 1912 1913 // Carve out the G1 part of the heap. 1914 1915 ReservedSpace g1_rs = heap_rs.first_part(max_byte_size); 1916 G1RegionToSpaceMapper* heap_storage = 1917 G1RegionToSpaceMapper::create_mapper(g1_rs, 1918 UseLargePages ? os::large_page_size() : os::vm_page_size(), 1919 HeapRegion::GrainBytes, 1920 1, 1921 mtJavaHeap); 1922 heap_storage->set_mapping_changed_listener(&_listener); 1923 1924 // Reserve space for the block offset table. We do not support automatic uncommit 1925 // for the card table at this time. BOT only. 1926 ReservedSpace bot_rs(G1BlockOffsetSharedArray::compute_size(g1_rs.size() / HeapWordSize)); 1927 G1RegionToSpaceMapper* bot_storage = 1928 G1RegionToSpaceMapper::create_mapper(bot_rs, 1929 os::vm_page_size(), 1930 HeapRegion::GrainBytes, 1931 G1BlockOffsetSharedArray::N_bytes, 1932 mtGC); 1933 1934 ReservedSpace cardtable_rs(G1SATBCardTableLoggingModRefBS::compute_size(g1_rs.size() / HeapWordSize)); 1935 G1RegionToSpaceMapper* cardtable_storage = 1936 G1RegionToSpaceMapper::create_mapper(cardtable_rs, 1937 os::vm_page_size(), 1938 HeapRegion::GrainBytes, 1939 G1BlockOffsetSharedArray::N_bytes, 1940 mtGC); 1941 1942 // Reserve space for the card counts table. 1943 ReservedSpace card_counts_rs(G1BlockOffsetSharedArray::compute_size(g1_rs.size() / HeapWordSize)); 1944 G1RegionToSpaceMapper* card_counts_storage = 1945 G1RegionToSpaceMapper::create_mapper(card_counts_rs, 1946 os::vm_page_size(), 1947 HeapRegion::GrainBytes, 1948 G1BlockOffsetSharedArray::N_bytes, 1949 mtGC); 1950 1951 // Reserve space for prev and next bitmap. 1952 size_t bitmap_size = CMBitMap::compute_size(g1_rs.size()); 1953 1954 ReservedSpace prev_bitmap_rs(ReservedSpace::allocation_align_size_up(bitmap_size)); 1955 G1RegionToSpaceMapper* prev_bitmap_storage = 1956 G1RegionToSpaceMapper::create_mapper(prev_bitmap_rs, 1957 os::vm_page_size(), 1958 HeapRegion::GrainBytes, 1959 CMBitMap::mark_distance(), 1960 mtGC); 1961 1962 ReservedSpace next_bitmap_rs(ReservedSpace::allocation_align_size_up(bitmap_size)); 1963 G1RegionToSpaceMapper* next_bitmap_storage = 1964 G1RegionToSpaceMapper::create_mapper(next_bitmap_rs, 1965 os::vm_page_size(), 1966 HeapRegion::GrainBytes, 1967 CMBitMap::mark_distance(), 1968 mtGC); 1969 1970 _hrm.initialize(heap_storage, prev_bitmap_storage, next_bitmap_storage, bot_storage, cardtable_storage, card_counts_storage); 1971 g1_barrier_set()->initialize(cardtable_storage); 1972 // Do later initialization work for concurrent refinement. 1973 _cg1r->init(card_counts_storage); 1974 1975 // 6843694 - ensure that the maximum region index can fit 1976 // in the remembered set structures. 1977 const uint max_region_idx = (1U << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1; 1978 guarantee((max_regions() - 1) <= max_region_idx, "too many regions"); 1979 1980 size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1; 1981 guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized"); 1982 guarantee(HeapRegion::CardsPerRegion < max_cards_per_region, 1983 "too many cards per region"); 1984 1985 FreeRegionList::set_unrealistically_long_length(max_regions() + 1); 1986 1987 _bot_shared = new G1BlockOffsetSharedArray(reserved_region(), bot_storage); 1988 1989 _g1h = this; 1990 1991 _in_cset_fast_test.initialize(_hrm.reserved().start(), _hrm.reserved().end(), HeapRegion::GrainBytes); 1992 _humongous_is_live.initialize(_hrm.reserved().start(), _hrm.reserved().end(), HeapRegion::GrainBytes); 1993 1994 // Create the ConcurrentMark data structure and thread. 1995 // (Must do this late, so that "max_regions" is defined.) 1996 _cm = new ConcurrentMark(this, prev_bitmap_storage, next_bitmap_storage); 1997 if (_cm == NULL || !_cm->completed_initialization()) { 1998 vm_shutdown_during_initialization("Could not create/initialize ConcurrentMark"); 1999 return JNI_ENOMEM; 2000 } 2001 _cmThread = _cm->cmThread(); 2002 2003 // Initialize the from_card cache structure of HeapRegionRemSet. 2004 HeapRegionRemSet::init_heap(max_regions()); 2005 2006 // Now expand into the initial heap size. 2007 if (!expand(init_byte_size)) { 2008 vm_shutdown_during_initialization("Failed to allocate initial heap."); 2009 return JNI_ENOMEM; 2010 } 2011 2012 // Perform any initialization actions delegated to the policy. 2013 g1_policy()->init(); 2014 2015 JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon, 2016 SATB_Q_FL_lock, 2017 G1SATBProcessCompletedThreshold, 2018 Shared_SATB_Q_lock); 2019 2020 JavaThread::dirty_card_queue_set().initialize(_refine_cte_cl, 2021 DirtyCardQ_CBL_mon, 2022 DirtyCardQ_FL_lock, 2023 concurrent_g1_refine()->yellow_zone(), 2024 concurrent_g1_refine()->red_zone(), 2025 Shared_DirtyCardQ_lock); 2026 2027 dirty_card_queue_set().initialize(NULL, // Should never be called by the Java code 2028 DirtyCardQ_CBL_mon, 2029 DirtyCardQ_FL_lock, 2030 -1, // never trigger processing 2031 -1, // no limit on length 2032 Shared_DirtyCardQ_lock, 2033 &JavaThread::dirty_card_queue_set()); 2034 2035 // Initialize the card queue set used to hold cards containing 2036 // references into the collection set. 2037 _into_cset_dirty_card_queue_set.initialize(NULL, // Should never be called by the Java code 2038 DirtyCardQ_CBL_mon, 2039 DirtyCardQ_FL_lock, 2040 -1, // never trigger processing 2041 -1, // no limit on length 2042 Shared_DirtyCardQ_lock, 2043 &JavaThread::dirty_card_queue_set()); 2044 2045 // In case we're keeping closure specialization stats, initialize those 2046 // counts and that mechanism. 2047 SpecializationStats::clear(); 2048 2049 // Here we allocate the dummy HeapRegion that is required by the 2050 // G1AllocRegion class. 2051 HeapRegion* dummy_region = _hrm.get_dummy_region(); 2052 2053 // We'll re-use the same region whether the alloc region will 2054 // require BOT updates or not and, if it doesn't, then a non-young 2055 // region will complain that it cannot support allocations without 2056 // BOT updates. So we'll tag the dummy region as eden to avoid that. 2057 dummy_region->set_eden(); 2058 // Make sure it's full. 2059 dummy_region->set_top(dummy_region->end()); 2060 G1AllocRegion::setup(this, dummy_region); 2061 2062 _allocator->init_mutator_alloc_region(); 2063 2064 // Do create of the monitoring and management support so that 2065 // values in the heap have been properly initialized. 2066 _g1mm = new G1MonitoringSupport(this); 2067 2068 G1StringDedup::initialize(); 2069 2070 return JNI_OK; 2071 } 2072 2073 void G1CollectedHeap::stop() { 2074 // Stop all concurrent threads. We do this to make sure these threads 2075 // do not continue to execute and access resources (e.g. gclog_or_tty) 2076 // that are destroyed during shutdown. 2077 _cg1r->stop(); 2078 _cmThread->stop(); 2079 if (G1StringDedup::is_enabled()) { 2080 G1StringDedup::stop(); 2081 } 2082 } 2083 2084 void G1CollectedHeap::clear_humongous_is_live_table() { 2085 guarantee(G1EagerReclaimHumongousObjects, "Should only be called if true"); 2086 _humongous_is_live.clear(); 2087 } 2088 2089 size_t G1CollectedHeap::conservative_max_heap_alignment() { 2090 return HeapRegion::max_region_size(); 2091 } 2092 2093 void G1CollectedHeap::ref_processing_init() { 2094 // Reference processing in G1 currently works as follows: 2095 // 2096 // * There are two reference processor instances. One is 2097 // used to record and process discovered references 2098 // during concurrent marking; the other is used to 2099 // record and process references during STW pauses 2100 // (both full and incremental). 2101 // * Both ref processors need to 'span' the entire heap as 2102 // the regions in the collection set may be dotted around. 2103 // 2104 // * For the concurrent marking ref processor: 2105 // * Reference discovery is enabled at initial marking. 2106 // * Reference discovery is disabled and the discovered 2107 // references processed etc during remarking. 2108 // * Reference discovery is MT (see below). 2109 // * Reference discovery requires a barrier (see below). 2110 // * Reference processing may or may not be MT 2111 // (depending on the value of ParallelRefProcEnabled 2112 // and ParallelGCThreads). 2113 // * A full GC disables reference discovery by the CM 2114 // ref processor and abandons any entries on it's 2115 // discovered lists. 2116 // 2117 // * For the STW processor: 2118 // * Non MT discovery is enabled at the start of a full GC. 2119 // * Processing and enqueueing during a full GC is non-MT. 2120 // * During a full GC, references are processed after marking. 2121 // 2122 // * Discovery (may or may not be MT) is enabled at the start 2123 // of an incremental evacuation pause. 2124 // * References are processed near the end of a STW evacuation pause. 2125 // * For both types of GC: 2126 // * Discovery is atomic - i.e. not concurrent. 2127 // * Reference discovery will not need a barrier. 2128 2129 SharedHeap::ref_processing_init(); 2130 MemRegion mr = reserved_region(); 2131 2132 // Concurrent Mark ref processor 2133 _ref_processor_cm = 2134 new ReferenceProcessor(mr, // span 2135 ParallelRefProcEnabled && (ParallelGCThreads > 1), 2136 // mt processing 2137 (int) ParallelGCThreads, 2138 // degree of mt processing 2139 (ParallelGCThreads > 1) || (ConcGCThreads > 1), 2140 // mt discovery 2141 (int) MAX2(ParallelGCThreads, ConcGCThreads), 2142 // degree of mt discovery 2143 false, 2144 // Reference discovery is not atomic 2145 &_is_alive_closure_cm); 2146 // is alive closure 2147 // (for efficiency/performance) 2148 2149 // STW ref processor 2150 _ref_processor_stw = 2151 new ReferenceProcessor(mr, // span 2152 ParallelRefProcEnabled && (ParallelGCThreads > 1), 2153 // mt processing 2154 MAX2((int)ParallelGCThreads, 1), 2155 // degree of mt processing 2156 (ParallelGCThreads > 1), 2157 // mt discovery 2158 MAX2((int)ParallelGCThreads, 1), 2159 // degree of mt discovery 2160 true, 2161 // Reference discovery is atomic 2162 &_is_alive_closure_stw); 2163 // is alive closure 2164 // (for efficiency/performance) 2165 } 2166 2167 size_t G1CollectedHeap::capacity() const { 2168 return _hrm.length() * HeapRegion::GrainBytes; 2169 } 2170 2171 void G1CollectedHeap::reset_gc_time_stamps(HeapRegion* hr) { 2172 assert(!hr->is_continues_humongous(), "pre-condition"); 2173 hr->reset_gc_time_stamp(); 2174 if (hr->is_starts_humongous()) { 2175 uint first_index = hr->hrm_index() + 1; 2176 uint last_index = hr->last_hc_index(); 2177 for (uint i = first_index; i < last_index; i += 1) { 2178 HeapRegion* chr = region_at(i); 2179 assert(chr->is_continues_humongous(), "sanity"); 2180 chr->reset_gc_time_stamp(); 2181 } 2182 } 2183 } 2184 2185 #ifndef PRODUCT 2186 class CheckGCTimeStampsHRClosure : public HeapRegionClosure { 2187 private: 2188 unsigned _gc_time_stamp; 2189 bool _failures; 2190 2191 public: 2192 CheckGCTimeStampsHRClosure(unsigned gc_time_stamp) : 2193 _gc_time_stamp(gc_time_stamp), _failures(false) { } 2194 2195 virtual bool doHeapRegion(HeapRegion* hr) { 2196 unsigned region_gc_time_stamp = hr->get_gc_time_stamp(); 2197 if (_gc_time_stamp != region_gc_time_stamp) { 2198 gclog_or_tty->print_cr("Region "HR_FORMAT" has GC time stamp = %d, " 2199 "expected %d", HR_FORMAT_PARAMS(hr), 2200 region_gc_time_stamp, _gc_time_stamp); 2201 _failures = true; 2202 } 2203 return false; 2204 } 2205 2206 bool failures() { return _failures; } 2207 }; 2208 2209 void G1CollectedHeap::check_gc_time_stamps() { 2210 CheckGCTimeStampsHRClosure cl(_gc_time_stamp); 2211 heap_region_iterate(&cl); 2212 guarantee(!cl.failures(), "all GC time stamps should have been reset"); 2213 } 2214 #endif // PRODUCT 2215 2216 void G1CollectedHeap::iterate_dirty_card_closure(CardTableEntryClosure* cl, 2217 DirtyCardQueue* into_cset_dcq, 2218 bool concurrent, 2219 uint worker_i) { 2220 // Clean cards in the hot card cache 2221 G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache(); 2222 hot_card_cache->drain(worker_i, g1_rem_set(), into_cset_dcq); 2223 2224 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set(); 2225 int n_completed_buffers = 0; 2226 while (dcqs.apply_closure_to_completed_buffer(cl, worker_i, 0, true)) { 2227 n_completed_buffers++; 2228 } 2229 g1_policy()->phase_times()->record_update_rs_processed_buffers(worker_i, n_completed_buffers); 2230 dcqs.clear_n_completed_buffers(); 2231 assert(!dcqs.completed_buffers_exist_dirty(), "Completed buffers exist!"); 2232 } 2233 2234 2235 // Computes the sum of the storage used by the various regions. 2236 size_t G1CollectedHeap::used() const { 2237 return _allocator->used(); 2238 } 2239 2240 size_t G1CollectedHeap::used_unlocked() const { 2241 return _allocator->used_unlocked(); 2242 } 2243 2244 class SumUsedClosure: public HeapRegionClosure { 2245 size_t _used; 2246 public: 2247 SumUsedClosure() : _used(0) {} 2248 bool doHeapRegion(HeapRegion* r) { 2249 if (!r->is_continues_humongous()) { 2250 _used += r->used(); 2251 } 2252 return false; 2253 } 2254 size_t result() { return _used; } 2255 }; 2256 2257 size_t G1CollectedHeap::recalculate_used() const { 2258 double recalculate_used_start = os::elapsedTime(); 2259 2260 SumUsedClosure blk; 2261 heap_region_iterate(&blk); 2262 2263 g1_policy()->phase_times()->record_evac_fail_recalc_used_time((os::elapsedTime() - recalculate_used_start) * 1000.0); 2264 return blk.result(); 2265 } 2266 2267 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) { 2268 switch (cause) { 2269 case GCCause::_gc_locker: return GCLockerInvokesConcurrent; 2270 case GCCause::_java_lang_system_gc: return ExplicitGCInvokesConcurrent; 2271 case GCCause::_g1_humongous_allocation: return true; 2272 case GCCause::_update_allocation_context_stats_inc: return true; 2273 case GCCause::_wb_conc_mark: return true; 2274 default: return false; 2275 } 2276 } 2277 2278 #ifndef PRODUCT 2279 void G1CollectedHeap::allocate_dummy_regions() { 2280 // Let's fill up most of the region 2281 size_t word_size = HeapRegion::GrainWords - 1024; 2282 // And as a result the region we'll allocate will be humongous. 2283 guarantee(is_humongous(word_size), "sanity"); 2284 2285 for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) { 2286 // Let's use the existing mechanism for the allocation 2287 HeapWord* dummy_obj = humongous_obj_allocate(word_size, 2288 AllocationContext::system()); 2289 if (dummy_obj != NULL) { 2290 MemRegion mr(dummy_obj, word_size); 2291 CollectedHeap::fill_with_object(mr); 2292 } else { 2293 // If we can't allocate once, we probably cannot allocate 2294 // again. Let's get out of the loop. 2295 break; 2296 } 2297 } 2298 } 2299 #endif // !PRODUCT 2300 2301 void G1CollectedHeap::increment_old_marking_cycles_started() { 2302 assert(_old_marking_cycles_started == _old_marking_cycles_completed || 2303 _old_marking_cycles_started == _old_marking_cycles_completed + 1, 2304 err_msg("Wrong marking cycle count (started: %d, completed: %d)", 2305 _old_marking_cycles_started, _old_marking_cycles_completed)); 2306 2307 _old_marking_cycles_started++; 2308 } 2309 2310 void G1CollectedHeap::increment_old_marking_cycles_completed(bool concurrent) { 2311 MonitorLockerEx x(FullGCCount_lock, Mutex::_no_safepoint_check_flag); 2312 2313 // We assume that if concurrent == true, then the caller is a 2314 // concurrent thread that was joined the Suspendible Thread 2315 // Set. If there's ever a cheap way to check this, we should add an 2316 // assert here. 2317 2318 // Given that this method is called at the end of a Full GC or of a 2319 // concurrent cycle, and those can be nested (i.e., a Full GC can 2320 // interrupt a concurrent cycle), the number of full collections 2321 // completed should be either one (in the case where there was no 2322 // nesting) or two (when a Full GC interrupted a concurrent cycle) 2323 // behind the number of full collections started. 2324 2325 // This is the case for the inner caller, i.e. a Full GC. 2326 assert(concurrent || 2327 (_old_marking_cycles_started == _old_marking_cycles_completed + 1) || 2328 (_old_marking_cycles_started == _old_marking_cycles_completed + 2), 2329 err_msg("for inner caller (Full GC): _old_marking_cycles_started = %u " 2330 "is inconsistent with _old_marking_cycles_completed = %u", 2331 _old_marking_cycles_started, _old_marking_cycles_completed)); 2332 2333 // This is the case for the outer caller, i.e. the concurrent cycle. 2334 assert(!concurrent || 2335 (_old_marking_cycles_started == _old_marking_cycles_completed + 1), 2336 err_msg("for outer caller (concurrent cycle): " 2337 "_old_marking_cycles_started = %u " 2338 "is inconsistent with _old_marking_cycles_completed = %u", 2339 _old_marking_cycles_started, _old_marking_cycles_completed)); 2340 2341 _old_marking_cycles_completed += 1; 2342 2343 // We need to clear the "in_progress" flag in the CM thread before 2344 // we wake up any waiters (especially when ExplicitInvokesConcurrent 2345 // is set) so that if a waiter requests another System.gc() it doesn't 2346 // incorrectly see that a marking cycle is still in progress. 2347 if (concurrent) { 2348 _cmThread->clear_in_progress(); 2349 } 2350 2351 // This notify_all() will ensure that a thread that called 2352 // System.gc() with (with ExplicitGCInvokesConcurrent set or not) 2353 // and it's waiting for a full GC to finish will be woken up. It is 2354 // waiting in VM_G1IncCollectionPause::doit_epilogue(). 2355 FullGCCount_lock->notify_all(); 2356 } 2357 2358 void G1CollectedHeap::register_concurrent_cycle_start(const Ticks& start_time) { 2359 _concurrent_cycle_started = true; 2360 _gc_timer_cm->register_gc_start(start_time); 2361 2362 _gc_tracer_cm->report_gc_start(gc_cause(), _gc_timer_cm->gc_start()); 2363 trace_heap_before_gc(_gc_tracer_cm); 2364 } 2365 2366 void G1CollectedHeap::register_concurrent_cycle_end() { 2367 if (_concurrent_cycle_started) { 2368 if (_cm->has_aborted()) { 2369 _gc_tracer_cm->report_concurrent_mode_failure(); 2370 } 2371 2372 _gc_timer_cm->register_gc_end(); 2373 _gc_tracer_cm->report_gc_end(_gc_timer_cm->gc_end(), _gc_timer_cm->time_partitions()); 2374 2375 // Clear state variables to prepare for the next concurrent cycle. 2376 _concurrent_cycle_started = false; 2377 _heap_summary_sent = false; 2378 } 2379 } 2380 2381 void G1CollectedHeap::trace_heap_after_concurrent_cycle() { 2382 if (_concurrent_cycle_started) { 2383 // This function can be called when: 2384 // the cleanup pause is run 2385 // the concurrent cycle is aborted before the cleanup pause. 2386 // the concurrent cycle is aborted after the cleanup pause, 2387 // but before the concurrent cycle end has been registered. 2388 // Make sure that we only send the heap information once. 2389 if (!_heap_summary_sent) { 2390 trace_heap_after_gc(_gc_tracer_cm); 2391 _heap_summary_sent = true; 2392 } 2393 } 2394 } 2395 2396 G1YCType G1CollectedHeap::yc_type() { 2397 bool is_young = g1_policy()->collector_state()->gcs_are_young(); 2398 bool is_initial_mark = g1_policy()->collector_state()->during_initial_mark_pause(); 2399 bool is_during_mark = mark_in_progress(); 2400 2401 if (is_initial_mark) { 2402 return InitialMark; 2403 } else if (is_during_mark) { 2404 return DuringMark; 2405 } else if (is_young) { 2406 return Normal; 2407 } else { 2408 return Mixed; 2409 } 2410 } 2411 2412 void G1CollectedHeap::collect(GCCause::Cause cause) { 2413 assert_heap_not_locked(); 2414 2415 unsigned int gc_count_before; 2416 unsigned int old_marking_count_before; 2417 unsigned int full_gc_count_before; 2418 bool retry_gc; 2419 2420 do { 2421 retry_gc = false; 2422 2423 { 2424 MutexLocker ml(Heap_lock); 2425 2426 // Read the GC count while holding the Heap_lock 2427 gc_count_before = total_collections(); 2428 full_gc_count_before = total_full_collections(); 2429 old_marking_count_before = _old_marking_cycles_started; 2430 } 2431 2432 if (should_do_concurrent_full_gc(cause)) { 2433 // Schedule an initial-mark evacuation pause that will start a 2434 // concurrent cycle. We're setting word_size to 0 which means that 2435 // we are not requesting a post-GC allocation. 2436 VM_G1IncCollectionPause op(gc_count_before, 2437 0, /* word_size */ 2438 true, /* should_initiate_conc_mark */ 2439 g1_policy()->max_pause_time_ms(), 2440 cause); 2441 op.set_allocation_context(AllocationContext::current()); 2442 2443 VMThread::execute(&op); 2444 if (!op.pause_succeeded()) { 2445 if (old_marking_count_before == _old_marking_cycles_started) { 2446 retry_gc = op.should_retry_gc(); 2447 } else { 2448 // A Full GC happened while we were trying to schedule the 2449 // initial-mark GC. No point in starting a new cycle given 2450 // that the whole heap was collected anyway. 2451 } 2452 2453 if (retry_gc) { 2454 if (GC_locker::is_active_and_needs_gc()) { 2455 GC_locker::stall_until_clear(); 2456 } 2457 } 2458 } 2459 } else { 2460 if (cause == GCCause::_gc_locker || cause == GCCause::_wb_young_gc 2461 DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) { 2462 2463 // Schedule a standard evacuation pause. We're setting word_size 2464 // to 0 which means that we are not requesting a post-GC allocation. 2465 VM_G1IncCollectionPause op(gc_count_before, 2466 0, /* word_size */ 2467 false, /* should_initiate_conc_mark */ 2468 g1_policy()->max_pause_time_ms(), 2469 cause); 2470 VMThread::execute(&op); 2471 } else { 2472 // Schedule a Full GC. 2473 VM_G1CollectFull op(gc_count_before, full_gc_count_before, cause); 2474 VMThread::execute(&op); 2475 } 2476 } 2477 } while (retry_gc); 2478 } 2479 2480 bool G1CollectedHeap::is_in(const void* p) const { 2481 if (_hrm.reserved().contains(p)) { 2482 // Given that we know that p is in the reserved space, 2483 // heap_region_containing_raw() should successfully 2484 // return the containing region. 2485 HeapRegion* hr = heap_region_containing_raw(p); 2486 return hr->is_in(p); 2487 } else { 2488 return false; 2489 } 2490 } 2491 2492 #ifdef ASSERT 2493 bool G1CollectedHeap::is_in_exact(const void* p) const { 2494 bool contains = reserved_region().contains(p); 2495 bool available = _hrm.is_available(addr_to_region((HeapWord*)p)); 2496 if (contains && available) { 2497 return true; 2498 } else { 2499 return false; 2500 } 2501 } 2502 #endif 2503 2504 // Iteration functions. 2505 2506 // Applies an ExtendedOopClosure onto all references of objects within a HeapRegion. 2507 2508 class IterateOopClosureRegionClosure: public HeapRegionClosure { 2509 ExtendedOopClosure* _cl; 2510 public: 2511 IterateOopClosureRegionClosure(ExtendedOopClosure* cl) : _cl(cl) {} 2512 bool doHeapRegion(HeapRegion* r) { 2513 if (!r->is_continues_humongous()) { 2514 r->oop_iterate(_cl); 2515 } 2516 return false; 2517 } 2518 }; 2519 2520 void G1CollectedHeap::oop_iterate(ExtendedOopClosure* cl) { 2521 IterateOopClosureRegionClosure blk(cl); 2522 heap_region_iterate(&blk); 2523 } 2524 2525 // Iterates an ObjectClosure over all objects within a HeapRegion. 2526 2527 class IterateObjectClosureRegionClosure: public HeapRegionClosure { 2528 ObjectClosure* _cl; 2529 public: 2530 IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {} 2531 bool doHeapRegion(HeapRegion* r) { 2532 if (!r->is_continues_humongous()) { 2533 r->object_iterate(_cl); 2534 } 2535 return false; 2536 } 2537 }; 2538 2539 void G1CollectedHeap::object_iterate(ObjectClosure* cl) { 2540 IterateObjectClosureRegionClosure blk(cl); 2541 heap_region_iterate(&blk); 2542 } 2543 2544 // Calls a SpaceClosure on a HeapRegion. 2545 2546 class SpaceClosureRegionClosure: public HeapRegionClosure { 2547 SpaceClosure* _cl; 2548 public: 2549 SpaceClosureRegionClosure(SpaceClosure* cl) : _cl(cl) {} 2550 bool doHeapRegion(HeapRegion* r) { 2551 _cl->do_space(r); 2552 return false; 2553 } 2554 }; 2555 2556 void G1CollectedHeap::space_iterate(SpaceClosure* cl) { 2557 SpaceClosureRegionClosure blk(cl); 2558 heap_region_iterate(&blk); 2559 } 2560 2561 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const { 2562 _hrm.iterate(cl); 2563 } 2564 2565 void 2566 G1CollectedHeap::heap_region_par_iterate(HeapRegionClosure* cl, 2567 uint worker_id, 2568 HeapRegionClaimer *hrclaimer, 2569 bool concurrent) const { 2570 _hrm.par_iterate(cl, worker_id, hrclaimer, concurrent); 2571 } 2572 2573 // Clear the cached CSet starting regions and (more importantly) 2574 // the time stamps. Called when we reset the GC time stamp. 2575 void G1CollectedHeap::clear_cset_start_regions() { 2576 assert(_worker_cset_start_region != NULL, "sanity"); 2577 assert(_worker_cset_start_region_time_stamp != NULL, "sanity"); 2578 2579 int n_queues = MAX2((int)ParallelGCThreads, 1); 2580 for (int i = 0; i < n_queues; i++) { 2581 _worker_cset_start_region[i] = NULL; 2582 _worker_cset_start_region_time_stamp[i] = 0; 2583 } 2584 } 2585 2586 // Given the id of a worker, obtain or calculate a suitable 2587 // starting region for iterating over the current collection set. 2588 HeapRegion* G1CollectedHeap::start_cset_region_for_worker(uint worker_i) { 2589 assert(get_gc_time_stamp() > 0, "should have been updated by now"); 2590 2591 HeapRegion* result = NULL; 2592 unsigned gc_time_stamp = get_gc_time_stamp(); 2593 2594 if (_worker_cset_start_region_time_stamp[worker_i] == gc_time_stamp) { 2595 // Cached starting region for current worker was set 2596 // during the current pause - so it's valid. 2597 // Note: the cached starting heap region may be NULL 2598 // (when the collection set is empty). 2599 result = _worker_cset_start_region[worker_i]; 2600 assert(result == NULL || result->in_collection_set(), "sanity"); 2601 return result; 2602 } 2603 2604 // The cached entry was not valid so let's calculate 2605 // a suitable starting heap region for this worker. 2606 2607 // We want the parallel threads to start their collection 2608 // set iteration at different collection set regions to 2609 // avoid contention. 2610 // If we have: 2611 // n collection set regions 2612 // p threads 2613 // Then thread t will start at region floor ((t * n) / p) 2614 2615 result = g1_policy()->collection_set(); 2616 uint cs_size = g1_policy()->cset_region_length(); 2617 uint active_workers = workers()->active_workers(); 2618 assert(UseDynamicNumberOfGCThreads || 2619 active_workers == workers()->total_workers(), 2620 "Unless dynamic should use total workers"); 2621 2622 uint end_ind = (cs_size * worker_i) / active_workers; 2623 uint start_ind = 0; 2624 2625 if (worker_i > 0 && 2626 _worker_cset_start_region_time_stamp[worker_i - 1] == gc_time_stamp) { 2627 // Previous workers starting region is valid 2628 // so let's iterate from there 2629 start_ind = (cs_size * (worker_i - 1)) / active_workers; 2630 result = _worker_cset_start_region[worker_i - 1]; 2631 } 2632 2633 for (uint i = start_ind; i < end_ind; i++) { 2634 result = result->next_in_collection_set(); 2635 } 2636 2637 // Note: the calculated starting heap region may be NULL 2638 // (when the collection set is empty). 2639 assert(result == NULL || result->in_collection_set(), "sanity"); 2640 assert(_worker_cset_start_region_time_stamp[worker_i] != gc_time_stamp, 2641 "should be updated only once per pause"); 2642 _worker_cset_start_region[worker_i] = result; 2643 OrderAccess::storestore(); 2644 _worker_cset_start_region_time_stamp[worker_i] = gc_time_stamp; 2645 return result; 2646 } 2647 2648 void G1CollectedHeap::collection_set_iterate(HeapRegionClosure* cl) { 2649 HeapRegion* r = g1_policy()->collection_set(); 2650 while (r != NULL) { 2651 HeapRegion* next = r->next_in_collection_set(); 2652 if (cl->doHeapRegion(r)) { 2653 cl->incomplete(); 2654 return; 2655 } 2656 r = next; 2657 } 2658 } 2659 2660 void G1CollectedHeap::collection_set_iterate_from(HeapRegion* r, 2661 HeapRegionClosure *cl) { 2662 if (r == NULL) { 2663 // The CSet is empty so there's nothing to do. 2664 return; 2665 } 2666 2667 assert(r->in_collection_set(), 2668 "Start region must be a member of the collection set."); 2669 HeapRegion* cur = r; 2670 while (cur != NULL) { 2671 HeapRegion* next = cur->next_in_collection_set(); 2672 if (cl->doHeapRegion(cur) && false) { 2673 cl->incomplete(); 2674 return; 2675 } 2676 cur = next; 2677 } 2678 cur = g1_policy()->collection_set(); 2679 while (cur != r) { 2680 HeapRegion* next = cur->next_in_collection_set(); 2681 if (cl->doHeapRegion(cur) && false) { 2682 cl->incomplete(); 2683 return; 2684 } 2685 cur = next; 2686 } 2687 } 2688 2689 HeapRegion* G1CollectedHeap::next_compaction_region(const HeapRegion* from) const { 2690 HeapRegion* result = _hrm.next_region_in_heap(from); 2691 while (result != NULL && result->is_humongous()) { 2692 result = _hrm.next_region_in_heap(result); 2693 } 2694 return result; 2695 } 2696 2697 Space* G1CollectedHeap::space_containing(const void* addr) const { 2698 return heap_region_containing(addr); 2699 } 2700 2701 HeapWord* G1CollectedHeap::block_start(const void* addr) const { 2702 Space* sp = space_containing(addr); 2703 return sp->block_start(addr); 2704 } 2705 2706 size_t G1CollectedHeap::block_size(const HeapWord* addr) const { 2707 Space* sp = space_containing(addr); 2708 return sp->block_size(addr); 2709 } 2710 2711 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const { 2712 Space* sp = space_containing(addr); 2713 return sp->block_is_obj(addr); 2714 } 2715 2716 bool G1CollectedHeap::supports_tlab_allocation() const { 2717 return true; 2718 } 2719 2720 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const { 2721 return (_g1_policy->young_list_target_length() - young_list()->survivor_length()) * HeapRegion::GrainBytes; 2722 } 2723 2724 size_t G1CollectedHeap::tlab_used(Thread* ignored) const { 2725 return young_list()->eden_used_bytes(); 2726 } 2727 2728 // For G1 TLABs should not contain humongous objects, so the maximum TLAB size 2729 // must be smaller than the humongous object limit. 2730 size_t G1CollectedHeap::max_tlab_size() const { 2731 return align_size_down(_humongous_object_threshold_in_words - 1, MinObjAlignment); 2732 } 2733 2734 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const { 2735 // Return the remaining space in the cur alloc region, but not less than 2736 // the min TLAB size. 2737 2738 // Also, this value can be at most the humongous object threshold, 2739 // since we can't allow tlabs to grow big enough to accommodate 2740 // humongous objects. 2741 2742 HeapRegion* hr = _allocator->mutator_alloc_region(AllocationContext::current())->get(); 2743 size_t max_tlab = max_tlab_size() * wordSize; 2744 if (hr == NULL) { 2745 return max_tlab; 2746 } else { 2747 return MIN2(MAX2(hr->free(), (size_t) MinTLABSize), max_tlab); 2748 } 2749 } 2750 2751 size_t G1CollectedHeap::max_capacity() const { 2752 return _hrm.reserved().byte_size(); 2753 } 2754 2755 jlong G1CollectedHeap::millis_since_last_gc() { 2756 // assert(false, "NYI"); 2757 return 0; 2758 } 2759 2760 void G1CollectedHeap::prepare_for_verify() { 2761 if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) { 2762 ensure_parsability(false); 2763 } 2764 g1_rem_set()->prepare_for_verify(); 2765 } 2766 2767 bool G1CollectedHeap::allocated_since_marking(oop obj, HeapRegion* hr, 2768 VerifyOption vo) { 2769 switch (vo) { 2770 case VerifyOption_G1UsePrevMarking: 2771 return hr->obj_allocated_since_prev_marking(obj); 2772 case VerifyOption_G1UseNextMarking: 2773 return hr->obj_allocated_since_next_marking(obj); 2774 case VerifyOption_G1UseMarkWord: 2775 return false; 2776 default: 2777 ShouldNotReachHere(); 2778 } 2779 return false; // keep some compilers happy 2780 } 2781 2782 HeapWord* G1CollectedHeap::top_at_mark_start(HeapRegion* hr, VerifyOption vo) { 2783 switch (vo) { 2784 case VerifyOption_G1UsePrevMarking: return hr->prev_top_at_mark_start(); 2785 case VerifyOption_G1UseNextMarking: return hr->next_top_at_mark_start(); 2786 case VerifyOption_G1UseMarkWord: return NULL; 2787 default: ShouldNotReachHere(); 2788 } 2789 return NULL; // keep some compilers happy 2790 } 2791 2792 bool G1CollectedHeap::is_marked(oop obj, VerifyOption vo) { 2793 switch (vo) { 2794 case VerifyOption_G1UsePrevMarking: return isMarkedPrev(obj); 2795 case VerifyOption_G1UseNextMarking: return isMarkedNext(obj); 2796 case VerifyOption_G1UseMarkWord: return obj->is_gc_marked(); 2797 default: ShouldNotReachHere(); 2798 } 2799 return false; // keep some compilers happy 2800 } 2801 2802 const char* G1CollectedHeap::top_at_mark_start_str(VerifyOption vo) { 2803 switch (vo) { 2804 case VerifyOption_G1UsePrevMarking: return "PTAMS"; 2805 case VerifyOption_G1UseNextMarking: return "NTAMS"; 2806 case VerifyOption_G1UseMarkWord: return "NONE"; 2807 default: ShouldNotReachHere(); 2808 } 2809 return NULL; // keep some compilers happy 2810 } 2811 2812 class VerifyRootsClosure: public OopClosure { 2813 private: 2814 G1CollectedHeap* _g1h; 2815 VerifyOption _vo; 2816 bool _failures; 2817 public: 2818 // _vo == UsePrevMarking -> use "prev" marking information, 2819 // _vo == UseNextMarking -> use "next" marking information, 2820 // _vo == UseMarkWord -> use mark word from object header. 2821 VerifyRootsClosure(VerifyOption vo) : 2822 _g1h(G1CollectedHeap::heap()), 2823 _vo(vo), 2824 _failures(false) { } 2825 2826 bool failures() { return _failures; } 2827 2828 template <class T> void do_oop_nv(T* p) { 2829 T heap_oop = oopDesc::load_heap_oop(p); 2830 if (!oopDesc::is_null(heap_oop)) { 2831 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop); 2832 if (_g1h->is_obj_dead_cond(obj, _vo)) { 2833 gclog_or_tty->print_cr("Root location "PTR_FORMAT" " 2834 "points to dead obj "PTR_FORMAT, p, (void*) obj); 2835 if (_vo == VerifyOption_G1UseMarkWord) { 2836 gclog_or_tty->print_cr(" Mark word: "PTR_FORMAT, (void*)(obj->mark())); 2837 } 2838 obj->print_on(gclog_or_tty); 2839 _failures = true; 2840 } 2841 } 2842 } 2843 2844 void do_oop(oop* p) { do_oop_nv(p); } 2845 void do_oop(narrowOop* p) { do_oop_nv(p); } 2846 }; 2847 2848 class G1VerifyCodeRootOopClosure: public OopClosure { 2849 G1CollectedHeap* _g1h; 2850 OopClosure* _root_cl; 2851 nmethod* _nm; 2852 VerifyOption _vo; 2853 bool _failures; 2854 2855 template <class T> void do_oop_work(T* p) { 2856 // First verify that this root is live 2857 _root_cl->do_oop(p); 2858 2859 if (!G1VerifyHeapRegionCodeRoots) { 2860 // We're not verifying the code roots attached to heap region. 2861 return; 2862 } 2863 2864 // Don't check the code roots during marking verification in a full GC 2865 if (_vo == VerifyOption_G1UseMarkWord) { 2866 return; 2867 } 2868 2869 // Now verify that the current nmethod (which contains p) is 2870 // in the code root list of the heap region containing the 2871 // object referenced by p. 2872 2873 T heap_oop = oopDesc::load_heap_oop(p); 2874 if (!oopDesc::is_null(heap_oop)) { 2875 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop); 2876 2877 // Now fetch the region containing the object 2878 HeapRegion* hr = _g1h->heap_region_containing(obj); 2879 HeapRegionRemSet* hrrs = hr->rem_set(); 2880 // Verify that the strong code root list for this region 2881 // contains the nmethod 2882 if (!hrrs->strong_code_roots_list_contains(_nm)) { 2883 gclog_or_tty->print_cr("Code root location "PTR_FORMAT" " 2884 "from nmethod "PTR_FORMAT" not in strong " 2885 "code roots for region ["PTR_FORMAT","PTR_FORMAT")", 2886 p, _nm, hr->bottom(), hr->end()); 2887 _failures = true; 2888 } 2889 } 2890 } 2891 2892 public: 2893 G1VerifyCodeRootOopClosure(G1CollectedHeap* g1h, OopClosure* root_cl, VerifyOption vo): 2894 _g1h(g1h), _root_cl(root_cl), _vo(vo), _nm(NULL), _failures(false) {} 2895 2896 void do_oop(oop* p) { do_oop_work(p); } 2897 void do_oop(narrowOop* p) { do_oop_work(p); } 2898 2899 void set_nmethod(nmethod* nm) { _nm = nm; } 2900 bool failures() { return _failures; } 2901 }; 2902 2903 class G1VerifyCodeRootBlobClosure: public CodeBlobClosure { 2904 G1VerifyCodeRootOopClosure* _oop_cl; 2905 2906 public: 2907 G1VerifyCodeRootBlobClosure(G1VerifyCodeRootOopClosure* oop_cl): 2908 _oop_cl(oop_cl) {} 2909 2910 void do_code_blob(CodeBlob* cb) { 2911 nmethod* nm = cb->as_nmethod_or_null(); 2912 if (nm != NULL) { 2913 _oop_cl->set_nmethod(nm); 2914 nm->oops_do(_oop_cl); 2915 } 2916 } 2917 }; 2918 2919 class YoungRefCounterClosure : public OopClosure { 2920 G1CollectedHeap* _g1h; 2921 int _count; 2922 public: 2923 YoungRefCounterClosure(G1CollectedHeap* g1h) : _g1h(g1h), _count(0) {} 2924 void do_oop(oop* p) { if (_g1h->is_in_young(*p)) { _count++; } } 2925 void do_oop(narrowOop* p) { ShouldNotReachHere(); } 2926 2927 int count() { return _count; } 2928 void reset_count() { _count = 0; }; 2929 }; 2930 2931 class VerifyKlassClosure: public KlassClosure { 2932 YoungRefCounterClosure _young_ref_counter_closure; 2933 OopClosure *_oop_closure; 2934 public: 2935 VerifyKlassClosure(G1CollectedHeap* g1h, OopClosure* cl) : _young_ref_counter_closure(g1h), _oop_closure(cl) {} 2936 void do_klass(Klass* k) { 2937 k->oops_do(_oop_closure); 2938 2939 _young_ref_counter_closure.reset_count(); 2940 k->oops_do(&_young_ref_counter_closure); 2941 if (_young_ref_counter_closure.count() > 0) { 2942 guarantee(k->has_modified_oops(), err_msg("Klass " PTR_FORMAT ", has young refs but is not dirty.", k)); 2943 } 2944 } 2945 }; 2946 2947 class VerifyLivenessOopClosure: public OopClosure { 2948 G1CollectedHeap* _g1h; 2949 VerifyOption _vo; 2950 public: 2951 VerifyLivenessOopClosure(G1CollectedHeap* g1h, VerifyOption vo): 2952 _g1h(g1h), _vo(vo) 2953 { } 2954 void do_oop(narrowOop *p) { do_oop_work(p); } 2955 void do_oop( oop *p) { do_oop_work(p); } 2956 2957 template <class T> void do_oop_work(T *p) { 2958 oop obj = oopDesc::load_decode_heap_oop(p); 2959 guarantee(obj == NULL || !_g1h->is_obj_dead_cond(obj, _vo), 2960 "Dead object referenced by a not dead object"); 2961 } 2962 }; 2963 2964 class VerifyObjsInRegionClosure: public ObjectClosure { 2965 private: 2966 G1CollectedHeap* _g1h; 2967 size_t _live_bytes; 2968 HeapRegion *_hr; 2969 VerifyOption _vo; 2970 public: 2971 // _vo == UsePrevMarking -> use "prev" marking information, 2972 // _vo == UseNextMarking -> use "next" marking information, 2973 // _vo == UseMarkWord -> use mark word from object header. 2974 VerifyObjsInRegionClosure(HeapRegion *hr, VerifyOption vo) 2975 : _live_bytes(0), _hr(hr), _vo(vo) { 2976 _g1h = G1CollectedHeap::heap(); 2977 } 2978 void do_object(oop o) { 2979 VerifyLivenessOopClosure isLive(_g1h, _vo); 2980 assert(o != NULL, "Huh?"); 2981 if (!_g1h->is_obj_dead_cond(o, _vo)) { 2982 // If the object is alive according to the mark word, 2983 // then verify that the marking information agrees. 2984 // Note we can't verify the contra-positive of the 2985 // above: if the object is dead (according to the mark 2986 // word), it may not be marked, or may have been marked 2987 // but has since became dead, or may have been allocated 2988 // since the last marking. 2989 if (_vo == VerifyOption_G1UseMarkWord) { 2990 guarantee(!_g1h->is_obj_dead(o), "mark word and concurrent mark mismatch"); 2991 } 2992 2993 o->oop_iterate_no_header(&isLive); 2994 if (!_hr->obj_allocated_since_prev_marking(o)) { 2995 size_t obj_size = o->size(); // Make sure we don't overflow 2996 _live_bytes += (obj_size * HeapWordSize); 2997 } 2998 } 2999 } 3000 size_t live_bytes() { return _live_bytes; } 3001 }; 3002 3003 class PrintObjsInRegionClosure : public ObjectClosure { 3004 HeapRegion *_hr; 3005 G1CollectedHeap *_g1; 3006 public: 3007 PrintObjsInRegionClosure(HeapRegion *hr) : _hr(hr) { 3008 _g1 = G1CollectedHeap::heap(); 3009 }; 3010 3011 void do_object(oop o) { 3012 if (o != NULL) { 3013 HeapWord *start = (HeapWord *) o; 3014 size_t word_sz = o->size(); 3015 gclog_or_tty->print("\nPrinting obj "PTR_FORMAT" of size " SIZE_FORMAT 3016 " isMarkedPrev %d isMarkedNext %d isAllocSince %d\n", 3017 (void*) o, word_sz, 3018 _g1->isMarkedPrev(o), 3019 _g1->isMarkedNext(o), 3020 _hr->obj_allocated_since_prev_marking(o)); 3021 HeapWord *end = start + word_sz; 3022 HeapWord *cur; 3023 int *val; 3024 for (cur = start; cur < end; cur++) { 3025 val = (int *) cur; 3026 gclog_or_tty->print("\t "PTR_FORMAT":%d\n", val, *val); 3027 } 3028 } 3029 } 3030 }; 3031 3032 class VerifyRegionClosure: public HeapRegionClosure { 3033 private: 3034 bool _par; 3035 VerifyOption _vo; 3036 bool _failures; 3037 public: 3038 // _vo == UsePrevMarking -> use "prev" marking information, 3039 // _vo == UseNextMarking -> use "next" marking information, 3040 // _vo == UseMarkWord -> use mark word from object header. 3041 VerifyRegionClosure(bool par, VerifyOption vo) 3042 : _par(par), 3043 _vo(vo), 3044 _failures(false) {} 3045 3046 bool failures() { 3047 return _failures; 3048 } 3049 3050 bool doHeapRegion(HeapRegion* r) { 3051 if (!r->is_continues_humongous()) { 3052 bool failures = false; 3053 r->verify(_vo, &failures); 3054 if (failures) { 3055 _failures = true; 3056 } else { 3057 VerifyObjsInRegionClosure not_dead_yet_cl(r, _vo); 3058 r->object_iterate(¬_dead_yet_cl); 3059 if (_vo != VerifyOption_G1UseNextMarking) { 3060 if (r->max_live_bytes() < not_dead_yet_cl.live_bytes()) { 3061 gclog_or_tty->print_cr("["PTR_FORMAT","PTR_FORMAT"] " 3062 "max_live_bytes "SIZE_FORMAT" " 3063 "< calculated "SIZE_FORMAT, 3064 r->bottom(), r->end(), 3065 r->max_live_bytes(), 3066 not_dead_yet_cl.live_bytes()); 3067 _failures = true; 3068 } 3069 } else { 3070 // When vo == UseNextMarking we cannot currently do a sanity 3071 // check on the live bytes as the calculation has not been 3072 // finalized yet. 3073 } 3074 } 3075 } 3076 return false; // stop the region iteration if we hit a failure 3077 } 3078 }; 3079 3080 // This is the task used for parallel verification of the heap regions 3081 3082 class G1ParVerifyTask: public AbstractGangTask { 3083 private: 3084 G1CollectedHeap* _g1h; 3085 VerifyOption _vo; 3086 bool _failures; 3087 HeapRegionClaimer _hrclaimer; 3088 3089 public: 3090 // _vo == UsePrevMarking -> use "prev" marking information, 3091 // _vo == UseNextMarking -> use "next" marking information, 3092 // _vo == UseMarkWord -> use mark word from object header. 3093 G1ParVerifyTask(G1CollectedHeap* g1h, VerifyOption vo) : 3094 AbstractGangTask("Parallel verify task"), 3095 _g1h(g1h), 3096 _vo(vo), 3097 _failures(false), 3098 _hrclaimer(g1h->workers()->active_workers()) {} 3099 3100 bool failures() { 3101 return _failures; 3102 } 3103 3104 void work(uint worker_id) { 3105 HandleMark hm; 3106 VerifyRegionClosure blk(true, _vo); 3107 _g1h->heap_region_par_iterate(&blk, worker_id, &_hrclaimer); 3108 if (blk.failures()) { 3109 _failures = true; 3110 } 3111 } 3112 }; 3113 3114 void G1CollectedHeap::verify(bool silent, VerifyOption vo) { 3115 if (SafepointSynchronize::is_at_safepoint()) { 3116 assert(Thread::current()->is_VM_thread(), 3117 "Expected to be executed serially by the VM thread at this point"); 3118 3119 if (!silent) { gclog_or_tty->print("Roots "); } 3120 VerifyRootsClosure rootsCl(vo); 3121 VerifyKlassClosure klassCl(this, &rootsCl); 3122 CLDToKlassAndOopClosure cldCl(&klassCl, &rootsCl, false); 3123 3124 // We apply the relevant closures to all the oops in the 3125 // system dictionary, class loader data graph, the string table 3126 // and the nmethods in the code cache. 3127 G1VerifyCodeRootOopClosure codeRootsCl(this, &rootsCl, vo); 3128 G1VerifyCodeRootBlobClosure blobsCl(&codeRootsCl); 3129 3130 process_all_roots(true, // activate StrongRootsScope 3131 SO_AllCodeCache, // roots scanning options 3132 &rootsCl, 3133 &cldCl, 3134 &blobsCl); 3135 3136 bool failures = rootsCl.failures() || codeRootsCl.failures(); 3137 3138 if (vo != VerifyOption_G1UseMarkWord) { 3139 // If we're verifying during a full GC then the region sets 3140 // will have been torn down at the start of the GC. Therefore 3141 // verifying the region sets will fail. So we only verify 3142 // the region sets when not in a full GC. 3143 if (!silent) { gclog_or_tty->print("HeapRegionSets "); } 3144 verify_region_sets(); 3145 } 3146 3147 if (!silent) { gclog_or_tty->print("HeapRegions "); } 3148 if (GCParallelVerificationEnabled && ParallelGCThreads > 1) { 3149 3150 G1ParVerifyTask task(this, vo); 3151 assert(UseDynamicNumberOfGCThreads || 3152 workers()->active_workers() == workers()->total_workers(), 3153 "If not dynamic should be using all the workers"); 3154 int n_workers = workers()->active_workers(); 3155 set_par_threads(n_workers); 3156 workers()->run_task(&task); 3157 set_par_threads(0); 3158 if (task.failures()) { 3159 failures = true; 3160 } 3161 3162 } else { 3163 VerifyRegionClosure blk(false, vo); 3164 heap_region_iterate(&blk); 3165 if (blk.failures()) { 3166 failures = true; 3167 } 3168 } 3169 3170 if (G1StringDedup::is_enabled()) { 3171 if (!silent) gclog_or_tty->print("StrDedup "); 3172 G1StringDedup::verify(); 3173 } 3174 3175 if (failures) { 3176 gclog_or_tty->print_cr("Heap:"); 3177 // It helps to have the per-region information in the output to 3178 // help us track down what went wrong. This is why we call 3179 // print_extended_on() instead of print_on(). 3180 print_extended_on(gclog_or_tty); 3181 gclog_or_tty->cr(); 3182 #ifndef PRODUCT 3183 if (VerifyDuringGC && G1VerifyDuringGCPrintReachable) { 3184 concurrent_mark()->print_reachable("at-verification-failure", 3185 vo, false /* all */); 3186 } 3187 #endif 3188 gclog_or_tty->flush(); 3189 } 3190 guarantee(!failures, "there should not have been any failures"); 3191 } else { 3192 if (!silent) { 3193 gclog_or_tty->print("(SKIPPING Roots, HeapRegionSets, HeapRegions, RemSet"); 3194 if (G1StringDedup::is_enabled()) { 3195 gclog_or_tty->print(", StrDedup"); 3196 } 3197 gclog_or_tty->print(") "); 3198 } 3199 } 3200 } 3201 3202 void G1CollectedHeap::verify(bool silent) { 3203 verify(silent, VerifyOption_G1UsePrevMarking); 3204 } 3205 3206 double G1CollectedHeap::verify(bool guard, const char* msg) { 3207 double verify_time_ms = 0.0; 3208 3209 if (guard && total_collections() >= VerifyGCStartAt) { 3210 double verify_start = os::elapsedTime(); 3211 HandleMark hm; // Discard invalid handles created during verification 3212 prepare_for_verify(); 3213 Universe::verify(VerifyOption_G1UsePrevMarking, msg); 3214 verify_time_ms = (os::elapsedTime() - verify_start) * 1000; 3215 } 3216 3217 return verify_time_ms; 3218 } 3219 3220 void G1CollectedHeap::verify_before_gc() { 3221 double verify_time_ms = verify(VerifyBeforeGC, " VerifyBeforeGC:"); 3222 g1_policy()->phase_times()->record_verify_before_time_ms(verify_time_ms); 3223 } 3224 3225 void G1CollectedHeap::verify_after_gc() { 3226 double verify_time_ms = verify(VerifyAfterGC, " VerifyAfterGC:"); 3227 g1_policy()->phase_times()->record_verify_after_time_ms(verify_time_ms); 3228 } 3229 3230 class PrintRegionClosure: public HeapRegionClosure { 3231 outputStream* _st; 3232 public: 3233 PrintRegionClosure(outputStream* st) : _st(st) {} 3234 bool doHeapRegion(HeapRegion* r) { 3235 r->print_on(_st); 3236 return false; 3237 } 3238 }; 3239 3240 bool G1CollectedHeap::is_obj_dead_cond(const oop obj, 3241 const HeapRegion* hr, 3242 const VerifyOption vo) const { 3243 switch (vo) { 3244 case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj, hr); 3245 case VerifyOption_G1UseNextMarking: return is_obj_ill(obj, hr); 3246 case VerifyOption_G1UseMarkWord: return !obj->is_gc_marked(); 3247 default: ShouldNotReachHere(); 3248 } 3249 return false; // keep some compilers happy 3250 } 3251 3252 bool G1CollectedHeap::is_obj_dead_cond(const oop obj, 3253 const VerifyOption vo) const { 3254 switch (vo) { 3255 case VerifyOption_G1UsePrevMarking: return is_obj_dead(obj); 3256 case VerifyOption_G1UseNextMarking: return is_obj_ill(obj); 3257 case VerifyOption_G1UseMarkWord: return !obj->is_gc_marked(); 3258 default: ShouldNotReachHere(); 3259 } 3260 return false; // keep some compilers happy 3261 } 3262 3263 void G1CollectedHeap::print_on(outputStream* st) const { 3264 st->print(" %-20s", "garbage-first heap"); 3265 st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K", 3266 capacity()/K, used_unlocked()/K); 3267 st->print(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT ")", 3268 _hrm.reserved().start(), 3269 _hrm.reserved().start() + _hrm.length() + HeapRegion::GrainWords, 3270 _hrm.reserved().end()); 3271 st->cr(); 3272 st->print(" region size " SIZE_FORMAT "K, ", HeapRegion::GrainBytes / K); 3273 uint young_regions = _young_list->length(); 3274 st->print("%u young (" SIZE_FORMAT "K), ", young_regions, 3275 (size_t) young_regions * HeapRegion::GrainBytes / K); 3276 uint survivor_regions = g1_policy()->recorded_survivor_regions(); 3277 st->print("%u survivors (" SIZE_FORMAT "K)", survivor_regions, 3278 (size_t) survivor_regions * HeapRegion::GrainBytes / K); 3279 st->cr(); 3280 MetaspaceAux::print_on(st); 3281 } 3282 3283 void G1CollectedHeap::print_extended_on(outputStream* st) const { 3284 print_on(st); 3285 3286 // Print the per-region information. 3287 st->cr(); 3288 st->print_cr("Heap Regions: (Y=young(eden), SU=young(survivor), " 3289 "HS=humongous(starts), HC=humongous(continues), " 3290 "CS=collection set, F=free, TS=gc time stamp, " 3291 "PTAMS=previous top-at-mark-start, " 3292 "NTAMS=next top-at-mark-start)"); 3293 PrintRegionClosure blk(st); 3294 heap_region_iterate(&blk); 3295 } 3296 3297 void G1CollectedHeap::print_on_error(outputStream* st) const { 3298 this->CollectedHeap::print_on_error(st); 3299 3300 if (_cm != NULL) { 3301 st->cr(); 3302 _cm->print_on_error(st); 3303 } 3304 } 3305 3306 void G1CollectedHeap::print_gc_threads_on(outputStream* st) const { 3307 workers()->print_worker_threads_on(st); 3308 _cmThread->print_on(st); 3309 st->cr(); 3310 _cm->print_worker_threads_on(st); 3311 _cg1r->print_worker_threads_on(st); 3312 if (G1StringDedup::is_enabled()) { 3313 G1StringDedup::print_worker_threads_on(st); 3314 } 3315 } 3316 3317 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const { 3318 workers()->threads_do(tc); 3319 tc->do_thread(_cmThread); 3320 _cg1r->threads_do(tc); 3321 if (G1StringDedup::is_enabled()) { 3322 G1StringDedup::threads_do(tc); 3323 } 3324 } 3325 3326 void G1CollectedHeap::print_tracing_info() const { 3327 // We'll overload this to mean "trace GC pause statistics." 3328 if (TraceYoungGenTime || TraceOldGenTime) { 3329 // The "G1CollectorPolicy" is keeping track of these stats, so delegate 3330 // to that. 3331 g1_policy()->print_tracing_info(); 3332 } 3333 if (G1SummarizeRSetStats) { 3334 g1_rem_set()->print_summary_info(); 3335 } 3336 if (G1SummarizeConcMark) { 3337 concurrent_mark()->print_summary_info(); 3338 } 3339 g1_policy()->print_yg_surv_rate_info(); 3340 SpecializationStats::print(); 3341 } 3342 3343 #ifndef PRODUCT 3344 // Helpful for debugging RSet issues. 3345 3346 class PrintRSetsClosure : public HeapRegionClosure { 3347 private: 3348 const char* _msg; 3349 size_t _occupied_sum; 3350 3351 public: 3352 bool doHeapRegion(HeapRegion* r) { 3353 HeapRegionRemSet* hrrs = r->rem_set(); 3354 size_t occupied = hrrs->occupied(); 3355 _occupied_sum += occupied; 3356 3357 gclog_or_tty->print_cr("Printing RSet for region "HR_FORMAT, 3358 HR_FORMAT_PARAMS(r)); 3359 if (occupied == 0) { 3360 gclog_or_tty->print_cr(" RSet is empty"); 3361 } else { 3362 hrrs->print(); 3363 } 3364 gclog_or_tty->print_cr("----------"); 3365 return false; 3366 } 3367 3368 PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) { 3369 gclog_or_tty->cr(); 3370 gclog_or_tty->print_cr("========================================"); 3371 gclog_or_tty->print_cr("%s", msg); 3372 gclog_or_tty->cr(); 3373 } 3374 3375 ~PrintRSetsClosure() { 3376 gclog_or_tty->print_cr("Occupied Sum: "SIZE_FORMAT, _occupied_sum); 3377 gclog_or_tty->print_cr("========================================"); 3378 gclog_or_tty->cr(); 3379 } 3380 }; 3381 3382 void G1CollectedHeap::print_cset_rsets() { 3383 PrintRSetsClosure cl("Printing CSet RSets"); 3384 collection_set_iterate(&cl); 3385 } 3386 3387 void G1CollectedHeap::print_all_rsets() { 3388 PrintRSetsClosure cl("Printing All RSets");; 3389 heap_region_iterate(&cl); 3390 } 3391 #endif // PRODUCT 3392 3393 G1CollectedHeap* G1CollectedHeap::heap() { 3394 assert(_sh->kind() == CollectedHeap::G1CollectedHeap, 3395 "not a garbage-first heap"); 3396 return _g1h; 3397 } 3398 3399 void G1CollectedHeap::gc_prologue(bool full /* Ignored */) { 3400 // always_do_update_barrier = false; 3401 assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer"); 3402 // Fill TLAB's and such 3403 accumulate_statistics_all_tlabs(); 3404 ensure_parsability(true); 3405 3406 if (G1SummarizeRSetStats && (G1SummarizeRSetStatsPeriod > 0) && 3407 (total_collections() % G1SummarizeRSetStatsPeriod == 0)) { 3408 g1_rem_set()->print_periodic_summary_info("Before GC RS summary"); 3409 } 3410 } 3411 3412 void G1CollectedHeap::gc_epilogue(bool full) { 3413 3414 if (G1SummarizeRSetStats && 3415 (G1SummarizeRSetStatsPeriod > 0) && 3416 // we are at the end of the GC. Total collections has already been increased. 3417 ((total_collections() - 1) % G1SummarizeRSetStatsPeriod == 0)) { 3418 g1_rem_set()->print_periodic_summary_info("After GC RS summary"); 3419 } 3420 3421 // FIXME: what is this about? 3422 // I'm ignoring the "fill_newgen()" call if "alloc_event_enabled" 3423 // is set. 3424 COMPILER2_PRESENT(assert(DerivedPointerTable::is_empty(), 3425 "derived pointer present")); 3426 // always_do_update_barrier = true; 3427 3428 resize_all_tlabs(); 3429 allocation_context_stats().update(full); 3430 3431 // We have just completed a GC. Update the soft reference 3432 // policy with the new heap occupancy 3433 Universe::update_heap_info_at_gc(); 3434 } 3435 3436 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size, 3437 unsigned int gc_count_before, 3438 bool* succeeded, 3439 GCCause::Cause gc_cause) { 3440 assert_heap_not_locked_and_not_at_safepoint(); 3441 g1_policy()->record_stop_world_start(); 3442 VM_G1IncCollectionPause op(gc_count_before, 3443 word_size, 3444 false, /* should_initiate_conc_mark */ 3445 g1_policy()->max_pause_time_ms(), 3446 gc_cause); 3447 3448 op.set_allocation_context(AllocationContext::current()); 3449 VMThread::execute(&op); 3450 3451 HeapWord* result = op.result(); 3452 bool ret_succeeded = op.prologue_succeeded() && op.pause_succeeded(); 3453 assert(result == NULL || ret_succeeded, 3454 "the result should be NULL if the VM did not succeed"); 3455 *succeeded = ret_succeeded; 3456 3457 assert_heap_not_locked(); 3458 return result; 3459 } 3460 3461 void 3462 G1CollectedHeap::doConcurrentMark() { 3463 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag); 3464 if (!_cmThread->in_progress()) { 3465 _cmThread->set_started(); 3466 CGC_lock->notify(); 3467 } 3468 } 3469 3470 size_t G1CollectedHeap::pending_card_num() { 3471 size_t extra_cards = 0; 3472 JavaThread *curr = Threads::first(); 3473 while (curr != NULL) { 3474 DirtyCardQueue& dcq = curr->dirty_card_queue(); 3475 extra_cards += dcq.size(); 3476 curr = curr->next(); 3477 } 3478 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set(); 3479 size_t buffer_size = dcqs.buffer_size(); 3480 size_t buffer_num = dcqs.completed_buffers_num(); 3481 3482 // PtrQueueSet::buffer_size() and PtrQueue:size() return sizes 3483 // in bytes - not the number of 'entries'. We need to convert 3484 // into a number of cards. 3485 return (buffer_size * buffer_num + extra_cards) / oopSize; 3486 } 3487 3488 size_t G1CollectedHeap::cards_scanned() { 3489 return g1_rem_set()->cardsScanned(); 3490 } 3491 3492 bool G1CollectedHeap::humongous_region_is_always_live(uint index) { 3493 HeapRegion* region = region_at(index); 3494 assert(region->is_starts_humongous(), "Must start a humongous object"); 3495 return oop(region->bottom())->is_objArray() || !region->rem_set()->is_empty(); 3496 } 3497 3498 class RegisterHumongousWithInCSetFastTestClosure : public HeapRegionClosure { 3499 private: 3500 size_t _total_humongous; 3501 size_t _candidate_humongous; 3502 3503 DirtyCardQueue _dcq; 3504 3505 bool humongous_region_is_candidate(uint index) { 3506 HeapRegion* region = G1CollectedHeap::heap()->region_at(index); 3507 assert(region->is_starts_humongous(), "Must start a humongous object"); 3508 HeapRegionRemSet* const rset = region->rem_set(); 3509 bool const allow_stale_refs = G1EagerReclaimHumongousObjectsWithStaleRefs; 3510 return !oop(region->bottom())->is_objArray() && 3511 ((allow_stale_refs && rset->occupancy_less_or_equal_than(G1RSetSparseRegionEntries)) || 3512 (!allow_stale_refs && rset->is_empty())); 3513 } 3514 3515 public: 3516 RegisterHumongousWithInCSetFastTestClosure() 3517 : _total_humongous(0), 3518 _candidate_humongous(0), 3519 _dcq(&JavaThread::dirty_card_queue_set()) { 3520 } 3521 3522 virtual bool doHeapRegion(HeapRegion* r) { 3523 if (!r->is_starts_humongous()) { 3524 return false; 3525 } 3526 G1CollectedHeap* g1h = G1CollectedHeap::heap(); 3527 3528 uint region_idx = r->hrm_index(); 3529 bool is_candidate = humongous_region_is_candidate(region_idx); 3530 // Is_candidate already filters out humongous object with large remembered sets. 3531 // If we have a humongous object with a few remembered sets, we simply flush these 3532 // remembered set entries into the DCQS. That will result in automatic 3533 // re-evaluation of their remembered set entries during the following evacuation 3534 // phase. 3535 if (is_candidate) { 3536 if (!r->rem_set()->is_empty()) { 3537 guarantee(r->rem_set()->occupancy_less_or_equal_than(G1RSetSparseRegionEntries), 3538 "Found a not-small remembered set here. This is inconsistent with previous assumptions."); 3539 G1SATBCardTableLoggingModRefBS* bs = g1h->g1_barrier_set(); 3540 HeapRegionRemSetIterator hrrs(r->rem_set()); 3541 size_t card_index; 3542 while (hrrs.has_next(card_index)) { 3543 jbyte* card_ptr = (jbyte*)bs->byte_for_index(card_index); 3544 if (*card_ptr != CardTableModRefBS::dirty_card_val()) { 3545 *card_ptr = CardTableModRefBS::dirty_card_val(); 3546 _dcq.enqueue(card_ptr); 3547 } 3548 } 3549 r->rem_set()->clear_locked(); 3550 } 3551 assert(r->rem_set()->is_empty(), "At this point any humongous candidate remembered set must be empty."); 3552 g1h->register_humongous_region_with_in_cset_fast_test(region_idx); 3553 _candidate_humongous++; 3554 } 3555 _total_humongous++; 3556 3557 return false; 3558 } 3559 3560 size_t total_humongous() const { return _total_humongous; } 3561 size_t candidate_humongous() const { return _candidate_humongous; } 3562 3563 void flush_rem_set_entries() { _dcq.flush(); } 3564 }; 3565 3566 void G1CollectedHeap::register_humongous_regions_with_in_cset_fast_test() { 3567 if (!G1EagerReclaimHumongousObjects) { 3568 g1_policy()->phase_times()->record_fast_reclaim_humongous_stats(0.0, 0, 0); 3569 return; 3570 } 3571 double time = os::elapsed_counter(); 3572 3573 RegisterHumongousWithInCSetFastTestClosure cl; 3574 heap_region_iterate(&cl); 3575 3576 time = ((double)(os::elapsed_counter() - time) / os::elapsed_frequency()) * 1000.0; 3577 g1_policy()->phase_times()->record_fast_reclaim_humongous_stats(time, 3578 cl.total_humongous(), 3579 cl.candidate_humongous()); 3580 _has_humongous_reclaim_candidates = cl.candidate_humongous() > 0; 3581 3582 if (_has_humongous_reclaim_candidates || G1TraceEagerReclaimHumongousObjects) { 3583 clear_humongous_is_live_table(); 3584 } 3585 3586 // Finally flush all remembered set entries to re-check into the global DCQS. 3587 cl.flush_rem_set_entries(); 3588 } 3589 3590 void 3591 G1CollectedHeap::setup_surviving_young_words() { 3592 assert(_surviving_young_words == NULL, "pre-condition"); 3593 uint array_length = g1_policy()->young_cset_region_length(); 3594 _surviving_young_words = NEW_C_HEAP_ARRAY(size_t, (size_t) array_length, mtGC); 3595 if (_surviving_young_words == NULL) { 3596 vm_exit_out_of_memory(sizeof(size_t) * array_length, OOM_MALLOC_ERROR, 3597 "Not enough space for young surv words summary."); 3598 } 3599 memset(_surviving_young_words, 0, (size_t) array_length * sizeof(size_t)); 3600 #ifdef ASSERT 3601 for (uint i = 0; i < array_length; ++i) { 3602 assert( _surviving_young_words[i] == 0, "memset above" ); 3603 } 3604 #endif // !ASSERT 3605 } 3606 3607 void 3608 G1CollectedHeap::update_surviving_young_words(size_t* surv_young_words) { 3609 MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag); 3610 uint array_length = g1_policy()->young_cset_region_length(); 3611 for (uint i = 0; i < array_length; ++i) { 3612 _surviving_young_words[i] += surv_young_words[i]; 3613 } 3614 } 3615 3616 void 3617 G1CollectedHeap::cleanup_surviving_young_words() { 3618 guarantee( _surviving_young_words != NULL, "pre-condition" ); 3619 FREE_C_HEAP_ARRAY(size_t, _surviving_young_words); 3620 _surviving_young_words = NULL; 3621 } 3622 3623 #ifdef ASSERT 3624 class VerifyCSetClosure: public HeapRegionClosure { 3625 public: 3626 bool doHeapRegion(HeapRegion* hr) { 3627 // Here we check that the CSet region's RSet is ready for parallel 3628 // iteration. The fields that we'll verify are only manipulated 3629 // when the region is part of a CSet and is collected. Afterwards, 3630 // we reset these fields when we clear the region's RSet (when the 3631 // region is freed) so they are ready when the region is 3632 // re-allocated. The only exception to this is if there's an 3633 // evacuation failure and instead of freeing the region we leave 3634 // it in the heap. In that case, we reset these fields during 3635 // evacuation failure handling. 3636 guarantee(hr->rem_set()->verify_ready_for_par_iteration(), "verification"); 3637 3638 // Here's a good place to add any other checks we'd like to 3639 // perform on CSet regions. 3640 return false; 3641 } 3642 }; 3643 #endif // ASSERT 3644 3645 #if TASKQUEUE_STATS 3646 void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) { 3647 st->print_raw_cr("GC Task Stats"); 3648 st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr(); 3649 st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr(); 3650 } 3651 3652 void G1CollectedHeap::print_taskqueue_stats(outputStream* const st) const { 3653 print_taskqueue_stats_hdr(st); 3654 3655 TaskQueueStats totals; 3656 const int n = workers()->total_workers(); 3657 for (int i = 0; i < n; ++i) { 3658 st->print("%3d ", i); task_queue(i)->stats.print(st); st->cr(); 3659 totals += task_queue(i)->stats; 3660 } 3661 st->print_raw("tot "); totals.print(st); st->cr(); 3662 3663 DEBUG_ONLY(totals.verify()); 3664 } 3665 3666 void G1CollectedHeap::reset_taskqueue_stats() { 3667 const int n = workers()->total_workers(); 3668 for (int i = 0; i < n; ++i) { 3669 task_queue(i)->stats.reset(); 3670 } 3671 } 3672 #endif // TASKQUEUE_STATS 3673 3674 void G1CollectedHeap::log_gc_header() { 3675 if (!G1Log::fine()) { 3676 return; 3677 } 3678 3679 gclog_or_tty->gclog_stamp(_gc_tracer_stw->gc_id()); 3680 3681 GCCauseString gc_cause_str = GCCauseString("GC pause", gc_cause()) 3682 .append(g1_policy()->collector_state()->gcs_are_young() ? "(young)" : "(mixed)") 3683 .append(g1_policy()->collector_state()->during_initial_mark_pause() ? " (initial-mark)" : ""); 3684 3685 gclog_or_tty->print("[%s", (const char*)gc_cause_str); 3686 } 3687 3688 void G1CollectedHeap::log_gc_footer(double pause_time_sec) { 3689 if (!G1Log::fine()) { 3690 return; 3691 } 3692 3693 if (G1Log::finer()) { 3694 if (evacuation_failed()) { 3695 gclog_or_tty->print(" (to-space exhausted)"); 3696 } 3697 gclog_or_tty->print_cr(", %3.7f secs]", pause_time_sec); 3698 g1_policy()->phase_times()->note_gc_end(); 3699 g1_policy()->phase_times()->print(pause_time_sec); 3700 g1_policy()->print_detailed_heap_transition(); 3701 } else { 3702 if (evacuation_failed()) { 3703 gclog_or_tty->print("--"); 3704 } 3705 g1_policy()->print_heap_transition(); 3706 gclog_or_tty->print_cr(", %3.7f secs]", pause_time_sec); 3707 } 3708 gclog_or_tty->flush(); 3709 } 3710 3711 bool 3712 G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) { 3713 assert_at_safepoint(true /* should_be_vm_thread */); 3714 guarantee(!is_gc_active(), "collection is not reentrant"); 3715 3716 if (GC_locker::check_active_before_gc()) { 3717 return false; 3718 } 3719 3720 _gc_timer_stw->register_gc_start(); 3721 3722 _gc_tracer_stw->report_gc_start(gc_cause(), _gc_timer_stw->gc_start()); 3723 3724 SvcGCMarker sgcm(SvcGCMarker::MINOR); 3725 ResourceMark rm; 3726 3727 print_heap_before_gc(); 3728 trace_heap_before_gc(_gc_tracer_stw); 3729 3730 verify_region_sets_optional(); 3731 verify_dirty_young_regions(); 3732 3733 // This call will decide whether this pause is an initial-mark 3734 // pause. If it is, during_initial_mark_pause() will return true 3735 // for the duration of this pause. 3736 g1_policy()->decide_on_conc_mark_initiation(); 3737 3738 // We do not allow initial-mark to be piggy-backed on a mixed GC. 3739 assert(!g1_policy()->collector_state()->during_initial_mark_pause() || 3740 g1_policy()->collector_state()->gcs_are_young(), "sanity"); 3741 3742 // We also do not allow mixed GCs during marking. 3743 assert(!mark_in_progress() || g1_policy()->collector_state()->gcs_are_young(), "sanity"); 3744 3745 // Record whether this pause is an initial mark. When the current 3746 // thread has completed its logging output and it's safe to signal 3747 // the CM thread, the flag's value in the policy has been reset. 3748 bool should_start_conc_mark = g1_policy()->collector_state()->during_initial_mark_pause(); 3749 3750 // Inner scope for scope based logging, timers, and stats collection 3751 { 3752 EvacuationInfo evacuation_info; 3753 3754 if (g1_policy()->collector_state()->during_initial_mark_pause()) { 3755 // We are about to start a marking cycle, so we increment the 3756 // full collection counter. 3757 increment_old_marking_cycles_started(); 3758 register_concurrent_cycle_start(_gc_timer_stw->gc_start()); 3759 } 3760 3761 _gc_tracer_stw->report_yc_type(yc_type()); 3762 3763 TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty); 3764 3765 int active_workers = workers()->active_workers(); 3766 double pause_start_sec = os::elapsedTime(); 3767 g1_policy()->phase_times()->note_gc_start(active_workers); 3768 log_gc_header(); 3769 3770 TraceCollectorStats tcs(g1mm()->incremental_collection_counters()); 3771 TraceMemoryManagerStats tms(false /* fullGC */, gc_cause()); 3772 3773 // If the secondary_free_list is not empty, append it to the 3774 // free_list. No need to wait for the cleanup operation to finish; 3775 // the region allocation code will check the secondary_free_list 3776 // and wait if necessary. If the G1StressConcRegionFreeing flag is 3777 // set, skip this step so that the region allocation code has to 3778 // get entries from the secondary_free_list. 3779 if (!G1StressConcRegionFreeing) { 3780 append_secondary_free_list_if_not_empty_with_lock(); 3781 } 3782 3783 assert(check_young_list_well_formed(), "young list should be well formed"); 3784 3785 // Don't dynamically change the number of GC threads this early. A value of 3786 // 0 is used to indicate serial work. When parallel work is done, 3787 // it will be set. 3788 3789 { // Call to jvmpi::post_class_unload_events must occur outside of active GC 3790 IsGCActiveMark x; 3791 3792 gc_prologue(false); 3793 increment_total_collections(false /* full gc */); 3794 increment_gc_time_stamp(); 3795 3796 verify_before_gc(); 3797 3798 check_bitmaps("GC Start"); 3799 3800 COMPILER2_PRESENT(DerivedPointerTable::clear()); 3801 3802 // Please see comment in g1CollectedHeap.hpp and 3803 // G1CollectedHeap::ref_processing_init() to see how 3804 // reference processing currently works in G1. 3805 3806 // Enable discovery in the STW reference processor 3807 ref_processor_stw()->enable_discovery(); 3808 3809 { 3810 // We want to temporarily turn off discovery by the 3811 // CM ref processor, if necessary, and turn it back on 3812 // on again later if we do. Using a scoped 3813 // NoRefDiscovery object will do this. 3814 NoRefDiscovery no_cm_discovery(ref_processor_cm()); 3815 3816 // Forget the current alloc region (we might even choose it to be part 3817 // of the collection set!). 3818 _allocator->release_mutator_alloc_region(); 3819 3820 // We should call this after we retire the mutator alloc 3821 // region(s) so that all the ALLOC / RETIRE events are generated 3822 // before the start GC event. 3823 _hr_printer.start_gc(false /* full */, (size_t) total_collections()); 3824 3825 // This timing is only used by the ergonomics to handle our pause target. 3826 // It is unclear why this should not include the full pause. We will 3827 // investigate this in CR 7178365. 3828 // 3829 // Preserving the old comment here if that helps the investigation: 3830 // 3831 // The elapsed time induced by the start time below deliberately elides 3832 // the possible verification above. 3833 double sample_start_time_sec = os::elapsedTime(); 3834 3835 #if YOUNG_LIST_VERBOSE 3836 gclog_or_tty->print_cr("\nBefore recording pause start.\nYoung_list:"); 3837 _young_list->print(); 3838 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty); 3839 #endif // YOUNG_LIST_VERBOSE 3840 3841 g1_policy()->record_collection_pause_start(sample_start_time_sec); 3842 3843 double scan_wait_start = os::elapsedTime(); 3844 // We have to wait until the CM threads finish scanning the 3845 // root regions as it's the only way to ensure that all the 3846 // objects on them have been correctly scanned before we start 3847 // moving them during the GC. 3848 bool waited = _cm->root_regions()->wait_until_scan_finished(); 3849 double wait_time_ms = 0.0; 3850 if (waited) { 3851 double scan_wait_end = os::elapsedTime(); 3852 wait_time_ms = (scan_wait_end - scan_wait_start) * 1000.0; 3853 } 3854 g1_policy()->phase_times()->record_root_region_scan_wait_time(wait_time_ms); 3855 3856 #if YOUNG_LIST_VERBOSE 3857 gclog_or_tty->print_cr("\nAfter recording pause start.\nYoung_list:"); 3858 _young_list->print(); 3859 #endif // YOUNG_LIST_VERBOSE 3860 3861 if (g1_policy()->collector_state()->during_initial_mark_pause()) { 3862 concurrent_mark()->checkpointRootsInitialPre(); 3863 } 3864 3865 #if YOUNG_LIST_VERBOSE 3866 gclog_or_tty->print_cr("\nBefore choosing collection set.\nYoung_list:"); 3867 _young_list->print(); 3868 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty); 3869 #endif // YOUNG_LIST_VERBOSE 3870 3871 g1_policy()->finalize_cset(target_pause_time_ms, evacuation_info); 3872 3873 register_humongous_regions_with_in_cset_fast_test(); 3874 3875 assert(check_cset_fast_test(), "Inconsistency in the InCSetState table."); 3876 3877 _cm->note_start_of_gc(); 3878 // We should not verify the per-thread SATB buffers given that 3879 // we have not filtered them yet (we'll do so during the 3880 // GC). We also call this after finalize_cset() to 3881 // ensure that the CSet has been finalized. 3882 _cm->verify_no_cset_oops(true /* verify_stacks */, 3883 true /* verify_enqueued_buffers */, 3884 false /* verify_thread_buffers */, 3885 true /* verify_fingers */); 3886 3887 if (_hr_printer.is_active()) { 3888 HeapRegion* hr = g1_policy()->collection_set(); 3889 while (hr != NULL) { 3890 _hr_printer.cset(hr); 3891 hr = hr->next_in_collection_set(); 3892 } 3893 } 3894 3895 #ifdef ASSERT 3896 VerifyCSetClosure cl; 3897 collection_set_iterate(&cl); 3898 #endif // ASSERT 3899 3900 setup_surviving_young_words(); 3901 3902 // Initialize the GC alloc regions. 3903 _allocator->init_gc_alloc_regions(evacuation_info); 3904 3905 // Actually do the work... 3906 evacuate_collection_set(evacuation_info); 3907 3908 // We do this to mainly verify the per-thread SATB buffers 3909 // (which have been filtered by now) since we didn't verify 3910 // them earlier. No point in re-checking the stacks / enqueued 3911 // buffers given that the CSet has not changed since last time 3912 // we checked. 3913 _cm->verify_no_cset_oops(false /* verify_stacks */, 3914 false /* verify_enqueued_buffers */, 3915 true /* verify_thread_buffers */, 3916 true /* verify_fingers */); 3917 3918 free_collection_set(g1_policy()->collection_set(), evacuation_info); 3919 3920 eagerly_reclaim_humongous_regions(); 3921 3922 g1_policy()->clear_collection_set(); 3923 3924 cleanup_surviving_young_words(); 3925 3926 // Start a new incremental collection set for the next pause. 3927 g1_policy()->start_incremental_cset_building(); 3928 3929 clear_cset_fast_test(); 3930 3931 _young_list->reset_sampled_info(); 3932 3933 // Don't check the whole heap at this point as the 3934 // GC alloc regions from this pause have been tagged 3935 // as survivors and moved on to the survivor list. 3936 // Survivor regions will fail the !is_young() check. 3937 assert(check_young_list_empty(false /* check_heap */), 3938 "young list should be empty"); 3939 3940 #if YOUNG_LIST_VERBOSE 3941 gclog_or_tty->print_cr("Before recording survivors.\nYoung List:"); 3942 _young_list->print(); 3943 #endif // YOUNG_LIST_VERBOSE 3944 3945 g1_policy()->record_survivor_regions(_young_list->survivor_length(), 3946 _young_list->first_survivor_region(), 3947 _young_list->last_survivor_region()); 3948 3949 _young_list->reset_auxilary_lists(); 3950 3951 if (evacuation_failed()) { 3952 _allocator->set_used(recalculate_used()); 3953 uint n_queues = MAX2((int)ParallelGCThreads, 1); 3954 for (uint i = 0; i < n_queues; i++) { 3955 if (_evacuation_failed_info_array[i].has_failed()) { 3956 _gc_tracer_stw->report_evacuation_failed(_evacuation_failed_info_array[i]); 3957 } 3958 } 3959 } else { 3960 // The "used" of the the collection set have already been subtracted 3961 // when they were freed. Add in the bytes evacuated. 3962 _allocator->increase_used(g1_policy()->bytes_copied_during_gc()); 3963 } 3964 3965 if (g1_policy()->collector_state()->during_initial_mark_pause()) { 3966 // We have to do this before we notify the CM threads that 3967 // they can start working to make sure that all the 3968 // appropriate initialization is done on the CM object. 3969 concurrent_mark()->checkpointRootsInitialPost(); 3970 set_marking_started(); 3971 // Note that we don't actually trigger the CM thread at 3972 // this point. We do that later when we're sure that 3973 // the current thread has completed its logging output. 3974 } 3975 3976 allocate_dummy_regions(); 3977 3978 #if YOUNG_LIST_VERBOSE 3979 gclog_or_tty->print_cr("\nEnd of the pause.\nYoung_list:"); 3980 _young_list->print(); 3981 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty); 3982 #endif // YOUNG_LIST_VERBOSE 3983 3984 _allocator->init_mutator_alloc_region(); 3985 3986 { 3987 size_t expand_bytes = g1_policy()->expansion_amount(); 3988 if (expand_bytes > 0) { 3989 size_t bytes_before = capacity(); 3990 // No need for an ergo verbose message here, 3991 // expansion_amount() does this when it returns a value > 0. 3992 if (!expand(expand_bytes)) { 3993 // We failed to expand the heap. Cannot do anything about it. 3994 } 3995 } 3996 } 3997 3998 // We redo the verification but now wrt to the new CSet which 3999 // has just got initialized after the previous CSet was freed. 4000 _cm->verify_no_cset_oops(true /* verify_stacks */, 4001 true /* verify_enqueued_buffers */, 4002 true /* verify_thread_buffers */, 4003 true /* verify_fingers */); 4004 _cm->note_end_of_gc(); 4005 4006 // This timing is only used by the ergonomics to handle our pause target. 4007 // It is unclear why this should not include the full pause. We will 4008 // investigate this in CR 7178365. 4009 double sample_end_time_sec = os::elapsedTime(); 4010 double pause_time_ms = (sample_end_time_sec - sample_start_time_sec) * MILLIUNITS; 4011 g1_policy()->record_collection_pause_end(pause_time_ms, evacuation_info); 4012 4013 MemoryService::track_memory_usage(); 4014 4015 // In prepare_for_verify() below we'll need to scan the deferred 4016 // update buffers to bring the RSets up-to-date if 4017 // G1HRRSFlushLogBuffersOnVerify has been set. While scanning 4018 // the update buffers we'll probably need to scan cards on the 4019 // regions we just allocated to (i.e., the GC alloc 4020 // regions). However, during the last GC we called 4021 // set_saved_mark() on all the GC alloc regions, so card 4022 // scanning might skip the [saved_mark_word()...top()] area of 4023 // those regions (i.e., the area we allocated objects into 4024 // during the last GC). But it shouldn't. Given that 4025 // saved_mark_word() is conditional on whether the GC time stamp 4026 // on the region is current or not, by incrementing the GC time 4027 // stamp here we invalidate all the GC time stamps on all the 4028 // regions and saved_mark_word() will simply return top() for 4029 // all the regions. This is a nicer way of ensuring this rather 4030 // than iterating over the regions and fixing them. In fact, the 4031 // GC time stamp increment here also ensures that 4032 // saved_mark_word() will return top() between pauses, i.e., 4033 // during concurrent refinement. So we don't need the 4034 // is_gc_active() check to decided which top to use when 4035 // scanning cards (see CR 7039627). 4036 increment_gc_time_stamp(); 4037 4038 verify_after_gc(); 4039 check_bitmaps("GC End"); 4040 4041 assert(!ref_processor_stw()->discovery_enabled(), "Postcondition"); 4042 ref_processor_stw()->verify_no_references_recorded(); 4043 4044 // CM reference discovery will be re-enabled if necessary. 4045 } 4046 4047 // We should do this after we potentially expand the heap so 4048 // that all the COMMIT events are generated before the end GC 4049 // event, and after we retire the GC alloc regions so that all 4050 // RETIRE events are generated before the end GC event. 4051 _hr_printer.end_gc(false /* full */, (size_t) total_collections()); 4052 4053 #ifdef TRACESPINNING 4054 ParallelTaskTerminator::print_termination_counts(); 4055 #endif 4056 4057 gc_epilogue(false); 4058 } 4059 4060 // Print the remainder of the GC log output. 4061 log_gc_footer(os::elapsedTime() - pause_start_sec); 4062 4063 // It is not yet to safe to tell the concurrent mark to 4064 // start as we have some optional output below. We don't want the 4065 // output from the concurrent mark thread interfering with this 4066 // logging output either. 4067 4068 _hrm.verify_optional(); 4069 verify_region_sets_optional(); 4070 4071 TASKQUEUE_STATS_ONLY(if (PrintTaskqueue) print_taskqueue_stats()); 4072 TASKQUEUE_STATS_ONLY(reset_taskqueue_stats()); 4073 4074 print_heap_after_gc(); 4075 trace_heap_after_gc(_gc_tracer_stw); 4076 4077 // We must call G1MonitoringSupport::update_sizes() in the same scoping level 4078 // as an active TraceMemoryManagerStats object (i.e. before the destructor for the 4079 // TraceMemoryManagerStats is called) so that the G1 memory pools are updated 4080 // before any GC notifications are raised. 4081 g1mm()->update_sizes(); 4082 4083 _gc_tracer_stw->report_evacuation_info(&evacuation_info); 4084 _gc_tracer_stw->report_tenuring_threshold(_g1_policy->tenuring_threshold()); 4085 _gc_timer_stw->register_gc_end(); 4086 _gc_tracer_stw->report_gc_end(_gc_timer_stw->gc_end(), _gc_timer_stw->time_partitions()); 4087 } 4088 // It should now be safe to tell the concurrent mark thread to start 4089 // without its logging output interfering with the logging output 4090 // that came from the pause. 4091 4092 if (should_start_conc_mark) { 4093 // CAUTION: after the doConcurrentMark() call below, 4094 // the concurrent marking thread(s) could be running 4095 // concurrently with us. Make sure that anything after 4096 // this point does not assume that we are the only GC thread 4097 // running. Note: of course, the actual marking work will 4098 // not start until the safepoint itself is released in 4099 // SuspendibleThreadSet::desynchronize(). 4100 doConcurrentMark(); 4101 } 4102 4103 return true; 4104 } 4105 4106 void G1CollectedHeap::init_for_evac_failure(OopsInHeapRegionClosure* cl) { 4107 _drain_in_progress = false; 4108 set_evac_failure_closure(cl); 4109 _evac_failure_scan_stack = new (ResourceObj::C_HEAP, mtGC) GrowableArray<oop>(40, true); 4110 } 4111 4112 void G1CollectedHeap::finalize_for_evac_failure() { 4113 assert(_evac_failure_scan_stack != NULL && 4114 _evac_failure_scan_stack->length() == 0, 4115 "Postcondition"); 4116 assert(!_drain_in_progress, "Postcondition"); 4117 delete _evac_failure_scan_stack; 4118 _evac_failure_scan_stack = NULL; 4119 } 4120 4121 void G1CollectedHeap::remove_self_forwarding_pointers() { 4122 double remove_self_forwards_start = os::elapsedTime(); 4123 4124 set_par_threads(); 4125 G1ParRemoveSelfForwardPtrsTask rsfp_task(this); 4126 workers()->run_task(&rsfp_task); 4127 set_par_threads(0); 4128 4129 // Now restore saved marks, if any. 4130 assert(_objs_with_preserved_marks.size() == 4131 _preserved_marks_of_objs.size(), "Both or none."); 4132 while (!_objs_with_preserved_marks.is_empty()) { 4133 oop obj = _objs_with_preserved_marks.pop(); 4134 markOop m = _preserved_marks_of_objs.pop(); 4135 obj->set_mark(m); 4136 } 4137 _objs_with_preserved_marks.clear(true); 4138 _preserved_marks_of_objs.clear(true); 4139 4140 g1_policy()->phase_times()->record_evac_fail_remove_self_forwards((os::elapsedTime() - remove_self_forwards_start) * 1000.0); 4141 } 4142 4143 void G1CollectedHeap::push_on_evac_failure_scan_stack(oop obj) { 4144 _evac_failure_scan_stack->push(obj); 4145 } 4146 4147 void G1CollectedHeap::drain_evac_failure_scan_stack() { 4148 assert(_evac_failure_scan_stack != NULL, "precondition"); 4149 4150 while (_evac_failure_scan_stack->length() > 0) { 4151 oop obj = _evac_failure_scan_stack->pop(); 4152 _evac_failure_closure->set_region(heap_region_containing(obj)); 4153 obj->oop_iterate_backwards(_evac_failure_closure); 4154 } 4155 } 4156 4157 oop 4158 G1CollectedHeap::handle_evacuation_failure_par(G1ParScanThreadState* _par_scan_state, 4159 oop old) { 4160 assert(obj_in_cs(old), 4161 err_msg("obj: "PTR_FORMAT" should still be in the CSet", 4162 (HeapWord*) old)); 4163 markOop m = old->mark(); 4164 oop forward_ptr = old->forward_to_atomic(old); 4165 if (forward_ptr == NULL) { 4166 // Forward-to-self succeeded. 4167 assert(_par_scan_state != NULL, "par scan state"); 4168 OopsInHeapRegionClosure* cl = _par_scan_state->evac_failure_closure(); 4169 uint queue_num = _par_scan_state->queue_num(); 4170 4171 _evacuation_failed = true; 4172 _evacuation_failed_info_array[queue_num].register_copy_failure(old->size()); 4173 if (_evac_failure_closure != cl) { 4174 MutexLockerEx x(EvacFailureStack_lock, Mutex::_no_safepoint_check_flag); 4175 assert(!_drain_in_progress, 4176 "Should only be true while someone holds the lock."); 4177 // Set the global evac-failure closure to the current thread's. 4178 assert(_evac_failure_closure == NULL, "Or locking has failed."); 4179 set_evac_failure_closure(cl); 4180 // Now do the common part. 4181 handle_evacuation_failure_common(old, m); 4182 // Reset to NULL. 4183 set_evac_failure_closure(NULL); 4184 } else { 4185 // The lock is already held, and this is recursive. 4186 assert(_drain_in_progress, "This should only be the recursive case."); 4187 handle_evacuation_failure_common(old, m); 4188 } 4189 return old; 4190 } else { 4191 // Forward-to-self failed. Either someone else managed to allocate 4192 // space for this object (old != forward_ptr) or they beat us in 4193 // self-forwarding it (old == forward_ptr). 4194 assert(old == forward_ptr || !obj_in_cs(forward_ptr), 4195 err_msg("obj: "PTR_FORMAT" forwarded to: "PTR_FORMAT" " 4196 "should not be in the CSet", 4197 (HeapWord*) old, (HeapWord*) forward_ptr)); 4198 return forward_ptr; 4199 } 4200 } 4201 4202 void G1CollectedHeap::handle_evacuation_failure_common(oop old, markOop m) { 4203 preserve_mark_if_necessary(old, m); 4204 4205 HeapRegion* r = heap_region_containing(old); 4206 if (!r->evacuation_failed()) { 4207 r->set_evacuation_failed(true); 4208 _hr_printer.evac_failure(r); 4209 } 4210 4211 push_on_evac_failure_scan_stack(old); 4212 4213 if (!_drain_in_progress) { 4214 // prevent recursion in copy_to_survivor_space() 4215 _drain_in_progress = true; 4216 drain_evac_failure_scan_stack(); 4217 _drain_in_progress = false; 4218 } 4219 } 4220 4221 void G1CollectedHeap::preserve_mark_if_necessary(oop obj, markOop m) { 4222 assert(evacuation_failed(), "Oversaving!"); 4223 // We want to call the "for_promotion_failure" version only in the 4224 // case of a promotion failure. 4225 if (m->must_be_preserved_for_promotion_failure(obj)) { 4226 _objs_with_preserved_marks.push(obj); 4227 _preserved_marks_of_objs.push(m); 4228 } 4229 } 4230 4231 void G1ParCopyHelper::mark_object(oop obj) { 4232 assert(!_g1->heap_region_containing(obj)->in_collection_set(), "should not mark objects in the CSet"); 4233 4234 // We know that the object is not moving so it's safe to read its size. 4235 _cm->grayRoot(obj, (size_t) obj->size(), _worker_id); 4236 } 4237 4238 void G1ParCopyHelper::mark_forwarded_object(oop from_obj, oop to_obj) { 4239 assert(from_obj->is_forwarded(), "from obj should be forwarded"); 4240 assert(from_obj->forwardee() == to_obj, "to obj should be the forwardee"); 4241 assert(from_obj != to_obj, "should not be self-forwarded"); 4242 4243 assert(_g1->heap_region_containing(from_obj)->in_collection_set(), "from obj should be in the CSet"); 4244 assert(!_g1->heap_region_containing(to_obj)->in_collection_set(), "should not mark objects in the CSet"); 4245 4246 // The object might be in the process of being copied by another 4247 // worker so we cannot trust that its to-space image is 4248 // well-formed. So we have to read its size from its from-space 4249 // image which we know should not be changing. 4250 _cm->grayRoot(to_obj, (size_t) from_obj->size(), _worker_id); 4251 } 4252 4253 template <class T> 4254 void G1ParCopyHelper::do_klass_barrier(T* p, oop new_obj) { 4255 if (_g1->heap_region_containing_raw(new_obj)->is_young()) { 4256 _scanned_klass->record_modified_oops(); 4257 } 4258 } 4259 4260 template <G1Barrier barrier, G1Mark do_mark_object> 4261 template <class T> 4262 void G1ParCopyClosure<barrier, do_mark_object>::do_oop_work(T* p) { 4263 T heap_oop = oopDesc::load_heap_oop(p); 4264 4265 if (oopDesc::is_null(heap_oop)) { 4266 return; 4267 } 4268 4269 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop); 4270 4271 assert(_worker_id == _par_scan_state->queue_num(), "sanity"); 4272 4273 const InCSetState state = _g1->in_cset_state(obj); 4274 if (state.is_in_cset()) { 4275 oop forwardee; 4276 markOop m = obj->mark(); 4277 if (m->is_marked()) { 4278 forwardee = (oop) m->decode_pointer(); 4279 } else { 4280 forwardee = _par_scan_state->copy_to_survivor_space(state, obj, m); 4281 } 4282 assert(forwardee != NULL, "forwardee should not be NULL"); 4283 oopDesc::encode_store_heap_oop(p, forwardee); 4284 if (do_mark_object != G1MarkNone && forwardee != obj) { 4285 // If the object is self-forwarded we don't need to explicitly 4286 // mark it, the evacuation failure protocol will do so. 4287 mark_forwarded_object(obj, forwardee); 4288 } 4289 4290 if (barrier == G1BarrierKlass) { 4291 do_klass_barrier(p, forwardee); 4292 } 4293 } else { 4294 if (state.is_humongous()) { 4295 _g1->set_humongous_is_live(obj); 4296 } 4297 // The object is not in collection set. If we're a root scanning 4298 // closure during an initial mark pause then attempt to mark the object. 4299 if (do_mark_object == G1MarkFromRoot) { 4300 mark_object(obj); 4301 } 4302 } 4303 4304 if (barrier == G1BarrierEvac) { 4305 _par_scan_state->update_rs(_from, p, _worker_id); 4306 } 4307 } 4308 4309 template void G1ParCopyClosure<G1BarrierEvac, G1MarkNone>::do_oop_work(oop* p); 4310 template void G1ParCopyClosure<G1BarrierEvac, G1MarkNone>::do_oop_work(narrowOop* p); 4311 4312 class G1ParEvacuateFollowersClosure : public VoidClosure { 4313 protected: 4314 G1CollectedHeap* _g1h; 4315 G1ParScanThreadState* _par_scan_state; 4316 RefToScanQueueSet* _queues; 4317 ParallelTaskTerminator* _terminator; 4318 4319 G1ParScanThreadState* par_scan_state() { return _par_scan_state; } 4320 RefToScanQueueSet* queues() { return _queues; } 4321 ParallelTaskTerminator* terminator() { return _terminator; } 4322 4323 public: 4324 G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h, 4325 G1ParScanThreadState* par_scan_state, 4326 RefToScanQueueSet* queues, 4327 ParallelTaskTerminator* terminator) 4328 : _g1h(g1h), _par_scan_state(par_scan_state), 4329 _queues(queues), _terminator(terminator) {} 4330 4331 void do_void(); 4332 4333 private: 4334 inline bool offer_termination(); 4335 }; 4336 4337 bool G1ParEvacuateFollowersClosure::offer_termination() { 4338 G1ParScanThreadState* const pss = par_scan_state(); 4339 pss->start_term_time(); 4340 const bool res = terminator()->offer_termination(); 4341 pss->end_term_time(); 4342 return res; 4343 } 4344 4345 void G1ParEvacuateFollowersClosure::do_void() { 4346 G1ParScanThreadState* const pss = par_scan_state(); 4347 pss->trim_queue(); 4348 do { 4349 pss->steal_and_trim_queue(queues()); 4350 } while (!offer_termination()); 4351 } 4352 4353 class G1KlassScanClosure : public KlassClosure { 4354 G1ParCopyHelper* _closure; 4355 bool _process_only_dirty; 4356 int _count; 4357 public: 4358 G1KlassScanClosure(G1ParCopyHelper* closure, bool process_only_dirty) 4359 : _process_only_dirty(process_only_dirty), _closure(closure), _count(0) {} 4360 void do_klass(Klass* klass) { 4361 // If the klass has not been dirtied we know that there's 4362 // no references into the young gen and we can skip it. 4363 if (!_process_only_dirty || klass->has_modified_oops()) { 4364 // Clean the klass since we're going to scavenge all the metadata. 4365 klass->clear_modified_oops(); 4366 4367 // Tell the closure that this klass is the Klass to scavenge 4368 // and is the one to dirty if oops are left pointing into the young gen. 4369 _closure->set_scanned_klass(klass); 4370 4371 klass->oops_do(_closure); 4372 4373 _closure->set_scanned_klass(NULL); 4374 } 4375 _count++; 4376 } 4377 }; 4378 4379 class G1CodeBlobClosure : public CodeBlobClosure { 4380 class HeapRegionGatheringOopClosure : public OopClosure { 4381 G1CollectedHeap* _g1h; 4382 OopClosure* _work; 4383 nmethod* _nm; 4384 4385 template <typename T> 4386 void do_oop_work(T* p) { 4387 _work->do_oop(p); 4388 T oop_or_narrowoop = oopDesc::load_heap_oop(p); 4389 if (!oopDesc::is_null(oop_or_narrowoop)) { 4390 oop o = oopDesc::decode_heap_oop_not_null(oop_or_narrowoop); 4391 HeapRegion* hr = _g1h->heap_region_containing_raw(o); 4392 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"); 4393 hr->add_strong_code_root(_nm); 4394 } 4395 } 4396 4397 public: 4398 HeapRegionGatheringOopClosure(OopClosure* oc) : _g1h(G1CollectedHeap::heap()), _work(oc), _nm(NULL) {} 4399 4400 void do_oop(oop* o) { 4401 do_oop_work(o); 4402 } 4403 4404 void do_oop(narrowOop* o) { 4405 do_oop_work(o); 4406 } 4407 4408 void set_nm(nmethod* nm) { 4409 _nm = nm; 4410 } 4411 }; 4412 4413 HeapRegionGatheringOopClosure _oc; 4414 public: 4415 G1CodeBlobClosure(OopClosure* oc) : _oc(oc) {} 4416 4417 void do_code_blob(CodeBlob* cb) { 4418 nmethod* nm = cb->as_nmethod_or_null(); 4419 if (nm != NULL) { 4420 if (!nm->test_set_oops_do_mark()) { 4421 _oc.set_nm(nm); 4422 nm->oops_do(&_oc); 4423 nm->fix_oop_relocations(); 4424 } 4425 } 4426 } 4427 }; 4428 4429 class G1ParTask : public AbstractGangTask { 4430 protected: 4431 G1CollectedHeap* _g1h; 4432 RefToScanQueueSet *_queues; 4433 ParallelTaskTerminator _terminator; 4434 uint _n_workers; 4435 4436 Mutex _stats_lock; 4437 Mutex* stats_lock() { return &_stats_lock; } 4438 4439 public: 4440 G1ParTask(G1CollectedHeap* g1h, RefToScanQueueSet *task_queues) 4441 : AbstractGangTask("G1 collection"), 4442 _g1h(g1h), 4443 _queues(task_queues), 4444 _terminator(0, _queues), 4445 _stats_lock(Mutex::leaf, "parallel G1 stats lock", true) 4446 {} 4447 4448 RefToScanQueueSet* queues() { return _queues; } 4449 4450 RefToScanQueue *work_queue(int i) { 4451 return queues()->queue(i); 4452 } 4453 4454 ParallelTaskTerminator* terminator() { return &_terminator; } 4455 4456 virtual void set_for_termination(int active_workers) { 4457 // This task calls set_n_termination() in par_non_clean_card_iterate_work() 4458 // in the young space (_par_seq_tasks) in the G1 heap 4459 // for SequentialSubTasksDone. 4460 // This task also uses SubTasksDone in SharedHeap and G1CollectedHeap 4461 // both of which need setting by set_n_termination(). 4462 _g1h->SharedHeap::set_n_termination(active_workers); 4463 _g1h->set_n_termination(active_workers); 4464 terminator()->reset_for_reuse(active_workers); 4465 _n_workers = active_workers; 4466 } 4467 4468 // Helps out with CLD processing. 4469 // 4470 // During InitialMark we need to: 4471 // 1) Scavenge all CLDs for the young GC. 4472 // 2) Mark all objects directly reachable from strong CLDs. 4473 template <G1Mark do_mark_object> 4474 class G1CLDClosure : public CLDClosure { 4475 G1ParCopyClosure<G1BarrierNone, do_mark_object>* _oop_closure; 4476 G1ParCopyClosure<G1BarrierKlass, do_mark_object> _oop_in_klass_closure; 4477 G1KlassScanClosure _klass_in_cld_closure; 4478 bool _claim; 4479 4480 public: 4481 G1CLDClosure(G1ParCopyClosure<G1BarrierNone, do_mark_object>* oop_closure, 4482 bool only_young, bool claim) 4483 : _oop_closure(oop_closure), 4484 _oop_in_klass_closure(oop_closure->g1(), 4485 oop_closure->pss(), 4486 oop_closure->rp()), 4487 _klass_in_cld_closure(&_oop_in_klass_closure, only_young), 4488 _claim(claim) { 4489 4490 } 4491 4492 void do_cld(ClassLoaderData* cld) { 4493 cld->oops_do(_oop_closure, &_klass_in_cld_closure, _claim); 4494 } 4495 }; 4496 4497 void work(uint worker_id) { 4498 if (worker_id >= _n_workers) return; // no work needed this round 4499 4500 double start_time_ms = os::elapsedTime() * 1000.0; 4501 _g1h->g1_policy()->phase_times()->record_gc_worker_start_time(worker_id, start_time_ms); 4502 4503 { 4504 ResourceMark rm; 4505 HandleMark hm; 4506 4507 ReferenceProcessor* rp = _g1h->ref_processor_stw(); 4508 4509 G1ParScanThreadState pss(_g1h, worker_id, rp); 4510 G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, rp); 4511 4512 pss.set_evac_failure_closure(&evac_failure_cl); 4513 4514 bool only_young = _g1h->g1_policy()->collector_state()->gcs_are_young(); 4515 4516 // Non-IM young GC. 4517 G1ParCopyClosure<G1BarrierNone, G1MarkNone> scan_only_root_cl(_g1h, &pss, rp); 4518 G1CLDClosure<G1MarkNone> scan_only_cld_cl(&scan_only_root_cl, 4519 only_young, // Only process dirty klasses. 4520 false); // No need to claim CLDs. 4521 // IM young GC. 4522 // Strong roots closures. 4523 G1ParCopyClosure<G1BarrierNone, G1MarkFromRoot> scan_mark_root_cl(_g1h, &pss, rp); 4524 G1CLDClosure<G1MarkFromRoot> scan_mark_cld_cl(&scan_mark_root_cl, 4525 false, // Process all klasses. 4526 true); // Need to claim CLDs. 4527 // Weak roots closures. 4528 G1ParCopyClosure<G1BarrierNone, G1MarkPromotedFromRoot> scan_mark_weak_root_cl(_g1h, &pss, rp); 4529 G1CLDClosure<G1MarkPromotedFromRoot> scan_mark_weak_cld_cl(&scan_mark_weak_root_cl, 4530 false, // Process all klasses. 4531 true); // Need to claim CLDs. 4532 4533 G1CodeBlobClosure scan_only_code_cl(&scan_only_root_cl); 4534 G1CodeBlobClosure scan_mark_code_cl(&scan_mark_root_cl); 4535 // IM Weak code roots are handled later. 4536 4537 OopClosure* strong_root_cl; 4538 OopClosure* weak_root_cl; 4539 CLDClosure* strong_cld_cl; 4540 CLDClosure* weak_cld_cl; 4541 CodeBlobClosure* strong_code_cl; 4542 4543 if (_g1h->g1_policy()->collector_state()->during_initial_mark_pause()) { 4544 // We also need to mark copied objects. 4545 strong_root_cl = &scan_mark_root_cl; 4546 strong_cld_cl = &scan_mark_cld_cl; 4547 strong_code_cl = &scan_mark_code_cl; 4548 if (ClassUnloadingWithConcurrentMark) { 4549 weak_root_cl = &scan_mark_weak_root_cl; 4550 weak_cld_cl = &scan_mark_weak_cld_cl; 4551 } else { 4552 weak_root_cl = &scan_mark_root_cl; 4553 weak_cld_cl = &scan_mark_cld_cl; 4554 } 4555 } else { 4556 strong_root_cl = &scan_only_root_cl; 4557 weak_root_cl = &scan_only_root_cl; 4558 strong_cld_cl = &scan_only_cld_cl; 4559 weak_cld_cl = &scan_only_cld_cl; 4560 strong_code_cl = &scan_only_code_cl; 4561 } 4562 4563 4564 G1ParPushHeapRSClosure push_heap_rs_cl(_g1h, &pss); 4565 4566 pss.start_strong_roots(); 4567 _g1h->g1_process_roots(strong_root_cl, 4568 weak_root_cl, 4569 &push_heap_rs_cl, 4570 strong_cld_cl, 4571 weak_cld_cl, 4572 strong_code_cl, 4573 worker_id); 4574 4575 pss.end_strong_roots(); 4576 4577 { 4578 double start = os::elapsedTime(); 4579 G1ParEvacuateFollowersClosure evac(_g1h, &pss, _queues, &_terminator); 4580 evac.do_void(); 4581 double elapsed_ms = (os::elapsedTime()-start)*1000.0; 4582 double term_ms = pss.term_time()*1000.0; 4583 _g1h->g1_policy()->phase_times()->add_obj_copy_time(worker_id, elapsed_ms-term_ms); 4584 _g1h->g1_policy()->phase_times()->record_termination(worker_id, term_ms, pss.term_attempts()); 4585 } 4586 _g1h->g1_policy()->record_thread_age_table(pss.age_table()); 4587 _g1h->update_surviving_young_words(pss.surviving_young_words()+1); 4588 4589 if (PrintTerminationStats) { 4590 MutexLocker x(stats_lock()); 4591 pss.print_termination_stats(worker_id); 4592 } 4593 4594 assert(pss.queue_is_empty(), "should be empty"); 4595 4596 // Close the inner scope so that the ResourceMark and HandleMark 4597 // destructors are executed here and are included as part of the 4598 // "GC Worker Time". 4599 } 4600 4601 double end_time_ms = os::elapsedTime() * 1000.0; 4602 _g1h->g1_policy()->phase_times()->record_gc_worker_end_time(worker_id, end_time_ms); 4603 } 4604 }; 4605 4606 // *** Common G1 Evacuation Stuff 4607 4608 // This method is run in a GC worker. 4609 4610 void 4611 G1CollectedHeap:: 4612 g1_process_roots(OopClosure* scan_non_heap_roots, 4613 OopClosure* scan_non_heap_weak_roots, 4614 G1ParPushHeapRSClosure* scan_rs, 4615 CLDClosure* scan_strong_clds, 4616 CLDClosure* scan_weak_clds, 4617 CodeBlobClosure* scan_strong_code, 4618 uint worker_i) { 4619 4620 // First scan the shared roots. 4621 double ext_roots_start = os::elapsedTime(); 4622 double closure_app_time_sec = 0.0; 4623 4624 bool during_im = _g1h->g1_policy()->collector_state()->during_initial_mark_pause(); 4625 bool trace_metadata = during_im && ClassUnloadingWithConcurrentMark; 4626 4627 BufferingOopClosure buf_scan_non_heap_roots(scan_non_heap_roots); 4628 BufferingOopClosure buf_scan_non_heap_weak_roots(scan_non_heap_weak_roots); 4629 4630 process_roots(false, // no scoping; this is parallel code 4631 SharedHeap::SO_None, 4632 &buf_scan_non_heap_roots, 4633 &buf_scan_non_heap_weak_roots, 4634 scan_strong_clds, 4635 // Unloading Initial Marks handle the weak CLDs separately. 4636 (trace_metadata ? NULL : scan_weak_clds), 4637 scan_strong_code); 4638 4639 // Now the CM ref_processor roots. 4640 if (!_process_strong_tasks->is_task_claimed(G1H_PS_refProcessor_oops_do)) { 4641 // We need to treat the discovered reference lists of the 4642 // concurrent mark ref processor as roots and keep entries 4643 // (which are added by the marking threads) on them live 4644 // until they can be processed at the end of marking. 4645 ref_processor_cm()->weak_oops_do(&buf_scan_non_heap_roots); 4646 } 4647 4648 if (trace_metadata) { 4649 // Barrier to make sure all workers passed 4650 // the strong CLD and strong nmethods phases. 4651 active_strong_roots_scope()->wait_until_all_workers_done_with_threads(n_par_threads()); 4652 4653 // Now take the complement of the strong CLDs. 4654 ClassLoaderDataGraph::roots_cld_do(NULL, scan_weak_clds); 4655 } 4656 4657 // Finish up any enqueued closure apps (attributed as object copy time). 4658 buf_scan_non_heap_roots.done(); 4659 buf_scan_non_heap_weak_roots.done(); 4660 4661 double obj_copy_time_sec = buf_scan_non_heap_roots.closure_app_seconds() 4662 + buf_scan_non_heap_weak_roots.closure_app_seconds(); 4663 4664 g1_policy()->phase_times()->record_obj_copy_time(worker_i, obj_copy_time_sec * 1000.0); 4665 4666 double ext_root_time_ms = 4667 ((os::elapsedTime() - ext_roots_start) - obj_copy_time_sec) * 1000.0; 4668 4669 g1_policy()->phase_times()->record_ext_root_scan_time(worker_i, ext_root_time_ms); 4670 4671 // During conc marking we have to filter the per-thread SATB buffers 4672 // to make sure we remove any oops into the CSet (which will show up 4673 // as implicitly live). 4674 double satb_filtering_ms = 0.0; 4675 if (!_process_strong_tasks->is_task_claimed(G1H_PS_filter_satb_buffers)) { 4676 if (mark_in_progress()) { 4677 double satb_filter_start = os::elapsedTime(); 4678 4679 JavaThread::satb_mark_queue_set().filter_thread_buffers(); 4680 4681 satb_filtering_ms = (os::elapsedTime() - satb_filter_start) * 1000.0; 4682 } 4683 } 4684 g1_policy()->phase_times()->record_satb_filtering_time(worker_i, satb_filtering_ms); 4685 4686 // Now scan the complement of the collection set. 4687 G1CodeBlobClosure scavenge_cs_nmethods(scan_non_heap_weak_roots); 4688 4689 g1_rem_set()->oops_into_collection_set_do(scan_rs, &scavenge_cs_nmethods, worker_i); 4690 4691 _process_strong_tasks->all_tasks_completed(); 4692 } 4693 4694 class G1StringSymbolTableUnlinkTask : public AbstractGangTask { 4695 private: 4696 BoolObjectClosure* _is_alive; 4697 int _initial_string_table_size; 4698 int _initial_symbol_table_size; 4699 4700 bool _process_strings; 4701 int _strings_processed; 4702 int _strings_removed; 4703 4704 bool _process_symbols; 4705 int _symbols_processed; 4706 int _symbols_removed; 4707 4708 public: 4709 G1StringSymbolTableUnlinkTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols) : 4710 AbstractGangTask("String/Symbol Unlinking"), 4711 _is_alive(is_alive), 4712 _process_strings(process_strings), _strings_processed(0), _strings_removed(0), 4713 _process_symbols(process_symbols), _symbols_processed(0), _symbols_removed(0) { 4714 4715 _initial_string_table_size = StringTable::the_table()->table_size(); 4716 _initial_symbol_table_size = SymbolTable::the_table()->table_size(); 4717 if (process_strings) { 4718 StringTable::clear_parallel_claimed_index(); 4719 } 4720 if (process_symbols) { 4721 SymbolTable::clear_parallel_claimed_index(); 4722 } 4723 } 4724 4725 ~G1StringSymbolTableUnlinkTask() { 4726 guarantee(!_process_strings || StringTable::parallel_claimed_index() >= _initial_string_table_size, 4727 err_msg("claim value %d after unlink less than initial string table size %d", 4728 StringTable::parallel_claimed_index(), _initial_string_table_size)); 4729 guarantee(!_process_symbols || SymbolTable::parallel_claimed_index() >= _initial_symbol_table_size, 4730 err_msg("claim value %d after unlink less than initial symbol table size %d", 4731 SymbolTable::parallel_claimed_index(), _initial_symbol_table_size)); 4732 4733 if (G1TraceStringSymbolTableScrubbing) { 4734 gclog_or_tty->print_cr("Cleaned string and symbol table, " 4735 "strings: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed, " 4736 "symbols: "SIZE_FORMAT" processed, "SIZE_FORMAT" removed", 4737 strings_processed(), strings_removed(), 4738 symbols_processed(), symbols_removed()); 4739 } 4740 } 4741 4742 void work(uint worker_id) { 4743 int strings_processed = 0; 4744 int strings_removed = 0; 4745 int symbols_processed = 0; 4746 int symbols_removed = 0; 4747 if (_process_strings) { 4748 StringTable::possibly_parallel_unlink(_is_alive, &strings_processed, &strings_removed); 4749 Atomic::add(strings_processed, &_strings_processed); 4750 Atomic::add(strings_removed, &_strings_removed); 4751 } 4752 if (_process_symbols) { 4753 SymbolTable::possibly_parallel_unlink(&symbols_processed, &symbols_removed); 4754 Atomic::add(symbols_processed, &_symbols_processed); 4755 Atomic::add(symbols_removed, &_symbols_removed); 4756 } 4757 } 4758 4759 size_t strings_processed() const { return (size_t)_strings_processed; } 4760 size_t strings_removed() const { return (size_t)_strings_removed; } 4761 4762 size_t symbols_processed() const { return (size_t)_symbols_processed; } 4763 size_t symbols_removed() const { return (size_t)_symbols_removed; } 4764 }; 4765 4766 class G1CodeCacheUnloadingTask VALUE_OBJ_CLASS_SPEC { 4767 private: 4768 static Monitor* _lock; 4769 4770 BoolObjectClosure* const _is_alive; 4771 const bool _unloading_occurred; 4772 const uint _num_workers; 4773 4774 // Variables used to claim nmethods. 4775 nmethod* _first_nmethod; 4776 volatile nmethod* _claimed_nmethod; 4777 4778 // The list of nmethods that need to be processed by the second pass. 4779 volatile nmethod* _postponed_list; 4780 volatile uint _num_entered_barrier; 4781 4782 public: 4783 G1CodeCacheUnloadingTask(uint num_workers, BoolObjectClosure* is_alive, bool unloading_occurred) : 4784 _is_alive(is_alive), 4785 _unloading_occurred(unloading_occurred), 4786 _num_workers(num_workers), 4787 _first_nmethod(NULL), 4788 _claimed_nmethod(NULL), 4789 _postponed_list(NULL), 4790 _num_entered_barrier(0) 4791 { 4792 nmethod::increase_unloading_clock(); 4793 // Get first alive nmethod 4794 NMethodIterator iter = NMethodIterator(); 4795 if(iter.next_alive()) { 4796 _first_nmethod = iter.method(); 4797 } 4798 _claimed_nmethod = (volatile nmethod*)_first_nmethod; 4799 } 4800 4801 ~G1CodeCacheUnloadingTask() { 4802 CodeCache::verify_clean_inline_caches(); 4803 4804 CodeCache::set_needs_cache_clean(false); 4805 guarantee(CodeCache::scavenge_root_nmethods() == NULL, "Must be"); 4806 4807 CodeCache::verify_icholder_relocations(); 4808 } 4809 4810 private: 4811 void add_to_postponed_list(nmethod* nm) { 4812 nmethod* old; 4813 do { 4814 old = (nmethod*)_postponed_list; 4815 nm->set_unloading_next(old); 4816 } while ((nmethod*)Atomic::cmpxchg_ptr(nm, &_postponed_list, old) != old); 4817 } 4818 4819 void clean_nmethod(nmethod* nm) { 4820 bool postponed = nm->do_unloading_parallel(_is_alive, _unloading_occurred); 4821 4822 if (postponed) { 4823 // This nmethod referred to an nmethod that has not been cleaned/unloaded yet. 4824 add_to_postponed_list(nm); 4825 } 4826 4827 // Mark that this thread has been cleaned/unloaded. 4828 // After this call, it will be safe to ask if this nmethod was unloaded or not. 4829 nm->set_unloading_clock(nmethod::global_unloading_clock()); 4830 } 4831 4832 void clean_nmethod_postponed(nmethod* nm) { 4833 nm->do_unloading_parallel_postponed(_is_alive, _unloading_occurred); 4834 } 4835 4836 static const int MaxClaimNmethods = 16; 4837 4838 void claim_nmethods(nmethod** claimed_nmethods, int *num_claimed_nmethods) { 4839 nmethod* first; 4840 NMethodIterator last; 4841 4842 do { 4843 *num_claimed_nmethods = 0; 4844 4845 first = (nmethod*)_claimed_nmethod; 4846 last = NMethodIterator(first); 4847 4848 if (first != NULL) { 4849 4850 for (int i = 0; i < MaxClaimNmethods; i++) { 4851 if (!last.next_alive()) { 4852 break; 4853 } 4854 claimed_nmethods[i] = last.method(); 4855 (*num_claimed_nmethods)++; 4856 } 4857 } 4858 4859 } while ((nmethod*)Atomic::cmpxchg_ptr(last.method(), &_claimed_nmethod, first) != first); 4860 } 4861 4862 nmethod* claim_postponed_nmethod() { 4863 nmethod* claim; 4864 nmethod* next; 4865 4866 do { 4867 claim = (nmethod*)_postponed_list; 4868 if (claim == NULL) { 4869 return NULL; 4870 } 4871 4872 next = claim->unloading_next(); 4873 4874 } while ((nmethod*)Atomic::cmpxchg_ptr(next, &_postponed_list, claim) != claim); 4875 4876 return claim; 4877 } 4878 4879 public: 4880 // Mark that we're done with the first pass of nmethod cleaning. 4881 void barrier_mark(uint worker_id) { 4882 MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag); 4883 _num_entered_barrier++; 4884 if (_num_entered_barrier == _num_workers) { 4885 ml.notify_all(); 4886 } 4887 } 4888 4889 // See if we have to wait for the other workers to 4890 // finish their first-pass nmethod cleaning work. 4891 void barrier_wait(uint worker_id) { 4892 if (_num_entered_barrier < _num_workers) { 4893 MonitorLockerEx ml(_lock, Mutex::_no_safepoint_check_flag); 4894 while (_num_entered_barrier < _num_workers) { 4895 ml.wait(Mutex::_no_safepoint_check_flag, 0, false); 4896 } 4897 } 4898 } 4899 4900 // Cleaning and unloading of nmethods. Some work has to be postponed 4901 // to the second pass, when we know which nmethods survive. 4902 void work_first_pass(uint worker_id) { 4903 // The first nmethods is claimed by the first worker. 4904 if (worker_id == 0 && _first_nmethod != NULL) { 4905 clean_nmethod(_first_nmethod); 4906 _first_nmethod = NULL; 4907 } 4908 4909 int num_claimed_nmethods; 4910 nmethod* claimed_nmethods[MaxClaimNmethods]; 4911 4912 while (true) { 4913 claim_nmethods(claimed_nmethods, &num_claimed_nmethods); 4914 4915 if (num_claimed_nmethods == 0) { 4916 break; 4917 } 4918 4919 for (int i = 0; i < num_claimed_nmethods; i++) { 4920 clean_nmethod(claimed_nmethods[i]); 4921 } 4922 } 4923 4924 // The nmethod cleaning helps out and does the CodeCache part of MetadataOnStackMark. 4925 // Need to retire the buffers now that this thread has stopped cleaning nmethods. 4926 MetadataOnStackMark::retire_buffer_for_thread(Thread::current()); 4927 } 4928 4929 void work_second_pass(uint worker_id) { 4930 nmethod* nm; 4931 // Take care of postponed nmethods. 4932 while ((nm = claim_postponed_nmethod()) != NULL) { 4933 clean_nmethod_postponed(nm); 4934 } 4935 } 4936 }; 4937 4938 Monitor* G1CodeCacheUnloadingTask::_lock = new Monitor(Mutex::leaf, "Code Cache Unload lock", false, Monitor::_safepoint_check_never); 4939 4940 class G1KlassCleaningTask : public StackObj { 4941 BoolObjectClosure* _is_alive; 4942 volatile jint _clean_klass_tree_claimed; 4943 ClassLoaderDataGraphKlassIteratorAtomic _klass_iterator; 4944 4945 public: 4946 G1KlassCleaningTask(BoolObjectClosure* is_alive) : 4947 _is_alive(is_alive), 4948 _clean_klass_tree_claimed(0), 4949 _klass_iterator() { 4950 } 4951 4952 private: 4953 bool claim_clean_klass_tree_task() { 4954 if (_clean_klass_tree_claimed) { 4955 return false; 4956 } 4957 4958 return Atomic::cmpxchg(1, (jint*)&_clean_klass_tree_claimed, 0) == 0; 4959 } 4960 4961 InstanceKlass* claim_next_klass() { 4962 Klass* klass; 4963 do { 4964 klass =_klass_iterator.next_klass(); 4965 } while (klass != NULL && !klass->oop_is_instance()); 4966 4967 return (InstanceKlass*)klass; 4968 } 4969 4970 public: 4971 4972 void clean_klass(InstanceKlass* ik) { 4973 ik->clean_implementors_list(_is_alive); 4974 ik->clean_method_data(_is_alive); 4975 4976 // G1 specific cleanup work that has 4977 // been moved here to be done in parallel. 4978 ik->clean_dependent_nmethods(); 4979 if (JvmtiExport::has_redefined_a_class()) { 4980 InstanceKlass::purge_previous_versions(ik); 4981 } 4982 } 4983 4984 void work() { 4985 ResourceMark rm; 4986 4987 // One worker will clean the subklass/sibling klass tree. 4988 if (claim_clean_klass_tree_task()) { 4989 Klass::clean_subklass_tree(_is_alive); 4990 } 4991 4992 // All workers will help cleaning the classes, 4993 InstanceKlass* klass; 4994 while ((klass = claim_next_klass()) != NULL) { 4995 clean_klass(klass); 4996 } 4997 } 4998 }; 4999 5000 // To minimize the remark pause times, the tasks below are done in parallel. 5001 class G1ParallelCleaningTask : public AbstractGangTask { 5002 private: 5003 G1StringSymbolTableUnlinkTask _string_symbol_task; 5004 G1CodeCacheUnloadingTask _code_cache_task; 5005 G1KlassCleaningTask _klass_cleaning_task; 5006 5007 public: 5008 // The constructor is run in the VMThread. 5009 G1ParallelCleaningTask(BoolObjectClosure* is_alive, bool process_strings, bool process_symbols, uint num_workers, bool unloading_occurred) : 5010 AbstractGangTask("Parallel Cleaning"), 5011 _string_symbol_task(is_alive, process_strings, process_symbols), 5012 _code_cache_task(num_workers, is_alive, unloading_occurred), 5013 _klass_cleaning_task(is_alive) { 5014 } 5015 5016 void pre_work_verification() { 5017 assert(!MetadataOnStackMark::has_buffer_for_thread(Thread::current()), "Should be empty"); 5018 } 5019 5020 void post_work_verification() { 5021 assert(!MetadataOnStackMark::has_buffer_for_thread(Thread::current()), "Should be empty"); 5022 } 5023 5024 // The parallel work done by all worker threads. 5025 void work(uint worker_id) { 5026 pre_work_verification(); 5027 5028 // Do first pass of code cache cleaning. 5029 _code_cache_task.work_first_pass(worker_id); 5030 5031 // Let the threads mark that the first pass is done. 5032 _code_cache_task.barrier_mark(worker_id); 5033 5034 // Clean the Strings and Symbols. 5035 _string_symbol_task.work(worker_id); 5036 5037 // Wait for all workers to finish the first code cache cleaning pass. 5038 _code_cache_task.barrier_wait(worker_id); 5039 5040 // Do the second code cache cleaning work, which realize on 5041 // the liveness information gathered during the first pass. 5042 _code_cache_task.work_second_pass(worker_id); 5043 5044 // Clean all klasses that were not unloaded. 5045 _klass_cleaning_task.work(); 5046 5047 post_work_verification(); 5048 } 5049 }; 5050 5051 5052 void G1CollectedHeap::parallel_cleaning(BoolObjectClosure* is_alive, 5053 bool process_strings, 5054 bool process_symbols, 5055 bool class_unloading_occurred) { 5056 uint n_workers = workers()->active_workers(); 5057 5058 G1ParallelCleaningTask g1_unlink_task(is_alive, process_strings, process_symbols, 5059 n_workers, class_unloading_occurred); 5060 set_par_threads(n_workers); 5061 workers()->run_task(&g1_unlink_task); 5062 set_par_threads(0); 5063 } 5064 5065 void G1CollectedHeap::unlink_string_and_symbol_table(BoolObjectClosure* is_alive, 5066 bool process_strings, bool process_symbols) { 5067 { 5068 uint n_workers = _g1h->workers()->active_workers(); 5069 G1StringSymbolTableUnlinkTask g1_unlink_task(is_alive, process_strings, process_symbols); 5070 set_par_threads(n_workers); 5071 workers()->run_task(&g1_unlink_task); 5072 set_par_threads(0); 5073 } 5074 5075 if (G1StringDedup::is_enabled()) { 5076 G1StringDedup::unlink(is_alive); 5077 } 5078 } 5079 5080 class G1RedirtyLoggedCardsTask : public AbstractGangTask { 5081 private: 5082 DirtyCardQueueSet* _queue; 5083 public: 5084 G1RedirtyLoggedCardsTask(DirtyCardQueueSet* queue) : AbstractGangTask("Redirty Cards"), _queue(queue) { } 5085 5086 virtual void work(uint worker_id) { 5087 double start_time = os::elapsedTime(); 5088 5089 RedirtyLoggedCardTableEntryClosure cl; 5090 _queue->par_apply_closure_to_all_completed_buffers(&cl); 5091 5092 G1GCPhaseTimes* timer = G1CollectedHeap::heap()->g1_policy()->phase_times(); 5093 timer->record_redirty_logged_cards_time_ms(worker_id, (os::elapsedTime() - start_time) * 1000.0); 5094 timer->record_redirty_logged_cards_processed_cards(worker_id, cl.num_processed()); 5095 } 5096 }; 5097 5098 void G1CollectedHeap::redirty_logged_cards() { 5099 double redirty_logged_cards_start = os::elapsedTime(); 5100 5101 uint n_workers = _g1h->workers()->active_workers(); 5102 5103 G1RedirtyLoggedCardsTask redirty_task(&dirty_card_queue_set()); 5104 dirty_card_queue_set().reset_for_par_iteration(); 5105 set_par_threads(n_workers); 5106 workers()->run_task(&redirty_task); 5107 set_par_threads(0); 5108 5109 DirtyCardQueueSet& dcq = JavaThread::dirty_card_queue_set(); 5110 dcq.merge_bufferlists(&dirty_card_queue_set()); 5111 assert(dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed"); 5112 5113 g1_policy()->phase_times()->record_redirty_logged_cards_time_ms((os::elapsedTime() - redirty_logged_cards_start) * 1000.0); 5114 } 5115 5116 // Weak Reference Processing support 5117 5118 // An always "is_alive" closure that is used to preserve referents. 5119 // If the object is non-null then it's alive. Used in the preservation 5120 // of referent objects that are pointed to by reference objects 5121 // discovered by the CM ref processor. 5122 class G1AlwaysAliveClosure: public BoolObjectClosure { 5123 G1CollectedHeap* _g1; 5124 public: 5125 G1AlwaysAliveClosure(G1CollectedHeap* g1) : _g1(g1) {} 5126 bool do_object_b(oop p) { 5127 if (p != NULL) { 5128 return true; 5129 } 5130 return false; 5131 } 5132 }; 5133 5134 bool G1STWIsAliveClosure::do_object_b(oop p) { 5135 // An object is reachable if it is outside the collection set, 5136 // or is inside and copied. 5137 return !_g1->obj_in_cs(p) || p->is_forwarded(); 5138 } 5139 5140 // Non Copying Keep Alive closure 5141 class G1KeepAliveClosure: public OopClosure { 5142 G1CollectedHeap* _g1; 5143 public: 5144 G1KeepAliveClosure(G1CollectedHeap* g1) : _g1(g1) {} 5145 void do_oop(narrowOop* p) { guarantee(false, "Not needed"); } 5146 void do_oop(oop* p) { 5147 oop obj = *p; 5148 assert(obj != NULL, "the caller should have filtered out NULL values"); 5149 5150 const InCSetState cset_state = _g1->in_cset_state(obj); 5151 if (!cset_state.is_in_cset_or_humongous()) { 5152 return; 5153 } 5154 if (cset_state.is_in_cset()) { 5155 assert( obj->is_forwarded(), "invariant" ); 5156 *p = obj->forwardee(); 5157 } else { 5158 assert(!obj->is_forwarded(), "invariant" ); 5159 assert(cset_state.is_humongous(), 5160 err_msg("Only allowed InCSet state is IsHumongous, but is %d", cset_state.value())); 5161 _g1->set_humongous_is_live(obj); 5162 } 5163 } 5164 }; 5165 5166 // Copying Keep Alive closure - can be called from both 5167 // serial and parallel code as long as different worker 5168 // threads utilize different G1ParScanThreadState instances 5169 // and different queues. 5170 5171 class G1CopyingKeepAliveClosure: public OopClosure { 5172 G1CollectedHeap* _g1h; 5173 OopClosure* _copy_non_heap_obj_cl; 5174 G1ParScanThreadState* _par_scan_state; 5175 5176 public: 5177 G1CopyingKeepAliveClosure(G1CollectedHeap* g1h, 5178 OopClosure* non_heap_obj_cl, 5179 G1ParScanThreadState* pss): 5180 _g1h(g1h), 5181 _copy_non_heap_obj_cl(non_heap_obj_cl), 5182 _par_scan_state(pss) 5183 {} 5184 5185 virtual void do_oop(narrowOop* p) { do_oop_work(p); } 5186 virtual void do_oop( oop* p) { do_oop_work(p); } 5187 5188 template <class T> void do_oop_work(T* p) { 5189 oop obj = oopDesc::load_decode_heap_oop(p); 5190 5191 if (_g1h->is_in_cset_or_humongous(obj)) { 5192 // If the referent object has been forwarded (either copied 5193 // to a new location or to itself in the event of an 5194 // evacuation failure) then we need to update the reference 5195 // field and, if both reference and referent are in the G1 5196 // heap, update the RSet for the referent. 5197 // 5198 // If the referent has not been forwarded then we have to keep 5199 // it alive by policy. Therefore we have copy the referent. 5200 // 5201 // If the reference field is in the G1 heap then we can push 5202 // on the PSS queue. When the queue is drained (after each 5203 // phase of reference processing) the object and it's followers 5204 // will be copied, the reference field set to point to the 5205 // new location, and the RSet updated. Otherwise we need to 5206 // use the the non-heap or metadata closures directly to copy 5207 // the referent object and update the pointer, while avoiding 5208 // updating the RSet. 5209 5210 if (_g1h->is_in_g1_reserved(p)) { 5211 _par_scan_state->push_on_queue(p); 5212 } else { 5213 assert(!Metaspace::contains((const void*)p), 5214 err_msg("Unexpectedly found a pointer from metadata: " 5215 PTR_FORMAT, p)); 5216 _copy_non_heap_obj_cl->do_oop(p); 5217 } 5218 } 5219 } 5220 }; 5221 5222 // Serial drain queue closure. Called as the 'complete_gc' 5223 // closure for each discovered list in some of the 5224 // reference processing phases. 5225 5226 class G1STWDrainQueueClosure: public VoidClosure { 5227 protected: 5228 G1CollectedHeap* _g1h; 5229 G1ParScanThreadState* _par_scan_state; 5230 5231 G1ParScanThreadState* par_scan_state() { return _par_scan_state; } 5232 5233 public: 5234 G1STWDrainQueueClosure(G1CollectedHeap* g1h, G1ParScanThreadState* pss) : 5235 _g1h(g1h), 5236 _par_scan_state(pss) 5237 { } 5238 5239 void do_void() { 5240 G1ParScanThreadState* const pss = par_scan_state(); 5241 pss->trim_queue(); 5242 } 5243 }; 5244 5245 // Parallel Reference Processing closures 5246 5247 // Implementation of AbstractRefProcTaskExecutor for parallel reference 5248 // processing during G1 evacuation pauses. 5249 5250 class G1STWRefProcTaskExecutor: public AbstractRefProcTaskExecutor { 5251 private: 5252 G1CollectedHeap* _g1h; 5253 RefToScanQueueSet* _queues; 5254 FlexibleWorkGang* _workers; 5255 int _active_workers; 5256 5257 public: 5258 G1STWRefProcTaskExecutor(G1CollectedHeap* g1h, 5259 FlexibleWorkGang* workers, 5260 RefToScanQueueSet *task_queues, 5261 int n_workers) : 5262 _g1h(g1h), 5263 _queues(task_queues), 5264 _workers(workers), 5265 _active_workers(n_workers) 5266 { 5267 assert(n_workers > 0, "shouldn't call this otherwise"); 5268 } 5269 5270 // Executes the given task using concurrent marking worker threads. 5271 virtual void execute(ProcessTask& task); 5272 virtual void execute(EnqueueTask& task); 5273 }; 5274 5275 // Gang task for possibly parallel reference processing 5276 5277 class G1STWRefProcTaskProxy: public AbstractGangTask { 5278 typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask; 5279 ProcessTask& _proc_task; 5280 G1CollectedHeap* _g1h; 5281 RefToScanQueueSet *_task_queues; 5282 ParallelTaskTerminator* _terminator; 5283 5284 public: 5285 G1STWRefProcTaskProxy(ProcessTask& proc_task, 5286 G1CollectedHeap* g1h, 5287 RefToScanQueueSet *task_queues, 5288 ParallelTaskTerminator* terminator) : 5289 AbstractGangTask("Process reference objects in parallel"), 5290 _proc_task(proc_task), 5291 _g1h(g1h), 5292 _task_queues(task_queues), 5293 _terminator(terminator) 5294 {} 5295 5296 virtual void work(uint worker_id) { 5297 // The reference processing task executed by a single worker. 5298 ResourceMark rm; 5299 HandleMark hm; 5300 5301 G1STWIsAliveClosure is_alive(_g1h); 5302 5303 G1ParScanThreadState pss(_g1h, worker_id, NULL); 5304 G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, NULL); 5305 5306 pss.set_evac_failure_closure(&evac_failure_cl); 5307 5308 G1ParScanExtRootClosure only_copy_non_heap_cl(_g1h, &pss, NULL); 5309 5310 G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL); 5311 5312 OopClosure* copy_non_heap_cl = &only_copy_non_heap_cl; 5313 5314 if (_g1h->g1_policy()->collector_state()->during_initial_mark_pause()) { 5315 // We also need to mark copied objects. 5316 copy_non_heap_cl = ©_mark_non_heap_cl; 5317 } 5318 5319 // Keep alive closure. 5320 G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, &pss); 5321 5322 // Complete GC closure 5323 G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _task_queues, _terminator); 5324 5325 // Call the reference processing task's work routine. 5326 _proc_task.work(worker_id, is_alive, keep_alive, drain_queue); 5327 5328 // Note we cannot assert that the refs array is empty here as not all 5329 // of the processing tasks (specifically phase2 - pp2_work) execute 5330 // the complete_gc closure (which ordinarily would drain the queue) so 5331 // the queue may not be empty. 5332 } 5333 }; 5334 5335 // Driver routine for parallel reference processing. 5336 // Creates an instance of the ref processing gang 5337 // task and has the worker threads execute it. 5338 void G1STWRefProcTaskExecutor::execute(ProcessTask& proc_task) { 5339 assert(_workers != NULL, "Need parallel worker threads."); 5340 5341 ParallelTaskTerminator terminator(_active_workers, _queues); 5342 G1STWRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _queues, &terminator); 5343 5344 _g1h->set_par_threads(_active_workers); 5345 _workers->run_task(&proc_task_proxy); 5346 _g1h->set_par_threads(0); 5347 } 5348 5349 // Gang task for parallel reference enqueueing. 5350 5351 class G1STWRefEnqueueTaskProxy: public AbstractGangTask { 5352 typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask; 5353 EnqueueTask& _enq_task; 5354 5355 public: 5356 G1STWRefEnqueueTaskProxy(EnqueueTask& enq_task) : 5357 AbstractGangTask("Enqueue reference objects in parallel"), 5358 _enq_task(enq_task) 5359 { } 5360 5361 virtual void work(uint worker_id) { 5362 _enq_task.work(worker_id); 5363 } 5364 }; 5365 5366 // Driver routine for parallel reference enqueueing. 5367 // Creates an instance of the ref enqueueing gang 5368 // task and has the worker threads execute it. 5369 5370 void G1STWRefProcTaskExecutor::execute(EnqueueTask& enq_task) { 5371 assert(_workers != NULL, "Need parallel worker threads."); 5372 5373 G1STWRefEnqueueTaskProxy enq_task_proxy(enq_task); 5374 5375 _g1h->set_par_threads(_active_workers); 5376 _workers->run_task(&enq_task_proxy); 5377 _g1h->set_par_threads(0); 5378 } 5379 5380 // End of weak reference support closures 5381 5382 // Abstract task used to preserve (i.e. copy) any referent objects 5383 // that are in the collection set and are pointed to by reference 5384 // objects discovered by the CM ref processor. 5385 5386 class G1ParPreserveCMReferentsTask: public AbstractGangTask { 5387 protected: 5388 G1CollectedHeap* _g1h; 5389 RefToScanQueueSet *_queues; 5390 ParallelTaskTerminator _terminator; 5391 uint _n_workers; 5392 5393 public: 5394 G1ParPreserveCMReferentsTask(G1CollectedHeap* g1h,int workers, RefToScanQueueSet *task_queues) : 5395 AbstractGangTask("ParPreserveCMReferents"), 5396 _g1h(g1h), 5397 _queues(task_queues), 5398 _terminator(workers, _queues), 5399 _n_workers(workers) 5400 { } 5401 5402 void work(uint worker_id) { 5403 ResourceMark rm; 5404 HandleMark hm; 5405 5406 G1ParScanThreadState pss(_g1h, worker_id, NULL); 5407 G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss, NULL); 5408 5409 pss.set_evac_failure_closure(&evac_failure_cl); 5410 5411 assert(pss.queue_is_empty(), "both queue and overflow should be empty"); 5412 5413 G1ParScanExtRootClosure only_copy_non_heap_cl(_g1h, &pss, NULL); 5414 5415 G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(_g1h, &pss, NULL); 5416 5417 OopClosure* copy_non_heap_cl = &only_copy_non_heap_cl; 5418 5419 if (_g1h->g1_policy()->collector_state()->during_initial_mark_pause()) { 5420 // We also need to mark copied objects. 5421 copy_non_heap_cl = ©_mark_non_heap_cl; 5422 } 5423 5424 // Is alive closure 5425 G1AlwaysAliveClosure always_alive(_g1h); 5426 5427 // Copying keep alive closure. Applied to referent objects that need 5428 // to be copied. 5429 G1CopyingKeepAliveClosure keep_alive(_g1h, copy_non_heap_cl, &pss); 5430 5431 ReferenceProcessor* rp = _g1h->ref_processor_cm(); 5432 5433 uint limit = ReferenceProcessor::number_of_subclasses_of_ref() * rp->max_num_q(); 5434 uint stride = MIN2(MAX2(_n_workers, 1U), limit); 5435 5436 // limit is set using max_num_q() - which was set using ParallelGCThreads. 5437 // So this must be true - but assert just in case someone decides to 5438 // change the worker ids. 5439 assert(0 <= worker_id && worker_id < limit, "sanity"); 5440 assert(!rp->discovery_is_atomic(), "check this code"); 5441 5442 // Select discovered lists [i, i+stride, i+2*stride,...,limit) 5443 for (uint idx = worker_id; idx < limit; idx += stride) { 5444 DiscoveredList& ref_list = rp->discovered_refs()[idx]; 5445 5446 DiscoveredListIterator iter(ref_list, &keep_alive, &always_alive); 5447 while (iter.has_next()) { 5448 // Since discovery is not atomic for the CM ref processor, we 5449 // can see some null referent objects. 5450 iter.load_ptrs(DEBUG_ONLY(true)); 5451 oop ref = iter.obj(); 5452 5453 // This will filter nulls. 5454 if (iter.is_referent_alive()) { 5455 iter.make_referent_alive(); 5456 } 5457 iter.move_to_next(); 5458 } 5459 } 5460 5461 // Drain the queue - which may cause stealing 5462 G1ParEvacuateFollowersClosure drain_queue(_g1h, &pss, _queues, &_terminator); 5463 drain_queue.do_void(); 5464 // Allocation buffers were retired at the end of G1ParEvacuateFollowersClosure 5465 assert(pss.queue_is_empty(), "should be"); 5466 } 5467 }; 5468 5469 // Weak Reference processing during an evacuation pause (part 1). 5470 void G1CollectedHeap::process_discovered_references(uint no_of_gc_workers) { 5471 double ref_proc_start = os::elapsedTime(); 5472 5473 ReferenceProcessor* rp = _ref_processor_stw; 5474 assert(rp->discovery_enabled(), "should have been enabled"); 5475 5476 // Any reference objects, in the collection set, that were 'discovered' 5477 // by the CM ref processor should have already been copied (either by 5478 // applying the external root copy closure to the discovered lists, or 5479 // by following an RSet entry). 5480 // 5481 // But some of the referents, that are in the collection set, that these 5482 // reference objects point to may not have been copied: the STW ref 5483 // processor would have seen that the reference object had already 5484 // been 'discovered' and would have skipped discovering the reference, 5485 // but would not have treated the reference object as a regular oop. 5486 // As a result the copy closure would not have been applied to the 5487 // referent object. 5488 // 5489 // We need to explicitly copy these referent objects - the references 5490 // will be processed at the end of remarking. 5491 // 5492 // We also need to do this copying before we process the reference 5493 // objects discovered by the STW ref processor in case one of these 5494 // referents points to another object which is also referenced by an 5495 // object discovered by the STW ref processor. 5496 5497 assert(no_of_gc_workers == workers()->active_workers(), "Need to reset active GC workers"); 5498 5499 set_par_threads(no_of_gc_workers); 5500 G1ParPreserveCMReferentsTask keep_cm_referents(this, 5501 no_of_gc_workers, 5502 _task_queues); 5503 5504 workers()->run_task(&keep_cm_referents); 5505 5506 set_par_threads(0); 5507 5508 // Closure to test whether a referent is alive. 5509 G1STWIsAliveClosure is_alive(this); 5510 5511 // Even when parallel reference processing is enabled, the processing 5512 // of JNI refs is serial and performed serially by the current thread 5513 // rather than by a worker. The following PSS will be used for processing 5514 // JNI refs. 5515 5516 // Use only a single queue for this PSS. 5517 G1ParScanThreadState pss(this, 0, NULL); 5518 5519 // We do not embed a reference processor in the copying/scanning 5520 // closures while we're actually processing the discovered 5521 // reference objects. 5522 G1ParScanHeapEvacFailureClosure evac_failure_cl(this, &pss, NULL); 5523 5524 pss.set_evac_failure_closure(&evac_failure_cl); 5525 5526 assert(pss.queue_is_empty(), "pre-condition"); 5527 5528 G1ParScanExtRootClosure only_copy_non_heap_cl(this, &pss, NULL); 5529 5530 G1ParScanAndMarkExtRootClosure copy_mark_non_heap_cl(this, &pss, NULL); 5531 5532 OopClosure* copy_non_heap_cl = &only_copy_non_heap_cl; 5533 5534 if (_g1h->g1_policy()->collector_state()->during_initial_mark_pause()) { 5535 // We also need to mark copied objects. 5536 copy_non_heap_cl = ©_mark_non_heap_cl; 5537 } 5538 5539 // Keep alive closure. 5540 G1CopyingKeepAliveClosure keep_alive(this, copy_non_heap_cl, &pss); 5541 5542 // Serial Complete GC closure 5543 G1STWDrainQueueClosure drain_queue(this, &pss); 5544 5545 // Setup the soft refs policy... 5546 rp->setup_policy(false); 5547 5548 ReferenceProcessorStats stats; 5549 if (!rp->processing_is_mt()) { 5550 // Serial reference processing... 5551 stats = rp->process_discovered_references(&is_alive, 5552 &keep_alive, 5553 &drain_queue, 5554 NULL, 5555 _gc_timer_stw, 5556 _gc_tracer_stw->gc_id()); 5557 } else { 5558 // Parallel reference processing 5559 assert(rp->num_q() == no_of_gc_workers, "sanity"); 5560 assert(no_of_gc_workers <= rp->max_num_q(), "sanity"); 5561 5562 G1STWRefProcTaskExecutor par_task_executor(this, workers(), _task_queues, no_of_gc_workers); 5563 stats = rp->process_discovered_references(&is_alive, 5564 &keep_alive, 5565 &drain_queue, 5566 &par_task_executor, 5567 _gc_timer_stw, 5568 _gc_tracer_stw->gc_id()); 5569 } 5570 5571 _gc_tracer_stw->report_gc_reference_stats(stats); 5572 5573 // We have completed copying any necessary live referent objects. 5574 assert(pss.queue_is_empty(), "both queue and overflow should be empty"); 5575 5576 double ref_proc_time = os::elapsedTime() - ref_proc_start; 5577 g1_policy()->phase_times()->record_ref_proc_time(ref_proc_time * 1000.0); 5578 } 5579 5580 // Weak Reference processing during an evacuation pause (part 2). 5581 void G1CollectedHeap::enqueue_discovered_references(uint no_of_gc_workers) { 5582 double ref_enq_start = os::elapsedTime(); 5583 5584 ReferenceProcessor* rp = _ref_processor_stw; 5585 assert(!rp->discovery_enabled(), "should have been disabled as part of processing"); 5586 5587 // Now enqueue any remaining on the discovered lists on to 5588 // the pending list. 5589 if (!rp->processing_is_mt()) { 5590 // Serial reference processing... 5591 rp->enqueue_discovered_references(); 5592 } else { 5593 // Parallel reference enqueueing 5594 5595 assert(no_of_gc_workers == workers()->active_workers(), 5596 "Need to reset active workers"); 5597 assert(rp->num_q() == no_of_gc_workers, "sanity"); 5598 assert(no_of_gc_workers <= rp->max_num_q(), "sanity"); 5599 5600 G1STWRefProcTaskExecutor par_task_executor(this, workers(), _task_queues, no_of_gc_workers); 5601 rp->enqueue_discovered_references(&par_task_executor); 5602 } 5603 5604 rp->verify_no_references_recorded(); 5605 assert(!rp->discovery_enabled(), "should have been disabled"); 5606 5607 // FIXME 5608 // CM's reference processing also cleans up the string and symbol tables. 5609 // Should we do that here also? We could, but it is a serial operation 5610 // and could significantly increase the pause time. 5611 5612 double ref_enq_time = os::elapsedTime() - ref_enq_start; 5613 g1_policy()->phase_times()->record_ref_enq_time(ref_enq_time * 1000.0); 5614 } 5615 5616 void G1CollectedHeap::evacuate_collection_set(EvacuationInfo& evacuation_info) { 5617 _expand_heap_after_alloc_failure = true; 5618 _evacuation_failed = false; 5619 5620 // Should G1EvacuationFailureALot be in effect for this GC? 5621 NOT_PRODUCT(set_evacuation_failure_alot_for_current_gc();) 5622 5623 g1_rem_set()->prepare_for_oops_into_collection_set_do(); 5624 5625 // Disable the hot card cache. 5626 G1HotCardCache* hot_card_cache = _cg1r->hot_card_cache(); 5627 hot_card_cache->reset_hot_cache_claimed_index(); 5628 hot_card_cache->set_use_cache(false); 5629 5630 uint n_workers; 5631 n_workers = 5632 AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(), 5633 workers()->active_workers(), 5634 Threads::number_of_non_daemon_threads()); 5635 assert(UseDynamicNumberOfGCThreads || 5636 n_workers == workers()->total_workers(), 5637 "If not dynamic should be using all the workers"); 5638 workers()->set_active_workers(n_workers); 5639 set_par_threads(n_workers); 5640 5641 G1ParTask g1_par_task(this, _task_queues); 5642 5643 init_for_evac_failure(NULL); 5644 5645 assert(dirty_card_queue_set().completed_buffers_num() == 0, "Should be empty"); 5646 double start_par_time_sec = os::elapsedTime(); 5647 double end_par_time_sec; 5648 5649 { 5650 StrongRootsScope srs(this); 5651 // InitialMark needs claim bits to keep track of the marked-through CLDs. 5652 if (g1_policy()->collector_state()->during_initial_mark_pause()) { 5653 ClassLoaderDataGraph::clear_claimed_marks(); 5654 } 5655 5656 // The individual threads will set their evac-failure closures. 5657 if (PrintTerminationStats) G1ParScanThreadState::print_termination_stats_hdr(); 5658 // These tasks use ShareHeap::_process_strong_tasks 5659 assert(UseDynamicNumberOfGCThreads || 5660 workers()->active_workers() == workers()->total_workers(), 5661 "If not dynamic should be using all the workers"); 5662 workers()->run_task(&g1_par_task); 5663 end_par_time_sec = os::elapsedTime(); 5664 5665 // Closing the inner scope will execute the destructor 5666 // for the StrongRootsScope object. We record the current 5667 // elapsed time before closing the scope so that time 5668 // taken for the SRS destructor is NOT included in the 5669 // reported parallel time. 5670 } 5671 5672 double par_time_ms = (end_par_time_sec - start_par_time_sec) * 1000.0; 5673 g1_policy()->phase_times()->record_par_time(par_time_ms); 5674 5675 double code_root_fixup_time_ms = 5676 (os::elapsedTime() - end_par_time_sec) * 1000.0; 5677 g1_policy()->phase_times()->record_code_root_fixup_time(code_root_fixup_time_ms); 5678 5679 set_par_threads(0); 5680 5681 // Process any discovered reference objects - we have 5682 // to do this _before_ we retire the GC alloc regions 5683 // as we may have to copy some 'reachable' referent 5684 // objects (and their reachable sub-graphs) that were 5685 // not copied during the pause. 5686 process_discovered_references(n_workers); 5687 5688 if (G1StringDedup::is_enabled()) { 5689 G1STWIsAliveClosure is_alive(this); 5690 G1KeepAliveClosure keep_alive(this); 5691 G1StringDedup::unlink_or_oops_do(&is_alive, &keep_alive); 5692 } 5693 5694 _allocator->release_gc_alloc_regions(n_workers, evacuation_info); 5695 g1_rem_set()->cleanup_after_oops_into_collection_set_do(); 5696 5697 // Reset and re-enable the hot card cache. 5698 // Note the counts for the cards in the regions in the 5699 // collection set are reset when the collection set is freed. 5700 hot_card_cache->reset_hot_cache(); 5701 hot_card_cache->set_use_cache(true); 5702 5703 purge_code_root_memory(); 5704 5705 finalize_for_evac_failure(); 5706 5707 if (evacuation_failed()) { 5708 remove_self_forwarding_pointers(); 5709 5710 // Reset the G1EvacuationFailureALot counters and flags 5711 // Note: the values are reset only when an actual 5712 // evacuation failure occurs. 5713 NOT_PRODUCT(reset_evacuation_should_fail();) 5714 } 5715 5716 // Enqueue any remaining references remaining on the STW 5717 // reference processor's discovered lists. We need to do 5718 // this after the card table is cleaned (and verified) as 5719 // the act of enqueueing entries on to the pending list 5720 // will log these updates (and dirty their associated 5721 // cards). We need these updates logged to update any 5722 // RSets. 5723 enqueue_discovered_references(n_workers); 5724 5725 redirty_logged_cards(); 5726 COMPILER2_PRESENT(DerivedPointerTable::update_pointers()); 5727 } 5728 5729 void G1CollectedHeap::free_region(HeapRegion* hr, 5730 FreeRegionList* free_list, 5731 bool par, 5732 bool locked) { 5733 assert(!hr->is_free(), "the region should not be free"); 5734 assert(!hr->is_empty(), "the region should not be empty"); 5735 assert(_hrm.is_available(hr->hrm_index()), "region should be committed"); 5736 assert(free_list != NULL, "pre-condition"); 5737 5738 if (G1VerifyBitmaps) { 5739 MemRegion mr(hr->bottom(), hr->end()); 5740 concurrent_mark()->clearRangePrevBitmap(mr); 5741 } 5742 5743 // Clear the card counts for this region. 5744 // Note: we only need to do this if the region is not young 5745 // (since we don't refine cards in young regions). 5746 if (!hr->is_young()) { 5747 _cg1r->hot_card_cache()->reset_card_counts(hr); 5748 } 5749 hr->hr_clear(par, true /* clear_space */, locked /* locked */); 5750 free_list->add_ordered(hr); 5751 } 5752 5753 void G1CollectedHeap::free_humongous_region(HeapRegion* hr, 5754 FreeRegionList* free_list, 5755 bool par) { 5756 assert(hr->is_starts_humongous(), "this is only for starts humongous regions"); 5757 assert(free_list != NULL, "pre-condition"); 5758 5759 size_t hr_capacity = hr->capacity(); 5760 // We need to read this before we make the region non-humongous, 5761 // otherwise the information will be gone. 5762 uint last_index = hr->last_hc_index(); 5763 hr->clear_humongous(); 5764 free_region(hr, free_list, par); 5765 5766 uint i = hr->hrm_index() + 1; 5767 while (i < last_index) { 5768 HeapRegion* curr_hr = region_at(i); 5769 assert(curr_hr->is_continues_humongous(), "invariant"); 5770 curr_hr->clear_humongous(); 5771 free_region(curr_hr, free_list, par); 5772 i += 1; 5773 } 5774 } 5775 5776 void G1CollectedHeap::remove_from_old_sets(const HeapRegionSetCount& old_regions_removed, 5777 const HeapRegionSetCount& humongous_regions_removed) { 5778 if (old_regions_removed.length() > 0 || humongous_regions_removed.length() > 0) { 5779 MutexLockerEx x(OldSets_lock, Mutex::_no_safepoint_check_flag); 5780 _old_set.bulk_remove(old_regions_removed); 5781 _humongous_set.bulk_remove(humongous_regions_removed); 5782 } 5783 5784 } 5785 5786 void G1CollectedHeap::prepend_to_freelist(FreeRegionList* list) { 5787 assert(list != NULL, "list can't be null"); 5788 if (!list->is_empty()) { 5789 MutexLockerEx x(FreeList_lock, Mutex::_no_safepoint_check_flag); 5790 _hrm.insert_list_into_free_list(list); 5791 } 5792 } 5793 5794 void G1CollectedHeap::decrement_summary_bytes(size_t bytes) { 5795 _allocator->decrease_used(bytes); 5796 } 5797 5798 class G1ParCleanupCTTask : public AbstractGangTask { 5799 G1SATBCardTableModRefBS* _ct_bs; 5800 G1CollectedHeap* _g1h; 5801 HeapRegion* volatile _su_head; 5802 public: 5803 G1ParCleanupCTTask(G1SATBCardTableModRefBS* ct_bs, 5804 G1CollectedHeap* g1h) : 5805 AbstractGangTask("G1 Par Cleanup CT Task"), 5806 _ct_bs(ct_bs), _g1h(g1h) { } 5807 5808 void work(uint worker_id) { 5809 HeapRegion* r; 5810 while (r = _g1h->pop_dirty_cards_region()) { 5811 clear_cards(r); 5812 } 5813 } 5814 5815 void clear_cards(HeapRegion* r) { 5816 // Cards of the survivors should have already been dirtied. 5817 if (!r->is_survivor()) { 5818 _ct_bs->clear(MemRegion(r->bottom(), r->end())); 5819 } 5820 } 5821 }; 5822 5823 #ifndef PRODUCT 5824 class G1VerifyCardTableCleanup: public HeapRegionClosure { 5825 G1CollectedHeap* _g1h; 5826 G1SATBCardTableModRefBS* _ct_bs; 5827 public: 5828 G1VerifyCardTableCleanup(G1CollectedHeap* g1h, G1SATBCardTableModRefBS* ct_bs) 5829 : _g1h(g1h), _ct_bs(ct_bs) { } 5830 virtual bool doHeapRegion(HeapRegion* r) { 5831 if (r->is_survivor()) { 5832 _g1h->verify_dirty_region(r); 5833 } else { 5834 _g1h->verify_not_dirty_region(r); 5835 } 5836 return false; 5837 } 5838 }; 5839 5840 void G1CollectedHeap::verify_not_dirty_region(HeapRegion* hr) { 5841 // All of the region should be clean. 5842 G1SATBCardTableModRefBS* ct_bs = g1_barrier_set(); 5843 MemRegion mr(hr->bottom(), hr->end()); 5844 ct_bs->verify_not_dirty_region(mr); 5845 } 5846 5847 void G1CollectedHeap::verify_dirty_region(HeapRegion* hr) { 5848 // We cannot guarantee that [bottom(),end()] is dirty. Threads 5849 // dirty allocated blocks as they allocate them. The thread that 5850 // retires each region and replaces it with a new one will do a 5851 // maximal allocation to fill in [pre_dummy_top(),end()] but will 5852 // not dirty that area (one less thing to have to do while holding 5853 // a lock). So we can only verify that [bottom(),pre_dummy_top()] 5854 // is dirty. 5855 G1SATBCardTableModRefBS* ct_bs = g1_barrier_set(); 5856 MemRegion mr(hr->bottom(), hr->pre_dummy_top()); 5857 if (hr->is_young()) { 5858 ct_bs->verify_g1_young_region(mr); 5859 } else { 5860 ct_bs->verify_dirty_region(mr); 5861 } 5862 } 5863 5864 void G1CollectedHeap::verify_dirty_young_list(HeapRegion* head) { 5865 G1SATBCardTableModRefBS* ct_bs = g1_barrier_set(); 5866 for (HeapRegion* hr = head; hr != NULL; hr = hr->get_next_young_region()) { 5867 verify_dirty_region(hr); 5868 } 5869 } 5870 5871 void G1CollectedHeap::verify_dirty_young_regions() { 5872 verify_dirty_young_list(_young_list->first_region()); 5873 } 5874 5875 bool G1CollectedHeap::verify_no_bits_over_tams(const char* bitmap_name, CMBitMapRO* bitmap, 5876 HeapWord* tams, HeapWord* end) { 5877 guarantee(tams <= end, 5878 err_msg("tams: "PTR_FORMAT" end: "PTR_FORMAT, tams, end)); 5879 HeapWord* result = bitmap->getNextMarkedWordAddress(tams, end); 5880 if (result < end) { 5881 gclog_or_tty->cr(); 5882 gclog_or_tty->print_cr("## wrong marked address on %s bitmap: "PTR_FORMAT, 5883 bitmap_name, result); 5884 gclog_or_tty->print_cr("## %s tams: "PTR_FORMAT" end: "PTR_FORMAT, 5885 bitmap_name, tams, end); 5886 return false; 5887 } 5888 return true; 5889 } 5890 5891 bool G1CollectedHeap::verify_bitmaps(const char* caller, HeapRegion* hr) { 5892 CMBitMapRO* prev_bitmap = concurrent_mark()->prevMarkBitMap(); 5893 CMBitMapRO* next_bitmap = (CMBitMapRO*) concurrent_mark()->nextMarkBitMap(); 5894 5895 HeapWord* bottom = hr->bottom(); 5896 HeapWord* ptams = hr->prev_top_at_mark_start(); 5897 HeapWord* ntams = hr->next_top_at_mark_start(); 5898 HeapWord* end = hr->end(); 5899 5900 bool res_p = verify_no_bits_over_tams("prev", prev_bitmap, ptams, end); 5901 5902 bool res_n = true; 5903 // We reset mark_in_progress() before we reset _cmThread->in_progress() and in this window 5904 // we do the clearing of the next bitmap concurrently. Thus, we can not verify the bitmap 5905 // if we happen to be in that state. 5906 if (mark_in_progress() || !_cmThread->in_progress()) { 5907 res_n = verify_no_bits_over_tams("next", next_bitmap, ntams, end); 5908 } 5909 if (!res_p || !res_n) { 5910 gclog_or_tty->print_cr("#### Bitmap verification failed for "HR_FORMAT, 5911 HR_FORMAT_PARAMS(hr)); 5912 gclog_or_tty->print_cr("#### Caller: %s", caller); 5913 return false; 5914 } 5915 return true; 5916 } 5917 5918 void G1CollectedHeap::check_bitmaps(const char* caller, HeapRegion* hr) { 5919 if (!G1VerifyBitmaps) return; 5920 5921 guarantee(verify_bitmaps(caller, hr), "bitmap verification"); 5922 } 5923 5924 class G1VerifyBitmapClosure : public HeapRegionClosure { 5925 private: 5926 const char* _caller; 5927 G1CollectedHeap* _g1h; 5928 bool _failures; 5929 5930 public: 5931 G1VerifyBitmapClosure(const char* caller, G1CollectedHeap* g1h) : 5932 _caller(caller), _g1h(g1h), _failures(false) { } 5933 5934 bool failures() { return _failures; } 5935 5936 virtual bool doHeapRegion(HeapRegion* hr) { 5937 if (hr->is_continues_humongous()) return false; 5938 5939 bool result = _g1h->verify_bitmaps(_caller, hr); 5940 if (!result) { 5941 _failures = true; 5942 } 5943 return false; 5944 } 5945 }; 5946 5947 void G1CollectedHeap::check_bitmaps(const char* caller) { 5948 if (!G1VerifyBitmaps) return; 5949 5950 G1VerifyBitmapClosure cl(caller, this); 5951 heap_region_iterate(&cl); 5952 guarantee(!cl.failures(), "bitmap verification"); 5953 } 5954 5955 class G1CheckCSetFastTableClosure : public HeapRegionClosure { 5956 private: 5957 bool _failures; 5958 public: 5959 G1CheckCSetFastTableClosure() : HeapRegionClosure(), _failures(false) { } 5960 5961 virtual bool doHeapRegion(HeapRegion* hr) { 5962 uint i = hr->hrm_index(); 5963 InCSetState cset_state = (InCSetState) G1CollectedHeap::heap()->_in_cset_fast_test.get_by_index(i); 5964 if (hr->is_humongous()) { 5965 if (hr->in_collection_set()) { 5966 gclog_or_tty->print_cr("\n## humongous region %u in CSet", i); 5967 _failures = true; 5968 return true; 5969 } 5970 if (cset_state.is_in_cset()) { 5971 gclog_or_tty->print_cr("\n## inconsistent cset state %d for humongous region %u", cset_state.value(), i); 5972 _failures = true; 5973 return true; 5974 } 5975 if (hr->is_continues_humongous() && cset_state.is_humongous()) { 5976 gclog_or_tty->print_cr("\n## inconsistent cset state %d for continues humongous region %u", cset_state.value(), i); 5977 _failures = true; 5978 return true; 5979 } 5980 } else { 5981 if (cset_state.is_humongous()) { 5982 gclog_or_tty->print_cr("\n## inconsistent cset state %d for non-humongous region %u", cset_state.value(), i); 5983 _failures = true; 5984 return true; 5985 } 5986 if (hr->in_collection_set() != cset_state.is_in_cset()) { 5987 gclog_or_tty->print_cr("\n## in CSet %d / cset state %d inconsistency for region %u", 5988 hr->in_collection_set(), cset_state.value(), i); 5989 _failures = true; 5990 return true; 5991 } 5992 if (cset_state.is_in_cset()) { 5993 if (hr->is_young() != (cset_state.is_young())) { 5994 gclog_or_tty->print_cr("\n## is_young %d / cset state %d inconsistency for region %u", 5995 hr->is_young(), cset_state.value(), i); 5996 _failures = true; 5997 return true; 5998 } 5999 if (hr->is_old() != (cset_state.is_old())) { 6000 gclog_or_tty->print_cr("\n## is_old %d / cset state %d inconsistency for region %u", 6001 hr->is_old(), cset_state.value(), i); 6002 _failures = true; 6003 return true; 6004 } 6005 } 6006 } 6007 return false; 6008 } 6009 6010 bool failures() const { return _failures; } 6011 }; 6012 6013 bool G1CollectedHeap::check_cset_fast_test() { 6014 G1CheckCSetFastTableClosure cl; 6015 _hrm.iterate(&cl); 6016 return !cl.failures(); 6017 } 6018 #endif // PRODUCT 6019 6020 void G1CollectedHeap::cleanUpCardTable() { 6021 G1SATBCardTableModRefBS* ct_bs = g1_barrier_set(); 6022 double start = os::elapsedTime(); 6023 6024 { 6025 // Iterate over the dirty cards region list. 6026 G1ParCleanupCTTask cleanup_task(ct_bs, this); 6027 6028 set_par_threads(); 6029 workers()->run_task(&cleanup_task); 6030 set_par_threads(0); 6031 #ifndef PRODUCT 6032 if (G1VerifyCTCleanup || VerifyAfterGC) { 6033 G1VerifyCardTableCleanup cleanup_verifier(this, ct_bs); 6034 heap_region_iterate(&cleanup_verifier); 6035 } 6036 #endif 6037 } 6038 6039 double elapsed = os::elapsedTime() - start; 6040 g1_policy()->phase_times()->record_clear_ct_time(elapsed * 1000.0); 6041 } 6042 6043 void G1CollectedHeap::free_collection_set(HeapRegion* cs_head, EvacuationInfo& evacuation_info) { 6044 size_t pre_used = 0; 6045 FreeRegionList local_free_list("Local List for CSet Freeing"); 6046 6047 double young_time_ms = 0.0; 6048 double non_young_time_ms = 0.0; 6049 6050 // Since the collection set is a superset of the the young list, 6051 // all we need to do to clear the young list is clear its 6052 // head and length, and unlink any young regions in the code below 6053 _young_list->clear(); 6054 6055 G1CollectorPolicy* policy = g1_policy(); 6056 6057 double start_sec = os::elapsedTime(); 6058 bool non_young = true; 6059 6060 HeapRegion* cur = cs_head; 6061 int age_bound = -1; 6062 size_t rs_lengths = 0; 6063 6064 while (cur != NULL) { 6065 assert(!is_on_master_free_list(cur), "sanity"); 6066 if (non_young) { 6067 if (cur->is_young()) { 6068 double end_sec = os::elapsedTime(); 6069 double elapsed_ms = (end_sec - start_sec) * 1000.0; 6070 non_young_time_ms += elapsed_ms; 6071 6072 start_sec = os::elapsedTime(); 6073 non_young = false; 6074 } 6075 } else { 6076 if (!cur->is_young()) { 6077 double end_sec = os::elapsedTime(); 6078 double elapsed_ms = (end_sec - start_sec) * 1000.0; 6079 young_time_ms += elapsed_ms; 6080 6081 start_sec = os::elapsedTime(); 6082 non_young = true; 6083 } 6084 } 6085 6086 rs_lengths += cur->rem_set()->occupied_locked(); 6087 6088 HeapRegion* next = cur->next_in_collection_set(); 6089 assert(cur->in_collection_set(), "bad CS"); 6090 cur->set_next_in_collection_set(NULL); 6091 cur->set_in_collection_set(false); 6092 6093 if (cur->is_young()) { 6094 int index = cur->young_index_in_cset(); 6095 assert(index != -1, "invariant"); 6096 assert((uint) index < policy->young_cset_region_length(), "invariant"); 6097 size_t words_survived = _surviving_young_words[index]; 6098 cur->record_surv_words_in_group(words_survived); 6099 6100 // At this point the we have 'popped' cur from the collection set 6101 // (linked via next_in_collection_set()) but it is still in the 6102 // young list (linked via next_young_region()). Clear the 6103 // _next_young_region field. 6104 cur->set_next_young_region(NULL); 6105 } else { 6106 int index = cur->young_index_in_cset(); 6107 assert(index == -1, "invariant"); 6108 } 6109 6110 assert( (cur->is_young() && cur->young_index_in_cset() > -1) || 6111 (!cur->is_young() && cur->young_index_in_cset() == -1), 6112 "invariant" ); 6113 6114 if (!cur->evacuation_failed()) { 6115 MemRegion used_mr = cur->used_region(); 6116 6117 // And the region is empty. 6118 assert(!used_mr.is_empty(), "Should not have empty regions in a CS."); 6119 pre_used += cur->used(); 6120 free_region(cur, &local_free_list, false /* par */, true /* locked */); 6121 } else { 6122 cur->uninstall_surv_rate_group(); 6123 if (cur->is_young()) { 6124 cur->set_young_index_in_cset(-1); 6125 } 6126 cur->set_evacuation_failed(false); 6127 // The region is now considered to be old. 6128 cur->set_old(); 6129 _old_set.add(cur); 6130 evacuation_info.increment_collectionset_used_after(cur->used()); 6131 } 6132 cur = next; 6133 } 6134 6135 evacuation_info.set_regions_freed(local_free_list.length()); 6136 policy->record_max_rs_lengths(rs_lengths); 6137 policy->cset_regions_freed(); 6138 6139 double end_sec = os::elapsedTime(); 6140 double elapsed_ms = (end_sec - start_sec) * 1000.0; 6141 6142 if (non_young) { 6143 non_young_time_ms += elapsed_ms; 6144 } else { 6145 young_time_ms += elapsed_ms; 6146 } 6147 6148 prepend_to_freelist(&local_free_list); 6149 decrement_summary_bytes(pre_used); 6150 policy->phase_times()->record_young_free_cset_time_ms(young_time_ms); 6151 policy->phase_times()->record_non_young_free_cset_time_ms(non_young_time_ms); 6152 } 6153 6154 class G1FreeHumongousRegionClosure : public HeapRegionClosure { 6155 private: 6156 FreeRegionList* _free_region_list; 6157 HeapRegionSet* _proxy_set; 6158 HeapRegionSetCount _humongous_regions_removed; 6159 size_t _freed_bytes; 6160 public: 6161 6162 G1FreeHumongousRegionClosure(FreeRegionList* free_region_list) : 6163 _free_region_list(free_region_list), _humongous_regions_removed(), _freed_bytes(0) { 6164 } 6165 6166 virtual bool doHeapRegion(HeapRegion* r) { 6167 if (!r->is_starts_humongous()) { 6168 return false; 6169 } 6170 6171 G1CollectedHeap* g1h = G1CollectedHeap::heap(); 6172 6173 oop obj = (oop)r->bottom(); 6174 CMBitMap* next_bitmap = g1h->concurrent_mark()->nextMarkBitMap(); 6175 6176 // The following checks whether the humongous object is live are sufficient. 6177 // The main additional check (in addition to having a reference from the roots 6178 // or the young gen) is whether the humongous object has a remembered set entry. 6179 // 6180 // A humongous object cannot be live if there is no remembered set for it 6181 // because: 6182 // - there can be no references from within humongous starts regions referencing 6183 // the object because we never allocate other objects into them. 6184 // (I.e. there are no intra-region references that may be missed by the 6185 // remembered set) 6186 // - as soon there is a remembered set entry to the humongous starts region 6187 // (i.e. it has "escaped" to an old object) this remembered set entry will stay 6188 // until the end of a concurrent mark. 6189 // 6190 // It is not required to check whether the object has been found dead by marking 6191 // or not, in fact it would prevent reclamation within a concurrent cycle, as 6192 // all objects allocated during that time are considered live. 6193 // SATB marking is even more conservative than the remembered set. 6194 // So if at this point in the collection there is no remembered set entry, 6195 // nobody has a reference to it. 6196 // At the start of collection we flush all refinement logs, and remembered sets 6197 // are completely up-to-date wrt to references to the humongous object. 6198 // 6199 // Other implementation considerations: 6200 // - never consider object arrays at this time because they would pose 6201 // considerable effort for cleaning up the the remembered sets. This is 6202 // required because stale remembered sets might reference locations that 6203 // are currently allocated into. 6204 uint region_idx = r->hrm_index(); 6205 if (g1h->humongous_is_live(region_idx) || 6206 g1h->humongous_region_is_always_live(region_idx)) { 6207 6208 if (G1TraceEagerReclaimHumongousObjects) { 6209 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", 6210 region_idx, 6211 obj->size()*HeapWordSize, 6212 r->bottom(), 6213 r->region_num(), 6214 r->rem_set()->occupied(), 6215 r->rem_set()->strong_code_roots_list_length(), 6216 next_bitmap->isMarked(r->bottom()), 6217 g1h->humongous_is_live(region_idx), 6218 obj->is_objArray() 6219 ); 6220 } 6221 6222 return false; 6223 } 6224 6225 guarantee(!obj->is_objArray(), 6226 err_msg("Eagerly reclaiming object arrays is not supported, but the object "PTR_FORMAT" is.", 6227 r->bottom())); 6228 6229 if (G1TraceEagerReclaimHumongousObjects) { 6230 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", 6231 region_idx, 6232 obj->size()*HeapWordSize, 6233 r->bottom(), 6234 r->region_num(), 6235 r->rem_set()->occupied(), 6236 r->rem_set()->strong_code_roots_list_length(), 6237 next_bitmap->isMarked(r->bottom()), 6238 g1h->humongous_is_live(region_idx), 6239 obj->is_objArray() 6240 ); 6241 } 6242 // Need to clear mark bit of the humongous object if already set. 6243 if (next_bitmap->isMarked(r->bottom())) { 6244 next_bitmap->clear(r->bottom()); 6245 } 6246 _freed_bytes += r->used(); 6247 r->set_containing_set(NULL); 6248 _humongous_regions_removed.increment(1u, r->capacity()); 6249 g1h->free_humongous_region(r, _free_region_list, false); 6250 6251 return false; 6252 } 6253 6254 HeapRegionSetCount& humongous_free_count() { 6255 return _humongous_regions_removed; 6256 } 6257 6258 size_t bytes_freed() const { 6259 return _freed_bytes; 6260 } 6261 6262 size_t humongous_reclaimed() const { 6263 return _humongous_regions_removed.length(); 6264 } 6265 }; 6266 6267 void G1CollectedHeap::eagerly_reclaim_humongous_regions() { 6268 assert_at_safepoint(true); 6269 6270 if (!G1EagerReclaimHumongousObjects || 6271 (!_has_humongous_reclaim_candidates && !G1TraceEagerReclaimHumongousObjects)) { 6272 g1_policy()->phase_times()->record_fast_reclaim_humongous_time_ms(0.0, 0); 6273 return; 6274 } 6275 6276 double start_time = os::elapsedTime(); 6277 6278 FreeRegionList local_cleanup_list("Local Humongous Cleanup List"); 6279 6280 G1FreeHumongousRegionClosure cl(&local_cleanup_list); 6281 heap_region_iterate(&cl); 6282 6283 HeapRegionSetCount empty_set; 6284 remove_from_old_sets(empty_set, cl.humongous_free_count()); 6285 6286 G1HRPrinter* hr_printer = _g1h->hr_printer(); 6287 if (hr_printer->is_active()) { 6288 FreeRegionListIterator iter(&local_cleanup_list); 6289 while (iter.more_available()) { 6290 HeapRegion* hr = iter.get_next(); 6291 hr_printer->cleanup(hr); 6292 } 6293 } 6294 6295 prepend_to_freelist(&local_cleanup_list); 6296 decrement_summary_bytes(cl.bytes_freed()); 6297 6298 g1_policy()->phase_times()->record_fast_reclaim_humongous_time_ms((os::elapsedTime() - start_time) * 1000.0, 6299 cl.humongous_reclaimed()); 6300 } 6301 6302 // This routine is similar to the above but does not record 6303 // any policy statistics or update free lists; we are abandoning 6304 // the current incremental collection set in preparation of a 6305 // full collection. After the full GC we will start to build up 6306 // the incremental collection set again. 6307 // This is only called when we're doing a full collection 6308 // and is immediately followed by the tearing down of the young list. 6309 6310 void G1CollectedHeap::abandon_collection_set(HeapRegion* cs_head) { 6311 HeapRegion* cur = cs_head; 6312 6313 while (cur != NULL) { 6314 HeapRegion* next = cur->next_in_collection_set(); 6315 assert(cur->in_collection_set(), "bad CS"); 6316 cur->set_next_in_collection_set(NULL); 6317 cur->set_in_collection_set(false); 6318 cur->set_young_index_in_cset(-1); 6319 cur = next; 6320 } 6321 } 6322 6323 void G1CollectedHeap::set_free_regions_coming() { 6324 if (G1ConcRegionFreeingVerbose) { 6325 gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : " 6326 "setting free regions coming"); 6327 } 6328 6329 assert(!free_regions_coming(), "pre-condition"); 6330 _free_regions_coming = true; 6331 } 6332 6333 void G1CollectedHeap::reset_free_regions_coming() { 6334 assert(free_regions_coming(), "pre-condition"); 6335 6336 { 6337 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag); 6338 _free_regions_coming = false; 6339 SecondaryFreeList_lock->notify_all(); 6340 } 6341 6342 if (G1ConcRegionFreeingVerbose) { 6343 gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : " 6344 "reset free regions coming"); 6345 } 6346 } 6347 6348 void G1CollectedHeap::wait_while_free_regions_coming() { 6349 // Most of the time we won't have to wait, so let's do a quick test 6350 // first before we take the lock. 6351 if (!free_regions_coming()) { 6352 return; 6353 } 6354 6355 if (G1ConcRegionFreeingVerbose) { 6356 gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : " 6357 "waiting for free regions"); 6358 } 6359 6360 { 6361 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag); 6362 while (free_regions_coming()) { 6363 SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag); 6364 } 6365 } 6366 6367 if (G1ConcRegionFreeingVerbose) { 6368 gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : " 6369 "done waiting for free regions"); 6370 } 6371 } 6372 6373 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) { 6374 assert(heap_lock_held_for_gc(), 6375 "the heap lock should already be held by or for this thread"); 6376 _young_list->push_region(hr); 6377 } 6378 6379 class NoYoungRegionsClosure: public HeapRegionClosure { 6380 private: 6381 bool _success; 6382 public: 6383 NoYoungRegionsClosure() : _success(true) { } 6384 bool doHeapRegion(HeapRegion* r) { 6385 if (r->is_young()) { 6386 gclog_or_tty->print_cr("Region ["PTR_FORMAT", "PTR_FORMAT") tagged as young", 6387 r->bottom(), r->end()); 6388 _success = false; 6389 } 6390 return false; 6391 } 6392 bool success() { return _success; } 6393 }; 6394 6395 bool G1CollectedHeap::check_young_list_empty(bool check_heap, bool check_sample) { 6396 bool ret = _young_list->check_list_empty(check_sample); 6397 6398 if (check_heap) { 6399 NoYoungRegionsClosure closure; 6400 heap_region_iterate(&closure); 6401 ret = ret && closure.success(); 6402 } 6403 6404 return ret; 6405 } 6406 6407 class TearDownRegionSetsClosure : public HeapRegionClosure { 6408 private: 6409 HeapRegionSet *_old_set; 6410 6411 public: 6412 TearDownRegionSetsClosure(HeapRegionSet* old_set) : _old_set(old_set) { } 6413 6414 bool doHeapRegion(HeapRegion* r) { 6415 if (r->is_old()) { 6416 _old_set->remove(r); 6417 } else { 6418 // We ignore free regions, we'll empty the free list afterwards. 6419 // We ignore young regions, we'll empty the young list afterwards. 6420 // We ignore humongous regions, we're not tearing down the 6421 // humongous regions set. 6422 assert(r->is_free() || r->is_young() || r->is_humongous(), 6423 "it cannot be another type"); 6424 } 6425 return false; 6426 } 6427 6428 ~TearDownRegionSetsClosure() { 6429 assert(_old_set->is_empty(), "post-condition"); 6430 } 6431 }; 6432 6433 void G1CollectedHeap::tear_down_region_sets(bool free_list_only) { 6434 assert_at_safepoint(true /* should_be_vm_thread */); 6435 6436 if (!free_list_only) { 6437 TearDownRegionSetsClosure cl(&_old_set); 6438 heap_region_iterate(&cl); 6439 6440 // Note that emptying the _young_list is postponed and instead done as 6441 // the first step when rebuilding the regions sets again. The reason for 6442 // this is that during a full GC string deduplication needs to know if 6443 // a collected region was young or old when the full GC was initiated. 6444 } 6445 _hrm.remove_all_free_regions(); 6446 } 6447 6448 class RebuildRegionSetsClosure : public HeapRegionClosure { 6449 private: 6450 bool _free_list_only; 6451 HeapRegionSet* _old_set; 6452 HeapRegionManager* _hrm; 6453 size_t _total_used; 6454 6455 public: 6456 RebuildRegionSetsClosure(bool free_list_only, 6457 HeapRegionSet* old_set, HeapRegionManager* hrm) : 6458 _free_list_only(free_list_only), 6459 _old_set(old_set), _hrm(hrm), _total_used(0) { 6460 assert(_hrm->num_free_regions() == 0, "pre-condition"); 6461 if (!free_list_only) { 6462 assert(_old_set->is_empty(), "pre-condition"); 6463 } 6464 } 6465 6466 bool doHeapRegion(HeapRegion* r) { 6467 if (r->is_continues_humongous()) { 6468 return false; 6469 } 6470 6471 if (r->is_empty()) { 6472 // Add free regions to the free list 6473 r->set_free(); 6474 r->set_allocation_context(AllocationContext::system()); 6475 _hrm->insert_into_free_list(r); 6476 } else if (!_free_list_only) { 6477 assert(!r->is_young(), "we should not come across young regions"); 6478 6479 if (r->is_humongous()) { 6480 // We ignore humongous regions, we left the humongous set unchanged 6481 } else { 6482 // Objects that were compacted would have ended up on regions 6483 // that were previously old or free. 6484 assert(r->is_free() || r->is_old(), "invariant"); 6485 // We now consider them old, so register as such. 6486 r->set_old(); 6487 _old_set->add(r); 6488 } 6489 _total_used += r->used(); 6490 } 6491 6492 return false; 6493 } 6494 6495 size_t total_used() { 6496 return _total_used; 6497 } 6498 }; 6499 6500 void G1CollectedHeap::rebuild_region_sets(bool free_list_only) { 6501 assert_at_safepoint(true /* should_be_vm_thread */); 6502 6503 if (!free_list_only) { 6504 _young_list->empty_list(); 6505 } 6506 6507 RebuildRegionSetsClosure cl(free_list_only, &_old_set, &_hrm); 6508 heap_region_iterate(&cl); 6509 6510 if (!free_list_only) { 6511 _allocator->set_used(cl.total_used()); 6512 } 6513 assert(_allocator->used_unlocked() == recalculate_used(), 6514 err_msg("inconsistent _allocator->used_unlocked(), " 6515 "value: "SIZE_FORMAT" recalculated: "SIZE_FORMAT, 6516 _allocator->used_unlocked(), recalculate_used())); 6517 } 6518 6519 void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) { 6520 _refine_cte_cl->set_concurrent(concurrent); 6521 } 6522 6523 bool G1CollectedHeap::is_in_closed_subset(const void* p) const { 6524 HeapRegion* hr = heap_region_containing(p); 6525 return hr->is_in(p); 6526 } 6527 6528 // Methods for the mutator alloc region 6529 6530 HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size, 6531 bool force) { 6532 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */); 6533 assert(!force || g1_policy()->can_expand_young_list(), 6534 "if force is true we should be able to expand the young list"); 6535 bool young_list_full = g1_policy()->is_young_list_full(); 6536 if (force || !young_list_full) { 6537 HeapRegion* new_alloc_region = new_region(word_size, 6538 false /* is_old */, 6539 false /* do_expand */); 6540 if (new_alloc_region != NULL) { 6541 set_region_short_lived_locked(new_alloc_region); 6542 _hr_printer.alloc(new_alloc_region, G1HRPrinter::Eden, young_list_full); 6543 check_bitmaps("Mutator Region Allocation", new_alloc_region); 6544 return new_alloc_region; 6545 } 6546 } 6547 return NULL; 6548 } 6549 6550 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region, 6551 size_t allocated_bytes) { 6552 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */); 6553 assert(alloc_region->is_eden(), "all mutator alloc regions should be eden"); 6554 6555 g1_policy()->add_region_to_incremental_cset_lhs(alloc_region); 6556 _allocator->increase_used(allocated_bytes); 6557 _hr_printer.retire(alloc_region); 6558 // We update the eden sizes here, when the region is retired, 6559 // instead of when it's allocated, since this is the point that its 6560 // used space has been recored in _summary_bytes_used. 6561 g1mm()->update_eden_size(); 6562 } 6563 6564 void G1CollectedHeap::set_par_threads() { 6565 // Don't change the number of workers. Use the value previously set 6566 // in the workgroup. 6567 uint n_workers = workers()->active_workers(); 6568 assert(UseDynamicNumberOfGCThreads || 6569 n_workers == workers()->total_workers(), 6570 "Otherwise should be using the total number of workers"); 6571 if (n_workers == 0) { 6572 assert(false, "Should have been set in prior evacuation pause."); 6573 n_workers = ParallelGCThreads; 6574 workers()->set_active_workers(n_workers); 6575 } 6576 set_par_threads(n_workers); 6577 } 6578 6579 // Methods for the GC alloc regions 6580 6581 HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size, 6582 uint count, 6583 InCSetState dest) { 6584 assert(FreeList_lock->owned_by_self(), "pre-condition"); 6585 6586 if (count < g1_policy()->max_regions(dest)) { 6587 const bool is_survivor = (dest.is_young()); 6588 HeapRegion* new_alloc_region = new_region(word_size, 6589 !is_survivor, 6590 true /* do_expand */); 6591 if (new_alloc_region != NULL) { 6592 // We really only need to do this for old regions given that we 6593 // should never scan survivors. But it doesn't hurt to do it 6594 // for survivors too. 6595 new_alloc_region->record_timestamp(); 6596 if (is_survivor) { 6597 new_alloc_region->set_survivor(); 6598 _hr_printer.alloc(new_alloc_region, G1HRPrinter::Survivor); 6599 check_bitmaps("Survivor Region Allocation", new_alloc_region); 6600 } else { 6601 new_alloc_region->set_old(); 6602 _hr_printer.alloc(new_alloc_region, G1HRPrinter::Old); 6603 check_bitmaps("Old Region Allocation", new_alloc_region); 6604 } 6605 bool during_im = g1_policy()->collector_state()->during_initial_mark_pause(); 6606 new_alloc_region->note_start_of_copying(during_im); 6607 return new_alloc_region; 6608 } 6609 } 6610 return NULL; 6611 } 6612 6613 void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region, 6614 size_t allocated_bytes, 6615 InCSetState dest) { 6616 bool during_im = g1_policy()->collector_state()->during_initial_mark_pause(); 6617 alloc_region->note_end_of_copying(during_im); 6618 g1_policy()->record_bytes_copied_during_gc(allocated_bytes); 6619 if (dest.is_young()) { 6620 young_list()->add_survivor_region(alloc_region); 6621 } else { 6622 _old_set.add(alloc_region); 6623 } 6624 _hr_printer.retire(alloc_region); 6625 } 6626 6627 // Heap region set verification 6628 6629 class VerifyRegionListsClosure : public HeapRegionClosure { 6630 private: 6631 HeapRegionSet* _old_set; 6632 HeapRegionSet* _humongous_set; 6633 HeapRegionManager* _hrm; 6634 6635 public: 6636 HeapRegionSetCount _old_count; 6637 HeapRegionSetCount _humongous_count; 6638 HeapRegionSetCount _free_count; 6639 6640 VerifyRegionListsClosure(HeapRegionSet* old_set, 6641 HeapRegionSet* humongous_set, 6642 HeapRegionManager* hrm) : 6643 _old_set(old_set), _humongous_set(humongous_set), _hrm(hrm), 6644 _old_count(), _humongous_count(), _free_count(){ } 6645 6646 bool doHeapRegion(HeapRegion* hr) { 6647 if (hr->is_continues_humongous()) { 6648 return false; 6649 } 6650 6651 if (hr->is_young()) { 6652 // TODO 6653 } else if (hr->is_starts_humongous()) { 6654 assert(hr->containing_set() == _humongous_set, err_msg("Heap region %u is starts humongous but not in humongous set.", hr->hrm_index())); 6655 _humongous_count.increment(1u, hr->capacity()); 6656 } else if (hr->is_empty()) { 6657 assert(_hrm->is_free(hr), err_msg("Heap region %u is empty but not on the free list.", hr->hrm_index())); 6658 _free_count.increment(1u, hr->capacity()); 6659 } else if (hr->is_old()) { 6660 assert(hr->containing_set() == _old_set, err_msg("Heap region %u is old but not in the old set.", hr->hrm_index())); 6661 _old_count.increment(1u, hr->capacity()); 6662 } else { 6663 ShouldNotReachHere(); 6664 } 6665 return false; 6666 } 6667 6668 void verify_counts(HeapRegionSet* old_set, HeapRegionSet* humongous_set, HeapRegionManager* free_list) { 6669 guarantee(old_set->length() == _old_count.length(), err_msg("Old set count mismatch. Expected %u, actual %u.", old_set->length(), _old_count.length())); 6670 guarantee(old_set->total_capacity_bytes() == _old_count.capacity(), err_msg("Old set capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT, 6671 old_set->total_capacity_bytes(), _old_count.capacity())); 6672 6673 guarantee(humongous_set->length() == _humongous_count.length(), err_msg("Hum set count mismatch. Expected %u, actual %u.", humongous_set->length(), _humongous_count.length())); 6674 guarantee(humongous_set->total_capacity_bytes() == _humongous_count.capacity(), err_msg("Hum set capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT, 6675 humongous_set->total_capacity_bytes(), _humongous_count.capacity())); 6676 6677 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())); 6678 guarantee(free_list->total_capacity_bytes() == _free_count.capacity(), err_msg("Free list capacity mismatch. Expected " SIZE_FORMAT ", actual " SIZE_FORMAT, 6679 free_list->total_capacity_bytes(), _free_count.capacity())); 6680 } 6681 }; 6682 6683 void G1CollectedHeap::verify_region_sets() { 6684 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */); 6685 6686 // First, check the explicit lists. 6687 _hrm.verify(); 6688 { 6689 // Given that a concurrent operation might be adding regions to 6690 // the secondary free list we have to take the lock before 6691 // verifying it. 6692 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag); 6693 _secondary_free_list.verify_list(); 6694 } 6695 6696 // If a concurrent region freeing operation is in progress it will 6697 // be difficult to correctly attributed any free regions we come 6698 // across to the correct free list given that they might belong to 6699 // one of several (free_list, secondary_free_list, any local lists, 6700 // etc.). So, if that's the case we will skip the rest of the 6701 // verification operation. Alternatively, waiting for the concurrent 6702 // operation to complete will have a non-trivial effect on the GC's 6703 // operation (no concurrent operation will last longer than the 6704 // interval between two calls to verification) and it might hide 6705 // any issues that we would like to catch during testing. 6706 if (free_regions_coming()) { 6707 return; 6708 } 6709 6710 // Make sure we append the secondary_free_list on the free_list so 6711 // that all free regions we will come across can be safely 6712 // attributed to the free_list. 6713 append_secondary_free_list_if_not_empty_with_lock(); 6714 6715 // Finally, make sure that the region accounting in the lists is 6716 // consistent with what we see in the heap. 6717 6718 VerifyRegionListsClosure cl(&_old_set, &_humongous_set, &_hrm); 6719 heap_region_iterate(&cl); 6720 cl.verify_counts(&_old_set, &_humongous_set, &_hrm); 6721 } 6722 6723 // Optimized nmethod scanning 6724 6725 class RegisterNMethodOopClosure: public OopClosure { 6726 G1CollectedHeap* _g1h; 6727 nmethod* _nm; 6728 6729 template <class T> void do_oop_work(T* p) { 6730 T heap_oop = oopDesc::load_heap_oop(p); 6731 if (!oopDesc::is_null(heap_oop)) { 6732 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop); 6733 HeapRegion* hr = _g1h->heap_region_containing(obj); 6734 assert(!hr->is_continues_humongous(), 6735 err_msg("trying to add code root "PTR_FORMAT" in continuation of humongous region "HR_FORMAT 6736 " starting at "HR_FORMAT, 6737 _nm, HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()))); 6738 6739 // HeapRegion::add_strong_code_root_locked() avoids adding duplicate entries. 6740 hr->add_strong_code_root_locked(_nm); 6741 } 6742 } 6743 6744 public: 6745 RegisterNMethodOopClosure(G1CollectedHeap* g1h, nmethod* nm) : 6746 _g1h(g1h), _nm(nm) {} 6747 6748 void do_oop(oop* p) { do_oop_work(p); } 6749 void do_oop(narrowOop* p) { do_oop_work(p); } 6750 }; 6751 6752 class UnregisterNMethodOopClosure: public OopClosure { 6753 G1CollectedHeap* _g1h; 6754 nmethod* _nm; 6755 6756 template <class T> void do_oop_work(T* p) { 6757 T heap_oop = oopDesc::load_heap_oop(p); 6758 if (!oopDesc::is_null(heap_oop)) { 6759 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop); 6760 HeapRegion* hr = _g1h->heap_region_containing(obj); 6761 assert(!hr->is_continues_humongous(), 6762 err_msg("trying to remove code root "PTR_FORMAT" in continuation of humongous region "HR_FORMAT 6763 " starting at "HR_FORMAT, 6764 _nm, HR_FORMAT_PARAMS(hr), HR_FORMAT_PARAMS(hr->humongous_start_region()))); 6765 6766 hr->remove_strong_code_root(_nm); 6767 } 6768 } 6769 6770 public: 6771 UnregisterNMethodOopClosure(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 void G1CollectedHeap::register_nmethod(nmethod* nm) { 6779 CollectedHeap::register_nmethod(nm); 6780 6781 guarantee(nm != NULL, "sanity"); 6782 RegisterNMethodOopClosure reg_cl(this, nm); 6783 nm->oops_do(®_cl); 6784 } 6785 6786 void G1CollectedHeap::unregister_nmethod(nmethod* nm) { 6787 CollectedHeap::unregister_nmethod(nm); 6788 6789 guarantee(nm != NULL, "sanity"); 6790 UnregisterNMethodOopClosure reg_cl(this, nm); 6791 nm->oops_do(®_cl, true); 6792 } 6793 6794 void G1CollectedHeap::purge_code_root_memory() { 6795 double purge_start = os::elapsedTime(); 6796 G1CodeRootSet::purge(); 6797 double purge_time_ms = (os::elapsedTime() - purge_start) * 1000.0; 6798 g1_policy()->phase_times()->record_strong_code_root_purge_time(purge_time_ms); 6799 } 6800 6801 class RebuildStrongCodeRootClosure: public CodeBlobClosure { 6802 G1CollectedHeap* _g1h; 6803 6804 public: 6805 RebuildStrongCodeRootClosure(G1CollectedHeap* g1h) : 6806 _g1h(g1h) {} 6807 6808 void do_code_blob(CodeBlob* cb) { 6809 nmethod* nm = (cb != NULL) ? cb->as_nmethod_or_null() : NULL; 6810 if (nm == NULL) { 6811 return; 6812 } 6813 6814 if (ScavengeRootsInCode) { 6815 _g1h->register_nmethod(nm); 6816 } 6817 } 6818 }; 6819 6820 void G1CollectedHeap::rebuild_strong_code_roots() { 6821 RebuildStrongCodeRootClosure blob_cl(this); 6822 CodeCache::blobs_do(&blob_cl); 6823 }