Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/gc_implementation/parNew/parNewGeneration.cpp
38920 views
/*1* Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*22*/2324#include "precompiled.hpp"25#include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp"26#include "gc_implementation/parNew/parNewGeneration.hpp"27#include "gc_implementation/parNew/parOopClosures.inline.hpp"28#include "gc_implementation/shared/adaptiveSizePolicy.hpp"29#include "gc_implementation/shared/ageTable.hpp"30#include "gc_implementation/shared/copyFailedInfo.hpp"31#include "gc_implementation/shared/gcHeapSummary.hpp"32#include "gc_implementation/shared/gcTimer.hpp"33#include "gc_implementation/shared/gcTrace.hpp"34#include "gc_implementation/shared/gcTraceTime.hpp"35#include "gc_implementation/shared/parGCAllocBuffer.inline.hpp"36#include "gc_implementation/shared/spaceDecorator.hpp"37#include "memory/defNewGeneration.inline.hpp"38#include "memory/genCollectedHeap.hpp"39#include "memory/genOopClosures.inline.hpp"40#include "memory/generation.hpp"41#include "memory/generation.inline.hpp"42#include "memory/referencePolicy.hpp"43#include "memory/resourceArea.hpp"44#include "memory/sharedHeap.hpp"45#include "memory/space.hpp"46#include "oops/objArrayOop.hpp"47#include "oops/oop.inline.hpp"48#include "oops/oop.pcgc.inline.hpp"49#include "runtime/handles.hpp"50#include "runtime/handles.inline.hpp"51#include "runtime/java.hpp"52#include "runtime/thread.inline.hpp"53#include "utilities/copy.hpp"54#include "utilities/globalDefinitions.hpp"55#include "utilities/workgroup.hpp"5657PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC5859#ifdef _MSC_VER60#pragma warning( push )61#pragma warning( disable:4355 ) // 'this' : used in base member initializer list62#endif63ParScanThreadState::ParScanThreadState(Space* to_space_,64ParNewGeneration* gen_,65Generation* old_gen_,66int thread_num_,67ObjToScanQueueSet* work_queue_set_,68Stack<oop, mtGC>* overflow_stacks_,69size_t desired_plab_sz_,70ParallelTaskTerminator& term_) :71_to_space(to_space_), _old_gen(old_gen_), _young_gen(gen_), _thread_num(thread_num_),72_work_queue(work_queue_set_->queue(thread_num_)), _to_space_full(false),73_overflow_stack(overflow_stacks_ ? overflow_stacks_ + thread_num_ : NULL),74_ageTable(false), // false ==> not the global age table, no perf data.75_to_space_alloc_buffer(desired_plab_sz_),76_to_space_closure(gen_, this), _old_gen_closure(gen_, this),77_to_space_root_closure(gen_, this), _old_gen_root_closure(gen_, this),78_older_gen_closure(gen_, this),79_evacuate_followers(this, &_to_space_closure, &_old_gen_closure,80&_to_space_root_closure, gen_, &_old_gen_root_closure,81work_queue_set_, &term_),82_is_alive_closure(gen_), _scan_weak_ref_closure(gen_, this),83_keep_alive_closure(&_scan_weak_ref_closure),84_strong_roots_time(0.0), _term_time(0.0)85{86#if TASKQUEUE_STATS87_term_attempts = 0;88_overflow_refills = 0;89_overflow_refill_objs = 0;90#endif // TASKQUEUE_STATS9192_survivor_chunk_array =93(ChunkArray*) old_gen()->get_data_recorder(thread_num());94_hash_seed = 17; // Might want to take time-based random value.95_start = os::elapsedTime();96_old_gen_closure.set_generation(old_gen_);97_old_gen_root_closure.set_generation(old_gen_);98}99#ifdef _MSC_VER100#pragma warning( pop )101#endif102103void ParScanThreadState::record_survivor_plab(HeapWord* plab_start,104size_t plab_word_size) {105ChunkArray* sca = survivor_chunk_array();106if (sca != NULL) {107// A non-null SCA implies that we want the PLAB data recorded.108sca->record_sample(plab_start, plab_word_size);109}110}111112bool ParScanThreadState::should_be_partially_scanned(oop new_obj, oop old_obj) const {113return new_obj->is_objArray() &&114arrayOop(new_obj)->length() > ParGCArrayScanChunk &&115new_obj != old_obj;116}117118void ParScanThreadState::scan_partial_array_and_push_remainder(oop old) {119assert(old->is_objArray(), "must be obj array");120assert(old->is_forwarded(), "must be forwarded");121assert(Universe::heap()->is_in_reserved(old), "must be in heap.");122assert(!old_gen()->is_in(old), "must be in young generation.");123124objArrayOop obj = objArrayOop(old->forwardee());125// Process ParGCArrayScanChunk elements now126// and push the remainder back onto queue127int start = arrayOop(old)->length();128int end = obj->length();129int remainder = end - start;130assert(start <= end, "just checking");131if (remainder > 2 * ParGCArrayScanChunk) {132// Test above combines last partial chunk with a full chunk133end = start + ParGCArrayScanChunk;134arrayOop(old)->set_length(end);135// Push remainder.136bool ok = work_queue()->push(old);137assert(ok, "just popped, push must be okay");138} else {139// Restore length so that it can be used if there140// is a promotion failure and forwarding pointers141// must be removed.142arrayOop(old)->set_length(end);143}144145// process our set of indices (include header in first chunk)146// should make sure end is even (aligned to HeapWord in case of compressed oops)147if ((HeapWord *)obj < young_old_boundary()) {148// object is in to_space149obj->oop_iterate_range(&_to_space_closure, start, end);150} else {151// object is in old generation152obj->oop_iterate_range(&_old_gen_closure, start, end);153}154}155156157void ParScanThreadState::trim_queues(int max_size) {158ObjToScanQueue* queue = work_queue();159do {160while (queue->size() > (juint)max_size) {161oop obj_to_scan;162if (queue->pop_local(obj_to_scan)) {163if ((HeapWord *)obj_to_scan < young_old_boundary()) {164if (obj_to_scan->is_objArray() &&165obj_to_scan->is_forwarded() &&166obj_to_scan->forwardee() != obj_to_scan) {167scan_partial_array_and_push_remainder(obj_to_scan);168} else {169// object is in to_space170obj_to_scan->oop_iterate(&_to_space_closure);171}172} else {173// object is in old generation174obj_to_scan->oop_iterate(&_old_gen_closure);175}176}177}178// For the case of compressed oops, we have a private, non-shared179// overflow stack, so we eagerly drain it so as to more evenly180// distribute load early. Note: this may be good to do in181// general rather than delay for the final stealing phase.182// If applicable, we'll transfer a set of objects over to our183// work queue, allowing them to be stolen and draining our184// private overflow stack.185} while (ParGCTrimOverflow && young_gen()->take_from_overflow_list(this));186}187188bool ParScanThreadState::take_from_overflow_stack() {189assert(ParGCUseLocalOverflow, "Else should not call");190assert(young_gen()->overflow_list() == NULL, "Error");191ObjToScanQueue* queue = work_queue();192Stack<oop, mtGC>* const of_stack = overflow_stack();193const size_t num_overflow_elems = of_stack->size();194const size_t space_available = queue->max_elems() - queue->size();195const size_t num_take_elems = MIN3(space_available / 4,196ParGCDesiredObjsFromOverflowList,197num_overflow_elems);198// Transfer the most recent num_take_elems from the overflow199// stack to our work queue.200for (size_t i = 0; i != num_take_elems; i++) {201oop cur = of_stack->pop();202oop obj_to_push = cur->forwardee();203assert(Universe::heap()->is_in_reserved(cur), "Should be in heap");204assert(!old_gen()->is_in_reserved(cur), "Should be in young gen");205assert(Universe::heap()->is_in_reserved(obj_to_push), "Should be in heap");206if (should_be_partially_scanned(obj_to_push, cur)) {207assert(arrayOop(cur)->length() == 0, "entire array remaining to be scanned");208obj_to_push = cur;209}210bool ok = queue->push(obj_to_push);211assert(ok, "Should have succeeded");212}213assert(young_gen()->overflow_list() == NULL, "Error");214return num_take_elems > 0; // was something transferred?215}216217void ParScanThreadState::push_on_overflow_stack(oop p) {218assert(ParGCUseLocalOverflow, "Else should not call");219overflow_stack()->push(p);220assert(young_gen()->overflow_list() == NULL, "Error");221}222223HeapWord* ParScanThreadState::alloc_in_to_space_slow(size_t word_sz) {224225// Otherwise, if the object is small enough, try to reallocate the226// buffer.227HeapWord* obj = NULL;228if (!_to_space_full) {229ParGCAllocBuffer* const plab = to_space_alloc_buffer();230Space* const sp = to_space();231if (word_sz * 100 <232ParallelGCBufferWastePct * plab->word_sz()) {233// Is small enough; abandon this buffer and start a new one.234plab->retire(false, false);235size_t buf_size = plab->word_sz();236HeapWord* buf_space = sp->par_allocate(buf_size);237if (buf_space == NULL) {238const size_t min_bytes =239ParGCAllocBuffer::min_size() << LogHeapWordSize;240size_t free_bytes = sp->free();241while(buf_space == NULL && free_bytes >= min_bytes) {242buf_size = free_bytes >> LogHeapWordSize;243assert(buf_size == (size_t)align_object_size(buf_size),244"Invariant");245buf_space = sp->par_allocate(buf_size);246free_bytes = sp->free();247}248}249if (buf_space != NULL) {250plab->set_word_size(buf_size);251plab->set_buf(buf_space);252record_survivor_plab(buf_space, buf_size);253obj = plab->allocate_aligned(word_sz, SurvivorAlignmentInBytes);254// Note that we cannot compare buf_size < word_sz below255// because of AlignmentReserve (see ParGCAllocBuffer::allocate()).256assert(obj != NULL || plab->words_remaining() < word_sz,257"Else should have been able to allocate");258// It's conceivable that we may be able to use the259// buffer we just grabbed for subsequent small requests260// even if not for this one.261} else {262// We're used up.263_to_space_full = true;264}265266} else {267// Too large; allocate the object individually.268obj = sp->par_allocate(word_sz);269}270}271return obj;272}273274275void ParScanThreadState::undo_alloc_in_to_space(HeapWord* obj,276size_t word_sz) {277// Is the alloc in the current alloc buffer?278if (to_space_alloc_buffer()->contains(obj)) {279assert(to_space_alloc_buffer()->contains(obj + word_sz - 1),280"Should contain whole object.");281to_space_alloc_buffer()->undo_allocation(obj, word_sz);282} else {283CollectedHeap::fill_with_object(obj, word_sz);284}285}286287void ParScanThreadState::print_promotion_failure_size() {288if (_promotion_failed_info.has_failed() && PrintPromotionFailure) {289gclog_or_tty->print(" (%d: promotion failure size = " SIZE_FORMAT ") ",290_thread_num, _promotion_failed_info.first_size());291}292}293294class ParScanThreadStateSet: private ResourceArray {295public:296// Initializes states for the specified number of threads;297ParScanThreadStateSet(int num_threads,298Space& to_space,299ParNewGeneration& gen,300Generation& old_gen,301ObjToScanQueueSet& queue_set,302Stack<oop, mtGC>* overflow_stacks_,303size_t desired_plab_sz,304ParallelTaskTerminator& term);305306~ParScanThreadStateSet() { TASKQUEUE_STATS_ONLY(reset_stats()); }307308inline ParScanThreadState& thread_state(int i);309310void trace_promotion_failed(YoungGCTracer& gc_tracer);311void reset(int active_workers, bool promotion_failed);312void flush();313314#if TASKQUEUE_STATS315static void316print_termination_stats_hdr(outputStream* const st = gclog_or_tty);317void print_termination_stats(outputStream* const st = gclog_or_tty);318static void319print_taskqueue_stats_hdr(outputStream* const st = gclog_or_tty);320void print_taskqueue_stats(outputStream* const st = gclog_or_tty);321void reset_stats();322#endif // TASKQUEUE_STATS323324private:325ParallelTaskTerminator& _term;326ParNewGeneration& _gen;327Generation& _next_gen;328public:329bool is_valid(int id) const { return id < length(); }330ParallelTaskTerminator* terminator() { return &_term; }331};332333334ParScanThreadStateSet::ParScanThreadStateSet(335int num_threads, Space& to_space, ParNewGeneration& gen,336Generation& old_gen, ObjToScanQueueSet& queue_set,337Stack<oop, mtGC>* overflow_stacks,338size_t desired_plab_sz, ParallelTaskTerminator& term)339: ResourceArray(sizeof(ParScanThreadState), num_threads),340_gen(gen), _next_gen(old_gen), _term(term)341{342assert(num_threads > 0, "sanity check!");343assert(ParGCUseLocalOverflow == (overflow_stacks != NULL),344"overflow_stack allocation mismatch");345// Initialize states.346for (int i = 0; i < num_threads; ++i) {347new ((ParScanThreadState*)_data + i)348ParScanThreadState(&to_space, &gen, &old_gen, i, &queue_set,349overflow_stacks, desired_plab_sz, term);350}351}352353inline ParScanThreadState& ParScanThreadStateSet::thread_state(int i)354{355assert(i >= 0 && i < length(), "sanity check!");356return ((ParScanThreadState*)_data)[i];357}358359void ParScanThreadStateSet::trace_promotion_failed(YoungGCTracer& gc_tracer) {360for (int i = 0; i < length(); ++i) {361if (thread_state(i).promotion_failed()) {362gc_tracer.report_promotion_failed(thread_state(i).promotion_failed_info());363thread_state(i).promotion_failed_info().reset();364}365}366}367368void ParScanThreadStateSet::reset(int active_threads, bool promotion_failed)369{370_term.reset_for_reuse(active_threads);371if (promotion_failed) {372for (int i = 0; i < length(); ++i) {373thread_state(i).print_promotion_failure_size();374}375}376}377378#if TASKQUEUE_STATS379void380ParScanThreadState::reset_stats()381{382taskqueue_stats().reset();383_term_attempts = 0;384_overflow_refills = 0;385_overflow_refill_objs = 0;386}387388void ParScanThreadStateSet::reset_stats()389{390for (int i = 0; i < length(); ++i) {391thread_state(i).reset_stats();392}393}394395void396ParScanThreadStateSet::print_termination_stats_hdr(outputStream* const st)397{398st->print_raw_cr("GC Termination Stats");399st->print_raw_cr(" elapsed --strong roots-- "400"-------termination-------");401st->print_raw_cr("thr ms ms % "402" ms % attempts");403st->print_raw_cr("--- --------- --------- ------ "404"--------- ------ --------");405}406407void ParScanThreadStateSet::print_termination_stats(outputStream* const st)408{409print_termination_stats_hdr(st);410411for (int i = 0; i < length(); ++i) {412const ParScanThreadState & pss = thread_state(i);413const double elapsed_ms = pss.elapsed_time() * 1000.0;414const double s_roots_ms = pss.strong_roots_time() * 1000.0;415const double term_ms = pss.term_time() * 1000.0;416st->print_cr("%3d %9.2f %9.2f %6.2f "417"%9.2f %6.2f " SIZE_FORMAT_W(8),418i, elapsed_ms, s_roots_ms, s_roots_ms * 100 / elapsed_ms,419term_ms, term_ms * 100 / elapsed_ms, pss.term_attempts());420}421}422423// Print stats related to work queue activity.424void ParScanThreadStateSet::print_taskqueue_stats_hdr(outputStream* const st)425{426st->print_raw_cr("GC Task Stats");427st->print_raw("thr "); TaskQueueStats::print_header(1, st); st->cr();428st->print_raw("--- "); TaskQueueStats::print_header(2, st); st->cr();429}430431void ParScanThreadStateSet::print_taskqueue_stats(outputStream* const st)432{433print_taskqueue_stats_hdr(st);434435TaskQueueStats totals;436for (int i = 0; i < length(); ++i) {437const ParScanThreadState & pss = thread_state(i);438const TaskQueueStats & stats = pss.taskqueue_stats();439st->print("%3d ", i); stats.print(st); st->cr();440totals += stats;441442if (pss.overflow_refills() > 0) {443st->print_cr(" " SIZE_FORMAT_W(10) " overflow refills "444SIZE_FORMAT_W(10) " overflow objects",445pss.overflow_refills(), pss.overflow_refill_objs());446}447}448st->print("tot "); totals.print(st); st->cr();449450DEBUG_ONLY(totals.verify());451}452#endif // TASKQUEUE_STATS453454void ParScanThreadStateSet::flush()455{456// Work in this loop should be kept as lightweight as457// possible since this might otherwise become a bottleneck458// to scaling. Should we add heavy-weight work into this459// loop, consider parallelizing the loop into the worker threads.460for (int i = 0; i < length(); ++i) {461ParScanThreadState& par_scan_state = thread_state(i);462463// Flush stats related to To-space PLAB activity and464// retire the last buffer.465par_scan_state.to_space_alloc_buffer()->466flush_stats_and_retire(_gen.plab_stats(),467true /* end_of_gc */,468false /* retain */);469470// Every thread has its own age table. We need to merge471// them all into one.472ageTable *local_table = par_scan_state.age_table();473_gen.age_table()->merge(local_table);474475// Inform old gen that we're done.476_next_gen.par_promote_alloc_done(i);477_next_gen.par_oop_since_save_marks_iterate_done(i);478}479480if (UseConcMarkSweepGC && ParallelGCThreads > 0) {481// We need to call this even when ResizeOldPLAB is disabled482// so as to avoid breaking some asserts. While we may be able483// to avoid this by reorganizing the code a bit, I am loathe484// to do that unless we find cases where ergo leads to bad485// performance.486CFLS_LAB::compute_desired_plab_size();487}488}489490ParScanClosure::ParScanClosure(ParNewGeneration* g,491ParScanThreadState* par_scan_state) :492OopsInKlassOrGenClosure(g), _par_scan_state(par_scan_state), _g(g)493{494assert(_g->level() == 0, "Optimized for youngest generation");495_boundary = _g->reserved().end();496}497498void ParScanWithBarrierClosure::do_oop(oop* p) { ParScanClosure::do_oop_work(p, true, false); }499void ParScanWithBarrierClosure::do_oop(narrowOop* p) { ParScanClosure::do_oop_work(p, true, false); }500501void ParScanWithoutBarrierClosure::do_oop(oop* p) { ParScanClosure::do_oop_work(p, false, false); }502void ParScanWithoutBarrierClosure::do_oop(narrowOop* p) { ParScanClosure::do_oop_work(p, false, false); }503504void ParRootScanWithBarrierTwoGensClosure::do_oop(oop* p) { ParScanClosure::do_oop_work(p, true, true); }505void ParRootScanWithBarrierTwoGensClosure::do_oop(narrowOop* p) { ParScanClosure::do_oop_work(p, true, true); }506507void ParRootScanWithoutBarrierClosure::do_oop(oop* p) { ParScanClosure::do_oop_work(p, false, true); }508void ParRootScanWithoutBarrierClosure::do_oop(narrowOop* p) { ParScanClosure::do_oop_work(p, false, true); }509510ParScanWeakRefClosure::ParScanWeakRefClosure(ParNewGeneration* g,511ParScanThreadState* par_scan_state)512: ScanWeakRefClosure(g), _par_scan_state(par_scan_state)513{}514515void ParScanWeakRefClosure::do_oop(oop* p) { ParScanWeakRefClosure::do_oop_work(p); }516void ParScanWeakRefClosure::do_oop(narrowOop* p) { ParScanWeakRefClosure::do_oop_work(p); }517518#ifdef WIN32519#pragma warning(disable: 4786) /* identifier was truncated to '255' characters in the browser information */520#endif521522ParEvacuateFollowersClosure::ParEvacuateFollowersClosure(523ParScanThreadState* par_scan_state_,524ParScanWithoutBarrierClosure* to_space_closure_,525ParScanWithBarrierClosure* old_gen_closure_,526ParRootScanWithoutBarrierClosure* to_space_root_closure_,527ParNewGeneration* par_gen_,528ParRootScanWithBarrierTwoGensClosure* old_gen_root_closure_,529ObjToScanQueueSet* task_queues_,530ParallelTaskTerminator* terminator_) :531532_par_scan_state(par_scan_state_),533_to_space_closure(to_space_closure_),534_old_gen_closure(old_gen_closure_),535_to_space_root_closure(to_space_root_closure_),536_old_gen_root_closure(old_gen_root_closure_),537_par_gen(par_gen_),538_task_queues(task_queues_),539_terminator(terminator_)540{}541542void ParEvacuateFollowersClosure::do_void() {543ObjToScanQueue* work_q = par_scan_state()->work_queue();544545while (true) {546547// Scan to-space and old-gen objs until we run out of both.548oop obj_to_scan;549par_scan_state()->trim_queues(0);550551// We have no local work, attempt to steal from other threads.552553// attempt to steal work from promoted.554if (task_queues()->steal(par_scan_state()->thread_num(),555par_scan_state()->hash_seed(),556obj_to_scan)) {557bool res = work_q->push(obj_to_scan);558assert(res, "Empty queue should have room for a push.");559560// if successful, goto Start.561continue;562563// try global overflow list.564} else if (par_gen()->take_from_overflow_list(par_scan_state())) {565continue;566}567568// Otherwise, offer termination.569par_scan_state()->start_term_time();570if (terminator()->offer_termination()) break;571par_scan_state()->end_term_time();572}573assert(par_gen()->_overflow_list == NULL && par_gen()->_num_par_pushes == 0,574"Broken overflow list?");575// Finish the last termination pause.576par_scan_state()->end_term_time();577}578579ParNewGenTask::ParNewGenTask(ParNewGeneration* gen, Generation* next_gen,580HeapWord* young_old_boundary, ParScanThreadStateSet* state_set) :581AbstractGangTask("ParNewGeneration collection"),582_gen(gen), _next_gen(next_gen),583_young_old_boundary(young_old_boundary),584_state_set(state_set)585{}586587// Reset the terminator for the given number of588// active threads.589void ParNewGenTask::set_for_termination(int active_workers) {590_state_set->reset(active_workers, _gen->promotion_failed());591// Should the heap be passed in? There's only 1 for now so592// grab it instead.593GenCollectedHeap* gch = GenCollectedHeap::heap();594gch->set_n_termination(active_workers);595}596597void ParNewGenTask::work(uint worker_id) {598GenCollectedHeap* gch = GenCollectedHeap::heap();599// Since this is being done in a separate thread, need new resource600// and handle marks.601ResourceMark rm;602HandleMark hm;603// We would need multiple old-gen queues otherwise.604assert(gch->n_gens() == 2, "Par young collection currently only works with one older gen.");605606Generation* old_gen = gch->next_gen(_gen);607608ParScanThreadState& par_scan_state = _state_set->thread_state(worker_id);609assert(_state_set->is_valid(worker_id), "Should not have been called");610611par_scan_state.set_young_old_boundary(_young_old_boundary);612613KlassScanClosure klass_scan_closure(&par_scan_state.to_space_root_closure(),614gch->rem_set()->klass_rem_set());615CLDToKlassAndOopClosure cld_scan_closure(&klass_scan_closure,616&par_scan_state.to_space_root_closure(),617false);618619par_scan_state.start_strong_roots();620gch->gen_process_roots(_gen->level(),621true, // Process younger gens, if any,622// as strong roots.623false, // no scope; this is parallel code624GenCollectedHeap::SO_ScavengeCodeCache,625GenCollectedHeap::StrongAndWeakRoots,626&par_scan_state.to_space_root_closure(),627&par_scan_state.older_gen_closure(),628&cld_scan_closure);629630par_scan_state.end_strong_roots();631632// "evacuate followers".633par_scan_state.evacuate_followers_closure().do_void();634}635636#ifdef _MSC_VER637#pragma warning( push )638#pragma warning( disable:4355 ) // 'this' : used in base member initializer list639#endif640ParNewGeneration::641ParNewGeneration(ReservedSpace rs, size_t initial_byte_size, int level)642: DefNewGeneration(rs, initial_byte_size, level, "PCopy"),643_overflow_list(NULL),644_is_alive_closure(this),645_plab_stats(YoungPLABSize, PLABWeight)646{647NOT_PRODUCT(_overflow_counter = ParGCWorkQueueOverflowInterval;)648NOT_PRODUCT(_num_par_pushes = 0;)649_task_queues = new ObjToScanQueueSet(ParallelGCThreads);650guarantee(_task_queues != NULL, "task_queues allocation failure.");651652for (uint i1 = 0; i1 < ParallelGCThreads; i1++) {653ObjToScanQueue *q = new ObjToScanQueue();654guarantee(q != NULL, "work_queue Allocation failure.");655_task_queues->register_queue(i1, q);656}657658for (uint i2 = 0; i2 < ParallelGCThreads; i2++)659_task_queues->queue(i2)->initialize();660661_overflow_stacks = NULL;662if (ParGCUseLocalOverflow) {663664// typedef to workaround NEW_C_HEAP_ARRAY macro, which can not deal665// with ','666typedef Stack<oop, mtGC> GCOopStack;667668_overflow_stacks = NEW_C_HEAP_ARRAY(GCOopStack, ParallelGCThreads, mtGC);669for (size_t i = 0; i < ParallelGCThreads; ++i) {670new (_overflow_stacks + i) Stack<oop, mtGC>();671}672}673674if (UsePerfData) {675EXCEPTION_MARK;676ResourceMark rm;677678const char* cname =679PerfDataManager::counter_name(_gen_counters->name_space(), "threads");680PerfDataManager::create_constant(SUN_GC, cname, PerfData::U_None,681ParallelGCThreads, CHECK);682}683}684#ifdef _MSC_VER685#pragma warning( pop )686#endif687688// ParNewGeneration::689ParKeepAliveClosure::ParKeepAliveClosure(ParScanWeakRefClosure* cl) :690DefNewGeneration::KeepAliveClosure(cl), _par_cl(cl) {}691692template <class T>693void /*ParNewGeneration::*/ParKeepAliveClosure::do_oop_work(T* p) {694#ifdef ASSERT695{696assert(!oopDesc::is_null(*p), "expected non-null ref");697oop obj = oopDesc::load_decode_heap_oop_not_null(p);698// We never expect to see a null reference being processed699// as a weak reference.700assert(obj->is_oop(), "expected an oop while scanning weak refs");701}702#endif // ASSERT703704_par_cl->do_oop_nv(p);705706if (Universe::heap()->is_in_reserved(p)) {707oop obj = oopDesc::load_decode_heap_oop_not_null(p);708_rs->write_ref_field_gc_par(p, obj);709}710}711712void /*ParNewGeneration::*/ParKeepAliveClosure::do_oop(oop* p) { ParKeepAliveClosure::do_oop_work(p); }713void /*ParNewGeneration::*/ParKeepAliveClosure::do_oop(narrowOop* p) { ParKeepAliveClosure::do_oop_work(p); }714715// ParNewGeneration::716KeepAliveClosure::KeepAliveClosure(ScanWeakRefClosure* cl) :717DefNewGeneration::KeepAliveClosure(cl) {}718719template <class T>720void /*ParNewGeneration::*/KeepAliveClosure::do_oop_work(T* p) {721#ifdef ASSERT722{723assert(!oopDesc::is_null(*p), "expected non-null ref");724oop obj = oopDesc::load_decode_heap_oop_not_null(p);725// We never expect to see a null reference being processed726// as a weak reference.727assert(obj->is_oop(), "expected an oop while scanning weak refs");728}729#endif // ASSERT730731_cl->do_oop_nv(p);732733if (Universe::heap()->is_in_reserved(p)) {734oop obj = oopDesc::load_decode_heap_oop_not_null(p);735_rs->write_ref_field_gc_par(p, obj);736}737}738739void /*ParNewGeneration::*/KeepAliveClosure::do_oop(oop* p) { KeepAliveClosure::do_oop_work(p); }740void /*ParNewGeneration::*/KeepAliveClosure::do_oop(narrowOop* p) { KeepAliveClosure::do_oop_work(p); }741742template <class T> void ScanClosureWithParBarrier::do_oop_work(T* p) {743T heap_oop = oopDesc::load_heap_oop(p);744if (!oopDesc::is_null(heap_oop)) {745oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);746if ((HeapWord*)obj < _boundary) {747assert(!_g->to()->is_in_reserved(obj), "Scanning field twice?");748oop new_obj = obj->is_forwarded()749? obj->forwardee()750: _g->DefNewGeneration::copy_to_survivor_space(obj);751oopDesc::encode_store_heap_oop_not_null(p, new_obj);752}753if (_gc_barrier) {754// If p points to a younger generation, mark the card.755if ((HeapWord*)obj < _gen_boundary) {756_rs->write_ref_field_gc_par(p, obj);757}758}759}760}761762void ScanClosureWithParBarrier::do_oop(oop* p) { ScanClosureWithParBarrier::do_oop_work(p); }763void ScanClosureWithParBarrier::do_oop(narrowOop* p) { ScanClosureWithParBarrier::do_oop_work(p); }764765class ParNewRefProcTaskProxy: public AbstractGangTask {766typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;767public:768ParNewRefProcTaskProxy(ProcessTask& task, ParNewGeneration& gen,769Generation& next_gen,770HeapWord* young_old_boundary,771ParScanThreadStateSet& state_set);772773private:774virtual void work(uint worker_id);775virtual void set_for_termination(int active_workers) {776_state_set.terminator()->reset_for_reuse(active_workers);777}778private:779ParNewGeneration& _gen;780ProcessTask& _task;781Generation& _next_gen;782HeapWord* _young_old_boundary;783ParScanThreadStateSet& _state_set;784};785786ParNewRefProcTaskProxy::ParNewRefProcTaskProxy(787ProcessTask& task, ParNewGeneration& gen,788Generation& next_gen,789HeapWord* young_old_boundary,790ParScanThreadStateSet& state_set)791: AbstractGangTask("ParNewGeneration parallel reference processing"),792_gen(gen),793_task(task),794_next_gen(next_gen),795_young_old_boundary(young_old_boundary),796_state_set(state_set)797{798}799800void ParNewRefProcTaskProxy::work(uint worker_id)801{802ResourceMark rm;803HandleMark hm;804ParScanThreadState& par_scan_state = _state_set.thread_state(worker_id);805par_scan_state.set_young_old_boundary(_young_old_boundary);806_task.work(worker_id, par_scan_state.is_alive_closure(),807par_scan_state.keep_alive_closure(),808par_scan_state.evacuate_followers_closure());809}810811class ParNewRefEnqueueTaskProxy: public AbstractGangTask {812typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;813EnqueueTask& _task;814815public:816ParNewRefEnqueueTaskProxy(EnqueueTask& task)817: AbstractGangTask("ParNewGeneration parallel reference enqueue"),818_task(task)819{ }820821virtual void work(uint worker_id)822{823_task.work(worker_id);824}825};826827828void ParNewRefProcTaskExecutor::execute(ProcessTask& task)829{830GenCollectedHeap* gch = GenCollectedHeap::heap();831assert(gch->kind() == CollectedHeap::GenCollectedHeap,832"not a generational heap");833FlexibleWorkGang* workers = gch->workers();834assert(workers != NULL, "Need parallel worker threads.");835_state_set.reset(workers->active_workers(), _generation.promotion_failed());836ParNewRefProcTaskProxy rp_task(task, _generation, *_generation.next_gen(),837_generation.reserved().end(), _state_set);838workers->run_task(&rp_task);839_state_set.reset(0 /* bad value in debug if not reset */,840_generation.promotion_failed());841}842843void ParNewRefProcTaskExecutor::execute(EnqueueTask& task)844{845GenCollectedHeap* gch = GenCollectedHeap::heap();846FlexibleWorkGang* workers = gch->workers();847assert(workers != NULL, "Need parallel worker threads.");848ParNewRefEnqueueTaskProxy enq_task(task);849workers->run_task(&enq_task);850}851852void ParNewRefProcTaskExecutor::set_single_threaded_mode()853{854_state_set.flush();855GenCollectedHeap* gch = GenCollectedHeap::heap();856gch->set_par_threads(0); // 0 ==> non-parallel.857gch->save_marks();858}859860ScanClosureWithParBarrier::861ScanClosureWithParBarrier(ParNewGeneration* g, bool gc_barrier) :862ScanClosure(g, gc_barrier) {}863864EvacuateFollowersClosureGeneral::865EvacuateFollowersClosureGeneral(GenCollectedHeap* gch, int level,866OopsInGenClosure* cur,867OopsInGenClosure* older) :868_gch(gch), _level(level),869_scan_cur_or_nonheap(cur), _scan_older(older)870{}871872void EvacuateFollowersClosureGeneral::do_void() {873do {874// Beware: this call will lead to closure applications via virtual875// calls.876_gch->oop_since_save_marks_iterate(_level,877_scan_cur_or_nonheap,878_scan_older);879} while (!_gch->no_allocs_since_save_marks(_level));880}881882883// A Generation that does parallel young-gen collection.884885bool ParNewGeneration::_avoid_promotion_undo = false;886887void ParNewGeneration::handle_promotion_failed(GenCollectedHeap* gch, ParScanThreadStateSet& thread_state_set, ParNewTracer& gc_tracer) {888assert(_promo_failure_scan_stack.is_empty(), "post condition");889_promo_failure_scan_stack.clear(true); // Clear cached segments.890891remove_forwarding_pointers();892if (PrintGCDetails) {893gclog_or_tty->print(" (promotion failed)");894}895// All the spaces are in play for mark-sweep.896swap_spaces(); // Make life simpler for CMS || rescan; see 6483690.897from()->set_next_compaction_space(to());898gch->set_incremental_collection_failed();899// Inform the next generation that a promotion failure occurred.900_next_gen->promotion_failure_occurred();901902// Trace promotion failure in the parallel GC threads903thread_state_set.trace_promotion_failed(gc_tracer);904// Single threaded code may have reported promotion failure to the global state905if (_promotion_failed_info.has_failed()) {906gc_tracer.report_promotion_failed(_promotion_failed_info);907}908// Reset the PromotionFailureALot counters.909NOT_PRODUCT(Universe::heap()->reset_promotion_should_fail();)910}911912void ParNewGeneration::collect(bool full,913bool clear_all_soft_refs,914size_t size,915bool is_tlab) {916assert(full || size > 0, "otherwise we don't want to collect");917918GenCollectedHeap* gch = GenCollectedHeap::heap();919920_gc_timer->register_gc_start();921922assert(gch->kind() == CollectedHeap::GenCollectedHeap,923"not a CMS generational heap");924AdaptiveSizePolicy* size_policy = gch->gen_policy()->size_policy();925FlexibleWorkGang* workers = gch->workers();926assert(workers != NULL, "Need workgang for parallel work");927int active_workers =928AdaptiveSizePolicy::calc_active_workers(workers->total_workers(),929workers->active_workers(),930Threads::number_of_non_daemon_threads());931workers->set_active_workers(active_workers);932assert(gch->n_gens() == 2,933"Par collection currently only works with single older gen.");934_next_gen = gch->next_gen(this);935// Do we have to avoid promotion_undo?936if (gch->collector_policy()->is_concurrent_mark_sweep_policy()) {937set_avoid_promotion_undo(true);938}939940// If the next generation is too full to accommodate worst-case promotion941// from this generation, pass on collection; let the next generation942// do it.943if (!collection_attempt_is_safe()) {944gch->set_incremental_collection_failed(); // slight lie, in that we did not even attempt one945return;946}947assert(to()->is_empty(), "Else not collection_attempt_is_safe");948949ParNewTracer gc_tracer;950gc_tracer.report_gc_start(gch->gc_cause(), _gc_timer->gc_start());951gch->trace_heap_before_gc(&gc_tracer);952953init_assuming_no_promotion_failure();954955if (UseAdaptiveSizePolicy) {956set_survivor_overflow(false);957size_policy->minor_collection_begin();958}959960GCTraceTime t1(GCCauseString("GC", gch->gc_cause()), PrintGC && !PrintGCDetails, true, NULL, gc_tracer.gc_id());961// Capture heap used before collection (for printing).962size_t gch_prev_used = gch->used();963964SpecializationStats::clear();965966age_table()->clear();967to()->clear(SpaceDecorator::Mangle);968969gch->save_marks();970assert(workers != NULL, "Need parallel worker threads.");971int n_workers = active_workers;972973// Set the correct parallelism (number of queues) in the reference processor974ref_processor()->set_active_mt_degree(n_workers);975976// Always set the terminator for the active number of workers977// because only those workers go through the termination protocol.978ParallelTaskTerminator _term(n_workers, task_queues());979ParScanThreadStateSet thread_state_set(workers->active_workers(),980*to(), *this, *_next_gen, *task_queues(),981_overflow_stacks, desired_plab_sz(), _term);982983ParNewGenTask tsk(this, _next_gen, reserved().end(), &thread_state_set);984gch->set_par_threads(n_workers);985gch->rem_set()->prepare_for_younger_refs_iterate(true);986// It turns out that even when we're using 1 thread, doing the work in a987// separate thread causes wide variance in run times. We can't help this988// in the multi-threaded case, but we special-case n=1 here to get989// repeatable measurements of the 1-thread overhead of the parallel code.990if (n_workers > 1) {991GenCollectedHeap::StrongRootsScope srs(gch);992workers->run_task(&tsk);993} else {994GenCollectedHeap::StrongRootsScope srs(gch);995tsk.work(0);996}997thread_state_set.reset(0 /* Bad value in debug if not reset */,998promotion_failed());9991000// Process (weak) reference objects found during scavenge.1001ReferenceProcessor* rp = ref_processor();1002IsAliveClosure is_alive(this);1003ScanWeakRefClosure scan_weak_ref(this);1004KeepAliveClosure keep_alive(&scan_weak_ref);1005ScanClosure scan_without_gc_barrier(this, false);1006ScanClosureWithParBarrier scan_with_gc_barrier(this, true);1007set_promo_failure_scan_stack_closure(&scan_without_gc_barrier);1008EvacuateFollowersClosureGeneral evacuate_followers(gch, _level,1009&scan_without_gc_barrier, &scan_with_gc_barrier);1010rp->setup_policy(clear_all_soft_refs);1011// Can the mt_degree be set later (at run_task() time would be best)?1012rp->set_active_mt_degree(active_workers);1013ReferenceProcessorStats stats;1014if (rp->processing_is_mt()) {1015ParNewRefProcTaskExecutor task_executor(*this, thread_state_set);1016stats = rp->process_discovered_references(&is_alive, &keep_alive,1017&evacuate_followers, &task_executor,1018_gc_timer, gc_tracer.gc_id());1019} else {1020thread_state_set.flush();1021gch->set_par_threads(0); // 0 ==> non-parallel.1022gch->save_marks();1023stats = rp->process_discovered_references(&is_alive, &keep_alive,1024&evacuate_followers, NULL,1025_gc_timer, gc_tracer.gc_id());1026}1027gc_tracer.report_gc_reference_stats(stats);1028if (!promotion_failed()) {1029// Swap the survivor spaces.1030eden()->clear(SpaceDecorator::Mangle);1031from()->clear(SpaceDecorator::Mangle);1032if (ZapUnusedHeapArea) {1033// This is now done here because of the piece-meal mangling which1034// can check for valid mangling at intermediate points in the1035// collection(s). When a minor collection fails to collect1036// sufficient space resizing of the young generation can occur1037// an redistribute the spaces in the young generation. Mangle1038// here so that unzapped regions don't get distributed to1039// other spaces.1040to()->mangle_unused_area();1041}1042swap_spaces();10431044// A successful scavenge should restart the GC time limit count which is1045// for full GC's.1046size_policy->reset_gc_overhead_limit_count();10471048assert(to()->is_empty(), "to space should be empty now");10491050adjust_desired_tenuring_threshold(gc_tracer);1051} else {1052handle_promotion_failed(gch, thread_state_set, gc_tracer);1053}1054// set new iteration safe limit for the survivor spaces1055from()->set_concurrent_iteration_safe_limit(from()->top());1056to()->set_concurrent_iteration_safe_limit(to()->top());10571058if (ResizePLAB) {1059plab_stats()->adjust_desired_plab_sz(n_workers);1060}10611062if (PrintGC && !PrintGCDetails) {1063gch->print_heap_change(gch_prev_used);1064}10651066if (PrintGCDetails && ParallelGCVerbose) {1067TASKQUEUE_STATS_ONLY(thread_state_set.print_termination_stats());1068TASKQUEUE_STATS_ONLY(thread_state_set.print_taskqueue_stats());1069}10701071if (UseAdaptiveSizePolicy) {1072size_policy->minor_collection_end(gch->gc_cause());1073size_policy->avg_survived()->sample(from()->used());1074}10751076// We need to use a monotonically non-deccreasing time in ms1077// or we will see time-warp warnings and os::javaTimeMillis()1078// does not guarantee monotonicity.1079jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;1080update_time_of_last_gc(now);10811082SpecializationStats::print();10831084rp->set_enqueuing_is_done(true);1085if (rp->processing_is_mt()) {1086ParNewRefProcTaskExecutor task_executor(*this, thread_state_set);1087rp->enqueue_discovered_references(&task_executor);1088} else {1089rp->enqueue_discovered_references(NULL);1090}1091rp->verify_no_references_recorded();10921093gch->trace_heap_after_gc(&gc_tracer);1094gc_tracer.report_tenuring_threshold(tenuring_threshold());10951096_gc_timer->register_gc_end();10971098gc_tracer.report_gc_end(_gc_timer->gc_end(), _gc_timer->time_partitions());1099}11001101static int sum;1102void ParNewGeneration::waste_some_time() {1103for (int i = 0; i < 100; i++) {1104sum += i;1105}1106}11071108static const oop ClaimedForwardPtr = cast_to_oop<intptr_t>(0x4);11091110// Because of concurrency, there are times where an object for which1111// "is_forwarded()" is true contains an "interim" forwarding pointer1112// value. Such a value will soon be overwritten with a real value.1113// This method requires "obj" to have a forwarding pointer, and waits, if1114// necessary for a real one to be inserted, and returns it.11151116oop ParNewGeneration::real_forwardee(oop obj) {1117oop forward_ptr = obj->forwardee();1118if (forward_ptr != ClaimedForwardPtr) {1119return forward_ptr;1120} else {1121return real_forwardee_slow(obj);1122}1123}11241125oop ParNewGeneration::real_forwardee_slow(oop obj) {1126// Spin-read if it is claimed but not yet written by another thread.1127oop forward_ptr = obj->forwardee();1128while (forward_ptr == ClaimedForwardPtr) {1129waste_some_time();1130assert(obj->is_forwarded(), "precondition");1131forward_ptr = obj->forwardee();1132}1133return forward_ptr;1134}11351136#ifdef ASSERT1137bool ParNewGeneration::is_legal_forward_ptr(oop p) {1138return1139(_avoid_promotion_undo && p == ClaimedForwardPtr)1140|| Universe::heap()->is_in_reserved(p);1141}1142#endif11431144void ParNewGeneration::preserve_mark_if_necessary(oop obj, markOop m) {1145if (m->must_be_preserved_for_promotion_failure(obj)) {1146// We should really have separate per-worker stacks, rather1147// than use locking of a common pair of stacks.1148MutexLocker ml(ParGCRareEvent_lock);1149preserve_mark(obj, m);1150}1151}11521153// Multiple GC threads may try to promote an object. If the object1154// is successfully promoted, a forwarding pointer will be installed in1155// the object in the young generation. This method claims the right1156// to install the forwarding pointer before it copies the object,1157// thus avoiding the need to undo the copy as in1158// copy_to_survivor_space_avoiding_with_undo.11591160oop ParNewGeneration::copy_to_survivor_space_avoiding_promotion_undo(1161ParScanThreadState* par_scan_state, oop old, size_t sz, markOop m) {1162// In the sequential version, this assert also says that the object is1163// not forwarded. That might not be the case here. It is the case that1164// the caller observed it to be not forwarded at some time in the past.1165assert(is_in_reserved(old), "shouldn't be scavenging this oop");11661167// The sequential code read "old->age()" below. That doesn't work here,1168// since the age is in the mark word, and that might be overwritten with1169// a forwarding pointer by a parallel thread. So we must save the mark1170// word in a local and then analyze it.1171oopDesc dummyOld;1172dummyOld.set_mark(m);1173assert(!dummyOld.is_forwarded(),1174"should not be called with forwarding pointer mark word.");11751176oop new_obj = NULL;1177oop forward_ptr;11781179// Try allocating obj in to-space (unless too old)1180if (dummyOld.age() < tenuring_threshold()) {1181new_obj = (oop)par_scan_state->alloc_in_to_space(sz);1182if (new_obj == NULL) {1183set_survivor_overflow(true);1184}1185}11861187if (new_obj == NULL) {1188// Either to-space is full or we decided to promote1189// try allocating obj tenured11901191// Attempt to install a null forwarding pointer (atomically),1192// to claim the right to install the real forwarding pointer.1193forward_ptr = old->forward_to_atomic(ClaimedForwardPtr);1194if (forward_ptr != NULL) {1195// someone else beat us to it.1196return real_forwardee(old);1197}11981199if (!_promotion_failed) {1200new_obj = _next_gen->par_promote(par_scan_state->thread_num(),1201old, m, sz);1202}12031204if (new_obj == NULL) {1205// promotion failed, forward to self1206_promotion_failed = true;1207new_obj = old;12081209preserve_mark_if_necessary(old, m);1210par_scan_state->register_promotion_failure(sz);1211}12121213old->forward_to(new_obj);1214forward_ptr = NULL;1215} else {1216// Is in to-space; do copying ourselves.1217Copy::aligned_disjoint_words((HeapWord*)old, (HeapWord*)new_obj, sz);1218forward_ptr = old->forward_to_atomic(new_obj);1219// Restore the mark word copied above.1220new_obj->set_mark(m);1221// Increment age if obj still in new generation1222new_obj->incr_age();1223par_scan_state->age_table()->add(new_obj, sz);1224}1225assert(new_obj != NULL, "just checking");12261227#ifndef PRODUCT1228// This code must come after the CAS test, or it will print incorrect1229// information.1230if (TraceScavenge) {1231gclog_or_tty->print_cr("{%s %s " PTR_FORMAT " -> " PTR_FORMAT " (%d)}",1232is_in_reserved(new_obj) ? "copying" : "tenuring",1233new_obj->klass()->internal_name(), (void *)old, (void *)new_obj, new_obj->size());1234}1235#endif12361237if (forward_ptr == NULL) {1238oop obj_to_push = new_obj;1239if (par_scan_state->should_be_partially_scanned(obj_to_push, old)) {1240// Length field used as index of next element to be scanned.1241// Real length can be obtained from real_forwardee()1242arrayOop(old)->set_length(0);1243obj_to_push = old;1244assert(obj_to_push->is_forwarded() && obj_to_push->forwardee() != obj_to_push,1245"push forwarded object");1246}1247// Push it on one of the queues of to-be-scanned objects.1248bool simulate_overflow = false;1249NOT_PRODUCT(1250if (ParGCWorkQueueOverflowALot && should_simulate_overflow()) {1251// simulate a stack overflow1252simulate_overflow = true;1253}1254)1255if (simulate_overflow || !par_scan_state->work_queue()->push(obj_to_push)) {1256// Add stats for overflow pushes.1257if (Verbose && PrintGCDetails) {1258gclog_or_tty->print("queue overflow!\n");1259}1260push_on_overflow_list(old, par_scan_state);1261TASKQUEUE_STATS_ONLY(par_scan_state->taskqueue_stats().record_overflow(0));1262}12631264return new_obj;1265}12661267// Oops. Someone beat us to it. Undo the allocation. Where did we1268// allocate it?1269if (is_in_reserved(new_obj)) {1270// Must be in to_space.1271assert(to()->is_in_reserved(new_obj), "Checking");1272if (forward_ptr == ClaimedForwardPtr) {1273// Wait to get the real forwarding pointer value.1274forward_ptr = real_forwardee(old);1275}1276par_scan_state->undo_alloc_in_to_space((HeapWord*)new_obj, sz);1277}12781279return forward_ptr;1280}128112821283// Multiple GC threads may try to promote the same object. If two1284// or more GC threads copy the object, only one wins the race to install1285// the forwarding pointer. The other threads have to undo their copy.12861287oop ParNewGeneration::copy_to_survivor_space_with_undo(1288ParScanThreadState* par_scan_state, oop old, size_t sz, markOop m) {12891290// In the sequential version, this assert also says that the object is1291// not forwarded. That might not be the case here. It is the case that1292// the caller observed it to be not forwarded at some time in the past.1293assert(is_in_reserved(old), "shouldn't be scavenging this oop");12941295// The sequential code read "old->age()" below. That doesn't work here,1296// since the age is in the mark word, and that might be overwritten with1297// a forwarding pointer by a parallel thread. So we must save the mark1298// word here, install it in a local oopDesc, and then analyze it.1299oopDesc dummyOld;1300dummyOld.set_mark(m);1301assert(!dummyOld.is_forwarded(),1302"should not be called with forwarding pointer mark word.");13031304bool failed_to_promote = false;1305oop new_obj = NULL;1306oop forward_ptr;13071308// Try allocating obj in to-space (unless too old)1309if (dummyOld.age() < tenuring_threshold()) {1310new_obj = (oop)par_scan_state->alloc_in_to_space(sz);1311if (new_obj == NULL) {1312set_survivor_overflow(true);1313}1314}13151316if (new_obj == NULL) {1317// Either to-space is full or we decided to promote1318// try allocating obj tenured1319new_obj = _next_gen->par_promote(par_scan_state->thread_num(),1320old, m, sz);13211322if (new_obj == NULL) {1323// promotion failed, forward to self1324forward_ptr = old->forward_to_atomic(old);1325new_obj = old;13261327if (forward_ptr != NULL) {1328return forward_ptr; // someone else succeeded1329}13301331_promotion_failed = true;1332failed_to_promote = true;13331334preserve_mark_if_necessary(old, m);1335par_scan_state->register_promotion_failure(sz);1336}1337} else {1338// Is in to-space; do copying ourselves.1339Copy::aligned_disjoint_words((HeapWord*)old, (HeapWord*)new_obj, sz);1340// Restore the mark word copied above.1341new_obj->set_mark(m);1342// Increment age if new_obj still in new generation1343new_obj->incr_age();1344par_scan_state->age_table()->add(new_obj, sz);1345}1346assert(new_obj != NULL, "just checking");13471348#ifndef PRODUCT1349// This code must come after the CAS test, or it will print incorrect1350// information.1351if (TraceScavenge) {1352gclog_or_tty->print_cr("{%s %s " PTR_FORMAT " -> " PTR_FORMAT " (%d)}",1353is_in_reserved(new_obj) ? "copying" : "tenuring",1354new_obj->klass()->internal_name(), (void *)old, (void *)new_obj, new_obj->size());1355}1356#endif13571358// Now attempt to install the forwarding pointer (atomically).1359// We have to copy the mark word before overwriting with forwarding1360// ptr, so we can restore it below in the copy.1361if (!failed_to_promote) {1362forward_ptr = old->forward_to_atomic(new_obj);1363}13641365if (forward_ptr == NULL) {1366oop obj_to_push = new_obj;1367if (par_scan_state->should_be_partially_scanned(obj_to_push, old)) {1368// Length field used as index of next element to be scanned.1369// Real length can be obtained from real_forwardee()1370arrayOop(old)->set_length(0);1371obj_to_push = old;1372assert(obj_to_push->is_forwarded() && obj_to_push->forwardee() != obj_to_push,1373"push forwarded object");1374}1375// Push it on one of the queues of to-be-scanned objects.1376bool simulate_overflow = false;1377NOT_PRODUCT(1378if (ParGCWorkQueueOverflowALot && should_simulate_overflow()) {1379// simulate a stack overflow1380simulate_overflow = true;1381}1382)1383if (simulate_overflow || !par_scan_state->work_queue()->push(obj_to_push)) {1384// Add stats for overflow pushes.1385push_on_overflow_list(old, par_scan_state);1386TASKQUEUE_STATS_ONLY(par_scan_state->taskqueue_stats().record_overflow(0));1387}13881389return new_obj;1390}13911392// Oops. Someone beat us to it. Undo the allocation. Where did we1393// allocate it?1394if (is_in_reserved(new_obj)) {1395// Must be in to_space.1396assert(to()->is_in_reserved(new_obj), "Checking");1397par_scan_state->undo_alloc_in_to_space((HeapWord*)new_obj, sz);1398} else {1399assert(!_avoid_promotion_undo, "Should not be here if avoiding.");1400_next_gen->par_promote_alloc_undo(par_scan_state->thread_num(),1401(HeapWord*)new_obj, sz);1402}14031404return forward_ptr;1405}14061407#ifndef PRODUCT1408// It's OK to call this multi-threaded; the worst thing1409// that can happen is that we'll get a bunch of closely1410// spaced simulated oveflows, but that's OK, in fact1411// probably good as it would exercise the overflow code1412// under contention.1413bool ParNewGeneration::should_simulate_overflow() {1414if (_overflow_counter-- <= 0) { // just being defensive1415_overflow_counter = ParGCWorkQueueOverflowInterval;1416return true;1417} else {1418return false;1419}1420}1421#endif14221423// In case we are using compressed oops, we need to be careful.1424// If the object being pushed is an object array, then its length1425// field keeps track of the "grey boundary" at which the next1426// incremental scan will be done (see ParGCArrayScanChunk).1427// When using compressed oops, this length field is kept in the1428// lower 32 bits of the erstwhile klass word and cannot be used1429// for the overflow chaining pointer (OCP below). As such the OCP1430// would itself need to be compressed into the top 32-bits in this1431// case. Unfortunately, see below, in the event that we have a1432// promotion failure, the node to be pushed on the list can be1433// outside of the Java heap, so the heap-based pointer compression1434// would not work (we would have potential aliasing between C-heap1435// and Java-heap pointers). For this reason, when using compressed1436// oops, we simply use a worker-thread-local, non-shared overflow1437// list in the form of a growable array, with a slightly different1438// overflow stack draining strategy. If/when we start using fat1439// stacks here, we can go back to using (fat) pointer chains1440// (although some performance comparisons would be useful since1441// single global lists have their own performance disadvantages1442// as we were made painfully aware not long ago, see 6786503).1443#define BUSY (cast_to_oop<intptr_t>(0x1aff1aff))1444void ParNewGeneration::push_on_overflow_list(oop from_space_obj, ParScanThreadState* par_scan_state) {1445assert(is_in_reserved(from_space_obj), "Should be from this generation");1446if (ParGCUseLocalOverflow) {1447// In the case of compressed oops, we use a private, not-shared1448// overflow stack.1449par_scan_state->push_on_overflow_stack(from_space_obj);1450} else {1451assert(!UseCompressedOops, "Error");1452// if the object has been forwarded to itself, then we cannot1453// use the klass pointer for the linked list. Instead we have1454// to allocate an oopDesc in the C-Heap and use that for the linked list.1455// XXX This is horribly inefficient when a promotion failure occurs1456// and should be fixed. XXX FIX ME !!!1457#ifndef PRODUCT1458Atomic::inc_ptr(&_num_par_pushes);1459assert(_num_par_pushes > 0, "Tautology");1460#endif1461if (from_space_obj->forwardee() == from_space_obj) {1462oopDesc* listhead = NEW_C_HEAP_ARRAY(oopDesc, 1, mtGC);1463listhead->forward_to(from_space_obj);1464from_space_obj = listhead;1465}1466oop observed_overflow_list = _overflow_list;1467oop cur_overflow_list;1468do {1469cur_overflow_list = observed_overflow_list;1470if (cur_overflow_list != BUSY) {1471from_space_obj->set_klass_to_list_ptr(cur_overflow_list);1472} else {1473from_space_obj->set_klass_to_list_ptr(NULL);1474}1475observed_overflow_list =1476(oop)Atomic::cmpxchg_ptr(from_space_obj, &_overflow_list, cur_overflow_list);1477} while (cur_overflow_list != observed_overflow_list);1478}1479}14801481bool ParNewGeneration::take_from_overflow_list(ParScanThreadState* par_scan_state) {1482bool res;14831484if (ParGCUseLocalOverflow) {1485res = par_scan_state->take_from_overflow_stack();1486} else {1487assert(!UseCompressedOops, "Error");1488res = take_from_overflow_list_work(par_scan_state);1489}1490return res;1491}149214931494// *NOTE*: The overflow list manipulation code here and1495// in CMSCollector:: are very similar in shape,1496// except that in the CMS case we thread the objects1497// directly into the list via their mark word, and do1498// not need to deal with special cases below related1499// to chunking of object arrays and promotion failure1500// handling.1501// CR 6797058 has been filed to attempt consolidation of1502// the common code.1503// Because of the common code, if you make any changes in1504// the code below, please check the CMS version to see if1505// similar changes might be needed.1506// See CMSCollector::par_take_from_overflow_list() for1507// more extensive documentation comments.1508bool ParNewGeneration::take_from_overflow_list_work(ParScanThreadState* par_scan_state) {1509ObjToScanQueue* work_q = par_scan_state->work_queue();1510// How many to take?1511size_t objsFromOverflow = MIN2((size_t)(work_q->max_elems() - work_q->size())/4,1512(size_t)ParGCDesiredObjsFromOverflowList);15131514assert(!UseCompressedOops, "Error");1515assert(par_scan_state->overflow_stack() == NULL, "Error");1516if (_overflow_list == NULL) return false;15171518// Otherwise, there was something there; try claiming the list.1519oop prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list));1520// Trim off a prefix of at most objsFromOverflow items1521Thread* tid = Thread::current();1522size_t spin_count = (size_t)ParallelGCThreads;1523size_t sleep_time_millis = MAX2((size_t)1, objsFromOverflow/100);1524for (size_t spin = 0; prefix == BUSY && spin < spin_count; spin++) {1525// someone grabbed it before we did ...1526// ... we spin for a short while...1527os::sleep(tid, sleep_time_millis, false);1528if (_overflow_list == NULL) {1529// nothing left to take1530return false;1531} else if (_overflow_list != BUSY) {1532// try and grab the prefix1533prefix = cast_to_oop(Atomic::xchg_ptr(BUSY, &_overflow_list));1534}1535}1536if (prefix == NULL || prefix == BUSY) {1537// Nothing to take or waited long enough1538if (prefix == NULL) {1539// Write back the NULL in case we overwrote it with BUSY above1540// and it is still the same value.1541(void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY);1542}1543return false;1544}1545assert(prefix != NULL && prefix != BUSY, "Error");1546oop cur = prefix;1547for (size_t i = 1; i < objsFromOverflow; ++i) {1548oop next = cur->list_ptr_from_klass();1549if (next == NULL) break;1550cur = next;1551}1552assert(cur != NULL, "Loop postcondition");15531554// Reattach remaining (suffix) to overflow list1555oop suffix = cur->list_ptr_from_klass();1556if (suffix == NULL) {1557// Write back the NULL in lieu of the BUSY we wrote1558// above and it is still the same value.1559if (_overflow_list == BUSY) {1560(void) Atomic::cmpxchg_ptr(NULL, &_overflow_list, BUSY);1561}1562} else {1563assert(suffix != BUSY, "Error");1564// suffix will be put back on global list1565cur->set_klass_to_list_ptr(NULL); // break off suffix1566// It's possible that the list is still in the empty(busy) state1567// we left it in a short while ago; in that case we may be1568// able to place back the suffix.1569oop observed_overflow_list = _overflow_list;1570oop cur_overflow_list = observed_overflow_list;1571bool attached = false;1572while (observed_overflow_list == BUSY || observed_overflow_list == NULL) {1573observed_overflow_list =1574(oop) Atomic::cmpxchg_ptr(suffix, &_overflow_list, cur_overflow_list);1575if (cur_overflow_list == observed_overflow_list) {1576attached = true;1577break;1578} else cur_overflow_list = observed_overflow_list;1579}1580if (!attached) {1581// Too bad, someone else got in in between; we'll need to do a splice.1582// Find the last item of suffix list1583oop last = suffix;1584while (true) {1585oop next = last->list_ptr_from_klass();1586if (next == NULL) break;1587last = next;1588}1589// Atomically prepend suffix to current overflow list1590observed_overflow_list = _overflow_list;1591do {1592cur_overflow_list = observed_overflow_list;1593if (cur_overflow_list != BUSY) {1594// Do the splice ...1595last->set_klass_to_list_ptr(cur_overflow_list);1596} else { // cur_overflow_list == BUSY1597last->set_klass_to_list_ptr(NULL);1598}1599observed_overflow_list =1600(oop)Atomic::cmpxchg_ptr(suffix, &_overflow_list, cur_overflow_list);1601} while (cur_overflow_list != observed_overflow_list);1602}1603}16041605// Push objects on prefix list onto this thread's work queue1606assert(prefix != NULL && prefix != BUSY, "program logic");1607cur = prefix;1608ssize_t n = 0;1609while (cur != NULL) {1610oop obj_to_push = cur->forwardee();1611oop next = cur->list_ptr_from_klass();1612cur->set_klass(obj_to_push->klass());1613// This may be an array object that is self-forwarded. In that case, the list pointer1614// space, cur, is not in the Java heap, but rather in the C-heap and should be freed.1615if (!is_in_reserved(cur)) {1616// This can become a scaling bottleneck when there is work queue overflow coincident1617// with promotion failure.1618oopDesc* f = cur;1619FREE_C_HEAP_ARRAY(oopDesc, f, mtGC);1620} else if (par_scan_state->should_be_partially_scanned(obj_to_push, cur)) {1621assert(arrayOop(cur)->length() == 0, "entire array remaining to be scanned");1622obj_to_push = cur;1623}1624bool ok = work_q->push(obj_to_push);1625assert(ok, "Should have succeeded");1626cur = next;1627n++;1628}1629TASKQUEUE_STATS_ONLY(par_scan_state->note_overflow_refill(n));1630#ifndef PRODUCT1631assert(_num_par_pushes >= n, "Too many pops?");1632Atomic::add_ptr(-(intptr_t)n, &_num_par_pushes);1633#endif1634return true;1635}1636#undef BUSY16371638void ParNewGeneration::ref_processor_init() {1639if (_ref_processor == NULL) {1640// Allocate and initialize a reference processor1641_ref_processor =1642new ReferenceProcessor(_reserved, // span1643ParallelRefProcEnabled && (ParallelGCThreads > 1), // mt processing1644(int) ParallelGCThreads, // mt processing degree1645refs_discovery_is_mt(), // mt discovery1646(int) ParallelGCThreads, // mt discovery degree1647refs_discovery_is_atomic(), // atomic_discovery1648NULL); // is_alive_non_header1649}1650}16511652const char* ParNewGeneration::name() const {1653return "par new generation";1654}165516561657