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     guarantee((char*) block >= _memory.low(),
 194               "The newly allocated block " INTPTR_FORMAT " is not within the heap starting with "  INTPTR_FORMAT,
 195               p2i(block), p2i(_memory.low()));
 196     DEBUG_ONLY(memset((void*)block->allocated_space(), badCodeHeapNewVal, instance_size));
 197     _max_allocated_capacity = MAX2(_max_allocated_capacity, allocated_capacity());
 198     _blob_count++;
 199     return block->allocated_space();
 200   }
 201 
 202   // Ensure minimum size for allocation to the heap.
 203   number_of_segments = MAX2((int)CodeCacheMinBlockLength, (int)number_of_segments);
 204 
 205   if (_next_segment + number_of_segments <= _number_of_committed_segments) {
 206     mark_segmap_as_used(_next_segment, _next_segment + number_of_segments);
 207     HeapBlock* b =  block_at(_next_segment);
 208     b->initialize(number_of_segments);
 209     _next_segment += number_of_segments;
 210     guarantee((char*) b >= _memory.low(),
 211               "The newly allocated block " INTPTR_FORMAT " is not within the heap starting with "  INTPTR_FORMAT,
 212               p2i(b), p2i(_memory.low()));
 213     DEBUG_ONLY(memset((void *)b->allocated_space(), badCodeHeapNewVal, instance_size));
 214     _max_allocated_capacity = MAX2(_max_allocated_capacity, allocated_capacity());
 215     _blob_count++;
 216     return b->allocated_space();
 217   } else {
 218     return NULL;
 219   }
 220 }
 221 
 222 
 223 void CodeHeap::deallocate(void* p) {
 224   assert(p == find_start(p), "illegal deallocation");
 225   // Find start of HeapBlock
 226   HeapBlock* b = (((HeapBlock *)p) - 1);
 227   assert(b->allocated_space() == p, "sanity check");
 228   guarantee((char*) b >= _memory.low(),
 229             "The block to be deallocated " INTPTR_FORMAT " is not within the heap starting with "  INTPTR_FORMAT,
 230             p2i(b), p2i(_memory.low()));
 231   DEBUG_ONLY(memset((void *)b->allocated_space(), badCodeHeapFreeVal,
 232              segments_to_size(b->length()) - sizeof(HeapBlock)));
 233   add_to_freelist(b);
 234   NOT_PRODUCT(verify());
 235 }
 236 
 237 /**
 238  * Uses segment map to find the the start (header) of a nmethod. This works as follows:
 239  * The memory of the code cache is divided into 'segments'. The size of a segment is
 240  * determined by -XX:CodeCacheSegmentSize=XX. Allocation in the code cache can only
 241  * happen at segment boundaries. A pointer in the code cache can be mapped to a segment
 242  * by calling segment_for(addr). Each time memory is requested from the code cache,
 243  * the segmap is updated accordingly. See the following example, which illustrates the
 244  * state of code cache and the segment map: (seg -> segment, nm ->nmethod)
 245  *
 246  *          code cache          segmap
 247  *         -----------        ---------
 248  * seg 1   | nm 1    |   ->   | 0     |
 249  * seg 2   | nm 1    |   ->   | 1     |
 250  * ...     | nm 1    |   ->   | ..    |
 251  * seg m   | nm 2    |   ->   | 0     |
 252  * seg m+1 | nm 2    |   ->   | 1     |
 253  * ...     | nm 2    |   ->   | 2     |
 254  * ...     | nm 2    |   ->   | ..    |
 255  * ...     | nm 2    |   ->   | 0xFE  |
 256  * seg m+n | nm 2    |   ->   | 1     |
 257  * ...     | nm 2    |   ->   |       |
 258  *
 259  * A value of '0' in the segmap indicates that this segment contains the beginning of
 260  * an nmethod. Let's walk through a simple example: If we want to find the start of
 261  * an nmethod that falls into seg 2, we read the value of the segmap[2]. The value
 262  * is an offset that points to the segment that contains the start of the nmethod.
 263  * Another example: If we want to get the start of nm 2, and we happen to get a pointer
 264  * that points to seg m+n, we first read seg[n+m], which returns '1'. So we have to
 265  * do one more read of the segmap[m+n-1] to finally get the segment header.
 266  */
 267 void* CodeHeap::find_start(void* p) const {
 268   if (!contains(p)) {
 269     return NULL;
 270   }
 271   size_t seg_idx = segment_for(p);
 272   address seg_map = (address)_segmap.low();
 273   if (is_segment_unused(seg_map[seg_idx])) {
 274     return NULL;
 275   }
 276   while (seg_map[seg_idx] > 0) {
 277     seg_idx -= (int)seg_map[seg_idx];
 278   }
 279 
 280   HeapBlock* h = block_at(seg_idx);
 281   if (h->free()) {
 282     return NULL;
 283   }
 284   return h->allocated_space();
 285 }
 286 
 287 CodeBlob* CodeHeap::find_blob_unsafe(void* start) const {
 288   CodeBlob* result = (CodeBlob*)CodeHeap::find_start(start);
 289   if (result != NULL && result->blob_contains((address)start)) {
 290     return result;
 291   }
 292   return NULL;
 293 }
 294 
 295 size_t CodeHeap::alignment_unit() const {
 296   // this will be a power of two
 297   return _segment_size;
 298 }
 299 
 300 
 301 size_t CodeHeap::alignment_offset() const {
 302   // The lowest address in any allocated block will be
 303   // equal to alignment_offset (mod alignment_unit).
 304   return sizeof(HeapBlock) & (_segment_size - 1);
 305 }
 306 
 307 // Returns the current block if available and used.
 308 // If not, it returns the subsequent block (if available), NULL otherwise.
 309 // Free blocks are merged, therefore there is at most one free block
 310 // between two used ones. As a result, the subsequent block (if available) is
 311 // guaranteed to be used.
 312 void* CodeHeap::next_used(HeapBlock* b) const {
 313   if (b != NULL && b->free()) b = next_block(b);
 314   assert(b == NULL || !b->free(), "must be in use or at end of heap");
 315   return (b == NULL) ? NULL : b->allocated_space();
 316 }
 317 
 318 // Returns the first used HeapBlock
 319 HeapBlock* CodeHeap::first_block() const {
 320   if (_next_segment > 0)
 321     return block_at(0);
 322   return NULL;
 323 }
 324 
 325 HeapBlock* CodeHeap::block_start(void* q) const {
 326   HeapBlock* b = (HeapBlock*)find_start(q);
 327   if (b == NULL) return NULL;
 328   return b - 1;
 329 }
 330 
 331 // Returns the next Heap block an offset into one
 332 HeapBlock* CodeHeap::next_block(HeapBlock *b) const {
 333   if (b == NULL) return NULL;
 334   size_t i = segment_for(b) + b->length();
 335   if (i < _next_segment)
 336     return block_at(i);
 337   return NULL;
 338 }
 339 
 340 
 341 // Returns current capacity
 342 size_t CodeHeap::capacity() const {
 343   return _memory.committed_size();
 344 }
 345 
 346 size_t CodeHeap::max_capacity() const {
 347   return _memory.reserved_size();
 348 }
 349 
 350 int CodeHeap::allocated_segments() const {
 351   return (int)_next_segment;
 352 }
 353 
 354 size_t CodeHeap::allocated_capacity() const {
 355   // size of used heap - size on freelist
 356   return segments_to_size(_next_segment - _freelist_segments);
 357 }
 358 
 359 // Returns size of the unallocated heap block
 360 size_t CodeHeap::heap_unallocated_capacity() const {
 361   // Total number of segments - number currently used
 362   return segments_to_size(_number_of_reserved_segments - _next_segment);
 363 }
 364 
 365 // Free list management
 366 
 367 FreeBlock* CodeHeap::following_block(FreeBlock *b) {
 368   return (FreeBlock*)(((address)b) + _segment_size * b->length());
 369 }
 370 
 371 // Inserts block b after a
 372 void CodeHeap::insert_after(FreeBlock* a, FreeBlock* b) {
 373   assert(a != NULL && b != NULL, "must be real pointers");
 374 
 375   // Link b into the list after a
 376   b->set_link(a->link());
 377   a->set_link(b);
 378 
 379   // See if we can merge blocks
 380   merge_right(b); // Try to make b bigger
 381   merge_right(a); // Try to make a include b
 382 }
 383 
 384 // Try to merge this block with the following block
 385 bool CodeHeap::merge_right(FreeBlock* a) {
 386   assert(a->free(), "must be a free block");
 387   if (following_block(a) == a->link()) {
 388     assert(a->link() != NULL && a->link()->free(), "must be free too");
 389     // Update block a to include the following block
 390     a->set_length(a->length() + a->link()->length());
 391     a->set_link(a->link()->link());
 392     // Update find_start map
 393     size_t beg = segment_for(a);
 394     mark_segmap_as_used(beg, beg + a->length());
 395     _freelist_length--;
 396     return true;
 397   }
 398   return false;
 399 }
 400 
 401 
 402 void CodeHeap::add_to_freelist(HeapBlock* a) {
 403   FreeBlock* b = (FreeBlock*)a;
 404   _freelist_length++;
 405 
 406   assert(b != _freelist, "cannot be removed twice");
 407 
 408 
 409   // Mark as free and update free space count
 410   _freelist_segments += b->length();
 411   b->set_free();
 412 
 413   // First element in list?
 414   if (_freelist == NULL) {
 415     _freelist = b;
 416     b->set_link(NULL);
 417     return;
 418   }
 419 
 420   // Since the freelist is ordered (smaller addresses -> larger addresses) and the
 421   // element we want to insert into the freelist has a smaller address than the first
 422   // element, we can simply add 'b' as the first element and we are done.
 423   if (b < _freelist) {
 424     // Insert first in list
 425     b->set_link(_freelist);
 426     _freelist = b;
 427     merge_right(_freelist);
 428     return;
 429   }
 430 
 431   // Scan for right place to put into list. List
 432   // is sorted by increasing addresses
 433   FreeBlock* prev = _freelist;
 434   FreeBlock* cur  = _freelist->link();
 435   while(cur != NULL && cur < b) {
 436     assert(prev < cur, "Freelist must be ordered");
 437     prev = cur;
 438     cur  = cur->link();
 439   }
 440   assert((prev < b) && (cur == NULL || b < cur), "free-list must be ordered");
 441   insert_after(prev, b);
 442 }
 443 
 444 /**
 445  * Search freelist for an entry on the list with the best fit.
 446  * @return NULL, if no one was found
 447  */
 448 FreeBlock* CodeHeap::search_freelist(size_t length) {
 449   FreeBlock* found_block = NULL;
 450   FreeBlock* found_prev  = NULL;
 451   size_t     found_length = 0;
 452 
 453   FreeBlock* prev = NULL;
 454   FreeBlock* cur = _freelist;
 455 
 456   // Search for first block that fits
 457   while(cur != NULL) {
 458     if (cur->length() >= length) {
 459       // Remember block, its previous element, and its length
 460       found_block = cur;
 461       found_prev  = prev;
 462       found_length = found_block->length();
 463 
 464       break;
 465     }
 466     // Next element in list
 467     prev = cur;
 468     cur  = cur->link();
 469   }
 470 
 471   if (found_block == NULL) {
 472     // None found
 473     return NULL;
 474   }
 475 
 476   // Exact (or at least good enough) fit. Remove from list.
 477   // Don't leave anything on the freelist smaller than CodeCacheMinBlockLength.
 478   if (found_length - length < CodeCacheMinBlockLength) {
 479     _freelist_length--;
 480     length = found_length;
 481     if (found_prev == NULL) {
 482       assert(_freelist == found_block, "sanity check");
 483       _freelist = _freelist->link();
 484     } else {
 485       assert((found_prev->link() == found_block), "sanity check");
 486       // Unmap element
 487       found_prev->set_link(found_block->link());
 488     }
 489   } else {
 490     // Truncate block and return a pointer to the following block
 491     // Set used bit and length on new block
 492     found_block->set_length(found_length - length);
 493     found_block = following_block(found_block);
 494 
 495     size_t beg = segment_for(found_block);
 496     mark_segmap_as_used(beg, beg + length);
 497     found_block->set_length(length);
 498   }
 499 
 500   found_block->set_used();
 501   _freelist_segments -= length;
 502   return found_block;
 503 }
 504 
 505 //----------------------------------------------------------------------------
 506 // Non-product code
 507 
 508 #ifndef PRODUCT
 509 
 510 void CodeHeap::print() {
 511   tty->print_cr("The Heap");
 512 }
 513 
 514 void CodeHeap::verify() {
 515   if (VerifyCodeCache) {
 516     size_t len = 0;
 517     int count = 0;
 518     for(FreeBlock* b = _freelist; b != NULL; b = b->link()) {
 519       len += b->length();
 520       count++;
 521       // Check if we have merged all free blocks
 522       assert(merge_right(b) == false, "Missed merging opportunity");
 523     }
 524     // Verify that freelist contains the right amount of free space
 525     assert(len == _freelist_segments, "wrong freelist");
 526 
 527     for(HeapBlock* h = first_block(); h != NULL; h = next_block(h)) {
 528       if (h->free()) count--;
 529     }
 530     // Verify that the freelist contains the same number of blocks
 531     // than free blocks found on the full list.
 532     assert(count == 0, "missing free blocks");
 533 
 534     // Verify that the number of free blocks is not out of hand.
 535     static int free_block_threshold = 10000;
 536     if (count > free_block_threshold) {
 537       warning("CodeHeap: # of free blocks > %d", free_block_threshold);
 538       // Double the warning limit
 539       free_block_threshold *= 2;
 540     }
 541   }
 542 }
 543 
 544 #endif
--- EOF ---