Path: blob/master/src/hotspot/share/memory/virtualspace.cpp
40949 views
/*1* Copyright (c) 1997, 2021, 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 "logging/log.hpp"26#include "memory/resourceArea.hpp"27#include "memory/virtualspace.hpp"28#include "oops/compressedOops.hpp"29#include "oops/markWord.hpp"30#include "oops/oop.inline.hpp"31#include "runtime/globals_extension.hpp"32#include "runtime/java.hpp"33#include "runtime/os.hpp"34#include "services/memTracker.hpp"35#include "utilities/align.hpp"36#include "utilities/formatBuffer.hpp"37#include "utilities/powerOfTwo.hpp"3839// ReservedSpace4041// Dummy constructor42ReservedSpace::ReservedSpace() : _base(NULL), _size(0), _noaccess_prefix(0),43_alignment(0), _special(false), _fd_for_heap(-1), _executable(false) {44}4546ReservedSpace::ReservedSpace(size_t size) : _fd_for_heap(-1) {47// Want to use large pages where possible. If the size is48// not large page aligned the mapping will be a mix of49// large and normal pages.50size_t page_size = os::page_size_for_region_unaligned(size, 1);51size_t alignment = os::vm_allocation_granularity();52initialize(size, alignment, page_size, NULL, false);53}5455ReservedSpace::ReservedSpace(size_t size, size_t preferred_page_size) : _fd_for_heap(-1) {56// When a page size is given we don't want to mix large57// and normal pages. If the size is not a multiple of the58// page size it will be aligned up to achieve this.59size_t alignment = os::vm_allocation_granularity();;60if (preferred_page_size != (size_t)os::vm_page_size()) {61alignment = MAX2(preferred_page_size, alignment);62size = align_up(size, alignment);63}64initialize(size, alignment, preferred_page_size, NULL, false);65}6667ReservedSpace::ReservedSpace(size_t size,68size_t alignment,69size_t page_size,70char* requested_address) : _fd_for_heap(-1) {71initialize(size, alignment, page_size, requested_address, false);72}7374ReservedSpace::ReservedSpace(char* base, size_t size, size_t alignment, size_t page_size,75bool special, bool executable) : _fd_for_heap(-1) {76assert((size % os::vm_allocation_granularity()) == 0,77"size not allocation aligned");78initialize_members(base, size, alignment, page_size, special, executable);79}8081// Helper method82static char* attempt_map_or_reserve_memory_at(char* base, size_t size, int fd, bool executable) {83if (fd != -1) {84return os::attempt_map_memory_to_file_at(base, size, fd);85}86return os::attempt_reserve_memory_at(base, size, executable);87}8889// Helper method90static char* map_or_reserve_memory(size_t size, int fd, bool executable) {91if (fd != -1) {92return os::map_memory_to_file(size, fd);93}94return os::reserve_memory(size, executable);95}9697// Helper method98static char* map_or_reserve_memory_aligned(size_t size, size_t alignment, int fd, bool executable) {99if (fd != -1) {100return os::map_memory_to_file_aligned(size, alignment, fd);101}102return os::reserve_memory_aligned(size, alignment, executable);103}104105// Helper method106static void unmap_or_release_memory(char* base, size_t size, bool is_file_mapped) {107if (is_file_mapped) {108if (!os::unmap_memory(base, size)) {109fatal("os::unmap_memory failed");110}111} else if (!os::release_memory(base, size)) {112fatal("os::release_memory failed");113}114}115116// Helper method117static bool failed_to_reserve_as_requested(char* base, char* requested_address) {118if (base == requested_address || requested_address == NULL) {119return false; // did not fail120}121122if (base != NULL) {123// Different reserve address may be acceptable in other cases124// but for compressed oops heap should be at requested address.125assert(UseCompressedOops, "currently requested address used only for compressed oops");126log_debug(gc, heap, coops)("Reserved memory not at requested address: " PTR_FORMAT " vs " PTR_FORMAT, p2i(base), p2i(requested_address));127}128return true;129}130131static bool use_explicit_large_pages(size_t page_size) {132return !os::can_commit_large_page_memory() &&133page_size != (size_t) os::vm_page_size();134}135136static bool large_pages_requested() {137return UseLargePages &&138(!FLAG_IS_DEFAULT(UseLargePages) || !FLAG_IS_DEFAULT(LargePageSizeInBytes));139}140141static char* reserve_memory(char* requested_address, const size_t size,142const size_t alignment, int fd, bool exec) {143char* base;144// If the memory was requested at a particular address, use145// os::attempt_reserve_memory_at() to avoid mapping over something146// important. If the reservation fails, return NULL.147if (requested_address != 0) {148assert(is_aligned(requested_address, alignment),149"Requested address " PTR_FORMAT " must be aligned to " SIZE_FORMAT,150p2i(requested_address), alignment);151base = attempt_map_or_reserve_memory_at(requested_address, size, fd, exec);152} else {153// Optimistically assume that the OS returns an aligned base pointer.154// When reserving a large address range, most OSes seem to align to at155// least 64K.156base = map_or_reserve_memory(size, fd, exec);157// Check alignment constraints. This is only needed when there is158// no requested address.159if (!is_aligned(base, alignment)) {160// Base not aligned, retry.161unmap_or_release_memory(base, size, fd != -1 /*is_file_mapped*/);162// Map using the requested alignment.163base = map_or_reserve_memory_aligned(size, alignment, fd, exec);164}165}166167return base;168}169170static char* reserve_memory_special(char* requested_address, const size_t size,171const size_t alignment, const size_t page_size, bool exec) {172173log_trace(pagesize)("Attempt special mapping: size: " SIZE_FORMAT "%s, "174"alignment: " SIZE_FORMAT "%s",175byte_size_in_exact_unit(size), exact_unit_for_byte_size(size),176byte_size_in_exact_unit(alignment), exact_unit_for_byte_size(alignment));177178char* base = os::reserve_memory_special(size, alignment, page_size, requested_address, exec);179if (base != NULL) {180// Check alignment constraints.181assert(is_aligned(base, alignment),182"reserve_memory_special() returned an unaligned address, base: " PTR_FORMAT183" alignment: " SIZE_FORMAT_HEX,184p2i(base), alignment);185} else {186if (large_pages_requested()) {187log_debug(gc, heap, coops)("Reserve regular memory without large pages");188}189}190return base;191}192193void ReservedSpace::clear_members() {194initialize_members(NULL, 0, 0, 0, false, false);195}196197void ReservedSpace::initialize_members(char* base, size_t size, size_t alignment,198size_t page_size, bool special, bool executable) {199_base = base;200_size = size;201_alignment = alignment;202_page_size = page_size;203_special = special;204_executable = executable;205_noaccess_prefix = 0;206}207208void ReservedSpace::reserve(size_t size,209size_t alignment,210size_t page_size,211char* requested_address,212bool executable) {213assert(is_aligned(size, alignment), "Size must be aligned to the requested alignment");214215// There are basically three different cases that we need to handle below:216// - Mapping backed by a file217// - Mapping backed by explicit large pages218// - Mapping backed by normal pages or transparent huge pages219// The first two have restrictions that requires the whole mapping to be220// committed up front. To record this the ReservedSpace is marked 'special'.221222if (_fd_for_heap != -1) {223// When there is a backing file directory for this space then whether224// large pages are allocated is up to the filesystem of the backing file.225// So UseLargePages is not taken into account for this reservation.226char* base = reserve_memory(requested_address, size, alignment, _fd_for_heap, executable);227if (base != NULL) {228initialize_members(base, size, alignment, os::vm_page_size(), true, executable);229}230// Always return, not possible to fall back to reservation not using a file.231return;232} else if (use_explicit_large_pages(page_size)) {233// System can't commit large pages i.e. use transparent huge pages and234// the caller requested large pages. To satisfy this request we use235// explicit large pages and these have to be committed up front to ensure236// no reservations are lost.237238char* base = reserve_memory_special(requested_address, size, alignment, page_size, executable);239if (base != NULL) {240// Successful reservation using large pages.241initialize_members(base, size, alignment, page_size, true, executable);242return;243}244// Failed to reserve explicit large pages, fall back to normal reservation.245page_size = os::vm_page_size();246}247248// Not a 'special' reservation.249char* base = reserve_memory(requested_address, size, alignment, -1, executable);250if (base != NULL) {251// Successful mapping.252initialize_members(base, size, alignment, page_size, false, executable);253}254}255256void ReservedSpace::initialize(size_t size,257size_t alignment,258size_t page_size,259char* requested_address,260bool executable) {261const size_t granularity = os::vm_allocation_granularity();262assert((size & (granularity - 1)) == 0,263"size not aligned to os::vm_allocation_granularity()");264assert((alignment & (granularity - 1)) == 0,265"alignment not aligned to os::vm_allocation_granularity()");266assert(alignment == 0 || is_power_of_2((intptr_t)alignment),267"not a power of 2");268assert(page_size >= (size_t) os::vm_page_size(), "Invalid page size");269assert(is_power_of_2(page_size), "Invalid page size");270271clear_members();272273if (size == 0) {274return;275}276277// Adjust alignment to not be 0.278alignment = MAX2(alignment, (size_t)os::vm_page_size());279280// Reserve the memory.281reserve(size, alignment, page_size, requested_address, executable);282283// Check that the requested address is used if given.284if (failed_to_reserve_as_requested(_base, requested_address)) {285// OS ignored the requested address, release the reservation.286release();287return;288}289}290291ReservedSpace ReservedSpace::first_part(size_t partition_size, size_t alignment) {292assert(partition_size <= size(), "partition failed");293ReservedSpace result(base(), partition_size, alignment, page_size(), special(), executable());294return result;295}296297298ReservedSpace299ReservedSpace::last_part(size_t partition_size, size_t alignment) {300assert(partition_size <= size(), "partition failed");301ReservedSpace result(base() + partition_size, size() - partition_size,302alignment, page_size(), special(), executable());303return result;304}305306307size_t ReservedSpace::page_align_size_up(size_t size) {308return align_up(size, os::vm_page_size());309}310311312size_t ReservedSpace::page_align_size_down(size_t size) {313return align_down(size, os::vm_page_size());314}315316317size_t ReservedSpace::allocation_align_size_up(size_t size) {318return align_up(size, os::vm_allocation_granularity());319}320321void ReservedSpace::release() {322if (is_reserved()) {323char *real_base = _base - _noaccess_prefix;324const size_t real_size = _size + _noaccess_prefix;325if (special()) {326if (_fd_for_heap != -1) {327os::unmap_memory(real_base, real_size);328} else {329os::release_memory_special(real_base, real_size);330}331} else{332os::release_memory(real_base, real_size);333}334clear_members();335}336}337338static size_t noaccess_prefix_size(size_t alignment) {339return lcm(os::vm_page_size(), alignment);340}341342void ReservedHeapSpace::establish_noaccess_prefix() {343assert(_alignment >= (size_t)os::vm_page_size(), "must be at least page size big");344_noaccess_prefix = noaccess_prefix_size(_alignment);345346if (base() && base() + _size > (char *)OopEncodingHeapMax) {347if (true348WIN64_ONLY(&& !UseLargePages)349AIX_ONLY(&& os::vm_page_size() != 64*K)) {350// Protect memory at the base of the allocated region.351// If special, the page was committed (only matters on windows)352if (!os::protect_memory(_base, _noaccess_prefix, os::MEM_PROT_NONE, _special)) {353fatal("cannot protect protection page");354}355log_debug(gc, heap, coops)("Protected page at the reserved heap base: "356PTR_FORMAT " / " INTX_FORMAT " bytes",357p2i(_base),358_noaccess_prefix);359assert(CompressedOops::use_implicit_null_checks() == true, "not initialized?");360} else {361CompressedOops::set_use_implicit_null_checks(false);362}363}364365_base += _noaccess_prefix;366_size -= _noaccess_prefix;367assert(((uintptr_t)_base % _alignment == 0), "must be exactly of required alignment");368}369370// Tries to allocate memory of size 'size' at address requested_address with alignment 'alignment'.371// Does not check whether the reserved memory actually is at requested_address, as the memory returned372// might still fulfill the wishes of the caller.373// Assures the memory is aligned to 'alignment'.374// NOTE: If ReservedHeapSpace already points to some reserved memory this is freed, first.375void ReservedHeapSpace::try_reserve_heap(size_t size,376size_t alignment,377size_t page_size,378char* requested_address) {379if (_base != NULL) {380// We tried before, but we didn't like the address delivered.381release();382}383384// Try to reserve the memory for the heap.385log_trace(gc, heap, coops)("Trying to allocate at address " PTR_FORMAT386" heap of size " SIZE_FORMAT_HEX,387p2i(requested_address),388size);389390reserve(size, alignment, page_size, requested_address, false);391392// Check alignment constraints.393if (is_reserved() && !is_aligned(_base, _alignment)) {394// Base not aligned, retry.395release();396}397}398399void ReservedHeapSpace::try_reserve_range(char *highest_start,400char *lowest_start,401size_t attach_point_alignment,402char *aligned_heap_base_min_address,403char *upper_bound,404size_t size,405size_t alignment,406size_t page_size) {407const size_t attach_range = highest_start - lowest_start;408// Cap num_attempts at possible number.409// At least one is possible even for 0 sized attach range.410const uint64_t num_attempts_possible = (attach_range / attach_point_alignment) + 1;411const uint64_t num_attempts_to_try = MIN2((uint64_t)HeapSearchSteps, num_attempts_possible);412413const size_t stepsize = (attach_range == 0) ? // Only one try.414(size_t) highest_start : align_up(attach_range / num_attempts_to_try, attach_point_alignment);415416// Try attach points from top to bottom.417char* attach_point = highest_start;418while (attach_point >= lowest_start &&419attach_point <= highest_start && // Avoid wrap around.420((_base == NULL) ||421(_base < aligned_heap_base_min_address || _base + size > upper_bound))) {422try_reserve_heap(size, alignment, page_size, attach_point);423attach_point -= stepsize;424}425}426427#define SIZE_64K ((uint64_t) UCONST64( 0x10000))428#define SIZE_256M ((uint64_t) UCONST64( 0x10000000))429#define SIZE_32G ((uint64_t) UCONST64( 0x800000000))430431// Helper for heap allocation. Returns an array with addresses432// (OS-specific) which are suited for disjoint base mode. Array is433// NULL terminated.434static char** get_attach_addresses_for_disjoint_mode() {435static uint64_t addresses[] = {4362 * SIZE_32G,4373 * SIZE_32G,4384 * SIZE_32G,4398 * SIZE_32G,44010 * SIZE_32G,4411 * SIZE_64K * SIZE_32G,4422 * SIZE_64K * SIZE_32G,4433 * SIZE_64K * SIZE_32G,4444 * SIZE_64K * SIZE_32G,44516 * SIZE_64K * SIZE_32G,44632 * SIZE_64K * SIZE_32G,44734 * SIZE_64K * SIZE_32G,4480449};450451// Sort out addresses smaller than HeapBaseMinAddress. This assumes452// the array is sorted.453uint i = 0;454while (addresses[i] != 0 &&455(addresses[i] < OopEncodingHeapMax || addresses[i] < HeapBaseMinAddress)) {456i++;457}458uint start = i;459460// Avoid more steps than requested.461i = 0;462while (addresses[start+i] != 0) {463if (i == HeapSearchSteps) {464addresses[start+i] = 0;465break;466}467i++;468}469470return (char**) &addresses[start];471}472473void ReservedHeapSpace::initialize_compressed_heap(const size_t size, size_t alignment, size_t page_size) {474guarantee(size + noaccess_prefix_size(alignment) <= OopEncodingHeapMax,475"can not allocate compressed oop heap for this size");476guarantee(alignment == MAX2(alignment, (size_t)os::vm_page_size()), "alignment too small");477478const size_t granularity = os::vm_allocation_granularity();479assert((size & (granularity - 1)) == 0,480"size not aligned to os::vm_allocation_granularity()");481assert((alignment & (granularity - 1)) == 0,482"alignment not aligned to os::vm_allocation_granularity()");483assert(alignment == 0 || is_power_of_2((intptr_t)alignment),484"not a power of 2");485486// The necessary attach point alignment for generated wish addresses.487// This is needed to increase the chance of attaching for mmap and shmat.488const size_t os_attach_point_alignment =489AIX_ONLY(SIZE_256M) // Known shm boundary alignment.490NOT_AIX(os::vm_allocation_granularity());491const size_t attach_point_alignment = lcm(alignment, os_attach_point_alignment);492493char *aligned_heap_base_min_address = (char *)align_up((void *)HeapBaseMinAddress, alignment);494size_t noaccess_prefix = ((aligned_heap_base_min_address + size) > (char*)OopEncodingHeapMax) ?495noaccess_prefix_size(alignment) : 0;496497// Attempt to alloc at user-given address.498if (!FLAG_IS_DEFAULT(HeapBaseMinAddress)) {499try_reserve_heap(size + noaccess_prefix, alignment, page_size, aligned_heap_base_min_address);500if (_base != aligned_heap_base_min_address) { // Enforce this exact address.501release();502}503}504505// Keep heap at HeapBaseMinAddress.506if (_base == NULL) {507508// Try to allocate the heap at addresses that allow efficient oop compression.509// Different schemes are tried, in order of decreasing optimization potential.510//511// For this, try_reserve_heap() is called with the desired heap base addresses.512// A call into the os layer to allocate at a given address can return memory513// at a different address than requested. Still, this might be memory at a useful514// address. try_reserve_heap() always returns this allocated memory, as only here515// the criteria for a good heap are checked.516517// Attempt to allocate so that we can run without base and scale (32-Bit unscaled compressed oops).518// Give it several tries from top of range to bottom.519if (aligned_heap_base_min_address + size <= (char *)UnscaledOopHeapMax) {520521// Calc address range within we try to attach (range of possible start addresses).522char* const highest_start = align_down((char *)UnscaledOopHeapMax - size, attach_point_alignment);523char* const lowest_start = align_up(aligned_heap_base_min_address, attach_point_alignment);524try_reserve_range(highest_start, lowest_start, attach_point_alignment,525aligned_heap_base_min_address, (char *)UnscaledOopHeapMax, size, alignment, page_size);526}527528// zerobased: Attempt to allocate in the lower 32G.529// But leave room for the compressed class pointers, which is allocated above530// the heap.531char *zerobased_max = (char *)OopEncodingHeapMax;532const size_t class_space = align_up(CompressedClassSpaceSize, alignment);533// For small heaps, save some space for compressed class pointer534// space so it can be decoded with no base.535if (UseCompressedClassPointers && !UseSharedSpaces &&536OopEncodingHeapMax <= KlassEncodingMetaspaceMax &&537(uint64_t)(aligned_heap_base_min_address + size + class_space) <= KlassEncodingMetaspaceMax) {538zerobased_max = (char *)OopEncodingHeapMax - class_space;539}540541// Give it several tries from top of range to bottom.542if (aligned_heap_base_min_address + size <= zerobased_max && // Zerobased theoretical possible.543((_base == NULL) || // No previous try succeeded.544(_base + size > zerobased_max))) { // Unscaled delivered an arbitrary address.545546// Calc address range within we try to attach (range of possible start addresses).547char *const highest_start = align_down(zerobased_max - size, attach_point_alignment);548// Need to be careful about size being guaranteed to be less549// than UnscaledOopHeapMax due to type constraints.550char *lowest_start = aligned_heap_base_min_address;551uint64_t unscaled_end = UnscaledOopHeapMax - size;552if (unscaled_end < UnscaledOopHeapMax) { // unscaled_end wrapped if size is large553lowest_start = MAX2(lowest_start, (char*)unscaled_end);554}555lowest_start = align_up(lowest_start, attach_point_alignment);556try_reserve_range(highest_start, lowest_start, attach_point_alignment,557aligned_heap_base_min_address, zerobased_max, size, alignment, page_size);558}559560// Now we go for heaps with base != 0. We need a noaccess prefix to efficiently561// implement null checks.562noaccess_prefix = noaccess_prefix_size(alignment);563564// Try to attach at addresses that are aligned to OopEncodingHeapMax. Disjointbase mode.565char** addresses = get_attach_addresses_for_disjoint_mode();566int i = 0;567while (addresses[i] && // End of array not yet reached.568((_base == NULL) || // No previous try succeeded.569(_base + size > (char *)OopEncodingHeapMax && // Not zerobased or unscaled address.570!CompressedOops::is_disjoint_heap_base_address((address)_base)))) { // Not disjoint address.571char* const attach_point = addresses[i];572assert(attach_point >= aligned_heap_base_min_address, "Flag support broken");573try_reserve_heap(size + noaccess_prefix, alignment, page_size, attach_point);574i++;575}576577// Last, desperate try without any placement.578if (_base == NULL) {579log_trace(gc, heap, coops)("Trying to allocate at address NULL heap of size " SIZE_FORMAT_HEX, size + noaccess_prefix);580initialize(size + noaccess_prefix, alignment, page_size, NULL, false);581}582}583}584585ReservedHeapSpace::ReservedHeapSpace(size_t size, size_t alignment, size_t page_size, const char* heap_allocation_directory) : ReservedSpace() {586587if (size == 0) {588return;589}590591if (heap_allocation_directory != NULL) {592_fd_for_heap = os::create_file_for_heap(heap_allocation_directory);593if (_fd_for_heap == -1) {594vm_exit_during_initialization(595err_msg("Could not create file for Heap at location %s", heap_allocation_directory));596}597// When there is a backing file directory for this space then whether598// large pages are allocated is up to the filesystem of the backing file.599// If requested, let the user know that explicit large pages can't be used.600if (use_explicit_large_pages(page_size) && large_pages_requested()) {601log_debug(gc, heap)("Cannot allocate explicit large pages for Java Heap when AllocateHeapAt option is set.");602}603}604605// Heap size should be aligned to alignment, too.606guarantee(is_aligned(size, alignment), "set by caller");607608if (UseCompressedOops) {609initialize_compressed_heap(size, alignment, page_size);610if (_size > size) {611// We allocated heap with noaccess prefix.612// It can happen we get a zerobased/unscaled heap with noaccess prefix,613// if we had to try at arbitrary address.614establish_noaccess_prefix();615}616} else {617initialize(size, alignment, page_size, NULL, false);618}619620assert(markWord::encode_pointer_as_mark(_base).decode_pointer() == _base,621"area must be distinguishable from marks for mark-sweep");622assert(markWord::encode_pointer_as_mark(&_base[size]).decode_pointer() == &_base[size],623"area must be distinguishable from marks for mark-sweep");624625if (base() != NULL) {626MemTracker::record_virtual_memory_type((address)base(), mtJavaHeap);627}628629if (_fd_for_heap != -1) {630os::close(_fd_for_heap);631}632}633634MemRegion ReservedHeapSpace::region() const {635return MemRegion((HeapWord*)base(), (HeapWord*)end());636}637638// Reserve space for code segment. Same as Java heap only we mark this as639// executable.640ReservedCodeSpace::ReservedCodeSpace(size_t r_size,641size_t rs_align,642size_t rs_page_size) : ReservedSpace() {643initialize(r_size, rs_align, rs_page_size, /*requested address*/ NULL, /*executable*/ true);644MemTracker::record_virtual_memory_type((address)base(), mtCode);645}646647// VirtualSpace648649VirtualSpace::VirtualSpace() {650_low_boundary = NULL;651_high_boundary = NULL;652_low = NULL;653_high = NULL;654_lower_high = NULL;655_middle_high = NULL;656_upper_high = NULL;657_lower_high_boundary = NULL;658_middle_high_boundary = NULL;659_upper_high_boundary = NULL;660_lower_alignment = 0;661_middle_alignment = 0;662_upper_alignment = 0;663_special = false;664_executable = false;665}666667668bool VirtualSpace::initialize(ReservedSpace rs, size_t committed_size) {669const size_t max_commit_granularity = os::page_size_for_region_unaligned(rs.size(), 1);670return initialize_with_granularity(rs, committed_size, max_commit_granularity);671}672673bool VirtualSpace::initialize_with_granularity(ReservedSpace rs, size_t committed_size, size_t max_commit_granularity) {674if(!rs.is_reserved()) return false; // allocation failed.675assert(_low_boundary == NULL, "VirtualSpace already initialized");676assert(max_commit_granularity > 0, "Granularity must be non-zero.");677678_low_boundary = rs.base();679_high_boundary = low_boundary() + rs.size();680681_low = low_boundary();682_high = low();683684_special = rs.special();685_executable = rs.executable();686687// When a VirtualSpace begins life at a large size, make all future expansion688// and shrinking occur aligned to a granularity of large pages. This avoids689// fragmentation of physical addresses that inhibits the use of large pages690// by the OS virtual memory system. Empirically, we see that with a 4MB691// page size, the only spaces that get handled this way are codecache and692// the heap itself, both of which provide a substantial performance693// boost in many benchmarks when covered by large pages.694//695// No attempt is made to force large page alignment at the very top and696// bottom of the space if they are not aligned so already.697_lower_alignment = os::vm_page_size();698_middle_alignment = max_commit_granularity;699_upper_alignment = os::vm_page_size();700701// End of each region702_lower_high_boundary = align_up(low_boundary(), middle_alignment());703_middle_high_boundary = align_down(high_boundary(), middle_alignment());704_upper_high_boundary = high_boundary();705706// High address of each region707_lower_high = low_boundary();708_middle_high = lower_high_boundary();709_upper_high = middle_high_boundary();710711// commit to initial size712if (committed_size > 0) {713if (!expand_by(committed_size)) {714return false;715}716}717return true;718}719720721VirtualSpace::~VirtualSpace() {722release();723}724725726void VirtualSpace::release() {727// This does not release memory it reserved.728// Caller must release via rs.release();729_low_boundary = NULL;730_high_boundary = NULL;731_low = NULL;732_high = NULL;733_lower_high = NULL;734_middle_high = NULL;735_upper_high = NULL;736_lower_high_boundary = NULL;737_middle_high_boundary = NULL;738_upper_high_boundary = NULL;739_lower_alignment = 0;740_middle_alignment = 0;741_upper_alignment = 0;742_special = false;743_executable = false;744}745746747size_t VirtualSpace::committed_size() const {748return pointer_delta(high(), low(), sizeof(char));749}750751752size_t VirtualSpace::reserved_size() const {753return pointer_delta(high_boundary(), low_boundary(), sizeof(char));754}755756757size_t VirtualSpace::uncommitted_size() const {758return reserved_size() - committed_size();759}760761size_t VirtualSpace::actual_committed_size() const {762// Special VirtualSpaces commit all reserved space up front.763if (special()) {764return reserved_size();765}766767size_t committed_low = pointer_delta(_lower_high, _low_boundary, sizeof(char));768size_t committed_middle = pointer_delta(_middle_high, _lower_high_boundary, sizeof(char));769size_t committed_high = pointer_delta(_upper_high, _middle_high_boundary, sizeof(char));770771#ifdef ASSERT772size_t lower = pointer_delta(_lower_high_boundary, _low_boundary, sizeof(char));773size_t middle = pointer_delta(_middle_high_boundary, _lower_high_boundary, sizeof(char));774size_t upper = pointer_delta(_upper_high_boundary, _middle_high_boundary, sizeof(char));775776if (committed_high > 0) {777assert(committed_low == lower, "Must be");778assert(committed_middle == middle, "Must be");779}780781if (committed_middle > 0) {782assert(committed_low == lower, "Must be");783}784if (committed_middle < middle) {785assert(committed_high == 0, "Must be");786}787788if (committed_low < lower) {789assert(committed_high == 0, "Must be");790assert(committed_middle == 0, "Must be");791}792#endif793794return committed_low + committed_middle + committed_high;795}796797798bool VirtualSpace::contains(const void* p) const {799return low() <= (const char*) p && (const char*) p < high();800}801802static void pretouch_expanded_memory(void* start, void* end) {803assert(is_aligned(start, os::vm_page_size()), "Unexpected alignment");804assert(is_aligned(end, os::vm_page_size()), "Unexpected alignment");805806os::pretouch_memory(start, end);807}808809static bool commit_expanded(char* start, size_t size, size_t alignment, bool pre_touch, bool executable) {810if (os::commit_memory(start, size, alignment, executable)) {811if (pre_touch || AlwaysPreTouch) {812pretouch_expanded_memory(start, start + size);813}814return true;815}816817debug_only(warning(818"INFO: os::commit_memory(" PTR_FORMAT ", " PTR_FORMAT819" size=" SIZE_FORMAT ", executable=%d) failed",820p2i(start), p2i(start + size), size, executable);)821822return false;823}824825/*826First we need to determine if a particular virtual space is using large827pages. This is done at the initialize function and only virtual spaces828that are larger than LargePageSizeInBytes use large pages. Once we829have determined this, all expand_by and shrink_by calls must grow and830shrink by large page size chunks. If a particular request831is within the current large page, the call to commit and uncommit memory832can be ignored. In the case that the low and high boundaries of this833space is not large page aligned, the pages leading to the first large834page address and the pages after the last large page address must be835allocated with default pages.836*/837bool VirtualSpace::expand_by(size_t bytes, bool pre_touch) {838if (uncommitted_size() < bytes) {839return false;840}841842if (special()) {843// don't commit memory if the entire space is pinned in memory844_high += bytes;845return true;846}847848char* previous_high = high();849char* unaligned_new_high = high() + bytes;850assert(unaligned_new_high <= high_boundary(), "cannot expand by more than upper boundary");851852// Calculate where the new high for each of the regions should be. If853// the low_boundary() and high_boundary() are LargePageSizeInBytes aligned854// then the unaligned lower and upper new highs would be the855// lower_high() and upper_high() respectively.856char* unaligned_lower_new_high = MIN2(unaligned_new_high, lower_high_boundary());857char* unaligned_middle_new_high = MIN2(unaligned_new_high, middle_high_boundary());858char* unaligned_upper_new_high = MIN2(unaligned_new_high, upper_high_boundary());859860// Align the new highs based on the regions alignment. lower and upper861// alignment will always be default page size. middle alignment will be862// LargePageSizeInBytes if the actual size of the virtual space is in863// fact larger than LargePageSizeInBytes.864char* aligned_lower_new_high = align_up(unaligned_lower_new_high, lower_alignment());865char* aligned_middle_new_high = align_up(unaligned_middle_new_high, middle_alignment());866char* aligned_upper_new_high = align_up(unaligned_upper_new_high, upper_alignment());867868// Determine which regions need to grow in this expand_by call.869// If you are growing in the lower region, high() must be in that870// region so calculate the size based on high(). For the middle and871// upper regions, determine the starting point of growth based on the872// location of high(). By getting the MAX of the region's low address873// (or the previous region's high address) and high(), we can tell if it874// is an intra or inter region growth.875size_t lower_needs = 0;876if (aligned_lower_new_high > lower_high()) {877lower_needs = pointer_delta(aligned_lower_new_high, lower_high(), sizeof(char));878}879size_t middle_needs = 0;880if (aligned_middle_new_high > middle_high()) {881middle_needs = pointer_delta(aligned_middle_new_high, middle_high(), sizeof(char));882}883size_t upper_needs = 0;884if (aligned_upper_new_high > upper_high()) {885upper_needs = pointer_delta(aligned_upper_new_high, upper_high(), sizeof(char));886}887888// Check contiguity.889assert(low_boundary() <= lower_high() && lower_high() <= lower_high_boundary(),890"high address must be contained within the region");891assert(lower_high_boundary() <= middle_high() && middle_high() <= middle_high_boundary(),892"high address must be contained within the region");893assert(middle_high_boundary() <= upper_high() && upper_high() <= upper_high_boundary(),894"high address must be contained within the region");895896// Commit regions897if (lower_needs > 0) {898assert(lower_high() + lower_needs <= lower_high_boundary(), "must not expand beyond region");899if (!commit_expanded(lower_high(), lower_needs, _lower_alignment, pre_touch, _executable)) {900return false;901}902_lower_high += lower_needs;903}904905if (middle_needs > 0) {906assert(middle_high() + middle_needs <= middle_high_boundary(), "must not expand beyond region");907if (!commit_expanded(middle_high(), middle_needs, _middle_alignment, pre_touch, _executable)) {908return false;909}910_middle_high += middle_needs;911}912913if (upper_needs > 0) {914assert(upper_high() + upper_needs <= upper_high_boundary(), "must not expand beyond region");915if (!commit_expanded(upper_high(), upper_needs, _upper_alignment, pre_touch, _executable)) {916return false;917}918_upper_high += upper_needs;919}920921_high += bytes;922return true;923}924925// A page is uncommitted if the contents of the entire page is deemed unusable.926// Continue to decrement the high() pointer until it reaches a page boundary927// in which case that particular page can now be uncommitted.928void VirtualSpace::shrink_by(size_t size) {929if (committed_size() < size)930fatal("Cannot shrink virtual space to negative size");931932if (special()) {933// don't uncommit if the entire space is pinned in memory934_high -= size;935return;936}937938char* unaligned_new_high = high() - size;939assert(unaligned_new_high >= low_boundary(), "cannot shrink past lower boundary");940941// Calculate new unaligned address942char* unaligned_upper_new_high =943MAX2(unaligned_new_high, middle_high_boundary());944char* unaligned_middle_new_high =945MAX2(unaligned_new_high, lower_high_boundary());946char* unaligned_lower_new_high =947MAX2(unaligned_new_high, low_boundary());948949// Align address to region's alignment950char* aligned_upper_new_high = align_up(unaligned_upper_new_high, upper_alignment());951char* aligned_middle_new_high = align_up(unaligned_middle_new_high, middle_alignment());952char* aligned_lower_new_high = align_up(unaligned_lower_new_high, lower_alignment());953954// Determine which regions need to shrink955size_t upper_needs = 0;956if (aligned_upper_new_high < upper_high()) {957upper_needs =958pointer_delta(upper_high(), aligned_upper_new_high, sizeof(char));959}960size_t middle_needs = 0;961if (aligned_middle_new_high < middle_high()) {962middle_needs =963pointer_delta(middle_high(), aligned_middle_new_high, sizeof(char));964}965size_t lower_needs = 0;966if (aligned_lower_new_high < lower_high()) {967lower_needs =968pointer_delta(lower_high(), aligned_lower_new_high, sizeof(char));969}970971// Check contiguity.972assert(middle_high_boundary() <= upper_high() &&973upper_high() <= upper_high_boundary(),974"high address must be contained within the region");975assert(lower_high_boundary() <= middle_high() &&976middle_high() <= middle_high_boundary(),977"high address must be contained within the region");978assert(low_boundary() <= lower_high() &&979lower_high() <= lower_high_boundary(),980"high address must be contained within the region");981982// Uncommit983if (upper_needs > 0) {984assert(middle_high_boundary() <= aligned_upper_new_high &&985aligned_upper_new_high + upper_needs <= upper_high_boundary(),986"must not shrink beyond region");987if (!os::uncommit_memory(aligned_upper_new_high, upper_needs, _executable)) {988debug_only(warning("os::uncommit_memory failed"));989return;990} else {991_upper_high -= upper_needs;992}993}994if (middle_needs > 0) {995assert(lower_high_boundary() <= aligned_middle_new_high &&996aligned_middle_new_high + middle_needs <= middle_high_boundary(),997"must not shrink beyond region");998if (!os::uncommit_memory(aligned_middle_new_high, middle_needs, _executable)) {999debug_only(warning("os::uncommit_memory failed"));1000return;1001} else {1002_middle_high -= middle_needs;1003}1004}1005if (lower_needs > 0) {1006assert(low_boundary() <= aligned_lower_new_high &&1007aligned_lower_new_high + lower_needs <= lower_high_boundary(),1008"must not shrink beyond region");1009if (!os::uncommit_memory(aligned_lower_new_high, lower_needs, _executable)) {1010debug_only(warning("os::uncommit_memory failed"));1011return;1012} else {1013_lower_high -= lower_needs;1014}1015}10161017_high -= size;1018}10191020#ifndef PRODUCT1021void VirtualSpace::check_for_contiguity() {1022// Check contiguity.1023assert(low_boundary() <= lower_high() &&1024lower_high() <= lower_high_boundary(),1025"high address must be contained within the region");1026assert(lower_high_boundary() <= middle_high() &&1027middle_high() <= middle_high_boundary(),1028"high address must be contained within the region");1029assert(middle_high_boundary() <= upper_high() &&1030upper_high() <= upper_high_boundary(),1031"high address must be contained within the region");1032assert(low() >= low_boundary(), "low");1033assert(low_boundary() <= lower_high_boundary(), "lower high boundary");1034assert(upper_high_boundary() <= high_boundary(), "upper high boundary");1035assert(high() <= upper_high(), "upper high");1036}10371038void VirtualSpace::print_on(outputStream* out) {1039out->print ("Virtual space:");1040if (special()) out->print(" (pinned in memory)");1041out->cr();1042out->print_cr(" - committed: " SIZE_FORMAT, committed_size());1043out->print_cr(" - reserved: " SIZE_FORMAT, reserved_size());1044out->print_cr(" - [low, high]: [" INTPTR_FORMAT ", " INTPTR_FORMAT "]", p2i(low()), p2i(high()));1045out->print_cr(" - [low_b, high_b]: [" INTPTR_FORMAT ", " INTPTR_FORMAT "]", p2i(low_boundary()), p2i(high_boundary()));1046}10471048void VirtualSpace::print() {1049print_on(tty);1050}10511052#endif105310541055