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