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