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