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