Path: blob/aarch64-shenandoah-jdk8u272-b10/hotspot/src/share/vm/memory/genCollectedHeap.cpp
32285 views
/*1* Copyright (c) 2000, 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 "classfile/systemDictionary.hpp"27#include "classfile/vmSymbols.hpp"28#include "code/codeCache.hpp"29#include "code/icBuffer.hpp"30#include "gc_implementation/shared/collectorCounters.hpp"31#include "gc_implementation/shared/gcTrace.hpp"32#include "gc_implementation/shared/gcTraceTime.hpp"33#include "gc_implementation/shared/vmGCOperations.hpp"34#include "gc_interface/collectedHeap.inline.hpp"35#include "memory/filemap.hpp"36#include "memory/gcLocker.inline.hpp"37#include "memory/genCollectedHeap.hpp"38#include "memory/genOopClosures.inline.hpp"39#include "memory/generation.inline.hpp"40#include "memory/generationSpec.hpp"41#include "memory/resourceArea.hpp"42#include "memory/sharedHeap.hpp"43#include "memory/space.hpp"44#include "oops/oop.inline.hpp"45#include "oops/oop.inline2.hpp"46#include "runtime/biasedLocking.hpp"47#include "runtime/fprofiler.hpp"48#include "runtime/handles.hpp"49#include "runtime/handles.inline.hpp"50#include "runtime/java.hpp"51#include "runtime/vmThread.hpp"52#include "services/management.hpp"53#include "services/memoryService.hpp"54#include "utilities/vmError.hpp"55#include "utilities/workgroup.hpp"56#include "utilities/macros.hpp"57#if INCLUDE_ALL_GCS58#include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"59#include "gc_implementation/concurrentMarkSweep/vmCMSOperations.hpp"60#endif // INCLUDE_ALL_GCS61#if INCLUDE_JFR62#include "jfr/jfr.hpp"63#endif // INCLUDE_JFR6465GenCollectedHeap* GenCollectedHeap::_gch;66NOT_PRODUCT(size_t GenCollectedHeap::_skip_header_HeapWords = 0;)6768// The set of potentially parallel tasks in root scanning.69enum GCH_strong_roots_tasks {70GCH_PS_Universe_oops_do,71GCH_PS_JNIHandles_oops_do,72GCH_PS_ObjectSynchronizer_oops_do,73GCH_PS_FlatProfiler_oops_do,74GCH_PS_Management_oops_do,75GCH_PS_SystemDictionary_oops_do,76GCH_PS_ClassLoaderDataGraph_oops_do,77GCH_PS_jvmti_oops_do,78GCH_PS_CodeCache_oops_do,79GCH_PS_younger_gens,80// Leave this one last.81GCH_PS_NumElements82};8384GenCollectedHeap::GenCollectedHeap(GenCollectorPolicy *policy) :85SharedHeap(policy),86_gen_policy(policy),87_process_strong_tasks(new SubTasksDone(GCH_PS_NumElements)),88_full_collections_completed(0)89{90assert(policy != NULL, "Sanity check");91}9293jint GenCollectedHeap::initialize() {94CollectedHeap::pre_initialize();9596int i;97_n_gens = gen_policy()->number_of_generations();9899// While there are no constraints in the GC code that HeapWordSize100// be any particular value, there are multiple other areas in the101// system which believe this to be true (e.g. oop->object_size in some102// cases incorrectly returns the size in wordSize units rather than103// HeapWordSize).104guarantee(HeapWordSize == wordSize, "HeapWordSize must equal wordSize");105106// The heap must be at least as aligned as generations.107size_t gen_alignment = Generation::GenGrain;108109_gen_specs = gen_policy()->generations();110111// Make sure the sizes are all aligned.112for (i = 0; i < _n_gens; i++) {113_gen_specs[i]->align(gen_alignment);114}115116// Allocate space for the heap.117118char* heap_address;119size_t total_reserved = 0;120int n_covered_regions = 0;121ReservedSpace heap_rs;122123size_t heap_alignment = collector_policy()->heap_alignment();124125heap_address = allocate(heap_alignment, &total_reserved,126&n_covered_regions, &heap_rs);127128if (!heap_rs.is_reserved()) {129vm_shutdown_during_initialization(130"Could not reserve enough space for object heap");131return JNI_ENOMEM;132}133134_reserved = MemRegion((HeapWord*)heap_rs.base(),135(HeapWord*)(heap_rs.base() + heap_rs.size()));136137// It is important to do this in a way such that concurrent readers can't138// temporarily think somethings in the heap. (Seen this happen in asserts.)139_reserved.set_word_size(0);140_reserved.set_start((HeapWord*)heap_rs.base());141size_t actual_heap_size = heap_rs.size();142_reserved.set_end((HeapWord*)(heap_rs.base() + actual_heap_size));143144_rem_set = collector_policy()->create_rem_set(_reserved, n_covered_regions);145set_barrier_set(rem_set()->bs());146147_gch = this;148149for (i = 0; i < _n_gens; i++) {150ReservedSpace this_rs = heap_rs.first_part(_gen_specs[i]->max_size(), false, false);151_gens[i] = _gen_specs[i]->init(this_rs, i, rem_set());152heap_rs = heap_rs.last_part(_gen_specs[i]->max_size());153}154clear_incremental_collection_failed();155156#if INCLUDE_ALL_GCS157// If we are running CMS, create the collector responsible158// for collecting the CMS generations.159if (collector_policy()->is_concurrent_mark_sweep_policy()) {160bool success = create_cms_collector();161if (!success) return JNI_ENOMEM;162}163#endif // INCLUDE_ALL_GCS164165return JNI_OK;166}167168169char* GenCollectedHeap::allocate(size_t alignment,170size_t* _total_reserved,171int* _n_covered_regions,172ReservedSpace* heap_rs){173const char overflow_msg[] = "The size of the object heap + VM data exceeds "174"the maximum representable size";175176// Now figure out the total size.177size_t total_reserved = 0;178int n_covered_regions = 0;179const size_t pageSize = UseLargePages ?180os::large_page_size() : os::vm_page_size();181182assert(alignment % pageSize == 0, "Must be");183184for (int i = 0; i < _n_gens; i++) {185total_reserved += _gen_specs[i]->max_size();186if (total_reserved < _gen_specs[i]->max_size()) {187vm_exit_during_initialization(overflow_msg);188}189n_covered_regions += _gen_specs[i]->n_covered_regions();190}191assert(total_reserved % alignment == 0,192err_msg("Gen size; total_reserved=" SIZE_FORMAT ", alignment="193SIZE_FORMAT, total_reserved, alignment));194195// Needed until the cardtable is fixed to have the right number196// of covered regions.197n_covered_regions += 2;198199*_total_reserved = total_reserved;200*_n_covered_regions = n_covered_regions;201202*heap_rs = Universe::reserve_heap(total_reserved, alignment);203return heap_rs->base();204}205206207void GenCollectedHeap::post_initialize() {208SharedHeap::post_initialize();209TwoGenerationCollectorPolicy *policy =210(TwoGenerationCollectorPolicy *)collector_policy();211guarantee(policy->is_two_generation_policy(), "Illegal policy type");212DefNewGeneration* def_new_gen = (DefNewGeneration*) get_gen(0);213assert(def_new_gen->kind() == Generation::DefNew ||214def_new_gen->kind() == Generation::ParNew ||215def_new_gen->kind() == Generation::ASParNew,216"Wrong generation kind");217218Generation* old_gen = get_gen(1);219assert(old_gen->kind() == Generation::ConcurrentMarkSweep ||220old_gen->kind() == Generation::ASConcurrentMarkSweep ||221old_gen->kind() == Generation::MarkSweepCompact,222"Wrong generation kind");223224policy->initialize_size_policy(def_new_gen->eden()->capacity(),225old_gen->capacity(),226def_new_gen->from()->capacity());227policy->initialize_gc_policy_counters();228}229230void GenCollectedHeap::ref_processing_init() {231SharedHeap::ref_processing_init();232for (int i = 0; i < _n_gens; i++) {233_gens[i]->ref_processor_init();234}235}236237size_t GenCollectedHeap::capacity() const {238size_t res = 0;239for (int i = 0; i < _n_gens; i++) {240res += _gens[i]->capacity();241}242return res;243}244245size_t GenCollectedHeap::used() const {246size_t res = 0;247for (int i = 0; i < _n_gens; i++) {248res += _gens[i]->used();249}250return res;251}252253// Save the "used_region" for generations level and lower.254void GenCollectedHeap::save_used_regions(int level) {255assert(level < _n_gens, "Illegal level parameter");256for (int i = level; i >= 0; i--) {257_gens[i]->save_used_region();258}259}260261size_t GenCollectedHeap::max_capacity() const {262size_t res = 0;263for (int i = 0; i < _n_gens; i++) {264res += _gens[i]->max_capacity();265}266return res;267}268269// Update the _full_collections_completed counter270// at the end of a stop-world full GC.271unsigned int GenCollectedHeap::update_full_collections_completed() {272MonitorLockerEx ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag);273assert(_full_collections_completed <= _total_full_collections,274"Can't complete more collections than were started");275_full_collections_completed = _total_full_collections;276ml.notify_all();277return _full_collections_completed;278}279280// Update the _full_collections_completed counter, as appropriate,281// at the end of a concurrent GC cycle. Note the conditional update282// below to allow this method to be called by a concurrent collector283// without synchronizing in any manner with the VM thread (which284// may already have initiated a STW full collection "concurrently").285unsigned int GenCollectedHeap::update_full_collections_completed(unsigned int count) {286MonitorLockerEx ml(FullGCCount_lock, Mutex::_no_safepoint_check_flag);287assert((_full_collections_completed <= _total_full_collections) &&288(count <= _total_full_collections),289"Can't complete more collections than were started");290if (count > _full_collections_completed) {291_full_collections_completed = count;292ml.notify_all();293}294return _full_collections_completed;295}296297298#ifndef PRODUCT299// Override of memory state checking method in CollectedHeap:300// Some collectors (CMS for example) can't have badHeapWordVal written301// in the first two words of an object. (For instance , in the case of302// CMS these words hold state used to synchronize between certain303// (concurrent) GC steps and direct allocating mutators.)304// The skip_header_HeapWords() method below, allows us to skip305// over the requisite number of HeapWord's. Note that (for306// generational collectors) this means that those many words are307// skipped in each object, irrespective of the generation in which308// that object lives. The resultant loss of precision seems to be309// harmless and the pain of avoiding that imprecision appears somewhat310// higher than we are prepared to pay for such rudimentary debugging311// support.312void GenCollectedHeap::check_for_non_bad_heap_word_value(HeapWord* addr,313size_t size) {314if (CheckMemoryInitialization && ZapUnusedHeapArea) {315// We are asked to check a size in HeapWords,316// but the memory is mangled in juint words.317juint* start = (juint*) (addr + skip_header_HeapWords());318juint* end = (juint*) (addr + size);319for (juint* slot = start; slot < end; slot += 1) {320assert(*slot == badHeapWordVal,321"Found non badHeapWordValue in pre-allocation check");322}323}324}325#endif326327HeapWord* GenCollectedHeap::attempt_allocation(size_t size,328bool is_tlab,329bool first_only) {330HeapWord* res;331for (int i = 0; i < _n_gens; i++) {332if (_gens[i]->should_allocate(size, is_tlab)) {333res = _gens[i]->allocate(size, is_tlab);334if (res != NULL) return res;335else if (first_only) break;336}337}338// Otherwise...339return NULL;340}341342HeapWord* GenCollectedHeap::mem_allocate(size_t size,343bool* gc_overhead_limit_was_exceeded) {344return collector_policy()->mem_allocate_work(size,345false /* is_tlab */,346gc_overhead_limit_was_exceeded);347}348349bool GenCollectedHeap::must_clear_all_soft_refs() {350return _gc_cause == GCCause::_last_ditch_collection;351}352353bool GenCollectedHeap::should_do_concurrent_full_gc(GCCause::Cause cause) {354return UseConcMarkSweepGC &&355((cause == GCCause::_gc_locker && GCLockerInvokesConcurrent) ||356(cause == GCCause::_java_lang_system_gc && ExplicitGCInvokesConcurrent));357}358359void GenCollectedHeap::do_collection(bool full,360bool clear_all_soft_refs,361size_t size,362bool is_tlab,363int max_level) {364bool prepared_for_verification = false;365ResourceMark rm;366DEBUG_ONLY(Thread* my_thread = Thread::current();)367368assert(SafepointSynchronize::is_at_safepoint(), "should be at safepoint");369assert(my_thread->is_VM_thread() ||370my_thread->is_ConcurrentGC_thread(),371"incorrect thread type capability");372assert(Heap_lock->is_locked(),373"the requesting thread should have the Heap_lock");374guarantee(!is_gc_active(), "collection is not reentrant");375assert(max_level < n_gens(), "sanity check");376377if (GC_locker::check_active_before_gc()) {378return; // GC is disabled (e.g. JNI GetXXXCritical operation)379}380381const bool do_clear_all_soft_refs = clear_all_soft_refs ||382collector_policy()->should_clear_all_soft_refs();383384ClearedAllSoftRefs casr(do_clear_all_soft_refs, collector_policy());385386const size_t metadata_prev_used = MetaspaceAux::used_bytes();387388print_heap_before_gc();389390{391FlagSetting fl(_is_gc_active, true);392393bool complete = full && (max_level == (n_gens()-1));394const char* gc_cause_prefix = complete ? "Full GC" : "GC";395TraceCPUTime tcpu(PrintGCDetails, true, gclog_or_tty);396// The PrintGCDetails logging starts before we have incremented the GC id. We will do that later397// so we can assume here that the next GC id is what we want.398GCTraceTime t(GCCauseString(gc_cause_prefix, gc_cause()), PrintGCDetails, false, NULL, GCId::peek());399400gc_prologue(complete);401increment_total_collections(complete);402403size_t gch_prev_used = used();404405int starting_level = 0;406if (full) {407// Search for the oldest generation which will collect all younger408// generations, and start collection loop there.409for (int i = max_level; i >= 0; i--) {410if (_gens[i]->full_collects_younger_generations()) {411starting_level = i;412break;413}414}415}416417bool must_restore_marks_for_biased_locking = false;418419int max_level_collected = starting_level;420for (int i = starting_level; i <= max_level; i++) {421if (_gens[i]->should_collect(full, size, is_tlab)) {422if (i == n_gens() - 1) { // a major collection is to happen423if (!complete) {424// The full_collections increment was missed above.425increment_total_full_collections();426}427pre_full_gc_dump(NULL); // do any pre full gc dumps428}429// Timer for individual generations. Last argument is false: no CR430// FIXME: We should try to start the timing earlier to cover more of the GC pause431// The PrintGCDetails logging starts before we have incremented the GC id. We will do that later432// so we can assume here that the next GC id is what we want.433GCTraceTime t1(_gens[i]->short_name(), PrintGCDetails, false, NULL, GCId::peek());434TraceCollectorStats tcs(_gens[i]->counters());435TraceMemoryManagerStats tmms(_gens[i]->kind(),gc_cause());436437size_t prev_used = _gens[i]->used();438_gens[i]->stat_record()->invocations++;439_gens[i]->stat_record()->accumulated_time.start();440441// Must be done anew before each collection because442// a previous collection will do mangling and will443// change top of some spaces.444record_gen_tops_before_GC();445446if (PrintGC && Verbose) {447gclog_or_tty->print("level=%d invoke=%d size=" SIZE_FORMAT,448i,449_gens[i]->stat_record()->invocations,450size*HeapWordSize);451}452453if (VerifyBeforeGC && i >= VerifyGCLevel &&454total_collections() >= VerifyGCStartAt) {455HandleMark hm; // Discard invalid handles created during verification456if (!prepared_for_verification) {457prepare_for_verify();458prepared_for_verification = true;459}460Universe::verify(" VerifyBeforeGC:");461}462COMPILER2_PRESENT(DerivedPointerTable::clear());463464if (!must_restore_marks_for_biased_locking &&465_gens[i]->performs_in_place_marking()) {466// We perform this mark word preservation work lazily467// because it's only at this point that we know whether we468// absolutely have to do it; we want to avoid doing it for469// scavenge-only collections where it's unnecessary470must_restore_marks_for_biased_locking = true;471BiasedLocking::preserve_marks();472}473474// Do collection work475{476// Note on ref discovery: For what appear to be historical reasons,477// GCH enables and disabled (by enqueing) refs discovery.478// In the future this should be moved into the generation's479// collect method so that ref discovery and enqueueing concerns480// are local to a generation. The collect method could return481// an appropriate indication in the case that notification on482// the ref lock was needed. This will make the treatment of483// weak refs more uniform (and indeed remove such concerns484// from GCH). XXX485486HandleMark hm; // Discard invalid handles created during gc487save_marks(); // save marks for all gens488// We want to discover references, but not process them yet.489// This mode is disabled in process_discovered_references if the490// generation does some collection work, or in491// enqueue_discovered_references if the generation returns492// without doing any work.493ReferenceProcessor* rp = _gens[i]->ref_processor();494// If the discovery of ("weak") refs in this generation is495// atomic wrt other collectors in this configuration, we496// are guaranteed to have empty discovered ref lists.497if (rp->discovery_is_atomic()) {498rp->enable_discovery(true /*verify_disabled*/, true /*verify_no_refs*/);499rp->setup_policy(do_clear_all_soft_refs);500} else {501// collect() below will enable discovery as appropriate502}503_gens[i]->collect(full, do_clear_all_soft_refs, size, is_tlab);504if (!rp->enqueuing_is_done()) {505rp->enqueue_discovered_references();506} else {507rp->set_enqueuing_is_done(false);508}509rp->verify_no_references_recorded();510}511max_level_collected = i;512513// Determine if allocation request was met.514if (size > 0) {515if (!is_tlab || _gens[i]->supports_tlab_allocation()) {516if (size*HeapWordSize <= _gens[i]->unsafe_max_alloc_nogc()) {517size = 0;518}519}520}521522COMPILER2_PRESENT(DerivedPointerTable::update_pointers());523524_gens[i]->stat_record()->accumulated_time.stop();525526update_gc_stats(i, full);527528if (VerifyAfterGC && i >= VerifyGCLevel &&529total_collections() >= VerifyGCStartAt) {530HandleMark hm; // Discard invalid handles created during verification531Universe::verify(" VerifyAfterGC:");532}533534if (PrintGCDetails) {535gclog_or_tty->print(":");536_gens[i]->print_heap_change(prev_used);537}538}539}540541// Update "complete" boolean wrt what actually transpired --542// for instance, a promotion failure could have led to543// a whole heap collection.544complete = complete || (max_level_collected == n_gens() - 1);545546if (complete) { // We did a "major" collection547// FIXME: See comment at pre_full_gc_dump call548post_full_gc_dump(NULL); // do any post full gc dumps549}550551if (PrintGCDetails) {552print_heap_change(gch_prev_used);553554// Print metaspace info for full GC with PrintGCDetails flag.555if (complete) {556MetaspaceAux::print_metaspace_change(metadata_prev_used);557}558}559560for (int j = max_level_collected; j >= 0; j -= 1) {561// Adjust generation sizes.562_gens[j]->compute_new_size();563}564565if (complete) {566// Delete metaspaces for unloaded class loaders and clean up loader_data graph567ClassLoaderDataGraph::purge();568MetaspaceAux::verify_metrics();569// Resize the metaspace capacity after full collections570MetaspaceGC::compute_new_size();571update_full_collections_completed();572}573574// Track memory usage and detect low memory after GC finishes575MemoryService::track_memory_usage();576577gc_epilogue(complete);578579if (must_restore_marks_for_biased_locking) {580BiasedLocking::restore_marks();581}582}583584AdaptiveSizePolicy* sp = gen_policy()->size_policy();585AdaptiveSizePolicyOutput(sp, total_collections());586587print_heap_after_gc();588589#ifdef TRACESPINNING590ParallelTaskTerminator::print_termination_counts();591#endif592}593594HeapWord* GenCollectedHeap::satisfy_failed_allocation(size_t size, bool is_tlab) {595return collector_policy()->satisfy_failed_allocation(size, is_tlab);596}597598void GenCollectedHeap::set_par_threads(uint t) {599SharedHeap::set_par_threads(t);600set_n_termination(t);601}602603void GenCollectedHeap::set_n_termination(uint t) {604_process_strong_tasks->set_n_threads(t);605}606607#ifdef ASSERT608class AssertNonScavengableClosure: public OopClosure {609public:610virtual void do_oop(oop* p) {611assert(!Universe::heap()->is_in_partial_collection(*p),612"Referent should not be scavengable."); }613virtual void do_oop(narrowOop* p) { ShouldNotReachHere(); }614};615static AssertNonScavengableClosure assert_is_non_scavengable_closure;616#endif617618void GenCollectedHeap::process_roots(bool activate_scope,619ScanningOption so,620OopClosure* strong_roots,621OopClosure* weak_roots,622CLDClosure* strong_cld_closure,623CLDClosure* weak_cld_closure,624CodeBlobToOopClosure* code_roots) {625StrongRootsScope srs(this, activate_scope);626627// General roots.628assert(_strong_roots_parity != 0, "must have called prologue code");629assert(code_roots != NULL, "code root closure should always be set");630// _n_termination for _process_strong_tasks should be set up stream631// in a method not running in a GC worker. Otherwise the GC worker632// could be trying to change the termination condition while the task633// is executing in another GC worker.634635if (!_process_strong_tasks->is_task_claimed(GCH_PS_ClassLoaderDataGraph_oops_do)) {636ClassLoaderDataGraph::roots_cld_do(strong_cld_closure, weak_cld_closure);637}638639// Some CLDs contained in the thread frames should be considered strong.640// Don't process them if they will be processed during the ClassLoaderDataGraph phase.641CLDClosure* roots_from_clds_p = (strong_cld_closure != weak_cld_closure) ? strong_cld_closure : NULL;642// Only process code roots from thread stacks if we aren't visiting the entire CodeCache anyway643CodeBlobToOopClosure* roots_from_code_p = (so & SO_AllCodeCache) ? NULL : code_roots;644645Threads::possibly_parallel_oops_do(strong_roots, roots_from_clds_p, roots_from_code_p);646647if (!_process_strong_tasks->is_task_claimed(GCH_PS_Universe_oops_do)) {648Universe::oops_do(strong_roots);649}650// Global (strong) JNI handles651if (!_process_strong_tasks->is_task_claimed(GCH_PS_JNIHandles_oops_do)) {652JNIHandles::oops_do(strong_roots);653}654655if (!_process_strong_tasks->is_task_claimed(GCH_PS_ObjectSynchronizer_oops_do)) {656ObjectSynchronizer::oops_do(strong_roots);657}658if (!_process_strong_tasks->is_task_claimed(GCH_PS_FlatProfiler_oops_do)) {659FlatProfiler::oops_do(strong_roots);660}661if (!_process_strong_tasks->is_task_claimed(GCH_PS_Management_oops_do)) {662Management::oops_do(strong_roots);663}664if (!_process_strong_tasks->is_task_claimed(GCH_PS_jvmti_oops_do)) {665JvmtiExport::oops_do(strong_roots);666}667668if (!_process_strong_tasks->is_task_claimed(GCH_PS_SystemDictionary_oops_do)) {669SystemDictionary::roots_oops_do(strong_roots, weak_roots);670}671672// All threads execute the following. A specific chunk of buckets673// from the StringTable are the individual tasks.674if (weak_roots != NULL) {675if (CollectedHeap::use_parallel_gc_threads()) {676StringTable::possibly_parallel_oops_do(weak_roots);677} else {678StringTable::oops_do(weak_roots);679}680}681682if (!_process_strong_tasks->is_task_claimed(GCH_PS_CodeCache_oops_do)) {683if (so & SO_ScavengeCodeCache) {684assert(code_roots != NULL, "must supply closure for code cache");685686// We only visit parts of the CodeCache when scavenging.687CodeCache::scavenge_root_nmethods_do(code_roots);688}689if (so & SO_AllCodeCache) {690assert(code_roots != NULL, "must supply closure for code cache");691692// CMSCollector uses this to do intermediate-strength collections.693// We scan the entire code cache, since CodeCache::do_unloading is not called.694CodeCache::blobs_do(code_roots);695}696// Verify that the code cache contents are not subject to697// movement by a scavenging collection.698DEBUG_ONLY(CodeBlobToOopClosure assert_code_is_non_scavengable(&assert_is_non_scavengable_closure, !CodeBlobToOopClosure::FixRelocations));699DEBUG_ONLY(CodeCache::asserted_non_scavengable_nmethods_do(&assert_code_is_non_scavengable));700}701702}703704void GenCollectedHeap::gen_process_roots(int level,705bool younger_gens_as_roots,706bool activate_scope,707ScanningOption so,708bool only_strong_roots,709OopsInGenClosure* not_older_gens,710OopsInGenClosure* older_gens,711CLDClosure* cld_closure) {712const bool is_adjust_phase = !only_strong_roots && !younger_gens_as_roots;713714bool is_moving_collection = false;715if (level == 0 || is_adjust_phase) {716// young collections are always moving717is_moving_collection = true;718}719720MarkingCodeBlobClosure mark_code_closure(not_older_gens, is_moving_collection);721OopsInGenClosure* weak_roots = only_strong_roots ? NULL : not_older_gens;722CLDClosure* weak_cld_closure = only_strong_roots ? NULL : cld_closure;723724process_roots(activate_scope, so,725not_older_gens, weak_roots,726cld_closure, weak_cld_closure,727&mark_code_closure);728729if (younger_gens_as_roots) {730if (!_process_strong_tasks->is_task_claimed(GCH_PS_younger_gens)) {731for (int i = 0; i < level; i++) {732not_older_gens->set_generation(_gens[i]);733_gens[i]->oop_iterate(not_older_gens);734}735not_older_gens->reset_generation();736}737}738// When collection is parallel, all threads get to cooperate to do739// older-gen scanning.740for (int i = level+1; i < _n_gens; i++) {741older_gens->set_generation(_gens[i]);742rem_set()->younger_refs_iterate(_gens[i], older_gens);743older_gens->reset_generation();744}745746_process_strong_tasks->all_tasks_completed();747}748749750void GenCollectedHeap::gen_process_weak_roots(OopClosure* root_closure) {751JNIHandles::weak_oops_do(root_closure);752JFR_ONLY(Jfr::weak_oops_do(root_closure));753for (int i = 0; i < _n_gens; i++) {754_gens[i]->ref_processor()->weak_oops_do(root_closure);755}756}757758#define GCH_SINCE_SAVE_MARKS_ITERATE_DEFN(OopClosureType, nv_suffix) \759void GenCollectedHeap:: \760oop_since_save_marks_iterate(int level, \761OopClosureType* cur, \762OopClosureType* older) { \763_gens[level]->oop_since_save_marks_iterate##nv_suffix(cur); \764for (int i = level+1; i < n_gens(); i++) { \765_gens[i]->oop_since_save_marks_iterate##nv_suffix(older); \766} \767}768769ALL_SINCE_SAVE_MARKS_CLOSURES(GCH_SINCE_SAVE_MARKS_ITERATE_DEFN)770771#undef GCH_SINCE_SAVE_MARKS_ITERATE_DEFN772773bool GenCollectedHeap::no_allocs_since_save_marks(int level) {774for (int i = level; i < _n_gens; i++) {775if (!_gens[i]->no_allocs_since_save_marks()) return false;776}777return true;778}779780bool GenCollectedHeap::supports_inline_contig_alloc() const {781return _gens[0]->supports_inline_contig_alloc();782}783784HeapWord** GenCollectedHeap::top_addr() const {785return _gens[0]->top_addr();786}787788HeapWord** GenCollectedHeap::end_addr() const {789return _gens[0]->end_addr();790}791792// public collection interfaces793794void GenCollectedHeap::collect(GCCause::Cause cause) {795if (should_do_concurrent_full_gc(cause)) {796#if INCLUDE_ALL_GCS797// mostly concurrent full collection798collect_mostly_concurrent(cause);799#else // INCLUDE_ALL_GCS800ShouldNotReachHere();801#endif // INCLUDE_ALL_GCS802} else if ((cause == GCCause::_wb_young_gc) ||803(cause == GCCause::_gc_locker)) {804// minor collection for WhiteBox or GCLocker.805// _gc_locker collections upgraded by GCLockerInvokesConcurrent806// are handled above and never discarded.807collect(cause, 0);808} else {809#ifdef ASSERT810if (cause == GCCause::_scavenge_alot) {811// minor collection only812collect(cause, 0);813} else {814// Stop-the-world full collection815collect(cause, n_gens() - 1);816}817#else818// Stop-the-world full collection819collect(cause, n_gens() - 1);820#endif821}822}823824void GenCollectedHeap::collect(GCCause::Cause cause, int max_level) {825// The caller doesn't have the Heap_lock826assert(!Heap_lock->owned_by_self(), "this thread should not own the Heap_lock");827MutexLocker ml(Heap_lock);828collect_locked(cause, max_level);829}830831void GenCollectedHeap::collect_locked(GCCause::Cause cause) {832// The caller has the Heap_lock833assert(Heap_lock->owned_by_self(), "this thread should own the Heap_lock");834collect_locked(cause, n_gens() - 1);835}836837// this is the private collection interface838// The Heap_lock is expected to be held on entry.839840void GenCollectedHeap::collect_locked(GCCause::Cause cause, int max_level) {841// Read the GC count while holding the Heap_lock842unsigned int gc_count_before = total_collections();843unsigned int full_gc_count_before = total_full_collections();844845if (GC_locker::should_discard(cause, gc_count_before)) {846return;847}848849{850MutexUnlocker mu(Heap_lock); // give up heap lock, execute gets it back851VM_GenCollectFull op(gc_count_before, full_gc_count_before,852cause, max_level);853VMThread::execute(&op);854}855}856857#if INCLUDE_ALL_GCS858bool GenCollectedHeap::create_cms_collector() {859860assert(((_gens[1]->kind() == Generation::ConcurrentMarkSweep) ||861(_gens[1]->kind() == Generation::ASConcurrentMarkSweep)),862"Unexpected generation kinds");863// Skip two header words in the block content verification864NOT_PRODUCT(_skip_header_HeapWords = CMSCollector::skip_header_HeapWords();)865CMSCollector* collector = new CMSCollector(866(ConcurrentMarkSweepGeneration*)_gens[1],867_rem_set->as_CardTableRS(),868(ConcurrentMarkSweepPolicy*) collector_policy());869870if (collector == NULL || !collector->completed_initialization()) {871if (collector) {872delete collector; // Be nice in embedded situation873}874vm_shutdown_during_initialization("Could not create CMS collector");875return false;876}877return true; // success878}879880void GenCollectedHeap::collect_mostly_concurrent(GCCause::Cause cause) {881assert(!Heap_lock->owned_by_self(), "Should not own Heap_lock");882883MutexLocker ml(Heap_lock);884// Read the GC counts while holding the Heap_lock885unsigned int full_gc_count_before = total_full_collections();886unsigned int gc_count_before = total_collections();887{888MutexUnlocker mu(Heap_lock);889VM_GenCollectFullConcurrent op(gc_count_before, full_gc_count_before, cause);890VMThread::execute(&op);891}892}893#endif // INCLUDE_ALL_GCS894895void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs) {896do_full_collection(clear_all_soft_refs, _n_gens - 1);897}898899void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs,900int max_level) {901902do_collection(true /* full */,903clear_all_soft_refs /* clear_all_soft_refs */,9040 /* size */,905false /* is_tlab */,906max_level /* max_level */);907// Hack XXX FIX ME !!!908// A scavenge may not have been attempted, or may have909// been attempted and failed, because the old gen was too full910if (gc_cause() == GCCause::_gc_locker && incremental_collection_failed()) {911if (PrintGCDetails) {912gclog_or_tty->print_cr("GC locker: Trying a full collection "913"because scavenge failed");914}915// This time allow the old gen to be collected as well916do_collection(true /* full */,917clear_all_soft_refs /* clear_all_soft_refs */,9180 /* size */,919false /* is_tlab */,920n_gens() - 1 /* max_level */);921}922}923924bool GenCollectedHeap::is_in_young(oop p) {925bool result = ((HeapWord*)p) < _gens[_n_gens - 1]->reserved().start();926assert(result == _gens[0]->is_in_reserved(p),927err_msg("incorrect test - result=%d, p=" PTR_FORMAT, result, p2i((void*)p)));928return result;929}930931// Returns "TRUE" iff "p" points into the committed areas of the heap.932bool GenCollectedHeap::is_in(const void* p) const {933#ifndef ASSERT934guarantee(VerifyBeforeGC ||935VerifyDuringGC ||936VerifyBeforeExit ||937VerifyDuringStartup ||938PrintAssembly ||939tty->count() != 0 || // already printing940VerifyAfterGC ||941VMError::fatal_error_in_progress(), "too expensive");942943#endif944// This might be sped up with a cache of the last generation that945// answered yes.946for (int i = 0; i < _n_gens; i++) {947if (_gens[i]->is_in(p)) return true;948}949// Otherwise...950return false;951}952953#ifdef ASSERT954// Don't implement this by using is_in_young(). This method is used955// in some cases to check that is_in_young() is correct.956bool GenCollectedHeap::is_in_partial_collection(const void* p) {957assert(is_in_reserved(p) || p == NULL,958"Does not work if address is non-null and outside of the heap");959return p < _gens[_n_gens - 2]->reserved().end() && p != NULL;960}961#endif962963void GenCollectedHeap::oop_iterate(ExtendedOopClosure* cl) {964for (int i = 0; i < _n_gens; i++) {965_gens[i]->oop_iterate(cl);966}967}968969void GenCollectedHeap::object_iterate(ObjectClosure* cl) {970for (int i = 0; i < _n_gens; i++) {971_gens[i]->object_iterate(cl);972}973}974975void GenCollectedHeap::safe_object_iterate(ObjectClosure* cl) {976for (int i = 0; i < _n_gens; i++) {977_gens[i]->safe_object_iterate(cl);978}979}980981Space* GenCollectedHeap::space_containing(const void* addr) const {982for (int i = 0; i < _n_gens; i++) {983Space* res = _gens[i]->space_containing(addr);984if (res != NULL) return res;985}986// Otherwise...987assert(false, "Could not find containing space");988return NULL;989}990991992HeapWord* GenCollectedHeap::block_start(const void* addr) const {993assert(is_in_reserved(addr), "block_start of address outside of heap");994for (int i = 0; i < _n_gens; i++) {995if (_gens[i]->is_in_reserved(addr)) {996assert(_gens[i]->is_in(addr),997"addr should be in allocated part of generation");998return _gens[i]->block_start(addr);999}1000}1001assert(false, "Some generation should contain the address");1002return NULL;1003}10041005size_t GenCollectedHeap::block_size(const HeapWord* addr) const {1006assert(is_in_reserved(addr), "block_size of address outside of heap");1007for (int i = 0; i < _n_gens; i++) {1008if (_gens[i]->is_in_reserved(addr)) {1009assert(_gens[i]->is_in(addr),1010"addr should be in allocated part of generation");1011return _gens[i]->block_size(addr);1012}1013}1014assert(false, "Some generation should contain the address");1015return 0;1016}10171018bool GenCollectedHeap::block_is_obj(const HeapWord* addr) const {1019assert(is_in_reserved(addr), "block_is_obj of address outside of heap");1020assert(block_start(addr) == addr, "addr must be a block start");1021for (int i = 0; i < _n_gens; i++) {1022if (_gens[i]->is_in_reserved(addr)) {1023return _gens[i]->block_is_obj(addr);1024}1025}1026assert(false, "Some generation should contain the address");1027return false;1028}10291030bool GenCollectedHeap::supports_tlab_allocation() const {1031for (int i = 0; i < _n_gens; i += 1) {1032if (_gens[i]->supports_tlab_allocation()) {1033return true;1034}1035}1036return false;1037}10381039size_t GenCollectedHeap::tlab_capacity(Thread* thr) const {1040size_t result = 0;1041for (int i = 0; i < _n_gens; i += 1) {1042if (_gens[i]->supports_tlab_allocation()) {1043result += _gens[i]->tlab_capacity();1044}1045}1046return result;1047}10481049size_t GenCollectedHeap::tlab_used(Thread* thr) const {1050size_t result = 0;1051for (int i = 0; i < _n_gens; i += 1) {1052if (_gens[i]->supports_tlab_allocation()) {1053result += _gens[i]->tlab_used();1054}1055}1056return result;1057}10581059size_t GenCollectedHeap::unsafe_max_tlab_alloc(Thread* thr) const {1060size_t result = 0;1061for (int i = 0; i < _n_gens; i += 1) {1062if (_gens[i]->supports_tlab_allocation()) {1063result += _gens[i]->unsafe_max_tlab_alloc();1064}1065}1066return result;1067}10681069HeapWord* GenCollectedHeap::allocate_new_tlab(size_t size) {1070bool gc_overhead_limit_was_exceeded;1071return collector_policy()->mem_allocate_work(size /* size */,1072true /* is_tlab */,1073&gc_overhead_limit_was_exceeded);1074}10751076// Requires "*prev_ptr" to be non-NULL. Deletes and a block of minimal size1077// from the list headed by "*prev_ptr".1078static ScratchBlock *removeSmallestScratch(ScratchBlock **prev_ptr) {1079bool first = true;1080size_t min_size = 0; // "first" makes this conceptually infinite.1081ScratchBlock **smallest_ptr, *smallest;1082ScratchBlock *cur = *prev_ptr;1083while (cur) {1084assert(*prev_ptr == cur, "just checking");1085if (first || cur->num_words < min_size) {1086smallest_ptr = prev_ptr;1087smallest = cur;1088min_size = smallest->num_words;1089first = false;1090}1091prev_ptr = &cur->next;1092cur = cur->next;1093}1094smallest = *smallest_ptr;1095*smallest_ptr = smallest->next;1096return smallest;1097}10981099// Sort the scratch block list headed by res into decreasing size order,1100// and set "res" to the result.1101static void sort_scratch_list(ScratchBlock*& list) {1102ScratchBlock* sorted = NULL;1103ScratchBlock* unsorted = list;1104while (unsorted) {1105ScratchBlock *smallest = removeSmallestScratch(&unsorted);1106smallest->next = sorted;1107sorted = smallest;1108}1109list = sorted;1110}11111112ScratchBlock* GenCollectedHeap::gather_scratch(Generation* requestor,1113size_t max_alloc_words) {1114ScratchBlock* res = NULL;1115for (int i = 0; i < _n_gens; i++) {1116_gens[i]->contribute_scratch(res, requestor, max_alloc_words);1117}1118sort_scratch_list(res);1119return res;1120}11211122void GenCollectedHeap::release_scratch() {1123for (int i = 0; i < _n_gens; i++) {1124_gens[i]->reset_scratch();1125}1126}11271128class GenPrepareForVerifyClosure: public GenCollectedHeap::GenClosure {1129void do_generation(Generation* gen) {1130gen->prepare_for_verify();1131}1132};11331134void GenCollectedHeap::prepare_for_verify() {1135ensure_parsability(false); // no need to retire TLABs1136GenPrepareForVerifyClosure blk;1137generation_iterate(&blk, false);1138}113911401141void GenCollectedHeap::generation_iterate(GenClosure* cl,1142bool old_to_young) {1143if (old_to_young) {1144for (int i = _n_gens-1; i >= 0; i--) {1145cl->do_generation(_gens[i]);1146}1147} else {1148for (int i = 0; i < _n_gens; i++) {1149cl->do_generation(_gens[i]);1150}1151}1152}11531154void GenCollectedHeap::space_iterate(SpaceClosure* cl) {1155for (int i = 0; i < _n_gens; i++) {1156_gens[i]->space_iterate(cl, true);1157}1158}11591160bool GenCollectedHeap::is_maximal_no_gc() const {1161for (int i = 0; i < _n_gens; i++) {1162if (!_gens[i]->is_maximal_no_gc()) {1163return false;1164}1165}1166return true;1167}11681169void GenCollectedHeap::save_marks() {1170for (int i = 0; i < _n_gens; i++) {1171_gens[i]->save_marks();1172}1173}11741175GenCollectedHeap* GenCollectedHeap::heap() {1176assert(_gch != NULL, "Uninitialized access to GenCollectedHeap::heap()");1177assert(_gch->kind() == CollectedHeap::GenCollectedHeap, "not a generational heap");1178return _gch;1179}118011811182void GenCollectedHeap::prepare_for_compaction() {1183guarantee(_n_gens == 2, "Wrong number of generations");1184Generation* old_gen = _gens[1];1185// Start by compacting into same gen.1186CompactPoint cp(old_gen);1187old_gen->prepare_for_compaction(&cp);1188Generation* young_gen = _gens[0];1189young_gen->prepare_for_compaction(&cp);1190}11911192GCStats* GenCollectedHeap::gc_stats(int level) const {1193return _gens[level]->gc_stats();1194}11951196void GenCollectedHeap::verify(bool silent, VerifyOption option /* ignored */) {1197for (int i = _n_gens-1; i >= 0; i--) {1198Generation* g = _gens[i];1199if (!silent) {1200gclog_or_tty->print("%s", g->name());1201gclog_or_tty->print(" ");1202}1203g->verify();1204}1205if (!silent) {1206gclog_or_tty->print("remset ");1207}1208rem_set()->verify();1209}12101211void GenCollectedHeap::print_on(outputStream* st) const {1212for (int i = 0; i < _n_gens; i++) {1213_gens[i]->print_on(st);1214}1215MetaspaceAux::print_on(st);1216}12171218void GenCollectedHeap::gc_threads_do(ThreadClosure* tc) const {1219if (workers() != NULL) {1220workers()->threads_do(tc);1221}1222#if INCLUDE_ALL_GCS1223if (UseConcMarkSweepGC) {1224ConcurrentMarkSweepThread::threads_do(tc);1225}1226#endif // INCLUDE_ALL_GCS1227}12281229void GenCollectedHeap::print_gc_threads_on(outputStream* st) const {1230#if INCLUDE_ALL_GCS1231if (UseParNewGC) {1232workers()->print_worker_threads_on(st);1233}1234if (UseConcMarkSweepGC) {1235ConcurrentMarkSweepThread::print_all_on(st);1236}1237#endif // INCLUDE_ALL_GCS1238}12391240void GenCollectedHeap::print_on_error(outputStream* st) const {1241this->CollectedHeap::print_on_error(st);12421243#if INCLUDE_ALL_GCS1244if (UseConcMarkSweepGC) {1245st->cr();1246CMSCollector::print_on_error(st);1247}1248#endif // INCLUDE_ALL_GCS1249}12501251void GenCollectedHeap::print_tracing_info() const {1252if (TraceGen0Time) {1253get_gen(0)->print_summary_info();1254}1255if (TraceGen1Time) {1256get_gen(1)->print_summary_info();1257}1258}12591260void GenCollectedHeap::print_heap_change(size_t prev_used) const {1261if (PrintGCDetails && Verbose) {1262gclog_or_tty->print(" " SIZE_FORMAT1263"->" SIZE_FORMAT1264"(" SIZE_FORMAT ")",1265prev_used, used(), capacity());1266} else {1267gclog_or_tty->print(" " SIZE_FORMAT "K"1268"->" SIZE_FORMAT "K"1269"(" SIZE_FORMAT "K)",1270prev_used / K, used() / K, capacity() / K);1271}1272}12731274class GenGCPrologueClosure: public GenCollectedHeap::GenClosure {1275private:1276bool _full;1277public:1278void do_generation(Generation* gen) {1279gen->gc_prologue(_full);1280}1281GenGCPrologueClosure(bool full) : _full(full) {};1282};12831284void GenCollectedHeap::gc_prologue(bool full) {1285assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer");12861287always_do_update_barrier = false;1288// Fill TLAB's and such1289CollectedHeap::accumulate_statistics_all_tlabs();1290ensure_parsability(true); // retire TLABs12911292// Walk generations1293GenGCPrologueClosure blk(full);1294generation_iterate(&blk, false); // not old-to-young.1295};12961297class GenGCEpilogueClosure: public GenCollectedHeap::GenClosure {1298private:1299bool _full;1300public:1301void do_generation(Generation* gen) {1302gen->gc_epilogue(_full);1303}1304GenGCEpilogueClosure(bool full) : _full(full) {};1305};13061307void GenCollectedHeap::gc_epilogue(bool full) {1308#ifdef COMPILER21309assert(DerivedPointerTable::is_empty(), "derived pointer present");1310size_t actual_gap = pointer_delta((HeapWord*) (max_uintx-3), *(end_addr()));1311guarantee(actual_gap > (size_t)FastAllocateSizeLimit, "inline allocation wraps");1312#endif /* COMPILER2 */13131314resize_all_tlabs();13151316GenGCEpilogueClosure blk(full);1317generation_iterate(&blk, false); // not old-to-young.13181319if (!CleanChunkPoolAsync) {1320Chunk::clean_chunk_pool();1321}13221323MetaspaceCounters::update_performance_counters();1324CompressedClassSpaceCounters::update_performance_counters();13251326always_do_update_barrier = UseConcMarkSweepGC;1327};13281329#ifndef PRODUCT1330class GenGCSaveTopsBeforeGCClosure: public GenCollectedHeap::GenClosure {1331private:1332public:1333void do_generation(Generation* gen) {1334gen->record_spaces_top();1335}1336};13371338void GenCollectedHeap::record_gen_tops_before_GC() {1339if (ZapUnusedHeapArea) {1340GenGCSaveTopsBeforeGCClosure blk;1341generation_iterate(&blk, false); // not old-to-young.1342}1343}1344#endif // not PRODUCT13451346class GenEnsureParsabilityClosure: public GenCollectedHeap::GenClosure {1347public:1348void do_generation(Generation* gen) {1349gen->ensure_parsability();1350}1351};13521353void GenCollectedHeap::ensure_parsability(bool retire_tlabs) {1354CollectedHeap::ensure_parsability(retire_tlabs);1355GenEnsureParsabilityClosure ep_cl;1356generation_iterate(&ep_cl, false);1357}13581359oop GenCollectedHeap::handle_failed_promotion(Generation* old_gen,1360oop obj,1361size_t obj_size) {1362guarantee(old_gen->level() == 1, "We only get here with an old generation");1363assert(obj_size == (size_t)obj->size(), "bad obj_size passed in");1364HeapWord* result = NULL;13651366result = old_gen->expand_and_allocate(obj_size, false);13671368if (result != NULL) {1369Copy::aligned_disjoint_words((HeapWord*)obj, result, obj_size);1370}1371return oop(result);1372}13731374class GenTimeOfLastGCClosure: public GenCollectedHeap::GenClosure {1375jlong _time; // in ms1376jlong _now; // in ms13771378public:1379GenTimeOfLastGCClosure(jlong now) : _time(now), _now(now) { }13801381jlong time() { return _time; }13821383void do_generation(Generation* gen) {1384_time = MIN2(_time, gen->time_of_last_gc(_now));1385}1386};13871388jlong GenCollectedHeap::millis_since_last_gc() {1389// We need a monotonically non-deccreasing time in ms but1390// os::javaTimeMillis() does not guarantee monotonicity.1391jlong now = os::javaTimeNanos() / NANOSECS_PER_MILLISEC;1392GenTimeOfLastGCClosure tolgc_cl(now);1393// iterate over generations getting the oldest1394// time that a generation was collected1395generation_iterate(&tolgc_cl, false);13961397// javaTimeNanos() is guaranteed to be monotonically non-decreasing1398// provided the underlying platform provides such a time source1399// (and it is bug free). So we still have to guard against getting1400// back a time later than 'now'.1401jlong retVal = now - tolgc_cl.time();1402if (retVal < 0) {1403NOT_PRODUCT(warning("time warp: " INT64_FORMAT, (int64_t) retVal);)1404return 0;1405}1406return retVal;1407}140814091410