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