Path: blob/master/src/hotspot/share/memory/metaspace.cpp
64440 views
/*1* Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved.2* Copyright (c) 2017, 2021 SAP SE. All rights reserved.3* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.4*5* This code is free software; you can redistribute it and/or modify it6* under the terms of the GNU General Public License version 2 only, as7* published by the Free Software Foundation.8*9* This code is distributed in the hope that it will be useful, but WITHOUT10* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or11* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License12* version 2 for more details (a copy is included in the LICENSE file that13* accompanied this code).14*15* You should have received a copy of the GNU General Public License version16* 2 along with this work; if not, write to the Free Software Foundation,17* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.18*19* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA20* or visit www.oracle.com if you need additional information or have any21* questions.22*23*/2425#include "precompiled.hpp"26#include "cds/metaspaceShared.hpp"27#include "classfile/classLoaderData.hpp"28#include "gc/shared/collectedHeap.hpp"29#include "logging/log.hpp"30#include "logging/logStream.hpp"31#include "memory/classLoaderMetaspace.hpp"32#include "memory/metaspace.hpp"33#include "memory/metaspace/chunkHeaderPool.hpp"34#include "memory/metaspace/chunkManager.hpp"35#include "memory/metaspace/commitLimiter.hpp"36#include "memory/metaspace/internalStats.hpp"37#include "memory/metaspace/metaspaceCommon.hpp"38#include "memory/metaspace/metaspaceContext.hpp"39#include "memory/metaspace/metaspaceReporter.hpp"40#include "memory/metaspace/metaspaceSettings.hpp"41#include "memory/metaspace/runningCounters.hpp"42#include "memory/metaspace/virtualSpaceList.hpp"43#include "memory/metaspaceTracer.hpp"44#include "memory/metaspaceStats.hpp"45#include "memory/metaspaceUtils.hpp"46#include "memory/resourceArea.hpp"47#include "memory/universe.hpp"48#include "oops/compressedOops.hpp"49#include "prims/jvmtiExport.hpp"50#include "runtime/atomic.hpp"51#include "runtime/globals_extension.hpp"52#include "runtime/init.hpp"53#include "runtime/java.hpp"54#include "services/memTracker.hpp"55#include "utilities/copy.hpp"56#include "utilities/debug.hpp"57#include "utilities/formatBuffer.hpp"58#include "utilities/globalDefinitions.hpp"5960using metaspace::ChunkManager;61using metaspace::CommitLimiter;62using metaspace::MetaspaceContext;63using metaspace::MetaspaceReporter;64using metaspace::RunningCounters;65using metaspace::VirtualSpaceList;6667size_t MetaspaceUtils::used_words() {68return RunningCounters::used_words();69}7071size_t MetaspaceUtils::used_words(Metaspace::MetadataType mdtype) {72return mdtype == Metaspace::ClassType ? RunningCounters::used_words_class() : RunningCounters::used_words_nonclass();73}7475size_t MetaspaceUtils::reserved_words() {76return RunningCounters::reserved_words();77}7879size_t MetaspaceUtils::reserved_words(Metaspace::MetadataType mdtype) {80return mdtype == Metaspace::ClassType ? RunningCounters::reserved_words_class() : RunningCounters::reserved_words_nonclass();81}8283size_t MetaspaceUtils::committed_words() {84return RunningCounters::committed_words();85}8687size_t MetaspaceUtils::committed_words(Metaspace::MetadataType mdtype) {88return mdtype == Metaspace::ClassType ? RunningCounters::committed_words_class() : RunningCounters::committed_words_nonclass();89}9091// Helper for get_statistics()92static void get_values_for(Metaspace::MetadataType mdtype, size_t* reserved, size_t* committed, size_t* used) {93#define w2b(x) (x * sizeof(MetaWord))94if (mdtype == Metaspace::ClassType) {95*reserved = w2b(RunningCounters::reserved_words_class());96*committed = w2b(RunningCounters::committed_words_class());97*used = w2b(RunningCounters::used_words_class());98} else {99*reserved = w2b(RunningCounters::reserved_words_nonclass());100*committed = w2b(RunningCounters::committed_words_nonclass());101*used = w2b(RunningCounters::used_words_nonclass());102}103#undef w2b104}105106// Retrieve all statistics in one go; make sure the values are consistent.107MetaspaceStats MetaspaceUtils::get_statistics(Metaspace::MetadataType mdtype) {108109// Consistency:110// This function reads three values (reserved, committed, used) from different counters. These counters111// may (very rarely) be out of sync. This has been a source for intermittent test errors in the past112// (see e.g. JDK-8237872, JDK-8151460).113// - reserved and committed counter are updated under protection of Metaspace_lock; an inconsistency114// between them can be the result of a dirty read.115// - used is an atomic counter updated outside any lock range; there is no way to guarantee116// a clean read wrt the other two values.117// Reading these values under lock protection would would only help for the first case. Therefore118// we don't bother and just re-read several times, then give up and correct the values.119120size_t r = 0, c = 0, u = 0; // Note: byte values.121get_values_for(mdtype, &r, &c, &u);122int retries = 10;123// If the first retrieval resulted in inconsistent values, retry a bit...124while ((r < c || c < u) && --retries >= 0) {125get_values_for(mdtype, &r, &c, &u);126}127if (c < u || r < c) { // still inconsistent.128// ... but not endlessly. If we don't get consistent values, correct them on the fly.129// The logic here is that we trust the used counter - its an atomic counter and whatever we see130// must have been the truth once - and from that we reconstruct a likely set of committed/reserved131// values.132metaspace::InternalStats::inc_num_inconsistent_stats();133if (c < u) {134c = align_up(u, Metaspace::commit_alignment());135}136if (r < c) {137r = align_up(c, Metaspace::reserve_alignment());138}139}140return MetaspaceStats(r, c, u);141}142143MetaspaceCombinedStats MetaspaceUtils::get_combined_statistics() {144return MetaspaceCombinedStats(get_statistics(Metaspace::ClassType), get_statistics(Metaspace::NonClassType));145}146147void MetaspaceUtils::print_metaspace_change(const MetaspaceCombinedStats& pre_meta_values) {148// Get values now:149const MetaspaceCombinedStats meta_values = get_combined_statistics();150151// We print used and committed since these are the most useful at-a-glance vitals for Metaspace:152// - used tells you how much memory is actually used for metadata153// - committed tells you how much memory is committed for the purpose of metadata154// The difference between those two would be waste, which can have various forms (freelists,155// unused parts of committed chunks etc)156//157// Left out is reserved, since this is not as exciting as the first two values: for class space,158// it is a constant (to uninformed users, often confusingly large). For non-class space, it would159// be interesting since free chunks can be uncommitted, but for now it is left out.160161if (Metaspace::using_class_space()) {162log_info(gc, metaspace)(HEAP_CHANGE_FORMAT" "163HEAP_CHANGE_FORMAT" "164HEAP_CHANGE_FORMAT,165HEAP_CHANGE_FORMAT_ARGS("Metaspace",166pre_meta_values.used(),167pre_meta_values.committed(),168meta_values.used(),169meta_values.committed()),170HEAP_CHANGE_FORMAT_ARGS("NonClass",171pre_meta_values.non_class_used(),172pre_meta_values.non_class_committed(),173meta_values.non_class_used(),174meta_values.non_class_committed()),175HEAP_CHANGE_FORMAT_ARGS("Class",176pre_meta_values.class_used(),177pre_meta_values.class_committed(),178meta_values.class_used(),179meta_values.class_committed()));180} else {181log_info(gc, metaspace)(HEAP_CHANGE_FORMAT,182HEAP_CHANGE_FORMAT_ARGS("Metaspace",183pre_meta_values.used(),184pre_meta_values.committed(),185meta_values.used(),186meta_values.committed()));187}188}189190// This will print out a basic metaspace usage report but191// unlike print_report() is guaranteed not to lock or to walk the CLDG.192void MetaspaceUtils::print_basic_report(outputStream* out, size_t scale) {193MetaspaceReporter::print_basic_report(out, scale);194}195196// Prints a report about the current metaspace state.197// Optional parts can be enabled via flags.198// Function will walk the CLDG and will lock the expand lock; if that is not199// convenient, use print_basic_report() instead.200void MetaspaceUtils::print_report(outputStream* out, size_t scale) {201const int flags =202(int)MetaspaceReporter::Option::ShowLoaders |203(int)MetaspaceReporter::Option::BreakDownByChunkType |204(int)MetaspaceReporter::Option::ShowClasses;205MetaspaceReporter::print_report(out, scale, flags);206}207208void MetaspaceUtils::print_on(outputStream* out) {209210// Used from all GCs. It first prints out totals, then, separately, the class space portion.211MetaspaceCombinedStats stats = get_combined_statistics();212out->print_cr(" Metaspace "213"used " SIZE_FORMAT "K, "214"committed " SIZE_FORMAT "K, "215"reserved " SIZE_FORMAT "K",216stats.used()/K,217stats.committed()/K,218stats.reserved()/K);219220if (Metaspace::using_class_space()) {221out->print_cr(" class space "222"used " SIZE_FORMAT "K, "223"committed " SIZE_FORMAT "K, "224"reserved " SIZE_FORMAT "K",225stats.class_space_stats().used()/K,226stats.class_space_stats().committed()/K,227stats.class_space_stats().reserved()/K);228}229}230231#ifdef ASSERT232void MetaspaceUtils::verify() {233if (Metaspace::initialized()) {234235// Verify non-class chunkmanager...236ChunkManager* cm = ChunkManager::chunkmanager_nonclass();237cm->verify();238239// ... and space list.240VirtualSpaceList* vsl = VirtualSpaceList::vslist_nonclass();241vsl->verify();242243if (Metaspace::using_class_space()) {244// If we use compressed class pointers, verify class chunkmanager...245cm = ChunkManager::chunkmanager_class();246cm->verify();247248// ... and class spacelist.249vsl = VirtualSpaceList::vslist_class();250vsl->verify();251}252253}254}255#endif256257////////////////////////////////7258// MetaspaceGC methods259260volatile size_t MetaspaceGC::_capacity_until_GC = 0;261uint MetaspaceGC::_shrink_factor = 0;262263// VM_CollectForMetadataAllocation is the vm operation used to GC.264// Within the VM operation after the GC the attempt to allocate the metadata265// should succeed. If the GC did not free enough space for the metaspace266// allocation, the HWM is increased so that another virtualspace will be267// allocated for the metadata. With perm gen the increase in the perm268// gen had bounds, MinMetaspaceExpansion and MaxMetaspaceExpansion. The269// metaspace policy uses those as the small and large steps for the HWM.270//271// After the GC the compute_new_size() for MetaspaceGC is called to272// resize the capacity of the metaspaces. The current implementation273// is based on the flags MinMetaspaceFreeRatio and MaxMetaspaceFreeRatio used274// to resize the Java heap by some GC's. New flags can be implemented275// if really needed. MinMetaspaceFreeRatio is used to calculate how much276// free space is desirable in the metaspace capacity to decide how much277// to increase the HWM. MaxMetaspaceFreeRatio is used to decide how much278// free space is desirable in the metaspace capacity before decreasing279// the HWM.280281// Calculate the amount to increase the high water mark (HWM).282// Increase by a minimum amount (MinMetaspaceExpansion) so that283// another expansion is not requested too soon. If that is not284// enough to satisfy the allocation, increase by MaxMetaspaceExpansion.285// If that is still not enough, expand by the size of the allocation286// plus some.287size_t MetaspaceGC::delta_capacity_until_GC(size_t bytes) {288size_t min_delta = MinMetaspaceExpansion;289size_t max_delta = MaxMetaspaceExpansion;290size_t delta = align_up(bytes, Metaspace::commit_alignment());291292if (delta <= min_delta) {293delta = min_delta;294} else if (delta <= max_delta) {295// Don't want to hit the high water mark on the next296// allocation so make the delta greater than just enough297// for this allocation.298delta = max_delta;299} else {300// This allocation is large but the next ones are probably not301// so increase by the minimum.302delta = delta + min_delta;303}304305assert_is_aligned(delta, Metaspace::commit_alignment());306307return delta;308}309310size_t MetaspaceGC::capacity_until_GC() {311size_t value = Atomic::load_acquire(&_capacity_until_GC);312assert(value >= MetaspaceSize, "Not initialized properly?");313return value;314}315316// Try to increase the _capacity_until_GC limit counter by v bytes.317// Returns true if it succeeded. It may fail if either another thread318// concurrently increased the limit or the new limit would be larger319// than MaxMetaspaceSize.320// On success, optionally returns new and old metaspace capacity in321// new_cap_until_GC and old_cap_until_GC respectively.322// On error, optionally sets can_retry to indicate whether if there is323// actually enough space remaining to satisfy the request.324bool MetaspaceGC::inc_capacity_until_GC(size_t v, size_t* new_cap_until_GC, size_t* old_cap_until_GC, bool* can_retry) {325assert_is_aligned(v, Metaspace::commit_alignment());326327size_t old_capacity_until_GC = _capacity_until_GC;328size_t new_value = old_capacity_until_GC + v;329330if (new_value < old_capacity_until_GC) {331// The addition wrapped around, set new_value to aligned max value.332new_value = align_down(max_uintx, Metaspace::reserve_alignment());333}334335if (new_value > MaxMetaspaceSize) {336if (can_retry != NULL) {337*can_retry = false;338}339return false;340}341342if (can_retry != NULL) {343*can_retry = true;344}345size_t prev_value = Atomic::cmpxchg(&_capacity_until_GC, old_capacity_until_GC, new_value);346347if (old_capacity_until_GC != prev_value) {348return false;349}350351if (new_cap_until_GC != NULL) {352*new_cap_until_GC = new_value;353}354if (old_cap_until_GC != NULL) {355*old_cap_until_GC = old_capacity_until_GC;356}357return true;358}359360size_t MetaspaceGC::dec_capacity_until_GC(size_t v) {361assert_is_aligned(v, Metaspace::commit_alignment());362363return Atomic::sub(&_capacity_until_GC, v);364}365366void MetaspaceGC::initialize() {367// Set the high-water mark to MaxMetapaceSize during VM initializaton since368// we can't do a GC during initialization.369_capacity_until_GC = MaxMetaspaceSize;370}371372void MetaspaceGC::post_initialize() {373// Reset the high-water mark once the VM initialization is done.374_capacity_until_GC = MAX2(MetaspaceUtils::committed_bytes(), MetaspaceSize);375}376377bool MetaspaceGC::can_expand(size_t word_size, bool is_class) {378// Check if the compressed class space is full.379if (is_class && Metaspace::using_class_space()) {380size_t class_committed = MetaspaceUtils::committed_bytes(Metaspace::ClassType);381if (class_committed + word_size * BytesPerWord > CompressedClassSpaceSize) {382log_trace(gc, metaspace, freelist)("Cannot expand %s metaspace by " SIZE_FORMAT " words (CompressedClassSpaceSize = " SIZE_FORMAT " words)",383(is_class ? "class" : "non-class"), word_size, CompressedClassSpaceSize / sizeof(MetaWord));384return false;385}386}387388// Check if the user has imposed a limit on the metaspace memory.389size_t committed_bytes = MetaspaceUtils::committed_bytes();390if (committed_bytes + word_size * BytesPerWord > MaxMetaspaceSize) {391log_trace(gc, metaspace, freelist)("Cannot expand %s metaspace by " SIZE_FORMAT " words (MaxMetaspaceSize = " SIZE_FORMAT " words)",392(is_class ? "class" : "non-class"), word_size, MaxMetaspaceSize / sizeof(MetaWord));393return false;394}395396return true;397}398399size_t MetaspaceGC::allowed_expansion() {400size_t committed_bytes = MetaspaceUtils::committed_bytes();401size_t capacity_until_gc = capacity_until_GC();402403assert(capacity_until_gc >= committed_bytes,404"capacity_until_gc: " SIZE_FORMAT " < committed_bytes: " SIZE_FORMAT,405capacity_until_gc, committed_bytes);406407size_t left_until_max = MaxMetaspaceSize - committed_bytes;408size_t left_until_GC = capacity_until_gc - committed_bytes;409size_t left_to_commit = MIN2(left_until_GC, left_until_max);410log_trace(gc, metaspace, freelist)("allowed expansion words: " SIZE_FORMAT411" (left_until_max: " SIZE_FORMAT ", left_until_GC: " SIZE_FORMAT ".",412left_to_commit / BytesPerWord, left_until_max / BytesPerWord, left_until_GC / BytesPerWord);413414return left_to_commit / BytesPerWord;415}416417void MetaspaceGC::compute_new_size() {418assert(_shrink_factor <= 100, "invalid shrink factor");419uint current_shrink_factor = _shrink_factor;420_shrink_factor = 0;421422// Using committed_bytes() for used_after_gc is an overestimation, since the423// chunk free lists are included in committed_bytes() and the memory in an424// un-fragmented chunk free list is available for future allocations.425// However, if the chunk free lists becomes fragmented, then the memory may426// not be available for future allocations and the memory is therefore "in use".427// Including the chunk free lists in the definition of "in use" is therefore428// necessary. Not including the chunk free lists can cause capacity_until_GC to429// shrink below committed_bytes() and this has caused serious bugs in the past.430const size_t used_after_gc = MetaspaceUtils::committed_bytes();431const size_t capacity_until_GC = MetaspaceGC::capacity_until_GC();432433const double minimum_free_percentage = MinMetaspaceFreeRatio / 100.0;434const double maximum_used_percentage = 1.0 - minimum_free_percentage;435436const double min_tmp = used_after_gc / maximum_used_percentage;437size_t minimum_desired_capacity =438(size_t)MIN2(min_tmp, double(MaxMetaspaceSize));439// Don't shrink less than the initial generation size440minimum_desired_capacity = MAX2(minimum_desired_capacity,441MetaspaceSize);442443log_trace(gc, metaspace)("MetaspaceGC::compute_new_size: ");444log_trace(gc, metaspace)(" minimum_free_percentage: %6.2f maximum_used_percentage: %6.2f",445minimum_free_percentage, maximum_used_percentage);446log_trace(gc, metaspace)(" used_after_gc : %6.1fKB", used_after_gc / (double) K);447448size_t shrink_bytes = 0;449if (capacity_until_GC < minimum_desired_capacity) {450// If we have less capacity below the metaspace HWM, then451// increment the HWM.452size_t expand_bytes = minimum_desired_capacity - capacity_until_GC;453expand_bytes = align_up(expand_bytes, Metaspace::commit_alignment());454// Don't expand unless it's significant455if (expand_bytes >= MinMetaspaceExpansion) {456size_t new_capacity_until_GC = 0;457bool succeeded = MetaspaceGC::inc_capacity_until_GC(expand_bytes, &new_capacity_until_GC);458assert(succeeded, "Should always succesfully increment HWM when at safepoint");459460Metaspace::tracer()->report_gc_threshold(capacity_until_GC,461new_capacity_until_GC,462MetaspaceGCThresholdUpdater::ComputeNewSize);463log_trace(gc, metaspace)(" expanding: minimum_desired_capacity: %6.1fKB expand_bytes: %6.1fKB MinMetaspaceExpansion: %6.1fKB new metaspace HWM: %6.1fKB",464minimum_desired_capacity / (double) K,465expand_bytes / (double) K,466MinMetaspaceExpansion / (double) K,467new_capacity_until_GC / (double) K);468}469return;470}471472// No expansion, now see if we want to shrink473// We would never want to shrink more than this474assert(capacity_until_GC >= minimum_desired_capacity,475SIZE_FORMAT " >= " SIZE_FORMAT,476capacity_until_GC, minimum_desired_capacity);477size_t max_shrink_bytes = capacity_until_GC - minimum_desired_capacity;478479// Should shrinking be considered?480if (MaxMetaspaceFreeRatio < 100) {481const double maximum_free_percentage = MaxMetaspaceFreeRatio / 100.0;482const double minimum_used_percentage = 1.0 - maximum_free_percentage;483const double max_tmp = used_after_gc / minimum_used_percentage;484size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(MaxMetaspaceSize));485maximum_desired_capacity = MAX2(maximum_desired_capacity,486MetaspaceSize);487log_trace(gc, metaspace)(" maximum_free_percentage: %6.2f minimum_used_percentage: %6.2f",488maximum_free_percentage, minimum_used_percentage);489log_trace(gc, metaspace)(" minimum_desired_capacity: %6.1fKB maximum_desired_capacity: %6.1fKB",490minimum_desired_capacity / (double) K, maximum_desired_capacity / (double) K);491492assert(minimum_desired_capacity <= maximum_desired_capacity,493"sanity check");494495if (capacity_until_GC > maximum_desired_capacity) {496// Capacity too large, compute shrinking size497shrink_bytes = capacity_until_GC - maximum_desired_capacity;498// We don't want shrink all the way back to initSize if people call499// System.gc(), because some programs do that between "phases" and then500// we'd just have to grow the heap up again for the next phase. So we501// damp the shrinking: 0% on the first call, 10% on the second call, 40%502// on the third call, and 100% by the fourth call. But if we recompute503// size without shrinking, it goes back to 0%.504shrink_bytes = shrink_bytes / 100 * current_shrink_factor;505506shrink_bytes = align_down(shrink_bytes, Metaspace::commit_alignment());507508assert(shrink_bytes <= max_shrink_bytes,509"invalid shrink size " SIZE_FORMAT " not <= " SIZE_FORMAT,510shrink_bytes, max_shrink_bytes);511if (current_shrink_factor == 0) {512_shrink_factor = 10;513} else {514_shrink_factor = MIN2(current_shrink_factor * 4, (uint) 100);515}516log_trace(gc, metaspace)(" shrinking: initThreshold: %.1fK maximum_desired_capacity: %.1fK",517MetaspaceSize / (double) K, maximum_desired_capacity / (double) K);518log_trace(gc, metaspace)(" shrink_bytes: %.1fK current_shrink_factor: %d new shrink factor: %d MinMetaspaceExpansion: %.1fK",519shrink_bytes / (double) K, current_shrink_factor, _shrink_factor, MinMetaspaceExpansion / (double) K);520}521}522523// Don't shrink unless it's significant524if (shrink_bytes >= MinMetaspaceExpansion &&525((capacity_until_GC - shrink_bytes) >= MetaspaceSize)) {526size_t new_capacity_until_GC = MetaspaceGC::dec_capacity_until_GC(shrink_bytes);527Metaspace::tracer()->report_gc_threshold(capacity_until_GC,528new_capacity_until_GC,529MetaspaceGCThresholdUpdater::ComputeNewSize);530}531}532533////// Metaspace methods /////534535const MetaspaceTracer* Metaspace::_tracer = NULL;536537bool Metaspace::initialized() {538return metaspace::MetaspaceContext::context_nonclass() != NULL539LP64_ONLY(&& (using_class_space() ? Metaspace::class_space_is_initialized() : true));540}541542#ifdef _LP64543544void Metaspace::print_compressed_class_space(outputStream* st) {545if (VirtualSpaceList::vslist_class() != NULL) {546MetaWord* base = VirtualSpaceList::vslist_class()->base_of_first_node();547size_t size = VirtualSpaceList::vslist_class()->word_size_of_first_node();548MetaWord* top = base + size;549st->print("Compressed class space mapped at: " PTR_FORMAT "-" PTR_FORMAT ", reserved size: " SIZE_FORMAT,550p2i(base), p2i(top), (top - base) * BytesPerWord);551st->cr();552}553}554555// Given a prereserved space, use that to set up the compressed class space list.556void Metaspace::initialize_class_space(ReservedSpace rs) {557assert(rs.size() >= CompressedClassSpaceSize,558SIZE_FORMAT " != " SIZE_FORMAT, rs.size(), CompressedClassSpaceSize);559assert(using_class_space(), "Must be using class space");560561assert(rs.size() == CompressedClassSpaceSize, SIZE_FORMAT " != " SIZE_FORMAT,562rs.size(), CompressedClassSpaceSize);563assert(is_aligned(rs.base(), Metaspace::reserve_alignment()) &&564is_aligned(rs.size(), Metaspace::reserve_alignment()),565"wrong alignment");566567MetaspaceContext::initialize_class_space_context(rs);568569// This does currently not work because rs may be the result of a split570// operation and NMT seems not to be able to handle splits.571// Will be fixed with JDK-8243535.572// MemTracker::record_virtual_memory_type((address)rs.base(), mtClass);573574}575576// Returns true if class space has been setup (initialize_class_space).577bool Metaspace::class_space_is_initialized() {578return MetaspaceContext::context_class() != NULL;579}580581// Reserve a range of memory at an address suitable for en/decoding narrow582// Klass pointers (see: CompressedClassPointers::is_valid_base()).583// The returned address shall both be suitable as a compressed class pointers584// base, and aligned to Metaspace::reserve_alignment (which is equal to or a585// multiple of allocation granularity).586// On error, returns an unreserved space.587ReservedSpace Metaspace::reserve_address_space_for_compressed_classes(size_t size) {588589#if defined(AARCH64) || defined(PPC64)590const size_t alignment = Metaspace::reserve_alignment();591592// AArch64: Try to align metaspace so that we can decode a compressed593// klass with a single MOVK instruction. We can do this iff the594// compressed class base is a multiple of 4G.595// Additionally, above 32G, ensure the lower LogKlassAlignmentInBytes bits596// of the upper 32-bits of the address are zero so we can handle a shift597// when decoding.598599// PPC64: smaller heaps up to 2g will be mapped just below 4g. Then the600// attempt to place the compressed class space just after the heap fails on601// Linux 4.1.42 and higher because the launcher is loaded at 4g602// (ELF_ET_DYN_BASE). In that case we reach here and search the address space603// below 32g to get a zerobased CCS. For simplicity we reuse the search604// strategy for AARCH64.605606static const struct {607address from;608address to;609size_t increment;610} search_ranges[] = {611{ (address)(4*G), (address)(32*G), 4*G, },612{ (address)(32*G), (address)(1024*G), (4 << LogKlassAlignmentInBytes) * G },613{ NULL, NULL, 0 }614};615616for (int i = 0; search_ranges[i].from != NULL; i ++) {617address a = search_ranges[i].from;618assert(CompressedKlassPointers::is_valid_base(a), "Sanity");619while (a < search_ranges[i].to) {620ReservedSpace rs(size, Metaspace::reserve_alignment(),621os::vm_page_size(), (char*)a);622if (rs.is_reserved()) {623assert(a == (address)rs.base(), "Sanity");624return rs;625}626a += search_ranges[i].increment;627}628}629#endif // defined(AARCH64) || defined(PPC64)630631#ifdef AARCH64632// Note: on AARCH64, if the code above does not find any good placement, we633// have no recourse. We return an empty space and the VM will exit.634return ReservedSpace();635#else636// Default implementation: Just reserve anywhere.637return ReservedSpace(size, Metaspace::reserve_alignment(), os::vm_page_size(), (char*)NULL);638#endif // AARCH64639}640641#endif // _LP64642643size_t Metaspace::reserve_alignment_words() {644return metaspace::Settings::virtual_space_node_reserve_alignment_words();645}646647size_t Metaspace::commit_alignment_words() {648return metaspace::Settings::commit_granule_words();649}650651void Metaspace::ergo_initialize() {652653// Must happen before using any setting from Settings::---654metaspace::Settings::ergo_initialize();655656// MaxMetaspaceSize and CompressedClassSpaceSize:657//658// MaxMetaspaceSize is the maximum size, in bytes, of memory we are allowed659// to commit for the Metaspace.660// It is just a number; a limit we compare against before committing. It661// does not have to be aligned to anything.662// It gets used as compare value before attempting to increase the metaspace663// commit charge. It defaults to max_uintx (unlimited).664//665// CompressedClassSpaceSize is the size, in bytes, of the address range we666// pre-reserve for the compressed class space (if we use class space).667// This size has to be aligned to the metaspace reserve alignment (to the668// size of a root chunk). It gets aligned up from whatever value the caller669// gave us to the next multiple of root chunk size.670//671// Note: Strictly speaking MaxMetaspaceSize and CompressedClassSpaceSize have672// very little to do with each other. The notion often encountered:673// MaxMetaspaceSize = CompressedClassSpaceSize + <non-class metadata size>674// is subtly wrong: MaxMetaspaceSize can besmaller than CompressedClassSpaceSize,675// in which case we just would not be able to fully commit the class space range.676//677// We still adjust CompressedClassSpaceSize to reasonable limits, mainly to678// save on reserved space, and to make ergnonomics less confusing.679680MaxMetaspaceSize = MAX2(MaxMetaspaceSize, commit_alignment());681682if (UseCompressedClassPointers) {683// Let CCS size not be larger than 80% of MaxMetaspaceSize. Note that is684// grossly over-dimensioned for most usage scenarios; typical ratio of685// class space : non class space usage is about 1:6. With many small classes,686// it can get as low as 1:2. It is not a big deal though since ccs is only687// reserved and will be committed on demand only.688size_t max_ccs_size = MaxMetaspaceSize * 0.8;689size_t adjusted_ccs_size = MIN2(CompressedClassSpaceSize, max_ccs_size);690691// CCS must be aligned to root chunk size, and be at least the size of one692// root chunk.693adjusted_ccs_size = align_up(adjusted_ccs_size, reserve_alignment());694adjusted_ccs_size = MAX2(adjusted_ccs_size, reserve_alignment());695696// Note: re-adjusting may have us left with a CompressedClassSpaceSize697// larger than MaxMetaspaceSize for very small values of MaxMetaspaceSize.698// Lets just live with that, its not a big deal.699700if (adjusted_ccs_size != CompressedClassSpaceSize) {701FLAG_SET_ERGO(CompressedClassSpaceSize, adjusted_ccs_size);702log_info(metaspace)("Setting CompressedClassSpaceSize to " SIZE_FORMAT ".",703CompressedClassSpaceSize);704}705}706707// Set MetaspaceSize, MinMetaspaceExpansion and MaxMetaspaceExpansion708if (MetaspaceSize > MaxMetaspaceSize) {709MetaspaceSize = MaxMetaspaceSize;710}711712MetaspaceSize = align_down_bounded(MetaspaceSize, commit_alignment());713714assert(MetaspaceSize <= MaxMetaspaceSize, "MetaspaceSize should be limited by MaxMetaspaceSize");715716MinMetaspaceExpansion = align_down_bounded(MinMetaspaceExpansion, commit_alignment());717MaxMetaspaceExpansion = align_down_bounded(MaxMetaspaceExpansion, commit_alignment());718719}720721void Metaspace::global_initialize() {722MetaspaceGC::initialize(); // <- since we do not prealloc init chunks anymore is this still needed?723724metaspace::ChunkHeaderPool::initialize();725726if (DumpSharedSpaces) {727assert(!UseSharedSpaces, "sanity");728MetaspaceShared::initialize_for_static_dump();729}730731// If UseCompressedClassPointers=1, we have two cases:732// a) if CDS is active (runtime, Xshare=on), it will create the class space733// for us, initialize it and set up CompressedKlassPointers encoding.734// Class space will be reserved above the mapped archives.735// b) if CDS either deactivated (Xshare=off) or a static dump is to be done (Xshare:dump),736// we will create the class space on our own. It will be placed above the java heap,737// since we assume it has been placed in low738// address regions. We may rethink this (see JDK-8244943). Failing that,739// it will be placed anywhere.740741#if INCLUDE_CDS742// case (a)743if (UseSharedSpaces) {744if (!FLAG_IS_DEFAULT(CompressedClassSpaceBaseAddress)) {745log_warning(metaspace)("CDS active - ignoring CompressedClassSpaceBaseAddress.");746}747MetaspaceShared::initialize_runtime_shared_and_meta_spaces();748// If any of the archived space fails to map, UseSharedSpaces749// is reset to false.750}751752if (DynamicDumpSharedSpaces && !UseSharedSpaces) {753vm_exit_during_initialization("DynamicDumpSharedSpaces is unsupported when base CDS archive is not loaded", NULL);754}755#endif // INCLUDE_CDS756757#ifdef _LP64758759if (using_class_space() && !class_space_is_initialized()) {760assert(!UseSharedSpaces, "CDS archive is not mapped at this point");761762// case (b) (No CDS)763ReservedSpace rs;764const size_t size = align_up(CompressedClassSpaceSize, Metaspace::reserve_alignment());765address base = NULL;766767// If CompressedClassSpaceBaseAddress is set, we attempt to force-map class space to768// the given address. This is a debug-only feature aiding tests. Due to the ASLR lottery769// this may fail, in which case the VM will exit after printing an appropiate message.770// Tests using this switch should cope with that.771if (CompressedClassSpaceBaseAddress != 0) {772base = (address)CompressedClassSpaceBaseAddress;773if (!is_aligned(base, Metaspace::reserve_alignment())) {774vm_exit_during_initialization(775err_msg("CompressedClassSpaceBaseAddress=" PTR_FORMAT " invalid "776"(must be aligned to " SIZE_FORMAT_HEX ").",777CompressedClassSpaceBaseAddress, Metaspace::reserve_alignment()));778}779rs = ReservedSpace(size, Metaspace::reserve_alignment(),780os::vm_page_size() /* large */, (char*)base);781if (rs.is_reserved()) {782log_info(metaspace)("Sucessfully forced class space address to " PTR_FORMAT, p2i(base));783} else {784vm_exit_during_initialization(785err_msg("CompressedClassSpaceBaseAddress=" PTR_FORMAT " given, but reserving class space failed.",786CompressedClassSpaceBaseAddress));787}788}789790if (!rs.is_reserved()) {791// If UseCompressedOops=1 and the java heap has been placed in coops-friendly792// territory, i.e. its base is under 32G, then we attempt to place ccs793// right above the java heap.794// Otherwise the lower 32G are still free. We try to place ccs at the lowest795// allowed mapping address.796base = (UseCompressedOops && (uint64_t)CompressedOops::base() < OopEncodingHeapMax) ?797CompressedOops::end() : (address)HeapBaseMinAddress;798base = align_up(base, Metaspace::reserve_alignment());799800if (base != NULL) {801if (CompressedKlassPointers::is_valid_base(base)) {802rs = ReservedSpace(size, Metaspace::reserve_alignment(),803os::vm_page_size(), (char*)base);804}805}806}807808// ...failing that, reserve anywhere, but let platform do optimized placement:809if (!rs.is_reserved()) {810rs = Metaspace::reserve_address_space_for_compressed_classes(size);811}812813// ...failing that, give up.814if (!rs.is_reserved()) {815vm_exit_during_initialization(816err_msg("Could not allocate compressed class space: " SIZE_FORMAT " bytes",817CompressedClassSpaceSize));818}819820// Initialize space821Metaspace::initialize_class_space(rs);822823// Set up compressed class pointer encoding.824CompressedKlassPointers::initialize((address)rs.base(), rs.size());825}826827#endif828829// Initialize non-class virtual space list, and its chunk manager:830MetaspaceContext::initialize_nonclass_space_context();831832_tracer = new MetaspaceTracer();833834// We must prevent the very first address of the ccs from being used to store835// metadata, since that address would translate to a narrow pointer of 0, and the836// VM does not distinguish between "narrow 0 as in NULL" and "narrow 0 as in start837// of ccs".838// Before Elastic Metaspace that did not happen due to the fact that every Metachunk839// had a header and therefore could not allocate anything at offset 0.840#ifdef _LP64841if (using_class_space()) {842// The simplest way to fix this is to allocate a tiny dummy chunk right at the843// start of ccs and do not use it for anything.844MetaspaceContext::context_class()->cm()->get_chunk(metaspace::chunklevel::HIGHEST_CHUNK_LEVEL);845}846#endif847848#ifdef _LP64849if (UseCompressedClassPointers) {850// Note: "cds" would be a better fit but keep this for backward compatibility.851LogTarget(Info, gc, metaspace) lt;852if (lt.is_enabled()) {853ResourceMark rm;854LogStream ls(lt);855CDS_ONLY(MetaspaceShared::print_on(&ls);)856Metaspace::print_compressed_class_space(&ls);857CompressedKlassPointers::print_mode(&ls);858}859}860#endif861862}863864void Metaspace::post_initialize() {865MetaspaceGC::post_initialize();866}867868size_t Metaspace::max_allocation_word_size() {869const size_t max_overhead_words = metaspace::get_raw_word_size_for_requested_word_size(1);870return metaspace::chunklevel::MAX_CHUNK_WORD_SIZE - max_overhead_words;871}872873// This version of Metaspace::allocate does not throw OOM but simply returns NULL, and874// is suitable for calling from non-Java threads.875// Callers are responsible for checking null.876MetaWord* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size,877MetaspaceObj::Type type) {878assert(word_size <= Metaspace::max_allocation_word_size(),879"allocation size too large (" SIZE_FORMAT ")", word_size);880881assert(loader_data != NULL, "Should never pass around a NULL loader_data. "882"ClassLoaderData::the_null_class_loader_data() should have been used.");883884MetadataType mdtype = (type == MetaspaceObj::ClassType) ? ClassType : NonClassType;885886// Try to allocate metadata.887MetaWord* result = loader_data->metaspace_non_null()->allocate(word_size, mdtype);888889if (result != NULL) {890// Zero initialize.891Copy::fill_to_words((HeapWord*)result, word_size, 0);892893log_trace(metaspace)("Metaspace::allocate: type %d return " PTR_FORMAT ".", (int)type, p2i(result));894}895896return result;897}898899MetaWord* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size,900MetaspaceObj::Type type, TRAPS) {901902if (HAS_PENDING_EXCEPTION) {903assert(false, "Should not allocate with exception pending");904return NULL; // caller does a CHECK_NULL too905}906907MetaWord* result = allocate(loader_data, word_size, type);908909if (result == NULL) {910MetadataType mdtype = (type == MetaspaceObj::ClassType) ? ClassType : NonClassType;911tracer()->report_metaspace_allocation_failure(loader_data, word_size, type, mdtype);912913// Allocation failed.914if (is_init_completed()) {915// Only start a GC if the bootstrapping has completed.916// Try to clean out some heap memory and retry. This can prevent premature917// expansion of the metaspace.918result = Universe::heap()->satisfy_failed_metadata_allocation(loader_data, word_size, mdtype);919}920921if (result == NULL) {922report_metadata_oome(loader_data, word_size, type, mdtype, THREAD);923assert(HAS_PENDING_EXCEPTION, "sanity");924return NULL;925}926927// Zero initialize.928Copy::fill_to_words((HeapWord*)result, word_size, 0);929930log_trace(metaspace)("Metaspace::allocate: type %d return " PTR_FORMAT ".", (int)type, p2i(result));931}932933return result;934}935936void Metaspace::report_metadata_oome(ClassLoaderData* loader_data, size_t word_size, MetaspaceObj::Type type, MetadataType mdtype, TRAPS) {937tracer()->report_metadata_oom(loader_data, word_size, type, mdtype);938939// If result is still null, we are out of memory.940Log(gc, metaspace, freelist, oom) log;941if (log.is_info()) {942log.info("Metaspace (%s) allocation failed for size " SIZE_FORMAT,943is_class_space_allocation(mdtype) ? "class" : "data", word_size);944ResourceMark rm;945if (log.is_debug()) {946if (loader_data->metaspace_or_null() != NULL) {947LogStream ls(log.debug());948loader_data->print_value_on(&ls);949}950}951LogStream ls(log.info());952// In case of an OOM, log out a short but still useful report.953MetaspaceUtils::print_basic_report(&ls, 0);954}955956bool out_of_compressed_class_space = false;957if (is_class_space_allocation(mdtype)) {958ClassLoaderMetaspace* metaspace = loader_data->metaspace_non_null();959out_of_compressed_class_space =960MetaspaceUtils::committed_bytes(Metaspace::ClassType) +961align_up(word_size * BytesPerWord, 4 * M) >962CompressedClassSpaceSize;963}964965// -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support966const char* space_string = out_of_compressed_class_space ?967"Compressed class space" : "Metaspace";968969report_java_out_of_memory(space_string);970971if (JvmtiExport::should_post_resource_exhausted()) {972JvmtiExport::post_resource_exhausted(973JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR,974space_string);975}976977if (!is_init_completed()) {978vm_exit_during_initialization("OutOfMemoryError", space_string);979}980981if (out_of_compressed_class_space) {982THROW_OOP(Universe::out_of_memory_error_class_metaspace());983} else {984THROW_OOP(Universe::out_of_memory_error_metaspace());985}986}987988const char* Metaspace::metadata_type_name(Metaspace::MetadataType mdtype) {989switch (mdtype) {990case Metaspace::ClassType: return "Class";991case Metaspace::NonClassType: return "Metadata";992default:993assert(false, "Got bad mdtype: %d", (int) mdtype);994return NULL;995}996}997998void Metaspace::purge() {999ChunkManager* cm = ChunkManager::chunkmanager_nonclass();1000if (cm != NULL) {1001cm->purge();1002}1003if (using_class_space()) {1004cm = ChunkManager::chunkmanager_class();1005if (cm != NULL) {1006cm->purge();1007}1008}1009}10101011bool Metaspace::contains(const void* ptr) {1012if (MetaspaceShared::is_in_shared_metaspace(ptr)) {1013return true;1014}1015return contains_non_shared(ptr);1016}10171018bool Metaspace::contains_non_shared(const void* ptr) {1019if (using_class_space() && VirtualSpaceList::vslist_class()->contains((MetaWord*)ptr)) {1020return true;1021}10221023return VirtualSpaceList::vslist_nonclass()->contains((MetaWord*)ptr);1024}102510261027