1 /* 2 * Copyright (c) 2001, 2020, 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 "gc/serial/defNewGeneration.inline.hpp" 27 #include "gc/serial/serialHeap.inline.hpp" 28 #include "gc/serial/tenuredGeneration.hpp" 29 #include "gc/shared/adaptiveSizePolicy.hpp" 30 #include "gc/shared/ageTable.inline.hpp" 31 #include "gc/shared/cardTableRS.hpp" 32 #include "gc/shared/collectorCounters.hpp" 33 #include "gc/shared/gcArguments.hpp" 34 #include "gc/shared/gcHeapSummary.hpp" 35 #include "gc/shared/gcLocker.hpp" 36 #include "gc/shared/gcPolicyCounters.hpp" 37 #include "gc/shared/gcTimer.hpp" 38 #include "gc/shared/gcTrace.hpp" 39 #include "gc/shared/gcTraceTime.inline.hpp" 40 #include "gc/shared/genOopClosures.inline.hpp" 41 #include "gc/shared/generationSpec.hpp" 42 #include "gc/shared/preservedMarks.inline.hpp" 43 #include "gc/shared/referencePolicy.hpp" 44 #include "gc/shared/referenceProcessorPhaseTimes.hpp" 45 #include "gc/shared/space.inline.hpp" 46 #include "gc/shared/spaceDecorator.inline.hpp" 47 #include "gc/shared/strongRootsScope.hpp" 48 #include "gc/shared/weakProcessor.hpp" 49 #include "logging/log.hpp" 50 #include "memory/iterator.inline.hpp" 51 #include "memory/resourceArea.hpp" 52 #include "oops/instanceRefKlass.hpp" 53 #include "oops/oop.inline.hpp" 54 #include "runtime/java.hpp" 55 #include "runtime/prefetch.inline.hpp" 56 #include "runtime/thread.inline.hpp" 57 #include "utilities/align.hpp" 58 #include "utilities/copy.hpp" 59 #include "utilities/globalDefinitions.hpp" 60 #include "utilities/stack.inline.hpp" 61 62 // 63 // DefNewGeneration functions. 64 65 // Methods of protected closure types. 66 67 DefNewGeneration::IsAliveClosure::IsAliveClosure(Generation* young_gen) : _young_gen(young_gen) { 68 assert(_young_gen->kind() == Generation::DefNew, "Expected the young generation here"); 69 } 70 71 bool DefNewGeneration::IsAliveClosure::do_object_b(oop p) { 72 return cast_from_oop<HeapWord*>(p) >= _young_gen->reserved().end() || p->is_forwarded(); 73 } 74 75 DefNewGeneration::KeepAliveClosure:: 76 KeepAliveClosure(ScanWeakRefClosure* cl) : _cl(cl) { 77 _rs = GenCollectedHeap::heap()->rem_set(); 78 } 79 80 void DefNewGeneration::KeepAliveClosure::do_oop(oop* p) { DefNewGeneration::KeepAliveClosure::do_oop_work(p); } 81 void DefNewGeneration::KeepAliveClosure::do_oop(narrowOop* p) { DefNewGeneration::KeepAliveClosure::do_oop_work(p); } 82 83 84 DefNewGeneration::FastKeepAliveClosure:: 85 FastKeepAliveClosure(DefNewGeneration* g, ScanWeakRefClosure* cl) : 86 DefNewGeneration::KeepAliveClosure(cl) { 87 _boundary = g->reserved().end(); 88 } 89 90 void DefNewGeneration::FastKeepAliveClosure::do_oop(oop* p) { DefNewGeneration::FastKeepAliveClosure::do_oop_work(p); } 91 void DefNewGeneration::FastKeepAliveClosure::do_oop(narrowOop* p) { DefNewGeneration::FastKeepAliveClosure::do_oop_work(p); } 92 93 DefNewGeneration::FastEvacuateFollowersClosure:: 94 FastEvacuateFollowersClosure(SerialHeap* heap, 95 DefNewScanClosure* cur, 96 DefNewYoungerGenClosure* older) : 97 _heap(heap), _scan_cur_or_nonheap(cur), _scan_older(older) 98 { 99 } 100 101 void DefNewGeneration::FastEvacuateFollowersClosure::do_void() { 102 do { 103 _heap->oop_since_save_marks_iterate(_scan_cur_or_nonheap, _scan_older); 104 } while (!_heap->no_allocs_since_save_marks()); 105 guarantee(_heap->young_gen()->promo_failure_scan_is_complete(), "Failed to finish scan"); 106 } 107 108 void CLDScanClosure::do_cld(ClassLoaderData* cld) { 109 NOT_PRODUCT(ResourceMark rm); 110 log_develop_trace(gc, scavenge)("CLDScanClosure::do_cld " PTR_FORMAT ", %s, dirty: %s", 111 p2i(cld), 112 cld->loader_name_and_id(), 113 cld->has_modified_oops() ? "true" : "false"); 114 115 // If the cld has not been dirtied we know that there's 116 // no references into the young gen and we can skip it. 117 if (cld->has_modified_oops()) { 118 if (_accumulate_modified_oops) { 119 cld->accumulate_modified_oops(); 120 } 121 122 // Tell the closure which CLD is being scanned so that it can be dirtied 123 // if oops are left pointing into the young gen. 124 _scavenge_closure->set_scanned_cld(cld); 125 126 // Clean the cld since we're going to scavenge all the metadata. 127 cld->oops_do(_scavenge_closure, ClassLoaderData::_claim_none, /*clear_modified_oops*/true); 128 129 _scavenge_closure->set_scanned_cld(NULL); 130 } 131 } 132 133 ScanWeakRefClosure::ScanWeakRefClosure(DefNewGeneration* g) : 134 _g(g) 135 { 136 _boundary = _g->reserved().end(); 137 } 138 139 DefNewGeneration::DefNewGeneration(ReservedSpace rs, 140 size_t initial_size, 141 size_t min_size, 142 size_t max_size, 143 const char* policy) 144 : Generation(rs, initial_size), 145 _preserved_marks_set(false /* in_c_heap */), 146 _promo_failure_drain_in_progress(false), 147 _should_allocate_from_space(false) 148 { 149 MemRegion cmr((HeapWord*)_virtual_space.low(), 150 (HeapWord*)_virtual_space.high()); 151 GenCollectedHeap* gch = GenCollectedHeap::heap(); 152 153 gch->rem_set()->resize_covered_region(cmr); 154 155 _eden_space = new ContiguousSpace(); 156 _from_space = new ContiguousSpace(); 157 _to_space = new ContiguousSpace(); 158 159 // Compute the maximum eden and survivor space sizes. These sizes 160 // are computed assuming the entire reserved space is committed. 161 // These values are exported as performance counters. 162 uintx size = _virtual_space.reserved_size(); 163 _max_survivor_size = compute_survivor_size(size, SpaceAlignment); 164 _max_eden_size = size - (2*_max_survivor_size); 165 166 // allocate the performance counters 167 168 // Generation counters -- generation 0, 3 subspaces 169 _gen_counters = new GenerationCounters("new", 0, 3, 170 min_size, max_size, &_virtual_space); 171 _gc_counters = new CollectorCounters(policy, 0); 172 173 _eden_counters = new CSpaceCounters("eden", 0, _max_eden_size, _eden_space, 174 _gen_counters); 175 _from_counters = new CSpaceCounters("s0", 1, _max_survivor_size, _from_space, 176 _gen_counters); 177 _to_counters = new CSpaceCounters("s1", 2, _max_survivor_size, _to_space, 178 _gen_counters); 179 180 compute_space_boundaries(0, SpaceDecorator::Clear, SpaceDecorator::Mangle); 181 update_counters(); 182 _old_gen = NULL; 183 _tenuring_threshold = MaxTenuringThreshold; 184 _pretenure_size_threshold_words = PretenureSizeThreshold >> LogHeapWordSize; 185 186 _gc_timer = new (ResourceObj::C_HEAP, mtGC) STWGCTimer(); 187 } 188 189 void DefNewGeneration::compute_space_boundaries(uintx minimum_eden_size, 190 bool clear_space, 191 bool mangle_space) { 192 // If the spaces are being cleared (only done at heap initialization 193 // currently), the survivor spaces need not be empty. 194 // Otherwise, no care is taken for used areas in the survivor spaces 195 // so check. 196 assert(clear_space || (to()->is_empty() && from()->is_empty()), 197 "Initialization of the survivor spaces assumes these are empty"); 198 199 // Compute sizes 200 uintx size = _virtual_space.committed_size(); 201 uintx survivor_size = compute_survivor_size(size, SpaceAlignment); 202 uintx eden_size = size - (2*survivor_size); 203 assert(eden_size > 0 && survivor_size <= eden_size, "just checking"); 204 205 if (eden_size < minimum_eden_size) { 206 // May happen due to 64Kb rounding, if so adjust eden size back up 207 minimum_eden_size = align_up(minimum_eden_size, SpaceAlignment); 208 uintx maximum_survivor_size = (size - minimum_eden_size) / 2; 209 uintx unaligned_survivor_size = 210 align_down(maximum_survivor_size, SpaceAlignment); 211 survivor_size = MAX2(unaligned_survivor_size, SpaceAlignment); 212 eden_size = size - (2*survivor_size); 213 assert(eden_size > 0 && survivor_size <= eden_size, "just checking"); 214 assert(eden_size >= minimum_eden_size, "just checking"); 215 } 216 217 char *eden_start = _virtual_space.low(); 218 char *from_start = eden_start + eden_size; 219 char *to_start = from_start + survivor_size; 220 char *to_end = to_start + survivor_size; 221 222 assert(to_end == _virtual_space.high(), "just checking"); 223 assert(Space::is_aligned(eden_start), "checking alignment"); 224 assert(Space::is_aligned(from_start), "checking alignment"); 225 assert(Space::is_aligned(to_start), "checking alignment"); 226 227 MemRegion edenMR((HeapWord*)eden_start, (HeapWord*)from_start); 228 MemRegion fromMR((HeapWord*)from_start, (HeapWord*)to_start); 229 MemRegion toMR ((HeapWord*)to_start, (HeapWord*)to_end); 230 231 // A minimum eden size implies that there is a part of eden that 232 // is being used and that affects the initialization of any 233 // newly formed eden. 234 bool live_in_eden = minimum_eden_size > 0; 235 236 // If not clearing the spaces, do some checking to verify that 237 // the space are already mangled. 238 if (!clear_space) { 239 // Must check mangling before the spaces are reshaped. Otherwise, 240 // the bottom or end of one space may have moved into another 241 // a failure of the check may not correctly indicate which space 242 // is not properly mangled. 243 if (ZapUnusedHeapArea) { 244 HeapWord* limit = (HeapWord*) _virtual_space.high(); 245 eden()->check_mangled_unused_area(limit); 246 from()->check_mangled_unused_area(limit); 247 to()->check_mangled_unused_area(limit); 248 } 249 } 250 251 // Reset the spaces for their new regions. 252 eden()->initialize(edenMR, 253 clear_space && !live_in_eden, 254 SpaceDecorator::Mangle); 255 // If clear_space and live_in_eden, we will not have cleared any 256 // portion of eden above its top. This can cause newly 257 // expanded space not to be mangled if using ZapUnusedHeapArea. 258 // We explicitly do such mangling here. 259 if (ZapUnusedHeapArea && clear_space && live_in_eden && mangle_space) { 260 eden()->mangle_unused_area(); 261 } 262 from()->initialize(fromMR, clear_space, mangle_space); 263 to()->initialize(toMR, clear_space, mangle_space); 264 265 // Set next compaction spaces. 266 eden()->set_next_compaction_space(from()); 267 // The to-space is normally empty before a compaction so need 268 // not be considered. The exception is during promotion 269 // failure handling when to-space can contain live objects. 270 from()->set_next_compaction_space(NULL); 271 } 272 273 void DefNewGeneration::swap_spaces() { 274 ContiguousSpace* s = from(); 275 _from_space = to(); 276 _to_space = s; 277 eden()->set_next_compaction_space(from()); 278 // The to-space is normally empty before a compaction so need 279 // not be considered. The exception is during promotion 280 // failure handling when to-space can contain live objects. 281 from()->set_next_compaction_space(NULL); 282 283 if (UsePerfData) { 284 CSpaceCounters* c = _from_counters; 285 _from_counters = _to_counters; 286 _to_counters = c; 287 } 288 } 289 290 bool DefNewGeneration::expand(size_t bytes) { 291 MutexLocker x(ExpandHeap_lock); 292 HeapWord* prev_high = (HeapWord*) _virtual_space.high(); 293 bool success = _virtual_space.expand_by(bytes); 294 if (success && ZapUnusedHeapArea) { 295 // Mangle newly committed space immediately because it 296 // can be done here more simply that after the new 297 // spaces have been computed. 298 HeapWord* new_high = (HeapWord*) _virtual_space.high(); 299 MemRegion mangle_region(prev_high, new_high); 300 SpaceMangler::mangle_region(mangle_region); 301 } 302 303 // Do not attempt an expand-to-the reserve size. The 304 // request should properly observe the maximum size of 305 // the generation so an expand-to-reserve should be 306 // unnecessary. Also a second call to expand-to-reserve 307 // value potentially can cause an undue expansion. 308 // For example if the first expand fail for unknown reasons, 309 // but the second succeeds and expands the heap to its maximum 310 // value. 311 if (GCLocker::is_active()) { 312 log_debug(gc)("Garbage collection disabled, expanded heap instead"); 313 } 314 315 return success; 316 } 317 318 size_t DefNewGeneration::adjust_for_thread_increase(size_t new_size_candidate, 319 size_t new_size_before, 320 size_t alignment) const { 321 size_t desired_new_size = new_size_before; 322 323 if (NewSizeThreadIncrease > 0) { 324 int threads_count; 325 size_t thread_increase_size = 0; 326 327 // 1. Check an overflow at 'threads_count * NewSizeThreadIncrease'. 328 threads_count = Threads::number_of_non_daemon_threads(); 329 if (threads_count > 0 && NewSizeThreadIncrease <= max_uintx / threads_count) { 330 thread_increase_size = threads_count * NewSizeThreadIncrease; 331 332 // 2. Check an overflow at 'new_size_candidate + thread_increase_size'. 333 if (new_size_candidate <= max_uintx - thread_increase_size) { 334 new_size_candidate += thread_increase_size; 335 336 // 3. Check an overflow at 'align_up'. 337 size_t aligned_max = ((max_uintx - alignment) & ~(alignment-1)); 338 if (new_size_candidate <= aligned_max) { 339 desired_new_size = align_up(new_size_candidate, alignment); 340 } 341 } 342 } 343 } 344 345 return desired_new_size; 346 } 347 348 void DefNewGeneration::compute_new_size() { 349 // This is called after a GC that includes the old generation, so from-space 350 // will normally be empty. 351 // Note that we check both spaces, since if scavenge failed they revert roles. 352 // If not we bail out (otherwise we would have to relocate the objects). 353 if (!from()->is_empty() || !to()->is_empty()) { 354 return; 355 } 356 357 GenCollectedHeap* gch = GenCollectedHeap::heap(); 358 359 size_t old_size = gch->old_gen()->capacity(); 360 size_t new_size_before = _virtual_space.committed_size(); 361 size_t min_new_size = initial_size(); 362 size_t max_new_size = reserved().byte_size(); 363 assert(min_new_size <= new_size_before && 364 new_size_before <= max_new_size, 365 "just checking"); 366 // All space sizes must be multiples of Generation::GenGrain. 367 size_t alignment = Generation::GenGrain; 368 369 int threads_count = 0; 370 size_t thread_increase_size = 0; 371 372 size_t new_size_candidate = old_size / NewRatio; 373 // Compute desired new generation size based on NewRatio and NewSizeThreadIncrease 374 // and reverts to previous value if any overflow happens 375 size_t desired_new_size = adjust_for_thread_increase(new_size_candidate, new_size_before, alignment); 376 377 // Adjust new generation size 378 desired_new_size = clamp(desired_new_size, min_new_size, max_new_size); 379 assert(desired_new_size <= max_new_size, "just checking"); 380 381 bool changed = false; 382 if (desired_new_size > new_size_before) { 383 size_t change = desired_new_size - new_size_before; 384 assert(change % alignment == 0, "just checking"); 385 if (expand(change)) { 386 changed = true; 387 } 388 // If the heap failed to expand to the desired size, 389 // "changed" will be false. If the expansion failed 390 // (and at this point it was expected to succeed), 391 // ignore the failure (leaving "changed" as false). 392 } 393 if (desired_new_size < new_size_before && eden()->is_empty()) { 394 // bail out of shrinking if objects in eden 395 size_t change = new_size_before - desired_new_size; 396 assert(change % alignment == 0, "just checking"); 397 _virtual_space.shrink_by(change); 398 changed = true; 399 } 400 if (changed) { 401 // The spaces have already been mangled at this point but 402 // may not have been cleared (set top = bottom) and should be. 403 // Mangling was done when the heap was being expanded. 404 compute_space_boundaries(eden()->used(), 405 SpaceDecorator::Clear, 406 SpaceDecorator::DontMangle); 407 MemRegion cmr((HeapWord*)_virtual_space.low(), 408 (HeapWord*)_virtual_space.high()); 409 gch->rem_set()->resize_covered_region(cmr); 410 411 log_debug(gc, ergo, heap)( 412 "New generation size " SIZE_FORMAT "K->" SIZE_FORMAT "K [eden=" SIZE_FORMAT "K,survivor=" SIZE_FORMAT "K]", 413 new_size_before/K, _virtual_space.committed_size()/K, 414 eden()->capacity()/K, from()->capacity()/K); 415 log_trace(gc, ergo, heap)( 416 " [allowed " SIZE_FORMAT "K extra for %d threads]", 417 thread_increase_size/K, threads_count); 418 } 419 } 420 421 422 size_t DefNewGeneration::capacity() const { 423 return eden()->capacity() 424 + from()->capacity(); // to() is only used during scavenge 425 } 426 427 428 size_t DefNewGeneration::used() const { 429 return eden()->used() 430 + from()->used(); // to() is only used during scavenge 431 } 432 433 434 size_t DefNewGeneration::free() const { 435 return eden()->free() 436 + from()->free(); // to() is only used during scavenge 437 } 438 439 size_t DefNewGeneration::max_capacity() const { 440 const size_t reserved_bytes = reserved().byte_size(); 441 return reserved_bytes - compute_survivor_size(reserved_bytes, SpaceAlignment); 442 } 443 444 size_t DefNewGeneration::unsafe_max_alloc_nogc() const { 445 return eden()->free(); 446 } 447 448 size_t DefNewGeneration::capacity_before_gc() const { 449 return eden()->capacity(); 450 } 451 452 size_t DefNewGeneration::contiguous_available() const { 453 return eden()->free(); 454 } 455 456 457 HeapWord* volatile* DefNewGeneration::top_addr() const { return eden()->top_addr(); } 458 HeapWord** DefNewGeneration::end_addr() const { return eden()->end_addr(); } 459 460 void DefNewGeneration::object_iterate(ObjectClosure* blk) { 461 eden()->object_iterate(blk); 462 from()->object_iterate(blk); 463 } 464 465 466 void DefNewGeneration::space_iterate(SpaceClosure* blk, 467 bool usedOnly) { 468 blk->do_space(eden()); 469 blk->do_space(from()); 470 blk->do_space(to()); 471 } 472 473 // The last collection bailed out, we are running out of heap space, 474 // so we try to allocate the from-space, too. 475 HeapWord* DefNewGeneration::allocate_from_space(size_t size) { 476 bool should_try_alloc = should_allocate_from_space() || GCLocker::is_active_and_needs_gc(); 477 478 // If the Heap_lock is not locked by this thread, this will be called 479 // again later with the Heap_lock held. 480 bool do_alloc = should_try_alloc && (Heap_lock->owned_by_self() || (SafepointSynchronize::is_at_safepoint() && Thread::current()->is_VM_thread())); 481 482 HeapWord* result = NULL; 483 if (do_alloc) { 484 result = from()->allocate(size); 485 } 486 487 log_trace(gc, alloc)("DefNewGeneration::allocate_from_space(" SIZE_FORMAT "): will_fail: %s heap_lock: %s free: " SIZE_FORMAT "%s%s returns %s", 488 size, 489 GenCollectedHeap::heap()->incremental_collection_will_fail(false /* don't consult_young */) ? 490 "true" : "false", 491 Heap_lock->is_locked() ? "locked" : "unlocked", 492 from()->free(), 493 should_try_alloc ? "" : " should_allocate_from_space: NOT", 494 do_alloc ? " Heap_lock is not owned by self" : "", 495 result == NULL ? "NULL" : "object"); 496 497 return result; 498 } 499 500 HeapWord* DefNewGeneration::expand_and_allocate(size_t size, 501 bool is_tlab, 502 bool parallel) { 503 // We don't attempt to expand the young generation (but perhaps we should.) 504 return allocate(size, is_tlab); 505 } 506 507 void DefNewGeneration::adjust_desired_tenuring_threshold() { 508 // Set the desired survivor size to half the real survivor space 509 size_t const survivor_capacity = to()->capacity() / HeapWordSize; 510 size_t const desired_survivor_size = (size_t)((((double)survivor_capacity) * TargetSurvivorRatio) / 100); 511 512 _tenuring_threshold = age_table()->compute_tenuring_threshold(desired_survivor_size); 513 514 if (UsePerfData) { 515 GCPolicyCounters* gc_counters = GenCollectedHeap::heap()->counters(); 516 gc_counters->tenuring_threshold()->set_value(_tenuring_threshold); 517 gc_counters->desired_survivor_size()->set_value(desired_survivor_size * oopSize); 518 } 519 520 age_table()->print_age_table(_tenuring_threshold); 521 } 522 523 void DefNewGeneration::collect(bool full, 524 bool clear_all_soft_refs, 525 size_t size, 526 bool is_tlab) { 527 assert(full || size > 0, "otherwise we don't want to collect"); 528 529 SerialHeap* heap = SerialHeap::heap(); 530 531 _gc_timer->register_gc_start(); 532 DefNewTracer gc_tracer; 533 gc_tracer.report_gc_start(heap->gc_cause(), _gc_timer->gc_start()); 534 535 _old_gen = heap->old_gen(); 536 537 // If the next generation is too full to accommodate promotion 538 // from this generation, pass on collection; let the next generation 539 // do it. 540 if (!collection_attempt_is_safe()) { 541 log_trace(gc)(":: Collection attempt not safe ::"); 542 heap->set_incremental_collection_failed(); // Slight lie: we did not even attempt one 543 return; 544 } 545 assert(to()->is_empty(), "Else not collection_attempt_is_safe"); 546 547 init_assuming_no_promotion_failure(); 548 549 GCTraceTime(Trace, gc, phases) tm("DefNew", NULL, heap->gc_cause()); 550 551 heap->trace_heap_before_gc(&gc_tracer); 552 553 // These can be shared for all code paths 554 IsAliveClosure is_alive(this); 555 ScanWeakRefClosure scan_weak_ref(this); 556 557 age_table()->clear(); 558 to()->clear(SpaceDecorator::Mangle); 559 // The preserved marks should be empty at the start of the GC. 560 _preserved_marks_set.init(1); 561 562 heap->rem_set()->prepare_for_younger_refs_iterate(false); 563 564 assert(heap->no_allocs_since_save_marks(), 565 "save marks have not been newly set."); 566 567 DefNewScanClosure scan_closure(this); 568 DefNewYoungerGenClosure younger_gen_closure(this, _old_gen); 569 570 CLDScanClosure cld_scan_closure(&scan_closure, 571 heap->rem_set()->cld_rem_set()->accumulate_modified_oops()); 572 573 set_promo_failure_scan_stack_closure(&scan_closure); 574 FastEvacuateFollowersClosure evacuate_followers(heap, 575 &scan_closure, 576 &younger_gen_closure); 577 578 assert(heap->no_allocs_since_save_marks(), 579 "save marks have not been newly set."); 580 581 { 582 // DefNew needs to run with n_threads == 0, to make sure the serial 583 // version of the card table scanning code is used. 584 // See: CardTableRS::non_clean_card_iterate_possibly_parallel. 585 StrongRootsScope srs(0); 586 587 heap->young_process_roots(&srs, 588 &scan_closure, 589 &younger_gen_closure, 590 &cld_scan_closure); 591 } 592 593 // "evacuate followers". 594 evacuate_followers.do_void(); 595 596 FastKeepAliveClosure keep_alive(this, &scan_weak_ref); 597 ReferenceProcessor* rp = ref_processor(); 598 rp->setup_policy(clear_all_soft_refs); 599 ReferenceProcessorPhaseTimes pt(_gc_timer, rp->max_num_queues()); 600 const ReferenceProcessorStats& stats = 601 rp->process_discovered_references(&is_alive, &keep_alive, &evacuate_followers, 602 NULL, &pt); 603 gc_tracer.report_gc_reference_stats(stats); 604 gc_tracer.report_tenuring_threshold(tenuring_threshold()); 605 pt.print_all_references(); 606 607 assert(heap->no_allocs_since_save_marks(), "save marks have not been newly set."); 608 609 WeakProcessor::weak_oops_do(&is_alive, &keep_alive); 610 611 // Verify that the usage of keep_alive didn't copy any objects. 612 assert(heap->no_allocs_since_save_marks(), "save marks have not been newly set."); 613 614 if (!_promotion_failed) { 615 // Swap the survivor spaces. 616 eden()->clear(SpaceDecorator::Mangle); 617 from()->clear(SpaceDecorator::Mangle); 618 if (ZapUnusedHeapArea) { 619 // This is now done here because of the piece-meal mangling which 620 // can check for valid mangling at intermediate points in the 621 // collection(s). When a young collection fails to collect 622 // sufficient space resizing of the young generation can occur 623 // an redistribute the spaces in the young generation. Mangle 624 // here so that unzapped regions don't get distributed to 625 // other spaces. 626 to()->mangle_unused_area(); 627 } 628 swap_spaces(); 629 630 assert(to()->is_empty(), "to space should be empty now"); 631 632 adjust_desired_tenuring_threshold(); 633 634 // A successful scavenge should restart the GC time limit count which is 635 // for full GC's. 636 AdaptiveSizePolicy* size_policy = heap->size_policy(); 637 size_policy->reset_gc_overhead_limit_count(); 638 assert(!heap->incremental_collection_failed(), "Should be clear"); 639 } else { 640 assert(_promo_failure_scan_stack.is_empty(), "post condition"); 641 _promo_failure_scan_stack.clear(true); // Clear cached segments. 642 643 remove_forwarding_pointers(); 644 log_info(gc, promotion)("Promotion failed"); 645 // Add to-space to the list of space to compact 646 // when a promotion failure has occurred. In that 647 // case there can be live objects in to-space 648 // as a result of a partial evacuation of eden 649 // and from-space. 650 swap_spaces(); // For uniformity wrt ParNewGeneration. 651 from()->set_next_compaction_space(to()); 652 heap->set_incremental_collection_failed(); 653 654 // Inform the next generation that a promotion failure occurred. 655 _old_gen->promotion_failure_occurred(); 656 gc_tracer.report_promotion_failed(_promotion_failed_info); 657 658 // Reset the PromotionFailureALot counters. 659 NOT_PRODUCT(heap->reset_promotion_should_fail();) 660 } 661 // We should have processed and cleared all the preserved marks. 662 _preserved_marks_set.reclaim(); 663 // set new iteration safe limit for the survivor spaces 664 from()->set_concurrent_iteration_safe_limit(from()->top()); 665 to()->set_concurrent_iteration_safe_limit(to()->top()); 666 667 heap->trace_heap_after_gc(&gc_tracer); 668 669 _gc_timer->register_gc_end(); 670 671 gc_tracer.report_gc_end(_gc_timer->gc_end(), _gc_timer->time_partitions()); 672 } 673 674 void DefNewGeneration::init_assuming_no_promotion_failure() { 675 _promotion_failed = false; 676 _promotion_failed_info.reset(); 677 from()->set_next_compaction_space(NULL); 678 } 679 680 void DefNewGeneration::remove_forwarding_pointers() { 681 RemoveForwardedPointerClosure rspc; 682 eden()->object_iterate(&rspc); 683 from()->object_iterate(&rspc); 684 restore_preserved_marks(); 685 } 686 687 void DefNewGeneration::restore_preserved_marks() { 688 _preserved_marks_set.restore(NULL); 689 } 690 691 void DefNewGeneration::handle_promotion_failure(oop old) { 692 log_debug(gc, promotion)("Promotion failure size = %d) ", old->size()); 693 694 _promotion_failed = true; 695 _promotion_failed_info.register_copy_failure(old->size()); 696 _preserved_marks_set.get()->push_if_necessary(old, old->mark_raw()); 697 // forward to self 698 old->forward_to(old); 699 700 _promo_failure_scan_stack.push(old); 701 702 if (!_promo_failure_drain_in_progress) { 703 // prevent recursion in copy_to_survivor_space() 704 _promo_failure_drain_in_progress = true; 705 drain_promo_failure_scan_stack(); 706 _promo_failure_drain_in_progress = false; 707 } 708 } 709 710 oop DefNewGeneration::copy_to_survivor_space(oop old) { 711 assert(is_in_reserved(old) && !old->is_forwarded(), 712 "shouldn't be scavenging this oop"); 713 size_t s = old->size(); 714 oop obj = NULL; 715 716 // Try allocating obj in to-space (unless too old) 717 if (old->age() < tenuring_threshold()) { 718 obj = (oop) to()->allocate_aligned(s); 719 } 720 721 // Otherwise try allocating obj tenured 722 if (obj == NULL) { 723 obj = _old_gen->promote(old, s); 724 if (obj == NULL) { 725 handle_promotion_failure(old); 726 return old; 727 } 728 } else { 729 // Prefetch beyond obj 730 const intx interval = PrefetchCopyIntervalInBytes; 731 Prefetch::write(obj, interval); 732 733 // Copy obj 734 Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(old), cast_from_oop<HeapWord*>(obj), s); 735 736 // Increment age if obj still in new generation 737 obj->incr_age(); 738 age_table()->add(obj, s); 739 } 740 741 // Done, insert forward pointer to obj in this header 742 old->forward_to(obj); 743 744 return obj; 745 } 746 747 void DefNewGeneration::drain_promo_failure_scan_stack() { 748 while (!_promo_failure_scan_stack.is_empty()) { 749 oop obj = _promo_failure_scan_stack.pop(); 750 obj->oop_iterate(_promo_failure_scan_stack_closure); 751 } 752 } 753 754 void DefNewGeneration::save_marks() { 755 eden()->set_saved_mark(); 756 to()->set_saved_mark(); 757 from()->set_saved_mark(); 758 } 759 760 761 void DefNewGeneration::reset_saved_marks() { 762 eden()->reset_saved_mark(); 763 to()->reset_saved_mark(); 764 from()->reset_saved_mark(); 765 } 766 767 768 bool DefNewGeneration::no_allocs_since_save_marks() { 769 assert(eden()->saved_mark_at_top(), "Violated spec - alloc in eden"); 770 assert(from()->saved_mark_at_top(), "Violated spec - alloc in from"); 771 return to()->saved_mark_at_top(); 772 } 773 774 void DefNewGeneration::contribute_scratch(ScratchBlock*& list, Generation* requestor, 775 size_t max_alloc_words) { 776 if (requestor == this || _promotion_failed) { 777 return; 778 } 779 assert(GenCollectedHeap::heap()->is_old_gen(requestor), "We should not call our own generation"); 780 781 /* $$$ Assert this? "trace" is a "MarkSweep" function so that's not appropriate. 782 if (to_space->top() > to_space->bottom()) { 783 trace("to_space not empty when contribute_scratch called"); 784 } 785 */ 786 787 ContiguousSpace* to_space = to(); 788 assert(to_space->end() >= to_space->top(), "pointers out of order"); 789 size_t free_words = pointer_delta(to_space->end(), to_space->top()); 790 if (free_words >= MinFreeScratchWords) { 791 ScratchBlock* sb = (ScratchBlock*)to_space->top(); 792 sb->num_words = free_words; 793 sb->next = list; 794 list = sb; 795 } 796 } 797 798 void DefNewGeneration::reset_scratch() { 799 // If contributing scratch in to_space, mangle all of 800 // to_space if ZapUnusedHeapArea. This is needed because 801 // top is not maintained while using to-space as scratch. 802 if (ZapUnusedHeapArea) { 803 to()->mangle_unused_area_complete(); 804 } 805 } 806 807 bool DefNewGeneration::collection_attempt_is_safe() { 808 if (!to()->is_empty()) { 809 log_trace(gc)(":: to is not empty ::"); 810 return false; 811 } 812 if (_old_gen == NULL) { 813 GenCollectedHeap* gch = GenCollectedHeap::heap(); 814 _old_gen = gch->old_gen(); 815 } 816 return _old_gen->promotion_attempt_is_safe(used()); 817 } 818 819 void DefNewGeneration::gc_epilogue(bool full) { 820 DEBUG_ONLY(static bool seen_incremental_collection_failed = false;) 821 822 assert(!GCLocker::is_active(), "We should not be executing here"); 823 // Check if the heap is approaching full after a collection has 824 // been done. Generally the young generation is empty at 825 // a minimum at the end of a collection. If it is not, then 826 // the heap is approaching full. 827 GenCollectedHeap* gch = GenCollectedHeap::heap(); 828 if (full) { 829 DEBUG_ONLY(seen_incremental_collection_failed = false;) 830 if (!collection_attempt_is_safe() && !_eden_space->is_empty()) { 831 log_trace(gc)("DefNewEpilogue: cause(%s), full, not safe, set_failed, set_alloc_from, clear_seen", 832 GCCause::to_string(gch->gc_cause())); 833 gch->set_incremental_collection_failed(); // Slight lie: a full gc left us in that state 834 set_should_allocate_from_space(); // we seem to be running out of space 835 } else { 836 log_trace(gc)("DefNewEpilogue: cause(%s), full, safe, clear_failed, clear_alloc_from, clear_seen", 837 GCCause::to_string(gch->gc_cause())); 838 gch->clear_incremental_collection_failed(); // We just did a full collection 839 clear_should_allocate_from_space(); // if set 840 } 841 } else { 842 #ifdef ASSERT 843 // It is possible that incremental_collection_failed() == true 844 // here, because an attempted scavenge did not succeed. The policy 845 // is normally expected to cause a full collection which should 846 // clear that condition, so we should not be here twice in a row 847 // with incremental_collection_failed() == true without having done 848 // a full collection in between. 849 if (!seen_incremental_collection_failed && 850 gch->incremental_collection_failed()) { 851 log_trace(gc)("DefNewEpilogue: cause(%s), not full, not_seen_failed, failed, set_seen_failed", 852 GCCause::to_string(gch->gc_cause())); 853 seen_incremental_collection_failed = true; 854 } else if (seen_incremental_collection_failed) { 855 log_trace(gc)("DefNewEpilogue: cause(%s), not full, seen_failed, will_clear_seen_failed", 856 GCCause::to_string(gch->gc_cause())); 857 assert(gch->gc_cause() == GCCause::_scavenge_alot || 858 !gch->incremental_collection_failed(), 859 "Twice in a row"); 860 seen_incremental_collection_failed = false; 861 } 862 #endif // ASSERT 863 } 864 865 if (ZapUnusedHeapArea) { 866 eden()->check_mangled_unused_area_complete(); 867 from()->check_mangled_unused_area_complete(); 868 to()->check_mangled_unused_area_complete(); 869 } 870 871 if (!CleanChunkPoolAsync) { 872 Chunk::clean_chunk_pool(); 873 } 874 875 // update the generation and space performance counters 876 update_counters(); 877 gch->counters()->update_counters(); 878 } 879 880 void DefNewGeneration::record_spaces_top() { 881 assert(ZapUnusedHeapArea, "Not mangling unused space"); 882 eden()->set_top_for_allocations(); 883 to()->set_top_for_allocations(); 884 from()->set_top_for_allocations(); 885 } 886 887 void DefNewGeneration::ref_processor_init() { 888 Generation::ref_processor_init(); 889 } 890 891 892 void DefNewGeneration::update_counters() { 893 if (UsePerfData) { 894 _eden_counters->update_all(); 895 _from_counters->update_all(); 896 _to_counters->update_all(); 897 _gen_counters->update_all(); 898 } 899 } 900 901 void DefNewGeneration::verify() { 902 eden()->verify(); 903 from()->verify(); 904 to()->verify(); 905 } 906 907 void DefNewGeneration::print_on(outputStream* st) const { 908 Generation::print_on(st); 909 st->print(" eden"); 910 eden()->print_on(st); 911 st->print(" from"); 912 from()->print_on(st); 913 st->print(" to "); 914 to()->print_on(st); 915 } 916 917 918 const char* DefNewGeneration::name() const { 919 return "def new generation"; 920 } 921 922 // Moved from inline file as they are not called inline 923 CompactibleSpace* DefNewGeneration::first_compaction_space() const { 924 return eden(); 925 } 926 927 HeapWord* DefNewGeneration::allocate(size_t word_size, bool is_tlab) { 928 // This is the slow-path allocation for the DefNewGeneration. 929 // Most allocations are fast-path in compiled code. 930 // We try to allocate from the eden. If that works, we are happy. 931 // Note that since DefNewGeneration supports lock-free allocation, we 932 // have to use it here, as well. 933 HeapWord* result = eden()->par_allocate(word_size); 934 if (result != NULL) { 935 if (_old_gen != NULL) { 936 _old_gen->sample_eden_chunk(); 937 } 938 } else { 939 // If the eden is full and the last collection bailed out, we are running 940 // out of heap space, and we try to allocate the from-space, too. 941 // allocate_from_space can't be inlined because that would introduce a 942 // circular dependency at compile time. 943 result = allocate_from_space(word_size); 944 } 945 return result; 946 } 947 948 HeapWord* DefNewGeneration::par_allocate(size_t word_size, 949 bool is_tlab) { 950 HeapWord* res = eden()->par_allocate(word_size); 951 if (_old_gen != NULL) { 952 _old_gen->sample_eden_chunk(); 953 } 954 return res; 955 } 956 957 size_t DefNewGeneration::tlab_capacity() const { 958 return eden()->capacity(); 959 } 960 961 size_t DefNewGeneration::tlab_used() const { 962 return eden()->used(); 963 } 964 965 size_t DefNewGeneration::unsafe_max_tlab_alloc() const { 966 return unsafe_max_alloc_nogc(); 967 }