Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp
38920 views
/*1* Copyright (c) 2002, 2016, 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 "classfile/symbolTable.hpp"26#include "code/codeCache.hpp"27#include "gc_implementation/parallelScavenge/cardTableExtension.hpp"28#include "gc_implementation/parallelScavenge/gcTaskManager.hpp"29#include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"30#include "gc_implementation/parallelScavenge/psAdaptiveSizePolicy.hpp"31#include "gc_implementation/parallelScavenge/psMarkSweep.hpp"32#include "gc_implementation/parallelScavenge/psParallelCompact.hpp"33#include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"34#include "gc_implementation/parallelScavenge/psTasks.hpp"35#include "gc_implementation/shared/gcHeapSummary.hpp"36#include "gc_implementation/shared/gcTimer.hpp"37#include "gc_implementation/shared/gcTrace.hpp"38#include "gc_implementation/shared/gcTraceTime.hpp"39#include "gc_implementation/shared/isGCActiveMark.hpp"40#include "gc_implementation/shared/spaceDecorator.hpp"41#include "gc_interface/gcCause.hpp"42#include "memory/collectorPolicy.hpp"43#include "memory/gcLocker.inline.hpp"44#include "memory/referencePolicy.hpp"45#include "memory/referenceProcessor.hpp"46#include "memory/resourceArea.hpp"47#include "oops/oop.inline.hpp"48#include "oops/oop.psgc.inline.hpp"49#include "runtime/biasedLocking.hpp"50#include "runtime/fprofiler.hpp"51#include "runtime/handles.inline.hpp"52#include "runtime/threadCritical.hpp"53#include "runtime/vmThread.hpp"54#include "runtime/vm_operations.hpp"55#include "services/memoryService.hpp"56#include "utilities/stack.inline.hpp"5758PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC5960HeapWord* PSScavenge::_to_space_top_before_gc = NULL;61int PSScavenge::_consecutive_skipped_scavenges = 0;62ReferenceProcessor* PSScavenge::_ref_processor = NULL;63CardTableExtension* PSScavenge::_card_table = NULL;64bool PSScavenge::_survivor_overflow = false;65uint PSScavenge::_tenuring_threshold = 0;66HeapWord* PSScavenge::_young_generation_boundary = NULL;67uintptr_t PSScavenge::_young_generation_boundary_compressed = 0;68elapsedTimer PSScavenge::_accumulated_time;69STWGCTimer PSScavenge::_gc_timer;70ParallelScavengeTracer PSScavenge::_gc_tracer;71Stack<markOop, mtGC> PSScavenge::_preserved_mark_stack;72Stack<oop, mtGC> PSScavenge::_preserved_oop_stack;73CollectorCounters* PSScavenge::_counters = NULL;7475// Define before use76class PSIsAliveClosure: public BoolObjectClosure {77public:78bool do_object_b(oop p) {79return (!PSScavenge::is_obj_in_young(p)) || p->is_forwarded();80}81};8283PSIsAliveClosure PSScavenge::_is_alive_closure;8485class PSKeepAliveClosure: public OopClosure {86protected:87MutableSpace* _to_space;88PSPromotionManager* _promotion_manager;8990public:91PSKeepAliveClosure(PSPromotionManager* pm) : _promotion_manager(pm) {92ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();93assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");94_to_space = heap->young_gen()->to_space();9596assert(_promotion_manager != NULL, "Sanity");97}9899template <class T> void do_oop_work(T* p) {100assert (!oopDesc::is_null(*p), "expected non-null ref");101assert ((oopDesc::load_decode_heap_oop_not_null(p))->is_oop(),102"expected an oop while scanning weak refs");103104// Weak refs may be visited more than once.105if (PSScavenge::should_scavenge(p, _to_space)) {106PSScavenge::copy_and_push_safe_barrier<T, /*promote_immediately=*/false>(_promotion_manager, p);107}108}109virtual void do_oop(oop* p) { PSKeepAliveClosure::do_oop_work(p); }110virtual void do_oop(narrowOop* p) { PSKeepAliveClosure::do_oop_work(p); }111};112113class PSEvacuateFollowersClosure: public VoidClosure {114private:115PSPromotionManager* _promotion_manager;116public:117PSEvacuateFollowersClosure(PSPromotionManager* pm) : _promotion_manager(pm) {}118119virtual void do_void() {120assert(_promotion_manager != NULL, "Sanity");121_promotion_manager->drain_stacks(true);122guarantee(_promotion_manager->stacks_empty(),123"stacks should be empty at this point");124}125};126127class PSPromotionFailedClosure : public ObjectClosure {128virtual void do_object(oop obj) {129if (obj->is_forwarded()) {130obj->init_mark();131}132}133};134135class PSRefProcTaskProxy: public GCTask {136typedef AbstractRefProcTaskExecutor::ProcessTask ProcessTask;137ProcessTask & _rp_task;138uint _work_id;139public:140PSRefProcTaskProxy(ProcessTask & rp_task, uint work_id)141: _rp_task(rp_task),142_work_id(work_id)143{ }144145private:146virtual char* name() { return (char *)"Process referents by policy in parallel"; }147virtual void do_it(GCTaskManager* manager, uint which);148};149150void PSRefProcTaskProxy::do_it(GCTaskManager* manager, uint which)151{152PSPromotionManager* promotion_manager =153PSPromotionManager::gc_thread_promotion_manager(which);154assert(promotion_manager != NULL, "sanity check");155PSKeepAliveClosure keep_alive(promotion_manager);156PSEvacuateFollowersClosure evac_followers(promotion_manager);157PSIsAliveClosure is_alive;158_rp_task.work(_work_id, is_alive, keep_alive, evac_followers);159}160161class PSRefEnqueueTaskProxy: public GCTask {162typedef AbstractRefProcTaskExecutor::EnqueueTask EnqueueTask;163EnqueueTask& _enq_task;164uint _work_id;165166public:167PSRefEnqueueTaskProxy(EnqueueTask& enq_task, uint work_id)168: _enq_task(enq_task),169_work_id(work_id)170{ }171172virtual char* name() { return (char *)"Enqueue reference objects in parallel"; }173virtual void do_it(GCTaskManager* manager, uint which)174{175_enq_task.work(_work_id);176}177};178179class PSRefProcTaskExecutor: public AbstractRefProcTaskExecutor {180virtual void execute(ProcessTask& task);181virtual void execute(EnqueueTask& task);182};183184void PSRefProcTaskExecutor::execute(ProcessTask& task)185{186GCTaskQueue* q = GCTaskQueue::create();187GCTaskManager* manager = ParallelScavengeHeap::gc_task_manager();188for(uint i=0; i < manager->active_workers(); i++) {189q->enqueue(new PSRefProcTaskProxy(task, i));190}191ParallelTaskTerminator terminator(manager->active_workers(),192(TaskQueueSetSuper*) PSPromotionManager::stack_array_depth());193if (task.marks_oops_alive() && manager->active_workers() > 1) {194for (uint j = 0; j < manager->active_workers(); j++) {195q->enqueue(new StealTask(&terminator));196}197}198manager->execute_and_wait(q);199}200201202void PSRefProcTaskExecutor::execute(EnqueueTask& task)203{204GCTaskQueue* q = GCTaskQueue::create();205GCTaskManager* manager = ParallelScavengeHeap::gc_task_manager();206for(uint i=0; i < manager->active_workers(); i++) {207q->enqueue(new PSRefEnqueueTaskProxy(task, i));208}209manager->execute_and_wait(q);210}211212// This method contains all heap specific policy for invoking scavenge.213// PSScavenge::invoke_no_policy() will do nothing but attempt to214// scavenge. It will not clean up after failed promotions, bail out if215// we've exceeded policy time limits, or any other special behavior.216// All such policy should be placed here.217//218// Note that this method should only be called from the vm_thread while219// at a safepoint!220bool PSScavenge::invoke() {221assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");222assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");223assert(!Universe::heap()->is_gc_active(), "not reentrant");224225ParallelScavengeHeap* const heap = (ParallelScavengeHeap*)Universe::heap();226assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");227228PSAdaptiveSizePolicy* policy = heap->size_policy();229IsGCActiveMark mark;230231const bool scavenge_done = PSScavenge::invoke_no_policy();232const bool need_full_gc = !scavenge_done ||233policy->should_full_GC(heap->old_gen()->free_in_bytes());234bool full_gc_done = false;235236if (UsePerfData) {237PSGCAdaptivePolicyCounters* const counters = heap->gc_policy_counters();238const int ffs_val = need_full_gc ? full_follows_scavenge : not_skipped;239counters->update_full_follows_scavenge(ffs_val);240}241242if (need_full_gc) {243GCCauseSetter gccs(heap, GCCause::_adaptive_size_policy);244CollectorPolicy* cp = heap->collector_policy();245const bool clear_all_softrefs = cp->should_clear_all_soft_refs();246247if (UseParallelOldGC) {248full_gc_done = PSParallelCompact::invoke_no_policy(clear_all_softrefs);249} else {250full_gc_done = PSMarkSweep::invoke_no_policy(clear_all_softrefs);251}252}253254return full_gc_done;255}256257// This method contains no policy. You should probably258// be calling invoke() instead.259bool PSScavenge::invoke_no_policy() {260assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");261assert(Thread::current() == (Thread*)VMThread::vm_thread(), "should be in vm thread");262263assert(_preserved_mark_stack.is_empty(), "should be empty");264assert(_preserved_oop_stack.is_empty(), "should be empty");265266_gc_timer.register_gc_start();267268TimeStamp scavenge_entry;269TimeStamp scavenge_midpoint;270TimeStamp scavenge_exit;271272scavenge_entry.update();273274if (GC_locker::check_active_before_gc()) {275return false;276}277278ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();279GCCause::Cause gc_cause = heap->gc_cause();280assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");281282// Check for potential problems.283if (!should_attempt_scavenge()) {284return false;285}286287_gc_tracer.report_gc_start(heap->gc_cause(), _gc_timer.gc_start());288289bool promotion_failure_occurred = false;290291PSYoungGen* young_gen = heap->young_gen();292PSOldGen* old_gen = heap->old_gen();293PSAdaptiveSizePolicy* size_policy = heap->size_policy();294295heap->increment_total_collections();296297AdaptiveSizePolicyOutput(size_policy, heap->total_collections());298299if ((gc_cause != GCCause::_java_lang_system_gc) ||300UseAdaptiveSizePolicyWithSystemGC) {301// Gather the feedback data for eden occupancy.302young_gen->eden_space()->accumulate_statistics();303}304305if (ZapUnusedHeapArea) {306// Save information needed to minimize mangling307heap->record_gen_tops_before_GC();308}309310heap->print_heap_before_gc();311heap->trace_heap_before_gc(&_gc_tracer);312313assert(!NeverTenure || _tenuring_threshold == markOopDesc::max_age + 1, "Sanity");314assert(!AlwaysTenure || _tenuring_threshold == 0, "Sanity");315316size_t prev_used = heap->used();317318// Fill in TLABs319heap->accumulate_statistics_all_tlabs();320heap->ensure_parsability(true); // retire TLABs321322if (VerifyBeforeGC && heap->total_collections() >= VerifyGCStartAt) {323HandleMark hm; // Discard invalid handles created during verification324Universe::verify(" VerifyBeforeGC:");325}326327{328ResourceMark rm;329HandleMark hm;330331TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);332GCTraceTime t1(GCCauseString("GC", gc_cause), PrintGC, !PrintGCDetails, NULL, _gc_tracer.gc_id());333TraceCollectorStats tcs(counters());334TraceMemoryManagerStats tms(false /* not full GC */,gc_cause);335336if (TraceGen0Time) accumulated_time()->start();337338// Let the size policy know we're starting339size_policy->minor_collection_begin();340341// Verify the object start arrays.342if (VerifyObjectStartArray &&343VerifyBeforeGC) {344old_gen->verify_object_start_array();345}346347// Verify no unmarked old->young roots348if (VerifyRememberedSets) {349CardTableExtension::verify_all_young_refs_imprecise();350}351352if (!ScavengeWithObjectsInToSpace) {353assert(young_gen->to_space()->is_empty(),354"Attempt to scavenge with live objects in to_space");355young_gen->to_space()->clear(SpaceDecorator::Mangle);356} else if (ZapUnusedHeapArea) {357young_gen->to_space()->mangle_unused_area();358}359save_to_space_top_before_gc();360361COMPILER2_PRESENT(DerivedPointerTable::clear());362363reference_processor()->enable_discovery(true /*verify_disabled*/, true /*verify_no_refs*/);364reference_processor()->setup_policy(false);365366// We track how much was promoted to the next generation for367// the AdaptiveSizePolicy.368size_t old_gen_used_before = old_gen->used_in_bytes();369370// For PrintGCDetails371size_t young_gen_used_before = young_gen->used_in_bytes();372373// Reset our survivor overflow.374set_survivor_overflow(false);375376// We need to save the old top values before377// creating the promotion_manager. We pass the top378// values to the card_table, to prevent it from379// straying into the promotion labs.380HeapWord* old_top = old_gen->object_space()->top();381382// Release all previously held resources383gc_task_manager()->release_all_resources();384385// Set the number of GC threads to be used in this collection386gc_task_manager()->set_active_gang();387gc_task_manager()->task_idle_workers();388// Get the active number of workers here and use that value389// throughout the methods.390uint active_workers = gc_task_manager()->active_workers();391heap->set_par_threads(active_workers);392393PSPromotionManager::pre_scavenge();394395// We'll use the promotion manager again later.396PSPromotionManager* promotion_manager = PSPromotionManager::vm_thread_promotion_manager();397{398GCTraceTime tm("Scavenge", false, false, &_gc_timer, _gc_tracer.gc_id());399ParallelScavengeHeap::ParStrongRootsScope psrs;400401GCTaskQueue* q = GCTaskQueue::create();402403if (!old_gen->object_space()->is_empty()) {404// There are only old-to-young pointers if there are objects405// in the old gen.406uint stripe_total = active_workers;407for(uint i=0; i < stripe_total; i++) {408q->enqueue(new OldToYoungRootsTask(old_gen, old_top, i, stripe_total));409}410}411412q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::universe));413q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::jni_handles));414// We scan the thread roots in parallel415Threads::create_thread_roots_tasks(q);416q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::object_synchronizer));417q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::flat_profiler));418q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::management));419q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::system_dictionary));420q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::class_loader_data));421q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::jvmti));422q->enqueue(new ScavengeRootsTask(ScavengeRootsTask::code_cache));423424ParallelTaskTerminator terminator(425active_workers,426(TaskQueueSetSuper*) promotion_manager->stack_array_depth());427if (active_workers > 1) {428for (uint j = 0; j < active_workers; j++) {429q->enqueue(new StealTask(&terminator));430}431}432433gc_task_manager()->execute_and_wait(q);434}435436scavenge_midpoint.update();437438// Process reference objects discovered during scavenge439{440GCTraceTime tm("References", false, false, &_gc_timer, _gc_tracer.gc_id());441442reference_processor()->setup_policy(false); // not always_clear443reference_processor()->set_active_mt_degree(active_workers);444PSKeepAliveClosure keep_alive(promotion_manager);445PSEvacuateFollowersClosure evac_followers(promotion_manager);446ReferenceProcessorStats stats;447if (reference_processor()->processing_is_mt()) {448PSRefProcTaskExecutor task_executor;449stats = reference_processor()->process_discovered_references(450&_is_alive_closure, &keep_alive, &evac_followers, &task_executor,451&_gc_timer, _gc_tracer.gc_id());452} else {453stats = reference_processor()->process_discovered_references(454&_is_alive_closure, &keep_alive, &evac_followers, NULL, &_gc_timer, _gc_tracer.gc_id());455}456457_gc_tracer.report_gc_reference_stats(stats);458459// Enqueue reference objects discovered during scavenge.460if (reference_processor()->processing_is_mt()) {461PSRefProcTaskExecutor task_executor;462reference_processor()->enqueue_discovered_references(&task_executor);463} else {464reference_processor()->enqueue_discovered_references(NULL);465}466}467468{469GCTraceTime tm("StringTable", false, false, &_gc_timer, _gc_tracer.gc_id());470// Unlink any dead interned Strings and process the remaining live ones.471PSScavengeRootsClosure root_closure(promotion_manager);472StringTable::unlink_or_oops_do(&_is_alive_closure, &root_closure);473}474475// Finally, flush the promotion_manager's labs, and deallocate its stacks.476promotion_failure_occurred = PSPromotionManager::post_scavenge(_gc_tracer);477if (promotion_failure_occurred) {478clean_up_failed_promotion();479if (PrintGC) {480gclog_or_tty->print("--");481}482}483484// Let the size policy know we're done. Note that we count promotion485// failure cleanup time as part of the collection (otherwise, we're486// implicitly saying it's mutator time).487size_policy->minor_collection_end(gc_cause);488489if (!promotion_failure_occurred) {490// Swap the survivor spaces.491young_gen->eden_space()->clear(SpaceDecorator::Mangle);492young_gen->from_space()->clear(SpaceDecorator::Mangle);493young_gen->swap_spaces();494495size_t survived = young_gen->from_space()->used_in_bytes();496size_t promoted = old_gen->used_in_bytes() - old_gen_used_before;497size_policy->update_averages(_survivor_overflow, survived, promoted);498499// A successful scavenge should restart the GC time limit count which is500// for full GC's.501size_policy->reset_gc_overhead_limit_count();502if (UseAdaptiveSizePolicy) {503// Calculate the new survivor size and tenuring threshold504505if (PrintAdaptiveSizePolicy) {506gclog_or_tty->print("AdaptiveSizeStart: ");507gclog_or_tty->stamp();508gclog_or_tty->print_cr(" collection: %d ",509heap->total_collections());510511if (Verbose) {512gclog_or_tty->print("old_gen_capacity: %d young_gen_capacity: %d",513old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes());514}515}516517518if (UsePerfData) {519PSGCAdaptivePolicyCounters* counters = heap->gc_policy_counters();520counters->update_old_eden_size(521size_policy->calculated_eden_size_in_bytes());522counters->update_old_promo_size(523size_policy->calculated_promo_size_in_bytes());524counters->update_old_capacity(old_gen->capacity_in_bytes());525counters->update_young_capacity(young_gen->capacity_in_bytes());526counters->update_survived(survived);527counters->update_promoted(promoted);528counters->update_survivor_overflowed(_survivor_overflow);529}530531size_t max_young_size = young_gen->max_size();532533// Deciding a free ratio in the young generation is tricky, so if534// MinHeapFreeRatio or MaxHeapFreeRatio are in use (implicating535// that the old generation size may have been limited because of them) we536// should then limit our young generation size using NewRatio to have it537// follow the old generation size.538if (MinHeapFreeRatio != 0 || MaxHeapFreeRatio != 100) {539max_young_size = MIN2(old_gen->capacity_in_bytes() / NewRatio, young_gen->max_size());540}541542size_t survivor_limit =543size_policy->max_survivor_size(max_young_size);544_tenuring_threshold =545size_policy->compute_survivor_space_size_and_threshold(546_survivor_overflow,547_tenuring_threshold,548survivor_limit);549550if (PrintTenuringDistribution) {551gclog_or_tty->cr();552gclog_or_tty->print_cr("Desired survivor size " SIZE_FORMAT " bytes, new threshold %u (max %u)",553size_policy->calculated_survivor_size_in_bytes(),554_tenuring_threshold, MaxTenuringThreshold);555}556557if (UsePerfData) {558PSGCAdaptivePolicyCounters* counters = heap->gc_policy_counters();559counters->update_tenuring_threshold(_tenuring_threshold);560counters->update_survivor_size_counters();561}562563// Do call at minor collections?564// Don't check if the size_policy is ready at this565// level. Let the size_policy check that internally.566if (UseAdaptiveGenerationSizePolicyAtMinorCollection &&567((gc_cause != GCCause::_java_lang_system_gc) ||568UseAdaptiveSizePolicyWithSystemGC)) {569570// Calculate optimial free space amounts571assert(young_gen->max_size() >572young_gen->from_space()->capacity_in_bytes() +573young_gen->to_space()->capacity_in_bytes(),574"Sizes of space in young gen are out-of-bounds");575576size_t young_live = young_gen->used_in_bytes();577size_t eden_live = young_gen->eden_space()->used_in_bytes();578size_t cur_eden = young_gen->eden_space()->capacity_in_bytes();579size_t max_old_gen_size = old_gen->max_gen_size();580size_t max_eden_size = max_young_size -581young_gen->from_space()->capacity_in_bytes() -582young_gen->to_space()->capacity_in_bytes();583584// Used for diagnostics585size_policy->clear_generation_free_space_flags();586587size_policy->compute_eden_space_size(young_live,588eden_live,589cur_eden,590max_eden_size,591false /* not full gc*/);592593size_policy->check_gc_overhead_limit(young_live,594eden_live,595max_old_gen_size,596max_eden_size,597false /* not full gc*/,598gc_cause,599heap->collector_policy());600601size_policy->decay_supplemental_growth(false /* not full gc*/);602}603// Resize the young generation at every collection604// even if new sizes have not been calculated. This is605// to allow resizes that may have been inhibited by the606// relative location of the "to" and "from" spaces.607608// Resizing the old gen at minor collects can cause increases609// that don't feed back to the generation sizing policy until610// a major collection. Don't resize the old gen here.611612heap->resize_young_gen(size_policy->calculated_eden_size_in_bytes(),613size_policy->calculated_survivor_size_in_bytes());614615if (PrintAdaptiveSizePolicy) {616gclog_or_tty->print_cr("AdaptiveSizeStop: collection: %d ",617heap->total_collections());618}619}620621// Update the structure of the eden. With NUMA-eden CPU hotplugging or offlining can622// cause the change of the heap layout. Make sure eden is reshaped if that's the case.623// Also update() will case adaptive NUMA chunk resizing.624assert(young_gen->eden_space()->is_empty(), "eden space should be empty now");625young_gen->eden_space()->update();626627heap->gc_policy_counters()->update_counters();628629heap->resize_all_tlabs();630631assert(young_gen->to_space()->is_empty(), "to space should be empty now");632}633634COMPILER2_PRESENT(DerivedPointerTable::update_pointers());635636NOT_PRODUCT(reference_processor()->verify_no_references_recorded());637638// Re-verify object start arrays639if (VerifyObjectStartArray &&640VerifyAfterGC) {641old_gen->verify_object_start_array();642}643644// Verify all old -> young cards are now precise645if (VerifyRememberedSets) {646// Precise verification will give false positives. Until this is fixed,647// use imprecise verification.648// CardTableExtension::verify_all_young_refs_precise();649CardTableExtension::verify_all_young_refs_imprecise();650}651652if (TraceGen0Time) accumulated_time()->stop();653654if (PrintGC) {655if (PrintGCDetails) {656// Don't print a GC timestamp here. This is after the GC so657// would be confusing.658young_gen->print_used_change(young_gen_used_before);659}660heap->print_heap_change(prev_used);661}662663// Track memory usage and detect low memory664MemoryService::track_memory_usage();665heap->update_counters();666667gc_task_manager()->release_idle_workers();668}669670if (VerifyAfterGC && heap->total_collections() >= VerifyGCStartAt) {671HandleMark hm; // Discard invalid handles created during verification672Universe::verify(" VerifyAfterGC:");673}674675heap->print_heap_after_gc();676heap->trace_heap_after_gc(&_gc_tracer);677_gc_tracer.report_tenuring_threshold(tenuring_threshold());678679if (ZapUnusedHeapArea) {680young_gen->eden_space()->check_mangled_unused_area_complete();681young_gen->from_space()->check_mangled_unused_area_complete();682young_gen->to_space()->check_mangled_unused_area_complete();683}684685scavenge_exit.update();686687if (PrintGCTaskTimeStamps) {688tty->print_cr("VM-Thread " INT64_FORMAT " " INT64_FORMAT " " INT64_FORMAT,689scavenge_entry.ticks(), scavenge_midpoint.ticks(),690scavenge_exit.ticks());691gc_task_manager()->print_task_time_stamps();692}693694#ifdef TRACESPINNING695ParallelTaskTerminator::print_termination_counts();696#endif697698699_gc_timer.register_gc_end();700701_gc_tracer.report_gc_end(_gc_timer.gc_end(), _gc_timer.time_partitions());702703return !promotion_failure_occurred;704}705706// This method iterates over all objects in the young generation,707// unforwarding markOops. It then restores any preserved mark oops,708// and clears the _preserved_mark_stack.709void PSScavenge::clean_up_failed_promotion() {710ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();711assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");712713PSYoungGen* young_gen = heap->young_gen();714715{716ResourceMark rm;717718// Unforward all pointers in the young gen.719PSPromotionFailedClosure unforward_closure;720young_gen->object_iterate(&unforward_closure);721722if (PrintGC && Verbose) {723gclog_or_tty->print_cr("Restoring %d marks", _preserved_oop_stack.size());724}725726// Restore any saved marks.727while (!_preserved_oop_stack.is_empty()) {728oop obj = _preserved_oop_stack.pop();729markOop mark = _preserved_mark_stack.pop();730obj->set_mark(mark);731}732733// Clear the preserved mark and oop stack caches.734_preserved_mark_stack.clear(true);735_preserved_oop_stack.clear(true);736}737738// Reset the PromotionFailureALot counters.739NOT_PRODUCT(Universe::heap()->reset_promotion_should_fail();)740}741742// This method is called whenever an attempt to promote an object743// fails. Some markOops will need preservation, some will not. Note744// that the entire eden is traversed after a failed promotion, with745// all forwarded headers replaced by the default markOop. This means746// it is not necessary to preserve most markOops.747void PSScavenge::oop_promotion_failed(oop obj, markOop obj_mark) {748if (obj_mark->must_be_preserved_for_promotion_failure(obj)) {749// Should use per-worker private stacks here rather than750// locking a common pair of stacks.751ThreadCritical tc;752_preserved_oop_stack.push(obj);753_preserved_mark_stack.push(obj_mark);754}755}756757bool PSScavenge::should_attempt_scavenge() {758ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();759assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");760PSGCAdaptivePolicyCounters* counters = heap->gc_policy_counters();761762if (UsePerfData) {763counters->update_scavenge_skipped(not_skipped);764}765766PSYoungGen* young_gen = heap->young_gen();767PSOldGen* old_gen = heap->old_gen();768769if (!ScavengeWithObjectsInToSpace) {770// Do not attempt to promote unless to_space is empty771if (!young_gen->to_space()->is_empty()) {772_consecutive_skipped_scavenges++;773if (UsePerfData) {774counters->update_scavenge_skipped(to_space_not_empty);775}776return false;777}778}779780// Test to see if the scavenge will likely fail.781PSAdaptiveSizePolicy* policy = heap->size_policy();782783// A similar test is done in the policy's should_full_GC(). If this is784// changed, decide if that test should also be changed.785size_t avg_promoted = (size_t) policy->padded_average_promoted_in_bytes();786size_t promotion_estimate = MIN2(avg_promoted, young_gen->used_in_bytes());787bool result = promotion_estimate < old_gen->free_in_bytes();788789if (PrintGCDetails && Verbose) {790gclog_or_tty->print(result ? " do scavenge: " : " skip scavenge: ");791gclog_or_tty->print_cr(" average_promoted " SIZE_FORMAT792" padded_average_promoted " SIZE_FORMAT793" free in old gen " SIZE_FORMAT,794(size_t) policy->average_promoted_in_bytes(),795(size_t) policy->padded_average_promoted_in_bytes(),796old_gen->free_in_bytes());797if (young_gen->used_in_bytes() <798(size_t) policy->padded_average_promoted_in_bytes()) {799gclog_or_tty->print_cr(" padded_promoted_average is greater"800" than maximum promotion = " SIZE_FORMAT, young_gen->used_in_bytes());801}802}803804if (result) {805_consecutive_skipped_scavenges = 0;806} else {807_consecutive_skipped_scavenges++;808if (UsePerfData) {809counters->update_scavenge_skipped(promoted_too_large);810}811}812return result;813}814815// Used to add tasks816GCTaskManager* const PSScavenge::gc_task_manager() {817assert(ParallelScavengeHeap::gc_task_manager() != NULL,818"shouldn't return NULL");819return ParallelScavengeHeap::gc_task_manager();820}821822void PSScavenge::initialize() {823// Arguments must have been parsed824825if (AlwaysTenure) {826_tenuring_threshold = 0;827} else if (NeverTenure) {828_tenuring_threshold = markOopDesc::max_age + 1;829} else {830// We want to smooth out our startup times for the AdaptiveSizePolicy831_tenuring_threshold = (UseAdaptiveSizePolicy) ? InitialTenuringThreshold :832MaxTenuringThreshold;833}834835ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();836assert(heap->kind() == CollectedHeap::ParallelScavengeHeap, "Sanity");837838PSYoungGen* young_gen = heap->young_gen();839PSOldGen* old_gen = heap->old_gen();840841// Set boundary between young_gen and old_gen842assert(old_gen->reserved().end() <= young_gen->eden_space()->bottom(),843"old above young");844set_young_generation_boundary(young_gen->eden_space()->bottom());845846// Initialize ref handling object for scavenging.847MemRegion mr = young_gen->reserved();848849_ref_processor =850new ReferenceProcessor(mr, // span851ParallelRefProcEnabled && (ParallelGCThreads > 1), // mt processing852(int) ParallelGCThreads, // mt processing degree853true, // mt discovery854(int) ParallelGCThreads, // mt discovery degree855true, // atomic_discovery856NULL); // header provides liveness info857858// Cache the cardtable859BarrierSet* bs = Universe::heap()->barrier_set();860assert(bs->kind() == BarrierSet::CardTableModRef, "Wrong barrier set kind");861_card_table = (CardTableExtension*)bs;862863_counters = new CollectorCounters("PSScavenge", 0);864}865866867