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