1 /* 2 * Copyright (c) 2001, 2012, 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_implementation/parallelScavenge/adjoiningGenerations.hpp" 27 #include "gc_implementation/parallelScavenge/adjoiningVirtualSpaces.hpp" 28 #include "gc_implementation/parallelScavenge/cardTableExtension.hpp" 29 #include "gc_implementation/parallelScavenge/gcTaskManager.hpp" 30 #include "gc_implementation/parallelScavenge/generationSizer.hpp" 31 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.inline.hpp" 32 #include "gc_implementation/parallelScavenge/psAdaptiveSizePolicy.hpp" 33 #include "gc_implementation/parallelScavenge/psMarkSweep.hpp" 34 #include "gc_implementation/parallelScavenge/psParallelCompact.hpp" 35 #include "gc_implementation/parallelScavenge/psPromotionManager.hpp" 36 #include "gc_implementation/parallelScavenge/psScavenge.hpp" 37 #include "gc_implementation/parallelScavenge/vmPSOperations.hpp" 38 #include "gc_implementation/shared/gcHeapSummary.hpp" 39 #include "gc_implementation/shared/gcWhen.hpp" 40 #include "memory/gcLocker.inline.hpp" 41 #include "oops/oop.inline.hpp" 42 #include "runtime/handles.inline.hpp" 43 #include "runtime/java.hpp" 44 #include "runtime/vmThread.hpp" 45 #include "services/memTracker.hpp" 46 #include "utilities/vmError.hpp" 47 48 PSYoungGen* ParallelScavengeHeap::_young_gen = NULL; 49 PSOldGen* ParallelScavengeHeap::_old_gen = NULL; 50 PSPermGen* ParallelScavengeHeap::_perm_gen = NULL; 51 PSAdaptiveSizePolicy* ParallelScavengeHeap::_size_policy = NULL; 52 PSGCAdaptivePolicyCounters* ParallelScavengeHeap::_gc_policy_counters = NULL; 53 ParallelScavengeHeap* ParallelScavengeHeap::_psh = NULL; 54 GCTaskManager* ParallelScavengeHeap::_gc_task_manager = NULL; 55 56 static void trace_gen_sizes(const char* const str, 57 size_t pg_min, size_t pg_max, 58 size_t og_min, size_t og_max, 59 size_t yg_min, size_t yg_max) 60 { 61 if (TracePageSizes) { 62 tty->print_cr("%s: " SIZE_FORMAT "," SIZE_FORMAT " " 63 SIZE_FORMAT "," SIZE_FORMAT " " 64 SIZE_FORMAT "," SIZE_FORMAT " " 65 SIZE_FORMAT, 66 str, pg_min / K, pg_max / K, 67 og_min / K, og_max / K, 68 yg_min / K, yg_max / K, 69 (pg_max + og_max + yg_max) / K); 70 } 71 } 72 73 jint ParallelScavengeHeap::initialize() { 74 CollectedHeap::pre_initialize(); 75 76 // Cannot be initialized until after the flags are parsed 77 // GenerationSizer flag_parser; 78 _collector_policy = new GenerationSizer(); 79 80 size_t yg_min_size = _collector_policy->min_young_gen_size(); 81 size_t yg_max_size = _collector_policy->max_young_gen_size(); 82 size_t og_min_size = _collector_policy->min_old_gen_size(); 83 size_t og_max_size = _collector_policy->max_old_gen_size(); 84 // Why isn't there a min_perm_gen_size()? 85 size_t pg_min_size = _collector_policy->perm_gen_size(); 86 size_t pg_max_size = _collector_policy->max_perm_gen_size(); 87 88 trace_gen_sizes("ps heap raw", 89 pg_min_size, pg_max_size, 90 og_min_size, og_max_size, 91 yg_min_size, yg_max_size); 92 93 // The ReservedSpace ctor used below requires that the page size for the perm 94 // gen is <= the page size for the rest of the heap (young + old gens). 95 const size_t og_page_sz = os::page_size_for_region(yg_min_size + og_min_size, 96 yg_max_size + og_max_size, 97 8); 98 const size_t pg_page_sz = MIN2(os::page_size_for_region(pg_min_size, 99 pg_max_size, 16), 100 og_page_sz); 101 102 const size_t pg_align = set_alignment(_perm_gen_alignment, pg_page_sz); 103 const size_t og_align = set_alignment(_old_gen_alignment, og_page_sz); 104 const size_t yg_align = set_alignment(_young_gen_alignment, og_page_sz); 105 106 // Update sizes to reflect the selected page size(s). 107 // 108 // NEEDS_CLEANUP. The default TwoGenerationCollectorPolicy uses NewRatio; it 109 // should check UseAdaptiveSizePolicy. Changes from generationSizer could 110 // move to the common code. 111 yg_min_size = align_size_up(yg_min_size, yg_align); 112 yg_max_size = align_size_up(yg_max_size, yg_align); 113 size_t yg_cur_size = 114 align_size_up(_collector_policy->young_gen_size(), yg_align); 115 yg_cur_size = MAX2(yg_cur_size, yg_min_size); 116 117 og_min_size = align_size_up(og_min_size, og_align); 118 // Align old gen size down to preserve specified heap size. 119 assert(og_align == yg_align, "sanity"); 120 og_max_size = align_size_down(og_max_size, og_align); 121 og_max_size = MAX2(og_max_size, og_min_size); 122 size_t og_cur_size = 123 align_size_down(_collector_policy->old_gen_size(), og_align); 124 og_cur_size = MAX2(og_cur_size, og_min_size); 125 126 pg_min_size = align_size_up(pg_min_size, pg_align); 127 pg_max_size = align_size_up(pg_max_size, pg_align); 128 size_t pg_cur_size = pg_min_size; 129 130 trace_gen_sizes("ps heap rnd", 131 pg_min_size, pg_max_size, 132 og_min_size, og_max_size, 133 yg_min_size, yg_max_size); 134 135 const size_t total_reserved = pg_max_size + og_max_size + yg_max_size; 136 char* addr = Universe::preferred_heap_base(total_reserved, Universe::UnscaledNarrowOop); 137 138 // The main part of the heap (old gen + young gen) can often use a larger page 139 // size than is needed or wanted for the perm gen. Use the "compound 140 // alignment" ReservedSpace ctor to avoid having to use the same page size for 141 // all gens. 142 143 ReservedHeapSpace heap_rs(pg_max_size, pg_align, og_max_size + yg_max_size, 144 og_align, addr); 145 146 if (UseCompressedOops) { 147 if (addr != NULL && !heap_rs.is_reserved()) { 148 // Failed to reserve at specified address - the requested memory 149 // region is taken already, for example, by 'java' launcher. 150 // Try again to reserver heap higher. 151 addr = Universe::preferred_heap_base(total_reserved, Universe::ZeroBasedNarrowOop); 152 ReservedHeapSpace heap_rs0(pg_max_size, pg_align, og_max_size + yg_max_size, 153 og_align, addr); 154 if (addr != NULL && !heap_rs0.is_reserved()) { 155 // Failed to reserve at specified address again - give up. 156 addr = Universe::preferred_heap_base(total_reserved, Universe::HeapBasedNarrowOop); 157 assert(addr == NULL, ""); 158 ReservedHeapSpace heap_rs1(pg_max_size, pg_align, og_max_size + yg_max_size, 159 og_align, addr); 160 heap_rs = heap_rs1; 161 } else { 162 heap_rs = heap_rs0; 163 } 164 } 165 } 166 167 MemTracker::record_virtual_memory_type((address)heap_rs.base(), mtJavaHeap); 168 169 os::trace_page_sizes("ps perm", pg_min_size, pg_max_size, pg_page_sz, 170 heap_rs.base(), pg_max_size); 171 os::trace_page_sizes("ps main", og_min_size + yg_min_size, 172 og_max_size + yg_max_size, og_page_sz, 173 heap_rs.base() + pg_max_size, 174 heap_rs.size() - pg_max_size); 175 if (!heap_rs.is_reserved()) { 176 vm_shutdown_during_initialization( 177 "Could not reserve enough space for object heap"); 178 return JNI_ENOMEM; 179 } 180 181 _reserved = MemRegion((HeapWord*)heap_rs.base(), 182 (HeapWord*)(heap_rs.base() + heap_rs.size())); 183 184 CardTableExtension* const barrier_set = new CardTableExtension(_reserved, 3); 185 _barrier_set = barrier_set; 186 oopDesc::set_bs(_barrier_set); 187 if (_barrier_set == NULL) { 188 vm_shutdown_during_initialization( 189 "Could not reserve enough space for barrier set"); 190 return JNI_ENOMEM; 191 } 192 193 // Initial young gen size is 4 Mb 194 // 195 // XXX - what about flag_parser.young_gen_size()? 196 const size_t init_young_size = align_size_up(4 * M, yg_align); 197 yg_cur_size = MAX2(MIN2(init_young_size, yg_max_size), yg_cur_size); 198 199 // Split the reserved space into perm gen and the main heap (everything else). 200 // The main heap uses a different alignment. 201 ReservedSpace perm_rs = heap_rs.first_part(pg_max_size); 202 ReservedSpace main_rs = heap_rs.last_part(pg_max_size, og_align); 203 204 // Make up the generations 205 // Calculate the maximum size that a generation can grow. This 206 // includes growth into the other generation. Note that the 207 // parameter _max_gen_size is kept as the maximum 208 // size of the generation as the boundaries currently stand. 209 // _max_gen_size is still used as that value. 210 double max_gc_pause_sec = ((double) MaxGCPauseMillis)/1000.0; 211 double max_gc_minor_pause_sec = ((double) MaxGCMinorPauseMillis)/1000.0; 212 213 _gens = new AdjoiningGenerations(main_rs, 214 og_cur_size, 215 og_min_size, 216 og_max_size, 217 yg_cur_size, 218 yg_min_size, 219 yg_max_size, 220 yg_align); 221 222 _old_gen = _gens->old_gen(); 223 _young_gen = _gens->young_gen(); 224 225 const size_t eden_capacity = _young_gen->eden_space()->capacity_in_bytes(); 226 const size_t old_capacity = _old_gen->capacity_in_bytes(); 227 const size_t initial_promo_size = MIN2(eden_capacity, old_capacity); 228 _size_policy = 229 new PSAdaptiveSizePolicy(eden_capacity, 230 initial_promo_size, 231 young_gen()->to_space()->capacity_in_bytes(), 232 intra_heap_alignment(), 233 max_gc_pause_sec, 234 max_gc_minor_pause_sec, 235 GCTimeRatio 236 ); 237 238 _perm_gen = new PSPermGen(perm_rs, 239 pg_align, 240 pg_cur_size, 241 pg_cur_size, 242 pg_max_size, 243 "perm", 2); 244 245 assert(!UseAdaptiveGCBoundary || 246 (old_gen()->virtual_space()->high_boundary() == 247 young_gen()->virtual_space()->low_boundary()), 248 "Boundaries must meet"); 249 // initialize the policy counters - 2 collectors, 3 generations 250 _gc_policy_counters = 251 new PSGCAdaptivePolicyCounters("ParScav:MSC", 2, 3, _size_policy); 252 _psh = this; 253 254 // Set up the GCTaskManager 255 _gc_task_manager = GCTaskManager::create(ParallelGCThreads); 256 257 if (UseParallelOldGC && !PSParallelCompact::initialize()) { 258 return JNI_ENOMEM; 259 } 260 261 return JNI_OK; 262 } 263 264 void ParallelScavengeHeap::post_initialize() { 265 // Need to init the tenuring threshold 266 PSScavenge::initialize(); 267 if (UseParallelOldGC) { 268 PSParallelCompact::post_initialize(); 269 } else { 270 PSMarkSweep::initialize(); 271 } 272 PSPromotionManager::initialize(); 273 } 274 275 void ParallelScavengeHeap::update_counters() { 276 young_gen()->update_counters(); 277 old_gen()->update_counters(); 278 perm_gen()->update_counters(); 279 } 280 281 size_t ParallelScavengeHeap::capacity() const { 282 size_t value = young_gen()->capacity_in_bytes() + old_gen()->capacity_in_bytes(); 283 return value; 284 } 285 286 size_t ParallelScavengeHeap::used() const { 287 size_t value = young_gen()->used_in_bytes() + old_gen()->used_in_bytes(); 288 return value; 289 } 290 291 bool ParallelScavengeHeap::is_maximal_no_gc() const { 292 return old_gen()->is_maximal_no_gc() && young_gen()->is_maximal_no_gc(); 293 } 294 295 296 size_t ParallelScavengeHeap::permanent_capacity() const { 297 return perm_gen()->capacity_in_bytes(); 298 } 299 300 size_t ParallelScavengeHeap::permanent_used() const { 301 return perm_gen()->used_in_bytes(); 302 } 303 304 size_t ParallelScavengeHeap::max_capacity() const { 305 size_t estimated = reserved_region().byte_size(); 306 estimated -= perm_gen()->reserved().byte_size(); 307 if (UseAdaptiveSizePolicy) { 308 estimated -= _size_policy->max_survivor_size(young_gen()->max_size()); 309 } else { 310 estimated -= young_gen()->to_space()->capacity_in_bytes(); 311 } 312 return MAX2(estimated, capacity()); 313 } 314 315 bool ParallelScavengeHeap::is_in(const void* p) const { 316 if (young_gen()->is_in(p)) { 317 return true; 318 } 319 320 if (old_gen()->is_in(p)) { 321 return true; 322 } 323 324 if (perm_gen()->is_in(p)) { 325 return true; 326 } 327 328 return false; 329 } 330 331 bool ParallelScavengeHeap::is_in_reserved(const void* p) const { 332 if (young_gen()->is_in_reserved(p)) { 333 return true; 334 } 335 336 if (old_gen()->is_in_reserved(p)) { 337 return true; 338 } 339 340 if (perm_gen()->is_in_reserved(p)) { 341 return true; 342 } 343 344 return false; 345 } 346 347 bool ParallelScavengeHeap::is_scavengable(const void* addr) { 348 return is_in_young((oop)addr); 349 } 350 351 #ifdef ASSERT 352 // Don't implement this by using is_in_young(). This method is used 353 // in some cases to check that is_in_young() is correct. 354 bool ParallelScavengeHeap::is_in_partial_collection(const void *p) { 355 assert(is_in_reserved(p) || p == NULL, 356 "Does not work if address is non-null and outside of the heap"); 357 // The order of the generations is perm (low addr), old, young (high addr) 358 return p >= old_gen()->reserved().end(); 359 } 360 #endif 361 362 // There are two levels of allocation policy here. 363 // 364 // When an allocation request fails, the requesting thread must invoke a VM 365 // operation, transfer control to the VM thread, and await the results of a 366 // garbage collection. That is quite expensive, and we should avoid doing it 367 // multiple times if possible. 368 // 369 // To accomplish this, we have a basic allocation policy, and also a 370 // failed allocation policy. 371 // 372 // The basic allocation policy controls how you allocate memory without 373 // attempting garbage collection. It is okay to grab locks and 374 // expand the heap, if that can be done without coming to a safepoint. 375 // It is likely that the basic allocation policy will not be very 376 // aggressive. 377 // 378 // The failed allocation policy is invoked from the VM thread after 379 // the basic allocation policy is unable to satisfy a mem_allocate 380 // request. This policy needs to cover the entire range of collection, 381 // heap expansion, and out-of-memory conditions. It should make every 382 // attempt to allocate the requested memory. 383 384 // Basic allocation policy. Should never be called at a safepoint, or 385 // from the VM thread. 386 // 387 // This method must handle cases where many mem_allocate requests fail 388 // simultaneously. When that happens, only one VM operation will succeed, 389 // and the rest will not be executed. For that reason, this method loops 390 // during failed allocation attempts. If the java heap becomes exhausted, 391 // we rely on the size_policy object to force a bail out. 392 HeapWord* ParallelScavengeHeap::mem_allocate( 393 size_t size, 394 bool* gc_overhead_limit_was_exceeded) { 395 assert(!SafepointSynchronize::is_at_safepoint(), "should not be at safepoint"); 396 assert(Thread::current() != (Thread*)VMThread::vm_thread(), "should not be in vm thread"); 397 assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock"); 398 399 // In general gc_overhead_limit_was_exceeded should be false so 400 // set it so here and reset it to true only if the gc time 401 // limit is being exceeded as checked below. 402 *gc_overhead_limit_was_exceeded = false; 403 404 HeapWord* result = young_gen()->allocate(size); 405 406 uint loop_count = 0; 407 uint gc_count = 0; 408 409 while (result == NULL) { 410 // We don't want to have multiple collections for a single filled generation. 411 // To prevent this, each thread tracks the total_collections() value, and if 412 // the count has changed, does not do a new collection. 413 // 414 // The collection count must be read only while holding the heap lock. VM 415 // operations also hold the heap lock during collections. There is a lock 416 // contention case where thread A blocks waiting on the Heap_lock, while 417 // thread B is holding it doing a collection. When thread A gets the lock, 418 // the collection count has already changed. To prevent duplicate collections, 419 // The policy MUST attempt allocations during the same period it reads the 420 // total_collections() value! 421 { 422 MutexLocker ml(Heap_lock); 423 gc_count = Universe::heap()->total_collections(); 424 425 result = young_gen()->allocate(size); 426 if (result != NULL) { 427 return result; 428 } 429 430 // If certain conditions hold, try allocating from the old gen. 431 result = mem_allocate_old_gen(size); 432 if (result != NULL) { 433 return result; 434 } 435 436 // Failed to allocate without a gc. 437 if (GC_locker::is_active_and_needs_gc()) { 438 // If this thread is not in a jni critical section, we stall 439 // the requestor until the critical section has cleared and 440 // GC allowed. When the critical section clears, a GC is 441 // initiated by the last thread exiting the critical section; so 442 // we retry the allocation sequence from the beginning of the loop, 443 // rather than causing more, now probably unnecessary, GC attempts. 444 JavaThread* jthr = JavaThread::current(); 445 if (!jthr->in_critical()) { 446 MutexUnlocker mul(Heap_lock); 447 GC_locker::stall_until_clear(); 448 continue; 449 } else { 450 if (CheckJNICalls) { 451 fatal("Possible deadlock due to allocating while" 452 " in jni critical section"); 453 } 454 return NULL; 455 } 456 } 457 } 458 459 if (result == NULL) { 460 // Generate a VM operation 461 VM_ParallelGCFailedAllocation op(size, gc_count); 462 VMThread::execute(&op); 463 464 // Did the VM operation execute? If so, return the result directly. 465 // This prevents us from looping until time out on requests that can 466 // not be satisfied. 467 if (op.prologue_succeeded()) { 468 assert(Universe::heap()->is_in_or_null(op.result()), 469 "result not in heap"); 470 471 // If GC was locked out during VM operation then retry allocation 472 // and/or stall as necessary. 473 if (op.gc_locked()) { 474 assert(op.result() == NULL, "must be NULL if gc_locked() is true"); 475 continue; // retry and/or stall as necessary 476 } 477 478 // Exit the loop if the gc time limit has been exceeded. 479 // The allocation must have failed above ("result" guarding 480 // this path is NULL) and the most recent collection has exceeded the 481 // gc overhead limit (although enough may have been collected to 482 // satisfy the allocation). Exit the loop so that an out-of-memory 483 // will be thrown (return a NULL ignoring the contents of 484 // op.result()), 485 // but clear gc_overhead_limit_exceeded so that the next collection 486 // starts with a clean slate (i.e., forgets about previous overhead 487 // excesses). Fill op.result() with a filler object so that the 488 // heap remains parsable. 489 const bool limit_exceeded = size_policy()->gc_overhead_limit_exceeded(); 490 const bool softrefs_clear = collector_policy()->all_soft_refs_clear(); 491 assert(!limit_exceeded || softrefs_clear, "Should have been cleared"); 492 if (limit_exceeded && softrefs_clear) { 493 *gc_overhead_limit_was_exceeded = true; 494 size_policy()->set_gc_overhead_limit_exceeded(false); 495 if (PrintGCDetails && Verbose) { 496 gclog_or_tty->print_cr("ParallelScavengeHeap::mem_allocate: " 497 "return NULL because gc_overhead_limit_exceeded is set"); 498 } 499 if (op.result() != NULL) { 500 CollectedHeap::fill_with_object(op.result(), size); 501 } 502 return NULL; 503 } 504 505 return op.result(); 506 } 507 } 508 509 // The policy object will prevent us from looping forever. If the 510 // time spent in gc crosses a threshold, we will bail out. 511 loop_count++; 512 if ((result == NULL) && (QueuedAllocationWarningCount > 0) && 513 (loop_count % QueuedAllocationWarningCount == 0)) { 514 warning("ParallelScavengeHeap::mem_allocate retries %d times \n\t" 515 " size=%d", loop_count, size); 516 } 517 } 518 519 return result; 520 } 521 522 // A "death march" is a series of ultra-slow allocations in which a full gc is 523 // done before each allocation, and after the full gc the allocation still 524 // cannot be satisfied from the young gen. This routine detects that condition; 525 // it should be called after a full gc has been done and the allocation 526 // attempted from the young gen. The parameter 'addr' should be the result of 527 // that young gen allocation attempt. 528 void 529 ParallelScavengeHeap::death_march_check(HeapWord* const addr, size_t size) { 530 if (addr != NULL) { 531 _death_march_count = 0; // death march has ended 532 } else if (_death_march_count == 0) { 533 if (should_alloc_in_eden(size)) { 534 _death_march_count = 1; // death march has started 535 } 536 } 537 } 538 539 HeapWord* ParallelScavengeHeap::mem_allocate_old_gen(size_t size) { 540 if (!should_alloc_in_eden(size) || GC_locker::is_active_and_needs_gc()) { 541 // Size is too big for eden, or gc is locked out. 542 return old_gen()->allocate(size); 543 } 544 545 // If a "death march" is in progress, allocate from the old gen a limited 546 // number of times before doing a GC. 547 if (_death_march_count > 0) { 548 if (_death_march_count < 64) { 549 ++_death_march_count; 550 return old_gen()->allocate(size); 551 } else { 552 _death_march_count = 0; 553 } 554 } 555 return NULL; 556 } 557 558 // Failed allocation policy. Must be called from the VM thread, and 559 // only at a safepoint! Note that this method has policy for allocation 560 // flow, and NOT collection policy. So we do not check for gc collection 561 // time over limit here, that is the responsibility of the heap specific 562 // collection methods. This method decides where to attempt allocations, 563 // and when to attempt collections, but no collection specific policy. 564 HeapWord* ParallelScavengeHeap::failed_mem_allocate(size_t size) { 565 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint"); 566 assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread"); 567 assert(!Universe::heap()->is_gc_active(), "not reentrant"); 568 assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock"); 569 570 // We assume that allocation in eden will fail unless we collect. 571 572 // First level allocation failure, scavenge and allocate in young gen. 573 GCCauseSetter gccs(this, GCCause::_allocation_failure); 574 const bool invoked_full_gc = PSScavenge::invoke(); 575 HeapWord* result = young_gen()->allocate(size); 576 577 // Second level allocation failure. 578 // Mark sweep and allocate in young generation. 579 if (result == NULL && !invoked_full_gc) { 580 invoke_full_gc(false); 581 result = young_gen()->allocate(size); 582 } 583 584 death_march_check(result, size); 585 586 // Third level allocation failure. 587 // After mark sweep and young generation allocation failure, 588 // allocate in old generation. 589 if (result == NULL) { 590 result = old_gen()->allocate(size); 591 } 592 593 // Fourth level allocation failure. We're running out of memory. 594 // More complete mark sweep and allocate in young generation. 595 if (result == NULL) { 596 invoke_full_gc(true); 597 result = young_gen()->allocate(size); 598 } 599 600 // Fifth level allocation failure. 601 // After more complete mark sweep, allocate in old generation. 602 if (result == NULL) { 603 result = old_gen()->allocate(size); 604 } 605 606 return result; 607 } 608 609 // 610 // This is the policy loop for allocating in the permanent generation. 611 // If the initial allocation fails, we create a vm operation which will 612 // cause a collection. 613 HeapWord* ParallelScavengeHeap::permanent_mem_allocate(size_t size) { 614 assert(!SafepointSynchronize::is_at_safepoint(), "should not be at safepoint"); 615 assert(Thread::current() != (Thread*)VMThread::vm_thread(), "should not be in vm thread"); 616 assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock"); 617 618 HeapWord* result; 619 620 uint loop_count = 0; 621 uint gc_count = 0; 622 uint full_gc_count = 0; 623 624 do { 625 // We don't want to have multiple collections for a single filled generation. 626 // To prevent this, each thread tracks the total_collections() value, and if 627 // the count has changed, does not do a new collection. 628 // 629 // The collection count must be read only while holding the heap lock. VM 630 // operations also hold the heap lock during collections. There is a lock 631 // contention case where thread A blocks waiting on the Heap_lock, while 632 // thread B is holding it doing a collection. When thread A gets the lock, 633 // the collection count has already changed. To prevent duplicate collections, 634 // The policy MUST attempt allocations during the same period it reads the 635 // total_collections() value! 636 { 637 MutexLocker ml(Heap_lock); 638 gc_count = Universe::heap()->total_collections(); 639 full_gc_count = Universe::heap()->total_full_collections(); 640 641 result = perm_gen()->allocate_permanent(size); 642 643 if (result != NULL) { 644 return result; 645 } 646 647 if (GC_locker::is_active_and_needs_gc()) { 648 // If this thread is not in a jni critical section, we stall 649 // the requestor until the critical section has cleared and 650 // GC allowed. When the critical section clears, a GC is 651 // initiated by the last thread exiting the critical section; so 652 // we retry the allocation sequence from the beginning of the loop, 653 // rather than causing more, now probably unnecessary, GC attempts. 654 JavaThread* jthr = JavaThread::current(); 655 if (!jthr->in_critical()) { 656 MutexUnlocker mul(Heap_lock); 657 GC_locker::stall_until_clear(); 658 continue; 659 } else { 660 if (CheckJNICalls) { 661 fatal("Possible deadlock due to allocating while" 662 " in jni critical section"); 663 } 664 return NULL; 665 } 666 } 667 } 668 669 if (result == NULL) { 670 671 // Exit the loop if the gc time limit has been exceeded. 672 // The allocation must have failed above (result must be NULL), 673 // and the most recent collection must have exceeded the 674 // gc time limit. Exit the loop so that an out-of-memory 675 // will be thrown (returning a NULL will do that), but 676 // clear gc_overhead_limit_exceeded so that the next collection 677 // will succeeded if the applications decides to handle the 678 // out-of-memory and tries to go on. 679 const bool limit_exceeded = size_policy()->gc_overhead_limit_exceeded(); 680 if (limit_exceeded) { 681 size_policy()->set_gc_overhead_limit_exceeded(false); 682 if (PrintGCDetails && Verbose) { 683 gclog_or_tty->print_cr("ParallelScavengeHeap::permanent_mem_allocate:" 684 " return NULL because gc_overhead_limit_exceeded is set"); 685 } 686 assert(result == NULL, "Allocation did not fail"); 687 return NULL; 688 } 689 690 // Generate a VM operation 691 VM_ParallelGCFailedPermanentAllocation op(size, gc_count, full_gc_count); 692 VMThread::execute(&op); 693 694 // Did the VM operation execute? If so, return the result directly. 695 // This prevents us from looping until time out on requests that can 696 // not be satisfied. 697 if (op.prologue_succeeded()) { 698 assert(Universe::heap()->is_in_permanent_or_null(op.result()), 699 "result not in heap"); 700 // If GC was locked out during VM operation then retry allocation 701 // and/or stall as necessary. 702 if (op.gc_locked()) { 703 assert(op.result() == NULL, "must be NULL if gc_locked() is true"); 704 continue; // retry and/or stall as necessary 705 } 706 // If a NULL results is being returned, an out-of-memory 707 // will be thrown now. Clear the gc_overhead_limit_exceeded 708 // flag to avoid the following situation. 709 // gc_overhead_limit_exceeded is set during a collection 710 // the collection fails to return enough space and an OOM is thrown 711 // a subsequent GC prematurely throws an out-of-memory because 712 // the gc_overhead_limit_exceeded counts did not start 713 // again from 0. 714 if (op.result() == NULL) { 715 size_policy()->reset_gc_overhead_limit_count(); 716 } 717 return op.result(); 718 } 719 } 720 721 // The policy object will prevent us from looping forever. If the 722 // time spent in gc crosses a threshold, we will bail out. 723 loop_count++; 724 if ((QueuedAllocationWarningCount > 0) && 725 (loop_count % QueuedAllocationWarningCount == 0)) { 726 warning("ParallelScavengeHeap::permanent_mem_allocate retries %d times \n\t" 727 " size=%d", loop_count, size); 728 } 729 } while (result == NULL); 730 731 return result; 732 } 733 734 // 735 // This is the policy code for permanent allocations which have failed 736 // and require a collection. Note that just as in failed_mem_allocate, 737 // we do not set collection policy, only where & when to allocate and 738 // collect. 739 HeapWord* ParallelScavengeHeap::failed_permanent_mem_allocate(size_t size) { 740 assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint"); 741 assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread"); 742 assert(!Universe::heap()->is_gc_active(), "not reentrant"); 743 assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock"); 744 assert(size > perm_gen()->free_in_words(), "Allocation should fail"); 745 746 // We assume (and assert!) that an allocation at this point will fail 747 // unless we collect. 748 749 // First level allocation failure. Mark-sweep and allocate in perm gen. 750 GCCauseSetter gccs(this, GCCause::_allocation_failure); 751 invoke_full_gc(false); 752 HeapWord* result = perm_gen()->allocate_permanent(size); 753 754 // Second level allocation failure. We're running out of memory. 755 if (result == NULL) { 756 invoke_full_gc(true); 757 result = perm_gen()->allocate_permanent(size); 758 } 759 760 return result; 761 } 762 763 void ParallelScavengeHeap::ensure_parsability(bool retire_tlabs) { 764 CollectedHeap::ensure_parsability(retire_tlabs); 765 young_gen()->eden_space()->ensure_parsability(); 766 } 767 768 size_t ParallelScavengeHeap::unsafe_max_alloc() { 769 return young_gen()->eden_space()->free_in_bytes(); 770 } 771 772 size_t ParallelScavengeHeap::tlab_capacity(Thread* thr) const { 773 return young_gen()->eden_space()->tlab_capacity(thr); 774 } 775 776 size_t ParallelScavengeHeap::unsafe_max_tlab_alloc(Thread* thr) const { 777 return young_gen()->eden_space()->unsafe_max_tlab_alloc(thr); 778 } 779 780 HeapWord* ParallelScavengeHeap::allocate_new_tlab(size_t size) { 781 return young_gen()->allocate(size); 782 } 783 784 void ParallelScavengeHeap::accumulate_statistics_all_tlabs() { 785 CollectedHeap::accumulate_statistics_all_tlabs(); 786 } 787 788 void ParallelScavengeHeap::resize_all_tlabs() { 789 CollectedHeap::resize_all_tlabs(); 790 } 791 792 bool ParallelScavengeHeap::can_elide_initializing_store_barrier(oop new_obj) { 793 // We don't need barriers for stores to objects in the 794 // young gen and, a fortiori, for initializing stores to 795 // objects therein. 796 return is_in_young(new_obj); 797 } 798 799 // This method is used by System.gc() and JVMTI. 800 void ParallelScavengeHeap::collect(GCCause::Cause cause) { 801 assert(!Heap_lock->owned_by_self(), 802 "this thread should not own the Heap_lock"); 803 804 unsigned int gc_count = 0; 805 unsigned int full_gc_count = 0; 806 { 807 MutexLocker ml(Heap_lock); 808 // This value is guarded by the Heap_lock 809 gc_count = Universe::heap()->total_collections(); 810 full_gc_count = Universe::heap()->total_full_collections(); 811 } 812 813 VM_ParallelGCSystemGC op(gc_count, full_gc_count, cause); 814 VMThread::execute(&op); 815 } 816 817 // This interface assumes that it's being called by the 818 // vm thread. It collects the heap assuming that the 819 // heap lock is already held and that we are executing in 820 // the context of the vm thread. 821 void ParallelScavengeHeap::collect_as_vm_thread(GCCause::Cause cause) { 822 assert(Thread::current()->is_VM_thread(), "Precondition#1"); 823 assert(Heap_lock->is_locked(), "Precondition#2"); 824 GCCauseSetter gcs(this, cause); 825 switch (cause) { 826 case GCCause::_heap_inspection: 827 case GCCause::_heap_dump: { 828 HandleMark hm; 829 invoke_full_gc(false); 830 break; 831 } 832 default: // XXX FIX ME 833 ShouldNotReachHere(); 834 } 835 } 836 837 838 void ParallelScavengeHeap::oop_iterate(OopClosure* cl) { 839 Unimplemented(); 840 } 841 842 void ParallelScavengeHeap::object_iterate(ObjectClosure* cl) { 843 young_gen()->object_iterate(cl); 844 old_gen()->object_iterate(cl); 845 perm_gen()->object_iterate(cl); 846 } 847 848 void ParallelScavengeHeap::permanent_oop_iterate(OopClosure* cl) { 849 Unimplemented(); 850 } 851 852 void ParallelScavengeHeap::permanent_object_iterate(ObjectClosure* cl) { 853 perm_gen()->object_iterate(cl); 854 } 855 856 HeapWord* ParallelScavengeHeap::block_start(const void* addr) const { 857 if (young_gen()->is_in_reserved(addr)) { 858 assert(young_gen()->is_in(addr), 859 "addr should be in allocated part of young gen"); 860 // called from os::print_location by find or VMError 861 if (Debugging || VMError::fatal_error_in_progress()) return NULL; 862 Unimplemented(); 863 } else if (old_gen()->is_in_reserved(addr)) { 864 assert(old_gen()->is_in(addr), 865 "addr should be in allocated part of old gen"); 866 return old_gen()->start_array()->object_start((HeapWord*)addr); 867 } else if (perm_gen()->is_in_reserved(addr)) { 868 assert(perm_gen()->is_in(addr), 869 "addr should be in allocated part of perm gen"); 870 return perm_gen()->start_array()->object_start((HeapWord*)addr); 871 } 872 return 0; 873 } 874 875 size_t ParallelScavengeHeap::block_size(const HeapWord* addr) const { 876 return oop(addr)->size(); 877 } 878 879 bool ParallelScavengeHeap::block_is_obj(const HeapWord* addr) const { 880 return block_start(addr) == addr; 881 } 882 883 jlong ParallelScavengeHeap::millis_since_last_gc() { 884 return UseParallelOldGC ? 885 PSParallelCompact::millis_since_last_gc() : 886 PSMarkSweep::millis_since_last_gc(); 887 } 888 889 void ParallelScavengeHeap::prepare_for_verify() { 890 ensure_parsability(false); // no need to retire TLABs for verification 891 } 892 893 PSHeapSummary ParallelScavengeHeap::create_ps_heap_summary() { 894 PSOldGen* old = old_gen(); 895 HeapWord* old_committed_end = (HeapWord*)old->virtual_space()->committed_high_addr(); 896 VirtualSpaceSummary old_summary(old->reserved().start(), old_committed_end, old->reserved().end()); 897 SpaceSummary old_space(old->reserved().start(), old_committed_end, old->used_in_bytes()); 898 899 PSYoungGen* young = young_gen(); 900 VirtualSpaceSummary young_summary(young->reserved().start(), 901 (HeapWord*)young->virtual_space()->committed_high_addr(), young->reserved().end()); 902 903 MutableSpace* eden = young_gen()->eden_space(); 904 SpaceSummary eden_space(eden->bottom(), eden->end(), eden->used_in_bytes()); 905 906 MutableSpace* from = young_gen()->from_space(); 907 SpaceSummary from_space(from->bottom(), from->end(), from->used_in_bytes()); 908 909 MutableSpace* to = young_gen()->to_space(); 910 SpaceSummary to_space(to->bottom(), to->end(), to->used_in_bytes()); 911 912 VirtualSpaceSummary heap_summary = create_heap_space_summary(); 913 return PSHeapSummary(heap_summary, used(), old_summary, old_space, young_summary, eden_space, from_space, to_space); 914 } 915 916 VirtualSpaceSummary ParallelScavengeHeap::create_perm_gen_space_summary() { 917 PSVirtualSpace* space = perm_gen()->virtual_space(); 918 return VirtualSpaceSummary( 919 (HeapWord*)space->low_boundary(), 920 (HeapWord*)space->high(), 921 (HeapWord*)space->high_boundary()); 922 } 923 924 void ParallelScavengeHeap::print_on(outputStream* st) const { 925 young_gen()->print_on(st); 926 old_gen()->print_on(st); 927 perm_gen()->print_on(st); 928 } 929 930 void ParallelScavengeHeap::gc_threads_do(ThreadClosure* tc) const { 931 PSScavenge::gc_task_manager()->threads_do(tc); 932 } 933 934 void ParallelScavengeHeap::print_gc_threads_on(outputStream* st) const { 935 PSScavenge::gc_task_manager()->print_threads_on(st); 936 } 937 938 void ParallelScavengeHeap::print_tracing_info() const { 939 if (TraceGen0Time) { 940 double time = PSScavenge::accumulated_time()->seconds(); 941 tty->print_cr("[Accumulated GC generation 0 time %3.7f secs]", time); 942 } 943 if (TraceGen1Time) { 944 double time = PSMarkSweep::accumulated_time()->seconds(); 945 tty->print_cr("[Accumulated GC generation 1 time %3.7f secs]", time); 946 } 947 } 948 949 950 void ParallelScavengeHeap::verify(bool silent, VerifyOption option /* ignored */) { 951 // Why do we need the total_collections()-filter below? 952 if (total_collections() > 0) { 953 if (!silent) { 954 gclog_or_tty->print("permanent "); 955 } 956 perm_gen()->verify(); 957 958 if (!silent) { 959 gclog_or_tty->print("tenured "); 960 } 961 old_gen()->verify(); 962 963 if (!silent) { 964 gclog_or_tty->print("eden "); 965 } 966 young_gen()->verify(); 967 } 968 } 969 970 void ParallelScavengeHeap::print_heap_change(size_t prev_used) { 971 if (PrintGCDetails && Verbose) { 972 gclog_or_tty->print(" " SIZE_FORMAT 973 "->" SIZE_FORMAT 974 "(" SIZE_FORMAT ")", 975 prev_used, used(), capacity()); 976 } else { 977 gclog_or_tty->print(" " SIZE_FORMAT "K" 978 "->" SIZE_FORMAT "K" 979 "(" SIZE_FORMAT "K)", 980 prev_used / K, used() / K, capacity() / K); 981 } 982 } 983 984 void ParallelScavengeHeap::trace_heap(GCWhen::Type when, GCTracer* gc_tracer) { 985 const PSHeapSummary& heap_summary = create_ps_heap_summary(); 986 const PermGenSummary& perm_gen_summary = create_perm_gen_summary(); 987 gc_tracer->report_gc_heap_summary(when, heap_summary, perm_gen_summary); 988 } 989 990 ParallelScavengeHeap* ParallelScavengeHeap::heap() { 991 assert(_psh != NULL, "Uninitialized access to ParallelScavengeHeap::heap()"); 992 assert(_psh->kind() == CollectedHeap::ParallelScavengeHeap, "not a parallel scavenge heap"); 993 return _psh; 994 } 995 996 // Before delegating the resize to the young generation, 997 // the reserved space for the young and old generations 998 // may be changed to accomodate the desired resize. 999 void ParallelScavengeHeap::resize_young_gen(size_t eden_size, 1000 size_t survivor_size) { 1001 if (UseAdaptiveGCBoundary) { 1002 if (size_policy()->bytes_absorbed_from_eden() != 0) { 1003 size_policy()->reset_bytes_absorbed_from_eden(); 1004 return; // The generation changed size already. 1005 } 1006 gens()->adjust_boundary_for_young_gen_needs(eden_size, survivor_size); 1007 } 1008 1009 // Delegate the resize to the generation. 1010 _young_gen->resize(eden_size, survivor_size); 1011 } 1012 1013 // Before delegating the resize to the old generation, 1014 // the reserved space for the young and old generations 1015 // may be changed to accomodate the desired resize. 1016 void ParallelScavengeHeap::resize_old_gen(size_t desired_free_space) { 1017 if (UseAdaptiveGCBoundary) { 1018 if (size_policy()->bytes_absorbed_from_eden() != 0) { 1019 size_policy()->reset_bytes_absorbed_from_eden(); 1020 return; // The generation changed size already. 1021 } 1022 gens()->adjust_boundary_for_old_gen_needs(desired_free_space); 1023 } 1024 1025 // Delegate the resize to the generation. 1026 _old_gen->resize(desired_free_space); 1027 } 1028 1029 ParallelScavengeHeap::ParStrongRootsScope::ParStrongRootsScope() { 1030 // nothing particular 1031 } 1032 1033 ParallelScavengeHeap::ParStrongRootsScope::~ParStrongRootsScope() { 1034 // nothing particular 1035 } 1036 1037 #ifndef PRODUCT 1038 void ParallelScavengeHeap::record_gen_tops_before_GC() { 1039 if (ZapUnusedHeapArea) { 1040 young_gen()->record_spaces_top(); 1041 old_gen()->record_spaces_top(); 1042 perm_gen()->record_spaces_top(); 1043 } 1044 } 1045 1046 void ParallelScavengeHeap::gen_mangle_unused_area() { 1047 if (ZapUnusedHeapArea) { 1048 young_gen()->eden_space()->mangle_unused_area(); 1049 young_gen()->to_space()->mangle_unused_area(); 1050 young_gen()->from_space()->mangle_unused_area(); 1051 old_gen()->object_space()->mangle_unused_area(); 1052 perm_gen()->object_space()->mangle_unused_area(); 1053 } 1054 } 1055 #endif