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