1 /*
   2  * Copyright (c) 1997, 2015, 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 
  31 size_t CodeHeap::header_size() {
  32   return sizeof(HeapBlock);
  33 }
  34 
  35 
  36 // Implementation of Heap
  37 
  38 CodeHeap::CodeHeap(const char* name, const int code_blob_type)
  39   : _code_blob_type(code_blob_type) {
  40   _name                         = name;
  41   _number_of_committed_segments = 0;
  42   _number_of_reserved_segments  = 0;
  43   _segment_size                 = 0;
  44   _log2_segment_size            = 0;
  45   _next_segment                 = 0;
  46   _freelist                     = NULL;
  47   _freelist_segments            = 0;
  48   _freelist_length              = 0;
  49   _max_allocated_capacity       = 0;
  50   _blob_count                   = 0;
  51   _nmethod_count                = 0;
  52   _adapter_count                = 0;
  53   _full_count                   = 0;
  54 }
  55 
  56 
  57 void CodeHeap::mark_segmap_as_free(size_t beg, size_t end) {
  58   assert(              beg <  _number_of_committed_segments, "interval begin out of bounds");
  59   assert(beg <  end && end <= _number_of_committed_segments, "interval end   out of bounds");
  60   // setup _segmap pointers for faster indexing
  61   address p = (address)_segmap.low() + beg;
  62   address q = (address)_segmap.low() + end;
  63   // initialize interval
  64   while (p < q) *p++ = free_sentinel;
  65 }
  66 
  67 
  68 void CodeHeap::mark_segmap_as_used(size_t beg, size_t end) {
  69   assert(              beg <  _number_of_committed_segments, "interval begin out of bounds");
  70   assert(beg <  end && end <= _number_of_committed_segments, "interval end   out of bounds");
  71   // setup _segmap pointers for faster indexing
  72   address p = (address)_segmap.low() + beg;
  73   address q = (address)_segmap.low() + end;
  74   // initialize interval
  75   int i = 0;
  76   while (p < q) {
  77     *p++ = i++;
  78     if (i == free_sentinel) i = 1;
  79   }
  80 }
  81 
  82 
  83 static size_t align_to_page_size(size_t size) {
  84   const size_t alignment = (size_t)os::vm_page_size();
  85   assert(is_power_of_2(alignment), "no kidding ???");
  86   return (size + alignment - 1) & ~(alignment - 1);
  87 }
  88 
  89 
  90 void CodeHeap::on_code_mapping(char* base, size_t size) {
  91 #ifdef LINUX
  92   extern void linux_wrap_code(char* base, size_t size);
  93   linux_wrap_code(base, size);
  94 #endif
  95 }
  96 
  97 
  98 bool CodeHeap::reserve(ReservedSpace rs, size_t committed_size, size_t segment_size) {
  99   assert(rs.size() >= committed_size, "reserved < committed");
 100   assert(segment_size >= sizeof(FreeBlock), "segment size is too small");
 101   assert(is_power_of_2(segment_size), "segment_size must be a power of 2");
 102 
 103   _segment_size      = segment_size;
 104   _log2_segment_size = exact_log2(segment_size);
 105 
 106   // Reserve and initialize space for _memory.
 107   size_t page_size = os::vm_page_size();
 108   if (os::can_execute_large_page_memory()) {
 109     const size_t min_pages = 8;
 110     page_size = MIN2(os::page_size_for_region_aligned(committed_size, min_pages),
 111                      os::page_size_for_region_aligned(rs.size(), min_pages));
 112   }
 113 
 114   const size_t granularity = os::vm_allocation_granularity();
 115   const size_t c_size = align_size_up(committed_size, page_size);
 116 
 117   os::trace_page_sizes(_name, committed_size, rs.size(), page_size,
 118                        rs.base(), rs.size());
 119   if (!_memory.initialize(rs, c_size)) {
 120     return false;
 121   }
 122 
 123   on_code_mapping(_memory.low(), _memory.committed_size());
 124   _number_of_committed_segments = size_to_segments(_memory.committed_size());
 125   _number_of_reserved_segments  = size_to_segments(_memory.reserved_size());
 126   assert(_number_of_reserved_segments >= _number_of_committed_segments, "just checking");
 127   const size_t reserved_segments_alignment = MAX2((size_t)os::vm_page_size(), granularity);
 128   const size_t reserved_segments_size = align_size_up(_number_of_reserved_segments, reserved_segments_alignment);
 129   const size_t committed_segments_size = align_to_page_size(_number_of_committed_segments);
 130 
 131   // reserve space for _segmap
 132   if (!_segmap.initialize(reserved_segments_size, committed_segments_size)) {
 133     return false;
 134   }
 135 
 136   MemTracker::record_virtual_memory_type((address)_segmap.low_boundary(), mtCode);
 137 
 138   assert(_segmap.committed_size() >= (size_t) _number_of_committed_segments, "could not commit  enough space for segment map");
 139   assert(_segmap.reserved_size()  >= (size_t) _number_of_reserved_segments , "could not reserve enough space for segment map");
 140   assert(_segmap.reserved_size()  >= _segmap.committed_size()     , "just checking");
 141 
 142   // initialize remaining instance variables
 143   clear();
 144   return true;
 145 }
 146 
 147 
 148 bool CodeHeap::expand_by(size_t size) {
 149   // expand _memory space
 150   size_t dm = align_to_page_size(_memory.committed_size() + size) - _memory.committed_size();
 151   if (dm > 0) {
 152     // Use at least the available uncommitted space if 'size' is larger
 153     if (_memory.uncommitted_size() != 0 && dm > _memory.uncommitted_size()) {
 154       dm = _memory.uncommitted_size();
 155     }
 156     char* base = _memory.low() + _memory.committed_size();
 157     if (!_memory.expand_by(dm)) return false;
 158     on_code_mapping(base, dm);
 159     size_t i = _number_of_committed_segments;
 160     _number_of_committed_segments = size_to_segments(_memory.committed_size());
 161     assert(_number_of_reserved_segments == size_to_segments(_memory.reserved_size()), "number of reserved segments should not change");
 162     assert(_number_of_reserved_segments >= _number_of_committed_segments, "just checking");
 163     // expand _segmap space
 164     size_t ds = align_to_page_size(_number_of_committed_segments) - _segmap.committed_size();
 165     if ((ds > 0) && !_segmap.expand_by(ds)) {
 166       return false;
 167     }
 168     assert(_segmap.committed_size() >= (size_t) _number_of_committed_segments, "just checking");
 169     // initialize additional segmap entries
 170     mark_segmap_as_free(i, _number_of_committed_segments);
 171   }
 172   return true;
 173 }
 174 
 175 void CodeHeap::clear() {
 176   _next_segment = 0;
 177   mark_segmap_as_free(0, _number_of_committed_segments);
 178 }
 179 
 180 
 181 void* CodeHeap::allocate(size_t instance_size) {
 182   size_t number_of_segments = size_to_segments(instance_size + header_size());
 183   assert(segments_to_size(number_of_segments) >= sizeof(FreeBlock), "not enough room for FreeList");
 184 
 185   // First check if we can satisfy request from freelist
 186   NOT_PRODUCT(verify());
 187   HeapBlock* block = search_freelist(number_of_segments);
 188   NOT_PRODUCT(verify());
 189 
 190   if (block != NULL) {
 191     assert(block->length() >= number_of_segments && block->length() < number_of_segments + CodeCacheMinBlockLength, "sanity check");
 192     assert(!block->free(), "must be marked free");
 193     DEBUG_ONLY(memset((void*)block->allocated_space(), badCodeHeapNewVal, instance_size));
 194     _max_allocated_capacity = MAX2(_max_allocated_capacity, allocated_capacity());
 195     _blob_count++;
 196     return block->allocated_space();
 197   }
 198 
 199   // Ensure minimum size for allocation to the heap.
 200   number_of_segments = MAX2((int)CodeCacheMinBlockLength, (int)number_of_segments);
 201 
 202   if (_next_segment + number_of_segments <= _number_of_committed_segments) {
 203     mark_segmap_as_used(_next_segment, _next_segment + number_of_segments);
 204     HeapBlock* b =  block_at(_next_segment);
 205     b->initialize(number_of_segments);
 206     _next_segment += number_of_segments;
 207     DEBUG_ONLY(memset((void *)b->allocated_space(), badCodeHeapNewVal, instance_size));
 208     _max_allocated_capacity = MAX2(_max_allocated_capacity, allocated_capacity());
 209     _blob_count++;
 210     return b->allocated_space();
 211   } else {
 212     return NULL;
 213   }
 214 }
 215 
 216 
 217 void CodeHeap::deallocate(void* p) {
 218   assert(p == find_start(p), "illegal deallocation");
 219   // Find start of HeapBlock
 220   HeapBlock* b = (((HeapBlock *)p) - 1);
 221   assert(b->allocated_space() == p, "sanity check");
 222   DEBUG_ONLY(memset((void *)b->allocated_space(), badCodeHeapFreeVal,
 223              segments_to_size(b->length()) - sizeof(HeapBlock)));
 224   add_to_freelist(b);
 225   NOT_PRODUCT(verify());
 226 }
 227 
 228 /**
 229  * Uses segment map to find the the start (header) of a nmethod. This works as follows:
 230  * The memory of the code cache is divided into 'segments'. The size of a segment is
 231  * determined by -XX:CodeCacheSegmentSize=XX. Allocation in the code cache can only
 232  * happen at segment boundaries. A pointer in the code cache can be mapped to a segment
 233  * by calling segment_for(addr). Each time memory is requested from the code cache,
 234  * the segmap is updated accordingly. See the following example, which illustrates the
 235  * state of code cache and the segment map: (seg -> segment, nm ->nmethod)
 236  *
 237  *          code cache          segmap
 238  *         -----------        ---------
 239  * seg 1   | nm 1    |   ->   | 0     |
 240  * seg 2   | nm 1    |   ->   | 1     |
 241  * ...     | nm 1    |   ->   | ..    |
 242  * seg m   | nm 2    |   ->   | 0     |
 243  * seg m+1 | nm 2    |   ->   | 1     |
 244  * ...     | nm 2    |   ->   | 2     |
 245  * ...     | nm 2    |   ->   | ..    |
 246  * ...     | nm 2    |   ->   | 0xFE  |
 247  * seg m+n | nm 2    |   ->   | 1     |
 248  * ...     | nm 2    |   ->   |       |
 249  *
 250  * A value of '0' in the segmap indicates that this segment contains the beginning of
 251  * an nmethod. Let's walk through a simple example: If we want to find the start of
 252  * an nmethod that falls into seg 2, we read the value of the segmap[2]. The value
 253  * is an offset that points to the segment that contains the start of the nmethod.
 254  * Another example: If we want to get the start of nm 2, and we happen to get a pointer
 255  * that points to seg m+n, we first read seg[n+m], which returns '1'. So we have to
 256  * do one more read of the segmap[m+n-1] to finally get the segment header.
 257  */
 258 void* CodeHeap::find_start(void* p) const {
 259   if (!contains(p)) {
 260     return NULL;
 261   }
 262   size_t seg_idx = segment_for(p);
 263   address seg_map = (address)_segmap.low();
 264   if (is_segment_unused(seg_map[seg_idx])) {
 265     return NULL;
 266   }
 267   while (seg_map[seg_idx] > 0) {
 268     seg_idx -= (int)seg_map[seg_idx];
 269   }
 270 
 271   HeapBlock* h = block_at(seg_idx);
 272   if (h->free()) {
 273     return NULL;
 274   }
 275   return h->allocated_space();
 276 }
 277 
 278 
 279 size_t CodeHeap::alignment_unit() const {
 280   // this will be a power of two
 281   return _segment_size;
 282 }
 283 
 284 
 285 size_t CodeHeap::alignment_offset() const {
 286   // The lowest address in any allocated block will be
 287   // equal to alignment_offset (mod alignment_unit).
 288   return sizeof(HeapBlock) & (_segment_size - 1);
 289 }
 290 
 291 // Returns the current block if available and used.
 292 // If not, it returns the subsequent block (if available), NULL otherwise.
 293 // Free blocks are merged, therefore there is at most one free block
 294 // between two used ones. As a result, the subsequent block (if available) is
 295 // guaranteed to be used.
 296 void* CodeHeap::next_used(HeapBlock* b) const {
 297   if (b != NULL && b->free()) b = next_block(b);
 298   assert(b == NULL || !b->free(), "must be in use or at end of heap");
 299   return (b == NULL) ? NULL : b->allocated_space();
 300 }
 301 
 302 // Returns the first used HeapBlock
 303 HeapBlock* CodeHeap::first_block() const {
 304   if (_next_segment > 0)
 305     return block_at(0);
 306   return NULL;
 307 }
 308 
 309 HeapBlock* CodeHeap::block_start(void* q) const {
 310   HeapBlock* b = (HeapBlock*)find_start(q);
 311   if (b == NULL) return NULL;
 312   return b - 1;
 313 }
 314 
 315 // Returns the next Heap block an offset into one
 316 HeapBlock* CodeHeap::next_block(HeapBlock *b) const {
 317   if (b == NULL) return NULL;
 318   size_t i = segment_for(b) + b->length();
 319   if (i < _next_segment)
 320     return block_at(i);
 321   return NULL;
 322 }
 323 
 324 
 325 // Returns current capacity
 326 size_t CodeHeap::capacity() const {
 327   return _memory.committed_size();
 328 }
 329 
 330 size_t CodeHeap::max_capacity() const {
 331   return _memory.reserved_size();
 332 }
 333 
 334 int CodeHeap::allocated_segments() const {
 335   return (int)_next_segment;
 336 }
 337 
 338 size_t CodeHeap::allocated_capacity() const {
 339   // size of used heap - size on freelist
 340   return segments_to_size(_next_segment - _freelist_segments);
 341 }
 342 
 343 // Returns size of the unallocated heap block
 344 size_t CodeHeap::heap_unallocated_capacity() const {
 345   // Total number of segments - number currently used
 346   return segments_to_size(_number_of_reserved_segments - _next_segment);
 347 }
 348 
 349 // Free list management
 350 
 351 FreeBlock* CodeHeap::following_block(FreeBlock *b) {
 352   return (FreeBlock*)(((address)b) + _segment_size * b->length());
 353 }
 354 
 355 // Inserts block b after a
 356 void CodeHeap::insert_after(FreeBlock* a, FreeBlock* b) {
 357   assert(a != NULL && b != NULL, "must be real pointers");
 358 
 359   // Link b into the list after a
 360   b->set_link(a->link());
 361   a->set_link(b);
 362 
 363   // See if we can merge blocks
 364   merge_right(b); // Try to make b bigger
 365   merge_right(a); // Try to make a include b
 366 }
 367 
 368 // Try to merge this block with the following block
 369 bool CodeHeap::merge_right(FreeBlock* a) {
 370   assert(a->free(), "must be a free block");
 371   if (following_block(a) == a->link()) {
 372     assert(a->link() != NULL && a->link()->free(), "must be free too");
 373     // Update block a to include the following block
 374     a->set_length(a->length() + a->link()->length());
 375     a->set_link(a->link()->link());
 376     // Update find_start map
 377     size_t beg = segment_for(a);
 378     mark_segmap_as_used(beg, beg + a->length());
 379     _freelist_length--;
 380     return true;
 381   }
 382   return false;
 383 }
 384 
 385 
 386 void CodeHeap::add_to_freelist(HeapBlock* a) {
 387   FreeBlock* b = (FreeBlock*)a;
 388   _freelist_length++;
 389 
 390   assert(b != _freelist, "cannot be removed twice");
 391 
 392 
 393   // Mark as free and update free space count
 394   _freelist_segments += b->length();
 395   b->set_free();
 396 
 397   // First element in list?
 398   if (_freelist == NULL) {
 399     _freelist = b;
 400     b->set_link(NULL);
 401     return;
 402   }
 403 
 404   // Since the freelist is ordered (smaller addresses -> larger addresses) and the
 405   // element we want to insert into the freelist has a smaller address than the first
 406   // element, we can simply add 'b' as the first element and we are done.
 407   if (b < _freelist) {
 408     // Insert first in list
 409     b->set_link(_freelist);
 410     _freelist = b;
 411     merge_right(_freelist);
 412     return;
 413   }
 414 
 415   // Scan for right place to put into list. List
 416   // is sorted by increasing addresses
 417   FreeBlock* prev = _freelist;
 418   FreeBlock* cur  = _freelist->link();
 419   while(cur != NULL && cur < b) {
 420     assert(prev < cur, "Freelist must be ordered");
 421     prev = cur;
 422     cur  = cur->link();
 423   }
 424   assert((prev < b) && (cur == NULL || b < cur), "free-list must be ordered");
 425   insert_after(prev, b);
 426 }
 427 
 428 /**
 429  * Search freelist for an entry on the list with the best fit.
 430  * @return NULL, if no one was found
 431  */
 432 FreeBlock* CodeHeap::search_freelist(size_t length) {
 433   FreeBlock* found_block = NULL;
 434   FreeBlock* found_prev  = NULL;
 435   size_t     found_length = 0;
 436 
 437   FreeBlock* prev = NULL;
 438   FreeBlock* cur = _freelist;
 439 
 440   // Search for first block that fits
 441   while(cur != NULL) {
 442     if (cur->length() >= length) {
 443       // Remember block, its previous element, and its length
 444       found_block = cur;
 445       found_prev  = prev;
 446       found_length = found_block->length();
 447 
 448       break;
 449     }
 450     // Next element in list
 451     prev = cur;
 452     cur  = cur->link();
 453   }
 454 
 455   if (found_block == NULL) {
 456     // None found
 457     return NULL;
 458   }
 459 
 460   // Exact (or at least good enough) fit. Remove from list.
 461   // Don't leave anything on the freelist smaller than CodeCacheMinBlockLength.
 462   if (found_length - length < CodeCacheMinBlockLength) {
 463     _freelist_length--;
 464     length = found_length;
 465     if (found_prev == NULL) {
 466       assert(_freelist == found_block, "sanity check");
 467       _freelist = _freelist->link();
 468     } else {
 469       assert((found_prev->link() == found_block), "sanity check");
 470       // Unmap element
 471       found_prev->set_link(found_block->link());
 472     }
 473   } else {
 474     // Truncate block and return a pointer to the following block
 475     // Set used bit and length on new block
 476     found_block->set_length(found_length - length);
 477     found_block = following_block(found_block);
 478 
 479     size_t beg = segment_for(found_block);
 480     mark_segmap_as_used(beg, beg + length);
 481     found_block->set_length(length);
 482   }
 483 
 484   found_block->set_used();
 485   _freelist_segments -= length;
 486   return found_block;
 487 }
 488 
 489 //----------------------------------------------------------------------------
 490 // Non-product code
 491 
 492 #ifndef PRODUCT
 493 
 494 void CodeHeap::print() {
 495   tty->print_cr("The Heap");
 496 }
 497 
 498 void CodeHeap::verify() {
 499   if (VerifyCodeCache) {
 500     size_t len = 0;
 501     int count = 0;
 502     for(FreeBlock* b = _freelist; b != NULL; b = b->link()) {
 503       len += b->length();
 504       count++;
 505       // Check if we have merged all free blocks
 506       assert(merge_right(b) == false, "Missed merging opportunity");
 507     }
 508     // Verify that freelist contains the right amount of free space
 509     assert(len == _freelist_segments, "wrong freelist");
 510 
 511     for(HeapBlock* h = first_block(); h != NULL; h = next_block(h)) {
 512       if (h->free()) count--;
 513     }
 514     // Verify that the freelist contains the same number of blocks
 515     // than free blocks found on the full list.
 516     assert(count == 0, "missing free blocks");
 517 
 518     // Verify that the number of free blocks is not out of hand.
 519     static int free_block_threshold = 10000;
 520     if (count > free_block_threshold) {
 521       warning("CodeHeap: # of free blocks > %d", free_block_threshold);
 522       // Double the warning limit
 523       free_block_threshold *= 2;
 524     }
 525   }
 526 }
 527 
 528 #endif