Path: blob/master/src/hotspot/share/memory/metaspace/chunkManager.cpp
40957 views
/*1* Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved.2* Copyright (c) 2018, 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 "logging/log.hpp"27#include "logging/logStream.hpp"28#include "memory/metaspace/chunkManager.hpp"29#include "memory/metaspace/internalStats.hpp"30#include "memory/metaspace/metachunk.hpp"31#include "memory/metaspace/metaspaceArenaGrowthPolicy.hpp"32#include "memory/metaspace/metaspaceCommon.hpp"33#include "memory/metaspace/metaspaceContext.hpp"34#include "memory/metaspace/metaspaceSettings.hpp"35#include "memory/metaspace/metaspaceStatistics.hpp"36#include "memory/metaspace/virtualSpaceList.hpp"37#include "memory/metaspace/virtualSpaceNode.hpp"38#include "runtime/mutexLocker.hpp"39#include "utilities/debug.hpp"40#include "utilities/globalDefinitions.hpp"4142namespace metaspace {4344#define LOGFMT "ChkMgr @" PTR_FORMAT " (%s)"45#define LOGFMT_ARGS p2i(this), this->_name4647// Return a single chunk to the freelist and adjust accounting. No merge is attempted.48void ChunkManager::return_chunk_simple_locked(Metachunk* c) {49assert_lock_strong(Metaspace_lock);50DEBUG_ONLY(c->verify());51_chunks.add(c);52c->reset_used_words();53// Tracing54log_debug(metaspace)("ChunkManager %s: returned chunk " METACHUNK_FORMAT ".",55_name, METACHUNK_FORMAT_ARGS(c));56}5758// Creates a chunk manager with a given name (which is for debug purposes only)59// and an associated space list which will be used to request new chunks from60// (see get_chunk())61ChunkManager::ChunkManager(const char* name, VirtualSpaceList* space_list) :62_vslist(space_list),63_name(name),64_chunks()65{66}6768// Given a chunk, split it into a target chunk of a smaller size (higher target level)69// and at least one, possible several splinter chunks.70// The original chunk must be outside of the freelist and its state must be free.71// The splinter chunks are added to the freelist.72// The resulting target chunk will be located at the same address as the original73// chunk, but it will of course be smaller (of a higher level).74// The committed areas within the original chunk carry over to the resulting75// chunks.76void ChunkManager::split_chunk_and_add_splinters(Metachunk* c, chunklevel_t target_level) {77assert_lock_strong(Metaspace_lock);78assert(c->is_free(), "chunk to be split must be free.");79assert(c->level() < target_level, "Target level must be higher than current level.");80assert(c->prev() == NULL && c->next() == NULL, "Chunk must be outside of any list.");8182DEBUG_ONLY(chunklevel::check_valid_level(target_level);)83DEBUG_ONLY(c->verify();)8485UL2(debug, "splitting chunk " METACHUNK_FORMAT " to " CHKLVL_FORMAT ".",86METACHUNK_FORMAT_ARGS(c), target_level);8788DEBUG_ONLY(size_t committed_words_before = c->committed_words();)8990const chunklevel_t orig_level = c->level();91c->vsnode()->split(target_level, c, &_chunks);9293// Splitting should never fail.94assert(c->level() == target_level, "Sanity");9596// The size of the committed portion should not change (subject to the reduced chunk size of course)97#ifdef ASSERT98if (committed_words_before > c->word_size()) {99assert(c->is_fully_committed(), "Sanity");100} else {101assert(c->committed_words() == committed_words_before, "Sanity");102}103c->verify();104verify_locked();105SOMETIMES(c->vsnode()->verify_locked();)106#endif107InternalStats::inc_num_chunk_splits();108}109110// On success, returns a chunk of level of <preferred_level>, but at most <max_level>.111// The first first <min_committed_words> of the chunk are guaranteed to be committed.112// On error, will return NULL.113//114// This function may fail for two reasons:115// - Either we are unable to reserve space for a new chunk (if the underlying VirtualSpaceList116// is non-expandable but needs expanding - aka out of compressed class space).117// - Or, if the necessary space cannot be committed because we hit a commit limit.118// This may be either the GC threshold or MaxMetaspaceSize.119Metachunk* ChunkManager::get_chunk(chunklevel_t preferred_level, chunklevel_t max_level, size_t min_committed_words) {120assert(preferred_level <= max_level, "Sanity");121assert(chunklevel::level_fitting_word_size(min_committed_words) >= max_level, "Sanity");122123MutexLocker fcl(Metaspace_lock, Mutex::_no_safepoint_check_flag);124125DEBUG_ONLY(verify_locked();)126DEBUG_ONLY(chunklevel::check_valid_level(max_level);)127DEBUG_ONLY(chunklevel::check_valid_level(preferred_level);)128129UL2(debug, "requested chunk: pref_level: " CHKLVL_FORMAT130", max_level: " CHKLVL_FORMAT ", min committed size: " SIZE_FORMAT ".",131preferred_level, max_level, min_committed_words);132133// First, optimistically look for a chunk which is already committed far enough to hold min_word_size.134135// 1) Search best or smaller committed chunks (first attempt):136// Start at the preferred chunk size and work your way down (level up).137// But for now, only consider chunks larger than a certain threshold -138// this is to prevent large loaders (eg boot) from unnecessarily gobbling up139// all the tiny splinter chunks lambdas leave around.140Metachunk* c = NULL;141c = _chunks.search_chunk_ascending(preferred_level, MIN2((chunklevel_t)(preferred_level + 2), max_level), min_committed_words);142143// 2) Search larger committed chunks:144// If that did not yield anything, look at larger chunks, which may be committed. We would have to split145// them first, of course.146if (c == NULL) {147c = _chunks.search_chunk_descending(preferred_level, min_committed_words);148}149// 3) Search best or smaller committed chunks (second attempt):150// Repeat (1) but now consider even the tiniest chunks as long as they are large enough to hold the151// committed min size.152if (c == NULL) {153c = _chunks.search_chunk_ascending(preferred_level, max_level, min_committed_words);154}155// if we did not get anything yet, there are no free chunks commmitted enough. Repeat search but look for uncommitted chunks too:156// 4) Search best or smaller chunks, can be uncommitted:157if (c == NULL) {158c = _chunks.search_chunk_ascending(preferred_level, max_level, 0);159}160// 5) Search a larger uncommitted chunk:161if (c == NULL) {162c = _chunks.search_chunk_descending(preferred_level, 0);163}164165if (c != NULL) {166UL(trace, "taken from freelist.");167}168169// Failing all that, allocate a new root chunk from the connected virtual space.170// This may fail if the underlying vslist cannot be expanded (e.g. compressed class space)171if (c == NULL) {172c = _vslist->allocate_root_chunk();173if (c == NULL) {174UL(info, "failed to get new root chunk.");175} else {176assert(c->level() == chunklevel::ROOT_CHUNK_LEVEL, "root chunk expected");177UL(debug, "allocated new root chunk.");178}179}180if (c == NULL) {181// If we end up here, we found no match in the freelists and were unable to get a new182// root chunk (so we used up all address space, e.g. out of CompressedClassSpace).183UL2(info, "failed to get chunk (preferred level: " CHKLVL_FORMAT184", max level " CHKLVL_FORMAT ".", preferred_level, max_level);185c = NULL;186}187if (c != NULL) {188// Now we have a chunk.189// It may be larger than what the caller wanted, so we may want to split it. This should190// always work.191if (c->level() < preferred_level) {192split_chunk_and_add_splinters(c, preferred_level);193assert(c->level() == preferred_level, "split failed?");194}195// Attempt to commit the chunk (depending on settings, we either fully commit it or just196// commit enough to get the caller going). That may fail if we hit a commit limit. In197// that case put the chunk back to the freelist (re-merging it with its neighbors if we198// did split it) and return NULL.199const size_t to_commit = Settings::new_chunks_are_fully_committed() ? c->word_size() : min_committed_words;200if (c->committed_words() < to_commit) {201if (c->ensure_committed_locked(to_commit) == false) {202UL2(info, "failed to commit " SIZE_FORMAT " words on chunk " METACHUNK_FORMAT ".",203to_commit, METACHUNK_FORMAT_ARGS(c));204return_chunk_locked(c);205c = NULL;206}207}208if (c != NULL) {209// Still here? We have now a good chunk, all is well.210assert(c->committed_words() >= min_committed_words, "Sanity");211212// Any chunk returned from ChunkManager shall be marked as in use.213c->set_in_use();214215UL2(debug, "handing out chunk " METACHUNK_FORMAT ".", METACHUNK_FORMAT_ARGS(c));216217InternalStats::inc_num_chunks_taken_from_freelist();218219SOMETIMES(c->vsnode()->verify_locked();)220}221}222223DEBUG_ONLY(verify_locked();)224return c;225}226227// Return a single chunk to the ChunkManager and adjust accounting. May merge chunk228// with neighbors.229// As a side effect this removes the chunk from whatever list it has been in previously.230// Happens after a Classloader was unloaded and releases its metaspace chunks.231// !! Note: this may invalidate the chunk. Do not access the chunk after232// this function returns !!233void ChunkManager::return_chunk(Metachunk* c) {234MutexLocker fcl(Metaspace_lock, Mutex::_no_safepoint_check_flag);235return_chunk_locked(c);236}237238// See return_chunk().239void ChunkManager::return_chunk_locked(Metachunk* c) {240assert_lock_strong(Metaspace_lock);241UL2(debug, ": returning chunk " METACHUNK_FORMAT ".", METACHUNK_FORMAT_ARGS(c));242DEBUG_ONLY(c->verify();)243assert(contains_chunk(c) == false, "A chunk to be added to the freelist must not be in the freelist already.");244assert(c->is_in_use() || c->is_free(), "Unexpected chunk state");245assert(!c->in_list(), "Remove from list first");246247c->set_free();248c->reset_used_words();249const chunklevel_t orig_lvl = c->level();250251Metachunk* merged = NULL;252if (!c->is_root_chunk()) {253// Only attempt merging if we are not of the lowest level already.254merged = c->vsnode()->merge(c, &_chunks);255}256257if (merged != NULL) {258InternalStats::inc_num_chunk_merges();259DEBUG_ONLY(merged->verify());260// We did merge chunks and now have a bigger chunk.261assert(merged->level() < orig_lvl, "Sanity");262UL2(debug, "merged into chunk " METACHUNK_FORMAT ".", METACHUNK_FORMAT_ARGS(merged));263c = merged;264}265266if (Settings::uncommit_free_chunks() &&267c->word_size() >= Settings::commit_granule_words()) {268UL2(debug, "uncommitting free chunk " METACHUNK_FORMAT ".", METACHUNK_FORMAT_ARGS(c));269c->uncommit_locked();270}271272return_chunk_simple_locked(c);273DEBUG_ONLY(verify_locked();)274SOMETIMES(c->vsnode()->verify_locked();)275InternalStats::inc_num_chunks_returned_to_freelist();276}277278// Given a chunk c, whose state must be "in-use" and must not be a root chunk, attempt to279// enlarge it in place by claiming its trailing buddy.280//281// This will only work if c is the leader of the buddy pair and the trailing buddy is free.282//283// If successful, the follower chunk will be removed from the freelists, the leader chunk c will284// double in size (level decreased by one).285//286// On success, true is returned, false otherwise.287bool ChunkManager::attempt_enlarge_chunk(Metachunk* c) {288MutexLocker fcl(Metaspace_lock, Mutex::_no_safepoint_check_flag);289return c->vsnode()->attempt_enlarge_chunk(c, &_chunks);290}291292static void print_word_size_delta(outputStream* st, size_t word_size_1, size_t word_size_2) {293if (word_size_1 == word_size_2) {294print_scaled_words(st, word_size_1);295st->print (" (no change)");296} else {297print_scaled_words(st, word_size_1);298st->print("->");299print_scaled_words(st, word_size_2);300st->print(" (");301if (word_size_2 <= word_size_1) {302st->print("-");303print_scaled_words(st, word_size_1 - word_size_2);304} else {305st->print("+");306print_scaled_words(st, word_size_2 - word_size_1);307}308st->print(")");309}310}311312void ChunkManager::purge() {313MutexLocker fcl(Metaspace_lock, Mutex::_no_safepoint_check_flag);314UL(info, ": reclaiming memory...");315316const size_t reserved_before = _vslist->reserved_words();317const size_t committed_before = _vslist->committed_words();318int num_nodes_purged = 0;319320// We purge to return unused memory to the Operating System. We do this in321// two independent steps.322323// 1) We purge the virtual space list: any memory mappings which are324// completely deserted can be potentially unmapped. We iterate over the list325// of mappings (VirtualSpaceList::purge) and delete every node whose memory326// only contains free chunks. Deleting that node includes unmapping its memory,327// so all chunk vanish automatically.328// Of course we need to remove the chunk headers of those vanished chunks from329// the ChunkManager freelist.330num_nodes_purged = _vslist->purge(&_chunks);331InternalStats::inc_num_purges();332333// 2) Since (1) is rather ineffective - it is rare that a whole node only contains334// free chunks - we now iterate over all remaining free chunks and335// and uncommit those which can be uncommitted (>= commit granule size).336if (Settings::uncommit_free_chunks()) {337const chunklevel_t max_level =338chunklevel::level_fitting_word_size(Settings::commit_granule_words());339for (chunklevel_t l = chunklevel::LOWEST_CHUNK_LEVEL;340l <= max_level;341l++) {342// Since we uncommit all chunks at this level, we do not break the "committed chunks are343// at the front of the list" condition.344for (Metachunk* c = _chunks.first_at_level(l); c != NULL; c = c->next()) {345c->uncommit_locked();346}347}348}349350const size_t reserved_after = _vslist->reserved_words();351const size_t committed_after = _vslist->committed_words();352353// Print a nice report.354if (reserved_after == reserved_before && committed_after == committed_before) {355UL(info, "nothing reclaimed.");356} else {357LogTarget(Info, metaspace) lt;358if (lt.is_enabled()) {359LogStream ls(lt);360ls.print_cr(LOGFMT ": finished reclaiming memory: ", LOGFMT_ARGS);361ls.print("reserved: ");362print_word_size_delta(&ls, reserved_before, reserved_after);363ls.cr();364ls.print("committed: ");365print_word_size_delta(&ls, committed_before, committed_after);366ls.cr();367ls.print_cr("full nodes purged: %d", num_nodes_purged);368}369}370DEBUG_ONLY(_vslist->verify_locked());371DEBUG_ONLY(verify_locked());372}373374// Convenience methods to return the global class-space chunkmanager375// and non-class chunkmanager, respectively.376ChunkManager* ChunkManager::chunkmanager_class() {377return MetaspaceContext::context_class() == NULL ? NULL : MetaspaceContext::context_class()->cm();378}379380ChunkManager* ChunkManager::chunkmanager_nonclass() {381return MetaspaceContext::context_nonclass() == NULL ? NULL : MetaspaceContext::context_nonclass()->cm();382}383384// Calculates the total number of committed words over all chunks. Walks chunks.385size_t ChunkManager::calc_committed_word_size() const {386MutexLocker fcl(Metaspace_lock, Mutex::_no_safepoint_check_flag);387return calc_committed_word_size_locked();388}389390size_t ChunkManager::calc_committed_word_size_locked() const {391assert_lock_strong(Metaspace_lock);392return _chunks.calc_committed_word_size();393}394395// Update statistics.396void ChunkManager::add_to_statistics(ChunkManagerStats* out) const {397MutexLocker fcl(Metaspace_lock, Mutex::_no_safepoint_check_flag);398for (chunklevel_t l = chunklevel::ROOT_CHUNK_LEVEL; l <= chunklevel::HIGHEST_CHUNK_LEVEL; l++) {399out->_num_chunks[l] += _chunks.num_chunks_at_level(l);400out->_committed_word_size[l] += _chunks.calc_committed_word_size_at_level(l);401}402DEBUG_ONLY(out->verify();)403}404405#ifdef ASSERT406407void ChunkManager::verify() const {408MutexLocker fcl(Metaspace_lock, Mutex::_no_safepoint_check_flag);409verify_locked();410}411412void ChunkManager::verify_locked() const {413assert_lock_strong(Metaspace_lock);414assert(_vslist != NULL, "No vslist");415_chunks.verify();416}417418bool ChunkManager::contains_chunk(Metachunk* c) const {419return _chunks.contains(c);420}421422#endif // ASSERT423424void ChunkManager::print_on(outputStream* st) const {425MutexLocker fcl(Metaspace_lock, Mutex::_no_safepoint_check_flag);426print_on_locked(st);427}428429void ChunkManager::print_on_locked(outputStream* st) const {430assert_lock_strong(Metaspace_lock);431st->print_cr("cm %s: %d chunks, total word size: " SIZE_FORMAT ".", _name,432total_num_chunks(), total_word_size());433_chunks.print_on(st);434}435436} // namespace metaspace437438439