Path: blob/master/src/hotspot/share/memory/heap.cpp
40950 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 "memory/heap.hpp"26#include "oops/oop.inline.hpp"27#include "runtime/os.hpp"28#include "runtime/mutexLocker.hpp"29#include "services/memTracker.hpp"30#include "utilities/align.hpp"31#include "utilities/powerOfTwo.hpp"3233// Implementation of Heap3435CodeHeap::CodeHeap(const char* name, const int code_blob_type)36: _code_blob_type(code_blob_type) {37_name = name;38_number_of_committed_segments = 0;39_number_of_reserved_segments = 0;40_segment_size = 0;41_log2_segment_size = 0;42_next_segment = 0;43_freelist = NULL;44_last_insert_point = NULL;45_freelist_segments = 0;46_freelist_length = 0;47_max_allocated_capacity = 0;48_blob_count = 0;49_nmethod_count = 0;50_adapter_count = 0;51_full_count = 0;52_fragmentation_count = 0;53}5455// Dummy initialization of template array.56char CodeHeap::segmap_template[] = {0};5758// This template array is used to (re)initialize the segmap,59// replacing a 1..254 loop.60void CodeHeap::init_segmap_template() {61assert(free_sentinel == 255, "Segment map logic changed!");62for (int i = 0; i <= free_sentinel; i++) {63segmap_template[i] = i;64}65}6667// The segmap is marked free for that part of the heap68// which has not been allocated yet (beyond _next_segment).69// The range of segments to be marked is given by [beg..end).70// "Allocated" space in this context means there exists a71// HeapBlock or a FreeBlock describing this space.72// This method takes segment map indices as range boundaries73void CodeHeap::mark_segmap_as_free(size_t beg, size_t end) {74assert( beg < _number_of_committed_segments, "interval begin out of bounds");75assert(beg < end && end <= _number_of_committed_segments, "interval end out of bounds");76// Don't do unpredictable things in PRODUCT build77if (beg < end) {78// setup _segmap pointers for faster indexing79address p = (address)_segmap.low() + beg;80address q = (address)_segmap.low() + end;81// initialize interval82memset(p, free_sentinel, q-p);83}84}8586// Don't get confused here.87// All existing blocks, no matter if they are used() or free(),88// have their segmap marked as used. This allows to find the89// block header (HeapBlock or FreeBlock) for any pointer90// within the allocated range (upper limit: _next_segment).91// This method takes segment map indices as range boundaries.92// The range of segments to be marked is given by [beg..end).93void CodeHeap::mark_segmap_as_used(size_t beg, size_t end, bool is_FreeBlock_join) {94assert( beg < _number_of_committed_segments, "interval begin out of bounds");95assert(beg < end && end <= _number_of_committed_segments, "interval end out of bounds");96// Don't do unpredictable things in PRODUCT build97if (beg < end) {98// setup _segmap pointers for faster indexing99address p = (address)_segmap.low() + beg;100address q = (address)_segmap.low() + end;101// initialize interval102// If we are joining two free blocks, the segmap range for each103// block is consistent. To create a consistent segmap range for104// the blocks combined, we have three choices:105// 1 - Do a full init from beg to end. Not very efficient because106// the segmap range for the left block is potentially initialized107// over and over again.108// 2 - Carry over the last segmap element value of the left block109// and initialize the segmap range of the right block starting110// with that value. Saves initializing the left block's segmap111// over and over again. Very efficient if FreeBlocks mostly112// are appended to the right.113// 3 - Take full advantage of the segmap being almost correct with114// the two blocks combined. Lets assume the left block consists115// of m segments. The the segmap looks like116// ... (m-2) (m-1) (m) 0 1 2 3 ...117// By substituting the '0' by '1', we create a valid, but118// suboptimal, segmap range covering the two blocks combined.119// We introduced an extra hop for the find_block_for() iteration.120//121// When this method is called with is_FreeBlock_join == true, the122// segmap index beg must select the first segment of the right block.123// Otherwise, it has to select the first segment of the left block.124// Variant 3 is used for all FreeBlock joins.125if (is_FreeBlock_join && (beg > 0)) {126#ifndef PRODUCT127FreeBlock* pBlock = (FreeBlock*)block_at(beg);128assert(beg + pBlock->length() == end, "Internal error: (%d - %d) != %d", (unsigned int)end, (unsigned int)beg, (unsigned int)(pBlock->length()));129assert(*p == 0, "Begin index does not select a block start segment, *p = %2.2x", *p);130#endif131// If possible, extend the previous hop.132if (*(p-1) < (free_sentinel-1)) {133*p = *(p-1) + 1;134} else {135*p = 1;136}137if (_fragmentation_count++ >= fragmentation_limit) {138defrag_segmap(true);139_fragmentation_count = 0;140}141} else {142size_t n_bulk = free_sentinel-1; // bulk processing uses template indices [1..254].143// Use shortcut for blocks <= 255 segments.144// Special case bulk processing: [0..254].145if ((end - beg) <= n_bulk) {146memcpy(p, &segmap_template[0], end - beg);147} else {148*p++ = 0; // block header marker149while (p < q) {150if ((p+n_bulk) <= q) {151memcpy(p, &segmap_template[1], n_bulk);152p += n_bulk;153} else {154memcpy(p, &segmap_template[1], q-p);155p = q;156}157}158}159}160}161}162163void CodeHeap::invalidate(size_t beg, size_t end, size_t hdr_size) {164#ifndef PRODUCT165// Fill the given range with some bad value.166// length is expected to be in segment_size units.167// This prevents inadvertent execution of code leftover from previous use.168char* p = low_boundary() + segments_to_size(beg) + hdr_size;169memset(p, badCodeHeapNewVal, segments_to_size(end-beg)-hdr_size);170#endif171}172173void CodeHeap::clear(size_t beg, size_t end) {174mark_segmap_as_free(beg, end);175invalidate(beg, end, 0);176}177178void CodeHeap::clear() {179_next_segment = 0;180clear(_next_segment, _number_of_committed_segments);181}182183184static size_t align_to_page_size(size_t size) {185const size_t alignment = (size_t)os::vm_page_size();186assert(is_power_of_2(alignment), "no kidding ???");187return (size + alignment - 1) & ~(alignment - 1);188}189190191void CodeHeap::on_code_mapping(char* base, size_t size) {192#ifdef LINUX193extern void linux_wrap_code(char* base, size_t size);194linux_wrap_code(base, size);195#endif196}197198199bool CodeHeap::reserve(ReservedSpace rs, size_t committed_size, size_t segment_size) {200assert(rs.size() >= committed_size, "reserved < committed");201assert(segment_size >= sizeof(FreeBlock), "segment size is too small");202assert(is_power_of_2(segment_size), "segment_size must be a power of 2");203assert_locked_or_safepoint(CodeCache_lock);204205_segment_size = segment_size;206_log2_segment_size = exact_log2(segment_size);207208// Reserve and initialize space for _memory.209const size_t page_size = rs.page_size();210const size_t granularity = os::vm_allocation_granularity();211const size_t c_size = align_up(committed_size, page_size);212assert(c_size <= rs.size(), "alignment made committed size to large");213214os::trace_page_sizes(_name, c_size, rs.size(), page_size,215rs.base(), rs.size());216if (!_memory.initialize(rs, c_size)) {217return false;218}219220on_code_mapping(_memory.low(), _memory.committed_size());221_number_of_committed_segments = size_to_segments(_memory.committed_size());222_number_of_reserved_segments = size_to_segments(_memory.reserved_size());223assert(_number_of_reserved_segments >= _number_of_committed_segments, "just checking");224const size_t reserved_segments_alignment = MAX2((size_t)os::vm_page_size(), granularity);225const size_t reserved_segments_size = align_up(_number_of_reserved_segments, reserved_segments_alignment);226const size_t committed_segments_size = align_to_page_size(_number_of_committed_segments);227228// reserve space for _segmap229ReservedSpace seg_rs(reserved_segments_size);230if (!_segmap.initialize(seg_rs, committed_segments_size)) {231return false;232}233234MemTracker::record_virtual_memory_type((address)_segmap.low_boundary(), mtCode);235236assert(_segmap.committed_size() >= (size_t) _number_of_committed_segments, "could not commit enough space for segment map");237assert(_segmap.reserved_size() >= (size_t) _number_of_reserved_segments , "could not reserve enough space for segment map");238assert(_segmap.reserved_size() >= _segmap.committed_size() , "just checking");239240// initialize remaining instance variables, heap memory and segmap241clear();242init_segmap_template();243return true;244}245246247bool CodeHeap::expand_by(size_t size) {248assert_locked_or_safepoint(CodeCache_lock);249250// expand _memory space251size_t dm = align_to_page_size(_memory.committed_size() + size) - _memory.committed_size();252if (dm > 0) {253// Use at least the available uncommitted space if 'size' is larger254if (_memory.uncommitted_size() != 0 && dm > _memory.uncommitted_size()) {255dm = _memory.uncommitted_size();256}257char* base = _memory.low() + _memory.committed_size();258if (!_memory.expand_by(dm)) return false;259on_code_mapping(base, dm);260size_t i = _number_of_committed_segments;261_number_of_committed_segments = size_to_segments(_memory.committed_size());262assert(_number_of_reserved_segments == size_to_segments(_memory.reserved_size()), "number of reserved segments should not change");263assert(_number_of_reserved_segments >= _number_of_committed_segments, "just checking");264// expand _segmap space265size_t ds = align_to_page_size(_number_of_committed_segments) - _segmap.committed_size();266if ((ds > 0) && !_segmap.expand_by(ds)) {267return false;268}269assert(_segmap.committed_size() >= (size_t) _number_of_committed_segments, "just checking");270// initialize additional space (heap memory and segmap)271clear(i, _number_of_committed_segments);272}273return true;274}275276277void* CodeHeap::allocate(size_t instance_size) {278size_t number_of_segments = size_to_segments(instance_size + header_size());279assert(segments_to_size(number_of_segments) >= sizeof(FreeBlock), "not enough room for FreeList");280assert_locked_or_safepoint(CodeCache_lock);281282// First check if we can satisfy request from freelist283NOT_PRODUCT(verify());284HeapBlock* block = search_freelist(number_of_segments);285NOT_PRODUCT(verify());286287if (block != NULL) {288assert(!block->free(), "must not be marked free");289guarantee((char*) block >= _memory.low_boundary() && (char*) block < _memory.high(),290"The newly allocated block " INTPTR_FORMAT " is not within the heap "291"starting with " INTPTR_FORMAT " and ending with " INTPTR_FORMAT,292p2i(block), p2i(_memory.low_boundary()), p2i(_memory.high()));293_max_allocated_capacity = MAX2(_max_allocated_capacity, allocated_capacity());294_blob_count++;295return block->allocated_space();296}297298// Ensure minimum size for allocation to the heap.299number_of_segments = MAX2((int)CodeCacheMinBlockLength, (int)number_of_segments);300301if (_next_segment + number_of_segments <= _number_of_committed_segments) {302mark_segmap_as_used(_next_segment, _next_segment + number_of_segments, false);303block = block_at(_next_segment);304block->initialize(number_of_segments);305_next_segment += number_of_segments;306guarantee((char*) block >= _memory.low_boundary() && (char*) block < _memory.high(),307"The newly allocated block " INTPTR_FORMAT " is not within the heap "308"starting with " INTPTR_FORMAT " and ending with " INTPTR_FORMAT,309p2i(block), p2i(_memory.low_boundary()), p2i(_memory.high()));310_max_allocated_capacity = MAX2(_max_allocated_capacity, allocated_capacity());311_blob_count++;312return block->allocated_space();313} else {314return NULL;315}316}317318// Split the given block into two at the given segment.319// This is helpful when a block was allocated too large320// to trim off the unused space at the end (interpreter).321// It also helps with splitting a large free block during allocation.322// Usage state (used or free) must be set by caller since323// we don't know if the resulting blocks will be used or free.324// split_at is the segment number (relative to segment_for(b))325// where the split happens. The segment with relative326// number split_at is the first segment of the split-off block.327HeapBlock* CodeHeap::split_block(HeapBlock *b, size_t split_at) {328if (b == NULL) return NULL;329// After the split, both blocks must have a size of at least CodeCacheMinBlockLength330assert((split_at >= CodeCacheMinBlockLength) && (split_at + CodeCacheMinBlockLength <= b->length()),331"split position(%d) out of range [0..%d]", (int)split_at, (int)b->length());332size_t split_segment = segment_for(b) + split_at;333size_t b_size = b->length();334size_t newb_size = b_size - split_at;335336HeapBlock* newb = block_at(split_segment);337newb->set_length(newb_size);338mark_segmap_as_used(segment_for(newb), segment_for(newb) + newb_size, false);339b->set_length(split_at);340return newb;341}342343void CodeHeap::deallocate_tail(void* p, size_t used_size) {344assert(p == find_start(p), "illegal deallocation");345assert_locked_or_safepoint(CodeCache_lock);346347// Find start of HeapBlock348HeapBlock* b = (((HeapBlock *)p) - 1);349assert(b->allocated_space() == p, "sanity check");350351size_t actual_number_of_segments = b->length();352size_t used_number_of_segments = size_to_segments(used_size + header_size());353size_t unused_number_of_segments = actual_number_of_segments - used_number_of_segments;354guarantee(used_number_of_segments <= actual_number_of_segments, "Must be!");355356HeapBlock* f = split_block(b, used_number_of_segments);357add_to_freelist(f);358NOT_PRODUCT(verify());359}360361void CodeHeap::deallocate(void* p) {362assert(p == find_start(p), "illegal deallocation");363assert_locked_or_safepoint(CodeCache_lock);364365// Find start of HeapBlock366HeapBlock* b = (((HeapBlock *)p) - 1);367assert(b->allocated_space() == p, "sanity check");368guarantee((char*) b >= _memory.low_boundary() && (char*) b < _memory.high(),369"The block to be deallocated " INTPTR_FORMAT " is not within the heap "370"starting with " INTPTR_FORMAT " and ending with " INTPTR_FORMAT,371p2i(b), p2i(_memory.low_boundary()), p2i(_memory.high()));372add_to_freelist(b);373NOT_PRODUCT(verify());374}375376/**377* The segment map is used to quickly find the the start (header) of a378* code block (e.g. nmethod) when only a pointer to a location inside the379* code block is known. This works as follows:380* - The storage reserved for the code heap is divided into 'segments'.381* - The size of a segment is determined by -XX:CodeCacheSegmentSize=<#bytes>.382* - The size must be a power of two to allow the use of shift operations383* to quickly convert between segment index and segment address.384* - Segment start addresses should be aligned to be multiples of CodeCacheSegmentSize.385* - It seems beneficial for CodeCacheSegmentSize to be equal to os::page_size().386* - Allocation in the code cache can only happen at segment start addresses.387* - Allocation in the code cache is in units of CodeCacheSegmentSize.388* - A pointer in the code cache can be mapped to a segment by calling389* segment_for(addr).390* - The segment map is a byte array where array element [i] is related391* to the i-th segment in the code heap.392* - Each time memory is allocated/deallocated from the code cache,393* the segment map is updated accordingly.394* Note: deallocation does not cause the memory to become "free", as395* indicated by the segment map state "free_sentinel". Deallocation396* just changes the block state from "used" to "free".397* - Elements of the segment map (byte) array are interpreted398* as unsigned integer.399* - Element values normally identify an offset backwards (in segment400* size units) from the associated segment towards the start of401* the block.402* - Some values have a special meaning:403* 0 - This segment is the start of a block (HeapBlock or FreeBlock).404* 255 - The free_sentinel value. This is a free segment, i.e. it is405* not yet allocated and thus does not belong to any block.406* - The value of the current element has to be subtracted from the407* current index to get closer to the start.408* - If the value of the then current element is zero, the block start409* segment is found and iteration stops. Otherwise, start over with the410* previous step.411*412* The following example illustrates a possible state of code cache413* and the segment map: (seg -> segment, nm ->nmethod)414*415* code cache segmap416* ----------- ---------417* seg 1 | nm 1 | -> | 0 |418* seg 2 | nm 1 | -> | 1 |419* ... | nm 1 | -> | .. |420* seg m-1 | nm 1 | -> | m-1 |421* seg m | nm 2 | -> | 0 |422* seg m+1 | nm 2 | -> | 1 |423* ... | nm 2 | -> | 2 |424* ... | nm 2 | -> | .. |425* ... | nm 2 | -> | 0xFE | (free_sentinel-1)426* ... | nm 2 | -> | 1 |427* seg m+n | nm 2 | -> | 2 |428* ... | nm 2 | -> | |429*430* How to read:431* A value of '0' in the segmap indicates that this segment contains the432* beginning of a CodeHeap block. Let's walk through a simple example:433*434* We want to find the start of the block that contains nm 1, and we are435* given a pointer that points into segment m-2. We then read the value436* of segmap[m-2]. The value is an offset that points to the segment437* which contains the start of the block.438*439* Another example: We want to locate the start of nm 2, and we happen to440* get a pointer that points into seg m+n. We first read seg[n+m], which441* returns '2'. So we have to update our segment map index (ix -= segmap[n+m])442* and start over.443*/444445// Find block which contains the passed pointer,446// regardless of the block being used or free.447// NULL is returned if anything invalid is detected.448void* CodeHeap::find_block_for(void* p) const {449// Check the pointer to be in committed range.450if (!contains(p)) {451return NULL;452}453454address seg_map = (address)_segmap.low();455size_t seg_idx = segment_for(p);456457// This may happen in special cases. Just ignore.458// Example: PPC ICache stub generation.459if (is_segment_unused(seg_map[seg_idx])) {460return NULL;461}462463// Iterate the segment map chain to find the start of the block.464while (seg_map[seg_idx] > 0) {465// Don't check each segment index to refer to a used segment.466// This method is called extremely often. Therefore, any checking467// has a significant impact on performance. Rely on CodeHeap::verify()468// to do the job on request.469seg_idx -= (int)seg_map[seg_idx];470}471472return address_for(seg_idx);473}474475// Find block which contains the passed pointer.476// The block must be used, i.e. must not be a FreeBlock.477// Return a pointer that points past the block header.478void* CodeHeap::find_start(void* p) const {479HeapBlock* h = (HeapBlock*)find_block_for(p);480return ((h == NULL) || h->free()) ? NULL : h->allocated_space();481}482483// Find block which contains the passed pointer.484// Same as find_start(p), but with additional safety net.485CodeBlob* CodeHeap::find_blob_unsafe(void* start) const {486CodeBlob* result = (CodeBlob*)CodeHeap::find_start(start);487return (result != NULL && result->blob_contains((address)start)) ? result : NULL;488}489490size_t CodeHeap::alignment_unit() const {491// this will be a power of two492return _segment_size;493}494495496size_t CodeHeap::alignment_offset() const {497// The lowest address in any allocated block will be498// equal to alignment_offset (mod alignment_unit).499return sizeof(HeapBlock) & (_segment_size - 1);500}501502// Returns the current block if available and used.503// If not, it returns the subsequent block (if available), NULL otherwise.504// Free blocks are merged, therefore there is at most one free block505// between two used ones. As a result, the subsequent block (if available) is506// guaranteed to be used.507// The returned pointer points past the block header.508void* CodeHeap::next_used(HeapBlock* b) const {509if (b != NULL && b->free()) b = next_block(b);510assert(b == NULL || !b->free(), "must be in use or at end of heap");511return (b == NULL) ? NULL : b->allocated_space();512}513514// Returns the first used HeapBlock515// The returned pointer points to the block header.516HeapBlock* CodeHeap::first_block() const {517if (_next_segment > 0)518return block_at(0);519return NULL;520}521522// The returned pointer points to the block header.523HeapBlock* CodeHeap::block_start(void* q) const {524HeapBlock* b = (HeapBlock*)find_start(q);525if (b == NULL) return NULL;526return b - 1;527}528529// Returns the next Heap block.530// The returned pointer points to the block header.531HeapBlock* CodeHeap::next_block(HeapBlock *b) const {532if (b == NULL) return NULL;533size_t i = segment_for(b) + b->length();534if (i < _next_segment)535return block_at(i);536return NULL;537}538539540// Returns current capacity541size_t CodeHeap::capacity() const {542return _memory.committed_size();543}544545size_t CodeHeap::max_capacity() const {546return _memory.reserved_size();547}548549int CodeHeap::allocated_segments() const {550return (int)_next_segment;551}552553size_t CodeHeap::allocated_capacity() const {554// size of used heap - size on freelist555return segments_to_size(_next_segment - _freelist_segments);556}557558// Returns size of the unallocated heap block559size_t CodeHeap::heap_unallocated_capacity() const {560// Total number of segments - number currently used561return segments_to_size(_number_of_reserved_segments - _next_segment);562}563564// Free list management565566FreeBlock* CodeHeap::following_block(FreeBlock *b) {567return (FreeBlock*)(((address)b) + _segment_size * b->length());568}569570// Inserts block b after a571void CodeHeap::insert_after(FreeBlock* a, FreeBlock* b) {572assert(a != NULL && b != NULL, "must be real pointers");573574// Link b into the list after a575b->set_link(a->link());576a->set_link(b);577578// See if we can merge blocks579merge_right(b); // Try to make b bigger580merge_right(a); // Try to make a include b581}582583// Try to merge this block with the following block584bool CodeHeap::merge_right(FreeBlock* a) {585assert(a->free(), "must be a free block");586if (following_block(a) == a->link()) {587assert(a->link() != NULL && a->link()->free(), "must be free too");588589// Remember linked (following) block. invalidate should only zap header of this block.590size_t follower = segment_for(a->link());591// Merge block a to include the following block.592a->set_length(a->length() + a->link()->length());593a->set_link(a->link()->link());594595// Update the segment map and invalidate block contents.596mark_segmap_as_used(follower, segment_for(a) + a->length(), true);597// Block contents has already been invalidated by add_to_freelist.598// What's left is the header of the following block which now is599// in the middle of the merged block. Just zap one segment.600invalidate(follower, follower + 1, 0);601602_freelist_length--;603return true;604}605return false;606}607608609void CodeHeap::add_to_freelist(HeapBlock* a) {610FreeBlock* b = (FreeBlock*)a;611size_t bseg = segment_for(b);612_freelist_length++;613614_blob_count--;615assert(_blob_count >= 0, "sanity");616617assert(b != _freelist, "cannot be removed twice");618619// Mark as free and update free space count620_freelist_segments += b->length();621b->set_free();622invalidate(bseg, bseg + b->length(), sizeof(FreeBlock));623624// First element in list?625if (_freelist == NULL) {626b->set_link(NULL);627_freelist = b;628return;629}630631// Since the freelist is ordered (smaller addresses -> larger addresses) and the632// element we want to insert into the freelist has a smaller address than the first633// element, we can simply add 'b' as the first element and we are done.634if (b < _freelist) {635// Insert first in list636b->set_link(_freelist);637_freelist = b;638merge_right(_freelist);639return;640}641642// Scan for right place to put into list.643// List is sorted by increasing addresses.644FreeBlock* prev = _freelist;645FreeBlock* cur = _freelist->link();646if ((_freelist_length > freelist_limit) && (_last_insert_point != NULL)) {647_last_insert_point = (FreeBlock*)find_block_for(_last_insert_point);648if ((_last_insert_point != NULL) && _last_insert_point->free() && (_last_insert_point < b)) {649prev = _last_insert_point;650cur = prev->link();651}652}653while(cur != NULL && cur < b) {654assert(prev < cur, "Freelist must be ordered");655prev = cur;656cur = cur->link();657}658assert((prev < b) && (cur == NULL || b < cur), "free-list must be ordered");659insert_after(prev, b);660_last_insert_point = prev;661}662663/**664* Search freelist for an entry on the list with the best fit.665* @return NULL, if no one was found666*/667HeapBlock* CodeHeap::search_freelist(size_t length) {668FreeBlock* found_block = NULL;669FreeBlock* found_prev = NULL;670size_t found_length = _next_segment; // max it out to begin with671672HeapBlock* res = NULL;673FreeBlock* prev = NULL;674FreeBlock* cur = _freelist;675676length = length < CodeCacheMinBlockLength ? CodeCacheMinBlockLength : length;677678// Search for best-fitting block679while(cur != NULL) {680size_t cur_length = cur->length();681if (cur_length == length) {682// We have a perfect fit683found_block = cur;684found_prev = prev;685found_length = cur_length;686break;687} else if ((cur_length > length) && (cur_length < found_length)) {688// This is a new, closer fit. Remember block, its previous element, and its length689found_block = cur;690found_prev = prev;691found_length = cur_length;692}693// Next element in list694prev = cur;695cur = cur->link();696}697698if (found_block == NULL) {699// None found700return NULL;701}702703// Exact (or at least good enough) fit. Remove from list.704// Don't leave anything on the freelist smaller than CodeCacheMinBlockLength.705if (found_length - length < CodeCacheMinBlockLength) {706_freelist_length--;707length = found_length;708if (found_prev == NULL) {709assert(_freelist == found_block, "sanity check");710_freelist = _freelist->link();711} else {712assert((found_prev->link() == found_block), "sanity check");713// Unmap element714found_prev->set_link(found_block->link());715}716res = (HeapBlock*)found_block;717// sizeof(HeapBlock) < sizeof(FreeBlock).718// Invalidate the additional space that FreeBlock occupies.719// The rest of the block should already be invalidated.720// This is necessary due to a dubious assert in nmethod.cpp(PcDescCache::reset_to()).721// Can't use invalidate() here because it works on segment_size units (too coarse).722DEBUG_ONLY(memset((void*)res->allocated_space(), badCodeHeapNewVal, sizeof(FreeBlock) - sizeof(HeapBlock)));723} else {724// Truncate the free block and return the truncated part725// as new HeapBlock. The remaining free block does not726// need to be updated, except for it's length. Truncating727// the segment map does not invalidate the leading part.728res = split_block(found_block, found_length - length);729}730731res->set_used();732_freelist_segments -= length;733return res;734}735736int CodeHeap::defrag_segmap(bool do_defrag) {737int extra_hops_used = 0;738int extra_hops_free = 0;739int blocks_used = 0;740int blocks_free = 0;741for(HeapBlock* h = first_block(); h != NULL; h = next_block(h)) {742size_t beg = segment_for(h);743size_t end = segment_for(h) + h->length();744int extra_hops = segmap_hops(beg, end);745if (h->free()) {746extra_hops_free += extra_hops;747blocks_free++;748} else {749extra_hops_used += extra_hops;750blocks_used++;751}752if (do_defrag && (extra_hops > 0)) {753mark_segmap_as_used(beg, end, false);754}755}756return extra_hops_used + extra_hops_free;757}758759// Count the hops required to get from the last segment of a760// heap block to the block header segment. For the optimal case,761// #hops = ((#segments-1)+(free_sentinel-2))/(free_sentinel-1)762// The range of segments to be checked is given by [beg..end).763// Return the number of extra hops required. There may be extra hops764// due to the is_FreeBlock_join optimization in mark_segmap_as_used().765int CodeHeap::segmap_hops(size_t beg, size_t end) {766if (beg < end) {767// setup _segmap pointers for faster indexing768address p = (address)_segmap.low() + beg;769int hops_expected770= checked_cast<int>(((end-beg-1)+(free_sentinel-2))/(free_sentinel-1));771int nhops = 0;772size_t ix = end-beg-1;773while (p[ix] > 0) {774ix -= p[ix];775nhops++;776}777return (nhops > hops_expected) ? nhops - hops_expected : 0;778}779return 0;780}781782//----------------------------------------------------------------------------783// Non-product code784785#ifndef PRODUCT786787void CodeHeap::print() {788tty->print_cr("The Heap");789}790791void CodeHeap::verify() {792if (VerifyCodeCache) {793assert_locked_or_safepoint(CodeCache_lock);794size_t len = 0;795int count = 0;796for(FreeBlock* b = _freelist; b != NULL; b = b->link()) {797len += b->length();798count++;799// Check if we have merged all free blocks800assert(merge_right(b) == false, "Missed merging opportunity");801}802// Verify that freelist contains the right amount of free space803assert(len == _freelist_segments, "wrong freelist");804805for(HeapBlock* h = first_block(); h != NULL; h = next_block(h)) {806if (h->free()) count--;807}808// Verify that the freelist contains the same number of blocks809// than free blocks found on the full list.810assert(count == 0, "missing free blocks");811812//---< all free block memory must have been invalidated >---813for(FreeBlock* b = _freelist; b != NULL; b = b->link()) {814for (char* c = (char*)b + sizeof(FreeBlock); c < (char*)b + segments_to_size(b->length()); c++) {815assert(*c == (char)badCodeHeapNewVal, "FreeBlock@" PTR_FORMAT "(" PTR_FORMAT ") not invalidated @byte %d", p2i(b), b->length(), (int)(c - (char*)b));816}817}818819address seg_map = (address)_segmap.low();820size_t nseg = 0;821int extra_hops = 0;822count = 0;823for(HeapBlock* b = first_block(); b != NULL; b = next_block(b)) {824size_t seg1 = segment_for(b);825size_t segn = seg1 + b->length();826extra_hops += segmap_hops(seg1, segn);827count++;828for (size_t i = seg1; i < segn; i++) {829nseg++;830//---< Verify segment map marking >---831// All allocated segments, no matter if in a free or used block,832// must be marked "in use".833assert(!is_segment_unused(seg_map[i]), "CodeHeap: unused segment. seg_map[%d]([%d..%d]) = %d, %s block", (int)i, (int)seg1, (int)segn, seg_map[i], b->free()? "free":"used");834assert((unsigned char)seg_map[i] < free_sentinel, "CodeHeap: seg_map[%d]([%d..%d]) = %d (out of range)", (int)i, (int)seg1, (int)segn, seg_map[i]);835}836}837assert(nseg == _next_segment, "CodeHeap: segment count mismatch. found %d, expected %d.", (int)nseg, (int)_next_segment);838assert(extra_hops <= _fragmentation_count, "CodeHeap: extra hops wrong. fragmentation: %d, extra hops: %d.", _fragmentation_count, extra_hops);839if (extra_hops >= (16 + 2 * count)) {840warning("CodeHeap: many extra hops due to optimization. blocks: %d, extra hops: %d.", count, extra_hops);841}842843// Verify that the number of free blocks is not out of hand.844static int free_block_threshold = 10000;845if (count > free_block_threshold) {846warning("CodeHeap: # of free blocks > %d", free_block_threshold);847// Double the warning limit848free_block_threshold *= 2;849}850}851}852853#endif854855856