1 /*
   2  * Copyright (c) 1997, 2019, Oracle and/or its affiliates. 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 it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 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 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  *
  23  */
  24 
  25 #include "precompiled.hpp"
  26 #include "memory/heap.hpp"
  27 #include "oops/oop.inline.hpp"
  28 #include "runtime/os.hpp"
  29 #include "services/memTracker.hpp"
  30 #include "utilities/align.hpp"
  31 #include "utilities/powerOfTwo.hpp"
  32 
  33 size_t CodeHeap::header_size() {
  34   return sizeof(HeapBlock);
  35 }
  36 
  37 
  38 // Implementation of Heap
  39 
  40 CodeHeap::CodeHeap(const char* name, const int code_blob_type)
  41   : _code_blob_type(code_blob_type) {
  42   _name                         = name;
  43   _number_of_committed_segments = 0;
  44   _number_of_reserved_segments  = 0;
  45   _segment_size                 = 0;
  46   _log2_segment_size            = 0;
  47   _next_segment                 = 0;
  48   _freelist                     = NULL;
  49   _last_insert_point            = NULL;
  50   _freelist_segments            = 0;
  51   _freelist_length              = 0;
  52   _max_allocated_capacity       = 0;
  53   _blob_count                   = 0;
  54   _nmethod_count                = 0;
  55   _adapter_count                = 0;
  56   _full_count                   = 0;
  57   _fragmentation_count          = 0;
  58 }
  59 
  60 // Dummy initialization of template array.
  61 char CodeHeap::segmap_template[] = {0};
  62 
  63 // This template array is used to (re)initialize the segmap,
  64 // replacing a 1..254 loop.
  65 void CodeHeap::init_segmap_template() {
  66   assert(free_sentinel == 255, "Segment map logic changed!");
  67   for (int i = 0; i <= free_sentinel; i++) {
  68     segmap_template[i] = i;
  69   }
  70 }
  71 
  72 // The segmap is marked free for that part of the heap
  73 // which has not been allocated yet (beyond _next_segment).
  74 // The range of segments to be marked is given by [beg..end).
  75 // "Allocated" space in this context means there exists a
  76 // HeapBlock or a FreeBlock describing this space.
  77 // This method takes segment map indices as range boundaries
  78 void CodeHeap::mark_segmap_as_free(size_t beg, size_t end) {
  79   assert(             beg <  _number_of_committed_segments, "interval begin out of bounds");
  80   assert(beg < end && end <= _number_of_committed_segments, "interval end   out of bounds");
  81   // Don't do unpredictable things in PRODUCT build
  82   if (beg < end) {
  83     // setup _segmap pointers for faster indexing
  84     address p = (address)_segmap.low() + beg;
  85     address q = (address)_segmap.low() + end;
  86     // initialize interval
  87     memset(p, free_sentinel, q-p);
  88   }
  89 }
  90 
  91 // Don't get confused here.
  92 // All existing blocks, no matter if they are used() or free(),
  93 // have their segmap marked as used. This allows to find the
  94 // block header (HeapBlock or FreeBlock) for any pointer
  95 // within the allocated range (upper limit: _next_segment).
  96 // This method takes segment map indices as range boundaries.
  97 // The range of segments to be marked is given by [beg..end).
  98 void CodeHeap::mark_segmap_as_used(size_t beg, size_t end, bool is_FreeBlock_join) {
  99   assert(             beg <  _number_of_committed_segments, "interval begin out of bounds");
 100   assert(beg < end && end <= _number_of_committed_segments, "interval end   out of bounds");
 101   // Don't do unpredictable things in PRODUCT build
 102   if (beg < end) {
 103     // setup _segmap pointers for faster indexing
 104     address p = (address)_segmap.low() + beg;
 105     address q = (address)_segmap.low() + end;
 106     // initialize interval
 107     // If we are joining two free blocks, the segmap range for each
 108     // block is consistent. To create a consistent segmap range for
 109     // the blocks combined, we have three choices:
 110     //  1 - Do a full init from beg to end. Not very efficient because
 111     //      the segmap range for the left block is potentially initialized
 112     //      over and over again.
 113     //  2 - Carry over the last segmap element value of the left block
 114     //      and initialize the segmap range of the right block starting
 115     //      with that value. Saves initializing the left block's segmap
 116     //      over and over again. Very efficient if FreeBlocks mostly
 117     //      are appended to the right.
 118     //  3 - Take full advantage of the segmap being almost correct with
 119     //      the two blocks combined. Lets assume the left block consists
 120     //      of m segments. The the segmap looks like
 121     //        ... (m-2) (m-1) (m) 0  1  2  3 ...
 122     //      By substituting the '0' by '1', we create a valid, but
 123     //      suboptimal, segmap range covering the two blocks combined.
 124     //      We introduced an extra hop for the find_block_for() iteration.
 125     //
 126     // When this method is called with is_FreeBlock_join == true, the
 127     // segmap index beg must select the first segment of the right block.
 128     // Otherwise, it has to select the first segment of the left block.
 129     // Variant 3 is used for all FreeBlock joins.
 130     if (is_FreeBlock_join && (beg > 0)) {
 131 #ifndef PRODUCT
 132       FreeBlock* pBlock = (FreeBlock*)block_at(beg);
 133       assert(beg + pBlock->length() == end, "Internal error: (%d - %d) != %d", (unsigned int)end, (unsigned int)beg, (unsigned int)(pBlock->length()));
 134       assert(*p == 0, "Begin index does not select a block start segment, *p = %2.2x", *p);
 135 #endif
 136       // If possible, extend the previous hop.
 137       if (*(p-1) < (free_sentinel-1)) {
 138         *p = *(p-1) + 1;
 139       } else {
 140         *p = 1;
 141       }
 142       if (_fragmentation_count++ >= fragmentation_limit) {
 143         defrag_segmap(true);
 144         _fragmentation_count = 0;
 145       }
 146     } else {
 147       size_t n_bulk = free_sentinel-1; // bulk processing uses template indices [1..254].
 148       // Use shortcut for blocks <= 255 segments.
 149       // Special case bulk processing: [0..254].
 150       if ((end - beg) <= n_bulk) {
 151         memcpy(p, &segmap_template[0], end - beg);
 152       } else {
 153         *p++  = 0;  // block header marker
 154         while (p < q) {
 155           if ((p+n_bulk) <= q) {
 156             memcpy(p, &segmap_template[1], n_bulk);
 157             p += n_bulk;
 158           } else {
 159             memcpy(p, &segmap_template[1], q-p);
 160             p = q;
 161           }
 162         }
 163       }
 164     }
 165   }
 166 }
 167 
 168 void CodeHeap::invalidate(size_t beg, size_t end, size_t hdr_size) {
 169 #ifndef PRODUCT
 170   // Fill the given range with some bad value.
 171   // length is expected to be in segment_size units.
 172   // This prevents inadvertent execution of code leftover from previous use.
 173   char* p = low_boundary() + segments_to_size(beg) + hdr_size;
 174   memset(p, badCodeHeapNewVal, segments_to_size(end-beg)-hdr_size);
 175 #endif
 176 }
 177 
 178 void CodeHeap::clear(size_t beg, size_t end) {
 179   mark_segmap_as_free(beg, end);
 180   invalidate(beg, end, 0);
 181 }
 182 
 183 void CodeHeap::clear() {
 184   _next_segment = 0;
 185   clear(_next_segment, _number_of_committed_segments);
 186 }
 187 
 188 
 189 static size_t align_to_page_size(size_t size) {
 190   const size_t alignment = (size_t)os::vm_page_size();
 191   assert(is_power_of_2(alignment), "no kidding ???");
 192   return (size + alignment - 1) & ~(alignment - 1);
 193 }
 194 
 195 
 196 void CodeHeap::on_code_mapping(char* base, size_t size) {
 197 #ifdef LINUX
 198   extern void linux_wrap_code(char* base, size_t size);
 199   linux_wrap_code(base, size);
 200 #endif
 201 }
 202 
 203 
 204 bool CodeHeap::reserve(ReservedSpace rs, size_t committed_size, size_t segment_size) {
 205   assert(rs.size() >= committed_size, "reserved < committed");
 206   assert(segment_size >= sizeof(FreeBlock), "segment size is too small");
 207   assert(is_power_of_2(segment_size), "segment_size must be a power of 2");
 208   assert_locked_or_safepoint(CodeCache_lock);
 209 
 210   _segment_size      = segment_size;
 211   _log2_segment_size = exact_log2(segment_size);
 212 
 213   // Reserve and initialize space for _memory.
 214   size_t page_size = os::vm_page_size();
 215   if (os::can_execute_large_page_memory()) {
 216     const size_t min_pages = 8;
 217     page_size = MIN2(os::page_size_for_region_aligned(committed_size, min_pages),
 218                      os::page_size_for_region_aligned(rs.size(), min_pages));
 219   }
 220 
 221   const size_t granularity = os::vm_allocation_granularity();
 222   const size_t c_size = align_up(committed_size, page_size);
 223 
 224   os::trace_page_sizes(_name, committed_size, rs.size(), page_size,
 225                        rs.base(), rs.size());
 226   if (!_memory.initialize(rs, c_size)) {
 227     return false;
 228   }
 229 
 230   on_code_mapping(_memory.low(), _memory.committed_size());
 231   _number_of_committed_segments = size_to_segments(_memory.committed_size());
 232   _number_of_reserved_segments  = size_to_segments(_memory.reserved_size());
 233   assert(_number_of_reserved_segments >= _number_of_committed_segments, "just checking");
 234   const size_t reserved_segments_alignment = MAX2((size_t)os::vm_page_size(), granularity);
 235   const size_t reserved_segments_size = align_up(_number_of_reserved_segments, reserved_segments_alignment);
 236   const size_t committed_segments_size = align_to_page_size(_number_of_committed_segments);
 237 
 238   // reserve space for _segmap
 239   if (!_segmap.initialize(reserved_segments_size, committed_segments_size)) {
 240     return false;
 241   }
 242 
 243   MemTracker::record_virtual_memory_type((address)_segmap.low_boundary(), mtCode);
 244 
 245   assert(_segmap.committed_size() >= (size_t) _number_of_committed_segments, "could not commit  enough space for segment map");
 246   assert(_segmap.reserved_size()  >= (size_t) _number_of_reserved_segments , "could not reserve enough space for segment map");
 247   assert(_segmap.reserved_size()  >= _segmap.committed_size()     , "just checking");
 248 
 249   // initialize remaining instance variables, heap memory and segmap
 250   clear();
 251   init_segmap_template();
 252   return true;
 253 }
 254 
 255 
 256 bool CodeHeap::expand_by(size_t size) {
 257   assert_locked_or_safepoint(CodeCache_lock);
 258 
 259   // expand _memory space
 260   size_t dm = align_to_page_size(_memory.committed_size() + size) - _memory.committed_size();
 261   if (dm > 0) {
 262     // Use at least the available uncommitted space if 'size' is larger
 263     if (_memory.uncommitted_size() != 0 && dm > _memory.uncommitted_size()) {
 264       dm = _memory.uncommitted_size();
 265     }
 266     char* base = _memory.low() + _memory.committed_size();
 267     if (!_memory.expand_by(dm)) return false;
 268     on_code_mapping(base, dm);
 269     size_t i = _number_of_committed_segments;
 270     _number_of_committed_segments = size_to_segments(_memory.committed_size());
 271     assert(_number_of_reserved_segments == size_to_segments(_memory.reserved_size()), "number of reserved segments should not change");
 272     assert(_number_of_reserved_segments >= _number_of_committed_segments, "just checking");
 273     // expand _segmap space
 274     size_t ds = align_to_page_size(_number_of_committed_segments) - _segmap.committed_size();
 275     if ((ds > 0) && !_segmap.expand_by(ds)) {
 276       return false;
 277     }
 278     assert(_segmap.committed_size() >= (size_t) _number_of_committed_segments, "just checking");
 279     // initialize additional space (heap memory and segmap)
 280     clear(i, _number_of_committed_segments);
 281   }
 282   return true;
 283 }
 284 
 285 
 286 void* CodeHeap::allocate(size_t instance_size) {
 287   size_t number_of_segments = size_to_segments(instance_size + header_size());
 288   assert(segments_to_size(number_of_segments) >= sizeof(FreeBlock), "not enough room for FreeList");
 289   assert_locked_or_safepoint(CodeCache_lock);
 290 
 291   // First check if we can satisfy request from freelist
 292   NOT_PRODUCT(verify());
 293   HeapBlock* block = search_freelist(number_of_segments);
 294   NOT_PRODUCT(verify());
 295 
 296   if (block != NULL) {
 297     assert(!block->free(), "must not be marked free");
 298     guarantee((char*) block >= _memory.low_boundary() && (char*) block < _memory.high(),
 299               "The newly allocated block " INTPTR_FORMAT " is not within the heap "
 300               "starting with "  INTPTR_FORMAT " and ending with "  INTPTR_FORMAT,
 301               p2i(block), p2i(_memory.low_boundary()), p2i(_memory.high()));
 302     _max_allocated_capacity = MAX2(_max_allocated_capacity, allocated_capacity());
 303     _blob_count++;
 304     return block->allocated_space();
 305   }
 306 
 307   // Ensure minimum size for allocation to the heap.
 308   number_of_segments = MAX2((int)CodeCacheMinBlockLength, (int)number_of_segments);
 309 
 310   if (_next_segment + number_of_segments <= _number_of_committed_segments) {
 311     mark_segmap_as_used(_next_segment, _next_segment + number_of_segments, false);
 312     block = block_at(_next_segment);
 313     block->initialize(number_of_segments);
 314     _next_segment += number_of_segments;
 315     guarantee((char*) block >= _memory.low_boundary() && (char*) block < _memory.high(),
 316               "The newly allocated block " INTPTR_FORMAT " is not within the heap "
 317               "starting with "  INTPTR_FORMAT " and ending with " INTPTR_FORMAT,
 318               p2i(block), p2i(_memory.low_boundary()), p2i(_memory.high()));
 319     _max_allocated_capacity = MAX2(_max_allocated_capacity, allocated_capacity());
 320     _blob_count++;
 321     return block->allocated_space();
 322   } else {
 323     return NULL;
 324   }
 325 }
 326 
 327 // Split the given block into two at the given segment.
 328 // This is helpful when a block was allocated too large
 329 // to trim off the unused space at the end (interpreter).
 330 // It also helps with splitting a large free block during allocation.
 331 // Usage state (used or free) must be set by caller since
 332 // we don't know if the resulting blocks will be used or free.
 333 // split_at is the segment number (relative to segment_for(b))
 334 //          where the split happens. The segment with relative
 335 //          number split_at is the first segment of the split-off block.
 336 HeapBlock* CodeHeap::split_block(HeapBlock *b, size_t split_at) {
 337   if (b == NULL) return NULL;
 338   // After the split, both blocks must have a size of at least CodeCacheMinBlockLength
 339   assert((split_at >= CodeCacheMinBlockLength) && (split_at + CodeCacheMinBlockLength <= b->length()),
 340          "split position(%d) out of range [0..%d]", (int)split_at, (int)b->length());
 341   size_t split_segment = segment_for(b) + split_at;
 342   size_t b_size        = b->length();
 343   size_t newb_size     = b_size - split_at;
 344 
 345   HeapBlock* newb = block_at(split_segment);
 346   newb->set_length(newb_size);
 347   mark_segmap_as_used(segment_for(newb), segment_for(newb) + newb_size, false);
 348   b->set_length(split_at);
 349   return newb;
 350 }
 351 
 352 void CodeHeap::deallocate_tail(void* p, size_t used_size) {
 353   assert(p == find_start(p), "illegal deallocation");
 354   assert_locked_or_safepoint(CodeCache_lock);
 355 
 356   // Find start of HeapBlock
 357   HeapBlock* b = (((HeapBlock *)p) - 1);
 358   assert(b->allocated_space() == p, "sanity check");
 359 
 360   size_t actual_number_of_segments = b->length();
 361   size_t used_number_of_segments   = size_to_segments(used_size + header_size());
 362   size_t unused_number_of_segments = actual_number_of_segments - used_number_of_segments;
 363   guarantee(used_number_of_segments <= actual_number_of_segments, "Must be!");
 364 
 365   HeapBlock* f = split_block(b, used_number_of_segments);
 366   add_to_freelist(f);
 367   NOT_PRODUCT(verify());
 368 }
 369 
 370 void CodeHeap::deallocate(void* p) {
 371   assert(p == find_start(p), "illegal deallocation");
 372   assert_locked_or_safepoint(CodeCache_lock);
 373 
 374   // Find start of HeapBlock
 375   HeapBlock* b = (((HeapBlock *)p) - 1);
 376   assert(b->allocated_space() == p, "sanity check");
 377   guarantee((char*) b >= _memory.low_boundary() && (char*) b < _memory.high(),
 378             "The block to be deallocated " INTPTR_FORMAT " is not within the heap "
 379             "starting with "  INTPTR_FORMAT " and ending with " INTPTR_FORMAT,
 380             p2i(b), p2i(_memory.low_boundary()), p2i(_memory.high()));
 381   add_to_freelist(b);
 382   NOT_PRODUCT(verify());
 383 }
 384 
 385 /**
 386  * The segment map is used to quickly find the the start (header) of a
 387  * code block (e.g. nmethod) when only a pointer to a location inside the
 388  * code block is known. This works as follows:
 389  *  - The storage reserved for the code heap is divided into 'segments'.
 390  *  - The size of a segment is determined by -XX:CodeCacheSegmentSize=<#bytes>.
 391  *  - The size must be a power of two to allow the use of shift operations
 392  *    to quickly convert between segment index and segment address.
 393  *  - Segment start addresses should be aligned to be multiples of CodeCacheSegmentSize.
 394  *  - It seems beneficial for CodeCacheSegmentSize to be equal to os::page_size().
 395  *  - Allocation in the code cache can only happen at segment start addresses.
 396  *  - Allocation in the code cache is in units of CodeCacheSegmentSize.
 397  *  - A pointer in the code cache can be mapped to a segment by calling
 398  *    segment_for(addr).
 399  *  - The segment map is a byte array where array element [i] is related
 400  *    to the i-th segment in the code heap.
 401  *  - Each time memory is allocated/deallocated from the code cache,
 402  *    the segment map is updated accordingly.
 403  *    Note: deallocation does not cause the memory to become "free", as
 404  *          indicated by the segment map state "free_sentinel". Deallocation
 405  *          just changes the block state from "used" to "free".
 406  *  - Elements of the segment map (byte) array are interpreted
 407  *    as unsigned integer.
 408  *  - Element values normally identify an offset backwards (in segment
 409  *    size units) from the associated segment towards the start of
 410  *    the block.
 411  *  - Some values have a special meaning:
 412  *       0 - This segment is the start of a block (HeapBlock or FreeBlock).
 413  *     255 - The free_sentinel value. This is a free segment, i.e. it is
 414  *           not yet allocated and thus does not belong to any block.
 415  *  - The value of the current element has to be subtracted from the
 416  *    current index to get closer to the start.
 417  *  - If the value of the then current element is zero, the block start
 418  *    segment is found and iteration stops. Otherwise, start over with the
 419  *    previous step.
 420  *
 421  *    The following example illustrates a possible state of code cache
 422  *    and the segment map: (seg -> segment, nm ->nmethod)
 423  *
 424  *          code cache          segmap
 425  *         -----------        ---------
 426  * seg 1   | nm 1    |   ->   | 0     |
 427  * seg 2   | nm 1    |   ->   | 1     |
 428  * ...     | nm 1    |   ->   | ..    |
 429  * seg m-1 | nm 1    |   ->   | m-1   |
 430  * seg m   | nm 2    |   ->   | 0     |
 431  * seg m+1 | nm 2    |   ->   | 1     |
 432  * ...     | nm 2    |   ->   | 2     |
 433  * ...     | nm 2    |   ->   | ..    |
 434  * ...     | nm 2    |   ->   | 0xFE  | (free_sentinel-1)
 435  * ...     | nm 2    |   ->   | 1     |
 436  * seg m+n | nm 2    |   ->   | 2     |
 437  * ...     | nm 2    |   ->   |       |
 438  *
 439  * How to read:
 440  * A value of '0' in the segmap indicates that this segment contains the
 441  * beginning of a CodeHeap block. Let's walk through a simple example:
 442  *
 443  * We want to find the start of the block that contains nm 1, and we are
 444  * given a pointer that points into segment m-2. We then read the value
 445  * of segmap[m-2]. The value is an offset that points to the segment
 446  * which contains the start of the block.
 447  *
 448  * Another example: We want to locate the start of nm 2, and we happen to
 449  * get a pointer that points into seg m+n. We first read seg[n+m], which
 450  * returns '2'. So we have to update our segment map index (ix -= segmap[n+m])
 451  * and start over.
 452  */
 453 
 454 // Find block which contains the passed pointer,
 455 // regardless of the block being used or free.
 456 // NULL is returned if anything invalid is detected.
 457 void* CodeHeap::find_block_for(void* p) const {
 458   // Check the pointer to be in committed range.
 459   if (!contains(p)) {
 460     return NULL;
 461   }
 462 
 463   address seg_map = (address)_segmap.low();
 464   size_t  seg_idx = segment_for(p);
 465 
 466   // This may happen in special cases. Just ignore.
 467   // Example: PPC ICache stub generation.
 468   if (is_segment_unused(seg_map[seg_idx])) {
 469     return NULL;
 470   }
 471 
 472   // Iterate the segment map chain to find the start of the block.
 473   while (seg_map[seg_idx] > 0) {
 474     // Don't check each segment index to refer to a used segment.
 475     // This method is called extremely often. Therefore, any checking
 476     // has a significant impact on performance. Rely on CodeHeap::verify()
 477     // to do the job on request.
 478     seg_idx -= (int)seg_map[seg_idx];
 479   }
 480 
 481   return address_for(seg_idx);
 482 }
 483 
 484 // Find block which contains the passed pointer.
 485 // The block must be used, i.e. must not be a FreeBlock.
 486 // Return a pointer that points past the block header.
 487 void* CodeHeap::find_start(void* p) const {
 488   HeapBlock* h = (HeapBlock*)find_block_for(p);
 489   return ((h == NULL) || h->free()) ? NULL : h->allocated_space();
 490 }
 491 
 492 // Find block which contains the passed pointer.
 493 // Same as find_start(p), but with additional safety net.
 494 CodeBlob* CodeHeap::find_blob_unsafe(void* start) const {
 495   CodeBlob* result = (CodeBlob*)CodeHeap::find_start(start);
 496   return (result != NULL && result->blob_contains((address)start)) ? result : NULL;
 497 }
 498 
 499 size_t CodeHeap::alignment_unit() const {
 500   // this will be a power of two
 501   return _segment_size;
 502 }
 503 
 504 
 505 size_t CodeHeap::alignment_offset() const {
 506   // The lowest address in any allocated block will be
 507   // equal to alignment_offset (mod alignment_unit).
 508   return sizeof(HeapBlock) & (_segment_size - 1);
 509 }
 510 
 511 // Returns the current block if available and used.
 512 // If not, it returns the subsequent block (if available), NULL otherwise.
 513 // Free blocks are merged, therefore there is at most one free block
 514 // between two used ones. As a result, the subsequent block (if available) is
 515 // guaranteed to be used.
 516 // The returned pointer points past the block header.
 517 void* CodeHeap::next_used(HeapBlock* b) const {
 518   if (b != NULL && b->free()) b = next_block(b);
 519   assert(b == NULL || !b->free(), "must be in use or at end of heap");
 520   return (b == NULL) ? NULL : b->allocated_space();
 521 }
 522 
 523 // Returns the first used HeapBlock
 524 // The returned pointer points to the block header.
 525 HeapBlock* CodeHeap::first_block() const {
 526   if (_next_segment > 0)
 527     return block_at(0);
 528   return NULL;
 529 }
 530 
 531 // The returned pointer points to the block header.
 532 HeapBlock* CodeHeap::block_start(void* q) const {
 533   HeapBlock* b = (HeapBlock*)find_start(q);
 534   if (b == NULL) return NULL;
 535   return b - 1;
 536 }
 537 
 538 // Returns the next Heap block.
 539 // The returned pointer points to the block header.
 540 HeapBlock* CodeHeap::next_block(HeapBlock *b) const {
 541   if (b == NULL) return NULL;
 542   size_t i = segment_for(b) + b->length();
 543   if (i < _next_segment)
 544     return block_at(i);
 545   return NULL;
 546 }
 547 
 548 
 549 // Returns current capacity
 550 size_t CodeHeap::capacity() const {
 551   return _memory.committed_size();
 552 }
 553 
 554 size_t CodeHeap::max_capacity() const {
 555   return _memory.reserved_size();
 556 }
 557 
 558 int CodeHeap::allocated_segments() const {
 559   return (int)_next_segment;
 560 }
 561 
 562 size_t CodeHeap::allocated_capacity() const {
 563   // size of used heap - size on freelist
 564   return segments_to_size(_next_segment - _freelist_segments);
 565 }
 566 
 567 // Returns size of the unallocated heap block
 568 size_t CodeHeap::heap_unallocated_capacity() const {
 569   // Total number of segments - number currently used
 570   return segments_to_size(_number_of_reserved_segments - _next_segment);
 571 }
 572 
 573 // Free list management
 574 
 575 FreeBlock* CodeHeap::following_block(FreeBlock *b) {
 576   return (FreeBlock*)(((address)b) + _segment_size * b->length());
 577 }
 578 
 579 // Inserts block b after a
 580 void CodeHeap::insert_after(FreeBlock* a, FreeBlock* b) {
 581   assert(a != NULL && b != NULL, "must be real pointers");
 582 
 583   // Link b into the list after a
 584   b->set_link(a->link());
 585   a->set_link(b);
 586 
 587   // See if we can merge blocks
 588   merge_right(b); // Try to make b bigger
 589   merge_right(a); // Try to make a include b
 590 }
 591 
 592 // Try to merge this block with the following block
 593 bool CodeHeap::merge_right(FreeBlock* a) {
 594   assert(a->free(), "must be a free block");
 595   if (following_block(a) == a->link()) {
 596     assert(a->link() != NULL && a->link()->free(), "must be free too");
 597 
 598     // Remember linked (following) block. invalidate should only zap header of this block.
 599     size_t follower = segment_for(a->link());
 600     // Merge block a to include the following block.
 601     a->set_length(a->length() + a->link()->length());
 602     a->set_link(a->link()->link());
 603 
 604     // Update the segment map and invalidate block contents.
 605     mark_segmap_as_used(follower, segment_for(a) + a->length(), true);
 606     // Block contents has already been invalidated by add_to_freelist.
 607     // What's left is the header of the following block which now is
 608     // in the middle of the merged block. Just zap one segment.
 609     invalidate(follower, follower + 1, 0);
 610 
 611     _freelist_length--;
 612     return true;
 613   }
 614   return false;
 615 }
 616 
 617 
 618 void CodeHeap::add_to_freelist(HeapBlock* a) {
 619   FreeBlock* b = (FreeBlock*)a;
 620   size_t  bseg = segment_for(b);
 621   _freelist_length++;
 622 
 623   _blob_count--;
 624   assert(_blob_count >= 0, "sanity");
 625 
 626   assert(b != _freelist, "cannot be removed twice");
 627 
 628   // Mark as free and update free space count
 629   _freelist_segments += b->length();
 630   b->set_free();
 631   invalidate(bseg, bseg + b->length(), sizeof(FreeBlock));
 632 
 633   // First element in list?
 634   if (_freelist == NULL) {
 635     b->set_link(NULL);
 636     _freelist = b;
 637     return;
 638   }
 639 
 640   // Since the freelist is ordered (smaller addresses -> larger addresses) and the
 641   // element we want to insert into the freelist has a smaller address than the first
 642   // element, we can simply add 'b' as the first element and we are done.
 643   if (b < _freelist) {
 644     // Insert first in list
 645     b->set_link(_freelist);
 646     _freelist = b;
 647     merge_right(_freelist);
 648     return;
 649   }
 650 
 651   // Scan for right place to put into list.
 652   // List is sorted by increasing addresses.
 653   FreeBlock* prev = _freelist;
 654   FreeBlock* cur  = _freelist->link();
 655   if ((_freelist_length > freelist_limit) && (_last_insert_point != NULL)) {
 656     _last_insert_point = (FreeBlock*)find_block_for(_last_insert_point);
 657     if ((_last_insert_point != NULL) && _last_insert_point->free() && (_last_insert_point < b)) {
 658       prev = _last_insert_point;
 659       cur  = prev->link();
 660     }
 661   }
 662   while(cur != NULL && cur < b) {
 663     assert(prev < cur, "Freelist must be ordered");
 664     prev = cur;
 665     cur  = cur->link();
 666   }
 667   assert((prev < b) && (cur == NULL || b < cur), "free-list must be ordered");
 668   insert_after(prev, b);
 669   _last_insert_point = prev;
 670 }
 671 
 672 /**
 673  * Search freelist for an entry on the list with the best fit.
 674  * @return NULL, if no one was found
 675  */
 676 HeapBlock* CodeHeap::search_freelist(size_t length) {
 677   FreeBlock* found_block  = NULL;
 678   FreeBlock* found_prev   = NULL;
 679   size_t     found_length = _next_segment; // max it out to begin with
 680 
 681   HeapBlock* res  = NULL;
 682   FreeBlock* prev = NULL;
 683   FreeBlock* cur  = _freelist;
 684 
 685   length = length < CodeCacheMinBlockLength ? CodeCacheMinBlockLength : length;
 686 
 687   // Search for best-fitting block
 688   while(cur != NULL) {
 689     size_t cur_length = cur->length();
 690     if (cur_length == length) {
 691       // We have a perfect fit
 692       found_block  = cur;
 693       found_prev   = prev;
 694       found_length = cur_length;
 695       break;
 696     } else if ((cur_length > length) && (cur_length < found_length)) {
 697       // This is a new, closer fit. Remember block, its previous element, and its length
 698       found_block  = cur;
 699       found_prev   = prev;
 700       found_length = cur_length;
 701     }
 702     // Next element in list
 703     prev = cur;
 704     cur  = cur->link();
 705   }
 706 
 707   if (found_block == NULL) {
 708     // None found
 709     return NULL;
 710   }
 711 
 712   // Exact (or at least good enough) fit. Remove from list.
 713   // Don't leave anything on the freelist smaller than CodeCacheMinBlockLength.
 714   if (found_length - length < CodeCacheMinBlockLength) {
 715     _freelist_length--;
 716     length = found_length;
 717     if (found_prev == NULL) {
 718       assert(_freelist == found_block, "sanity check");
 719       _freelist = _freelist->link();
 720     } else {
 721       assert((found_prev->link() == found_block), "sanity check");
 722       // Unmap element
 723       found_prev->set_link(found_block->link());
 724     }
 725     res = (HeapBlock*)found_block;
 726     // sizeof(HeapBlock) < sizeof(FreeBlock).
 727     // Invalidate the additional space that FreeBlock occupies.
 728     // The rest of the block should already be invalidated.
 729     // This is necessary due to a dubious assert in nmethod.cpp(PcDescCache::reset_to()).
 730     // Can't use invalidate() here because it works on segment_size units (too coarse).
 731     DEBUG_ONLY(memset((void*)res->allocated_space(), badCodeHeapNewVal, sizeof(FreeBlock) - sizeof(HeapBlock)));
 732   } else {
 733     // Truncate the free block and return the truncated part
 734     // as new HeapBlock. The remaining free block does not
 735     // need to be updated, except for it's length. Truncating
 736     // the segment map does not invalidate the leading part.
 737     res = split_block(found_block, found_length - length);
 738   }
 739 
 740   res->set_used();
 741   _freelist_segments -= length;
 742   return res;
 743 }
 744 
 745 int CodeHeap::defrag_segmap(bool do_defrag) {
 746   int extra_hops_used = 0;
 747   int extra_hops_free = 0;
 748   int blocks_used     = 0;
 749   int blocks_free     = 0;
 750   for(HeapBlock* h = first_block(); h != NULL; h = next_block(h)) {
 751     size_t beg = segment_for(h);
 752     size_t end = segment_for(h) + h->length();
 753     int extra_hops = segmap_hops(beg, end);
 754     if (h->free()) {
 755       extra_hops_free += extra_hops;
 756       blocks_free++;
 757     } else {
 758       extra_hops_used += extra_hops;
 759       blocks_used++;
 760     }
 761     if (do_defrag && (extra_hops > 0)) {
 762       mark_segmap_as_used(beg, end, false);
 763     }
 764   }
 765   return extra_hops_used + extra_hops_free;
 766 }
 767 
 768 // Count the hops required to get from the last segment of a
 769 // heap block to the block header segment. For the optimal case,
 770 //   #hops = ((#segments-1)+(free_sentinel-2))/(free_sentinel-1)
 771 // The range of segments to be checked is given by [beg..end).
 772 // Return the number of extra hops required. There may be extra hops
 773 // due to the is_FreeBlock_join optimization in mark_segmap_as_used().
 774 int CodeHeap::segmap_hops(size_t beg, size_t end) {
 775   if (beg < end) {
 776     // setup _segmap pointers for faster indexing
 777     address p = (address)_segmap.low() + beg;
 778     int hops_expected = (int)(((end-beg-1)+(free_sentinel-2))/(free_sentinel-1));
 779     int nhops = 0;
 780     size_t ix = end-beg-1;
 781     while (p[ix] > 0) {
 782       ix -= p[ix];
 783       nhops++;
 784     }
 785     return (nhops > hops_expected) ? nhops - hops_expected : 0;
 786   }
 787   return 0;
 788 }
 789 
 790 //----------------------------------------------------------------------------
 791 // Non-product code
 792 
 793 #ifndef PRODUCT
 794 
 795 void CodeHeap::print() {
 796   tty->print_cr("The Heap");
 797 }
 798 
 799 void CodeHeap::verify() {
 800   if (VerifyCodeCache) {
 801     assert_locked_or_safepoint(CodeCache_lock);
 802     size_t len = 0;
 803     int count = 0;
 804     for(FreeBlock* b = _freelist; b != NULL; b = b->link()) {
 805       len += b->length();
 806       count++;
 807       // Check if we have merged all free blocks
 808       assert(merge_right(b) == false, "Missed merging opportunity");
 809     }
 810     // Verify that freelist contains the right amount of free space
 811     assert(len == _freelist_segments, "wrong freelist");
 812 
 813     for(HeapBlock* h = first_block(); h != NULL; h = next_block(h)) {
 814       if (h->free()) count--;
 815     }
 816     // Verify that the freelist contains the same number of blocks
 817     // than free blocks found on the full list.
 818     assert(count == 0, "missing free blocks");
 819 
 820     //---<  all free block memory must have been invalidated  >---
 821     for(FreeBlock* b = _freelist; b != NULL; b = b->link()) {
 822       for (char* c = (char*)b + sizeof(FreeBlock); c < (char*)b + segments_to_size(b->length()); c++) {
 823         assert(*c == (char)badCodeHeapNewVal, "FreeBlock@" PTR_FORMAT "(" PTR_FORMAT ") not invalidated @byte %d", p2i(b), b->length(), (int)(c - (char*)b));
 824       }
 825     }
 826 
 827     address seg_map = (address)_segmap.low();
 828     size_t  nseg       = 0;
 829     int     extra_hops = 0;
 830     count = 0;
 831     for(HeapBlock* b = first_block(); b != NULL; b = next_block(b)) {
 832       size_t seg1 = segment_for(b);
 833       size_t segn = seg1 + b->length();
 834       extra_hops += segmap_hops(seg1, segn);
 835       count++;
 836       for (size_t i = seg1; i < segn; i++) {
 837         nseg++;
 838         //---<  Verify segment map marking  >---
 839         // All allocated segments, no matter if in a free or used block,
 840         // must be marked "in use".
 841         assert(!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");
 842         assert((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]);
 843       }
 844     }
 845     assert(nseg == _next_segment, "CodeHeap: segment count mismatch. found %d, expected %d.", (int)nseg, (int)_next_segment);
 846     assert((count == 0) || (extra_hops < (16 + 2*count)), "CodeHeap: many extra hops due to optimization. blocks: %d, extra hops: %d.", count, extra_hops);
 847 
 848     // Verify that the number of free blocks is not out of hand.
 849     static int free_block_threshold = 10000;
 850     if (count > free_block_threshold) {
 851       warning("CodeHeap: # of free blocks > %d", free_block_threshold);
 852       // Double the warning limit
 853       free_block_threshold *= 2;
 854     }
 855   }
 856 }
 857 
 858 #endif