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