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 size_t G1CollectedHeap::humongous_obj_allocate_find_first(size_t num_regions, 591 size_t word_size) { 592 assert(isHumongous(word_size), "word_size should be humongous"); 593 assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition"); 594 595 size_t first = G1_NULL_HRS_INDEX; 596 if (num_regions == 1) { 597 // Only one region to allocate, no need to go through the slower 598 // path. The caller will attempt the expasion if this fails, so 599 // let's not try to expand here too. 600 HeapRegion* hr = new_region(word_size, false /* do_expand */); 601 if (hr != NULL) { 602 first = hr->hrs_index(); 603 } else { 604 first = G1_NULL_HRS_INDEX; 605 } 606 } else { 607 // We can't allocate humongous regions while cleanupComplete() is 608 // running, since some of the regions we find to be empty might not 609 // yet be added to the free list and it is not straightforward to 610 // know which list they are on so that we can remove them. Note 611 // that we only need to do this if we need to allocate more than 612 // one region to satisfy the current humongous allocation 613 // request. If we are only allocating one region we use the common 614 // region allocation code (see above). 615 wait_while_free_regions_coming(); 616 append_secondary_free_list_if_not_empty_with_lock(); 617 618 if (free_regions() >= num_regions) { 619 first = _hrs.find_contiguous(num_regions); 620 if (first != G1_NULL_HRS_INDEX) { 621 for (size_t i = first; i < first + num_regions; ++i) { 622 HeapRegion* hr = region_at(i); 623 assert(hr->is_empty(), "sanity"); 624 assert(is_on_master_free_list(hr), "sanity"); 625 hr->set_pending_removal(true); 626 } 627 _free_list.remove_all_pending(num_regions); 628 } 629 } 630 } 631 return first; 632 } 633 634 HeapWord* 635 G1CollectedHeap::humongous_obj_allocate_initialize_regions(size_t first, 636 size_t num_regions, 637 size_t word_size) { 638 assert(first != G1_NULL_HRS_INDEX, "pre-condition"); 639 assert(isHumongous(word_size), "word_size should be humongous"); 640 assert(num_regions * HeapRegion::GrainWords >= word_size, "pre-condition"); 641 642 // Index of last region in the series + 1. 643 size_t last = first + num_regions; 644 645 // We need to initialize the region(s) we just discovered. This is 646 // a bit tricky given that it can happen concurrently with 647 // refinement threads refining cards on these regions and 648 // potentially wanting to refine the BOT as they are scanning 649 // those cards (this can happen shortly after a cleanup; see CR 650 // 6991377). So we have to set up the region(s) carefully and in 651 // a specific order. 652 653 // The word size sum of all the regions we will allocate. 654 size_t word_size_sum = num_regions * HeapRegion::GrainWords; 655 assert(word_size <= word_size_sum, "sanity"); 656 657 // This will be the "starts humongous" region. 658 HeapRegion* first_hr = region_at(first); 659 // The header of the new object will be placed at the bottom of 660 // the first region. 661 HeapWord* new_obj = first_hr->bottom(); 662 // This will be the new end of the first region in the series that 663 // should also match the end of the last region in the seriers. 664 HeapWord* new_end = new_obj + word_size_sum; 665 // This will be the new top of the first region that will reflect 666 // this allocation. 667 HeapWord* new_top = new_obj + word_size; 668 669 // First, we need to zero the header of the space that we will be 670 // allocating. When we update top further down, some refinement 671 // threads might try to scan the region. By zeroing the header we 672 // ensure that any thread that will try to scan the region will 673 // come across the zero klass word and bail out. 674 // 675 // NOTE: It would not have been correct to have used 676 // CollectedHeap::fill_with_object() and make the space look like 677 // an int array. The thread that is doing the allocation will 678 // later update the object header to a potentially different array 679 // type and, for a very short period of time, the klass and length 680 // fields will be inconsistent. This could cause a refinement 681 // thread to calculate the object size incorrectly. 682 Copy::fill_to_words(new_obj, oopDesc::header_size(), 0); 683 684 // We will set up the first region as "starts humongous". This 685 // will also update the BOT covering all the regions to reflect 686 // that there is a single object that starts at the bottom of the 687 // first region. 688 first_hr->set_startsHumongous(new_top, new_end); 689 690 // Then, if there are any, we will set up the "continues 691 // humongous" regions. 692 HeapRegion* hr = NULL; 693 for (size_t i = first + 1; i < last; ++i) { 694 hr = region_at(i); 695 hr->set_continuesHumongous(first_hr); 696 } 697 // If we have "continues humongous" regions (hr != NULL), then the 698 // end of the last one should match new_end. 699 assert(hr == NULL || hr->end() == new_end, "sanity"); 700 701 // Up to this point no concurrent thread would have been able to 702 // do any scanning on any region in this series. All the top 703 // fields still point to bottom, so the intersection between 704 // [bottom,top] and [card_start,card_end] will be empty. Before we 705 // update the top fields, we'll do a storestore to make sure that 706 // no thread sees the update to top before the zeroing of the 707 // object header and the BOT initialization. 708 OrderAccess::storestore(); 709 710 // Now that the BOT and the object header have been initialized, 711 // we can update top of the "starts humongous" region. 712 assert(first_hr->bottom() < new_top && new_top <= first_hr->end(), 713 "new_top should be in this region"); 714 first_hr->set_top(new_top); 715 if (_hr_printer.is_active()) { 716 HeapWord* bottom = first_hr->bottom(); 717 HeapWord* end = first_hr->orig_end(); 718 if ((first + 1) == last) { 719 // the series has a single humongous region 720 _hr_printer.alloc(G1HRPrinter::SingleHumongous, first_hr, new_top); 721 } else { 722 // the series has more than one humongous regions 723 _hr_printer.alloc(G1HRPrinter::StartsHumongous, first_hr, end); 724 } 725 } 726 727 // Now, we will update the top fields of the "continues humongous" 728 // regions. The reason we need to do this is that, otherwise, 729 // these regions would look empty and this will confuse parts of 730 // G1. For example, the code that looks for a consecutive number 731 // of empty regions will consider them empty and try to 732 // re-allocate them. We can extend is_empty() to also include 733 // !continuesHumongous(), but it is easier to just update the top 734 // fields here. The way we set top for all regions (i.e., top == 735 // end for all regions but the last one, top == new_top for the 736 // last one) is actually used when we will free up the humongous 737 // region in free_humongous_region(). 738 hr = NULL; 739 for (size_t i = first + 1; i < last; ++i) { 740 hr = region_at(i); 741 if ((i + 1) == last) { 742 // last continues humongous region 743 assert(hr->bottom() < new_top && new_top <= hr->end(), 744 "new_top should fall on this region"); 745 hr->set_top(new_top); 746 _hr_printer.alloc(G1HRPrinter::ContinuesHumongous, hr, new_top); 747 } else { 748 // not last one 749 assert(new_top > hr->end(), "new_top should be above this region"); 750 hr->set_top(hr->end()); 751 _hr_printer.alloc(G1HRPrinter::ContinuesHumongous, hr, hr->end()); 752 } 753 } 754 // If we have continues humongous regions (hr != NULL), then the 755 // end of the last one should match new_end and its top should 756 // match new_top. 757 assert(hr == NULL || 758 (hr->end() == new_end && hr->top() == new_top), "sanity"); 759 760 assert(first_hr->used() == word_size * HeapWordSize, "invariant"); 761 _summary_bytes_used += first_hr->used(); 762 _humongous_set.add(first_hr); 763 764 return new_obj; 765 } 766 767 // If could fit into free regions w/o expansion, try. 768 // Otherwise, if can expand, do so. 769 // Otherwise, if using ex regions might help, try with ex given back. 770 HeapWord* G1CollectedHeap::humongous_obj_allocate(size_t word_size) { 771 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */); 772 773 verify_region_sets_optional(); 774 775 size_t num_regions = 776 round_to(word_size, HeapRegion::GrainWords) / HeapRegion::GrainWords; 777 size_t x_size = expansion_regions(); 778 size_t fs = _hrs.free_suffix(); 779 size_t first = humongous_obj_allocate_find_first(num_regions, word_size); 780 if (first == G1_NULL_HRS_INDEX) { 781 // The only thing we can do now is attempt expansion. 782 if (fs + x_size >= num_regions) { 783 // If the number of regions we're trying to allocate for this 784 // object is at most the number of regions in the free suffix, 785 // then the call to humongous_obj_allocate_find_first() above 786 // should have succeeded and we wouldn't be here. 787 // 788 // We should only be trying to expand when the free suffix is 789 // not sufficient for the object _and_ we have some expansion 790 // room available. 791 assert(num_regions > fs, "earlier allocation should have succeeded"); 792 793 if (expand((num_regions - fs) * HeapRegion::GrainBytes)) { 794 // Even though the heap was expanded, it might not have 795 // reached the desired size. So, we cannot assume that the 796 // allocation will succeed. 797 first = humongous_obj_allocate_find_first(num_regions, word_size); 798 } 799 } 800 } 801 802 HeapWord* result = NULL; 803 if (first != G1_NULL_HRS_INDEX) { 804 result = 805 humongous_obj_allocate_initialize_regions(first, num_regions, word_size); 806 assert(result != NULL, "it should always return a valid result"); 807 } 808 809 verify_region_sets_optional(); 810 811 return result; 812 } 813 814 HeapWord* G1CollectedHeap::allocate_new_tlab(size_t word_size) { 815 assert_heap_not_locked_and_not_at_safepoint(); 816 assert(!isHumongous(word_size), "we do not allow humongous TLABs"); 817 818 unsigned int dummy_gc_count_before; 819 return attempt_allocation(word_size, &dummy_gc_count_before); 820 } 821 822 HeapWord* 823 G1CollectedHeap::mem_allocate(size_t word_size, 824 bool* gc_overhead_limit_was_exceeded) { 825 assert_heap_not_locked_and_not_at_safepoint(); 826 827 // Loop until the allocation is satisified, or unsatisfied after GC. 828 for (int try_count = 1; /* we'll return */; try_count += 1) { 829 unsigned int gc_count_before; 830 831 HeapWord* result = NULL; 832 if (!isHumongous(word_size)) { 833 result = attempt_allocation(word_size, &gc_count_before); 834 } else { 835 result = attempt_allocation_humongous(word_size, &gc_count_before); 836 } 837 if (result != NULL) { 838 return result; 839 } 840 841 // Create the garbage collection operation... 842 VM_G1CollectForAllocation op(gc_count_before, word_size); 843 // ...and get the VM thread to execute it. 844 VMThread::execute(&op); 845 846 if (op.prologue_succeeded() && op.pause_succeeded()) { 847 // If the operation was successful we'll return the result even 848 // if it is NULL. If the allocation attempt failed immediately 849 // after a Full GC, it's unlikely we'll be able to allocate now. 850 HeapWord* result = op.result(); 851 if (result != NULL && !isHumongous(word_size)) { 852 // Allocations that take place on VM operations do not do any 853 // card dirtying and we have to do it here. We only have to do 854 // this for non-humongous allocations, though. 855 dirty_young_block(result, word_size); 856 } 857 return result; 858 } else { 859 assert(op.result() == NULL, 860 "the result should be NULL if the VM op did not succeed"); 861 } 862 863 // Give a warning if we seem to be looping forever. 864 if ((QueuedAllocationWarningCount > 0) && 865 (try_count % QueuedAllocationWarningCount == 0)) { 866 warning("G1CollectedHeap::mem_allocate retries %d times", try_count); 867 } 868 } 869 870 ShouldNotReachHere(); 871 return NULL; 872 } 873 874 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size, 875 unsigned int *gc_count_before_ret) { 876 // Make sure you read the note in attempt_allocation_humongous(). 877 878 assert_heap_not_locked_and_not_at_safepoint(); 879 assert(!isHumongous(word_size), "attempt_allocation_slow() should not " 880 "be called for humongous allocation requests"); 881 882 // We should only get here after the first-level allocation attempt 883 // (attempt_allocation()) failed to allocate. 884 885 // We will loop until a) we manage to successfully perform the 886 // allocation or b) we successfully schedule a collection which 887 // fails to perform the allocation. b) is the only case when we'll 888 // return NULL. 889 HeapWord* result = NULL; 890 for (int try_count = 1; /* we'll return */; try_count += 1) { 891 bool should_try_gc; 892 unsigned int gc_count_before; 893 894 { 895 MutexLockerEx x(Heap_lock); 896 897 result = _mutator_alloc_region.attempt_allocation_locked(word_size, 898 false /* bot_updates */); 899 if (result != NULL) { 900 return result; 901 } 902 903 // If we reach here, attempt_allocation_locked() above failed to 904 // allocate a new region. So the mutator alloc region should be NULL. 905 assert(_mutator_alloc_region.get() == NULL, "only way to get here"); 906 907 if (GC_locker::is_active_and_needs_gc()) { 908 if (g1_policy()->can_expand_young_list()) { 909 result = _mutator_alloc_region.attempt_allocation_force(word_size, 910 false /* bot_updates */); 911 if (result != NULL) { 912 return result; 913 } 914 } 915 should_try_gc = false; 916 } else { 917 // Read the GC count while still holding the Heap_lock. 918 gc_count_before = SharedHeap::heap()->total_collections(); 919 should_try_gc = true; 920 } 921 } 922 923 if (should_try_gc) { 924 bool succeeded; 925 result = do_collection_pause(word_size, gc_count_before, &succeeded); 926 if (result != NULL) { 927 assert(succeeded, "only way to get back a non-NULL result"); 928 return result; 929 } 930 931 if (succeeded) { 932 // If we get here we successfully scheduled a collection which 933 // failed to allocate. No point in trying to allocate 934 // further. We'll just return NULL. 935 MutexLockerEx x(Heap_lock); 936 *gc_count_before_ret = SharedHeap::heap()->total_collections(); 937 return NULL; 938 } 939 } else { 940 GC_locker::stall_until_clear(); 941 } 942 943 // We can reach here if we were unsuccessul in scheduling a 944 // collection (because another thread beat us to it) or if we were 945 // stalled due to the GC locker. In either can we should retry the 946 // allocation attempt in case another thread successfully 947 // performed a collection and reclaimed enough space. We do the 948 // first attempt (without holding the Heap_lock) here and the 949 // follow-on attempt will be at the start of the next loop 950 // iteration (after taking the Heap_lock). 951 result = _mutator_alloc_region.attempt_allocation(word_size, 952 false /* bot_updates */); 953 if (result != NULL ){ 954 return result; 955 } 956 957 // Give a warning if we seem to be looping forever. 958 if ((QueuedAllocationWarningCount > 0) && 959 (try_count % QueuedAllocationWarningCount == 0)) { 960 warning("G1CollectedHeap::attempt_allocation_slow() " 961 "retries %d times", try_count); 962 } 963 } 964 965 ShouldNotReachHere(); 966 return NULL; 967 } 968 969 HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size, 970 unsigned int * gc_count_before_ret) { 971 // The structure of this method has a lot of similarities to 972 // attempt_allocation_slow(). The reason these two were not merged 973 // into a single one is that such a method would require several "if 974 // allocation is not humongous do this, otherwise do that" 975 // conditional paths which would obscure its flow. In fact, an early 976 // version of this code did use a unified method which was harder to 977 // follow and, as a result, it had subtle bugs that were hard to 978 // track down. So keeping these two methods separate allows each to 979 // be more readable. It will be good to keep these two in sync as 980 // much as possible. 981 982 assert_heap_not_locked_and_not_at_safepoint(); 983 assert(isHumongous(word_size), "attempt_allocation_humongous() " 984 "should only be called for humongous allocations"); 985 986 // We will loop until a) we manage to successfully perform the 987 // allocation or b) we successfully schedule a collection which 988 // fails to perform the allocation. b) is the only case when we'll 989 // return NULL. 990 HeapWord* result = NULL; 991 for (int try_count = 1; /* we'll return */; try_count += 1) { 992 bool should_try_gc; 993 unsigned int gc_count_before; 994 995 { 996 MutexLockerEx x(Heap_lock); 997 998 // Given that humongous objects are not allocated in young 999 // regions, we'll first try to do the allocation without doing a 1000 // collection hoping that there's enough space in the heap. 1001 result = humongous_obj_allocate(word_size); 1002 if (result != NULL) { 1003 return result; 1004 } 1005 1006 if (GC_locker::is_active_and_needs_gc()) { 1007 should_try_gc = false; 1008 } else { 1009 // Read the GC count while still holding the Heap_lock. 1010 gc_count_before = SharedHeap::heap()->total_collections(); 1011 should_try_gc = true; 1012 } 1013 } 1014 1015 if (should_try_gc) { 1016 // If we failed to allocate the humongous object, we should try to 1017 // do a collection pause (if we're allowed) in case it reclaims 1018 // enough space for the allocation to succeed after the pause. 1019 1020 bool succeeded; 1021 result = do_collection_pause(word_size, gc_count_before, &succeeded); 1022 if (result != NULL) { 1023 assert(succeeded, "only way to get back a non-NULL result"); 1024 return result; 1025 } 1026 1027 if (succeeded) { 1028 // If we get here we successfully scheduled a collection which 1029 // failed to allocate. No point in trying to allocate 1030 // further. We'll just return NULL. 1031 MutexLockerEx x(Heap_lock); 1032 *gc_count_before_ret = SharedHeap::heap()->total_collections(); 1033 return NULL; 1034 } 1035 } else { 1036 GC_locker::stall_until_clear(); 1037 } 1038 1039 // We can reach here if we were unsuccessul in scheduling a 1040 // collection (because another thread beat us to it) or if we were 1041 // stalled due to the GC locker. In either can we should retry the 1042 // allocation attempt in case another thread successfully 1043 // performed a collection and reclaimed enough space. Give a 1044 // warning if we seem to be looping forever. 1045 1046 if ((QueuedAllocationWarningCount > 0) && 1047 (try_count % QueuedAllocationWarningCount == 0)) { 1048 warning("G1CollectedHeap::attempt_allocation_humongous() " 1049 "retries %d times", try_count); 1050 } 1051 } 1052 1053 ShouldNotReachHere(); 1054 return NULL; 1055 } 1056 1057 HeapWord* G1CollectedHeap::attempt_allocation_at_safepoint(size_t word_size, 1058 bool expect_null_mutator_alloc_region) { 1059 assert_at_safepoint(true /* should_be_vm_thread */); 1060 assert(_mutator_alloc_region.get() == NULL || 1061 !expect_null_mutator_alloc_region, 1062 "the current alloc region was unexpectedly found to be non-NULL"); 1063 1064 if (!isHumongous(word_size)) { 1065 return _mutator_alloc_region.attempt_allocation_locked(word_size, 1066 false /* bot_updates */); 1067 } else { 1068 return humongous_obj_allocate(word_size); 1069 } 1070 1071 ShouldNotReachHere(); 1072 } 1073 1074 class PostMCRemSetClearClosure: public HeapRegionClosure { 1075 ModRefBarrierSet* _mr_bs; 1076 public: 1077 PostMCRemSetClearClosure(ModRefBarrierSet* mr_bs) : _mr_bs(mr_bs) {} 1078 bool doHeapRegion(HeapRegion* r) { 1079 r->reset_gc_time_stamp(); 1080 if (r->continuesHumongous()) 1081 return false; 1082 HeapRegionRemSet* hrrs = r->rem_set(); 1083 if (hrrs != NULL) hrrs->clear(); 1084 // You might think here that we could clear just the cards 1085 // corresponding to the used region. But no: if we leave a dirty card 1086 // in a region we might allocate into, then it would prevent that card 1087 // from being enqueued, and cause it to be missed. 1088 // Re: the performance cost: we shouldn't be doing full GC anyway! 1089 _mr_bs->clear(MemRegion(r->bottom(), r->end())); 1090 return false; 1091 } 1092 }; 1093 1094 1095 class PostMCRemSetInvalidateClosure: public HeapRegionClosure { 1096 ModRefBarrierSet* _mr_bs; 1097 public: 1098 PostMCRemSetInvalidateClosure(ModRefBarrierSet* mr_bs) : _mr_bs(mr_bs) {} 1099 bool doHeapRegion(HeapRegion* r) { 1100 if (r->continuesHumongous()) return false; 1101 if (r->used_region().word_size() != 0) { 1102 _mr_bs->invalidate(r->used_region(), true /*whole heap*/); 1103 } 1104 return false; 1105 } 1106 }; 1107 1108 class RebuildRSOutOfRegionClosure: public HeapRegionClosure { 1109 G1CollectedHeap* _g1h; 1110 UpdateRSOopClosure _cl; 1111 int _worker_i; 1112 public: 1113 RebuildRSOutOfRegionClosure(G1CollectedHeap* g1, int worker_i = 0) : 1114 _cl(g1->g1_rem_set(), worker_i), 1115 _worker_i(worker_i), 1116 _g1h(g1) 1117 { } 1118 1119 bool doHeapRegion(HeapRegion* r) { 1120 if (!r->continuesHumongous()) { 1121 _cl.set_from(r); 1122 r->oop_iterate(&_cl); 1123 } 1124 return false; 1125 } 1126 }; 1127 1128 class ParRebuildRSTask: public AbstractGangTask { 1129 G1CollectedHeap* _g1; 1130 public: 1131 ParRebuildRSTask(G1CollectedHeap* g1) 1132 : AbstractGangTask("ParRebuildRSTask"), 1133 _g1(g1) 1134 { } 1135 1136 void work(int i) { 1137 RebuildRSOutOfRegionClosure rebuild_rs(_g1, i); 1138 _g1->heap_region_par_iterate_chunked(&rebuild_rs, i, 1139 HeapRegion::RebuildRSClaimValue); 1140 } 1141 }; 1142 1143 class PostCompactionPrinterClosure: public HeapRegionClosure { 1144 private: 1145 G1HRPrinter* _hr_printer; 1146 public: 1147 bool doHeapRegion(HeapRegion* hr) { 1148 assert(!hr->is_young(), "not expecting to find young regions"); 1149 // We only generate output for non-empty regions. 1150 if (!hr->is_empty()) { 1151 if (!hr->isHumongous()) { 1152 _hr_printer->post_compaction(hr, G1HRPrinter::Old); 1153 } else if (hr->startsHumongous()) { 1154 if (hr->capacity() == (size_t) HeapRegion::GrainBytes) { 1155 // single humongous region 1156 _hr_printer->post_compaction(hr, G1HRPrinter::SingleHumongous); 1157 } else { 1158 _hr_printer->post_compaction(hr, G1HRPrinter::StartsHumongous); 1159 } 1160 } else { 1161 assert(hr->continuesHumongous(), "only way to get here"); 1162 _hr_printer->post_compaction(hr, G1HRPrinter::ContinuesHumongous); 1163 } 1164 } 1165 return false; 1166 } 1167 1168 PostCompactionPrinterClosure(G1HRPrinter* hr_printer) 1169 : _hr_printer(hr_printer) { } 1170 }; 1171 1172 bool G1CollectedHeap::do_collection(bool explicit_gc, 1173 bool clear_all_soft_refs, 1174 size_t word_size) { 1175 assert_at_safepoint(true /* should_be_vm_thread */); 1176 1177 if (GC_locker::check_active_before_gc()) { 1178 return false; 1179 } 1180 1181 SvcGCMarker sgcm(SvcGCMarker::FULL); 1182 ResourceMark rm; 1183 1184 if (PrintHeapAtGC) { 1185 Universe::print_heap_before_gc(); 1186 } 1187 1188 verify_region_sets_optional(); 1189 1190 const bool do_clear_all_soft_refs = clear_all_soft_refs || 1191 collector_policy()->should_clear_all_soft_refs(); 1192 1193 ClearedAllSoftRefs casr(do_clear_all_soft_refs, collector_policy()); 1194 1195 { 1196 IsGCActiveMark x; 1197 1198 // Timing 1199 bool system_gc = (gc_cause() == GCCause::_java_lang_system_gc); 1200 assert(!system_gc || explicit_gc, "invariant"); 1201 gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps); 1202 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); 1203 TraceTime t(system_gc ? "Full GC (System.gc())" : "Full GC", 1204 PrintGC, true, gclog_or_tty); 1205 1206 TraceCollectorStats tcs(g1mm()->full_collection_counters()); 1207 TraceMemoryManagerStats tms(true /* fullGC */, gc_cause()); 1208 1209 double start = os::elapsedTime(); 1210 g1_policy()->record_full_collection_start(); 1211 1212 wait_while_free_regions_coming(); 1213 append_secondary_free_list_if_not_empty_with_lock(); 1214 1215 gc_prologue(true); 1216 increment_total_collections(true /* full gc */); 1217 1218 size_t g1h_prev_used = used(); 1219 assert(used() == recalculate_used(), "Should be equal"); 1220 1221 if (VerifyBeforeGC && total_collections() >= VerifyGCStartAt) { 1222 HandleMark hm; // Discard invalid handles created during verification 1223 gclog_or_tty->print(" VerifyBeforeGC:"); 1224 prepare_for_verify(); 1225 Universe::verify(/* allow dirty */ true, 1226 /* silent */ false, 1227 /* option */ VerifyOption_G1UsePrevMarking); 1228 1229 } 1230 1231 COMPILER2_PRESENT(DerivedPointerTable::clear()); 1232 1233 // We want to discover references, but not process them yet. 1234 // This mode is disabled in 1235 // instanceRefKlass::process_discovered_references if the 1236 // generation does some collection work, or 1237 // instanceRefKlass::enqueue_discovered_references if the 1238 // generation returns without doing any work. 1239 ref_processor()->disable_discovery(); 1240 ref_processor()->abandon_partial_discovery(); 1241 ref_processor()->verify_no_references_recorded(); 1242 1243 // Abandon current iterations of concurrent marking and concurrent 1244 // refinement, if any are in progress. 1245 concurrent_mark()->abort(); 1246 1247 // Make sure we'll choose a new allocation region afterwards. 1248 release_mutator_alloc_region(); 1249 abandon_gc_alloc_regions(); 1250 g1_rem_set()->cleanupHRRS(); 1251 tear_down_region_lists(); 1252 1253 // We should call this after we retire any currently active alloc 1254 // regions so that all the ALLOC / RETIRE events are generated 1255 // before the start GC event. 1256 _hr_printer.start_gc(true /* full */, (size_t) total_collections()); 1257 1258 // We may have added regions to the current incremental collection 1259 // set between the last GC or pause and now. We need to clear the 1260 // incremental collection set and then start rebuilding it afresh 1261 // after this full GC. 1262 abandon_collection_set(g1_policy()->inc_cset_head()); 1263 g1_policy()->clear_incremental_cset(); 1264 g1_policy()->stop_incremental_cset_building(); 1265 1266 empty_young_list(); 1267 g1_policy()->set_full_young_gcs(true); 1268 1269 // See the comment in G1CollectedHeap::ref_processing_init() about 1270 // how reference processing currently works in G1. 1271 1272 // Temporarily make reference _discovery_ single threaded (non-MT). 1273 ReferenceProcessorMTDiscoveryMutator rp_disc_ser(ref_processor(), false); 1274 1275 // Temporarily make refs discovery atomic 1276 ReferenceProcessorAtomicMutator rp_disc_atomic(ref_processor(), true); 1277 1278 // Temporarily clear _is_alive_non_header 1279 ReferenceProcessorIsAliveMutator rp_is_alive_null(ref_processor(), NULL); 1280 1281 ref_processor()->enable_discovery(); 1282 ref_processor()->setup_policy(do_clear_all_soft_refs); 1283 // Do collection work 1284 { 1285 HandleMark hm; // Discard invalid handles created during gc 1286 G1MarkSweep::invoke_at_safepoint(ref_processor(), do_clear_all_soft_refs); 1287 } 1288 assert(free_regions() == 0, "we should not have added any free regions"); 1289 rebuild_region_lists(); 1290 1291 _summary_bytes_used = recalculate_used(); 1292 1293 ref_processor()->enqueue_discovered_references(); 1294 1295 COMPILER2_PRESENT(DerivedPointerTable::update_pointers()); 1296 1297 MemoryService::track_memory_usage(); 1298 1299 if (VerifyAfterGC && total_collections() >= VerifyGCStartAt) { 1300 HandleMark hm; // Discard invalid handles created during verification 1301 gclog_or_tty->print(" VerifyAfterGC:"); 1302 prepare_for_verify(); 1303 Universe::verify(/* allow dirty */ false, 1304 /* silent */ false, 1305 /* option */ VerifyOption_G1UsePrevMarking); 1306 1307 } 1308 NOT_PRODUCT(ref_processor()->verify_no_references_recorded()); 1309 1310 reset_gc_time_stamp(); 1311 // Since everything potentially moved, we will clear all remembered 1312 // sets, and clear all cards. Later we will rebuild remebered 1313 // sets. We will also reset the GC time stamps of the regions. 1314 PostMCRemSetClearClosure rs_clear(mr_bs()); 1315 heap_region_iterate(&rs_clear); 1316 1317 // Resize the heap if necessary. 1318 resize_if_necessary_after_full_collection(explicit_gc ? 0 : word_size); 1319 1320 if (_hr_printer.is_active()) { 1321 // We should do this after we potentially resize the heap so 1322 // that all the COMMIT / UNCOMMIT events are generated before 1323 // the end GC event. 1324 1325 PostCompactionPrinterClosure cl(hr_printer()); 1326 heap_region_iterate(&cl); 1327 1328 _hr_printer.end_gc(true /* full */, (size_t) total_collections()); 1329 } 1330 1331 if (_cg1r->use_cache()) { 1332 _cg1r->clear_and_record_card_counts(); 1333 _cg1r->clear_hot_cache(); 1334 } 1335 1336 // Rebuild remembered sets of all regions. 1337 1338 if (G1CollectedHeap::use_parallel_gc_threads()) { 1339 ParRebuildRSTask rebuild_rs_task(this); 1340 assert(check_heap_region_claim_values( 1341 HeapRegion::InitialClaimValue), "sanity check"); 1342 set_par_threads(workers()->total_workers()); 1343 workers()->run_task(&rebuild_rs_task); 1344 set_par_threads(0); 1345 assert(check_heap_region_claim_values( 1346 HeapRegion::RebuildRSClaimValue), "sanity check"); 1347 reset_heap_region_claim_values(); 1348 } else { 1349 RebuildRSOutOfRegionClosure rebuild_rs(this); 1350 heap_region_iterate(&rebuild_rs); 1351 } 1352 1353 if (PrintGC) { 1354 print_size_transition(gclog_or_tty, g1h_prev_used, used(), capacity()); 1355 } 1356 1357 if (true) { // FIXME 1358 // Ask the permanent generation to adjust size for full collections 1359 perm()->compute_new_size(); 1360 } 1361 1362 // Start a new incremental collection set for the next pause 1363 assert(g1_policy()->collection_set() == NULL, "must be"); 1364 g1_policy()->start_incremental_cset_building(); 1365 1366 // Clear the _cset_fast_test bitmap in anticipation of adding 1367 // regions to the incremental collection set for the next 1368 // evacuation pause. 1369 clear_cset_fast_test(); 1370 1371 init_mutator_alloc_region(); 1372 1373 double end = os::elapsedTime(); 1374 g1_policy()->record_full_collection_end(); 1375 1376 #ifdef TRACESPINNING 1377 ParallelTaskTerminator::print_termination_counts(); 1378 #endif 1379 1380 gc_epilogue(true); 1381 1382 // Discard all rset updates 1383 JavaThread::dirty_card_queue_set().abandon_logs(); 1384 assert(!G1DeferredRSUpdate 1385 || (G1DeferredRSUpdate && (dirty_card_queue_set().completed_buffers_num() == 0)), "Should not be any"); 1386 } 1387 1388 _young_list->reset_sampled_info(); 1389 // At this point there should be no regions in the 1390 // entire heap tagged as young. 1391 assert( check_young_list_empty(true /* check_heap */), 1392 "young list should be empty at this point"); 1393 1394 // Update the number of full collections that have been completed. 1395 increment_full_collections_completed(false /* concurrent */); 1396 1397 _hrs.verify_optional(); 1398 verify_region_sets_optional(); 1399 1400 if (PrintHeapAtGC) { 1401 Universe::print_heap_after_gc(); 1402 } 1403 g1mm()->update_counters(); 1404 1405 return true; 1406 } 1407 1408 void G1CollectedHeap::do_full_collection(bool clear_all_soft_refs) { 1409 // do_collection() will return whether it succeeded in performing 1410 // the GC. Currently, there is no facility on the 1411 // do_full_collection() API to notify the caller than the collection 1412 // did not succeed (e.g., because it was locked out by the GC 1413 // locker). So, right now, we'll ignore the return value. 1414 bool dummy = do_collection(true, /* explicit_gc */ 1415 clear_all_soft_refs, 1416 0 /* word_size */); 1417 } 1418 1419 // This code is mostly copied from TenuredGeneration. 1420 void 1421 G1CollectedHeap:: 1422 resize_if_necessary_after_full_collection(size_t word_size) { 1423 assert(MinHeapFreeRatio <= MaxHeapFreeRatio, "sanity check"); 1424 1425 // Include the current allocation, if any, and bytes that will be 1426 // pre-allocated to support collections, as "used". 1427 const size_t used_after_gc = used(); 1428 const size_t capacity_after_gc = capacity(); 1429 const size_t free_after_gc = capacity_after_gc - used_after_gc; 1430 1431 // This is enforced in arguments.cpp. 1432 assert(MinHeapFreeRatio <= MaxHeapFreeRatio, 1433 "otherwise the code below doesn't make sense"); 1434 1435 // We don't have floating point command-line arguments 1436 const double minimum_free_percentage = (double) MinHeapFreeRatio / 100.0; 1437 const double maximum_used_percentage = 1.0 - minimum_free_percentage; 1438 const double maximum_free_percentage = (double) MaxHeapFreeRatio / 100.0; 1439 const double minimum_used_percentage = 1.0 - maximum_free_percentage; 1440 1441 const size_t min_heap_size = collector_policy()->min_heap_byte_size(); 1442 const size_t max_heap_size = collector_policy()->max_heap_byte_size(); 1443 1444 // We have to be careful here as these two calculations can overflow 1445 // 32-bit size_t's. 1446 double used_after_gc_d = (double) used_after_gc; 1447 double minimum_desired_capacity_d = used_after_gc_d / maximum_used_percentage; 1448 double maximum_desired_capacity_d = used_after_gc_d / minimum_used_percentage; 1449 1450 // Let's make sure that they are both under the max heap size, which 1451 // by default will make them fit into a size_t. 1452 double desired_capacity_upper_bound = (double) max_heap_size; 1453 minimum_desired_capacity_d = MIN2(minimum_desired_capacity_d, 1454 desired_capacity_upper_bound); 1455 maximum_desired_capacity_d = MIN2(maximum_desired_capacity_d, 1456 desired_capacity_upper_bound); 1457 1458 // We can now safely turn them into size_t's. 1459 size_t minimum_desired_capacity = (size_t) minimum_desired_capacity_d; 1460 size_t maximum_desired_capacity = (size_t) maximum_desired_capacity_d; 1461 1462 // This assert only makes sense here, before we adjust them 1463 // with respect to the min and max heap size. 1464 assert(minimum_desired_capacity <= maximum_desired_capacity, 1465 err_msg("minimum_desired_capacity = "SIZE_FORMAT", " 1466 "maximum_desired_capacity = "SIZE_FORMAT, 1467 minimum_desired_capacity, maximum_desired_capacity)); 1468 1469 // Should not be greater than the heap max size. No need to adjust 1470 // it with respect to the heap min size as it's a lower bound (i.e., 1471 // we'll try to make the capacity larger than it, not smaller). 1472 minimum_desired_capacity = MIN2(minimum_desired_capacity, max_heap_size); 1473 // Should not be less than the heap min size. No need to adjust it 1474 // with respect to the heap max size as it's an upper bound (i.e., 1475 // we'll try to make the capacity smaller than it, not greater). 1476 maximum_desired_capacity = MAX2(maximum_desired_capacity, min_heap_size); 1477 1478 if (PrintGC && Verbose) { 1479 const double free_percentage = 1480 (double) free_after_gc / (double) capacity_after_gc; 1481 gclog_or_tty->print_cr("Computing new size after full GC "); 1482 gclog_or_tty->print_cr(" " 1483 " minimum_free_percentage: %6.2f", 1484 minimum_free_percentage); 1485 gclog_or_tty->print_cr(" " 1486 " maximum_free_percentage: %6.2f", 1487 maximum_free_percentage); 1488 gclog_or_tty->print_cr(" " 1489 " capacity: %6.1fK" 1490 " minimum_desired_capacity: %6.1fK" 1491 " maximum_desired_capacity: %6.1fK", 1492 (double) capacity_after_gc / (double) K, 1493 (double) minimum_desired_capacity / (double) K, 1494 (double) maximum_desired_capacity / (double) K); 1495 gclog_or_tty->print_cr(" " 1496 " free_after_gc: %6.1fK" 1497 " used_after_gc: %6.1fK", 1498 (double) free_after_gc / (double) K, 1499 (double) used_after_gc / (double) K); 1500 gclog_or_tty->print_cr(" " 1501 " free_percentage: %6.2f", 1502 free_percentage); 1503 } 1504 if (capacity_after_gc < minimum_desired_capacity) { 1505 // Don't expand unless it's significant 1506 size_t expand_bytes = minimum_desired_capacity - capacity_after_gc; 1507 if (expand(expand_bytes)) { 1508 if (PrintGC && Verbose) { 1509 gclog_or_tty->print_cr(" " 1510 " expanding:" 1511 " max_heap_size: %6.1fK" 1512 " minimum_desired_capacity: %6.1fK" 1513 " expand_bytes: %6.1fK", 1514 (double) max_heap_size / (double) K, 1515 (double) minimum_desired_capacity / (double) K, 1516 (double) expand_bytes / (double) K); 1517 } 1518 } 1519 1520 // No expansion, now see if we want to shrink 1521 } else if (capacity_after_gc > maximum_desired_capacity) { 1522 // Capacity too large, compute shrinking size 1523 size_t shrink_bytes = capacity_after_gc - maximum_desired_capacity; 1524 shrink(shrink_bytes); 1525 if (PrintGC && Verbose) { 1526 gclog_or_tty->print_cr(" " 1527 " shrinking:" 1528 " min_heap_size: %6.1fK" 1529 " maximum_desired_capacity: %6.1fK" 1530 " shrink_bytes: %6.1fK", 1531 (double) min_heap_size / (double) K, 1532 (double) maximum_desired_capacity / (double) K, 1533 (double) shrink_bytes / (double) K); 1534 } 1535 } 1536 } 1537 1538 1539 HeapWord* 1540 G1CollectedHeap::satisfy_failed_allocation(size_t word_size, 1541 bool* succeeded) { 1542 assert_at_safepoint(true /* should_be_vm_thread */); 1543 1544 *succeeded = true; 1545 // Let's attempt the allocation first. 1546 HeapWord* result = 1547 attempt_allocation_at_safepoint(word_size, 1548 false /* expect_null_mutator_alloc_region */); 1549 if (result != NULL) { 1550 assert(*succeeded, "sanity"); 1551 return result; 1552 } 1553 1554 // In a G1 heap, we're supposed to keep allocation from failing by 1555 // incremental pauses. Therefore, at least for now, we'll favor 1556 // expansion over collection. (This might change in the future if we can 1557 // do something smarter than full collection to satisfy a failed alloc.) 1558 result = expand_and_allocate(word_size); 1559 if (result != NULL) { 1560 assert(*succeeded, "sanity"); 1561 return result; 1562 } 1563 1564 // Expansion didn't work, we'll try to do a Full GC. 1565 bool gc_succeeded = do_collection(false, /* explicit_gc */ 1566 false, /* clear_all_soft_refs */ 1567 word_size); 1568 if (!gc_succeeded) { 1569 *succeeded = false; 1570 return NULL; 1571 } 1572 1573 // Retry the allocation 1574 result = attempt_allocation_at_safepoint(word_size, 1575 true /* expect_null_mutator_alloc_region */); 1576 if (result != NULL) { 1577 assert(*succeeded, "sanity"); 1578 return result; 1579 } 1580 1581 // Then, try a Full GC that will collect all soft references. 1582 gc_succeeded = do_collection(false, /* explicit_gc */ 1583 true, /* clear_all_soft_refs */ 1584 word_size); 1585 if (!gc_succeeded) { 1586 *succeeded = false; 1587 return NULL; 1588 } 1589 1590 // Retry the allocation once more 1591 result = attempt_allocation_at_safepoint(word_size, 1592 true /* expect_null_mutator_alloc_region */); 1593 if (result != NULL) { 1594 assert(*succeeded, "sanity"); 1595 return result; 1596 } 1597 1598 assert(!collector_policy()->should_clear_all_soft_refs(), 1599 "Flag should have been handled and cleared prior to this point"); 1600 1601 // What else? We might try synchronous finalization later. If the total 1602 // space available is large enough for the allocation, then a more 1603 // complete compaction phase than we've tried so far might be 1604 // appropriate. 1605 assert(*succeeded, "sanity"); 1606 return NULL; 1607 } 1608 1609 // Attempting to expand the heap sufficiently 1610 // to support an allocation of the given "word_size". If 1611 // successful, perform the allocation and return the address of the 1612 // allocated block, or else "NULL". 1613 1614 HeapWord* G1CollectedHeap::expand_and_allocate(size_t word_size) { 1615 assert_at_safepoint(true /* should_be_vm_thread */); 1616 1617 verify_region_sets_optional(); 1618 1619 size_t expand_bytes = MAX2(word_size * HeapWordSize, MinHeapDeltaBytes); 1620 if (expand(expand_bytes)) { 1621 _hrs.verify_optional(); 1622 verify_region_sets_optional(); 1623 return attempt_allocation_at_safepoint(word_size, 1624 false /* expect_null_mutator_alloc_region */); 1625 } 1626 return NULL; 1627 } 1628 1629 void G1CollectedHeap::update_committed_space(HeapWord* old_end, 1630 HeapWord* new_end) { 1631 assert(old_end != new_end, "don't call this otherwise"); 1632 assert((HeapWord*) _g1_storage.high() == new_end, "invariant"); 1633 1634 // Update the committed mem region. 1635 _g1_committed.set_end(new_end); 1636 // Tell the card table about the update. 1637 Universe::heap()->barrier_set()->resize_covered_region(_g1_committed); 1638 // Tell the BOT about the update. 1639 _bot_shared->resize(_g1_committed.word_size()); 1640 } 1641 1642 bool G1CollectedHeap::expand(size_t expand_bytes) { 1643 size_t old_mem_size = _g1_storage.committed_size(); 1644 size_t aligned_expand_bytes = ReservedSpace::page_align_size_up(expand_bytes); 1645 aligned_expand_bytes = align_size_up(aligned_expand_bytes, 1646 HeapRegion::GrainBytes); 1647 1648 if (Verbose && PrintGC) { 1649 gclog_or_tty->print("Expanding garbage-first heap from %ldK by %ldK", 1650 old_mem_size/K, aligned_expand_bytes/K); 1651 } 1652 1653 // First commit the memory. 1654 HeapWord* old_end = (HeapWord*) _g1_storage.high(); 1655 bool successful = _g1_storage.expand_by(aligned_expand_bytes); 1656 if (successful) { 1657 // Then propagate this update to the necessary data structures. 1658 HeapWord* new_end = (HeapWord*) _g1_storage.high(); 1659 update_committed_space(old_end, new_end); 1660 1661 FreeRegionList expansion_list("Local Expansion List"); 1662 MemRegion mr = _hrs.expand_by(old_end, new_end, &expansion_list); 1663 assert(mr.start() == old_end, "post-condition"); 1664 // mr might be a smaller region than what was requested if 1665 // expand_by() was unable to allocate the HeapRegion instances 1666 assert(mr.end() <= new_end, "post-condition"); 1667 1668 size_t actual_expand_bytes = mr.byte_size(); 1669 assert(actual_expand_bytes <= aligned_expand_bytes, "post-condition"); 1670 assert(actual_expand_bytes == expansion_list.total_capacity_bytes(), 1671 "post-condition"); 1672 if (actual_expand_bytes < aligned_expand_bytes) { 1673 // We could not expand _hrs to the desired size. In this case we 1674 // need to shrink the committed space accordingly. 1675 assert(mr.end() < new_end, "invariant"); 1676 1677 size_t diff_bytes = aligned_expand_bytes - actual_expand_bytes; 1678 // First uncommit the memory. 1679 _g1_storage.shrink_by(diff_bytes); 1680 // Then propagate this update to the necessary data structures. 1681 update_committed_space(new_end, mr.end()); 1682 } 1683 _free_list.add_as_tail(&expansion_list); 1684 1685 if (_hr_printer.is_active()) { 1686 HeapWord* curr = mr.start(); 1687 while (curr < mr.end()) { 1688 HeapWord* curr_end = curr + HeapRegion::GrainWords; 1689 _hr_printer.commit(curr, curr_end); 1690 curr = curr_end; 1691 } 1692 assert(curr == mr.end(), "post-condition"); 1693 } 1694 } else { 1695 // The expansion of the virtual storage space was unsuccessful. 1696 // Let's see if it was because we ran out of swap. 1697 if (G1ExitOnExpansionFailure && 1698 _g1_storage.uncommitted_size() >= aligned_expand_bytes) { 1699 // We had head room... 1700 vm_exit_out_of_memory(aligned_expand_bytes, "G1 heap expansion"); 1701 } 1702 } 1703 1704 if (Verbose && PrintGC) { 1705 size_t new_mem_size = _g1_storage.committed_size(); 1706 gclog_or_tty->print_cr("...%s, expanded to %ldK", 1707 (successful ? "Successful" : "Failed"), 1708 new_mem_size/K); 1709 } 1710 return successful; 1711 } 1712 1713 void G1CollectedHeap::shrink_helper(size_t shrink_bytes) { 1714 size_t old_mem_size = _g1_storage.committed_size(); 1715 size_t aligned_shrink_bytes = 1716 ReservedSpace::page_align_size_down(shrink_bytes); 1717 aligned_shrink_bytes = align_size_down(aligned_shrink_bytes, 1718 HeapRegion::GrainBytes); 1719 size_t num_regions_deleted = 0; 1720 MemRegion mr = _hrs.shrink_by(aligned_shrink_bytes, &num_regions_deleted); 1721 HeapWord* old_end = (HeapWord*) _g1_storage.high(); 1722 assert(mr.end() == old_end, "post-condition"); 1723 if (mr.byte_size() > 0) { 1724 if (_hr_printer.is_active()) { 1725 HeapWord* curr = mr.end(); 1726 while (curr > mr.start()) { 1727 HeapWord* curr_end = curr; 1728 curr -= HeapRegion::GrainWords; 1729 _hr_printer.uncommit(curr, curr_end); 1730 } 1731 assert(curr == mr.start(), "post-condition"); 1732 } 1733 1734 _g1_storage.shrink_by(mr.byte_size()); 1735 HeapWord* new_end = (HeapWord*) _g1_storage.high(); 1736 assert(mr.start() == new_end, "post-condition"); 1737 1738 _expansion_regions += num_regions_deleted; 1739 update_committed_space(old_end, new_end); 1740 HeapRegionRemSet::shrink_heap(n_regions()); 1741 1742 if (Verbose && PrintGC) { 1743 size_t new_mem_size = _g1_storage.committed_size(); 1744 gclog_or_tty->print_cr("Shrinking garbage-first heap from %ldK by %ldK to %ldK", 1745 old_mem_size/K, aligned_shrink_bytes/K, 1746 new_mem_size/K); 1747 } 1748 } 1749 } 1750 1751 void G1CollectedHeap::shrink(size_t shrink_bytes) { 1752 verify_region_sets_optional(); 1753 1754 // We should only reach here at the end of a Full GC which means we 1755 // should not not be holding to any GC alloc regions. The method 1756 // below will make sure of that and do any remaining clean up. 1757 abandon_gc_alloc_regions(); 1758 1759 // Instead of tearing down / rebuilding the free lists here, we 1760 // could instead use the remove_all_pending() method on free_list to 1761 // remove only the ones that we need to remove. 1762 tear_down_region_lists(); // We will rebuild them in a moment. 1763 shrink_helper(shrink_bytes); 1764 rebuild_region_lists(); 1765 1766 _hrs.verify_optional(); 1767 verify_region_sets_optional(); 1768 } 1769 1770 // Public methods. 1771 1772 #ifdef _MSC_VER // the use of 'this' below gets a warning, make it go away 1773 #pragma warning( disable:4355 ) // 'this' : used in base member initializer list 1774 #endif // _MSC_VER 1775 1776 1777 G1CollectedHeap::G1CollectedHeap(G1CollectorPolicy* policy_) : 1778 SharedHeap(policy_), 1779 _g1_policy(policy_), 1780 _dirty_card_queue_set(false), 1781 _into_cset_dirty_card_queue_set(false), 1782 _is_alive_closure(this), 1783 _ref_processor(NULL), 1784 _process_strong_tasks(new SubTasksDone(G1H_PS_NumElements)), 1785 _bot_shared(NULL), 1786 _objs_with_preserved_marks(NULL), _preserved_marks_of_objs(NULL), 1787 _evac_failure_scan_stack(NULL) , 1788 _mark_in_progress(false), 1789 _cg1r(NULL), _summary_bytes_used(0), 1790 _refine_cte_cl(NULL), 1791 _full_collection(false), 1792 _free_list("Master Free List"), 1793 _secondary_free_list("Secondary Free List"), 1794 _humongous_set("Master Humongous Set"), 1795 _free_regions_coming(false), 1796 _young_list(new YoungList(this)), 1797 _gc_time_stamp(0), 1798 _retained_old_gc_alloc_region(NULL), 1799 _surviving_young_words(NULL), 1800 _full_collections_completed(0), 1801 _in_cset_fast_test(NULL), 1802 _in_cset_fast_test_base(NULL), 1803 _dirty_cards_region_list(NULL) { 1804 _g1h = this; // To catch bugs. 1805 if (_process_strong_tasks == NULL || !_process_strong_tasks->valid()) { 1806 vm_exit_during_initialization("Failed necessary allocation."); 1807 } 1808 1809 _humongous_object_threshold_in_words = HeapRegion::GrainWords / 2; 1810 1811 int n_queues = MAX2((int)ParallelGCThreads, 1); 1812 _task_queues = new RefToScanQueueSet(n_queues); 1813 1814 int n_rem_sets = HeapRegionRemSet::num_par_rem_sets(); 1815 assert(n_rem_sets > 0, "Invariant."); 1816 1817 HeapRegionRemSetIterator** iter_arr = 1818 NEW_C_HEAP_ARRAY(HeapRegionRemSetIterator*, n_queues); 1819 for (int i = 0; i < n_queues; i++) { 1820 iter_arr[i] = new HeapRegionRemSetIterator(); 1821 } 1822 _rem_set_iterator = iter_arr; 1823 1824 for (int i = 0; i < n_queues; i++) { 1825 RefToScanQueue* q = new RefToScanQueue(); 1826 q->initialize(); 1827 _task_queues->register_queue(i, q); 1828 } 1829 1830 guarantee(_task_queues != NULL, "task_queues allocation failure."); 1831 } 1832 1833 jint G1CollectedHeap::initialize() { 1834 CollectedHeap::pre_initialize(); 1835 os::enable_vtime(); 1836 1837 // Necessary to satisfy locking discipline assertions. 1838 1839 MutexLocker x(Heap_lock); 1840 1841 // We have to initialize the printer before committing the heap, as 1842 // it will be used then. 1843 _hr_printer.set_active(G1PrintHeapRegions); 1844 1845 // While there are no constraints in the GC code that HeapWordSize 1846 // be any particular value, there are multiple other areas in the 1847 // system which believe this to be true (e.g. oop->object_size in some 1848 // cases incorrectly returns the size in wordSize units rather than 1849 // HeapWordSize). 1850 guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize"); 1851 1852 size_t init_byte_size = collector_policy()->initial_heap_byte_size(); 1853 size_t max_byte_size = collector_policy()->max_heap_byte_size(); 1854 1855 // Ensure that the sizes are properly aligned. 1856 Universe::check_alignment(init_byte_size, HeapRegion::GrainBytes, "g1 heap"); 1857 Universe::check_alignment(max_byte_size, HeapRegion::GrainBytes, "g1 heap"); 1858 1859 _cg1r = new ConcurrentG1Refine(); 1860 1861 // Reserve the maximum. 1862 PermanentGenerationSpec* pgs = collector_policy()->permanent_generation(); 1863 // Includes the perm-gen. 1864 1865 // When compressed oops are enabled, the preferred heap base 1866 // is calculated by subtracting the requested size from the 1867 // 32Gb boundary and using the result as the base address for 1868 // heap reservation. If the requested size is not aligned to 1869 // HeapRegion::GrainBytes (i.e. the alignment that is passed 1870 // into the ReservedHeapSpace constructor) then the actual 1871 // base of the reserved heap may end up differing from the 1872 // address that was requested (i.e. the preferred heap base). 1873 // If this happens then we could end up using a non-optimal 1874 // compressed oops mode. 1875 1876 // Since max_byte_size is aligned to the size of a heap region (checked 1877 // above), we also need to align the perm gen size as it might not be. 1878 const size_t total_reserved = max_byte_size + 1879 align_size_up(pgs->max_size(), HeapRegion::GrainBytes); 1880 Universe::check_alignment(total_reserved, HeapRegion::GrainBytes, "g1 heap and perm"); 1881 1882 char* addr = Universe::preferred_heap_base(total_reserved, Universe::UnscaledNarrowOop); 1883 1884 ReservedHeapSpace heap_rs(total_reserved, HeapRegion::GrainBytes, 1885 UseLargePages, addr); 1886 1887 if (UseCompressedOops) { 1888 if (addr != NULL && !heap_rs.is_reserved()) { 1889 // Failed to reserve at specified address - the requested memory 1890 // region is taken already, for example, by 'java' launcher. 1891 // Try again to reserver heap higher. 1892 addr = Universe::preferred_heap_base(total_reserved, Universe::ZeroBasedNarrowOop); 1893 1894 ReservedHeapSpace heap_rs0(total_reserved, HeapRegion::GrainBytes, 1895 UseLargePages, addr); 1896 1897 if (addr != NULL && !heap_rs0.is_reserved()) { 1898 // Failed to reserve at specified address again - give up. 1899 addr = Universe::preferred_heap_base(total_reserved, Universe::HeapBasedNarrowOop); 1900 assert(addr == NULL, ""); 1901 1902 ReservedHeapSpace heap_rs1(total_reserved, HeapRegion::GrainBytes, 1903 UseLargePages, addr); 1904 heap_rs = heap_rs1; 1905 } else { 1906 heap_rs = heap_rs0; 1907 } 1908 } 1909 } 1910 1911 if (!heap_rs.is_reserved()) { 1912 vm_exit_during_initialization("Could not reserve enough space for object heap"); 1913 return JNI_ENOMEM; 1914 } 1915 1916 // It is important to do this in a way such that concurrent readers can't 1917 // temporarily think somethings in the heap. (I've actually seen this 1918 // happen in asserts: DLD.) 1919 _reserved.set_word_size(0); 1920 _reserved.set_start((HeapWord*)heap_rs.base()); 1921 _reserved.set_end((HeapWord*)(heap_rs.base() + heap_rs.size())); 1922 1923 _expansion_regions = max_byte_size/HeapRegion::GrainBytes; 1924 1925 // Create the gen rem set (and barrier set) for the entire reserved region. 1926 _rem_set = collector_policy()->create_rem_set(_reserved, 2); 1927 set_barrier_set(rem_set()->bs()); 1928 if (barrier_set()->is_a(BarrierSet::ModRef)) { 1929 _mr_bs = (ModRefBarrierSet*)_barrier_set; 1930 } else { 1931 vm_exit_during_initialization("G1 requires a mod ref bs."); 1932 return JNI_ENOMEM; 1933 } 1934 1935 // Also create a G1 rem set. 1936 if (mr_bs()->is_a(BarrierSet::CardTableModRef)) { 1937 _g1_rem_set = new G1RemSet(this, (CardTableModRefBS*)mr_bs()); 1938 } else { 1939 vm_exit_during_initialization("G1 requires a cardtable mod ref bs."); 1940 return JNI_ENOMEM; 1941 } 1942 1943 // Carve out the G1 part of the heap. 1944 1945 ReservedSpace g1_rs = heap_rs.first_part(max_byte_size); 1946 _g1_reserved = MemRegion((HeapWord*)g1_rs.base(), 1947 g1_rs.size()/HeapWordSize); 1948 ReservedSpace perm_gen_rs = heap_rs.last_part(max_byte_size); 1949 1950 _perm_gen = pgs->init(perm_gen_rs, pgs->init_size(), rem_set()); 1951 1952 _g1_storage.initialize(g1_rs, 0); 1953 _g1_committed = MemRegion((HeapWord*)_g1_storage.low(), (size_t) 0); 1954 _hrs.initialize((HeapWord*) _g1_reserved.start(), 1955 (HeapWord*) _g1_reserved.end(), 1956 _expansion_regions); 1957 1958 // 6843694 - ensure that the maximum region index can fit 1959 // in the remembered set structures. 1960 const size_t max_region_idx = ((size_t)1 << (sizeof(RegionIdx_t)*BitsPerByte-1)) - 1; 1961 guarantee((max_regions() - 1) <= max_region_idx, "too many regions"); 1962 1963 size_t max_cards_per_region = ((size_t)1 << (sizeof(CardIdx_t)*BitsPerByte-1)) - 1; 1964 guarantee(HeapRegion::CardsPerRegion > 0, "make sure it's initialized"); 1965 guarantee((size_t) HeapRegion::CardsPerRegion < max_cards_per_region, 1966 "too many cards per region"); 1967 1968 HeapRegionSet::set_unrealistically_long_length(max_regions() + 1); 1969 1970 _bot_shared = new G1BlockOffsetSharedArray(_reserved, 1971 heap_word_size(init_byte_size)); 1972 1973 _g1h = this; 1974 1975 _in_cset_fast_test_length = max_regions(); 1976 _in_cset_fast_test_base = NEW_C_HEAP_ARRAY(bool, _in_cset_fast_test_length); 1977 1978 // We're biasing _in_cset_fast_test to avoid subtracting the 1979 // beginning of the heap every time we want to index; basically 1980 // it's the same with what we do with the card table. 1981 _in_cset_fast_test = _in_cset_fast_test_base - 1982 ((size_t) _g1_reserved.start() >> HeapRegion::LogOfHRGrainBytes); 1983 1984 // Clear the _cset_fast_test bitmap in anticipation of adding 1985 // regions to the incremental collection set for the first 1986 // evacuation pause. 1987 clear_cset_fast_test(); 1988 1989 // Create the ConcurrentMark data structure and thread. 1990 // (Must do this late, so that "max_regions" is defined.) 1991 _cm = new ConcurrentMark(heap_rs, (int) max_regions()); 1992 _cmThread = _cm->cmThread(); 1993 1994 // Initialize the from_card cache structure of HeapRegionRemSet. 1995 HeapRegionRemSet::init_heap(max_regions()); 1996 1997 // Now expand into the initial heap size. 1998 if (!expand(init_byte_size)) { 1999 vm_exit_during_initialization("Failed to allocate initial heap."); 2000 return JNI_ENOMEM; 2001 } 2002 2003 // Perform any initialization actions delegated to the policy. 2004 g1_policy()->init(); 2005 2006 g1_policy()->note_start_of_mark_thread(); 2007 2008 _refine_cte_cl = 2009 new RefineCardTableEntryClosure(ConcurrentG1RefineThread::sts(), 2010 g1_rem_set(), 2011 concurrent_g1_refine()); 2012 JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl); 2013 2014 JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon, 2015 SATB_Q_FL_lock, 2016 G1SATBProcessCompletedThreshold, 2017 Shared_SATB_Q_lock); 2018 2019 JavaThread::dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon, 2020 DirtyCardQ_FL_lock, 2021 concurrent_g1_refine()->yellow_zone(), 2022 concurrent_g1_refine()->red_zone(), 2023 Shared_DirtyCardQ_lock); 2024 2025 if (G1DeferredRSUpdate) { 2026 dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon, 2027 DirtyCardQ_FL_lock, 2028 -1, // never trigger processing 2029 -1, // no limit on length 2030 Shared_DirtyCardQ_lock, 2031 &JavaThread::dirty_card_queue_set()); 2032 } 2033 2034 // Initialize the card queue set used to hold cards containing 2035 // references into the collection set. 2036 _into_cset_dirty_card_queue_set.initialize(DirtyCardQ_CBL_mon, 2037 DirtyCardQ_FL_lock, 2038 -1, // never trigger processing 2039 -1, // no limit on length 2040 Shared_DirtyCardQ_lock, 2041 &JavaThread::dirty_card_queue_set()); 2042 2043 // In case we're keeping closure specialization stats, initialize those 2044 // counts and that mechanism. 2045 SpecializationStats::clear(); 2046 2047 // Do later initialization work for concurrent refinement. 2048 _cg1r->init(); 2049 2050 // Here we allocate the dummy full region that is required by the 2051 // G1AllocRegion class. If we don't pass an address in the reserved 2052 // space here, lots of asserts fire. 2053 2054 HeapRegion* dummy_region = new_heap_region(0 /* index of bottom region */, 2055 _g1_reserved.start()); 2056 // We'll re-use the same region whether the alloc region will 2057 // require BOT updates or not and, if it doesn't, then a non-young 2058 // region will complain that it cannot support allocations without 2059 // BOT updates. So we'll tag the dummy region as young to avoid that. 2060 dummy_region->set_young(); 2061 // Make sure it's full. 2062 dummy_region->set_top(dummy_region->end()); 2063 G1AllocRegion::setup(this, dummy_region); 2064 2065 init_mutator_alloc_region(); 2066 2067 // Do create of the monitoring and management support so that 2068 // values in the heap have been properly initialized. 2069 _g1mm = new G1MonitoringSupport(this, &_g1_storage); 2070 2071 return JNI_OK; 2072 } 2073 2074 void G1CollectedHeap::ref_processing_init() { 2075 // Reference processing in G1 currently works as follows: 2076 // 2077 // * There is only one reference processor instance that 2078 // 'spans' the entire heap. It is created by the code 2079 // below. 2080 // * Reference discovery is not enabled during an incremental 2081 // pause (see 6484982). 2082 // * Discoverered refs are not enqueued nor are they processed 2083 // during an incremental pause (see 6484982). 2084 // * Reference discovery is enabled at initial marking. 2085 // * Reference discovery is disabled and the discovered 2086 // references processed etc during remarking. 2087 // * Reference discovery is MT (see below). 2088 // * Reference discovery requires a barrier (see below). 2089 // * Reference processing is currently not MT (see 6608385). 2090 // * A full GC enables (non-MT) reference discovery and 2091 // processes any discovered references. 2092 2093 SharedHeap::ref_processing_init(); 2094 MemRegion mr = reserved_region(); 2095 _ref_processor = 2096 new ReferenceProcessor(mr, // span 2097 ParallelRefProcEnabled && (ParallelGCThreads > 1), // mt processing 2098 (int) ParallelGCThreads, // degree of mt processing 2099 ParallelGCThreads > 1 || ConcGCThreads > 1, // mt discovery 2100 (int) MAX2(ParallelGCThreads, ConcGCThreads), // degree of mt discovery 2101 false, // Reference discovery is not atomic 2102 &_is_alive_closure, // is alive closure for efficiency 2103 true); // Setting next fields of discovered 2104 // lists requires a barrier. 2105 } 2106 2107 size_t G1CollectedHeap::capacity() const { 2108 return _g1_committed.byte_size(); 2109 } 2110 2111 void G1CollectedHeap::iterate_dirty_card_closure(CardTableEntryClosure* cl, 2112 DirtyCardQueue* into_cset_dcq, 2113 bool concurrent, 2114 int worker_i) { 2115 // Clean cards in the hot card cache 2116 concurrent_g1_refine()->clean_up_cache(worker_i, g1_rem_set(), into_cset_dcq); 2117 2118 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set(); 2119 int n_completed_buffers = 0; 2120 while (dcqs.apply_closure_to_completed_buffer(cl, worker_i, 0, true)) { 2121 n_completed_buffers++; 2122 } 2123 g1_policy()->record_update_rs_processed_buffers(worker_i, 2124 (double) n_completed_buffers); 2125 dcqs.clear_n_completed_buffers(); 2126 assert(!dcqs.completed_buffers_exist_dirty(), "Completed buffers exist!"); 2127 } 2128 2129 2130 // Computes the sum of the storage used by the various regions. 2131 2132 size_t G1CollectedHeap::used() const { 2133 assert(Heap_lock->owner() != NULL, 2134 "Should be owned on this thread's behalf."); 2135 size_t result = _summary_bytes_used; 2136 // Read only once in case it is set to NULL concurrently 2137 HeapRegion* hr = _mutator_alloc_region.get(); 2138 if (hr != NULL) 2139 result += hr->used(); 2140 return result; 2141 } 2142 2143 size_t G1CollectedHeap::used_unlocked() const { 2144 size_t result = _summary_bytes_used; 2145 return result; 2146 } 2147 2148 class SumUsedClosure: public HeapRegionClosure { 2149 size_t _used; 2150 public: 2151 SumUsedClosure() : _used(0) {} 2152 bool doHeapRegion(HeapRegion* r) { 2153 if (!r->continuesHumongous()) { 2154 _used += r->used(); 2155 } 2156 return false; 2157 } 2158 size_t result() { return _used; } 2159 }; 2160 2161 size_t G1CollectedHeap::recalculate_used() const { 2162 SumUsedClosure blk; 2163 heap_region_iterate(&blk); 2164 return blk.result(); 2165 } 2166 2167 size_t G1CollectedHeap::unsafe_max_alloc() { 2168 if (free_regions() > 0) return HeapRegion::GrainBytes; 2169 // otherwise, is there space in the current allocation region? 2170 2171 // We need to store the current allocation region in a local variable 2172 // here. The problem is that this method doesn't take any locks and 2173 // there may be other threads which overwrite the current allocation 2174 // region field. attempt_allocation(), for example, sets it to NULL 2175 // and this can happen *after* the NULL check here but before the call 2176 // to free(), resulting in a SIGSEGV. Note that this doesn't appear 2177 // to be a problem in the optimized build, since the two loads of the 2178 // current allocation region field are optimized away. 2179 HeapRegion* hr = _mutator_alloc_region.get(); 2180 if (hr == NULL) { 2181 return 0; 2182 } 2183 return hr->free(); 2184 } 2185 2186 bool G1CollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) { 2187 return 2188 ((cause == GCCause::_gc_locker && GCLockerInvokesConcurrent) || 2189 (cause == GCCause::_java_lang_system_gc && ExplicitGCInvokesConcurrent)); 2190 } 2191 2192 #ifndef PRODUCT 2193 void G1CollectedHeap::allocate_dummy_regions() { 2194 // Let's fill up most of the region 2195 size_t word_size = HeapRegion::GrainWords - 1024; 2196 // And as a result the region we'll allocate will be humongous. 2197 guarantee(isHumongous(word_size), "sanity"); 2198 2199 for (uintx i = 0; i < G1DummyRegionsPerGC; ++i) { 2200 // Let's use the existing mechanism for the allocation 2201 HeapWord* dummy_obj = humongous_obj_allocate(word_size); 2202 if (dummy_obj != NULL) { 2203 MemRegion mr(dummy_obj, word_size); 2204 CollectedHeap::fill_with_object(mr); 2205 } else { 2206 // If we can't allocate once, we probably cannot allocate 2207 // again. Let's get out of the loop. 2208 break; 2209 } 2210 } 2211 } 2212 #endif // !PRODUCT 2213 2214 void G1CollectedHeap::increment_full_collections_completed(bool concurrent) { 2215 MonitorLockerEx x(FullGCCount_lock, Mutex::_no_safepoint_check_flag); 2216 2217 // We assume that if concurrent == true, then the caller is a 2218 // concurrent thread that was joined the Suspendible Thread 2219 // Set. If there's ever a cheap way to check this, we should add an 2220 // assert here. 2221 2222 // We have already incremented _total_full_collections at the start 2223 // of the GC, so total_full_collections() represents how many full 2224 // collections have been started. 2225 unsigned int full_collections_started = total_full_collections(); 2226 2227 // Given that this method is called at the end of a Full GC or of a 2228 // concurrent cycle, and those can be nested (i.e., a Full GC can 2229 // interrupt a concurrent cycle), the number of full collections 2230 // completed should be either one (in the case where there was no 2231 // nesting) or two (when a Full GC interrupted a concurrent cycle) 2232 // behind the number of full collections started. 2233 2234 // This is the case for the inner caller, i.e. a Full GC. 2235 assert(concurrent || 2236 (full_collections_started == _full_collections_completed + 1) || 2237 (full_collections_started == _full_collections_completed + 2), 2238 err_msg("for inner caller (Full GC): full_collections_started = %u " 2239 "is inconsistent with _full_collections_completed = %u", 2240 full_collections_started, _full_collections_completed)); 2241 2242 // This is the case for the outer caller, i.e. the concurrent cycle. 2243 assert(!concurrent || 2244 (full_collections_started == _full_collections_completed + 1), 2245 err_msg("for outer caller (concurrent cycle): " 2246 "full_collections_started = %u " 2247 "is inconsistent with _full_collections_completed = %u", 2248 full_collections_started, _full_collections_completed)); 2249 2250 _full_collections_completed += 1; 2251 2252 // We need to clear the "in_progress" flag in the CM thread before 2253 // we wake up any waiters (especially when ExplicitInvokesConcurrent 2254 // is set) so that if a waiter requests another System.gc() it doesn't 2255 // incorrectly see that a marking cyle is still in progress. 2256 if (concurrent) { 2257 _cmThread->clear_in_progress(); 2258 } 2259 2260 // This notify_all() will ensure that a thread that called 2261 // System.gc() with (with ExplicitGCInvokesConcurrent set or not) 2262 // and it's waiting for a full GC to finish will be woken up. It is 2263 // waiting in VM_G1IncCollectionPause::doit_epilogue(). 2264 FullGCCount_lock->notify_all(); 2265 } 2266 2267 void G1CollectedHeap::collect_as_vm_thread(GCCause::Cause cause) { 2268 assert_at_safepoint(true /* should_be_vm_thread */); 2269 GCCauseSetter gcs(this, cause); 2270 switch (cause) { 2271 case GCCause::_heap_inspection: 2272 case GCCause::_heap_dump: { 2273 HandleMark hm; 2274 do_full_collection(false); // don't clear all soft refs 2275 break; 2276 } 2277 default: // XXX FIX ME 2278 ShouldNotReachHere(); // Unexpected use of this function 2279 } 2280 } 2281 2282 void G1CollectedHeap::collect(GCCause::Cause cause) { 2283 // The caller doesn't have the Heap_lock 2284 assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock"); 2285 2286 unsigned int gc_count_before; 2287 unsigned int full_gc_count_before; 2288 { 2289 MutexLocker ml(Heap_lock); 2290 2291 // Read the GC count while holding the Heap_lock 2292 gc_count_before = SharedHeap::heap()->total_collections(); 2293 full_gc_count_before = SharedHeap::heap()->total_full_collections(); 2294 } 2295 2296 if (should_do_concurrent_full_gc(cause)) { 2297 // Schedule an initial-mark evacuation pause that will start a 2298 // concurrent cycle. We're setting word_size to 0 which means that 2299 // we are not requesting a post-GC allocation. 2300 VM_G1IncCollectionPause op(gc_count_before, 2301 0, /* word_size */ 2302 true, /* should_initiate_conc_mark */ 2303 g1_policy()->max_pause_time_ms(), 2304 cause); 2305 VMThread::execute(&op); 2306 } else { 2307 if (cause == GCCause::_gc_locker 2308 DEBUG_ONLY(|| cause == GCCause::_scavenge_alot)) { 2309 2310 // Schedule a standard evacuation pause. We're setting word_size 2311 // to 0 which means that we are not requesting a post-GC allocation. 2312 VM_G1IncCollectionPause op(gc_count_before, 2313 0, /* word_size */ 2314 false, /* should_initiate_conc_mark */ 2315 g1_policy()->max_pause_time_ms(), 2316 cause); 2317 VMThread::execute(&op); 2318 } else { 2319 // Schedule a Full GC. 2320 VM_G1CollectFull op(gc_count_before, full_gc_count_before, cause); 2321 VMThread::execute(&op); 2322 } 2323 } 2324 } 2325 2326 bool G1CollectedHeap::is_in(const void* p) const { 2327 HeapRegion* hr = _hrs.addr_to_region((HeapWord*) p); 2328 if (hr != NULL) { 2329 return hr->is_in(p); 2330 } else { 2331 return _perm_gen->as_gen()->is_in(p); 2332 } 2333 } 2334 2335 // Iteration functions. 2336 2337 // Iterates an OopClosure over all ref-containing fields of objects 2338 // within a HeapRegion. 2339 2340 class IterateOopClosureRegionClosure: public HeapRegionClosure { 2341 MemRegion _mr; 2342 OopClosure* _cl; 2343 public: 2344 IterateOopClosureRegionClosure(MemRegion mr, OopClosure* cl) 2345 : _mr(mr), _cl(cl) {} 2346 bool doHeapRegion(HeapRegion* r) { 2347 if (! r->continuesHumongous()) { 2348 r->oop_iterate(_cl); 2349 } 2350 return false; 2351 } 2352 }; 2353 2354 void G1CollectedHeap::oop_iterate(OopClosure* cl, bool do_perm) { 2355 IterateOopClosureRegionClosure blk(_g1_committed, cl); 2356 heap_region_iterate(&blk); 2357 if (do_perm) { 2358 perm_gen()->oop_iterate(cl); 2359 } 2360 } 2361 2362 void G1CollectedHeap::oop_iterate(MemRegion mr, OopClosure* cl, bool do_perm) { 2363 IterateOopClosureRegionClosure blk(mr, cl); 2364 heap_region_iterate(&blk); 2365 if (do_perm) { 2366 perm_gen()->oop_iterate(cl); 2367 } 2368 } 2369 2370 // Iterates an ObjectClosure over all objects within a HeapRegion. 2371 2372 class IterateObjectClosureRegionClosure: public HeapRegionClosure { 2373 ObjectClosure* _cl; 2374 public: 2375 IterateObjectClosureRegionClosure(ObjectClosure* cl) : _cl(cl) {} 2376 bool doHeapRegion(HeapRegion* r) { 2377 if (! r->continuesHumongous()) { 2378 r->object_iterate(_cl); 2379 } 2380 return false; 2381 } 2382 }; 2383 2384 void G1CollectedHeap::object_iterate(ObjectClosure* cl, bool do_perm) { 2385 IterateObjectClosureRegionClosure blk(cl); 2386 heap_region_iterate(&blk); 2387 if (do_perm) { 2388 perm_gen()->object_iterate(cl); 2389 } 2390 } 2391 2392 void G1CollectedHeap::object_iterate_since_last_GC(ObjectClosure* cl) { 2393 // FIXME: is this right? 2394 guarantee(false, "object_iterate_since_last_GC not supported by G1 heap"); 2395 } 2396 2397 // Calls a SpaceClosure on a HeapRegion. 2398 2399 class SpaceClosureRegionClosure: public HeapRegionClosure { 2400 SpaceClosure* _cl; 2401 public: 2402 SpaceClosureRegionClosure(SpaceClosure* cl) : _cl(cl) {} 2403 bool doHeapRegion(HeapRegion* r) { 2404 _cl->do_space(r); 2405 return false; 2406 } 2407 }; 2408 2409 void G1CollectedHeap::space_iterate(SpaceClosure* cl) { 2410 SpaceClosureRegionClosure blk(cl); 2411 heap_region_iterate(&blk); 2412 } 2413 2414 void G1CollectedHeap::heap_region_iterate(HeapRegionClosure* cl) const { 2415 _hrs.iterate(cl); 2416 } 2417 2418 void G1CollectedHeap::heap_region_iterate_from(HeapRegion* r, 2419 HeapRegionClosure* cl) const { 2420 _hrs.iterate_from(r, cl); 2421 } 2422 2423 void 2424 G1CollectedHeap::heap_region_par_iterate_chunked(HeapRegionClosure* cl, 2425 int worker, 2426 jint claim_value) { 2427 const size_t regions = n_regions(); 2428 const size_t worker_num = (G1CollectedHeap::use_parallel_gc_threads() ? ParallelGCThreads : 1); 2429 // try to spread out the starting points of the workers 2430 const size_t start_index = regions / worker_num * (size_t) worker; 2431 2432 // each worker will actually look at all regions 2433 for (size_t count = 0; count < regions; ++count) { 2434 const size_t index = (start_index + count) % regions; 2435 assert(0 <= index && index < regions, "sanity"); 2436 HeapRegion* r = region_at(index); 2437 // we'll ignore "continues humongous" regions (we'll process them 2438 // when we come across their corresponding "start humongous" 2439 // region) and regions already claimed 2440 if (r->claim_value() == claim_value || r->continuesHumongous()) { 2441 continue; 2442 } 2443 // OK, try to claim it 2444 if (r->claimHeapRegion(claim_value)) { 2445 // success! 2446 assert(!r->continuesHumongous(), "sanity"); 2447 if (r->startsHumongous()) { 2448 // If the region is "starts humongous" we'll iterate over its 2449 // "continues humongous" first; in fact we'll do them 2450 // first. The order is important. In on case, calling the 2451 // closure on the "starts humongous" region might de-allocate 2452 // and clear all its "continues humongous" regions and, as a 2453 // result, we might end up processing them twice. So, we'll do 2454 // them first (notice: most closures will ignore them anyway) and 2455 // then we'll do the "starts humongous" region. 2456 for (size_t ch_index = index + 1; ch_index < regions; ++ch_index) { 2457 HeapRegion* chr = region_at(ch_index); 2458 2459 // if the region has already been claimed or it's not 2460 // "continues humongous" we're done 2461 if (chr->claim_value() == claim_value || 2462 !chr->continuesHumongous()) { 2463 break; 2464 } 2465 2466 // Noone should have claimed it directly. We can given 2467 // that we claimed its "starts humongous" region. 2468 assert(chr->claim_value() != claim_value, "sanity"); 2469 assert(chr->humongous_start_region() == r, "sanity"); 2470 2471 if (chr->claimHeapRegion(claim_value)) { 2472 // we should always be able to claim it; noone else should 2473 // be trying to claim this region 2474 2475 bool res2 = cl->doHeapRegion(chr); 2476 assert(!res2, "Should not abort"); 2477 2478 // Right now, this holds (i.e., no closure that actually 2479 // does something with "continues humongous" regions 2480 // clears them). We might have to weaken it in the future, 2481 // but let's leave these two asserts here for extra safety. 2482 assert(chr->continuesHumongous(), "should still be the case"); 2483 assert(chr->humongous_start_region() == r, "sanity"); 2484 } else { 2485 guarantee(false, "we should not reach here"); 2486 } 2487 } 2488 } 2489 2490 assert(!r->continuesHumongous(), "sanity"); 2491 bool res = cl->doHeapRegion(r); 2492 assert(!res, "Should not abort"); 2493 } 2494 } 2495 } 2496 2497 class ResetClaimValuesClosure: public HeapRegionClosure { 2498 public: 2499 bool doHeapRegion(HeapRegion* r) { 2500 r->set_claim_value(HeapRegion::InitialClaimValue); 2501 return false; 2502 } 2503 }; 2504 2505 void 2506 G1CollectedHeap::reset_heap_region_claim_values() { 2507 ResetClaimValuesClosure blk; 2508 heap_region_iterate(&blk); 2509 } 2510 2511 #ifdef ASSERT 2512 // This checks whether all regions in the heap have the correct claim 2513 // value. I also piggy-backed on this a check to ensure that the 2514 // humongous_start_region() information on "continues humongous" 2515 // regions is correct. 2516 2517 class CheckClaimValuesClosure : public HeapRegionClosure { 2518 private: 2519 jint _claim_value; 2520 size_t _failures; 2521 HeapRegion* _sh_region; 2522 public: 2523 CheckClaimValuesClosure(jint claim_value) : 2524 _claim_value(claim_value), _failures(0), _sh_region(NULL) { } 2525 bool doHeapRegion(HeapRegion* r) { 2526 if (r->claim_value() != _claim_value) { 2527 gclog_or_tty->print_cr("Region ["PTR_FORMAT","PTR_FORMAT"), " 2528 "claim value = %d, should be %d", 2529 r->bottom(), r->end(), r->claim_value(), 2530 _claim_value); 2531 ++_failures; 2532 } 2533 if (!r->isHumongous()) { 2534 _sh_region = NULL; 2535 } else if (r->startsHumongous()) { 2536 _sh_region = r; 2537 } else if (r->continuesHumongous()) { 2538 if (r->humongous_start_region() != _sh_region) { 2539 gclog_or_tty->print_cr("Region ["PTR_FORMAT","PTR_FORMAT"), " 2540 "HS = "PTR_FORMAT", should be "PTR_FORMAT, 2541 r->bottom(), r->end(), 2542 r->humongous_start_region(), 2543 _sh_region); 2544 ++_failures; 2545 } 2546 } 2547 return false; 2548 } 2549 size_t failures() { 2550 return _failures; 2551 } 2552 }; 2553 2554 bool G1CollectedHeap::check_heap_region_claim_values(jint claim_value) { 2555 CheckClaimValuesClosure cl(claim_value); 2556 heap_region_iterate(&cl); 2557 return cl.failures() == 0; 2558 } 2559 #endif // ASSERT 2560 2561 void G1CollectedHeap::collection_set_iterate(HeapRegionClosure* cl) { 2562 HeapRegion* r = g1_policy()->collection_set(); 2563 while (r != NULL) { 2564 HeapRegion* next = r->next_in_collection_set(); 2565 if (cl->doHeapRegion(r)) { 2566 cl->incomplete(); 2567 return; 2568 } 2569 r = next; 2570 } 2571 } 2572 2573 void G1CollectedHeap::collection_set_iterate_from(HeapRegion* r, 2574 HeapRegionClosure *cl) { 2575 if (r == NULL) { 2576 // The CSet is empty so there's nothing to do. 2577 return; 2578 } 2579 2580 assert(r->in_collection_set(), 2581 "Start region must be a member of the collection set."); 2582 HeapRegion* cur = r; 2583 while (cur != NULL) { 2584 HeapRegion* next = cur->next_in_collection_set(); 2585 if (cl->doHeapRegion(cur) && false) { 2586 cl->incomplete(); 2587 return; 2588 } 2589 cur = next; 2590 } 2591 cur = g1_policy()->collection_set(); 2592 while (cur != r) { 2593 HeapRegion* next = cur->next_in_collection_set(); 2594 if (cl->doHeapRegion(cur) && false) { 2595 cl->incomplete(); 2596 return; 2597 } 2598 cur = next; 2599 } 2600 } 2601 2602 CompactibleSpace* G1CollectedHeap::first_compactible_space() { 2603 return n_regions() > 0 ? region_at(0) : NULL; 2604 } 2605 2606 2607 Space* G1CollectedHeap::space_containing(const void* addr) const { 2608 Space* res = heap_region_containing(addr); 2609 if (res == NULL) 2610 res = perm_gen()->space_containing(addr); 2611 return res; 2612 } 2613 2614 HeapWord* G1CollectedHeap::block_start(const void* addr) const { 2615 Space* sp = space_containing(addr); 2616 if (sp != NULL) { 2617 return sp->block_start(addr); 2618 } 2619 return NULL; 2620 } 2621 2622 size_t G1CollectedHeap::block_size(const HeapWord* addr) const { 2623 Space* sp = space_containing(addr); 2624 assert(sp != NULL, "block_size of address outside of heap"); 2625 return sp->block_size(addr); 2626 } 2627 2628 bool G1CollectedHeap::block_is_obj(const HeapWord* addr) const { 2629 Space* sp = space_containing(addr); 2630 return sp->block_is_obj(addr); 2631 } 2632 2633 bool G1CollectedHeap::supports_tlab_allocation() const { 2634 return true; 2635 } 2636 2637 size_t G1CollectedHeap::tlab_capacity(Thread* ignored) const { 2638 return HeapRegion::GrainBytes; 2639 } 2640 2641 size_t G1CollectedHeap::unsafe_max_tlab_alloc(Thread* ignored) const { 2642 // Return the remaining space in the cur alloc region, but not less than 2643 // the min TLAB size. 2644 2645 // Also, this value can be at most the humongous object threshold, 2646 // since we can't allow tlabs to grow big enough to accomodate 2647 // humongous objects. 2648 2649 HeapRegion* hr = _mutator_alloc_region.get(); 2650 size_t max_tlab_size = _humongous_object_threshold_in_words * wordSize; 2651 if (hr == NULL) { 2652 return max_tlab_size; 2653 } else { 2654 return MIN2(MAX2(hr->free(), (size_t) MinTLABSize), max_tlab_size); 2655 } 2656 } 2657 2658 size_t G1CollectedHeap::max_capacity() const { 2659 return _g1_reserved.byte_size(); 2660 } 2661 2662 jlong G1CollectedHeap::millis_since_last_gc() { 2663 // assert(false, "NYI"); 2664 return 0; 2665 } 2666 2667 void G1CollectedHeap::prepare_for_verify() { 2668 if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) { 2669 ensure_parsability(false); 2670 } 2671 g1_rem_set()->prepare_for_verify(); 2672 } 2673 2674 class VerifyLivenessOopClosure: public OopClosure { 2675 G1CollectedHeap* _g1h; 2676 VerifyOption _vo; 2677 public: 2678 VerifyLivenessOopClosure(G1CollectedHeap* g1h, VerifyOption vo): 2679 _g1h(g1h), _vo(vo) 2680 { } 2681 void do_oop(narrowOop *p) { do_oop_work(p); } 2682 void do_oop( oop *p) { do_oop_work(p); } 2683 2684 template <class T> void do_oop_work(T *p) { 2685 oop obj = oopDesc::load_decode_heap_oop(p); 2686 guarantee(obj == NULL || !_g1h->is_obj_dead_cond(obj, _vo), 2687 "Dead object referenced by a not dead object"); 2688 } 2689 }; 2690 2691 class VerifyObjsInRegionClosure: public ObjectClosure { 2692 private: 2693 G1CollectedHeap* _g1h; 2694 size_t _live_bytes; 2695 HeapRegion *_hr; 2696 VerifyOption _vo; 2697 public: 2698 // _vo == UsePrevMarking -> use "prev" marking information, 2699 // _vo == UseNextMarking -> use "next" marking information, 2700 // _vo == UseMarkWord -> use mark word from object header. 2701 VerifyObjsInRegionClosure(HeapRegion *hr, VerifyOption vo) 2702 : _live_bytes(0), _hr(hr), _vo(vo) { 2703 _g1h = G1CollectedHeap::heap(); 2704 } 2705 void do_object(oop o) { 2706 VerifyLivenessOopClosure isLive(_g1h, _vo); 2707 assert(o != NULL, "Huh?"); 2708 if (!_g1h->is_obj_dead_cond(o, _vo)) { 2709 // If the object is alive according to the mark word, 2710 // then verify that the marking information agrees. 2711 // Note we can't verify the contra-positive of the 2712 // above: if the object is dead (according to the mark 2713 // word), it may not be marked, or may have been marked 2714 // but has since became dead, or may have been allocated 2715 // since the last marking. 2716 if (_vo == VerifyOption_G1UseMarkWord) { 2717 guarantee(!_g1h->is_obj_dead(o), "mark word and concurrent mark mismatch"); 2718 } 2719 2720 o->oop_iterate(&isLive); 2721 if (!_hr->obj_allocated_since_prev_marking(o)) { 2722 size_t obj_size = o->size(); // Make sure we don't overflow 2723 _live_bytes += (obj_size * HeapWordSize); 2724 } 2725 } 2726 } 2727 size_t live_bytes() { return _live_bytes; } 2728 }; 2729 2730 class PrintObjsInRegionClosure : public ObjectClosure { 2731 HeapRegion *_hr; 2732 G1CollectedHeap *_g1; 2733 public: 2734 PrintObjsInRegionClosure(HeapRegion *hr) : _hr(hr) { 2735 _g1 = G1CollectedHeap::heap(); 2736 }; 2737 2738 void do_object(oop o) { 2739 if (o != NULL) { 2740 HeapWord *start = (HeapWord *) o; 2741 size_t word_sz = o->size(); 2742 gclog_or_tty->print("\nPrinting obj "PTR_FORMAT" of size " SIZE_FORMAT 2743 " isMarkedPrev %d isMarkedNext %d isAllocSince %d\n", 2744 (void*) o, word_sz, 2745 _g1->isMarkedPrev(o), 2746 _g1->isMarkedNext(o), 2747 _hr->obj_allocated_since_prev_marking(o)); 2748 HeapWord *end = start + word_sz; 2749 HeapWord *cur; 2750 int *val; 2751 for (cur = start; cur < end; cur++) { 2752 val = (int *) cur; 2753 gclog_or_tty->print("\t "PTR_FORMAT":"PTR_FORMAT"\n", val, *val); 2754 } 2755 } 2756 } 2757 }; 2758 2759 class VerifyRegionClosure: public HeapRegionClosure { 2760 private: 2761 bool _allow_dirty; 2762 bool _par; 2763 VerifyOption _vo; 2764 bool _failures; 2765 public: 2766 // _vo == UsePrevMarking -> use "prev" marking information, 2767 // _vo == UseNextMarking -> use "next" marking information, 2768 // _vo == UseMarkWord -> use mark word from object header. 2769 VerifyRegionClosure(bool allow_dirty, bool par, VerifyOption vo) 2770 : _allow_dirty(allow_dirty), 2771 _par(par), 2772 _vo(vo), 2773 _failures(false) {} 2774 2775 bool failures() { 2776 return _failures; 2777 } 2778 2779 bool doHeapRegion(HeapRegion* r) { 2780 guarantee(_par || r->claim_value() == HeapRegion::InitialClaimValue, 2781 "Should be unclaimed at verify points."); 2782 if (!r->continuesHumongous()) { 2783 bool failures = false; 2784 r->verify(_allow_dirty, _vo, &failures); 2785 if (failures) { 2786 _failures = true; 2787 } else { 2788 VerifyObjsInRegionClosure not_dead_yet_cl(r, _vo); 2789 r->object_iterate(¬_dead_yet_cl); 2790 if (r->max_live_bytes() < not_dead_yet_cl.live_bytes()) { 2791 gclog_or_tty->print_cr("["PTR_FORMAT","PTR_FORMAT"] " 2792 "max_live_bytes "SIZE_FORMAT" " 2793 "< calculated "SIZE_FORMAT, 2794 r->bottom(), r->end(), 2795 r->max_live_bytes(), 2796 not_dead_yet_cl.live_bytes()); 2797 _failures = true; 2798 } 2799 } 2800 } 2801 return false; // stop the region iteration if we hit a failure 2802 } 2803 }; 2804 2805 class VerifyRootsClosure: public OopsInGenClosure { 2806 private: 2807 G1CollectedHeap* _g1h; 2808 VerifyOption _vo; 2809 bool _failures; 2810 public: 2811 // _vo == UsePrevMarking -> use "prev" marking information, 2812 // _vo == UseNextMarking -> use "next" marking information, 2813 // _vo == UseMarkWord -> use mark word from object header. 2814 VerifyRootsClosure(VerifyOption vo) : 2815 _g1h(G1CollectedHeap::heap()), 2816 _vo(vo), 2817 _failures(false) { } 2818 2819 bool failures() { return _failures; } 2820 2821 template <class T> void do_oop_nv(T* p) { 2822 T heap_oop = oopDesc::load_heap_oop(p); 2823 if (!oopDesc::is_null(heap_oop)) { 2824 oop obj = oopDesc::decode_heap_oop_not_null(heap_oop); 2825 if (_g1h->is_obj_dead_cond(obj, _vo)) { 2826 gclog_or_tty->print_cr("Root location "PTR_FORMAT" " 2827 "points to dead obj "PTR_FORMAT, p, (void*) obj); 2828 if (_vo == VerifyOption_G1UseMarkWord) { 2829 gclog_or_tty->print_cr(" Mark word: "PTR_FORMAT, (void*)(obj->mark())); 2830 } 2831 obj->print_on(gclog_or_tty); 2832 _failures = true; 2833 } 2834 } 2835 } 2836 2837 void do_oop(oop* p) { do_oop_nv(p); } 2838 void do_oop(narrowOop* p) { do_oop_nv(p); } 2839 }; 2840 2841 // This is the task used for parallel heap verification. 2842 2843 class G1ParVerifyTask: public AbstractGangTask { 2844 private: 2845 G1CollectedHeap* _g1h; 2846 bool _allow_dirty; 2847 VerifyOption _vo; 2848 bool _failures; 2849 2850 public: 2851 // _vo == UsePrevMarking -> use "prev" marking information, 2852 // _vo == UseNextMarking -> use "next" marking information, 2853 // _vo == UseMarkWord -> use mark word from object header. 2854 G1ParVerifyTask(G1CollectedHeap* g1h, bool allow_dirty, VerifyOption vo) : 2855 AbstractGangTask("Parallel verify task"), 2856 _g1h(g1h), 2857 _allow_dirty(allow_dirty), 2858 _vo(vo), 2859 _failures(false) { } 2860 2861 bool failures() { 2862 return _failures; 2863 } 2864 2865 void work(int worker_i) { 2866 HandleMark hm; 2867 VerifyRegionClosure blk(_allow_dirty, true, _vo); 2868 _g1h->heap_region_par_iterate_chunked(&blk, worker_i, 2869 HeapRegion::ParVerifyClaimValue); 2870 if (blk.failures()) { 2871 _failures = true; 2872 } 2873 } 2874 }; 2875 2876 void G1CollectedHeap::verify(bool allow_dirty, bool silent) { 2877 verify(allow_dirty, silent, VerifyOption_G1UsePrevMarking); 2878 } 2879 2880 void G1CollectedHeap::verify(bool allow_dirty, 2881 bool silent, 2882 VerifyOption vo) { 2883 if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) { 2884 if (!silent) { gclog_or_tty->print("Roots (excluding permgen) "); } 2885 VerifyRootsClosure rootsCl(vo); 2886 CodeBlobToOopClosure blobsCl(&rootsCl, /*do_marking=*/ false); 2887 2888 // We apply the relevant closures to all the oops in the 2889 // system dictionary, the string table and the code cache. 2890 const int so = SharedHeap::SO_AllClasses | SharedHeap::SO_Strings | SharedHeap::SO_CodeCache; 2891 2892 process_strong_roots(true, // activate StrongRootsScope 2893 true, // we set "collecting perm gen" to true, 2894 // so we don't reset the dirty cards in the perm gen. 2895 SharedHeap::ScanningOption(so), // roots scanning options 2896 &rootsCl, 2897 &blobsCl, 2898 &rootsCl); 2899 2900 // If we're verifying after the marking phase of a Full GC then we can't 2901 // treat the perm gen as roots into the G1 heap. Some of the objects in 2902 // the perm gen may be dead and hence not marked. If one of these dead 2903 // objects is considered to be a root then we may end up with a false 2904 // "Root location <x> points to dead ob <y>" failure. 2905 if (vo != VerifyOption_G1UseMarkWord) { 2906 // Since we used "collecting_perm_gen" == true above, we will not have 2907 // checked the refs from perm into the G1-collected heap. We check those 2908 // references explicitly below. Whether the relevant cards are dirty 2909 // is checked further below in the rem set verification. 2910 if (!silent) { gclog_or_tty->print("Permgen roots "); } 2911 perm_gen()->oop_iterate(&rootsCl); 2912 } 2913 bool failures = rootsCl.failures(); 2914 2915 if (vo != VerifyOption_G1UseMarkWord) { 2916 // If we're verifying during a full GC then the region sets 2917 // will have been torn down at the start of the GC. Therefore 2918 // verifying the region sets will fail. So we only verify 2919 // the region sets when not in a full GC. 2920 if (!silent) { gclog_or_tty->print("HeapRegionSets "); } 2921 verify_region_sets(); 2922 } 2923 2924 if (!silent) { gclog_or_tty->print("HeapRegions "); } 2925 if (GCParallelVerificationEnabled && ParallelGCThreads > 1) { 2926 assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue), 2927 "sanity check"); 2928 2929 G1ParVerifyTask task(this, allow_dirty, vo); 2930 int n_workers = workers()->total_workers(); 2931 set_par_threads(n_workers); 2932 workers()->run_task(&task); 2933 set_par_threads(0); 2934 if (task.failures()) { 2935 failures = true; 2936 } 2937 2938 assert(check_heap_region_claim_values(HeapRegion::ParVerifyClaimValue), 2939 "sanity check"); 2940 2941 reset_heap_region_claim_values(); 2942 2943 assert(check_heap_region_claim_values(HeapRegion::InitialClaimValue), 2944 "sanity check"); 2945 } else { 2946 VerifyRegionClosure blk(allow_dirty, false, vo); 2947 heap_region_iterate(&blk); 2948 if (blk.failures()) { 2949 failures = true; 2950 } 2951 } 2952 if (!silent) gclog_or_tty->print("RemSet "); 2953 rem_set()->verify(); 2954 2955 if (failures) { 2956 gclog_or_tty->print_cr("Heap:"); 2957 print_on(gclog_or_tty, true /* extended */); 2958 gclog_or_tty->print_cr(""); 2959 #ifndef PRODUCT 2960 if (VerifyDuringGC && G1VerifyDuringGCPrintReachable) { 2961 concurrent_mark()->print_reachable("at-verification-failure", 2962 vo, false /* all */); 2963 } 2964 #endif 2965 gclog_or_tty->flush(); 2966 } 2967 guarantee(!failures, "there should not have been any failures"); 2968 } else { 2969 if (!silent) gclog_or_tty->print("(SKIPPING roots, heapRegions, remset) "); 2970 } 2971 } 2972 2973 class PrintRegionClosure: public HeapRegionClosure { 2974 outputStream* _st; 2975 public: 2976 PrintRegionClosure(outputStream* st) : _st(st) {} 2977 bool doHeapRegion(HeapRegion* r) { 2978 r->print_on(_st); 2979 return false; 2980 } 2981 }; 2982 2983 void G1CollectedHeap::print() const { print_on(tty); } 2984 2985 void G1CollectedHeap::print_on(outputStream* st) const { 2986 print_on(st, PrintHeapAtGCExtended); 2987 } 2988 2989 void G1CollectedHeap::print_on(outputStream* st, bool extended) const { 2990 st->print(" %-20s", "garbage-first heap"); 2991 st->print(" total " SIZE_FORMAT "K, used " SIZE_FORMAT "K", 2992 capacity()/K, used_unlocked()/K); 2993 st->print(" [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT ")", 2994 _g1_storage.low_boundary(), 2995 _g1_storage.high(), 2996 _g1_storage.high_boundary()); 2997 st->cr(); 2998 st->print(" region size " SIZE_FORMAT "K, ", 2999 HeapRegion::GrainBytes/K); 3000 size_t young_regions = _young_list->length(); 3001 st->print(SIZE_FORMAT " young (" SIZE_FORMAT "K), ", 3002 young_regions, young_regions * HeapRegion::GrainBytes / K); 3003 size_t survivor_regions = g1_policy()->recorded_survivor_regions(); 3004 st->print(SIZE_FORMAT " survivors (" SIZE_FORMAT "K)", 3005 survivor_regions, survivor_regions * HeapRegion::GrainBytes / K); 3006 st->cr(); 3007 perm()->as_gen()->print_on(st); 3008 if (extended) { 3009 st->cr(); 3010 print_on_extended(st); 3011 } 3012 } 3013 3014 void G1CollectedHeap::print_on_extended(outputStream* st) const { 3015 PrintRegionClosure blk(st); 3016 heap_region_iterate(&blk); 3017 } 3018 3019 void G1CollectedHeap::print_gc_threads_on(outputStream* st) const { 3020 if (G1CollectedHeap::use_parallel_gc_threads()) { 3021 workers()->print_worker_threads_on(st); 3022 } 3023 _cmThread->print_on(st); 3024 st->cr(); 3025 _cm->print_worker_threads_on(st); 3026 _cg1r->print_worker_threads_on(st); 3027 st->cr(); 3028 } 3029 3030 void G1CollectedHeap::gc_threads_do(ThreadClosure* tc) const { 3031 if (G1CollectedHeap::use_parallel_gc_threads()) { 3032 workers()->threads_do(tc); 3033 } 3034 tc->do_thread(_cmThread); 3035 _cg1r->threads_do(tc); 3036 } 3037 3038 void G1CollectedHeap::print_tracing_info() const { 3039 // We'll overload this to mean "trace GC pause statistics." 3040 if (TraceGen0Time || TraceGen1Time) { 3041 // The "G1CollectorPolicy" is keeping track of these stats, so delegate 3042 // to that. 3043 g1_policy()->print_tracing_info(); 3044 } 3045 if (G1SummarizeRSetStats) { 3046 g1_rem_set()->print_summary_info(); 3047 } 3048 if (G1SummarizeConcMark) { 3049 concurrent_mark()->print_summary_info(); 3050 } 3051 g1_policy()->print_yg_surv_rate_info(); 3052 SpecializationStats::print(); 3053 } 3054 3055 #ifndef PRODUCT 3056 // Helpful for debugging RSet issues. 3057 3058 class PrintRSetsClosure : public HeapRegionClosure { 3059 private: 3060 const char* _msg; 3061 size_t _occupied_sum; 3062 3063 public: 3064 bool doHeapRegion(HeapRegion* r) { 3065 HeapRegionRemSet* hrrs = r->rem_set(); 3066 size_t occupied = hrrs->occupied(); 3067 _occupied_sum += occupied; 3068 3069 gclog_or_tty->print_cr("Printing RSet for region "HR_FORMAT, 3070 HR_FORMAT_PARAMS(r)); 3071 if (occupied == 0) { 3072 gclog_or_tty->print_cr(" RSet is empty"); 3073 } else { 3074 hrrs->print(); 3075 } 3076 gclog_or_tty->print_cr("----------"); 3077 return false; 3078 } 3079 3080 PrintRSetsClosure(const char* msg) : _msg(msg), _occupied_sum(0) { 3081 gclog_or_tty->cr(); 3082 gclog_or_tty->print_cr("========================================"); 3083 gclog_or_tty->print_cr(msg); 3084 gclog_or_tty->cr(); 3085 } 3086 3087 ~PrintRSetsClosure() { 3088 gclog_or_tty->print_cr("Occupied Sum: "SIZE_FORMAT, _occupied_sum); 3089 gclog_or_tty->print_cr("========================================"); 3090 gclog_or_tty->cr(); 3091 } 3092 }; 3093 3094 void G1CollectedHeap::print_cset_rsets() { 3095 PrintRSetsClosure cl("Printing CSet RSets"); 3096 collection_set_iterate(&cl); 3097 } 3098 3099 void G1CollectedHeap::print_all_rsets() { 3100 PrintRSetsClosure cl("Printing All RSets");; 3101 heap_region_iterate(&cl); 3102 } 3103 #endif // PRODUCT 3104 3105 G1CollectedHeap* G1CollectedHeap::heap() { 3106 assert(_sh->kind() == CollectedHeap::G1CollectedHeap, 3107 "not a garbage-first heap"); 3108 return _g1h; 3109 } 3110 3111 void G1CollectedHeap::gc_prologue(bool full /* Ignored */) { 3112 // always_do_update_barrier = false; 3113 assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer"); 3114 // Call allocation profiler 3115 AllocationProfiler::iterate_since_last_gc(); 3116 // Fill TLAB's and such 3117 ensure_parsability(true); 3118 } 3119 3120 void G1CollectedHeap::gc_epilogue(bool full /* Ignored */) { 3121 // FIXME: what is this about? 3122 // I'm ignoring the "fill_newgen()" call if "alloc_event_enabled" 3123 // is set. 3124 COMPILER2_PRESENT(assert(DerivedPointerTable::is_empty(), 3125 "derived pointer present")); 3126 // always_do_update_barrier = true; 3127 } 3128 3129 HeapWord* G1CollectedHeap::do_collection_pause(size_t word_size, 3130 unsigned int gc_count_before, 3131 bool* succeeded) { 3132 assert_heap_not_locked_and_not_at_safepoint(); 3133 g1_policy()->record_stop_world_start(); 3134 VM_G1IncCollectionPause op(gc_count_before, 3135 word_size, 3136 false, /* should_initiate_conc_mark */ 3137 g1_policy()->max_pause_time_ms(), 3138 GCCause::_g1_inc_collection_pause); 3139 VMThread::execute(&op); 3140 3141 HeapWord* result = op.result(); 3142 bool ret_succeeded = op.prologue_succeeded() && op.pause_succeeded(); 3143 assert(result == NULL || ret_succeeded, 3144 "the result should be NULL if the VM did not succeed"); 3145 *succeeded = ret_succeeded; 3146 3147 assert_heap_not_locked(); 3148 return result; 3149 } 3150 3151 void 3152 G1CollectedHeap::doConcurrentMark() { 3153 MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag); 3154 if (!_cmThread->in_progress()) { 3155 _cmThread->set_started(); 3156 CGC_lock->notify(); 3157 } 3158 } 3159 3160 void G1CollectedHeap::do_sync_mark() { 3161 _cm->checkpointRootsInitial(); 3162 _cm->markFromRoots(); 3163 _cm->checkpointRootsFinal(false); 3164 } 3165 3166 // <NEW PREDICTION> 3167 3168 double G1CollectedHeap::predict_region_elapsed_time_ms(HeapRegion *hr, 3169 bool young) { 3170 return _g1_policy->predict_region_elapsed_time_ms(hr, young); 3171 } 3172 3173 void G1CollectedHeap::check_if_region_is_too_expensive(double 3174 predicted_time_ms) { 3175 _g1_policy->check_if_region_is_too_expensive(predicted_time_ms); 3176 } 3177 3178 size_t G1CollectedHeap::pending_card_num() { 3179 size_t extra_cards = 0; 3180 JavaThread *curr = Threads::first(); 3181 while (curr != NULL) { 3182 DirtyCardQueue& dcq = curr->dirty_card_queue(); 3183 extra_cards += dcq.size(); 3184 curr = curr->next(); 3185 } 3186 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set(); 3187 size_t buffer_size = dcqs.buffer_size(); 3188 size_t buffer_num = dcqs.completed_buffers_num(); 3189 return buffer_size * buffer_num + extra_cards; 3190 } 3191 3192 size_t G1CollectedHeap::max_pending_card_num() { 3193 DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set(); 3194 size_t buffer_size = dcqs.buffer_size(); 3195 size_t buffer_num = dcqs.completed_buffers_num(); 3196 int thread_num = Threads::number_of_threads(); 3197 return (buffer_num + thread_num) * buffer_size; 3198 } 3199 3200 size_t G1CollectedHeap::cards_scanned() { 3201 return g1_rem_set()->cardsScanned(); 3202 } 3203 3204 void 3205 G1CollectedHeap::setup_surviving_young_words() { 3206 guarantee( _surviving_young_words == NULL, "pre-condition" ); 3207 size_t array_length = g1_policy()->young_cset_length(); 3208 _surviving_young_words = NEW_C_HEAP_ARRAY(size_t, array_length); 3209 if (_surviving_young_words == NULL) { 3210 vm_exit_out_of_memory(sizeof(size_t) * array_length, 3211 "Not enough space for young surv words summary."); 3212 } 3213 memset(_surviving_young_words, 0, array_length * sizeof(size_t)); 3214 #ifdef ASSERT 3215 for (size_t i = 0; i < array_length; ++i) { 3216 assert( _surviving_young_words[i] == 0, "memset above" ); 3217 } 3218 #endif // !ASSERT 3219 } 3220 3221 void 3222 G1CollectedHeap::update_surviving_young_words(size_t* surv_young_words) { 3223 MutexLockerEx x(ParGCRareEvent_lock, Mutex::_no_safepoint_check_flag); 3224 size_t array_length = g1_policy()->young_cset_length(); 3225 for (size_t i = 0; i < array_length; ++i) 3226 _surviving_young_words[i] += surv_young_words[i]; 3227 } 3228 3229 void 3230 G1CollectedHeap::cleanup_surviving_young_words() { 3231 guarantee( _surviving_young_words != NULL, "pre-condition" ); 3232 FREE_C_HEAP_ARRAY(size_t, _surviving_young_words); 3233 _surviving_young_words = NULL; 3234 } 3235 3236 // </NEW PREDICTION> 3237 3238 #ifdef ASSERT 3239 class VerifyCSetClosure: public HeapRegionClosure { 3240 public: 3241 bool doHeapRegion(HeapRegion* hr) { 3242 // Here we check that the CSet region's RSet is ready for parallel 3243 // iteration. The fields that we'll verify are only manipulated 3244 // when the region is part of a CSet and is collected. Afterwards, 3245 // we reset these fields when we clear the region's RSet (when the 3246 // region is freed) so they are ready when the region is 3247 // re-allocated. The only exception to this is if there's an 3248 // evacuation failure and instead of freeing the region we leave 3249 // it in the heap. In that case, we reset these fields during 3250 // evacuation failure handling. 3251 guarantee(hr->rem_set()->verify_ready_for_par_iteration(), "verification"); 3252 3253 // Here's a good place to add any other checks we'd like to 3254 // perform on CSet regions. 3255 return false; 3256 } 3257 }; 3258 #endif // ASSERT 3259 3260 #if TASKQUEUE_STATS 3261 void G1CollectedHeap::print_taskqueue_stats_hdr(outputStream* const st) { 3262 st->print_raw_cr("GC Task Stats"); 3263 st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr(); 3264 st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr(); 3265 } 3266 3267 void G1CollectedHeap::print_taskqueue_stats(outputStream* const st) const { 3268 print_taskqueue_stats_hdr(st); 3269 3270 TaskQueueStats totals; 3271 const int n = workers() != NULL ? workers()->total_workers() : 1; 3272 for (int i = 0; i < n; ++i) { 3273 st->print("%3d ", i); task_queue(i)->stats.print(st); st->cr(); 3274 totals += task_queue(i)->stats; 3275 } 3276 st->print_raw("tot "); totals.print(st); st->cr(); 3277 3278 DEBUG_ONLY(totals.verify()); 3279 } 3280 3281 void G1CollectedHeap::reset_taskqueue_stats() { 3282 const int n = workers() != NULL ? workers()->total_workers() : 1; 3283 for (int i = 0; i < n; ++i) { 3284 task_queue(i)->stats.reset(); 3285 } 3286 } 3287 #endif // TASKQUEUE_STATS 3288 3289 bool 3290 G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) { 3291 assert_at_safepoint(true /* should_be_vm_thread */); 3292 guarantee(!is_gc_active(), "collection is not reentrant"); 3293 3294 if (GC_locker::check_active_before_gc()) { 3295 return false; 3296 } 3297 3298 SvcGCMarker sgcm(SvcGCMarker::MINOR); 3299 ResourceMark rm; 3300 3301 if (PrintHeapAtGC) { 3302 Universe::print_heap_before_gc(); 3303 } 3304 3305 verify_region_sets_optional(); 3306 verify_dirty_young_regions(); 3307 3308 { 3309 // This call will decide whether this pause is an initial-mark 3310 // pause. If it is, during_initial_mark_pause() will return true 3311 // for the duration of this pause. 3312 g1_policy()->decide_on_conc_mark_initiation(); 3313 3314 char verbose_str[128]; 3315 sprintf(verbose_str, "GC pause "); 3316 if (g1_policy()->full_young_gcs()) { 3317 strcat(verbose_str, "(young)"); 3318 } else { 3319 strcat(verbose_str, "(partial)"); 3320 } 3321 if (g1_policy()->during_initial_mark_pause()) { 3322 strcat(verbose_str, " (initial-mark)"); 3323 // We are about to start a marking cycle, so we increment the 3324 // full collection counter. 3325 increment_total_full_collections(); 3326 } 3327 3328 // if PrintGCDetails is on, we'll print long statistics information 3329 // in the collector policy code, so let's not print this as the output 3330 // is messy if we do. 3331 gclog_or_tty->date_stamp(PrintGC && PrintGCDateStamps); 3332 TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty); 3333 TraceTime t(verbose_str, PrintGC && !PrintGCDetails, true, gclog_or_tty); 3334 3335 TraceCollectorStats tcs(g1mm()->incremental_collection_counters()); 3336 TraceMemoryManagerStats tms(false /* fullGC */, gc_cause()); 3337 3338 // If the secondary_free_list is not empty, append it to the 3339 // free_list. No need to wait for the cleanup operation to finish; 3340 // the region allocation code will check the secondary_free_list 3341 // and wait if necessary. If the G1StressConcRegionFreeing flag is 3342 // set, skip this step so that the region allocation code has to 3343 // get entries from the secondary_free_list. 3344 if (!G1StressConcRegionFreeing) { 3345 append_secondary_free_list_if_not_empty_with_lock(); 3346 } 3347 3348 assert(check_young_list_well_formed(), 3349 "young list should be well formed"); 3350 3351 { // Call to jvmpi::post_class_unload_events must occur outside of active GC 3352 IsGCActiveMark x; 3353 3354 gc_prologue(false); 3355 increment_total_collections(false /* full gc */); 3356 increment_gc_time_stamp(); 3357 3358 if (VerifyBeforeGC && total_collections() >= VerifyGCStartAt) { 3359 HandleMark hm; // Discard invalid handles created during verification 3360 gclog_or_tty->print(" VerifyBeforeGC:"); 3361 prepare_for_verify(); 3362 Universe::verify(/* allow dirty */ false, 3363 /* silent */ false, 3364 /* option */ VerifyOption_G1UsePrevMarking); 3365 3366 } 3367 3368 COMPILER2_PRESENT(DerivedPointerTable::clear()); 3369 3370 // Please see comment in G1CollectedHeap::ref_processing_init() 3371 // to see how reference processing currently works in G1. 3372 // 3373 // We want to turn off ref discovery, if necessary, and turn it back on 3374 // on again later if we do. XXX Dubious: why is discovery disabled? 3375 bool was_enabled = ref_processor()->discovery_enabled(); 3376 if (was_enabled) ref_processor()->disable_discovery(); 3377 3378 // Forget the current alloc region (we might even choose it to be part 3379 // of the collection set!). 3380 release_mutator_alloc_region(); 3381 3382 // We should call this after we retire the mutator alloc 3383 // region(s) so that all the ALLOC / RETIRE events are generated 3384 // before the start GC event. 3385 _hr_printer.start_gc(false /* full */, (size_t) total_collections()); 3386 3387 // The elapsed time induced by the start time below deliberately elides 3388 // the possible verification above. 3389 double start_time_sec = os::elapsedTime(); 3390 size_t start_used_bytes = used(); 3391 3392 #if YOUNG_LIST_VERBOSE 3393 gclog_or_tty->print_cr("\nBefore recording pause start.\nYoung_list:"); 3394 _young_list->print(); 3395 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty); 3396 #endif // YOUNG_LIST_VERBOSE 3397 3398 g1_policy()->record_collection_pause_start(start_time_sec, 3399 start_used_bytes); 3400 3401 #if YOUNG_LIST_VERBOSE 3402 gclog_or_tty->print_cr("\nAfter recording pause start.\nYoung_list:"); 3403 _young_list->print(); 3404 #endif // YOUNG_LIST_VERBOSE 3405 3406 if (g1_policy()->during_initial_mark_pause()) { 3407 concurrent_mark()->checkpointRootsInitialPre(); 3408 } 3409 perm_gen()->save_marks(); 3410 3411 // We must do this before any possible evacuation that should propagate 3412 // marks. 3413 if (mark_in_progress()) { 3414 double start_time_sec = os::elapsedTime(); 3415 3416 _cm->drainAllSATBBuffers(); 3417 double finish_mark_ms = (os::elapsedTime() - start_time_sec) * 1000.0; 3418 g1_policy()->record_satb_drain_time(finish_mark_ms); 3419 } 3420 // Record the number of elements currently on the mark stack, so we 3421 // only iterate over these. (Since evacuation may add to the mark 3422 // stack, doing more exposes race conditions.) If no mark is in 3423 // progress, this will be zero. 3424 _cm->set_oops_do_bound(); 3425 3426 if (mark_in_progress()) { 3427 concurrent_mark()->newCSet(); 3428 } 3429 3430 #if YOUNG_LIST_VERBOSE 3431 gclog_or_tty->print_cr("\nBefore choosing collection set.\nYoung_list:"); 3432 _young_list->print(); 3433 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty); 3434 #endif // YOUNG_LIST_VERBOSE 3435 3436 g1_policy()->choose_collection_set(target_pause_time_ms); 3437 3438 if (_hr_printer.is_active()) { 3439 HeapRegion* hr = g1_policy()->collection_set(); 3440 while (hr != NULL) { 3441 G1HRPrinter::RegionType type; 3442 if (!hr->is_young()) { 3443 type = G1HRPrinter::Old; 3444 } else if (hr->is_survivor()) { 3445 type = G1HRPrinter::Survivor; 3446 } else { 3447 type = G1HRPrinter::Eden; 3448 } 3449 _hr_printer.cset(hr); 3450 hr = hr->next_in_collection_set(); 3451 } 3452 } 3453 3454 // We have chosen the complete collection set. If marking is 3455 // active then, we clear the region fields of any of the 3456 // concurrent marking tasks whose region fields point into 3457 // the collection set as these values will become stale. This 3458 // will cause the owning marking threads to claim a new region 3459 // when marking restarts. 3460 if (mark_in_progress()) { 3461 concurrent_mark()->reset_active_task_region_fields_in_cset(); 3462 } 3463 3464 #ifdef ASSERT 3465 VerifyCSetClosure cl; 3466 collection_set_iterate(&cl); 3467 #endif // ASSERT 3468 3469 setup_surviving_young_words(); 3470 3471 // Initialize the GC alloc regions. 3472 init_gc_alloc_regions(); 3473 3474 // Actually do the work... 3475 evacuate_collection_set(); 3476 3477 free_collection_set(g1_policy()->collection_set()); 3478 g1_policy()->clear_collection_set(); 3479 3480 cleanup_surviving_young_words(); 3481 3482 // Start a new incremental collection set for the next pause. 3483 g1_policy()->start_incremental_cset_building(); 3484 3485 // Clear the _cset_fast_test bitmap in anticipation of adding 3486 // regions to the incremental collection set for the next 3487 // evacuation pause. 3488 clear_cset_fast_test(); 3489 3490 _young_list->reset_sampled_info(); 3491 3492 // Don't check the whole heap at this point as the 3493 // GC alloc regions from this pause have been tagged 3494 // as survivors and moved on to the survivor list. 3495 // Survivor regions will fail the !is_young() check. 3496 assert(check_young_list_empty(false /* check_heap */), 3497 "young list should be empty"); 3498 3499 #if YOUNG_LIST_VERBOSE 3500 gclog_or_tty->print_cr("Before recording survivors.\nYoung List:"); 3501 _young_list->print(); 3502 #endif // YOUNG_LIST_VERBOSE 3503 3504 g1_policy()->record_survivor_regions(_young_list->survivor_length(), 3505 _young_list->first_survivor_region(), 3506 _young_list->last_survivor_region()); 3507 3508 _young_list->reset_auxilary_lists(); 3509 3510 if (evacuation_failed()) { 3511 _summary_bytes_used = recalculate_used(); 3512 } else { 3513 // The "used" of the the collection set have already been subtracted 3514 // when they were freed. Add in the bytes evacuated. 3515 _summary_bytes_used += g1_policy()->bytes_copied_during_gc(); 3516 } 3517 3518 if (g1_policy()->during_initial_mark_pause()) { 3519 concurrent_mark()->checkpointRootsInitialPost(); 3520 set_marking_started(); 3521 // CAUTION: after the doConcurrentMark() call below, 3522 // the concurrent marking thread(s) could be running 3523 // concurrently with us. Make sure that anything after 3524 // this point does not assume that we are the only GC thread 3525 // running. Note: of course, the actual marking work will 3526 // not start until the safepoint itself is released in 3527 // ConcurrentGCThread::safepoint_desynchronize(). 3528 doConcurrentMark(); 3529 } 3530 3531 allocate_dummy_regions(); 3532 3533 #if YOUNG_LIST_VERBOSE 3534 gclog_or_tty->print_cr("\nEnd of the pause.\nYoung_list:"); 3535 _young_list->print(); 3536 g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty); 3537 #endif // YOUNG_LIST_VERBOSE 3538 3539 init_mutator_alloc_region(); 3540 3541 double end_time_sec = os::elapsedTime(); 3542 double pause_time_ms = (end_time_sec - start_time_sec) * MILLIUNITS; 3543 g1_policy()->record_pause_time_ms(pause_time_ms); 3544 g1_policy()->record_collection_pause_end(); 3545 3546 MemoryService::track_memory_usage(); 3547 3548 // In prepare_for_verify() below we'll need to scan the deferred 3549 // update buffers to bring the RSets up-to-date if 3550 // G1HRRSFlushLogBuffersOnVerify has been set. While scanning 3551 // the update buffers we'll probably need to scan cards on the 3552 // regions we just allocated to (i.e., the GC alloc 3553 // regions). However, during the last GC we called 3554 // set_saved_mark() on all the GC alloc regions, so card 3555 // scanning might skip the [saved_mark_word()...top()] area of 3556 // those regions (i.e., the area we allocated objects into 3557 // during the last GC). But it shouldn't. Given that 3558 // saved_mark_word() is conditional on whether the GC time stamp 3559 // on the region is current or not, by incrementing the GC time 3560 // stamp here we invalidate all the GC time stamps on all the 3561 // regions and saved_mark_word() will simply return top() for 3562 // all the regions. This is a nicer way of ensuring this rather 3563 // than iterating over the regions and fixing them. In fact, the 3564 // GC time stamp increment here also ensures that 3565 // saved_mark_word() will return top() between pauses, i.e., 3566 // during concurrent refinement. So we don't need the 3567 // is_gc_active() check to decided which top to use when 3568 // scanning cards (see CR 7039627). 3569 increment_gc_time_stamp(); 3570 3571 if (VerifyAfterGC && total_collections() >= VerifyGCStartAt) { 3572 HandleMark hm; // Discard invalid handles created during verification 3573 gclog_or_tty->print(" VerifyAfterGC:"); 3574 prepare_for_verify(); 3575 Universe::verify(/* allow dirty */ true, 3576 /* silent */ false, 3577 /* option */ VerifyOption_G1UsePrevMarking); 3578 } 3579 3580 if (was_enabled) ref_processor()->enable_discovery(); 3581 3582 { 3583 size_t expand_bytes = g1_policy()->expansion_amount(); 3584 if (expand_bytes > 0) { 3585 size_t bytes_before = capacity(); 3586 if (!expand(expand_bytes)) { 3587 // We failed to expand the heap so let's verify that 3588 // committed/uncommitted amount match the backing store 3589 assert(capacity() == _g1_storage.committed_size(), "committed size mismatch"); 3590 assert(max_capacity() == _g1_storage.reserved_size(), "reserved size mismatch"); 3591 } 3592 } 3593 } 3594 3595 // We should do this after we potentially expand the heap so 3596 // that all the COMMIT events are generated before the end GC 3597 // event, and after we retire the GC alloc regions so that all 3598 // RETIRE events are generated before the end GC event. 3599 _hr_printer.end_gc(false /* full */, (size_t) total_collections()); 3600 3601 // We have to do this after we decide whether to expand the heap or not. 3602 g1_policy()->print_heap_transition(); 3603 3604 if (mark_in_progress()) { 3605 concurrent_mark()->update_g1_committed(); 3606 } 3607 3608 #ifdef TRACESPINNING 3609 ParallelTaskTerminator::print_termination_counts(); 3610 #endif 3611 3612 gc_epilogue(false); 3613 } 3614 3615 if (ExitAfterGCNum > 0 && total_collections() == ExitAfterGCNum) { 3616 gclog_or_tty->print_cr("Stopping after GC #%d", ExitAfterGCNum); 3617 print_tracing_info(); 3618 vm_exit(-1); 3619 } 3620 } 3621 3622 _hrs.verify_optional(); 3623 verify_region_sets_optional(); 3624 3625 TASKQUEUE_STATS_ONLY(if (ParallelGCVerbose) print_taskqueue_stats()); 3626 TASKQUEUE_STATS_ONLY(reset_taskqueue_stats()); 3627 3628 if (PrintHeapAtGC) { 3629 Universe::print_heap_after_gc(); 3630 } 3631 g1mm()->update_counters(); 3632 3633 if (G1SummarizeRSetStats && 3634 (G1SummarizeRSetStatsPeriod > 0) && 3635 (total_collections() % G1SummarizeRSetStatsPeriod == 0)) { 3636 g1_rem_set()->print_summary_info(); 3637 } 3638 3639 return true; 3640 } 3641 3642 size_t G1CollectedHeap::desired_plab_sz(GCAllocPurpose purpose) 3643 { 3644 size_t gclab_word_size; 3645 switch (purpose) { 3646 case GCAllocForSurvived: 3647 gclab_word_size = YoungPLABSize; 3648 break; 3649 case GCAllocForTenured: 3650 gclab_word_size = OldPLABSize; 3651 break; 3652 default: 3653 assert(false, "unknown GCAllocPurpose"); 3654 gclab_word_size = OldPLABSize; 3655 break; 3656 } 3657 return gclab_word_size; 3658 } 3659 3660 void G1CollectedHeap::init_mutator_alloc_region() { 3661 assert(_mutator_alloc_region.get() == NULL, "pre-condition"); 3662 _mutator_alloc_region.init(); 3663 } 3664 3665 void G1CollectedHeap::release_mutator_alloc_region() { 3666 _mutator_alloc_region.release(); 3667 assert(_mutator_alloc_region.get() == NULL, "post-condition"); 3668 } 3669 3670 void G1CollectedHeap::init_gc_alloc_regions() { 3671 assert_at_safepoint(true /* should_be_vm_thread */); 3672 3673 _survivor_gc_alloc_region.init(); 3674 _old_gc_alloc_region.init(); 3675 HeapRegion* retained_region = _retained_old_gc_alloc_region; 3676 _retained_old_gc_alloc_region = NULL; 3677 3678 // We will discard the current GC alloc region if: 3679 // a) it's in the collection set (it can happen!), 3680 // b) it's already full (no point in using it), 3681 // c) it's empty (this means that it was emptied during 3682 // a cleanup and it should be on the free list now), or 3683 // d) it's humongous (this means that it was emptied 3684 // during a cleanup and was added to the free list, but 3685 // has been subseqently used to allocate a humongous 3686 // object that may be less than the region size). 3687 if (retained_region != NULL && 3688 !retained_region->in_collection_set() && 3689 !(retained_region->top() == retained_region->end()) && 3690 !retained_region->is_empty() && 3691 !retained_region->isHumongous()) { 3692 retained_region->set_saved_mark(); 3693 _old_gc_alloc_region.set(retained_region); 3694 _hr_printer.reuse(retained_region); 3695 } 3696 } 3697 3698 void G1CollectedHeap::release_gc_alloc_regions() { 3699 _survivor_gc_alloc_region.release(); 3700 // If we have an old GC alloc region to release, we'll save it in 3701 // _retained_old_gc_alloc_region. If we don't 3702 // _retained_old_gc_alloc_region will become NULL. This is what we 3703 // want either way so no reason to check explicitly for either 3704 // condition. 3705 _retained_old_gc_alloc_region = _old_gc_alloc_region.release(); 3706 } 3707 3708 void G1CollectedHeap::abandon_gc_alloc_regions() { 3709 assert(_survivor_gc_alloc_region.get() == NULL, "pre-condition"); 3710 assert(_old_gc_alloc_region.get() == NULL, "pre-condition"); 3711 _retained_old_gc_alloc_region = NULL; 3712 } 3713 3714 void G1CollectedHeap::init_for_evac_failure(OopsInHeapRegionClosure* cl) { 3715 _drain_in_progress = false; 3716 set_evac_failure_closure(cl); 3717 _evac_failure_scan_stack = new (ResourceObj::C_HEAP) GrowableArray<oop>(40, true); 3718 } 3719 3720 void G1CollectedHeap::finalize_for_evac_failure() { 3721 assert(_evac_failure_scan_stack != NULL && 3722 _evac_failure_scan_stack->length() == 0, 3723 "Postcondition"); 3724 assert(!_drain_in_progress, "Postcondition"); 3725 delete _evac_failure_scan_stack; 3726 _evac_failure_scan_stack = NULL; 3727 } 3728 3729 // *** Sequential G1 Evacuation 3730 3731 class G1IsAliveClosure: public BoolObjectClosure { 3732 G1CollectedHeap* _g1; 3733 public: 3734 G1IsAliveClosure(G1CollectedHeap* g1) : _g1(g1) {} 3735 void do_object(oop p) { assert(false, "Do not call."); } 3736 bool do_object_b(oop p) { 3737 // It is reachable if it is outside the collection set, or is inside 3738 // and forwarded. 3739 3740 #ifdef G1_DEBUG 3741 gclog_or_tty->print_cr("is alive "PTR_FORMAT" in CS %d forwarded %d overall %d", 3742 (void*) p, _g1->obj_in_cs(p), p->is_forwarded(), 3743 !_g1->obj_in_cs(p) || p->is_forwarded()); 3744 #endif // G1_DEBUG 3745 3746 return !_g1->obj_in_cs(p) || p->is_forwarded(); 3747 } 3748 }; 3749 3750 class G1KeepAliveClosure: public OopClosure { 3751 G1CollectedHeap* _g1; 3752 public: 3753 G1KeepAliveClosure(G1CollectedHeap* g1) : _g1(g1) {} 3754 void do_oop(narrowOop* p) { guarantee(false, "Not needed"); } 3755 void do_oop( oop* p) { 3756 oop obj = *p; 3757 #ifdef G1_DEBUG 3758 if (PrintGC && Verbose) { 3759 gclog_or_tty->print_cr("keep alive *"PTR_FORMAT" = "PTR_FORMAT" "PTR_FORMAT, 3760 p, (void*) obj, (void*) *p); 3761 } 3762 #endif // G1_DEBUG 3763 3764 if (_g1->obj_in_cs(obj)) { 3765 assert( obj->is_forwarded(), "invariant" ); 3766 *p = obj->forwardee(); 3767 #ifdef G1_DEBUG 3768 gclog_or_tty->print_cr(" in CSet: moved "PTR_FORMAT" -> "PTR_FORMAT, 3769 (void*) obj, (void*) *p); 3770 #endif // G1_DEBUG 3771 } 3772 } 3773 }; 3774 3775 class UpdateRSetDeferred : public OopsInHeapRegionClosure { 3776 private: 3777 G1CollectedHeap* _g1; 3778 DirtyCardQueue *_dcq; 3779 CardTableModRefBS* _ct_bs; 3780 3781 public: 3782 UpdateRSetDeferred(G1CollectedHeap* g1, DirtyCardQueue* dcq) : 3783 _g1(g1), _ct_bs((CardTableModRefBS*)_g1->barrier_set()), _dcq(dcq) {} 3784 3785 virtual void do_oop(narrowOop* p) { do_oop_work(p); } 3786 virtual void do_oop( oop* p) { do_oop_work(p); } 3787 template <class T> void do_oop_work(T* p) { 3788 assert(_from->is_in_reserved(p), "paranoia"); 3789 if (!_from->is_in_reserved(oopDesc::load_decode_heap_oop(p)) && 3790 !_from->is_survivor()) { 3791 size_t card_index = _ct_bs->index_for(p); 3792 if (_ct_bs->mark_card_deferred(card_index)) { 3793 _dcq->enqueue((jbyte*)_ct_bs->byte_for_index(card_index)); 3794 } 3795 } 3796 } 3797 }; 3798 3799 class RemoveSelfPointerClosure: public ObjectClosure { 3800 private: 3801 G1CollectedHeap* _g1; 3802 ConcurrentMark* _cm; 3803 HeapRegion* _hr; 3804 size_t _prev_marked_bytes; 3805 size_t _next_marked_bytes; 3806 OopsInHeapRegionClosure *_cl; 3807 public: 3808 RemoveSelfPointerClosure(G1CollectedHeap* g1, HeapRegion* hr, 3809 OopsInHeapRegionClosure* cl) : 3810 _g1(g1), _hr(hr), _cm(_g1->concurrent_mark()), _prev_marked_bytes(0), 3811 _next_marked_bytes(0), _cl(cl) {} 3812 3813 size_t prev_marked_bytes() { return _prev_marked_bytes; } 3814 size_t next_marked_bytes() { return _next_marked_bytes; } 3815 3816 // <original comment> 3817 // The original idea here was to coalesce evacuated and dead objects. 3818 // However that caused complications with the block offset table (BOT). 3819 // In particular if there were two TLABs, one of them partially refined. 3820 // |----- TLAB_1--------|----TLAB_2-~~~(partially refined part)~~~| 3821 // The BOT entries of the unrefined part of TLAB_2 point to the start 3822 // of TLAB_2. If the last object of the TLAB_1 and the first object 3823 // of TLAB_2 are coalesced, then the cards of the unrefined part 3824 // would point into middle of the filler object. 3825 // The current approach is to not coalesce and leave the BOT contents intact. 3826 // </original comment> 3827 // 3828 // We now reset the BOT when we start the object iteration over the 3829 // region and refine its entries for every object we come across. So 3830 // the above comment is not really relevant and we should be able 3831 // to coalesce dead objects if we want to. 3832 void do_object(oop obj) { 3833 HeapWord* obj_addr = (HeapWord*) obj; 3834 assert(_hr->is_in(obj_addr), "sanity"); 3835 size_t obj_size = obj->size(); 3836 _hr->update_bot_for_object(obj_addr, obj_size); 3837 if (obj->is_forwarded() && obj->forwardee() == obj) { 3838 // The object failed to move. 3839 assert(!_g1->is_obj_dead(obj), "We should not be preserving dead objs."); 3840 _cm->markPrev(obj); 3841 assert(_cm->isPrevMarked(obj), "Should be marked!"); 3842 _prev_marked_bytes += (obj_size * HeapWordSize); 3843 if (_g1->mark_in_progress() && !_g1->is_obj_ill(obj)) { 3844 _cm->markAndGrayObjectIfNecessary(obj); 3845 } 3846 obj->set_mark(markOopDesc::prototype()); 3847 // While we were processing RSet buffers during the 3848 // collection, we actually didn't scan any cards on the 3849 // collection set, since we didn't want to update remebered 3850 // sets with entries that point into the collection set, given 3851 // that live objects fromthe collection set are about to move 3852 // and such entries will be stale very soon. This change also 3853 // dealt with a reliability issue which involved scanning a 3854 // card in the collection set and coming across an array that 3855 // was being chunked and looking malformed. The problem is 3856 // that, if evacuation fails, we might have remembered set 3857 // entries missing given that we skipped cards on the 3858 // collection set. So, we'll recreate such entries now. 3859 obj->oop_iterate(_cl); 3860 assert(_cm->isPrevMarked(obj), "Should be marked!"); 3861 } else { 3862 // The object has been either evacuated or is dead. Fill it with a 3863 // dummy object. 3864 MemRegion mr((HeapWord*)obj, obj_size); 3865 CollectedHeap::fill_with_object(mr); 3866 _cm->clearRangeBothMaps(mr); 3867 } 3868 } 3869 }; 3870 3871 void G1CollectedHeap::remove_self_forwarding_pointers() { 3872 UpdateRSetImmediate immediate_update(_g1h->g1_rem_set()); 3873 DirtyCardQueue dcq(&_g1h->dirty_card_queue_set()); 3874 UpdateRSetDeferred deferred_update(_g1h, &dcq); 3875 OopsInHeapRegionClosure *cl; 3876 if (G1DeferredRSUpdate) { 3877 cl = &deferred_update; 3878 } else { 3879 cl = &immediate_update; 3880 } 3881 HeapRegion* cur = g1_policy()->collection_set(); 3882 while (cur != NULL) { 3883 assert(g1_policy()->assertMarkedBytesDataOK(), "Should be!"); 3884 assert(!cur->isHumongous(), "sanity"); 3885 3886 if (cur->evacuation_failed()) { 3887 assert(cur->in_collection_set(), "bad CS"); 3888 RemoveSelfPointerClosure rspc(_g1h, cur, cl); 3889 3890 // In the common case we make sure that this is done when the 3891 // region is freed so that it is "ready-to-go" when it's 3892 // re-allocated. However, when evacuation failure happens, a 3893 // region will remain in the heap and might ultimately be added 3894 // to a CSet in the future. So we have to be careful here and 3895 // make sure the region's RSet is ready for parallel iteration 3896 // whenever this might be required in the future. 3897 cur->rem_set()->reset_for_par_iteration(); 3898 cur->reset_bot(); 3899 cl->set_region(cur); 3900 cur->object_iterate(&rspc); 3901 3902 // A number of manipulations to make the TAMS be the current top, 3903 // and the marked bytes be the ones observed in the iteration. 3904 if (_g1h->concurrent_mark()->at_least_one_mark_complete()) { 3905 // The comments below are the postconditions achieved by the 3906 // calls. Note especially the last such condition, which says that 3907 // the count of marked bytes has been properly restored. 3908 cur->note_start_of_marking(false); 3909 // _next_top_at_mark_start == top, _next_marked_bytes == 0 3910 cur->add_to_marked_bytes(rspc.prev_marked_bytes()); 3911 // _next_marked_bytes == prev_marked_bytes. 3912 cur->note_end_of_marking(); 3913 // _prev_top_at_mark_start == top(), 3914 // _prev_marked_bytes == prev_marked_bytes 3915 } 3916 // If there is no mark in progress, we modified the _next variables 3917 // above needlessly, but harmlessly. 3918 if (_g1h->mark_in_progress()) { 3919 cur->note_start_of_marking(false); 3920 // _next_top_at_mark_start == top, _next_marked_bytes == 0 3921 // _next_marked_bytes == next_marked_bytes. 3922 } 3923 3924 // Now make sure the region has the right index in the sorted array. 3925 g1_policy()->note_change_in_marked_bytes(cur); 3926 } 3927 cur = cur->next_in_collection_set(); 3928 } 3929 assert(g1_policy()->assertMarkedBytesDataOK(), "Should be!"); 3930 3931 // Now restore saved marks, if any. 3932 if (_objs_with_preserved_marks != NULL) { 3933 assert(_preserved_marks_of_objs != NULL, "Both or none."); 3934 guarantee(_objs_with_preserved_marks->length() == 3935 _preserved_marks_of_objs->length(), "Both or none."); 3936 for (int i = 0; i < _objs_with_preserved_marks->length(); i++) { 3937 oop obj = _objs_with_preserved_marks->at(i); 3938 markOop m = _preserved_marks_of_objs->at(i); 3939 obj->set_mark(m); 3940 } 3941 // Delete the preserved marks growable arrays (allocated on the C heap). 3942 delete _objs_with_preserved_marks; 3943 delete _preserved_marks_of_objs; 3944 _objs_with_preserved_marks = NULL; 3945 _preserved_marks_of_objs = NULL; 3946 } 3947 } 3948 3949 void G1CollectedHeap::push_on_evac_failure_scan_stack(oop obj) { 3950 _evac_failure_scan_stack->push(obj); 3951 } 3952 3953 void G1CollectedHeap::drain_evac_failure_scan_stack() { 3954 assert(_evac_failure_scan_stack != NULL, "precondition"); 3955 3956 while (_evac_failure_scan_stack->length() > 0) { 3957 oop obj = _evac_failure_scan_stack->pop(); 3958 _evac_failure_closure->set_region(heap_region_containing(obj)); 3959 obj->oop_iterate_backwards(_evac_failure_closure); 3960 } 3961 } 3962 3963 oop 3964 G1CollectedHeap::handle_evacuation_failure_par(OopsInHeapRegionClosure* cl, 3965 oop old) { 3966 assert(obj_in_cs(old), 3967 err_msg("obj: "PTR_FORMAT" should still be in the CSet", 3968 (HeapWord*) old)); 3969 markOop m = old->mark(); 3970 oop forward_ptr = old->forward_to_atomic(old); 3971 if (forward_ptr == NULL) { 3972 // Forward-to-self succeeded. 3973 if (_evac_failure_closure != cl) { 3974 MutexLockerEx x(EvacFailureStack_lock, Mutex::_no_safepoint_check_flag); 3975 assert(!_drain_in_progress, 3976 "Should only be true while someone holds the lock."); 3977 // Set the global evac-failure closure to the current thread's. 3978 assert(_evac_failure_closure == NULL, "Or locking has failed."); 3979 set_evac_failure_closure(cl); 3980 // Now do the common part. 3981 handle_evacuation_failure_common(old, m); 3982 // Reset to NULL. 3983 set_evac_failure_closure(NULL); 3984 } else { 3985 // The lock is already held, and this is recursive. 3986 assert(_drain_in_progress, "This should only be the recursive case."); 3987 handle_evacuation_failure_common(old, m); 3988 } 3989 return old; 3990 } else { 3991 // Forward-to-self failed. Either someone else managed to allocate 3992 // space for this object (old != forward_ptr) or they beat us in 3993 // self-forwarding it (old == forward_ptr). 3994 assert(old == forward_ptr || !obj_in_cs(forward_ptr), 3995 err_msg("obj: "PTR_FORMAT" forwarded to: "PTR_FORMAT" " 3996 "should not be in the CSet", 3997 (HeapWord*) old, (HeapWord*) forward_ptr)); 3998 return forward_ptr; 3999 } 4000 } 4001 4002 void G1CollectedHeap::handle_evacuation_failure_common(oop old, markOop m) { 4003 set_evacuation_failed(true); 4004 4005 preserve_mark_if_necessary(old, m); 4006 4007 HeapRegion* r = heap_region_containing(old); 4008 if (!r->evacuation_failed()) { 4009 r->set_evacuation_failed(true); 4010 _hr_printer.evac_failure(r); 4011 } 4012 4013 push_on_evac_failure_scan_stack(old); 4014 4015 if (!_drain_in_progress) { 4016 // prevent recursion in copy_to_survivor_space() 4017 _drain_in_progress = true; 4018 drain_evac_failure_scan_stack(); 4019 _drain_in_progress = false; 4020 } 4021 } 4022 4023 void G1CollectedHeap::preserve_mark_if_necessary(oop obj, markOop m) { 4024 assert(evacuation_failed(), "Oversaving!"); 4025 // We want to call the "for_promotion_failure" version only in the 4026 // case of a promotion failure. 4027 if (m->must_be_preserved_for_promotion_failure(obj)) { 4028 if (_objs_with_preserved_marks == NULL) { 4029 assert(_preserved_marks_of_objs == NULL, "Both or none."); 4030 _objs_with_preserved_marks = 4031 new (ResourceObj::C_HEAP) GrowableArray<oop>(40, true); 4032 _preserved_marks_of_objs = 4033 new (ResourceObj::C_HEAP) GrowableArray<markOop>(40, true); 4034 } 4035 _objs_with_preserved_marks->push(obj); 4036 _preserved_marks_of_objs->push(m); 4037 } 4038 } 4039 4040 HeapWord* G1CollectedHeap::par_allocate_during_gc(GCAllocPurpose purpose, 4041 size_t word_size) { 4042 if (purpose == GCAllocForSurvived) { 4043 HeapWord* result = survivor_attempt_allocation(word_size); 4044 if (result != NULL) { 4045 return result; 4046 } else { 4047 // Let's try to allocate in the old gen in case we can fit the 4048 // object there. 4049 return old_attempt_allocation(word_size); 4050 } 4051 } else { 4052 assert(purpose == GCAllocForTenured, "sanity"); 4053 HeapWord* result = old_attempt_allocation(word_size); 4054 if (result != NULL) { 4055 return result; 4056 } else { 4057 // Let's try to allocate in the survivors in case we can fit the 4058 // object there. 4059 return survivor_attempt_allocation(word_size); 4060 } 4061 } 4062 4063 ShouldNotReachHere(); 4064 // Trying to keep some compilers happy. 4065 return NULL; 4066 } 4067 4068 #ifndef PRODUCT 4069 bool GCLabBitMapClosure::do_bit(size_t offset) { 4070 HeapWord* addr = _bitmap->offsetToHeapWord(offset); 4071 guarantee(_cm->isMarked(oop(addr)), "it should be!"); 4072 return true; 4073 } 4074 #endif // PRODUCT 4075 4076 G1ParScanThreadState::G1ParScanThreadState(G1CollectedHeap* g1h, int queue_num) 4077 : _g1h(g1h), 4078 _refs(g1h->task_queue(queue_num)), 4079 _dcq(&g1h->dirty_card_queue_set()), 4080 _ct_bs((CardTableModRefBS*)_g1h->barrier_set()), 4081 _g1_rem(g1h->g1_rem_set()), 4082 _hash_seed(17), _queue_num(queue_num), 4083 _term_attempts(0), 4084 _surviving_alloc_buffer(g1h->desired_plab_sz(GCAllocForSurvived)), 4085 _tenured_alloc_buffer(g1h->desired_plab_sz(GCAllocForTenured)), 4086 _age_table(false), 4087 _strong_roots_time(0), _term_time(0), 4088 _alloc_buffer_waste(0), _undo_waste(0) 4089 { 4090 // we allocate G1YoungSurvRateNumRegions plus one entries, since 4091 // we "sacrifice" entry 0 to keep track of surviving bytes for 4092 // non-young regions (where the age is -1) 4093 // We also add a few elements at the beginning and at the end in 4094 // an attempt to eliminate cache contention 4095 size_t real_length = 1 + _g1h->g1_policy()->young_cset_length(); 4096 size_t array_length = PADDING_ELEM_NUM + 4097 real_length + 4098 PADDING_ELEM_NUM; 4099 _surviving_young_words_base = NEW_C_HEAP_ARRAY(size_t, array_length); 4100 if (_surviving_young_words_base == NULL) 4101 vm_exit_out_of_memory(array_length * sizeof(size_t), 4102 "Not enough space for young surv histo."); 4103 _surviving_young_words = _surviving_young_words_base + PADDING_ELEM_NUM; 4104 memset(_surviving_young_words, 0, real_length * sizeof(size_t)); 4105 4106 _alloc_buffers[GCAllocForSurvived] = &_surviving_alloc_buffer; 4107 _alloc_buffers[GCAllocForTenured] = &_tenured_alloc_buffer; 4108 4109 _start = os::elapsedTime(); 4110 } 4111 4112 void 4113 G1ParScanThreadState::print_termination_stats_hdr(outputStream* const st) 4114 { 4115 st->print_raw_cr("GC Termination Stats"); 4116 st->print_raw_cr(" elapsed --strong roots-- -------termination-------" 4117 " ------waste (KiB)------"); 4118 st->print_raw_cr("thr ms ms % ms % attempts" 4119 " total alloc undo"); 4120 st->print_raw_cr("--- --------- --------- ------ --------- ------ --------" 4121 " ------- ------- -------"); 4122 } 4123 4124 void 4125 G1ParScanThreadState::print_termination_stats(int i, 4126 outputStream* const st) const 4127 { 4128 const double elapsed_ms = elapsed_time() * 1000.0; 4129 const double s_roots_ms = strong_roots_time() * 1000.0; 4130 const double term_ms = term_time() * 1000.0; 4131 st->print_cr("%3d %9.2f %9.2f %6.2f " 4132 "%9.2f %6.2f " SIZE_FORMAT_W(8) " " 4133 SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7) " " SIZE_FORMAT_W(7), 4134 i, elapsed_ms, s_roots_ms, s_roots_ms * 100 / elapsed_ms, 4135 term_ms, term_ms * 100 / elapsed_ms, term_attempts(), 4136 (alloc_buffer_waste() + undo_waste()) * HeapWordSize / K, 4137 alloc_buffer_waste() * HeapWordSize / K, 4138 undo_waste() * HeapWordSize / K); 4139 } 4140 4141 #ifdef ASSERT 4142 bool G1ParScanThreadState::verify_ref(narrowOop* ref) const { 4143 assert(ref != NULL, "invariant"); 4144 assert(UseCompressedOops, "sanity"); 4145 assert(!has_partial_array_mask(ref), err_msg("ref=" PTR_FORMAT, ref)); 4146 oop p = oopDesc::load_decode_heap_oop(ref); 4147 assert(_g1h->is_in_g1_reserved(p), 4148 err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, intptr_t(p))); 4149 return true; 4150 } 4151 4152 bool G1ParScanThreadState::verify_ref(oop* ref) const { 4153 assert(ref != NULL, "invariant"); 4154 if (has_partial_array_mask(ref)) { 4155 // Must be in the collection set--it's already been copied. 4156 oop p = clear_partial_array_mask(ref); 4157 assert(_g1h->obj_in_cs(p), 4158 err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, intptr_t(p))); 4159 } else { 4160 oop p = oopDesc::load_decode_heap_oop(ref); 4161 assert(_g1h->is_in_g1_reserved(p), 4162 err_msg("ref=" PTR_FORMAT " p=" PTR_FORMAT, ref, intptr_t(p))); 4163 } 4164 return true; 4165 } 4166 4167 bool G1ParScanThreadState::verify_task(StarTask ref) const { 4168 if (ref.is_narrow()) { 4169 return verify_ref((narrowOop*) ref); 4170 } else { 4171 return verify_ref((oop*) ref); 4172 } 4173 } 4174 #endif // ASSERT 4175 4176 void G1ParScanThreadState::trim_queue() { 4177 StarTask ref; 4178 do { 4179 // Drain the overflow stack first, so other threads can steal. 4180 while (refs()->pop_overflow(ref)) { 4181 deal_with_reference(ref); 4182 } 4183 while (refs()->pop_local(ref)) { 4184 deal_with_reference(ref); 4185 } 4186 } while (!refs()->is_empty()); 4187 } 4188 4189 G1ParClosureSuper::G1ParClosureSuper(G1CollectedHeap* g1, G1ParScanThreadState* par_scan_state) : 4190 _g1(g1), _g1_rem(_g1->g1_rem_set()), _cm(_g1->concurrent_mark()), 4191 _par_scan_state(par_scan_state) { } 4192 4193 template <class T> void G1ParCopyHelper::mark_forwardee(T* p) { 4194 // This is called _after_ do_oop_work has been called, hence after 4195 // the object has been relocated to its new location and *p points 4196 // to its new location. 4197 4198 T heap_oop = oopDesc::load_heap_oop(p); 4199 if (!oopDesc::is_null(heap_oop)) { 4200 oop obj = oopDesc::decode_heap_oop(heap_oop); 4201 HeapWord* addr = (HeapWord*)obj; 4202 if (_g1->is_in_g1_reserved(addr)) { 4203 _cm->grayRoot(oop(addr)); 4204 } 4205 } 4206 } 4207 4208 oop G1ParCopyHelper::copy_to_survivor_space(oop old) { 4209 size_t word_sz = old->size(); 4210 HeapRegion* from_region = _g1->heap_region_containing_raw(old); 4211 // +1 to make the -1 indexes valid... 4212 int young_index = from_region->young_index_in_cset()+1; 4213 assert( (from_region->is_young() && young_index > 0) || 4214 (!from_region->is_young() && young_index == 0), "invariant" ); 4215 G1CollectorPolicy* g1p = _g1->g1_policy(); 4216 markOop m = old->mark(); 4217 int age = m->has_displaced_mark_helper() ? m->displaced_mark_helper()->age() 4218 : m->age(); 4219 GCAllocPurpose alloc_purpose = g1p->evacuation_destination(from_region, age, 4220 word_sz); 4221 HeapWord* obj_ptr = _par_scan_state->allocate(alloc_purpose, word_sz); 4222 oop obj = oop(obj_ptr); 4223 4224 if (obj_ptr == NULL) { 4225 // This will either forward-to-self, or detect that someone else has 4226 // installed a forwarding pointer. 4227 OopsInHeapRegionClosure* cl = _par_scan_state->evac_failure_closure(); 4228 return _g1->handle_evacuation_failure_par(cl, old); 4229 } 4230 4231 // We're going to allocate linearly, so might as well prefetch ahead. 4232 Prefetch::write(obj_ptr, PrefetchCopyIntervalInBytes); 4233 4234 oop forward_ptr = old->forward_to_atomic(obj); 4235 if (forward_ptr == NULL) { 4236 Copy::aligned_disjoint_words((HeapWord*) old, obj_ptr, word_sz); 4237 if (g1p->track_object_age(alloc_purpose)) { 4238 // We could simply do obj->incr_age(). However, this causes a 4239 // performance issue. obj->incr_age() will first check whether 4240 // the object has a displaced mark by checking its mark word; 4241 // getting the mark word from the new location of the object 4242 // stalls. So, given that we already have the mark word and we 4243 // are about to install it anyway, it's better to increase the 4244 // age on the mark word, when the object does not have a 4245 // displaced mark word. We're not expecting many objects to have 4246 // a displaced marked word, so that case is not optimized 4247 // further (it could be...) and we simply call obj->incr_age(). 4248 4249 if (m->has_displaced_mark_helper()) { 4250 // in this case, we have to install the mark word first, 4251 // otherwise obj looks to be forwarded (the old mark word, 4252 // which contains the forward pointer, was copied) 4253 obj->set_mark(m); 4254 obj->incr_age(); 4255 } else { 4256 m = m->incr_age(); 4257 obj->set_mark(m); 4258 } 4259 _par_scan_state->age_table()->add(obj, word_sz); 4260 } else { 4261 obj->set_mark(m); 4262 } 4263 4264 // preserve "next" mark bit 4265 if (_g1->mark_in_progress() && !_g1->is_obj_ill(old)) { 4266 if (!use_local_bitmaps || 4267 !_par_scan_state->alloc_buffer(alloc_purpose)->mark(obj_ptr)) { 4268 // if we couldn't mark it on the local bitmap (this happens when 4269 // the object was not allocated in the GCLab), we have to bite 4270 // the bullet and do the standard parallel mark 4271 _cm->markAndGrayObjectIfNecessary(obj); 4272 } 4273 #if 1 4274 if (_g1->isMarkedNext(old)) { 4275 _cm->nextMarkBitMap()->parClear((HeapWord*)old); 4276 } 4277 #endif 4278 } 4279 4280 size_t* surv_young_words = _par_scan_state->surviving_young_words(); 4281 surv_young_words[young_index] += word_sz; 4282 4283 if (obj->is_objArray() && arrayOop(obj)->length() >= ParGCArrayScanChunk) { 4284 arrayOop(old)->set_length(0); 4285 oop* old_p = set_partial_array_mask(old); 4286 _par_scan_state->push_on_queue(old_p); 4287 } else { 4288 // No point in using the slower heap_region_containing() method, 4289 // given that we know obj is in the heap. 4290 _scanner->set_region(_g1->heap_region_containing_raw(obj)); 4291 obj->oop_iterate_backwards(_scanner); 4292 } 4293 } else { 4294 _par_scan_state->undo_allocation(alloc_purpose, obj_ptr, word_sz); 4295 obj = forward_ptr; 4296 } 4297 return obj; 4298 } 4299 4300 template <bool do_gen_barrier, G1Barrier barrier, bool do_mark_forwardee> 4301 template <class T> 4302 void G1ParCopyClosure <do_gen_barrier, barrier, do_mark_forwardee> 4303 ::do_oop_work(T* p) { 4304 oop obj = oopDesc::load_decode_heap_oop(p); 4305 assert(barrier != G1BarrierRS || obj != NULL, 4306 "Precondition: G1BarrierRS implies obj is nonNull"); 4307 4308 // here the null check is implicit in the cset_fast_test() test 4309 if (_g1->in_cset_fast_test(obj)) { 4310 if (obj->is_forwarded()) { 4311 oopDesc::encode_store_heap_oop(p, obj->forwardee()); 4312 } else { 4313 oop copy_oop = copy_to_survivor_space(obj); 4314 oopDesc::encode_store_heap_oop(p, copy_oop); 4315 } 4316 // When scanning the RS, we only care about objs in CS. 4317 if (barrier == G1BarrierRS) { 4318 _par_scan_state->update_rs(_from, p, _par_scan_state->queue_num()); 4319 } 4320 } 4321 4322 if (barrier == G1BarrierEvac && obj != NULL) { 4323 _par_scan_state->update_rs(_from, p, _par_scan_state->queue_num()); 4324 } 4325 4326 if (do_gen_barrier && obj != NULL) { 4327 par_do_barrier(p); 4328 } 4329 } 4330 4331 template void G1ParCopyClosure<false, G1BarrierEvac, false>::do_oop_work(oop* p); 4332 template void G1ParCopyClosure<false, G1BarrierEvac, false>::do_oop_work(narrowOop* p); 4333 4334 template <class T> void G1ParScanPartialArrayClosure::do_oop_nv(T* p) { 4335 assert(has_partial_array_mask(p), "invariant"); 4336 oop old = clear_partial_array_mask(p); 4337 assert(old->is_objArray(), "must be obj array"); 4338 assert(old->is_forwarded(), "must be forwarded"); 4339 assert(Universe::heap()->is_in_reserved(old), "must be in heap."); 4340 4341 objArrayOop obj = objArrayOop(old->forwardee()); 4342 assert((void*)old != (void*)old->forwardee(), "self forwarding here?"); 4343 // Process ParGCArrayScanChunk elements now 4344 // and push the remainder back onto queue 4345 int start = arrayOop(old)->length(); 4346 int end = obj->length(); 4347 int remainder = end - start; 4348 assert(start <= end, "just checking"); 4349 if (remainder > 2 * ParGCArrayScanChunk) { 4350 // Test above combines last partial chunk with a full chunk 4351 end = start + ParGCArrayScanChunk; 4352 arrayOop(old)->set_length(end); 4353 // Push remainder. 4354 oop* old_p = set_partial_array_mask(old); 4355 assert(arrayOop(old)->length() < obj->length(), "Empty push?"); 4356 _par_scan_state->push_on_queue(old_p); 4357 } else { 4358 // Restore length so that the heap remains parsable in 4359 // case of evacuation failure. 4360 arrayOop(old)->set_length(end); 4361 } 4362 _scanner.set_region(_g1->heap_region_containing_raw(obj)); 4363 // process our set of indices (include header in first chunk) 4364 obj->oop_iterate_range(&_scanner, start, end); 4365 } 4366 4367 class G1ParEvacuateFollowersClosure : public VoidClosure { 4368 protected: 4369 G1CollectedHeap* _g1h; 4370 G1ParScanThreadState* _par_scan_state; 4371 RefToScanQueueSet* _queues; 4372 ParallelTaskTerminator* _terminator; 4373 4374 G1ParScanThreadState* par_scan_state() { return _par_scan_state; } 4375 RefToScanQueueSet* queues() { return _queues; } 4376 ParallelTaskTerminator* terminator() { return _terminator; } 4377 4378 public: 4379 G1ParEvacuateFollowersClosure(G1CollectedHeap* g1h, 4380 G1ParScanThreadState* par_scan_state, 4381 RefToScanQueueSet* queues, 4382 ParallelTaskTerminator* terminator) 4383 : _g1h(g1h), _par_scan_state(par_scan_state), 4384 _queues(queues), _terminator(terminator) {} 4385 4386 void do_void(); 4387 4388 private: 4389 inline bool offer_termination(); 4390 }; 4391 4392 bool G1ParEvacuateFollowersClosure::offer_termination() { 4393 G1ParScanThreadState* const pss = par_scan_state(); 4394 pss->start_term_time(); 4395 const bool res = terminator()->offer_termination(); 4396 pss->end_term_time(); 4397 return res; 4398 } 4399 4400 void G1ParEvacuateFollowersClosure::do_void() { 4401 StarTask stolen_task; 4402 G1ParScanThreadState* const pss = par_scan_state(); 4403 pss->trim_queue(); 4404 4405 do { 4406 while (queues()->steal(pss->queue_num(), pss->hash_seed(), stolen_task)) { 4407 assert(pss->verify_task(stolen_task), "sanity"); 4408 if (stolen_task.is_narrow()) { 4409 pss->deal_with_reference((narrowOop*) stolen_task); 4410 } else { 4411 pss->deal_with_reference((oop*) stolen_task); 4412 } 4413 4414 // We've just processed a reference and we might have made 4415 // available new entries on the queues. So we have to make sure 4416 // we drain the queues as necessary. 4417 pss->trim_queue(); 4418 } 4419 } while (!offer_termination()); 4420 4421 pss->retire_alloc_buffers(); 4422 } 4423 4424 class G1ParTask : public AbstractGangTask { 4425 protected: 4426 G1CollectedHeap* _g1h; 4427 RefToScanQueueSet *_queues; 4428 ParallelTaskTerminator _terminator; 4429 int _n_workers; 4430 4431 Mutex _stats_lock; 4432 Mutex* stats_lock() { return &_stats_lock; } 4433 4434 size_t getNCards() { 4435 return (_g1h->capacity() + G1BlockOffsetSharedArray::N_bytes - 1) 4436 / G1BlockOffsetSharedArray::N_bytes; 4437 } 4438 4439 public: 4440 G1ParTask(G1CollectedHeap* g1h, int workers, RefToScanQueueSet *task_queues) 4441 : AbstractGangTask("G1 collection"), 4442 _g1h(g1h), 4443 _queues(task_queues), 4444 _terminator(workers, _queues), 4445 _stats_lock(Mutex::leaf, "parallel G1 stats lock", true), 4446 _n_workers(workers) 4447 {} 4448 4449 RefToScanQueueSet* queues() { return _queues; } 4450 4451 RefToScanQueue *work_queue(int i) { 4452 return queues()->queue(i); 4453 } 4454 4455 void work(int i) { 4456 if (i >= _n_workers) return; // no work needed this round 4457 4458 double start_time_ms = os::elapsedTime() * 1000.0; 4459 _g1h->g1_policy()->record_gc_worker_start_time(i, start_time_ms); 4460 4461 ResourceMark rm; 4462 HandleMark hm; 4463 4464 G1ParScanThreadState pss(_g1h, i); 4465 G1ParScanHeapEvacClosure scan_evac_cl(_g1h, &pss); 4466 G1ParScanHeapEvacFailureClosure evac_failure_cl(_g1h, &pss); 4467 G1ParScanPartialArrayClosure partial_scan_cl(_g1h, &pss); 4468 4469 pss.set_evac_closure(&scan_evac_cl); 4470 pss.set_evac_failure_closure(&evac_failure_cl); 4471 pss.set_partial_scan_closure(&partial_scan_cl); 4472 4473 G1ParScanExtRootClosure only_scan_root_cl(_g1h, &pss); 4474 G1ParScanPermClosure only_scan_perm_cl(_g1h, &pss); 4475 G1ParScanHeapRSClosure only_scan_heap_rs_cl(_g1h, &pss); 4476 G1ParPushHeapRSClosure push_heap_rs_cl(_g1h, &pss); 4477 4478 G1ParScanAndMarkExtRootClosure scan_mark_root_cl(_g1h, &pss); 4479 G1ParScanAndMarkPermClosure scan_mark_perm_cl(_g1h, &pss); 4480 G1ParScanAndMarkHeapRSClosure scan_mark_heap_rs_cl(_g1h, &pss); 4481 4482 OopsInHeapRegionClosure *scan_root_cl; 4483 OopsInHeapRegionClosure *scan_perm_cl; 4484 4485 if (_g1h->g1_policy()->during_initial_mark_pause()) { 4486 scan_root_cl = &scan_mark_root_cl; 4487 scan_perm_cl = &scan_mark_perm_cl; 4488 } else { 4489 scan_root_cl = &only_scan_root_cl; 4490 scan_perm_cl = &only_scan_perm_cl; 4491 } 4492 4493 pss.start_strong_roots(); 4494 _g1h->g1_process_strong_roots(/* not collecting perm */ false, 4495 SharedHeap::SO_AllClasses, 4496 scan_root_cl, 4497 &push_heap_rs_cl, 4498 scan_perm_cl, 4499 i); 4500 pss.end_strong_roots(); 4501 4502 { 4503 double start = os::elapsedTime(); 4504 G1ParEvacuateFollowersClosure evac(_g1h, &pss, _queues, &_terminator); 4505 evac.do_void(); 4506 double elapsed_ms = (os::elapsedTime()-start)*1000.0; 4507 double term_ms = pss.term_time()*1000.0; 4508 _g1h->g1_policy()->record_obj_copy_time(i, elapsed_ms-term_ms); 4509 _g1h->g1_policy()->record_termination(i, term_ms, pss.term_attempts()); 4510 } 4511 _g1h->g1_policy()->record_thread_age_table(pss.age_table()); 4512 _g1h->update_surviving_young_words(pss.surviving_young_words()+1); 4513 4514 // Clean up any par-expanded rem sets. 4515 HeapRegionRemSet::par_cleanup(); 4516 4517 if (ParallelGCVerbose) { 4518 MutexLocker x(stats_lock()); 4519 pss.print_termination_stats(i); 4520 } 4521 4522 assert(pss.refs()->is_empty(), "should be empty"); 4523 double end_time_ms = os::elapsedTime() * 1000.0; 4524 _g1h->g1_policy()->record_gc_worker_end_time(i, end_time_ms); 4525 } 4526 }; 4527 4528 // *** Common G1 Evacuation Stuff 4529 4530 // This method is run in a GC worker. 4531 4532 void 4533 G1CollectedHeap:: 4534 g1_process_strong_roots(bool collecting_perm_gen, 4535 SharedHeap::ScanningOption so, 4536 OopClosure* scan_non_heap_roots, 4537 OopsInHeapRegionClosure* scan_rs, 4538 OopsInGenClosure* scan_perm, 4539 int worker_i) { 4540 // First scan the strong roots, including the perm gen. 4541 double ext_roots_start = os::elapsedTime(); 4542 double closure_app_time_sec = 0.0; 4543 4544 BufferingOopClosure buf_scan_non_heap_roots(scan_non_heap_roots); 4545 BufferingOopsInGenClosure buf_scan_perm(scan_perm); 4546 buf_scan_perm.set_generation(perm_gen()); 4547 4548 // Walk the code cache w/o buffering, because StarTask cannot handle 4549 // unaligned oop locations. 4550 CodeBlobToOopClosure eager_scan_code_roots(scan_non_heap_roots, /*do_marking=*/ true); 4551 4552 process_strong_roots(false, // no scoping; this is parallel code 4553 collecting_perm_gen, so, 4554 &buf_scan_non_heap_roots, 4555 &eager_scan_code_roots, 4556 &buf_scan_perm); 4557 4558 // Now the ref_processor roots. 4559 if (!_process_strong_tasks->is_task_claimed(G1H_PS_refProcessor_oops_do)) { 4560 // We need to treat the discovered reference lists as roots and 4561 // keep entries (which are added by the marking threads) on them 4562 // live until they can be processed at the end of marking. 4563 ref_processor()->weak_oops_do(&buf_scan_non_heap_roots); 4564 ref_processor()->oops_do(&buf_scan_non_heap_roots); 4565 } 4566 4567 // Finish up any enqueued closure apps (attributed as object copy time). 4568 buf_scan_non_heap_roots.done(); 4569 buf_scan_perm.done(); 4570 4571 double ext_roots_end = os::elapsedTime(); 4572 4573 g1_policy()->reset_obj_copy_time(worker_i); 4574 double obj_copy_time_sec = buf_scan_perm.closure_app_seconds() + 4575 buf_scan_non_heap_roots.closure_app_seconds(); 4576 g1_policy()->record_obj_copy_time(worker_i, obj_copy_time_sec * 1000.0); 4577 4578 double ext_root_time_ms = 4579 ((ext_roots_end - ext_roots_start) - obj_copy_time_sec) * 1000.0; 4580 4581 g1_policy()->record_ext_root_scan_time(worker_i, ext_root_time_ms); 4582 4583 // Scan strong roots in mark stack. 4584 if (!_process_strong_tasks->is_task_claimed(G1H_PS_mark_stack_oops_do)) { 4585 concurrent_mark()->oops_do(scan_non_heap_roots); 4586 } 4587 double mark_stack_scan_ms = (os::elapsedTime() - ext_roots_end) * 1000.0; 4588 g1_policy()->record_mark_stack_scan_time(worker_i, mark_stack_scan_ms); 4589 4590 // Now scan the complement of the collection set. 4591 if (scan_rs != NULL) { 4592 g1_rem_set()->oops_into_collection_set_do(scan_rs, worker_i); 4593 } 4594 4595 _process_strong_tasks->all_tasks_completed(); 4596 } 4597 4598 void 4599 G1CollectedHeap::g1_process_weak_roots(OopClosure* root_closure, 4600 OopClosure* non_root_closure) { 4601 CodeBlobToOopClosure roots_in_blobs(root_closure, /*do_marking=*/ false); 4602 SharedHeap::process_weak_roots(root_closure, &roots_in_blobs, non_root_closure); 4603 } 4604 4605 void G1CollectedHeap::evacuate_collection_set() { 4606 set_evacuation_failed(false); 4607 4608 g1_rem_set()->prepare_for_oops_into_collection_set_do(); 4609 concurrent_g1_refine()->set_use_cache(false); 4610 concurrent_g1_refine()->clear_hot_cache_claimed_index(); 4611 4612 int n_workers = (ParallelGCThreads > 0 ? workers()->total_workers() : 1); 4613 set_par_threads(n_workers); 4614 G1ParTask g1_par_task(this, n_workers, _task_queues); 4615 4616 init_for_evac_failure(NULL); 4617 4618 rem_set()->prepare_for_younger_refs_iterate(true); 4619 4620 assert(dirty_card_queue_set().completed_buffers_num() == 0, "Should be empty"); 4621 double start_par = os::elapsedTime(); 4622 if (G1CollectedHeap::use_parallel_gc_threads()) { 4623 // The individual threads will set their evac-failure closures. 4624 StrongRootsScope srs(this); 4625 if (ParallelGCVerbose) G1ParScanThreadState::print_termination_stats_hdr(); 4626 workers()->run_task(&g1_par_task); 4627 } else { 4628 StrongRootsScope srs(this); 4629 g1_par_task.work(0); 4630 } 4631 4632 double par_time = (os::elapsedTime() - start_par) * 1000.0; 4633 g1_policy()->record_par_time(par_time); 4634 set_par_threads(0); 4635 4636 // Weak root processing. 4637 // Note: when JSR 292 is enabled and code blobs can contain 4638 // non-perm oops then we will need to process the code blobs 4639 // here too. 4640 { 4641 G1IsAliveClosure is_alive(this); 4642 G1KeepAliveClosure keep_alive(this); 4643 JNIHandles::weak_oops_do(&is_alive, &keep_alive); 4644 } 4645 release_gc_alloc_regions(); 4646 g1_rem_set()->cleanup_after_oops_into_collection_set_do(); 4647 4648 concurrent_g1_refine()->clear_hot_cache(); 4649 concurrent_g1_refine()->set_use_cache(true); 4650 4651 finalize_for_evac_failure(); 4652 4653 // Must do this before removing self-forwarding pointers, which clears 4654 // the per-region evac-failure flags. 4655 concurrent_mark()->complete_marking_in_collection_set(); 4656 4657 if (evacuation_failed()) { 4658 remove_self_forwarding_pointers(); 4659 if (PrintGCDetails) { 4660 gclog_or_tty->print(" (to-space overflow)"); 4661 } else if (PrintGC) { 4662 gclog_or_tty->print("--"); 4663 } 4664 } 4665 4666 if (G1DeferredRSUpdate) { 4667 RedirtyLoggedCardTableEntryFastClosure redirty; 4668 dirty_card_queue_set().set_closure(&redirty); 4669 dirty_card_queue_set().apply_closure_to_all_completed_buffers(); 4670 4671 DirtyCardQueueSet& dcq = JavaThread::dirty_card_queue_set(); 4672 dcq.merge_bufferlists(&dirty_card_queue_set()); 4673 assert(dirty_card_queue_set().completed_buffers_num() == 0, "All should be consumed"); 4674 } 4675 COMPILER2_PRESENT(DerivedPointerTable::update_pointers()); 4676 } 4677 4678 void G1CollectedHeap::free_region_if_empty(HeapRegion* hr, 4679 size_t* pre_used, 4680 FreeRegionList* free_list, 4681 HumongousRegionSet* humongous_proxy_set, 4682 HRRSCleanupTask* hrrs_cleanup_task, 4683 bool par) { 4684 if (hr->used() > 0 && hr->max_live_bytes() == 0 && !hr->is_young()) { 4685 if (hr->isHumongous()) { 4686 assert(hr->startsHumongous(), "we should only see starts humongous"); 4687 free_humongous_region(hr, pre_used, free_list, humongous_proxy_set, par); 4688 } else { 4689 free_region(hr, pre_used, free_list, par); 4690 } 4691 } else { 4692 hr->rem_set()->do_cleanup_work(hrrs_cleanup_task); 4693 } 4694 } 4695 4696 void G1CollectedHeap::free_region(HeapRegion* hr, 4697 size_t* pre_used, 4698 FreeRegionList* free_list, 4699 bool par) { 4700 assert(!hr->isHumongous(), "this is only for non-humongous regions"); 4701 assert(!hr->is_empty(), "the region should not be empty"); 4702 assert(free_list != NULL, "pre-condition"); 4703 4704 *pre_used += hr->used(); 4705 hr->hr_clear(par, true /* clear_space */); 4706 free_list->add_as_head(hr); 4707 } 4708 4709 void G1CollectedHeap::free_humongous_region(HeapRegion* hr, 4710 size_t* pre_used, 4711 FreeRegionList* free_list, 4712 HumongousRegionSet* humongous_proxy_set, 4713 bool par) { 4714 assert(hr->startsHumongous(), "this is only for starts humongous regions"); 4715 assert(free_list != NULL, "pre-condition"); 4716 assert(humongous_proxy_set != NULL, "pre-condition"); 4717 4718 size_t hr_used = hr->used(); 4719 size_t hr_capacity = hr->capacity(); 4720 size_t hr_pre_used = 0; 4721 _humongous_set.remove_with_proxy(hr, humongous_proxy_set); 4722 hr->set_notHumongous(); 4723 free_region(hr, &hr_pre_used, free_list, par); 4724 4725 size_t i = hr->hrs_index() + 1; 4726 size_t num = 1; 4727 while (i < n_regions()) { 4728 HeapRegion* curr_hr = region_at(i); 4729 if (!curr_hr->continuesHumongous()) { 4730 break; 4731 } 4732 curr_hr->set_notHumongous(); 4733 free_region(curr_hr, &hr_pre_used, free_list, par); 4734 num += 1; 4735 i += 1; 4736 } 4737 assert(hr_pre_used == hr_used, 4738 err_msg("hr_pre_used: "SIZE_FORMAT" and hr_used: "SIZE_FORMAT" " 4739 "should be the same", hr_pre_used, hr_used)); 4740 *pre_used += hr_pre_used; 4741 } 4742 4743 void G1CollectedHeap::update_sets_after_freeing_regions(size_t pre_used, 4744 FreeRegionList* free_list, 4745 HumongousRegionSet* humongous_proxy_set, 4746 bool par) { 4747 if (pre_used > 0) { 4748 Mutex* lock = (par) ? ParGCRareEvent_lock : NULL; 4749 MutexLockerEx x(lock, Mutex::_no_safepoint_check_flag); 4750 assert(_summary_bytes_used >= pre_used, 4751 err_msg("invariant: _summary_bytes_used: "SIZE_FORMAT" " 4752 "should be >= pre_used: "SIZE_FORMAT, 4753 _summary_bytes_used, pre_used)); 4754 _summary_bytes_used -= pre_used; 4755 } 4756 if (free_list != NULL && !free_list->is_empty()) { 4757 MutexLockerEx x(FreeList_lock, Mutex::_no_safepoint_check_flag); 4758 _free_list.add_as_head(free_list); 4759 } 4760 if (humongous_proxy_set != NULL && !humongous_proxy_set->is_empty()) { 4761 MutexLockerEx x(OldSets_lock, Mutex::_no_safepoint_check_flag); 4762 _humongous_set.update_from_proxy(humongous_proxy_set); 4763 } 4764 } 4765 4766 class G1ParCleanupCTTask : public AbstractGangTask { 4767 CardTableModRefBS* _ct_bs; 4768 G1CollectedHeap* _g1h; 4769 HeapRegion* volatile _su_head; 4770 public: 4771 G1ParCleanupCTTask(CardTableModRefBS* ct_bs, 4772 G1CollectedHeap* g1h) : 4773 AbstractGangTask("G1 Par Cleanup CT Task"), 4774 _ct_bs(ct_bs), _g1h(g1h) { } 4775 4776 void work(int i) { 4777 HeapRegion* r; 4778 while (r = _g1h->pop_dirty_cards_region()) { 4779 clear_cards(r); 4780 } 4781 } 4782 4783 void clear_cards(HeapRegion* r) { 4784 // Cards of the survivors should have already been dirtied. 4785 if (!r->is_survivor()) { 4786 _ct_bs->clear(MemRegion(r->bottom(), r->end())); 4787 } 4788 } 4789 }; 4790 4791 #ifndef PRODUCT 4792 class G1VerifyCardTableCleanup: public HeapRegionClosure { 4793 G1CollectedHeap* _g1h; 4794 CardTableModRefBS* _ct_bs; 4795 public: 4796 G1VerifyCardTableCleanup(G1CollectedHeap* g1h, CardTableModRefBS* ct_bs) 4797 : _g1h(g1h), _ct_bs(ct_bs) { } 4798 virtual bool doHeapRegion(HeapRegion* r) { 4799 if (r->is_survivor()) { 4800 _g1h->verify_dirty_region(r); 4801 } else { 4802 _g1h->verify_not_dirty_region(r); 4803 } 4804 return false; 4805 } 4806 }; 4807 4808 void G1CollectedHeap::verify_not_dirty_region(HeapRegion* hr) { 4809 // All of the region should be clean. 4810 CardTableModRefBS* ct_bs = (CardTableModRefBS*)barrier_set(); 4811 MemRegion mr(hr->bottom(), hr->end()); 4812 ct_bs->verify_not_dirty_region(mr); 4813 } 4814 4815 void G1CollectedHeap::verify_dirty_region(HeapRegion* hr) { 4816 // We cannot guarantee that [bottom(),end()] is dirty. Threads 4817 // dirty allocated blocks as they allocate them. The thread that 4818 // retires each region and replaces it with a new one will do a 4819 // maximal allocation to fill in [pre_dummy_top(),end()] but will 4820 // not dirty that area (one less thing to have to do while holding 4821 // a lock). So we can only verify that [bottom(),pre_dummy_top()] 4822 // is dirty. 4823 CardTableModRefBS* ct_bs = (CardTableModRefBS*) barrier_set(); 4824 MemRegion mr(hr->bottom(), hr->pre_dummy_top()); 4825 ct_bs->verify_dirty_region(mr); 4826 } 4827 4828 void G1CollectedHeap::verify_dirty_young_list(HeapRegion* head) { 4829 CardTableModRefBS* ct_bs = (CardTableModRefBS*) barrier_set(); 4830 for (HeapRegion* hr = head; hr != NULL; hr = hr->get_next_young_region()) { 4831 verify_dirty_region(hr); 4832 } 4833 } 4834 4835 void G1CollectedHeap::verify_dirty_young_regions() { 4836 verify_dirty_young_list(_young_list->first_region()); 4837 verify_dirty_young_list(_young_list->first_survivor_region()); 4838 } 4839 #endif 4840 4841 void G1CollectedHeap::cleanUpCardTable() { 4842 CardTableModRefBS* ct_bs = (CardTableModRefBS*) (barrier_set()); 4843 double start = os::elapsedTime(); 4844 4845 // Iterate over the dirty cards region list. 4846 G1ParCleanupCTTask cleanup_task(ct_bs, this); 4847 4848 if (ParallelGCThreads > 0) { 4849 set_par_threads(workers()->total_workers()); 4850 workers()->run_task(&cleanup_task); 4851 set_par_threads(0); 4852 } else { 4853 while (_dirty_cards_region_list) { 4854 HeapRegion* r = _dirty_cards_region_list; 4855 cleanup_task.clear_cards(r); 4856 _dirty_cards_region_list = r->get_next_dirty_cards_region(); 4857 if (_dirty_cards_region_list == r) { 4858 // The last region. 4859 _dirty_cards_region_list = NULL; 4860 } 4861 r->set_next_dirty_cards_region(NULL); 4862 } 4863 } 4864 4865 double elapsed = os::elapsedTime() - start; 4866 g1_policy()->record_clear_ct_time( elapsed * 1000.0); 4867 #ifndef PRODUCT 4868 if (G1VerifyCTCleanup || VerifyAfterGC) { 4869 G1VerifyCardTableCleanup cleanup_verifier(this, ct_bs); 4870 heap_region_iterate(&cleanup_verifier); 4871 } 4872 #endif 4873 } 4874 4875 void G1CollectedHeap::free_collection_set(HeapRegion* cs_head) { 4876 size_t pre_used = 0; 4877 FreeRegionList local_free_list("Local List for CSet Freeing"); 4878 4879 double young_time_ms = 0.0; 4880 double non_young_time_ms = 0.0; 4881 4882 // Since the collection set is a superset of the the young list, 4883 // all we need to do to clear the young list is clear its 4884 // head and length, and unlink any young regions in the code below 4885 _young_list->clear(); 4886 4887 G1CollectorPolicy* policy = g1_policy(); 4888 4889 double start_sec = os::elapsedTime(); 4890 bool non_young = true; 4891 4892 HeapRegion* cur = cs_head; 4893 int age_bound = -1; 4894 size_t rs_lengths = 0; 4895 4896 while (cur != NULL) { 4897 assert(!is_on_master_free_list(cur), "sanity"); 4898 4899 if (non_young) { 4900 if (cur->is_young()) { 4901 double end_sec = os::elapsedTime(); 4902 double elapsed_ms = (end_sec - start_sec) * 1000.0; 4903 non_young_time_ms += elapsed_ms; 4904 4905 start_sec = os::elapsedTime(); 4906 non_young = false; 4907 } 4908 } else { 4909 double end_sec = os::elapsedTime(); 4910 double elapsed_ms = (end_sec - start_sec) * 1000.0; 4911 young_time_ms += elapsed_ms; 4912 4913 start_sec = os::elapsedTime(); 4914 non_young = true; 4915 } 4916 4917 rs_lengths += cur->rem_set()->occupied(); 4918 4919 HeapRegion* next = cur->next_in_collection_set(); 4920 assert(cur->in_collection_set(), "bad CS"); 4921 cur->set_next_in_collection_set(NULL); 4922 cur->set_in_collection_set(false); 4923 4924 if (cur->is_young()) { 4925 int index = cur->young_index_in_cset(); 4926 guarantee( index != -1, "invariant" ); 4927 guarantee( (size_t)index < policy->young_cset_length(), "invariant" ); 4928 size_t words_survived = _surviving_young_words[index]; 4929 cur->record_surv_words_in_group(words_survived); 4930 4931 // At this point the we have 'popped' cur from the collection set 4932 // (linked via next_in_collection_set()) but it is still in the 4933 // young list (linked via next_young_region()). Clear the 4934 // _next_young_region field. 4935 cur->set_next_young_region(NULL); 4936 } else { 4937 int index = cur->young_index_in_cset(); 4938 guarantee( index == -1, "invariant" ); 4939 } 4940 4941 assert( (cur->is_young() && cur->young_index_in_cset() > -1) || 4942 (!cur->is_young() && cur->young_index_in_cset() == -1), 4943 "invariant" ); 4944 4945 if (!cur->evacuation_failed()) { 4946 // And the region is empty. 4947 assert(!cur->is_empty(), "Should not have empty regions in a CS."); 4948 free_region(cur, &pre_used, &local_free_list, false /* par */); 4949 } else { 4950 cur->uninstall_surv_rate_group(); 4951 if (cur->is_young()) 4952 cur->set_young_index_in_cset(-1); 4953 cur->set_not_young(); 4954 cur->set_evacuation_failed(false); 4955 } 4956 cur = next; 4957 } 4958 4959 policy->record_max_rs_lengths(rs_lengths); 4960 policy->cset_regions_freed(); 4961 4962 double end_sec = os::elapsedTime(); 4963 double elapsed_ms = (end_sec - start_sec) * 1000.0; 4964 if (non_young) 4965 non_young_time_ms += elapsed_ms; 4966 else 4967 young_time_ms += elapsed_ms; 4968 4969 update_sets_after_freeing_regions(pre_used, &local_free_list, 4970 NULL /* humongous_proxy_set */, 4971 false /* par */); 4972 policy->record_young_free_cset_time_ms(young_time_ms); 4973 policy->record_non_young_free_cset_time_ms(non_young_time_ms); 4974 } 4975 4976 // This routine is similar to the above but does not record 4977 // any policy statistics or update free lists; we are abandoning 4978 // the current incremental collection set in preparation of a 4979 // full collection. After the full GC we will start to build up 4980 // the incremental collection set again. 4981 // This is only called when we're doing a full collection 4982 // and is immediately followed by the tearing down of the young list. 4983 4984 void G1CollectedHeap::abandon_collection_set(HeapRegion* cs_head) { 4985 HeapRegion* cur = cs_head; 4986 4987 while (cur != NULL) { 4988 HeapRegion* next = cur->next_in_collection_set(); 4989 assert(cur->in_collection_set(), "bad CS"); 4990 cur->set_next_in_collection_set(NULL); 4991 cur->set_in_collection_set(false); 4992 cur->set_young_index_in_cset(-1); 4993 cur = next; 4994 } 4995 } 4996 4997 void G1CollectedHeap::set_free_regions_coming() { 4998 if (G1ConcRegionFreeingVerbose) { 4999 gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : " 5000 "setting free regions coming"); 5001 } 5002 5003 assert(!free_regions_coming(), "pre-condition"); 5004 _free_regions_coming = true; 5005 } 5006 5007 void G1CollectedHeap::reset_free_regions_coming() { 5008 { 5009 assert(free_regions_coming(), "pre-condition"); 5010 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag); 5011 _free_regions_coming = false; 5012 SecondaryFreeList_lock->notify_all(); 5013 } 5014 5015 if (G1ConcRegionFreeingVerbose) { 5016 gclog_or_tty->print_cr("G1ConcRegionFreeing [cm thread] : " 5017 "reset free regions coming"); 5018 } 5019 } 5020 5021 void G1CollectedHeap::wait_while_free_regions_coming() { 5022 // Most of the time we won't have to wait, so let's do a quick test 5023 // first before we take the lock. 5024 if (!free_regions_coming()) { 5025 return; 5026 } 5027 5028 if (G1ConcRegionFreeingVerbose) { 5029 gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : " 5030 "waiting for free regions"); 5031 } 5032 5033 { 5034 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag); 5035 while (free_regions_coming()) { 5036 SecondaryFreeList_lock->wait(Mutex::_no_safepoint_check_flag); 5037 } 5038 } 5039 5040 if (G1ConcRegionFreeingVerbose) { 5041 gclog_or_tty->print_cr("G1ConcRegionFreeing [other] : " 5042 "done waiting for free regions"); 5043 } 5044 } 5045 5046 void G1CollectedHeap::set_region_short_lived_locked(HeapRegion* hr) { 5047 assert(heap_lock_held_for_gc(), 5048 "the heap lock should already be held by or for this thread"); 5049 _young_list->push_region(hr); 5050 g1_policy()->set_region_short_lived(hr); 5051 } 5052 5053 class NoYoungRegionsClosure: public HeapRegionClosure { 5054 private: 5055 bool _success; 5056 public: 5057 NoYoungRegionsClosure() : _success(true) { } 5058 bool doHeapRegion(HeapRegion* r) { 5059 if (r->is_young()) { 5060 gclog_or_tty->print_cr("Region ["PTR_FORMAT", "PTR_FORMAT") tagged as young", 5061 r->bottom(), r->end()); 5062 _success = false; 5063 } 5064 return false; 5065 } 5066 bool success() { return _success; } 5067 }; 5068 5069 bool G1CollectedHeap::check_young_list_empty(bool check_heap, bool check_sample) { 5070 bool ret = _young_list->check_list_empty(check_sample); 5071 5072 if (check_heap) { 5073 NoYoungRegionsClosure closure; 5074 heap_region_iterate(&closure); 5075 ret = ret && closure.success(); 5076 } 5077 5078 return ret; 5079 } 5080 5081 void G1CollectedHeap::empty_young_list() { 5082 assert(heap_lock_held_for_gc(), 5083 "the heap lock should already be held by or for this thread"); 5084 5085 _young_list->empty_list(); 5086 } 5087 5088 // Done at the start of full GC. 5089 void G1CollectedHeap::tear_down_region_lists() { 5090 _free_list.remove_all(); 5091 } 5092 5093 class RegionResetter: public HeapRegionClosure { 5094 G1CollectedHeap* _g1h; 5095 FreeRegionList _local_free_list; 5096 5097 public: 5098 RegionResetter() : _g1h(G1CollectedHeap::heap()), 5099 _local_free_list("Local Free List for RegionResetter") { } 5100 5101 bool doHeapRegion(HeapRegion* r) { 5102 if (r->continuesHumongous()) return false; 5103 if (r->top() > r->bottom()) { 5104 if (r->top() < r->end()) { 5105 Copy::fill_to_words(r->top(), 5106 pointer_delta(r->end(), r->top())); 5107 } 5108 } else { 5109 assert(r->is_empty(), "tautology"); 5110 _local_free_list.add_as_tail(r); 5111 } 5112 return false; 5113 } 5114 5115 void update_free_lists() { 5116 _g1h->update_sets_after_freeing_regions(0, &_local_free_list, NULL, 5117 false /* par */); 5118 } 5119 }; 5120 5121 // Done at the end of full GC. 5122 void G1CollectedHeap::rebuild_region_lists() { 5123 // This needs to go at the end of the full GC. 5124 RegionResetter rs; 5125 heap_region_iterate(&rs); 5126 rs.update_free_lists(); 5127 } 5128 5129 void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) { 5130 _refine_cte_cl->set_concurrent(concurrent); 5131 } 5132 5133 bool G1CollectedHeap::is_in_closed_subset(const void* p) const { 5134 HeapRegion* hr = heap_region_containing(p); 5135 if (hr == NULL) { 5136 return is_in_permanent(p); 5137 } else { 5138 return hr->is_in(p); 5139 } 5140 } 5141 5142 // Methods for the mutator alloc region 5143 5144 HeapRegion* G1CollectedHeap::new_mutator_alloc_region(size_t word_size, 5145 bool force) { 5146 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */); 5147 assert(!force || g1_policy()->can_expand_young_list(), 5148 "if force is true we should be able to expand the young list"); 5149 bool young_list_full = g1_policy()->is_young_list_full(); 5150 if (force || !young_list_full) { 5151 HeapRegion* new_alloc_region = new_region(word_size, 5152 false /* do_expand */); 5153 if (new_alloc_region != NULL) { 5154 g1_policy()->update_region_num(true /* next_is_young */); 5155 set_region_short_lived_locked(new_alloc_region); 5156 _hr_printer.alloc(new_alloc_region, G1HRPrinter::Eden, young_list_full); 5157 g1mm()->update_eden_counters(); 5158 return new_alloc_region; 5159 } 5160 } 5161 return NULL; 5162 } 5163 5164 void G1CollectedHeap::retire_mutator_alloc_region(HeapRegion* alloc_region, 5165 size_t allocated_bytes) { 5166 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */); 5167 assert(alloc_region->is_young(), "all mutator alloc regions should be young"); 5168 5169 g1_policy()->add_region_to_incremental_cset_lhs(alloc_region); 5170 _summary_bytes_used += allocated_bytes; 5171 _hr_printer.retire(alloc_region); 5172 } 5173 5174 HeapRegion* MutatorAllocRegion::allocate_new_region(size_t word_size, 5175 bool force) { 5176 return _g1h->new_mutator_alloc_region(word_size, force); 5177 } 5178 5179 void MutatorAllocRegion::retire_region(HeapRegion* alloc_region, 5180 size_t allocated_bytes) { 5181 _g1h->retire_mutator_alloc_region(alloc_region, allocated_bytes); 5182 } 5183 5184 // Methods for the GC alloc regions 5185 5186 HeapRegion* G1CollectedHeap::new_gc_alloc_region(size_t word_size, 5187 size_t count, 5188 GCAllocPurpose ap) { 5189 assert(FreeList_lock->owned_by_self(), "pre-condition"); 5190 5191 if (count < g1_policy()->max_regions(ap)) { 5192 HeapRegion* new_alloc_region = new_region(word_size, 5193 true /* do_expand */); 5194 if (new_alloc_region != NULL) { 5195 // We really only need to do this for old regions given that we 5196 // should never scan survivors. But it doesn't hurt to do it 5197 // for survivors too. 5198 new_alloc_region->set_saved_mark(); 5199 if (ap == GCAllocForSurvived) { 5200 new_alloc_region->set_survivor(); 5201 _hr_printer.alloc(new_alloc_region, G1HRPrinter::Survivor); 5202 } else { 5203 _hr_printer.alloc(new_alloc_region, G1HRPrinter::Old); 5204 } 5205 return new_alloc_region; 5206 } else { 5207 g1_policy()->note_alloc_region_limit_reached(ap); 5208 } 5209 } 5210 return NULL; 5211 } 5212 5213 void G1CollectedHeap::retire_gc_alloc_region(HeapRegion* alloc_region, 5214 size_t allocated_bytes, 5215 GCAllocPurpose ap) { 5216 alloc_region->note_end_of_copying(); 5217 g1_policy()->record_bytes_copied_during_gc(allocated_bytes); 5218 if (ap == GCAllocForSurvived) { 5219 young_list()->add_survivor_region(alloc_region); 5220 } 5221 _hr_printer.retire(alloc_region); 5222 } 5223 5224 HeapRegion* SurvivorGCAllocRegion::allocate_new_region(size_t word_size, 5225 bool force) { 5226 assert(!force, "not supported for GC alloc regions"); 5227 return _g1h->new_gc_alloc_region(word_size, count(), GCAllocForSurvived); 5228 } 5229 5230 void SurvivorGCAllocRegion::retire_region(HeapRegion* alloc_region, 5231 size_t allocated_bytes) { 5232 _g1h->retire_gc_alloc_region(alloc_region, allocated_bytes, 5233 GCAllocForSurvived); 5234 } 5235 5236 HeapRegion* OldGCAllocRegion::allocate_new_region(size_t word_size, 5237 bool force) { 5238 assert(!force, "not supported for GC alloc regions"); 5239 return _g1h->new_gc_alloc_region(word_size, count(), GCAllocForTenured); 5240 } 5241 5242 void OldGCAllocRegion::retire_region(HeapRegion* alloc_region, 5243 size_t allocated_bytes) { 5244 _g1h->retire_gc_alloc_region(alloc_region, allocated_bytes, 5245 GCAllocForTenured); 5246 } 5247 // Heap region set verification 5248 5249 class VerifyRegionListsClosure : public HeapRegionClosure { 5250 private: 5251 HumongousRegionSet* _humongous_set; 5252 FreeRegionList* _free_list; 5253 size_t _region_count; 5254 5255 public: 5256 VerifyRegionListsClosure(HumongousRegionSet* humongous_set, 5257 FreeRegionList* free_list) : 5258 _humongous_set(humongous_set), _free_list(free_list), 5259 _region_count(0) { } 5260 5261 size_t region_count() { return _region_count; } 5262 5263 bool doHeapRegion(HeapRegion* hr) { 5264 _region_count += 1; 5265 5266 if (hr->continuesHumongous()) { 5267 return false; 5268 } 5269 5270 if (hr->is_young()) { 5271 // TODO 5272 } else if (hr->startsHumongous()) { 5273 _humongous_set->verify_next_region(hr); 5274 } else if (hr->is_empty()) { 5275 _free_list->verify_next_region(hr); 5276 } 5277 return false; 5278 } 5279 }; 5280 5281 HeapRegion* G1CollectedHeap::new_heap_region(size_t hrs_index, 5282 HeapWord* bottom) { 5283 HeapWord* end = bottom + HeapRegion::GrainWords; 5284 MemRegion mr(bottom, end); 5285 assert(_g1_reserved.contains(mr), "invariant"); 5286 // This might return NULL if the allocation fails 5287 return new HeapRegion(hrs_index, _bot_shared, mr, true /* is_zeroed */); 5288 } 5289 5290 void G1CollectedHeap::verify_region_sets() { 5291 assert_heap_locked_or_at_safepoint(true /* should_be_vm_thread */); 5292 5293 // First, check the explicit lists. 5294 _free_list.verify(); 5295 { 5296 // Given that a concurrent operation might be adding regions to 5297 // the secondary free list we have to take the lock before 5298 // verifying it. 5299 MutexLockerEx x(SecondaryFreeList_lock, Mutex::_no_safepoint_check_flag); 5300 _secondary_free_list.verify(); 5301 } 5302 _humongous_set.verify(); 5303 5304 // If a concurrent region freeing operation is in progress it will 5305 // be difficult to correctly attributed any free regions we come 5306 // across to the correct free list given that they might belong to 5307 // one of several (free_list, secondary_free_list, any local lists, 5308 // etc.). So, if that's the case we will skip the rest of the 5309 // verification operation. Alternatively, waiting for the concurrent 5310 // operation to complete will have a non-trivial effect on the GC's 5311 // operation (no concurrent operation will last longer than the 5312 // interval between two calls to verification) and it might hide 5313 // any issues that we would like to catch during testing. 5314 if (free_regions_coming()) { 5315 return; 5316 } 5317 5318 // Make sure we append the secondary_free_list on the free_list so 5319 // that all free regions we will come across can be safely 5320 // attributed to the free_list. 5321 append_secondary_free_list_if_not_empty_with_lock(); 5322 5323 // Finally, make sure that the region accounting in the lists is 5324 // consistent with what we see in the heap. 5325 _humongous_set.verify_start(); 5326 _free_list.verify_start(); 5327 5328 VerifyRegionListsClosure cl(&_humongous_set, &_free_list); 5329 heap_region_iterate(&cl); 5330 5331 _humongous_set.verify_end(); 5332 _free_list.verify_end(); 5333 }