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 #ifndef SHARE_VM_MEMORY_HEAP_HPP
  26 #define SHARE_VM_MEMORY_HEAP_HPP
  27 
  28 #include "code/codeBlob.hpp"
  29 #include "memory/allocation.hpp"
  30 #include "memory/virtualspace.hpp"
  31 #include "utilities/macros.hpp"
  32 
  33 // Blocks
  34 
  35 class HeapBlock VALUE_OBJ_CLASS_SPEC {
  36   friend class VMStructs;
  37 
  38  public:
  39   struct Header {
  40     size_t  _length;                             // the length in segments
  41     bool    _used;                               // Used bit
  42   };
  43 
  44  protected:
  45   union {
  46     Header _header;
  47     int64_t _padding[ (sizeof(Header) + sizeof(int64_t)-1) / sizeof(int64_t) ];
  48                         // pad to 0 mod 8
  49   };
  50 
  51  public:
  52   // Initialization
  53   void initialize(size_t length)                 { _header._length = length; set_used(); }
  54 
  55   // Accessors
  56   void* allocated_space() const                  { return (void*)(this + 1); }
  57   size_t length() const                          { return _header._length; }
  58 
  59   // Used/free
  60   void set_used()                                { _header._used = true; }
  61   void set_free()                                { _header._used = false; }
  62   bool free()                                    { return !_header._used; }
  63 };
  64 
  65 class FreeBlock: public HeapBlock {
  66   friend class VMStructs;
  67  protected:
  68   FreeBlock* _link;
  69 
  70  public:
  71   // Initialization
  72   void initialize(size_t length)             { HeapBlock::initialize(length); _link= NULL; }
  73 
  74   // Merging
  75   void set_length(size_t l)                  { _header._length = l; }
  76 
  77   // Accessors
  78   FreeBlock* link() const                    { return _link; }
  79   void set_link(FreeBlock* link)             { _link = link; }
  80 };
  81 
  82 class CodeHeap : public CHeapObj<mtCode> {
  83   friend class VMStructs;
  84  protected:
  85   VirtualSpace _memory;                          // the memory holding the blocks
  86   VirtualSpace _segmap;                          // the memory holding the segment map
  87 
  88   size_t       _number_of_committed_segments;
  89   size_t       _number_of_reserved_segments;
  90   size_t       _segment_size;
  91   int          _log2_segment_size;
  92 
  93   size_t       _next_segment;
  94 
  95   FreeBlock*   _freelist;
  96   size_t       _freelist_segments;               // No. of segments in freelist
  97   int          _freelist_length;
  98   size_t       _max_allocated_capacity;          // Peak capacity that was allocated during lifetime of the heap
  99 
 100   const char*  _name;                            // Name of the CodeHeap
 101   const int    _code_blob_type;                  // CodeBlobType it contains
 102   int          _blob_count;                      // Number of CodeBlobs
 103   int          _nmethod_count;                   // Number of nmethods
 104   int          _adapter_count;                   // Number of adapters
 105   int          _full_count;                      // Number of times the code heap was full
 106 
 107 
 108   enum { free_sentinel = 0xFF };
 109 
 110   // Helper functions
 111   size_t   size_to_segments(size_t size) const { return (size + _segment_size - 1) >> _log2_segment_size; }
 112   size_t   segments_to_size(size_t number_of_segments) const { return number_of_segments << _log2_segment_size; }
 113 
 114   size_t   segment_for(void* p) const            { return ((char*)p - _memory.low()) >> _log2_segment_size; }
 115   bool     is_segment_unused(int val) const      { return val == free_sentinel; }
 116   HeapBlock* block_at(size_t i) const            { return (HeapBlock*)(_memory.low() + (i << _log2_segment_size)); }
 117 
 118   void  mark_segmap_as_free(size_t beg, size_t end);
 119   void  mark_segmap_as_used(size_t beg, size_t end);
 120 
 121   // Freelist management helpers
 122   FreeBlock* following_block(FreeBlock* b);
 123   void insert_after(FreeBlock* a, FreeBlock* b);
 124   bool merge_right (FreeBlock* a);
 125 
 126   // Toplevel freelist management
 127   void add_to_freelist(HeapBlock* b);
 128   FreeBlock* search_freelist(size_t length);
 129 
 130   // Iteration helpers
 131   void*      next_used(HeapBlock* b) const;
 132   HeapBlock* first_block() const;
 133   HeapBlock* next_block(HeapBlock* b) const;
 134   HeapBlock* block_start(void* p) const;
 135 
 136   // to perform additional actions on creation of executable code
 137   void on_code_mapping(char* base, size_t size);
 138   void clear();                                 // clears all heap contents
 139 
 140  public:
 141   CodeHeap(const char* name, const int code_blob_type);
 142 
 143   // Heap extents
 144   bool  reserve(ReservedSpace rs, size_t committed_size, size_t segment_size);
 145   bool  expand_by(size_t size);                  // expands committed memory by size
 146 
 147   // Memory allocation
 148   void* allocate (size_t size); // Allocate 'size' bytes in the code cache or return NULL
 149   void  deallocate(void* p);    // Deallocate memory
 150   // Free the tail of segments allocated by the last call to 'allocate()' which exceed 'used_size'.
 151   // ATTENTION: this is only safe to use if there was no other call to 'allocate()' after
 152   //            'p' was allocated. Only intended for freeing memory which would be otherwise
 153   //            wasted after the interpreter generation because we don't know the interpreter size
 154   //            beforehand and we also can't easily relocate the interpreter to a new location.
 155   void  deallocate_tail(void* p, size_t used_size);
 156 
 157   // Attributes
 158   char* low_boundary() const                     { return _memory.low_boundary(); }
 159   char* high() const                             { return _memory.high(); }
 160   char* high_boundary() const                    { return _memory.high_boundary(); }
 161 
 162   bool contains(const void* p) const             { return low_boundary() <= p && p < high(); }
 163   bool contains_blob(const CodeBlob* blob) const {
 164     // AOT CodeBlobs (i.e. AOTCompiledMethod) objects aren't allocated in the AOTCodeHeap but on the C-Heap.
 165     // Only the code they are pointing to is located in the AOTCodeHeap. All other CodeBlobs are allocated
 166     // directly in their corresponding CodeHeap with their code appended to the actual C++ object.
 167     // So all CodeBlobs except AOTCompiledMethod are continuous in memory with their data and code while
 168     // AOTCompiledMethod and their code/data is distributed in the C-Heap. This means we can use the
 169     // address of a CodeBlob object in order to locate it in its heap while we have to use the address
 170     // of the actual code an AOTCompiledMethod object is pointing to in order to locate it.
 171     // Notice that for an ordinary CodeBlob with code size zero, code_begin() may point beyond the object!
 172     const void* start = AOT_ONLY( (code_blob_type() == CodeBlobType::AOT) ? blob->code_begin() : ) (void*)blob;
 173     return contains(start);
 174   }
 175 
 176   virtual void* find_start(void* p)     const;   // returns the block containing p or NULL
 177   virtual CodeBlob* find_blob_unsafe(void* start) const;
 178   size_t alignment_unit()       const;           // alignment of any block
 179   size_t alignment_offset()     const;           // offset of first byte of any block, within the enclosing alignment unit
 180   static size_t header_size();                   // returns the header size for each heap block
 181 
 182   size_t allocated_in_freelist() const           { return _freelist_segments * CodeCacheSegmentSize; }
 183   int    freelist_length()       const           { return _freelist_length; } // number of elements in the freelist
 184 
 185   // returns the first block or NULL
 186   virtual void* first() const                    { return next_used(first_block()); }
 187   // returns the next block given a block p or NULL
 188   virtual void* next(void* p) const              { return next_used(next_block(block_start(p))); }
 189 
 190   // Statistics
 191   size_t capacity() const;
 192   size_t max_capacity() const;
 193   int    allocated_segments() const;
 194   size_t allocated_capacity() const;
 195   size_t max_allocated_capacity() const          { return _max_allocated_capacity; }
 196   size_t unallocated_capacity() const            { return max_capacity() - allocated_capacity(); }
 197 
 198   // Returns true if the CodeHeap contains CodeBlobs of the given type
 199   bool accepts(int code_blob_type) const         { return (_code_blob_type == CodeBlobType::All) ||
 200                                                           (_code_blob_type == code_blob_type); }
 201   int code_blob_type() const                     { return _code_blob_type; }
 202 
 203   // Debugging / Profiling
 204   const char* name() const                       { return _name; }
 205   int         blob_count()                       { return _blob_count; }
 206   int         nmethod_count()                    { return _nmethod_count; }
 207   void    set_nmethod_count(int count)           {        _nmethod_count = count; }
 208   int         adapter_count()                    { return _adapter_count; }
 209   void    set_adapter_count(int count)           {        _adapter_count = count; }
 210   int         full_count()                       { return _full_count; }
 211   void        report_full()                      {        _full_count++; }
 212 
 213 private:
 214   size_t heap_unallocated_capacity() const;
 215 
 216 public:
 217   // Debugging
 218   void verify() PRODUCT_RETURN;
 219   void print()  PRODUCT_RETURN;
 220 
 221   //---<  BEGIN  >--- 8198691: CodeHeap State Analytics.
 222 
 223  public:
 224   enum compType {
 225     noComp = 0     // must be! due to initialization by memset to zero
 226   , c1
 227   , c2
 228   , jvmci
 229   , lastComp
 230   };
 231 
 232   enum blobType {
 233      noType = 0     // must be! due to initialization by memset to zero
 234      // The nMethod_* values correspond 1:1 to the CompiledMethod enum values.
 235    , nMethod_inuse       // executable. This is the "normal" state for a nmethod.
 236    , nMethod_notused     // assumed inactive, marked not entrant. Could be revived if necessary.
 237    , nMethod_notentrant  // no new activations allowed, marked for deoptimization. Old activations may still exist.
 238                          // Will transition to "zombie" after all activations are gone.
 239    , nMethod_zombie      // No more activations exist, ready for purge (remove from code cache).
 240    , nMethod_unloaded    // No activations exist, should not be called. Transient state on the way to "zombie".
 241    , nMethod_alive = nMethod_notentrant // Combined state: nmethod may have activations, thus can't be purged.
 242    , nMethod_dead  = nMethod_zombie     // Combined state: nmethod does not have any activations.
 243    , runtimeStub   = nMethod_unloaded + 1
 244    , ricochetStub
 245    , deoptimizationStub
 246    , uncommonTrapStub
 247    , exceptionStub
 248    , safepointStub
 249    , adapterBlob
 250    , mh_adapterBlob
 251    , bufferBlob
 252    , lastType
 253   };
 254 
 255  private:
 256   void prepare_StatArray(outputStream *out, size_t nElem, size_t granularity, const char* heapName);
 257   void prepare_FreeArray(outputStream *out, unsigned int nElem, const char* heapName);
 258   void prepare_TopSizeArray(outputStream *out, unsigned int nElem, const char* heapName);
 259   void prepare_SizeDistArray(outputStream *out, unsigned int nElem, const char* heapName);
 260   void discard_StatArray(outputStream *out);
 261   void discard_FreeArray(outputStream *out);
 262   void discard_TopSizeArray(outputStream *out);
 263   void discard_SizeDistArray(outputStream *out);
 264 
 265   void update_SizeDistArray(outputStream *out, unsigned int len);
 266 
 267   const char* get_heapName();
 268   unsigned int findHeapIndex(outputStream *out, const char *heapName);
 269   void get_HeapStatGlobals(outputStream *out, const char *heapName);
 270   void set_HeapStatGlobals(outputStream *out, const char *heapName);
 271 
 272   void printBox(outputStream* out, const char border, const char* text1, const char* text2);
 273   void print_blobType_legend(outputStream *out);
 274   void print_space_legend(outputStream *out);
 275   void print_age_legend(outputStream *out);
 276   void print_blobType_single(outputStream *ast, u2 /* blobType */ type);
 277   void print_count_single(outputStream *ast, unsigned short count);
 278   void print_space_single(outputStream *ast, unsigned short space);
 279   void print_age_single(outputStream *ast, unsigned int age);
 280   void print_line_delim(outputStream *out, bufferedStream *sst, unsigned int ix, unsigned int gpl);
 281   void print_line_delim(outputStream *out, outputStream *sst, unsigned int ix, unsigned int gpl);
 282   blobType get_cbType(CodeBlob* cb);
 283 
 284  public:
 285   void discard(outputStream *out);
 286   void aggregate(outputStream *out, const char* granularity);
 287   void print_usedSpace(outputStream *out);
 288   void print_freeSpace(outputStream *out);
 289   void print_count(outputStream *out);
 290   void print_space(outputStream *out);
 291   void print_age(outputStream *out);
 292   void print_names(outputStream *out);
 293 
 294   //---<  END  >--- 8198691: CodeHeap State Analytics.
 295 };
 296 
 297 #endif // SHARE_VM_MEMORY_HEAP_HPP