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