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