src/share/vm/memory/metaspace.cpp

Tue, 11 Feb 2014 09:34:50 +0100

author
goetz
date
Tue, 11 Feb 2014 09:34:50 +0100
changeset 6337
ab36007d6358
parent 6305
40353abd7984
child 6417
daef39043d2c
permissions
-rw-r--r--

8034171: Remove use of template template parameters from binaryTreeDictionary.
Reviewed-by: mgerdin, jmasa
Contributed-by: matthias.baesken@sap.com

     1 /*
     2  * Copyright (c) 2011, 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 #include "precompiled.hpp"
    25 #include "gc_interface/collectedHeap.hpp"
    26 #include "memory/allocation.hpp"
    27 #include "memory/binaryTreeDictionary.hpp"
    28 #include "memory/freeList.hpp"
    29 #include "memory/collectorPolicy.hpp"
    30 #include "memory/filemap.hpp"
    31 #include "memory/freeList.hpp"
    32 #include "memory/gcLocker.hpp"
    33 #include "memory/metachunk.hpp"
    34 #include "memory/metaspace.hpp"
    35 #include "memory/metaspaceShared.hpp"
    36 #include "memory/resourceArea.hpp"
    37 #include "memory/universe.hpp"
    38 #include "runtime/atomic.inline.hpp"
    39 #include "runtime/globals.hpp"
    40 #include "runtime/init.hpp"
    41 #include "runtime/java.hpp"
    42 #include "runtime/mutex.hpp"
    43 #include "runtime/orderAccess.hpp"
    44 #include "services/memTracker.hpp"
    45 #include "services/memoryService.hpp"
    46 #include "utilities/copy.hpp"
    47 #include "utilities/debug.hpp"
    49 typedef BinaryTreeDictionary<Metablock, FreeList<Metablock> > BlockTreeDictionary;
    50 typedef BinaryTreeDictionary<Metachunk, FreeList<Metachunk> > ChunkTreeDictionary;
    52 // Set this constant to enable slow integrity checking of the free chunk lists
    53 const bool metaspace_slow_verify = false;
    55 size_t const allocation_from_dictionary_limit = 4 * K;
    57 MetaWord* last_allocated = 0;
    59 size_t Metaspace::_compressed_class_space_size;
    61 // Used in declarations in SpaceManager and ChunkManager
    62 enum ChunkIndex {
    63   ZeroIndex = 0,
    64   SpecializedIndex = ZeroIndex,
    65   SmallIndex = SpecializedIndex + 1,
    66   MediumIndex = SmallIndex + 1,
    67   HumongousIndex = MediumIndex + 1,
    68   NumberOfFreeLists = 3,
    69   NumberOfInUseLists = 4
    70 };
    72 enum ChunkSizes {    // in words.
    73   ClassSpecializedChunk = 128,
    74   SpecializedChunk = 128,
    75   ClassSmallChunk = 256,
    76   SmallChunk = 512,
    77   ClassMediumChunk = 4 * K,
    78   MediumChunk = 8 * K
    79 };
    81 static ChunkIndex next_chunk_index(ChunkIndex i) {
    82   assert(i < NumberOfInUseLists, "Out of bound");
    83   return (ChunkIndex) (i+1);
    84 }
    86 volatile intptr_t MetaspaceGC::_capacity_until_GC = 0;
    87 uint MetaspaceGC::_shrink_factor = 0;
    88 bool MetaspaceGC::_should_concurrent_collect = false;
    90 typedef class FreeList<Metachunk> ChunkList;
    92 // Manages the global free lists of chunks.
    93 class ChunkManager : public CHeapObj<mtInternal> {
    94   friend class TestVirtualSpaceNodeTest;
    96   // Free list of chunks of different sizes.
    97   //   SpecializedChunk
    98   //   SmallChunk
    99   //   MediumChunk
   100   //   HumongousChunk
   101   ChunkList _free_chunks[NumberOfFreeLists];
   103   //   HumongousChunk
   104   ChunkTreeDictionary _humongous_dictionary;
   106   // ChunkManager in all lists of this type
   107   size_t _free_chunks_total;
   108   size_t _free_chunks_count;
   110   void dec_free_chunks_total(size_t v) {
   111     assert(_free_chunks_count > 0 &&
   112              _free_chunks_total > 0,
   113              "About to go negative");
   114     Atomic::add_ptr(-1, &_free_chunks_count);
   115     jlong minus_v = (jlong) - (jlong) v;
   116     Atomic::add_ptr(minus_v, &_free_chunks_total);
   117   }
   119   // Debug support
   121   size_t sum_free_chunks();
   122   size_t sum_free_chunks_count();
   124   void locked_verify_free_chunks_total();
   125   void slow_locked_verify_free_chunks_total() {
   126     if (metaspace_slow_verify) {
   127       locked_verify_free_chunks_total();
   128     }
   129   }
   130   void locked_verify_free_chunks_count();
   131   void slow_locked_verify_free_chunks_count() {
   132     if (metaspace_slow_verify) {
   133       locked_verify_free_chunks_count();
   134     }
   135   }
   136   void verify_free_chunks_count();
   138  public:
   140   ChunkManager(size_t specialized_size, size_t small_size, size_t medium_size)
   141       : _free_chunks_total(0), _free_chunks_count(0) {
   142     _free_chunks[SpecializedIndex].set_size(specialized_size);
   143     _free_chunks[SmallIndex].set_size(small_size);
   144     _free_chunks[MediumIndex].set_size(medium_size);
   145   }
   147   // add or delete (return) a chunk to the global freelist.
   148   Metachunk* chunk_freelist_allocate(size_t word_size);
   150   // Map a size to a list index assuming that there are lists
   151   // for special, small, medium, and humongous chunks.
   152   static ChunkIndex list_index(size_t size);
   154   // Remove the chunk from its freelist.  It is
   155   // expected to be on one of the _free_chunks[] lists.
   156   void remove_chunk(Metachunk* chunk);
   158   // Add the simple linked list of chunks to the freelist of chunks
   159   // of type index.
   160   void return_chunks(ChunkIndex index, Metachunk* chunks);
   162   // Total of the space in the free chunks list
   163   size_t free_chunks_total_words();
   164   size_t free_chunks_total_bytes();
   166   // Number of chunks in the free chunks list
   167   size_t free_chunks_count();
   169   void inc_free_chunks_total(size_t v, size_t count = 1) {
   170     Atomic::add_ptr(count, &_free_chunks_count);
   171     Atomic::add_ptr(v, &_free_chunks_total);
   172   }
   173   ChunkTreeDictionary* humongous_dictionary() {
   174     return &_humongous_dictionary;
   175   }
   177   ChunkList* free_chunks(ChunkIndex index);
   179   // Returns the list for the given chunk word size.
   180   ChunkList* find_free_chunks_list(size_t word_size);
   182   // Remove from a list by size.  Selects list based on size of chunk.
   183   Metachunk* free_chunks_get(size_t chunk_word_size);
   185   // Debug support
   186   void verify();
   187   void slow_verify() {
   188     if (metaspace_slow_verify) {
   189       verify();
   190     }
   191   }
   192   void locked_verify();
   193   void slow_locked_verify() {
   194     if (metaspace_slow_verify) {
   195       locked_verify();
   196     }
   197   }
   198   void verify_free_chunks_total();
   200   void locked_print_free_chunks(outputStream* st);
   201   void locked_print_sum_free_chunks(outputStream* st);
   203   void print_on(outputStream* st) const;
   204 };
   206 // Used to manage the free list of Metablocks (a block corresponds
   207 // to the allocation of a quantum of metadata).
   208 class BlockFreelist VALUE_OBJ_CLASS_SPEC {
   209   BlockTreeDictionary* _dictionary;
   211   // Only allocate and split from freelist if the size of the allocation
   212   // is at least 1/4th the size of the available block.
   213   const static int WasteMultiplier = 4;
   215   // Accessors
   216   BlockTreeDictionary* dictionary() const { return _dictionary; }
   218  public:
   219   BlockFreelist();
   220   ~BlockFreelist();
   222   // Get and return a block to the free list
   223   MetaWord* get_block(size_t word_size);
   224   void return_block(MetaWord* p, size_t word_size);
   226   size_t total_size() {
   227   if (dictionary() == NULL) {
   228     return 0;
   229   } else {
   230     return dictionary()->total_size();
   231   }
   232 }
   234   void print_on(outputStream* st) const;
   235 };
   237 // A VirtualSpaceList node.
   238 class VirtualSpaceNode : public CHeapObj<mtClass> {
   239   friend class VirtualSpaceList;
   241   // Link to next VirtualSpaceNode
   242   VirtualSpaceNode* _next;
   244   // total in the VirtualSpace
   245   MemRegion _reserved;
   246   ReservedSpace _rs;
   247   VirtualSpace _virtual_space;
   248   MetaWord* _top;
   249   // count of chunks contained in this VirtualSpace
   250   uintx _container_count;
   252   // Convenience functions to access the _virtual_space
   253   char* low()  const { return virtual_space()->low(); }
   254   char* high() const { return virtual_space()->high(); }
   256   // The first Metachunk will be allocated at the bottom of the
   257   // VirtualSpace
   258   Metachunk* first_chunk() { return (Metachunk*) bottom(); }
   260   // Committed but unused space in the virtual space
   261   size_t free_words_in_vs() const;
   262  public:
   264   VirtualSpaceNode(size_t byte_size);
   265   VirtualSpaceNode(ReservedSpace rs) : _top(NULL), _next(NULL), _rs(rs), _container_count(0) {}
   266   ~VirtualSpaceNode();
   268   // Convenience functions for logical bottom and end
   269   MetaWord* bottom() const { return (MetaWord*) _virtual_space.low(); }
   270   MetaWord* end() const { return (MetaWord*) _virtual_space.high(); }
   272   size_t reserved_words() const  { return _virtual_space.reserved_size() / BytesPerWord; }
   273   size_t committed_words() const { return _virtual_space.actual_committed_size() / BytesPerWord; }
   275   bool is_pre_committed() const { return _virtual_space.special(); }
   277   // address of next available space in _virtual_space;
   278   // Accessors
   279   VirtualSpaceNode* next() { return _next; }
   280   void set_next(VirtualSpaceNode* v) { _next = v; }
   282   void set_reserved(MemRegion const v) { _reserved = v; }
   283   void set_top(MetaWord* v) { _top = v; }
   285   // Accessors
   286   MemRegion* reserved() { return &_reserved; }
   287   VirtualSpace* virtual_space() const { return (VirtualSpace*) &_virtual_space; }
   289   // Returns true if "word_size" is available in the VirtualSpace
   290   bool is_available(size_t word_size) { return word_size <= pointer_delta(end(), _top, sizeof(MetaWord)); }
   292   MetaWord* top() const { return _top; }
   293   void inc_top(size_t word_size) { _top += word_size; }
   295   uintx container_count() { return _container_count; }
   296   void inc_container_count();
   297   void dec_container_count();
   298 #ifdef ASSERT
   299   uint container_count_slow();
   300   void verify_container_count();
   301 #endif
   303   // used and capacity in this single entry in the list
   304   size_t used_words_in_vs() const;
   305   size_t capacity_words_in_vs() const;
   307   bool initialize();
   309   // get space from the virtual space
   310   Metachunk* take_from_committed(size_t chunk_word_size);
   312   // Allocate a chunk from the virtual space and return it.
   313   Metachunk* get_chunk_vs(size_t chunk_word_size);
   315   // Expands/shrinks the committed space in a virtual space.  Delegates
   316   // to Virtualspace
   317   bool expand_by(size_t min_words, size_t preferred_words);
   319   // In preparation for deleting this node, remove all the chunks
   320   // in the node from any freelist.
   321   void purge(ChunkManager* chunk_manager);
   323   // If an allocation doesn't fit in the current node a new node is created.
   324   // Allocate chunks out of the remaining committed space in this node
   325   // to avoid wasting that memory.
   326   // This always adds up because all the chunk sizes are multiples of
   327   // the smallest chunk size.
   328   void retire(ChunkManager* chunk_manager);
   330 #ifdef ASSERT
   331   // Debug support
   332   void mangle();
   333 #endif
   335   void print_on(outputStream* st) const;
   336 };
   338 #define assert_is_ptr_aligned(ptr, alignment) \
   339   assert(is_ptr_aligned(ptr, alignment),      \
   340     err_msg(PTR_FORMAT " is not aligned to "  \
   341       SIZE_FORMAT, ptr, alignment))
   343 #define assert_is_size_aligned(size, alignment) \
   344   assert(is_size_aligned(size, alignment),      \
   345     err_msg(SIZE_FORMAT " is not aligned to "   \
   346        SIZE_FORMAT, size, alignment))
   349 // Decide if large pages should be committed when the memory is reserved.
   350 static bool should_commit_large_pages_when_reserving(size_t bytes) {
   351   if (UseLargePages && UseLargePagesInMetaspace && !os::can_commit_large_page_memory()) {
   352     size_t words = bytes / BytesPerWord;
   353     bool is_class = false; // We never reserve large pages for the class space.
   354     if (MetaspaceGC::can_expand(words, is_class) &&
   355         MetaspaceGC::allowed_expansion() >= words) {
   356       return true;
   357     }
   358   }
   360   return false;
   361 }
   363   // byte_size is the size of the associated virtualspace.
   364 VirtualSpaceNode::VirtualSpaceNode(size_t bytes) : _top(NULL), _next(NULL), _rs(), _container_count(0) {
   365   assert_is_size_aligned(bytes, Metaspace::reserve_alignment());
   367   // This allocates memory with mmap.  For DumpSharedspaces, try to reserve
   368   // configurable address, generally at the top of the Java heap so other
   369   // memory addresses don't conflict.
   370   if (DumpSharedSpaces) {
   371     bool large_pages = false; // No large pages when dumping the CDS archive.
   372     char* shared_base = (char*)align_ptr_up((char*)SharedBaseAddress, Metaspace::reserve_alignment());
   374     _rs = ReservedSpace(bytes, Metaspace::reserve_alignment(), large_pages, shared_base, 0);
   375     if (_rs.is_reserved()) {
   376       assert(shared_base == 0 || _rs.base() == shared_base, "should match");
   377     } else {
   378       // Get a mmap region anywhere if the SharedBaseAddress fails.
   379       _rs = ReservedSpace(bytes, Metaspace::reserve_alignment(), large_pages);
   380     }
   381     MetaspaceShared::set_shared_rs(&_rs);
   382   } else {
   383     bool large_pages = should_commit_large_pages_when_reserving(bytes);
   385     _rs = ReservedSpace(bytes, Metaspace::reserve_alignment(), large_pages);
   386   }
   388   if (_rs.is_reserved()) {
   389     assert(_rs.base() != NULL, "Catch if we get a NULL address");
   390     assert(_rs.size() != 0, "Catch if we get a 0 size");
   391     assert_is_ptr_aligned(_rs.base(), Metaspace::reserve_alignment());
   392     assert_is_size_aligned(_rs.size(), Metaspace::reserve_alignment());
   394     MemTracker::record_virtual_memory_type((address)_rs.base(), mtClass);
   395   }
   396 }
   398 void VirtualSpaceNode::purge(ChunkManager* chunk_manager) {
   399   Metachunk* chunk = first_chunk();
   400   Metachunk* invalid_chunk = (Metachunk*) top();
   401   while (chunk < invalid_chunk ) {
   402     assert(chunk->is_tagged_free(), "Should be tagged free");
   403     MetaWord* next = ((MetaWord*)chunk) + chunk->word_size();
   404     chunk_manager->remove_chunk(chunk);
   405     assert(chunk->next() == NULL &&
   406            chunk->prev() == NULL,
   407            "Was not removed from its list");
   408     chunk = (Metachunk*) next;
   409   }
   410 }
   412 #ifdef ASSERT
   413 uint VirtualSpaceNode::container_count_slow() {
   414   uint count = 0;
   415   Metachunk* chunk = first_chunk();
   416   Metachunk* invalid_chunk = (Metachunk*) top();
   417   while (chunk < invalid_chunk ) {
   418     MetaWord* next = ((MetaWord*)chunk) + chunk->word_size();
   419     // Don't count the chunks on the free lists.  Those are
   420     // still part of the VirtualSpaceNode but not currently
   421     // counted.
   422     if (!chunk->is_tagged_free()) {
   423       count++;
   424     }
   425     chunk = (Metachunk*) next;
   426   }
   427   return count;
   428 }
   429 #endif
   431 // List of VirtualSpaces for metadata allocation.
   432 class VirtualSpaceList : public CHeapObj<mtClass> {
   433   friend class VirtualSpaceNode;
   435   enum VirtualSpaceSizes {
   436     VirtualSpaceSize = 256 * K
   437   };
   439   // Head of the list
   440   VirtualSpaceNode* _virtual_space_list;
   441   // virtual space currently being used for allocations
   442   VirtualSpaceNode* _current_virtual_space;
   444   // Is this VirtualSpaceList used for the compressed class space
   445   bool _is_class;
   447   // Sum of reserved and committed memory in the virtual spaces
   448   size_t _reserved_words;
   449   size_t _committed_words;
   451   // Number of virtual spaces
   452   size_t _virtual_space_count;
   454   ~VirtualSpaceList();
   456   VirtualSpaceNode* virtual_space_list() const { return _virtual_space_list; }
   458   void set_virtual_space_list(VirtualSpaceNode* v) {
   459     _virtual_space_list = v;
   460   }
   461   void set_current_virtual_space(VirtualSpaceNode* v) {
   462     _current_virtual_space = v;
   463   }
   465   void link_vs(VirtualSpaceNode* new_entry);
   467   // Get another virtual space and add it to the list.  This
   468   // is typically prompted by a failed attempt to allocate a chunk
   469   // and is typically followed by the allocation of a chunk.
   470   bool create_new_virtual_space(size_t vs_word_size);
   472   // Chunk up the unused committed space in the current
   473   // virtual space and add the chunks to the free list.
   474   void retire_current_virtual_space();
   476  public:
   477   VirtualSpaceList(size_t word_size);
   478   VirtualSpaceList(ReservedSpace rs);
   480   size_t free_bytes();
   482   Metachunk* get_new_chunk(size_t word_size,
   483                            size_t grow_chunks_by_words,
   484                            size_t medium_chunk_bunch);
   486   bool expand_node_by(VirtualSpaceNode* node,
   487                       size_t min_words,
   488                       size_t preferred_words);
   490   bool expand_by(size_t min_words,
   491                  size_t preferred_words);
   493   VirtualSpaceNode* current_virtual_space() {
   494     return _current_virtual_space;
   495   }
   497   bool is_class() const { return _is_class; }
   499   bool initialization_succeeded() { return _virtual_space_list != NULL; }
   501   size_t reserved_words()  { return _reserved_words; }
   502   size_t reserved_bytes()  { return reserved_words() * BytesPerWord; }
   503   size_t committed_words() { return _committed_words; }
   504   size_t committed_bytes() { return committed_words() * BytesPerWord; }
   506   void inc_reserved_words(size_t v);
   507   void dec_reserved_words(size_t v);
   508   void inc_committed_words(size_t v);
   509   void dec_committed_words(size_t v);
   510   void inc_virtual_space_count();
   511   void dec_virtual_space_count();
   513   // Unlink empty VirtualSpaceNodes and free it.
   514   void purge(ChunkManager* chunk_manager);
   516   void print_on(outputStream* st) const;
   518   class VirtualSpaceListIterator : public StackObj {
   519     VirtualSpaceNode* _virtual_spaces;
   520    public:
   521     VirtualSpaceListIterator(VirtualSpaceNode* virtual_spaces) :
   522       _virtual_spaces(virtual_spaces) {}
   524     bool repeat() {
   525       return _virtual_spaces != NULL;
   526     }
   528     VirtualSpaceNode* get_next() {
   529       VirtualSpaceNode* result = _virtual_spaces;
   530       if (_virtual_spaces != NULL) {
   531         _virtual_spaces = _virtual_spaces->next();
   532       }
   533       return result;
   534     }
   535   };
   536 };
   538 class Metadebug : AllStatic {
   539   // Debugging support for Metaspaces
   540   static int _allocation_fail_alot_count;
   542  public:
   544   static void init_allocation_fail_alot_count();
   545 #ifdef ASSERT
   546   static bool test_metadata_failure();
   547 #endif
   548 };
   550 int Metadebug::_allocation_fail_alot_count = 0;
   552 //  SpaceManager - used by Metaspace to handle allocations
   553 class SpaceManager : public CHeapObj<mtClass> {
   554   friend class Metaspace;
   555   friend class Metadebug;
   557  private:
   559   // protects allocations
   560   Mutex* const _lock;
   562   // Type of metadata allocated.
   563   Metaspace::MetadataType _mdtype;
   565   // List of chunks in use by this SpaceManager.  Allocations
   566   // are done from the current chunk.  The list is used for deallocating
   567   // chunks when the SpaceManager is freed.
   568   Metachunk* _chunks_in_use[NumberOfInUseLists];
   569   Metachunk* _current_chunk;
   571   // Number of small chunks to allocate to a manager
   572   // If class space manager, small chunks are unlimited
   573   static uint const _small_chunk_limit;
   575   // Sum of all space in allocated chunks
   576   size_t _allocated_blocks_words;
   578   // Sum of all allocated chunks
   579   size_t _allocated_chunks_words;
   580   size_t _allocated_chunks_count;
   582   // Free lists of blocks are per SpaceManager since they
   583   // are assumed to be in chunks in use by the SpaceManager
   584   // and all chunks in use by a SpaceManager are freed when
   585   // the class loader using the SpaceManager is collected.
   586   BlockFreelist _block_freelists;
   588   // protects virtualspace and chunk expansions
   589   static const char*  _expand_lock_name;
   590   static const int    _expand_lock_rank;
   591   static Mutex* const _expand_lock;
   593  private:
   594   // Accessors
   595   Metachunk* chunks_in_use(ChunkIndex index) const { return _chunks_in_use[index]; }
   596   void set_chunks_in_use(ChunkIndex index, Metachunk* v) {
   597     // ensure lock-free iteration sees fully initialized node
   598     OrderAccess::storestore();
   599     _chunks_in_use[index] = v;
   600   }
   602   BlockFreelist* block_freelists() const {
   603     return (BlockFreelist*) &_block_freelists;
   604   }
   606   Metaspace::MetadataType mdtype() { return _mdtype; }
   608   VirtualSpaceList* vs_list()   const { return Metaspace::get_space_list(_mdtype); }
   609   ChunkManager* chunk_manager() const { return Metaspace::get_chunk_manager(_mdtype); }
   611   Metachunk* current_chunk() const { return _current_chunk; }
   612   void set_current_chunk(Metachunk* v) {
   613     _current_chunk = v;
   614   }
   616   Metachunk* find_current_chunk(size_t word_size);
   618   // Add chunk to the list of chunks in use
   619   void add_chunk(Metachunk* v, bool make_current);
   620   void retire_current_chunk();
   622   Mutex* lock() const { return _lock; }
   624   const char* chunk_size_name(ChunkIndex index) const;
   626  protected:
   627   void initialize();
   629  public:
   630   SpaceManager(Metaspace::MetadataType mdtype,
   631                Mutex* lock);
   632   ~SpaceManager();
   634   enum ChunkMultiples {
   635     MediumChunkMultiple = 4
   636   };
   638   bool is_class() { return _mdtype == Metaspace::ClassType; }
   640   // Accessors
   641   size_t specialized_chunk_size() { return (size_t) is_class() ? ClassSpecializedChunk : SpecializedChunk; }
   642   size_t small_chunk_size()       { return (size_t) is_class() ? ClassSmallChunk : SmallChunk; }
   643   size_t medium_chunk_size()      { return (size_t) is_class() ? ClassMediumChunk : MediumChunk; }
   644   size_t medium_chunk_bunch()     { return medium_chunk_size() * MediumChunkMultiple; }
   646   size_t smallest_chunk_size()  { return specialized_chunk_size(); }
   648   size_t allocated_blocks_words() const { return _allocated_blocks_words; }
   649   size_t allocated_blocks_bytes() const { return _allocated_blocks_words * BytesPerWord; }
   650   size_t allocated_chunks_words() const { return _allocated_chunks_words; }
   651   size_t allocated_chunks_count() const { return _allocated_chunks_count; }
   653   bool is_humongous(size_t word_size) { return word_size > medium_chunk_size(); }
   655   static Mutex* expand_lock() { return _expand_lock; }
   657   // Increment the per Metaspace and global running sums for Metachunks
   658   // by the given size.  This is used when a Metachunk to added to
   659   // the in-use list.
   660   void inc_size_metrics(size_t words);
   661   // Increment the per Metaspace and global running sums Metablocks by the given
   662   // size.  This is used when a Metablock is allocated.
   663   void inc_used_metrics(size_t words);
   664   // Delete the portion of the running sums for this SpaceManager. That is,
   665   // the globals running sums for the Metachunks and Metablocks are
   666   // decremented for all the Metachunks in-use by this SpaceManager.
   667   void dec_total_from_size_metrics();
   669   // Set the sizes for the initial chunks.
   670   void get_initial_chunk_sizes(Metaspace::MetaspaceType type,
   671                                size_t* chunk_word_size,
   672                                size_t* class_chunk_word_size);
   674   size_t sum_capacity_in_chunks_in_use() const;
   675   size_t sum_used_in_chunks_in_use() const;
   676   size_t sum_free_in_chunks_in_use() const;
   677   size_t sum_waste_in_chunks_in_use() const;
   678   size_t sum_waste_in_chunks_in_use(ChunkIndex index ) const;
   680   size_t sum_count_in_chunks_in_use();
   681   size_t sum_count_in_chunks_in_use(ChunkIndex i);
   683   Metachunk* get_new_chunk(size_t word_size, size_t grow_chunks_by_words);
   685   // Block allocation and deallocation.
   686   // Allocates a block from the current chunk
   687   MetaWord* allocate(size_t word_size);
   689   // Helper for allocations
   690   MetaWord* allocate_work(size_t word_size);
   692   // Returns a block to the per manager freelist
   693   void deallocate(MetaWord* p, size_t word_size);
   695   // Based on the allocation size and a minimum chunk size,
   696   // returned chunk size (for expanding space for chunk allocation).
   697   size_t calc_chunk_size(size_t allocation_word_size);
   699   // Called when an allocation from the current chunk fails.
   700   // Gets a new chunk (may require getting a new virtual space),
   701   // and allocates from that chunk.
   702   MetaWord* grow_and_allocate(size_t word_size);
   704   // Notify memory usage to MemoryService.
   705   void track_metaspace_memory_usage();
   707   // debugging support.
   709   void dump(outputStream* const out) const;
   710   void print_on(outputStream* st) const;
   711   void locked_print_chunks_in_use_on(outputStream* st) const;
   713   bool contains(const void *ptr);
   715   void verify();
   716   void verify_chunk_size(Metachunk* chunk);
   717   NOT_PRODUCT(void mangle_freed_chunks();)
   718 #ifdef ASSERT
   719   void verify_allocated_blocks_words();
   720 #endif
   722   size_t get_raw_word_size(size_t word_size) {
   723     size_t byte_size = word_size * BytesPerWord;
   725     size_t raw_bytes_size = MAX2(byte_size, sizeof(Metablock));
   726     raw_bytes_size = align_size_up(raw_bytes_size, Metachunk::object_alignment());
   728     size_t raw_word_size = raw_bytes_size / BytesPerWord;
   729     assert(raw_word_size * BytesPerWord == raw_bytes_size, "Size problem");
   731     return raw_word_size;
   732   }
   733 };
   735 uint const SpaceManager::_small_chunk_limit = 4;
   737 const char* SpaceManager::_expand_lock_name =
   738   "SpaceManager chunk allocation lock";
   739 const int SpaceManager::_expand_lock_rank = Monitor::leaf - 1;
   740 Mutex* const SpaceManager::_expand_lock =
   741   new Mutex(SpaceManager::_expand_lock_rank,
   742             SpaceManager::_expand_lock_name,
   743             Mutex::_allow_vm_block_flag);
   745 void VirtualSpaceNode::inc_container_count() {
   746   assert_lock_strong(SpaceManager::expand_lock());
   747   _container_count++;
   748   assert(_container_count == container_count_slow(),
   749          err_msg("Inconsistency in countainer_count _container_count " SIZE_FORMAT
   750                  " container_count_slow() " SIZE_FORMAT,
   751                  _container_count, container_count_slow()));
   752 }
   754 void VirtualSpaceNode::dec_container_count() {
   755   assert_lock_strong(SpaceManager::expand_lock());
   756   _container_count--;
   757 }
   759 #ifdef ASSERT
   760 void VirtualSpaceNode::verify_container_count() {
   761   assert(_container_count == container_count_slow(),
   762     err_msg("Inconsistency in countainer_count _container_count " SIZE_FORMAT
   763             " container_count_slow() " SIZE_FORMAT, _container_count, container_count_slow()));
   764 }
   765 #endif
   767 // BlockFreelist methods
   769 BlockFreelist::BlockFreelist() : _dictionary(NULL) {}
   771 BlockFreelist::~BlockFreelist() {
   772   if (_dictionary != NULL) {
   773     if (Verbose && TraceMetadataChunkAllocation) {
   774       _dictionary->print_free_lists(gclog_or_tty);
   775     }
   776     delete _dictionary;
   777   }
   778 }
   780 void BlockFreelist::return_block(MetaWord* p, size_t word_size) {
   781   Metablock* free_chunk = ::new (p) Metablock(word_size);
   782   if (dictionary() == NULL) {
   783    _dictionary = new BlockTreeDictionary();
   784   }
   785   dictionary()->return_chunk(free_chunk);
   786 }
   788 MetaWord* BlockFreelist::get_block(size_t word_size) {
   789   if (dictionary() == NULL) {
   790     return NULL;
   791   }
   793   if (word_size < TreeChunk<Metablock, FreeList<Metablock> >::min_size()) {
   794     // Dark matter.  Too small for dictionary.
   795     return NULL;
   796   }
   798   Metablock* free_block =
   799     dictionary()->get_chunk(word_size, FreeBlockDictionary<Metablock>::atLeast);
   800   if (free_block == NULL) {
   801     return NULL;
   802   }
   804   const size_t block_size = free_block->size();
   805   if (block_size > WasteMultiplier * word_size) {
   806     return_block((MetaWord*)free_block, block_size);
   807     return NULL;
   808   }
   810   MetaWord* new_block = (MetaWord*)free_block;
   811   assert(block_size >= word_size, "Incorrect size of block from freelist");
   812   const size_t unused = block_size - word_size;
   813   if (unused >= TreeChunk<Metablock, FreeList<Metablock> >::min_size()) {
   814     return_block(new_block + word_size, unused);
   815   }
   817   return new_block;
   818 }
   820 void BlockFreelist::print_on(outputStream* st) const {
   821   if (dictionary() == NULL) {
   822     return;
   823   }
   824   dictionary()->print_free_lists(st);
   825 }
   827 // VirtualSpaceNode methods
   829 VirtualSpaceNode::~VirtualSpaceNode() {
   830   _rs.release();
   831 #ifdef ASSERT
   832   size_t word_size = sizeof(*this) / BytesPerWord;
   833   Copy::fill_to_words((HeapWord*) this, word_size, 0xf1f1f1f1);
   834 #endif
   835 }
   837 size_t VirtualSpaceNode::used_words_in_vs() const {
   838   return pointer_delta(top(), bottom(), sizeof(MetaWord));
   839 }
   841 // Space committed in the VirtualSpace
   842 size_t VirtualSpaceNode::capacity_words_in_vs() const {
   843   return pointer_delta(end(), bottom(), sizeof(MetaWord));
   844 }
   846 size_t VirtualSpaceNode::free_words_in_vs() const {
   847   return pointer_delta(end(), top(), sizeof(MetaWord));
   848 }
   850 // Allocates the chunk from the virtual space only.
   851 // This interface is also used internally for debugging.  Not all
   852 // chunks removed here are necessarily used for allocation.
   853 Metachunk* VirtualSpaceNode::take_from_committed(size_t chunk_word_size) {
   854   // Bottom of the new chunk
   855   MetaWord* chunk_limit = top();
   856   assert(chunk_limit != NULL, "Not safe to call this method");
   858   // The virtual spaces are always expanded by the
   859   // commit granularity to enforce the following condition.
   860   // Without this the is_available check will not work correctly.
   861   assert(_virtual_space.committed_size() == _virtual_space.actual_committed_size(),
   862       "The committed memory doesn't match the expanded memory.");
   864   if (!is_available(chunk_word_size)) {
   865     if (TraceMetadataChunkAllocation) {
   866       gclog_or_tty->print("VirtualSpaceNode::take_from_committed() not available %d words ", chunk_word_size);
   867       // Dump some information about the virtual space that is nearly full
   868       print_on(gclog_or_tty);
   869     }
   870     return NULL;
   871   }
   873   // Take the space  (bump top on the current virtual space).
   874   inc_top(chunk_word_size);
   876   // Initialize the chunk
   877   Metachunk* result = ::new (chunk_limit) Metachunk(chunk_word_size, this);
   878   return result;
   879 }
   882 // Expand the virtual space (commit more of the reserved space)
   883 bool VirtualSpaceNode::expand_by(size_t min_words, size_t preferred_words) {
   884   size_t min_bytes = min_words * BytesPerWord;
   885   size_t preferred_bytes = preferred_words * BytesPerWord;
   887   size_t uncommitted = virtual_space()->reserved_size() - virtual_space()->actual_committed_size();
   889   if (uncommitted < min_bytes) {
   890     return false;
   891   }
   893   size_t commit = MIN2(preferred_bytes, uncommitted);
   894   bool result = virtual_space()->expand_by(commit, false);
   896   assert(result, "Failed to commit memory");
   898   return result;
   899 }
   901 Metachunk* VirtualSpaceNode::get_chunk_vs(size_t chunk_word_size) {
   902   assert_lock_strong(SpaceManager::expand_lock());
   903   Metachunk* result = take_from_committed(chunk_word_size);
   904   if (result != NULL) {
   905     inc_container_count();
   906   }
   907   return result;
   908 }
   910 bool VirtualSpaceNode::initialize() {
   912   if (!_rs.is_reserved()) {
   913     return false;
   914   }
   916   // These are necessary restriction to make sure that the virtual space always
   917   // grows in steps of Metaspace::commit_alignment(). If both base and size are
   918   // aligned only the middle alignment of the VirtualSpace is used.
   919   assert_is_ptr_aligned(_rs.base(), Metaspace::commit_alignment());
   920   assert_is_size_aligned(_rs.size(), Metaspace::commit_alignment());
   922   // ReservedSpaces marked as special will have the entire memory
   923   // pre-committed. Setting a committed size will make sure that
   924   // committed_size and actual_committed_size agrees.
   925   size_t pre_committed_size = _rs.special() ? _rs.size() : 0;
   927   bool result = virtual_space()->initialize_with_granularity(_rs, pre_committed_size,
   928                                             Metaspace::commit_alignment());
   929   if (result) {
   930     assert(virtual_space()->committed_size() == virtual_space()->actual_committed_size(),
   931         "Checking that the pre-committed memory was registered by the VirtualSpace");
   933     set_top((MetaWord*)virtual_space()->low());
   934     set_reserved(MemRegion((HeapWord*)_rs.base(),
   935                  (HeapWord*)(_rs.base() + _rs.size())));
   937     assert(reserved()->start() == (HeapWord*) _rs.base(),
   938       err_msg("Reserved start was not set properly " PTR_FORMAT
   939         " != " PTR_FORMAT, reserved()->start(), _rs.base()));
   940     assert(reserved()->word_size() == _rs.size() / BytesPerWord,
   941       err_msg("Reserved size was not set properly " SIZE_FORMAT
   942         " != " SIZE_FORMAT, reserved()->word_size(),
   943         _rs.size() / BytesPerWord));
   944   }
   946   return result;
   947 }
   949 void VirtualSpaceNode::print_on(outputStream* st) const {
   950   size_t used = used_words_in_vs();
   951   size_t capacity = capacity_words_in_vs();
   952   VirtualSpace* vs = virtual_space();
   953   st->print_cr("   space @ " PTR_FORMAT " " SIZE_FORMAT "K, %3d%% used "
   954            "[" PTR_FORMAT ", " PTR_FORMAT ", "
   955            PTR_FORMAT ", " PTR_FORMAT ")",
   956            vs, capacity / K,
   957            capacity == 0 ? 0 : used * 100 / capacity,
   958            bottom(), top(), end(),
   959            vs->high_boundary());
   960 }
   962 #ifdef ASSERT
   963 void VirtualSpaceNode::mangle() {
   964   size_t word_size = capacity_words_in_vs();
   965   Copy::fill_to_words((HeapWord*) low(), word_size, 0xf1f1f1f1);
   966 }
   967 #endif // ASSERT
   969 // VirtualSpaceList methods
   970 // Space allocated from the VirtualSpace
   972 VirtualSpaceList::~VirtualSpaceList() {
   973   VirtualSpaceListIterator iter(virtual_space_list());
   974   while (iter.repeat()) {
   975     VirtualSpaceNode* vsl = iter.get_next();
   976     delete vsl;
   977   }
   978 }
   980 void VirtualSpaceList::inc_reserved_words(size_t v) {
   981   assert_lock_strong(SpaceManager::expand_lock());
   982   _reserved_words = _reserved_words + v;
   983 }
   984 void VirtualSpaceList::dec_reserved_words(size_t v) {
   985   assert_lock_strong(SpaceManager::expand_lock());
   986   _reserved_words = _reserved_words - v;
   987 }
   989 #define assert_committed_below_limit()                             \
   990   assert(MetaspaceAux::committed_bytes() <= MaxMetaspaceSize,      \
   991       err_msg("Too much committed memory. Committed: " SIZE_FORMAT \
   992               " limit (MaxMetaspaceSize): " SIZE_FORMAT,           \
   993           MetaspaceAux::committed_bytes(), MaxMetaspaceSize));
   995 void VirtualSpaceList::inc_committed_words(size_t v) {
   996   assert_lock_strong(SpaceManager::expand_lock());
   997   _committed_words = _committed_words + v;
   999   assert_committed_below_limit();
  1001 void VirtualSpaceList::dec_committed_words(size_t v) {
  1002   assert_lock_strong(SpaceManager::expand_lock());
  1003   _committed_words = _committed_words - v;
  1005   assert_committed_below_limit();
  1008 void VirtualSpaceList::inc_virtual_space_count() {
  1009   assert_lock_strong(SpaceManager::expand_lock());
  1010   _virtual_space_count++;
  1012 void VirtualSpaceList::dec_virtual_space_count() {
  1013   assert_lock_strong(SpaceManager::expand_lock());
  1014   _virtual_space_count--;
  1017 void ChunkManager::remove_chunk(Metachunk* chunk) {
  1018   size_t word_size = chunk->word_size();
  1019   ChunkIndex index = list_index(word_size);
  1020   if (index != HumongousIndex) {
  1021     free_chunks(index)->remove_chunk(chunk);
  1022   } else {
  1023     humongous_dictionary()->remove_chunk(chunk);
  1026   // Chunk is being removed from the chunks free list.
  1027   dec_free_chunks_total(chunk->word_size());
  1030 // Walk the list of VirtualSpaceNodes and delete
  1031 // nodes with a 0 container_count.  Remove Metachunks in
  1032 // the node from their respective freelists.
  1033 void VirtualSpaceList::purge(ChunkManager* chunk_manager) {
  1034   assert_lock_strong(SpaceManager::expand_lock());
  1035   // Don't use a VirtualSpaceListIterator because this
  1036   // list is being changed and a straightforward use of an iterator is not safe.
  1037   VirtualSpaceNode* purged_vsl = NULL;
  1038   VirtualSpaceNode* prev_vsl = virtual_space_list();
  1039   VirtualSpaceNode* next_vsl = prev_vsl;
  1040   while (next_vsl != NULL) {
  1041     VirtualSpaceNode* vsl = next_vsl;
  1042     next_vsl = vsl->next();
  1043     // Don't free the current virtual space since it will likely
  1044     // be needed soon.
  1045     if (vsl->container_count() == 0 && vsl != current_virtual_space()) {
  1046       // Unlink it from the list
  1047       if (prev_vsl == vsl) {
  1048         // This is the case of the current node being the first node.
  1049         assert(vsl == virtual_space_list(), "Expected to be the first node");
  1050         set_virtual_space_list(vsl->next());
  1051       } else {
  1052         prev_vsl->set_next(vsl->next());
  1055       vsl->purge(chunk_manager);
  1056       dec_reserved_words(vsl->reserved_words());
  1057       dec_committed_words(vsl->committed_words());
  1058       dec_virtual_space_count();
  1059       purged_vsl = vsl;
  1060       delete vsl;
  1061     } else {
  1062       prev_vsl = vsl;
  1065 #ifdef ASSERT
  1066   if (purged_vsl != NULL) {
  1067   // List should be stable enough to use an iterator here.
  1068   VirtualSpaceListIterator iter(virtual_space_list());
  1069     while (iter.repeat()) {
  1070       VirtualSpaceNode* vsl = iter.get_next();
  1071       assert(vsl != purged_vsl, "Purge of vsl failed");
  1074 #endif
  1077 void VirtualSpaceList::retire_current_virtual_space() {
  1078   assert_lock_strong(SpaceManager::expand_lock());
  1080   VirtualSpaceNode* vsn = current_virtual_space();
  1082   ChunkManager* cm = is_class() ? Metaspace::chunk_manager_class() :
  1083                                   Metaspace::chunk_manager_metadata();
  1085   vsn->retire(cm);
  1088 void VirtualSpaceNode::retire(ChunkManager* chunk_manager) {
  1089   for (int i = (int)MediumIndex; i >= (int)ZeroIndex; --i) {
  1090     ChunkIndex index = (ChunkIndex)i;
  1091     size_t chunk_size = chunk_manager->free_chunks(index)->size();
  1093     while (free_words_in_vs() >= chunk_size) {
  1094       DEBUG_ONLY(verify_container_count();)
  1095       Metachunk* chunk = get_chunk_vs(chunk_size);
  1096       assert(chunk != NULL, "allocation should have been successful");
  1098       chunk_manager->return_chunks(index, chunk);
  1099       chunk_manager->inc_free_chunks_total(chunk_size);
  1100       DEBUG_ONLY(verify_container_count();)
  1103   assert(free_words_in_vs() == 0, "should be empty now");
  1106 VirtualSpaceList::VirtualSpaceList(size_t word_size) :
  1107                                    _is_class(false),
  1108                                    _virtual_space_list(NULL),
  1109                                    _current_virtual_space(NULL),
  1110                                    _reserved_words(0),
  1111                                    _committed_words(0),
  1112                                    _virtual_space_count(0) {
  1113   MutexLockerEx cl(SpaceManager::expand_lock(),
  1114                    Mutex::_no_safepoint_check_flag);
  1115   create_new_virtual_space(word_size);
  1118 VirtualSpaceList::VirtualSpaceList(ReservedSpace rs) :
  1119                                    _is_class(true),
  1120                                    _virtual_space_list(NULL),
  1121                                    _current_virtual_space(NULL),
  1122                                    _reserved_words(0),
  1123                                    _committed_words(0),
  1124                                    _virtual_space_count(0) {
  1125   MutexLockerEx cl(SpaceManager::expand_lock(),
  1126                    Mutex::_no_safepoint_check_flag);
  1127   VirtualSpaceNode* class_entry = new VirtualSpaceNode(rs);
  1128   bool succeeded = class_entry->initialize();
  1129   if (succeeded) {
  1130     link_vs(class_entry);
  1134 size_t VirtualSpaceList::free_bytes() {
  1135   return virtual_space_list()->free_words_in_vs() * BytesPerWord;
  1138 // Allocate another meta virtual space and add it to the list.
  1139 bool VirtualSpaceList::create_new_virtual_space(size_t vs_word_size) {
  1140   assert_lock_strong(SpaceManager::expand_lock());
  1142   if (is_class()) {
  1143     assert(false, "We currently don't support more than one VirtualSpace for"
  1144                   " the compressed class space. The initialization of the"
  1145                   " CCS uses another code path and should not hit this path.");
  1146     return false;
  1149   if (vs_word_size == 0) {
  1150     assert(false, "vs_word_size should always be at least _reserve_alignment large.");
  1151     return false;
  1154   // Reserve the space
  1155   size_t vs_byte_size = vs_word_size * BytesPerWord;
  1156   assert_is_size_aligned(vs_byte_size, Metaspace::reserve_alignment());
  1158   // Allocate the meta virtual space and initialize it.
  1159   VirtualSpaceNode* new_entry = new VirtualSpaceNode(vs_byte_size);
  1160   if (!new_entry->initialize()) {
  1161     delete new_entry;
  1162     return false;
  1163   } else {
  1164     assert(new_entry->reserved_words() == vs_word_size,
  1165         "Reserved memory size differs from requested memory size");
  1166     link_vs(new_entry);
  1167     return true;
  1171 void VirtualSpaceList::link_vs(VirtualSpaceNode* new_entry) {
  1172   if (virtual_space_list() == NULL) {
  1173       set_virtual_space_list(new_entry);
  1174   } else {
  1175     current_virtual_space()->set_next(new_entry);
  1177   set_current_virtual_space(new_entry);
  1178   inc_reserved_words(new_entry->reserved_words());
  1179   inc_committed_words(new_entry->committed_words());
  1180   inc_virtual_space_count();
  1181 #ifdef ASSERT
  1182   new_entry->mangle();
  1183 #endif
  1184   if (TraceMetavirtualspaceAllocation && Verbose) {
  1185     VirtualSpaceNode* vsl = current_virtual_space();
  1186     vsl->print_on(gclog_or_tty);
  1190 bool VirtualSpaceList::expand_node_by(VirtualSpaceNode* node,
  1191                                       size_t min_words,
  1192                                       size_t preferred_words) {
  1193   size_t before = node->committed_words();
  1195   bool result = node->expand_by(min_words, preferred_words);
  1197   size_t after = node->committed_words();
  1199   // after and before can be the same if the memory was pre-committed.
  1200   assert(after >= before, "Inconsistency");
  1201   inc_committed_words(after - before);
  1203   return result;
  1206 bool VirtualSpaceList::expand_by(size_t min_words, size_t preferred_words) {
  1207   assert_is_size_aligned(min_words,       Metaspace::commit_alignment_words());
  1208   assert_is_size_aligned(preferred_words, Metaspace::commit_alignment_words());
  1209   assert(min_words <= preferred_words, "Invalid arguments");
  1211   if (!MetaspaceGC::can_expand(min_words, this->is_class())) {
  1212     return  false;
  1215   size_t allowed_expansion_words = MetaspaceGC::allowed_expansion();
  1216   if (allowed_expansion_words < min_words) {
  1217     return false;
  1220   size_t max_expansion_words = MIN2(preferred_words, allowed_expansion_words);
  1222   // Commit more memory from the the current virtual space.
  1223   bool vs_expanded = expand_node_by(current_virtual_space(),
  1224                                     min_words,
  1225                                     max_expansion_words);
  1226   if (vs_expanded) {
  1227     return true;
  1229   retire_current_virtual_space();
  1231   // Get another virtual space.
  1232   size_t grow_vs_words = MAX2((size_t)VirtualSpaceSize, preferred_words);
  1233   grow_vs_words = align_size_up(grow_vs_words, Metaspace::reserve_alignment_words());
  1235   if (create_new_virtual_space(grow_vs_words)) {
  1236     if (current_virtual_space()->is_pre_committed()) {
  1237       // The memory was pre-committed, so we are done here.
  1238       assert(min_words <= current_virtual_space()->committed_words(),
  1239           "The new VirtualSpace was pre-committed, so it"
  1240           "should be large enough to fit the alloc request.");
  1241       return true;
  1244     return expand_node_by(current_virtual_space(),
  1245                           min_words,
  1246                           max_expansion_words);
  1249   return false;
  1252 Metachunk* VirtualSpaceList::get_new_chunk(size_t word_size,
  1253                                            size_t grow_chunks_by_words,
  1254                                            size_t medium_chunk_bunch) {
  1256   // Allocate a chunk out of the current virtual space.
  1257   Metachunk* next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
  1259   if (next != NULL) {
  1260     return next;
  1263   // The expand amount is currently only determined by the requested sizes
  1264   // and not how much committed memory is left in the current virtual space.
  1266   size_t min_word_size       = align_size_up(grow_chunks_by_words, Metaspace::commit_alignment_words());
  1267   size_t preferred_word_size = align_size_up(medium_chunk_bunch,   Metaspace::commit_alignment_words());
  1268   if (min_word_size >= preferred_word_size) {
  1269     // Can happen when humongous chunks are allocated.
  1270     preferred_word_size = min_word_size;
  1273   bool expanded = expand_by(min_word_size, preferred_word_size);
  1274   if (expanded) {
  1275     next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
  1276     assert(next != NULL, "The allocation was expected to succeed after the expansion");
  1279    return next;
  1282 void VirtualSpaceList::print_on(outputStream* st) const {
  1283   if (TraceMetadataChunkAllocation && Verbose) {
  1284     VirtualSpaceListIterator iter(virtual_space_list());
  1285     while (iter.repeat()) {
  1286       VirtualSpaceNode* node = iter.get_next();
  1287       node->print_on(st);
  1292 // MetaspaceGC methods
  1294 // VM_CollectForMetadataAllocation is the vm operation used to GC.
  1295 // Within the VM operation after the GC the attempt to allocate the metadata
  1296 // should succeed.  If the GC did not free enough space for the metaspace
  1297 // allocation, the HWM is increased so that another virtualspace will be
  1298 // allocated for the metadata.  With perm gen the increase in the perm
  1299 // gen had bounds, MinMetaspaceExpansion and MaxMetaspaceExpansion.  The
  1300 // metaspace policy uses those as the small and large steps for the HWM.
  1301 //
  1302 // After the GC the compute_new_size() for MetaspaceGC is called to
  1303 // resize the capacity of the metaspaces.  The current implementation
  1304 // is based on the flags MinMetaspaceFreeRatio and MaxMetaspaceFreeRatio used
  1305 // to resize the Java heap by some GC's.  New flags can be implemented
  1306 // if really needed.  MinMetaspaceFreeRatio is used to calculate how much
  1307 // free space is desirable in the metaspace capacity to decide how much
  1308 // to increase the HWM.  MaxMetaspaceFreeRatio is used to decide how much
  1309 // free space is desirable in the metaspace capacity before decreasing
  1310 // the HWM.
  1312 // Calculate the amount to increase the high water mark (HWM).
  1313 // Increase by a minimum amount (MinMetaspaceExpansion) so that
  1314 // another expansion is not requested too soon.  If that is not
  1315 // enough to satisfy the allocation, increase by MaxMetaspaceExpansion.
  1316 // If that is still not enough, expand by the size of the allocation
  1317 // plus some.
  1318 size_t MetaspaceGC::delta_capacity_until_GC(size_t bytes) {
  1319   size_t min_delta = MinMetaspaceExpansion;
  1320   size_t max_delta = MaxMetaspaceExpansion;
  1321   size_t delta = align_size_up(bytes, Metaspace::commit_alignment());
  1323   if (delta <= min_delta) {
  1324     delta = min_delta;
  1325   } else if (delta <= max_delta) {
  1326     // Don't want to hit the high water mark on the next
  1327     // allocation so make the delta greater than just enough
  1328     // for this allocation.
  1329     delta = max_delta;
  1330   } else {
  1331     // This allocation is large but the next ones are probably not
  1332     // so increase by the minimum.
  1333     delta = delta + min_delta;
  1336   assert_is_size_aligned(delta, Metaspace::commit_alignment());
  1338   return delta;
  1341 size_t MetaspaceGC::capacity_until_GC() {
  1342   size_t value = (size_t)OrderAccess::load_ptr_acquire(&_capacity_until_GC);
  1343   assert(value >= MetaspaceSize, "Not initialied properly?");
  1344   return value;
  1347 size_t MetaspaceGC::inc_capacity_until_GC(size_t v) {
  1348   assert_is_size_aligned(v, Metaspace::commit_alignment());
  1350   return (size_t)Atomic::add_ptr(v, &_capacity_until_GC);
  1353 size_t MetaspaceGC::dec_capacity_until_GC(size_t v) {
  1354   assert_is_size_aligned(v, Metaspace::commit_alignment());
  1356   return (size_t)Atomic::add_ptr(-(intptr_t)v, &_capacity_until_GC);
  1359 bool MetaspaceGC::can_expand(size_t word_size, bool is_class) {
  1360   // Check if the compressed class space is full.
  1361   if (is_class && Metaspace::using_class_space()) {
  1362     size_t class_committed = MetaspaceAux::committed_bytes(Metaspace::ClassType);
  1363     if (class_committed + word_size * BytesPerWord > CompressedClassSpaceSize) {
  1364       return false;
  1368   // Check if the user has imposed a limit on the metaspace memory.
  1369   size_t committed_bytes = MetaspaceAux::committed_bytes();
  1370   if (committed_bytes + word_size * BytesPerWord > MaxMetaspaceSize) {
  1371     return false;
  1374   return true;
  1377 size_t MetaspaceGC::allowed_expansion() {
  1378   size_t committed_bytes = MetaspaceAux::committed_bytes();
  1380   size_t left_until_max  = MaxMetaspaceSize - committed_bytes;
  1382   // Always grant expansion if we are initiating the JVM,
  1383   // or if the GC_locker is preventing GCs.
  1384   if (!is_init_completed() || GC_locker::is_active_and_needs_gc()) {
  1385     return left_until_max / BytesPerWord;
  1388   size_t capacity_until_gc = capacity_until_GC();
  1390   if (capacity_until_gc <= committed_bytes) {
  1391     return 0;
  1394   size_t left_until_GC = capacity_until_gc - committed_bytes;
  1395   size_t left_to_commit = MIN2(left_until_GC, left_until_max);
  1397   return left_to_commit / BytesPerWord;
  1400 void MetaspaceGC::compute_new_size() {
  1401   assert(_shrink_factor <= 100, "invalid shrink factor");
  1402   uint current_shrink_factor = _shrink_factor;
  1403   _shrink_factor = 0;
  1405   const size_t used_after_gc = MetaspaceAux::allocated_capacity_bytes();
  1406   const size_t capacity_until_GC = MetaspaceGC::capacity_until_GC();
  1408   const double minimum_free_percentage = MinMetaspaceFreeRatio / 100.0;
  1409   const double maximum_used_percentage = 1.0 - minimum_free_percentage;
  1411   const double min_tmp = used_after_gc / maximum_used_percentage;
  1412   size_t minimum_desired_capacity =
  1413     (size_t)MIN2(min_tmp, double(max_uintx));
  1414   // Don't shrink less than the initial generation size
  1415   minimum_desired_capacity = MAX2(minimum_desired_capacity,
  1416                                   MetaspaceSize);
  1418   if (PrintGCDetails && Verbose) {
  1419     gclog_or_tty->print_cr("\nMetaspaceGC::compute_new_size: ");
  1420     gclog_or_tty->print_cr("  "
  1421                   "  minimum_free_percentage: %6.2f"
  1422                   "  maximum_used_percentage: %6.2f",
  1423                   minimum_free_percentage,
  1424                   maximum_used_percentage);
  1425     gclog_or_tty->print_cr("  "
  1426                   "   used_after_gc       : %6.1fKB",
  1427                   used_after_gc / (double) K);
  1431   size_t shrink_bytes = 0;
  1432   if (capacity_until_GC < minimum_desired_capacity) {
  1433     // If we have less capacity below the metaspace HWM, then
  1434     // increment the HWM.
  1435     size_t expand_bytes = minimum_desired_capacity - capacity_until_GC;
  1436     expand_bytes = align_size_up(expand_bytes, Metaspace::commit_alignment());
  1437     // Don't expand unless it's significant
  1438     if (expand_bytes >= MinMetaspaceExpansion) {
  1439       MetaspaceGC::inc_capacity_until_GC(expand_bytes);
  1441     if (PrintGCDetails && Verbose) {
  1442       size_t new_capacity_until_GC = capacity_until_GC;
  1443       gclog_or_tty->print_cr("    expanding:"
  1444                     "  minimum_desired_capacity: %6.1fKB"
  1445                     "  expand_bytes: %6.1fKB"
  1446                     "  MinMetaspaceExpansion: %6.1fKB"
  1447                     "  new metaspace HWM:  %6.1fKB",
  1448                     minimum_desired_capacity / (double) K,
  1449                     expand_bytes / (double) K,
  1450                     MinMetaspaceExpansion / (double) K,
  1451                     new_capacity_until_GC / (double) K);
  1453     return;
  1456   // No expansion, now see if we want to shrink
  1457   // We would never want to shrink more than this
  1458   size_t max_shrink_bytes = capacity_until_GC - minimum_desired_capacity;
  1459   assert(max_shrink_bytes >= 0, err_msg("max_shrink_bytes " SIZE_FORMAT,
  1460     max_shrink_bytes));
  1462   // Should shrinking be considered?
  1463   if (MaxMetaspaceFreeRatio < 100) {
  1464     const double maximum_free_percentage = MaxMetaspaceFreeRatio / 100.0;
  1465     const double minimum_used_percentage = 1.0 - maximum_free_percentage;
  1466     const double max_tmp = used_after_gc / minimum_used_percentage;
  1467     size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(max_uintx));
  1468     maximum_desired_capacity = MAX2(maximum_desired_capacity,
  1469                                     MetaspaceSize);
  1470     if (PrintGCDetails && Verbose) {
  1471       gclog_or_tty->print_cr("  "
  1472                              "  maximum_free_percentage: %6.2f"
  1473                              "  minimum_used_percentage: %6.2f",
  1474                              maximum_free_percentage,
  1475                              minimum_used_percentage);
  1476       gclog_or_tty->print_cr("  "
  1477                              "  minimum_desired_capacity: %6.1fKB"
  1478                              "  maximum_desired_capacity: %6.1fKB",
  1479                              minimum_desired_capacity / (double) K,
  1480                              maximum_desired_capacity / (double) K);
  1483     assert(minimum_desired_capacity <= maximum_desired_capacity,
  1484            "sanity check");
  1486     if (capacity_until_GC > maximum_desired_capacity) {
  1487       // Capacity too large, compute shrinking size
  1488       shrink_bytes = capacity_until_GC - maximum_desired_capacity;
  1489       // We don't want shrink all the way back to initSize if people call
  1490       // System.gc(), because some programs do that between "phases" and then
  1491       // we'd just have to grow the heap up again for the next phase.  So we
  1492       // damp the shrinking: 0% on the first call, 10% on the second call, 40%
  1493       // on the third call, and 100% by the fourth call.  But if we recompute
  1494       // size without shrinking, it goes back to 0%.
  1495       shrink_bytes = shrink_bytes / 100 * current_shrink_factor;
  1497       shrink_bytes = align_size_down(shrink_bytes, Metaspace::commit_alignment());
  1499       assert(shrink_bytes <= max_shrink_bytes,
  1500         err_msg("invalid shrink size " SIZE_FORMAT " not <= " SIZE_FORMAT,
  1501           shrink_bytes, max_shrink_bytes));
  1502       if (current_shrink_factor == 0) {
  1503         _shrink_factor = 10;
  1504       } else {
  1505         _shrink_factor = MIN2(current_shrink_factor * 4, (uint) 100);
  1507       if (PrintGCDetails && Verbose) {
  1508         gclog_or_tty->print_cr("  "
  1509                       "  shrinking:"
  1510                       "  initSize: %.1fK"
  1511                       "  maximum_desired_capacity: %.1fK",
  1512                       MetaspaceSize / (double) K,
  1513                       maximum_desired_capacity / (double) K);
  1514         gclog_or_tty->print_cr("  "
  1515                       "  shrink_bytes: %.1fK"
  1516                       "  current_shrink_factor: %d"
  1517                       "  new shrink factor: %d"
  1518                       "  MinMetaspaceExpansion: %.1fK",
  1519                       shrink_bytes / (double) K,
  1520                       current_shrink_factor,
  1521                       _shrink_factor,
  1522                       MinMetaspaceExpansion / (double) K);
  1527   // Don't shrink unless it's significant
  1528   if (shrink_bytes >= MinMetaspaceExpansion &&
  1529       ((capacity_until_GC - shrink_bytes) >= MetaspaceSize)) {
  1530     MetaspaceGC::dec_capacity_until_GC(shrink_bytes);
  1534 // Metadebug methods
  1536 void Metadebug::init_allocation_fail_alot_count() {
  1537   if (MetadataAllocationFailALot) {
  1538     _allocation_fail_alot_count =
  1539       1+(long)((double)MetadataAllocationFailALotInterval*os::random()/(max_jint+1.0));
  1543 #ifdef ASSERT
  1544 bool Metadebug::test_metadata_failure() {
  1545   if (MetadataAllocationFailALot &&
  1546       Threads::is_vm_complete()) {
  1547     if (_allocation_fail_alot_count > 0) {
  1548       _allocation_fail_alot_count--;
  1549     } else {
  1550       if (TraceMetadataChunkAllocation && Verbose) {
  1551         gclog_or_tty->print_cr("Metadata allocation failing for "
  1552                                "MetadataAllocationFailALot");
  1554       init_allocation_fail_alot_count();
  1555       return true;
  1558   return false;
  1560 #endif
  1562 // ChunkManager methods
  1564 size_t ChunkManager::free_chunks_total_words() {
  1565   return _free_chunks_total;
  1568 size_t ChunkManager::free_chunks_total_bytes() {
  1569   return free_chunks_total_words() * BytesPerWord;
  1572 size_t ChunkManager::free_chunks_count() {
  1573 #ifdef ASSERT
  1574   if (!UseConcMarkSweepGC && !SpaceManager::expand_lock()->is_locked()) {
  1575     MutexLockerEx cl(SpaceManager::expand_lock(),
  1576                      Mutex::_no_safepoint_check_flag);
  1577     // This lock is only needed in debug because the verification
  1578     // of the _free_chunks_totals walks the list of free chunks
  1579     slow_locked_verify_free_chunks_count();
  1581 #endif
  1582   return _free_chunks_count;
  1585 void ChunkManager::locked_verify_free_chunks_total() {
  1586   assert_lock_strong(SpaceManager::expand_lock());
  1587   assert(sum_free_chunks() == _free_chunks_total,
  1588     err_msg("_free_chunks_total " SIZE_FORMAT " is not the"
  1589            " same as sum " SIZE_FORMAT, _free_chunks_total,
  1590            sum_free_chunks()));
  1593 void ChunkManager::verify_free_chunks_total() {
  1594   MutexLockerEx cl(SpaceManager::expand_lock(),
  1595                      Mutex::_no_safepoint_check_flag);
  1596   locked_verify_free_chunks_total();
  1599 void ChunkManager::locked_verify_free_chunks_count() {
  1600   assert_lock_strong(SpaceManager::expand_lock());
  1601   assert(sum_free_chunks_count() == _free_chunks_count,
  1602     err_msg("_free_chunks_count " SIZE_FORMAT " is not the"
  1603            " same as sum " SIZE_FORMAT, _free_chunks_count,
  1604            sum_free_chunks_count()));
  1607 void ChunkManager::verify_free_chunks_count() {
  1608 #ifdef ASSERT
  1609   MutexLockerEx cl(SpaceManager::expand_lock(),
  1610                      Mutex::_no_safepoint_check_flag);
  1611   locked_verify_free_chunks_count();
  1612 #endif
  1615 void ChunkManager::verify() {
  1616   MutexLockerEx cl(SpaceManager::expand_lock(),
  1617                      Mutex::_no_safepoint_check_flag);
  1618   locked_verify();
  1621 void ChunkManager::locked_verify() {
  1622   locked_verify_free_chunks_count();
  1623   locked_verify_free_chunks_total();
  1626 void ChunkManager::locked_print_free_chunks(outputStream* st) {
  1627   assert_lock_strong(SpaceManager::expand_lock());
  1628   st->print_cr("Free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
  1629                 _free_chunks_total, _free_chunks_count);
  1632 void ChunkManager::locked_print_sum_free_chunks(outputStream* st) {
  1633   assert_lock_strong(SpaceManager::expand_lock());
  1634   st->print_cr("Sum free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
  1635                 sum_free_chunks(), sum_free_chunks_count());
  1637 ChunkList* ChunkManager::free_chunks(ChunkIndex index) {
  1638   return &_free_chunks[index];
  1641 // These methods that sum the free chunk lists are used in printing
  1642 // methods that are used in product builds.
  1643 size_t ChunkManager::sum_free_chunks() {
  1644   assert_lock_strong(SpaceManager::expand_lock());
  1645   size_t result = 0;
  1646   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
  1647     ChunkList* list = free_chunks(i);
  1649     if (list == NULL) {
  1650       continue;
  1653     result = result + list->count() * list->size();
  1655   result = result + humongous_dictionary()->total_size();
  1656   return result;
  1659 size_t ChunkManager::sum_free_chunks_count() {
  1660   assert_lock_strong(SpaceManager::expand_lock());
  1661   size_t count = 0;
  1662   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
  1663     ChunkList* list = free_chunks(i);
  1664     if (list == NULL) {
  1665       continue;
  1667     count = count + list->count();
  1669   count = count + humongous_dictionary()->total_free_blocks();
  1670   return count;
  1673 ChunkList* ChunkManager::find_free_chunks_list(size_t word_size) {
  1674   ChunkIndex index = list_index(word_size);
  1675   assert(index < HumongousIndex, "No humongous list");
  1676   return free_chunks(index);
  1679 Metachunk* ChunkManager::free_chunks_get(size_t word_size) {
  1680   assert_lock_strong(SpaceManager::expand_lock());
  1682   slow_locked_verify();
  1684   Metachunk* chunk = NULL;
  1685   if (list_index(word_size) != HumongousIndex) {
  1686     ChunkList* free_list = find_free_chunks_list(word_size);
  1687     assert(free_list != NULL, "Sanity check");
  1689     chunk = free_list->head();
  1691     if (chunk == NULL) {
  1692       return NULL;
  1695     // Remove the chunk as the head of the list.
  1696     free_list->remove_chunk(chunk);
  1698     if (TraceMetadataChunkAllocation && Verbose) {
  1699       gclog_or_tty->print_cr("ChunkManager::free_chunks_get: free_list "
  1700                              PTR_FORMAT " head " PTR_FORMAT " size " SIZE_FORMAT,
  1701                              free_list, chunk, chunk->word_size());
  1703   } else {
  1704     chunk = humongous_dictionary()->get_chunk(
  1705       word_size,
  1706       FreeBlockDictionary<Metachunk>::atLeast);
  1708     if (chunk == NULL) {
  1709       return NULL;
  1712     if (TraceMetadataHumongousAllocation) {
  1713       size_t waste = chunk->word_size() - word_size;
  1714       gclog_or_tty->print_cr("Free list allocate humongous chunk size "
  1715                              SIZE_FORMAT " for requested size " SIZE_FORMAT
  1716                              " waste " SIZE_FORMAT,
  1717                              chunk->word_size(), word_size, waste);
  1721   // Chunk is being removed from the chunks free list.
  1722   dec_free_chunks_total(chunk->word_size());
  1724   // Remove it from the links to this freelist
  1725   chunk->set_next(NULL);
  1726   chunk->set_prev(NULL);
  1727 #ifdef ASSERT
  1728   // Chunk is no longer on any freelist. Setting to false make container_count_slow()
  1729   // work.
  1730   chunk->set_is_tagged_free(false);
  1731 #endif
  1732   chunk->container()->inc_container_count();
  1734   slow_locked_verify();
  1735   return chunk;
  1738 Metachunk* ChunkManager::chunk_freelist_allocate(size_t word_size) {
  1739   assert_lock_strong(SpaceManager::expand_lock());
  1740   slow_locked_verify();
  1742   // Take from the beginning of the list
  1743   Metachunk* chunk = free_chunks_get(word_size);
  1744   if (chunk == NULL) {
  1745     return NULL;
  1748   assert((word_size <= chunk->word_size()) ||
  1749          list_index(chunk->word_size() == HumongousIndex),
  1750          "Non-humongous variable sized chunk");
  1751   if (TraceMetadataChunkAllocation) {
  1752     size_t list_count;
  1753     if (list_index(word_size) < HumongousIndex) {
  1754       ChunkList* list = find_free_chunks_list(word_size);
  1755       list_count = list->count();
  1756     } else {
  1757       list_count = humongous_dictionary()->total_count();
  1759     gclog_or_tty->print("ChunkManager::chunk_freelist_allocate: " PTR_FORMAT " chunk "
  1760                         PTR_FORMAT "  size " SIZE_FORMAT " count " SIZE_FORMAT " ",
  1761                         this, chunk, chunk->word_size(), list_count);
  1762     locked_print_free_chunks(gclog_or_tty);
  1765   return chunk;
  1768 void ChunkManager::print_on(outputStream* out) const {
  1769   if (PrintFLSStatistics != 0) {
  1770     const_cast<ChunkManager *>(this)->humongous_dictionary()->report_statistics();
  1774 // SpaceManager methods
  1776 void SpaceManager::get_initial_chunk_sizes(Metaspace::MetaspaceType type,
  1777                                            size_t* chunk_word_size,
  1778                                            size_t* class_chunk_word_size) {
  1779   switch (type) {
  1780   case Metaspace::BootMetaspaceType:
  1781     *chunk_word_size = Metaspace::first_chunk_word_size();
  1782     *class_chunk_word_size = Metaspace::first_class_chunk_word_size();
  1783     break;
  1784   case Metaspace::ROMetaspaceType:
  1785     *chunk_word_size = SharedReadOnlySize / wordSize;
  1786     *class_chunk_word_size = ClassSpecializedChunk;
  1787     break;
  1788   case Metaspace::ReadWriteMetaspaceType:
  1789     *chunk_word_size = SharedReadWriteSize / wordSize;
  1790     *class_chunk_word_size = ClassSpecializedChunk;
  1791     break;
  1792   case Metaspace::AnonymousMetaspaceType:
  1793   case Metaspace::ReflectionMetaspaceType:
  1794     *chunk_word_size = SpecializedChunk;
  1795     *class_chunk_word_size = ClassSpecializedChunk;
  1796     break;
  1797   default:
  1798     *chunk_word_size = SmallChunk;
  1799     *class_chunk_word_size = ClassSmallChunk;
  1800     break;
  1802   assert(*chunk_word_size != 0 && *class_chunk_word_size != 0,
  1803     err_msg("Initial chunks sizes bad: data  " SIZE_FORMAT
  1804             " class " SIZE_FORMAT,
  1805             *chunk_word_size, *class_chunk_word_size));
  1808 size_t SpaceManager::sum_free_in_chunks_in_use() const {
  1809   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1810   size_t free = 0;
  1811   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1812     Metachunk* chunk = chunks_in_use(i);
  1813     while (chunk != NULL) {
  1814       free += chunk->free_word_size();
  1815       chunk = chunk->next();
  1818   return free;
  1821 size_t SpaceManager::sum_waste_in_chunks_in_use() const {
  1822   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1823   size_t result = 0;
  1824   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1825    result += sum_waste_in_chunks_in_use(i);
  1828   return result;
  1831 size_t SpaceManager::sum_waste_in_chunks_in_use(ChunkIndex index) const {
  1832   size_t result = 0;
  1833   Metachunk* chunk = chunks_in_use(index);
  1834   // Count the free space in all the chunk but not the
  1835   // current chunk from which allocations are still being done.
  1836   while (chunk != NULL) {
  1837     if (chunk != current_chunk()) {
  1838       result += chunk->free_word_size();
  1840     chunk = chunk->next();
  1842   return result;
  1845 size_t SpaceManager::sum_capacity_in_chunks_in_use() const {
  1846   // For CMS use "allocated_chunks_words()" which does not need the
  1847   // Metaspace lock.  For the other collectors sum over the
  1848   // lists.  Use both methods as a check that "allocated_chunks_words()"
  1849   // is correct.  That is, sum_capacity_in_chunks() is too expensive
  1850   // to use in the product and allocated_chunks_words() should be used
  1851   // but allow for  checking that allocated_chunks_words() returns the same
  1852   // value as sum_capacity_in_chunks_in_use() which is the definitive
  1853   // answer.
  1854   if (UseConcMarkSweepGC) {
  1855     return allocated_chunks_words();
  1856   } else {
  1857     MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1858     size_t sum = 0;
  1859     for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1860       Metachunk* chunk = chunks_in_use(i);
  1861       while (chunk != NULL) {
  1862         sum += chunk->word_size();
  1863         chunk = chunk->next();
  1866   return sum;
  1870 size_t SpaceManager::sum_count_in_chunks_in_use() {
  1871   size_t count = 0;
  1872   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1873     count = count + sum_count_in_chunks_in_use(i);
  1876   return count;
  1879 size_t SpaceManager::sum_count_in_chunks_in_use(ChunkIndex i) {
  1880   size_t count = 0;
  1881   Metachunk* chunk = chunks_in_use(i);
  1882   while (chunk != NULL) {
  1883     count++;
  1884     chunk = chunk->next();
  1886   return count;
  1890 size_t SpaceManager::sum_used_in_chunks_in_use() const {
  1891   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1892   size_t used = 0;
  1893   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1894     Metachunk* chunk = chunks_in_use(i);
  1895     while (chunk != NULL) {
  1896       used += chunk->used_word_size();
  1897       chunk = chunk->next();
  1900   return used;
  1903 void SpaceManager::locked_print_chunks_in_use_on(outputStream* st) const {
  1905   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1906     Metachunk* chunk = chunks_in_use(i);
  1907     st->print("SpaceManager: %s " PTR_FORMAT,
  1908                  chunk_size_name(i), chunk);
  1909     if (chunk != NULL) {
  1910       st->print_cr(" free " SIZE_FORMAT,
  1911                    chunk->free_word_size());
  1912     } else {
  1913       st->print_cr("");
  1917   chunk_manager()->locked_print_free_chunks(st);
  1918   chunk_manager()->locked_print_sum_free_chunks(st);
  1921 size_t SpaceManager::calc_chunk_size(size_t word_size) {
  1923   // Decide between a small chunk and a medium chunk.  Up to
  1924   // _small_chunk_limit small chunks can be allocated but
  1925   // once a medium chunk has been allocated, no more small
  1926   // chunks will be allocated.
  1927   size_t chunk_word_size;
  1928   if (chunks_in_use(MediumIndex) == NULL &&
  1929       sum_count_in_chunks_in_use(SmallIndex) < _small_chunk_limit) {
  1930     chunk_word_size = (size_t) small_chunk_size();
  1931     if (word_size + Metachunk::overhead() > small_chunk_size()) {
  1932       chunk_word_size = medium_chunk_size();
  1934   } else {
  1935     chunk_word_size = medium_chunk_size();
  1938   // Might still need a humongous chunk.  Enforce
  1939   // humongous allocations sizes to be aligned up to
  1940   // the smallest chunk size.
  1941   size_t if_humongous_sized_chunk =
  1942     align_size_up(word_size + Metachunk::overhead(),
  1943                   smallest_chunk_size());
  1944   chunk_word_size =
  1945     MAX2((size_t) chunk_word_size, if_humongous_sized_chunk);
  1947   assert(!SpaceManager::is_humongous(word_size) ||
  1948          chunk_word_size == if_humongous_sized_chunk,
  1949          err_msg("Size calculation is wrong, word_size " SIZE_FORMAT
  1950                  " chunk_word_size " SIZE_FORMAT,
  1951                  word_size, chunk_word_size));
  1952   if (TraceMetadataHumongousAllocation &&
  1953       SpaceManager::is_humongous(word_size)) {
  1954     gclog_or_tty->print_cr("Metadata humongous allocation:");
  1955     gclog_or_tty->print_cr("  word_size " PTR_FORMAT, word_size);
  1956     gclog_or_tty->print_cr("  chunk_word_size " PTR_FORMAT,
  1957                            chunk_word_size);
  1958     gclog_or_tty->print_cr("    chunk overhead " PTR_FORMAT,
  1959                            Metachunk::overhead());
  1961   return chunk_word_size;
  1964 void SpaceManager::track_metaspace_memory_usage() {
  1965   if (is_init_completed()) {
  1966     if (is_class()) {
  1967       MemoryService::track_compressed_class_memory_usage();
  1969     MemoryService::track_metaspace_memory_usage();
  1973 MetaWord* SpaceManager::grow_and_allocate(size_t word_size) {
  1974   assert(vs_list()->current_virtual_space() != NULL,
  1975          "Should have been set");
  1976   assert(current_chunk() == NULL ||
  1977          current_chunk()->allocate(word_size) == NULL,
  1978          "Don't need to expand");
  1979   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  1981   if (TraceMetadataChunkAllocation && Verbose) {
  1982     size_t words_left = 0;
  1983     size_t words_used = 0;
  1984     if (current_chunk() != NULL) {
  1985       words_left = current_chunk()->free_word_size();
  1986       words_used = current_chunk()->used_word_size();
  1988     gclog_or_tty->print_cr("SpaceManager::grow_and_allocate for " SIZE_FORMAT
  1989                            " words " SIZE_FORMAT " words used " SIZE_FORMAT
  1990                            " words left",
  1991                             word_size, words_used, words_left);
  1994   // Get another chunk out of the virtual space
  1995   size_t grow_chunks_by_words = calc_chunk_size(word_size);
  1996   Metachunk* next = get_new_chunk(word_size, grow_chunks_by_words);
  1998   MetaWord* mem = NULL;
  2000   // If a chunk was available, add it to the in-use chunk list
  2001   // and do an allocation from it.
  2002   if (next != NULL) {
  2003     // Add to this manager's list of chunks in use.
  2004     add_chunk(next, false);
  2005     mem = next->allocate(word_size);
  2008   // Track metaspace memory usage statistic.
  2009   track_metaspace_memory_usage();
  2011   return mem;
  2014 void SpaceManager::print_on(outputStream* st) const {
  2016   for (ChunkIndex i = ZeroIndex;
  2017        i < NumberOfInUseLists ;
  2018        i = next_chunk_index(i) ) {
  2019     st->print_cr("  chunks_in_use " PTR_FORMAT " chunk size " PTR_FORMAT,
  2020                  chunks_in_use(i),
  2021                  chunks_in_use(i) == NULL ? 0 : chunks_in_use(i)->word_size());
  2023   st->print_cr("    waste:  Small " SIZE_FORMAT " Medium " SIZE_FORMAT
  2024                " Humongous " SIZE_FORMAT,
  2025                sum_waste_in_chunks_in_use(SmallIndex),
  2026                sum_waste_in_chunks_in_use(MediumIndex),
  2027                sum_waste_in_chunks_in_use(HumongousIndex));
  2028   // block free lists
  2029   if (block_freelists() != NULL) {
  2030     st->print_cr("total in block free lists " SIZE_FORMAT,
  2031       block_freelists()->total_size());
  2035 SpaceManager::SpaceManager(Metaspace::MetadataType mdtype,
  2036                            Mutex* lock) :
  2037   _mdtype(mdtype),
  2038   _allocated_blocks_words(0),
  2039   _allocated_chunks_words(0),
  2040   _allocated_chunks_count(0),
  2041   _lock(lock)
  2043   initialize();
  2046 void SpaceManager::inc_size_metrics(size_t words) {
  2047   assert_lock_strong(SpaceManager::expand_lock());
  2048   // Total of allocated Metachunks and allocated Metachunks count
  2049   // for each SpaceManager
  2050   _allocated_chunks_words = _allocated_chunks_words + words;
  2051   _allocated_chunks_count++;
  2052   // Global total of capacity in allocated Metachunks
  2053   MetaspaceAux::inc_capacity(mdtype(), words);
  2054   // Global total of allocated Metablocks.
  2055   // used_words_slow() includes the overhead in each
  2056   // Metachunk so include it in the used when the
  2057   // Metachunk is first added (so only added once per
  2058   // Metachunk).
  2059   MetaspaceAux::inc_used(mdtype(), Metachunk::overhead());
  2062 void SpaceManager::inc_used_metrics(size_t words) {
  2063   // Add to the per SpaceManager total
  2064   Atomic::add_ptr(words, &_allocated_blocks_words);
  2065   // Add to the global total
  2066   MetaspaceAux::inc_used(mdtype(), words);
  2069 void SpaceManager::dec_total_from_size_metrics() {
  2070   MetaspaceAux::dec_capacity(mdtype(), allocated_chunks_words());
  2071   MetaspaceAux::dec_used(mdtype(), allocated_blocks_words());
  2072   // Also deduct the overhead per Metachunk
  2073   MetaspaceAux::dec_used(mdtype(), allocated_chunks_count() * Metachunk::overhead());
  2076 void SpaceManager::initialize() {
  2077   Metadebug::init_allocation_fail_alot_count();
  2078   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2079     _chunks_in_use[i] = NULL;
  2081   _current_chunk = NULL;
  2082   if (TraceMetadataChunkAllocation && Verbose) {
  2083     gclog_or_tty->print_cr("SpaceManager(): " PTR_FORMAT, this);
  2087 void ChunkManager::return_chunks(ChunkIndex index, Metachunk* chunks) {
  2088   if (chunks == NULL) {
  2089     return;
  2091   ChunkList* list = free_chunks(index);
  2092   assert(list->size() == chunks->word_size(), "Mismatch in chunk sizes");
  2093   assert_lock_strong(SpaceManager::expand_lock());
  2094   Metachunk* cur = chunks;
  2096   // This returns chunks one at a time.  If a new
  2097   // class List can be created that is a base class
  2098   // of FreeList then something like FreeList::prepend()
  2099   // can be used in place of this loop
  2100   while (cur != NULL) {
  2101     assert(cur->container() != NULL, "Container should have been set");
  2102     cur->container()->dec_container_count();
  2103     // Capture the next link before it is changed
  2104     // by the call to return_chunk_at_head();
  2105     Metachunk* next = cur->next();
  2106     DEBUG_ONLY(cur->set_is_tagged_free(true);)
  2107     list->return_chunk_at_head(cur);
  2108     cur = next;
  2112 SpaceManager::~SpaceManager() {
  2113   // This call this->_lock which can't be done while holding expand_lock()
  2114   assert(sum_capacity_in_chunks_in_use() == allocated_chunks_words(),
  2115     err_msg("sum_capacity_in_chunks_in_use() " SIZE_FORMAT
  2116             " allocated_chunks_words() " SIZE_FORMAT,
  2117             sum_capacity_in_chunks_in_use(), allocated_chunks_words()));
  2119   MutexLockerEx fcl(SpaceManager::expand_lock(),
  2120                     Mutex::_no_safepoint_check_flag);
  2122   chunk_manager()->slow_locked_verify();
  2124   dec_total_from_size_metrics();
  2126   if (TraceMetadataChunkAllocation && Verbose) {
  2127     gclog_or_tty->print_cr("~SpaceManager(): " PTR_FORMAT, this);
  2128     locked_print_chunks_in_use_on(gclog_or_tty);
  2131   // Do not mangle freed Metachunks.  The chunk size inside Metachunks
  2132   // is during the freeing of a VirtualSpaceNodes.
  2134   // Have to update before the chunks_in_use lists are emptied
  2135   // below.
  2136   chunk_manager()->inc_free_chunks_total(allocated_chunks_words(),
  2137                                          sum_count_in_chunks_in_use());
  2139   // Add all the chunks in use by this space manager
  2140   // to the global list of free chunks.
  2142   // Follow each list of chunks-in-use and add them to the
  2143   // free lists.  Each list is NULL terminated.
  2145   for (ChunkIndex i = ZeroIndex; i < HumongousIndex; i = next_chunk_index(i)) {
  2146     if (TraceMetadataChunkAllocation && Verbose) {
  2147       gclog_or_tty->print_cr("returned %d %s chunks to freelist",
  2148                              sum_count_in_chunks_in_use(i),
  2149                              chunk_size_name(i));
  2151     Metachunk* chunks = chunks_in_use(i);
  2152     chunk_manager()->return_chunks(i, chunks);
  2153     set_chunks_in_use(i, NULL);
  2154     if (TraceMetadataChunkAllocation && Verbose) {
  2155       gclog_or_tty->print_cr("updated freelist count %d %s",
  2156                              chunk_manager()->free_chunks(i)->count(),
  2157                              chunk_size_name(i));
  2159     assert(i != HumongousIndex, "Humongous chunks are handled explicitly later");
  2162   // The medium chunk case may be optimized by passing the head and
  2163   // tail of the medium chunk list to add_at_head().  The tail is often
  2164   // the current chunk but there are probably exceptions.
  2166   // Humongous chunks
  2167   if (TraceMetadataChunkAllocation && Verbose) {
  2168     gclog_or_tty->print_cr("returned %d %s humongous chunks to dictionary",
  2169                             sum_count_in_chunks_in_use(HumongousIndex),
  2170                             chunk_size_name(HumongousIndex));
  2171     gclog_or_tty->print("Humongous chunk dictionary: ");
  2173   // Humongous chunks are never the current chunk.
  2174   Metachunk* humongous_chunks = chunks_in_use(HumongousIndex);
  2176   while (humongous_chunks != NULL) {
  2177 #ifdef ASSERT
  2178     humongous_chunks->set_is_tagged_free(true);
  2179 #endif
  2180     if (TraceMetadataChunkAllocation && Verbose) {
  2181       gclog_or_tty->print(PTR_FORMAT " (" SIZE_FORMAT ") ",
  2182                           humongous_chunks,
  2183                           humongous_chunks->word_size());
  2185     assert(humongous_chunks->word_size() == (size_t)
  2186            align_size_up(humongous_chunks->word_size(),
  2187                              smallest_chunk_size()),
  2188            err_msg("Humongous chunk size is wrong: word size " SIZE_FORMAT
  2189                    " granularity %d",
  2190                    humongous_chunks->word_size(), smallest_chunk_size()));
  2191     Metachunk* next_humongous_chunks = humongous_chunks->next();
  2192     humongous_chunks->container()->dec_container_count();
  2193     chunk_manager()->humongous_dictionary()->return_chunk(humongous_chunks);
  2194     humongous_chunks = next_humongous_chunks;
  2196   if (TraceMetadataChunkAllocation && Verbose) {
  2197     gclog_or_tty->print_cr("");
  2198     gclog_or_tty->print_cr("updated dictionary count %d %s",
  2199                      chunk_manager()->humongous_dictionary()->total_count(),
  2200                      chunk_size_name(HumongousIndex));
  2202   chunk_manager()->slow_locked_verify();
  2205 const char* SpaceManager::chunk_size_name(ChunkIndex index) const {
  2206   switch (index) {
  2207     case SpecializedIndex:
  2208       return "Specialized";
  2209     case SmallIndex:
  2210       return "Small";
  2211     case MediumIndex:
  2212       return "Medium";
  2213     case HumongousIndex:
  2214       return "Humongous";
  2215     default:
  2216       return NULL;
  2220 ChunkIndex ChunkManager::list_index(size_t size) {
  2221   switch (size) {
  2222     case SpecializedChunk:
  2223       assert(SpecializedChunk == ClassSpecializedChunk,
  2224              "Need branch for ClassSpecializedChunk");
  2225       return SpecializedIndex;
  2226     case SmallChunk:
  2227     case ClassSmallChunk:
  2228       return SmallIndex;
  2229     case MediumChunk:
  2230     case ClassMediumChunk:
  2231       return MediumIndex;
  2232     default:
  2233       assert(size > MediumChunk || size > ClassMediumChunk,
  2234              "Not a humongous chunk");
  2235       return HumongousIndex;
  2239 void SpaceManager::deallocate(MetaWord* p, size_t word_size) {
  2240   assert_lock_strong(_lock);
  2241   size_t raw_word_size = get_raw_word_size(word_size);
  2242   size_t min_size = TreeChunk<Metablock, FreeList<Metablock> >::min_size();
  2243   assert(raw_word_size >= min_size,
  2244          err_msg("Should not deallocate dark matter " SIZE_FORMAT "<" SIZE_FORMAT, word_size, min_size));
  2245   block_freelists()->return_block(p, raw_word_size);
  2248 // Adds a chunk to the list of chunks in use.
  2249 void SpaceManager::add_chunk(Metachunk* new_chunk, bool make_current) {
  2251   assert(new_chunk != NULL, "Should not be NULL");
  2252   assert(new_chunk->next() == NULL, "Should not be on a list");
  2254   new_chunk->reset_empty();
  2256   // Find the correct list and and set the current
  2257   // chunk for that list.
  2258   ChunkIndex index = ChunkManager::list_index(new_chunk->word_size());
  2260   if (index != HumongousIndex) {
  2261     retire_current_chunk();
  2262     set_current_chunk(new_chunk);
  2263     new_chunk->set_next(chunks_in_use(index));
  2264     set_chunks_in_use(index, new_chunk);
  2265   } else {
  2266     // For null class loader data and DumpSharedSpaces, the first chunk isn't
  2267     // small, so small will be null.  Link this first chunk as the current
  2268     // chunk.
  2269     if (make_current) {
  2270       // Set as the current chunk but otherwise treat as a humongous chunk.
  2271       set_current_chunk(new_chunk);
  2273     // Link at head.  The _current_chunk only points to a humongous chunk for
  2274     // the null class loader metaspace (class and data virtual space managers)
  2275     // any humongous chunks so will not point to the tail
  2276     // of the humongous chunks list.
  2277     new_chunk->set_next(chunks_in_use(HumongousIndex));
  2278     set_chunks_in_use(HumongousIndex, new_chunk);
  2280     assert(new_chunk->word_size() > medium_chunk_size(), "List inconsistency");
  2283   // Add to the running sum of capacity
  2284   inc_size_metrics(new_chunk->word_size());
  2286   assert(new_chunk->is_empty(), "Not ready for reuse");
  2287   if (TraceMetadataChunkAllocation && Verbose) {
  2288     gclog_or_tty->print("SpaceManager::add_chunk: %d) ",
  2289                         sum_count_in_chunks_in_use());
  2290     new_chunk->print_on(gclog_or_tty);
  2291     chunk_manager()->locked_print_free_chunks(gclog_or_tty);
  2295 void SpaceManager::retire_current_chunk() {
  2296   if (current_chunk() != NULL) {
  2297     size_t remaining_words = current_chunk()->free_word_size();
  2298     if (remaining_words >= TreeChunk<Metablock, FreeList<Metablock> >::min_size()) {
  2299       block_freelists()->return_block(current_chunk()->allocate(remaining_words), remaining_words);
  2300       inc_used_metrics(remaining_words);
  2305 Metachunk* SpaceManager::get_new_chunk(size_t word_size,
  2306                                        size_t grow_chunks_by_words) {
  2307   // Get a chunk from the chunk freelist
  2308   Metachunk* next = chunk_manager()->chunk_freelist_allocate(grow_chunks_by_words);
  2310   if (next == NULL) {
  2311     next = vs_list()->get_new_chunk(word_size,
  2312                                     grow_chunks_by_words,
  2313                                     medium_chunk_bunch());
  2316   if (TraceMetadataHumongousAllocation && next != NULL &&
  2317       SpaceManager::is_humongous(next->word_size())) {
  2318     gclog_or_tty->print_cr("  new humongous chunk word size "
  2319                            PTR_FORMAT, next->word_size());
  2322   return next;
  2325 MetaWord* SpaceManager::allocate(size_t word_size) {
  2326   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  2328   size_t raw_word_size = get_raw_word_size(word_size);
  2329   BlockFreelist* fl =  block_freelists();
  2330   MetaWord* p = NULL;
  2331   // Allocation from the dictionary is expensive in the sense that
  2332   // the dictionary has to be searched for a size.  Don't allocate
  2333   // from the dictionary until it starts to get fat.  Is this
  2334   // a reasonable policy?  Maybe an skinny dictionary is fast enough
  2335   // for allocations.  Do some profiling.  JJJ
  2336   if (fl->total_size() > allocation_from_dictionary_limit) {
  2337     p = fl->get_block(raw_word_size);
  2339   if (p == NULL) {
  2340     p = allocate_work(raw_word_size);
  2343   return p;
  2346 // Returns the address of spaced allocated for "word_size".
  2347 // This methods does not know about blocks (Metablocks)
  2348 MetaWord* SpaceManager::allocate_work(size_t word_size) {
  2349   assert_lock_strong(_lock);
  2350 #ifdef ASSERT
  2351   if (Metadebug::test_metadata_failure()) {
  2352     return NULL;
  2354 #endif
  2355   // Is there space in the current chunk?
  2356   MetaWord* result = NULL;
  2358   // For DumpSharedSpaces, only allocate out of the current chunk which is
  2359   // never null because we gave it the size we wanted.   Caller reports out
  2360   // of memory if this returns null.
  2361   if (DumpSharedSpaces) {
  2362     assert(current_chunk() != NULL, "should never happen");
  2363     inc_used_metrics(word_size);
  2364     return current_chunk()->allocate(word_size); // caller handles null result
  2367   if (current_chunk() != NULL) {
  2368     result = current_chunk()->allocate(word_size);
  2371   if (result == NULL) {
  2372     result = grow_and_allocate(word_size);
  2375   if (result != NULL) {
  2376     inc_used_metrics(word_size);
  2377     assert(result != (MetaWord*) chunks_in_use(MediumIndex),
  2378            "Head of the list is being allocated");
  2381   return result;
  2384 // This function looks at the chunks in the metaspace without locking.
  2385 // The chunks are added with store ordering and not deleted except for at
  2386 // unloading time.
  2387 bool SpaceManager::contains(const void *ptr) {
  2388   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i))
  2390     Metachunk* curr = chunks_in_use(i);
  2391     while (curr != NULL) {
  2392       if (curr->contains(ptr)) return true;
  2393       curr = curr->next();
  2396   return false;
  2399 void SpaceManager::verify() {
  2400   // If there are blocks in the dictionary, then
  2401   // verfication of chunks does not work since
  2402   // being in the dictionary alters a chunk.
  2403   if (block_freelists()->total_size() == 0) {
  2404     for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2405       Metachunk* curr = chunks_in_use(i);
  2406       while (curr != NULL) {
  2407         curr->verify();
  2408         verify_chunk_size(curr);
  2409         curr = curr->next();
  2415 void SpaceManager::verify_chunk_size(Metachunk* chunk) {
  2416   assert(is_humongous(chunk->word_size()) ||
  2417          chunk->word_size() == medium_chunk_size() ||
  2418          chunk->word_size() == small_chunk_size() ||
  2419          chunk->word_size() == specialized_chunk_size(),
  2420          "Chunk size is wrong");
  2421   return;
  2424 #ifdef ASSERT
  2425 void SpaceManager::verify_allocated_blocks_words() {
  2426   // Verification is only guaranteed at a safepoint.
  2427   assert(SafepointSynchronize::is_at_safepoint() || !Universe::is_fully_initialized(),
  2428     "Verification can fail if the applications is running");
  2429   assert(allocated_blocks_words() == sum_used_in_chunks_in_use(),
  2430     err_msg("allocation total is not consistent " SIZE_FORMAT
  2431             " vs " SIZE_FORMAT,
  2432             allocated_blocks_words(), sum_used_in_chunks_in_use()));
  2435 #endif
  2437 void SpaceManager::dump(outputStream* const out) const {
  2438   size_t curr_total = 0;
  2439   size_t waste = 0;
  2440   uint i = 0;
  2441   size_t used = 0;
  2442   size_t capacity = 0;
  2444   // Add up statistics for all chunks in this SpaceManager.
  2445   for (ChunkIndex index = ZeroIndex;
  2446        index < NumberOfInUseLists;
  2447        index = next_chunk_index(index)) {
  2448     for (Metachunk* curr = chunks_in_use(index);
  2449          curr != NULL;
  2450          curr = curr->next()) {
  2451       out->print("%d) ", i++);
  2452       curr->print_on(out);
  2453       curr_total += curr->word_size();
  2454       used += curr->used_word_size();
  2455       capacity += curr->word_size();
  2456       waste += curr->free_word_size() + curr->overhead();;
  2460   if (TraceMetadataChunkAllocation && Verbose) {
  2461     block_freelists()->print_on(out);
  2464   size_t free = current_chunk() == NULL ? 0 : current_chunk()->free_word_size();
  2465   // Free space isn't wasted.
  2466   waste -= free;
  2468   out->print_cr("total of all chunks "  SIZE_FORMAT " used " SIZE_FORMAT
  2469                 " free " SIZE_FORMAT " capacity " SIZE_FORMAT
  2470                 " waste " SIZE_FORMAT, curr_total, used, free, capacity, waste);
  2473 #ifndef PRODUCT
  2474 void SpaceManager::mangle_freed_chunks() {
  2475   for (ChunkIndex index = ZeroIndex;
  2476        index < NumberOfInUseLists;
  2477        index = next_chunk_index(index)) {
  2478     for (Metachunk* curr = chunks_in_use(index);
  2479          curr != NULL;
  2480          curr = curr->next()) {
  2481       curr->mangle();
  2485 #endif // PRODUCT
  2487 // MetaspaceAux
  2490 size_t MetaspaceAux::_allocated_capacity_words[] = {0, 0};
  2491 size_t MetaspaceAux::_allocated_used_words[] = {0, 0};
  2493 size_t MetaspaceAux::free_bytes(Metaspace::MetadataType mdtype) {
  2494   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
  2495   return list == NULL ? 0 : list->free_bytes();
  2498 size_t MetaspaceAux::free_bytes() {
  2499   return free_bytes(Metaspace::ClassType) + free_bytes(Metaspace::NonClassType);
  2502 void MetaspaceAux::dec_capacity(Metaspace::MetadataType mdtype, size_t words) {
  2503   assert_lock_strong(SpaceManager::expand_lock());
  2504   assert(words <= allocated_capacity_words(mdtype),
  2505     err_msg("About to decrement below 0: words " SIZE_FORMAT
  2506             " is greater than _allocated_capacity_words[%u] " SIZE_FORMAT,
  2507             words, mdtype, allocated_capacity_words(mdtype)));
  2508   _allocated_capacity_words[mdtype] -= words;
  2511 void MetaspaceAux::inc_capacity(Metaspace::MetadataType mdtype, size_t words) {
  2512   assert_lock_strong(SpaceManager::expand_lock());
  2513   // Needs to be atomic
  2514   _allocated_capacity_words[mdtype] += words;
  2517 void MetaspaceAux::dec_used(Metaspace::MetadataType mdtype, size_t words) {
  2518   assert(words <= allocated_used_words(mdtype),
  2519     err_msg("About to decrement below 0: words " SIZE_FORMAT
  2520             " is greater than _allocated_used_words[%u] " SIZE_FORMAT,
  2521             words, mdtype, allocated_used_words(mdtype)));
  2522   // For CMS deallocation of the Metaspaces occurs during the
  2523   // sweep which is a concurrent phase.  Protection by the expand_lock()
  2524   // is not enough since allocation is on a per Metaspace basis
  2525   // and protected by the Metaspace lock.
  2526   jlong minus_words = (jlong) - (jlong) words;
  2527   Atomic::add_ptr(minus_words, &_allocated_used_words[mdtype]);
  2530 void MetaspaceAux::inc_used(Metaspace::MetadataType mdtype, size_t words) {
  2531   // _allocated_used_words tracks allocations for
  2532   // each piece of metadata.  Those allocations are
  2533   // generally done concurrently by different application
  2534   // threads so must be done atomically.
  2535   Atomic::add_ptr(words, &_allocated_used_words[mdtype]);
  2538 size_t MetaspaceAux::used_bytes_slow(Metaspace::MetadataType mdtype) {
  2539   size_t used = 0;
  2540   ClassLoaderDataGraphMetaspaceIterator iter;
  2541   while (iter.repeat()) {
  2542     Metaspace* msp = iter.get_next();
  2543     // Sum allocated_blocks_words for each metaspace
  2544     if (msp != NULL) {
  2545       used += msp->used_words_slow(mdtype);
  2548   return used * BytesPerWord;
  2551 size_t MetaspaceAux::free_bytes_slow(Metaspace::MetadataType mdtype) {
  2552   size_t free = 0;
  2553   ClassLoaderDataGraphMetaspaceIterator iter;
  2554   while (iter.repeat()) {
  2555     Metaspace* msp = iter.get_next();
  2556     if (msp != NULL) {
  2557       free += msp->free_words_slow(mdtype);
  2560   return free * BytesPerWord;
  2563 size_t MetaspaceAux::capacity_bytes_slow(Metaspace::MetadataType mdtype) {
  2564   if ((mdtype == Metaspace::ClassType) && !Metaspace::using_class_space()) {
  2565     return 0;
  2567   // Don't count the space in the freelists.  That space will be
  2568   // added to the capacity calculation as needed.
  2569   size_t capacity = 0;
  2570   ClassLoaderDataGraphMetaspaceIterator iter;
  2571   while (iter.repeat()) {
  2572     Metaspace* msp = iter.get_next();
  2573     if (msp != NULL) {
  2574       capacity += msp->capacity_words_slow(mdtype);
  2577   return capacity * BytesPerWord;
  2580 size_t MetaspaceAux::capacity_bytes_slow() {
  2581 #ifdef PRODUCT
  2582   // Use allocated_capacity_bytes() in PRODUCT instead of this function.
  2583   guarantee(false, "Should not call capacity_bytes_slow() in the PRODUCT");
  2584 #endif
  2585   size_t class_capacity = capacity_bytes_slow(Metaspace::ClassType);
  2586   size_t non_class_capacity = capacity_bytes_slow(Metaspace::NonClassType);
  2587   assert(allocated_capacity_bytes() == class_capacity + non_class_capacity,
  2588       err_msg("bad accounting: allocated_capacity_bytes() " SIZE_FORMAT
  2589         " class_capacity + non_class_capacity " SIZE_FORMAT
  2590         " class_capacity " SIZE_FORMAT " non_class_capacity " SIZE_FORMAT,
  2591         allocated_capacity_bytes(), class_capacity + non_class_capacity,
  2592         class_capacity, non_class_capacity));
  2594   return class_capacity + non_class_capacity;
  2597 size_t MetaspaceAux::reserved_bytes(Metaspace::MetadataType mdtype) {
  2598   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
  2599   return list == NULL ? 0 : list->reserved_bytes();
  2602 size_t MetaspaceAux::committed_bytes(Metaspace::MetadataType mdtype) {
  2603   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
  2604   return list == NULL ? 0 : list->committed_bytes();
  2607 size_t MetaspaceAux::min_chunk_size_words() { return Metaspace::first_chunk_word_size(); }
  2609 size_t MetaspaceAux::free_chunks_total_words(Metaspace::MetadataType mdtype) {
  2610   ChunkManager* chunk_manager = Metaspace::get_chunk_manager(mdtype);
  2611   if (chunk_manager == NULL) {
  2612     return 0;
  2614   chunk_manager->slow_verify();
  2615   return chunk_manager->free_chunks_total_words();
  2618 size_t MetaspaceAux::free_chunks_total_bytes(Metaspace::MetadataType mdtype) {
  2619   return free_chunks_total_words(mdtype) * BytesPerWord;
  2622 size_t MetaspaceAux::free_chunks_total_words() {
  2623   return free_chunks_total_words(Metaspace::ClassType) +
  2624          free_chunks_total_words(Metaspace::NonClassType);
  2627 size_t MetaspaceAux::free_chunks_total_bytes() {
  2628   return free_chunks_total_words() * BytesPerWord;
  2631 void MetaspaceAux::print_metaspace_change(size_t prev_metadata_used) {
  2632   gclog_or_tty->print(", [Metaspace:");
  2633   if (PrintGCDetails && Verbose) {
  2634     gclog_or_tty->print(" "  SIZE_FORMAT
  2635                         "->" SIZE_FORMAT
  2636                         "("  SIZE_FORMAT ")",
  2637                         prev_metadata_used,
  2638                         allocated_used_bytes(),
  2639                         reserved_bytes());
  2640   } else {
  2641     gclog_or_tty->print(" "  SIZE_FORMAT "K"
  2642                         "->" SIZE_FORMAT "K"
  2643                         "("  SIZE_FORMAT "K)",
  2644                         prev_metadata_used/K,
  2645                         allocated_used_bytes()/K,
  2646                         reserved_bytes()/K);
  2649   gclog_or_tty->print("]");
  2652 // This is printed when PrintGCDetails
  2653 void MetaspaceAux::print_on(outputStream* out) {
  2654   Metaspace::MetadataType nct = Metaspace::NonClassType;
  2656   out->print_cr(" Metaspace       "
  2657                 "used "      SIZE_FORMAT "K, "
  2658                 "capacity "  SIZE_FORMAT "K, "
  2659                 "committed " SIZE_FORMAT "K, "
  2660                 "reserved "  SIZE_FORMAT "K",
  2661                 allocated_used_bytes()/K,
  2662                 allocated_capacity_bytes()/K,
  2663                 committed_bytes()/K,
  2664                 reserved_bytes()/K);
  2666   if (Metaspace::using_class_space()) {
  2667     Metaspace::MetadataType ct = Metaspace::ClassType;
  2668     out->print_cr("  class space    "
  2669                   "used "      SIZE_FORMAT "K, "
  2670                   "capacity "  SIZE_FORMAT "K, "
  2671                   "committed " SIZE_FORMAT "K, "
  2672                   "reserved "  SIZE_FORMAT "K",
  2673                   allocated_used_bytes(ct)/K,
  2674                   allocated_capacity_bytes(ct)/K,
  2675                   committed_bytes(ct)/K,
  2676                   reserved_bytes(ct)/K);
  2680 // Print information for class space and data space separately.
  2681 // This is almost the same as above.
  2682 void MetaspaceAux::print_on(outputStream* out, Metaspace::MetadataType mdtype) {
  2683   size_t free_chunks_capacity_bytes = free_chunks_total_bytes(mdtype);
  2684   size_t capacity_bytes = capacity_bytes_slow(mdtype);
  2685   size_t used_bytes = used_bytes_slow(mdtype);
  2686   size_t free_bytes = free_bytes_slow(mdtype);
  2687   size_t used_and_free = used_bytes + free_bytes +
  2688                            free_chunks_capacity_bytes;
  2689   out->print_cr("  Chunk accounting: used in chunks " SIZE_FORMAT
  2690              "K + unused in chunks " SIZE_FORMAT "K  + "
  2691              " capacity in free chunks " SIZE_FORMAT "K = " SIZE_FORMAT
  2692              "K  capacity in allocated chunks " SIZE_FORMAT "K",
  2693              used_bytes / K,
  2694              free_bytes / K,
  2695              free_chunks_capacity_bytes / K,
  2696              used_and_free / K,
  2697              capacity_bytes / K);
  2698   // Accounting can only be correct if we got the values during a safepoint
  2699   assert(!SafepointSynchronize::is_at_safepoint() || used_and_free == capacity_bytes, "Accounting is wrong");
  2702 // Print total fragmentation for class metaspaces
  2703 void MetaspaceAux::print_class_waste(outputStream* out) {
  2704   assert(Metaspace::using_class_space(), "class metaspace not used");
  2705   size_t cls_specialized_waste = 0, cls_small_waste = 0, cls_medium_waste = 0;
  2706   size_t cls_specialized_count = 0, cls_small_count = 0, cls_medium_count = 0, cls_humongous_count = 0;
  2707   ClassLoaderDataGraphMetaspaceIterator iter;
  2708   while (iter.repeat()) {
  2709     Metaspace* msp = iter.get_next();
  2710     if (msp != NULL) {
  2711       cls_specialized_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
  2712       cls_specialized_count += msp->class_vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
  2713       cls_small_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SmallIndex);
  2714       cls_small_count += msp->class_vsm()->sum_count_in_chunks_in_use(SmallIndex);
  2715       cls_medium_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(MediumIndex);
  2716       cls_medium_count += msp->class_vsm()->sum_count_in_chunks_in_use(MediumIndex);
  2717       cls_humongous_count += msp->class_vsm()->sum_count_in_chunks_in_use(HumongousIndex);
  2720   out->print_cr(" class: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
  2721                 SIZE_FORMAT " small(s) " SIZE_FORMAT ", "
  2722                 SIZE_FORMAT " medium(s) " SIZE_FORMAT ", "
  2723                 "large count " SIZE_FORMAT,
  2724                 cls_specialized_count, cls_specialized_waste,
  2725                 cls_small_count, cls_small_waste,
  2726                 cls_medium_count, cls_medium_waste, cls_humongous_count);
  2729 // Print total fragmentation for data and class metaspaces separately
  2730 void MetaspaceAux::print_waste(outputStream* out) {
  2731   size_t specialized_waste = 0, small_waste = 0, medium_waste = 0;
  2732   size_t specialized_count = 0, small_count = 0, medium_count = 0, humongous_count = 0;
  2734   ClassLoaderDataGraphMetaspaceIterator iter;
  2735   while (iter.repeat()) {
  2736     Metaspace* msp = iter.get_next();
  2737     if (msp != NULL) {
  2738       specialized_waste += msp->vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
  2739       specialized_count += msp->vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
  2740       small_waste += msp->vsm()->sum_waste_in_chunks_in_use(SmallIndex);
  2741       small_count += msp->vsm()->sum_count_in_chunks_in_use(SmallIndex);
  2742       medium_waste += msp->vsm()->sum_waste_in_chunks_in_use(MediumIndex);
  2743       medium_count += msp->vsm()->sum_count_in_chunks_in_use(MediumIndex);
  2744       humongous_count += msp->vsm()->sum_count_in_chunks_in_use(HumongousIndex);
  2747   out->print_cr("Total fragmentation waste (words) doesn't count free space");
  2748   out->print_cr("  data: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
  2749                         SIZE_FORMAT " small(s) " SIZE_FORMAT ", "
  2750                         SIZE_FORMAT " medium(s) " SIZE_FORMAT ", "
  2751                         "large count " SIZE_FORMAT,
  2752              specialized_count, specialized_waste, small_count,
  2753              small_waste, medium_count, medium_waste, humongous_count);
  2754   if (Metaspace::using_class_space()) {
  2755     print_class_waste(out);
  2759 // Dump global metaspace things from the end of ClassLoaderDataGraph
  2760 void MetaspaceAux::dump(outputStream* out) {
  2761   out->print_cr("All Metaspace:");
  2762   out->print("data space: "); print_on(out, Metaspace::NonClassType);
  2763   out->print("class space: "); print_on(out, Metaspace::ClassType);
  2764   print_waste(out);
  2767 void MetaspaceAux::verify_free_chunks() {
  2768   Metaspace::chunk_manager_metadata()->verify();
  2769   if (Metaspace::using_class_space()) {
  2770     Metaspace::chunk_manager_class()->verify();
  2774 void MetaspaceAux::verify_capacity() {
  2775 #ifdef ASSERT
  2776   size_t running_sum_capacity_bytes = allocated_capacity_bytes();
  2777   // For purposes of the running sum of capacity, verify against capacity
  2778   size_t capacity_in_use_bytes = capacity_bytes_slow();
  2779   assert(running_sum_capacity_bytes == capacity_in_use_bytes,
  2780     err_msg("allocated_capacity_words() * BytesPerWord " SIZE_FORMAT
  2781             " capacity_bytes_slow()" SIZE_FORMAT,
  2782             running_sum_capacity_bytes, capacity_in_use_bytes));
  2783   for (Metaspace::MetadataType i = Metaspace::ClassType;
  2784        i < Metaspace:: MetadataTypeCount;
  2785        i = (Metaspace::MetadataType)(i + 1)) {
  2786     size_t capacity_in_use_bytes = capacity_bytes_slow(i);
  2787     assert(allocated_capacity_bytes(i) == capacity_in_use_bytes,
  2788       err_msg("allocated_capacity_bytes(%u) " SIZE_FORMAT
  2789               " capacity_bytes_slow(%u)" SIZE_FORMAT,
  2790               i, allocated_capacity_bytes(i), i, capacity_in_use_bytes));
  2792 #endif
  2795 void MetaspaceAux::verify_used() {
  2796 #ifdef ASSERT
  2797   size_t running_sum_used_bytes = allocated_used_bytes();
  2798   // For purposes of the running sum of used, verify against used
  2799   size_t used_in_use_bytes = used_bytes_slow();
  2800   assert(allocated_used_bytes() == used_in_use_bytes,
  2801     err_msg("allocated_used_bytes() " SIZE_FORMAT
  2802             " used_bytes_slow()" SIZE_FORMAT,
  2803             allocated_used_bytes(), used_in_use_bytes));
  2804   for (Metaspace::MetadataType i = Metaspace::ClassType;
  2805        i < Metaspace:: MetadataTypeCount;
  2806        i = (Metaspace::MetadataType)(i + 1)) {
  2807     size_t used_in_use_bytes = used_bytes_slow(i);
  2808     assert(allocated_used_bytes(i) == used_in_use_bytes,
  2809       err_msg("allocated_used_bytes(%u) " SIZE_FORMAT
  2810               " used_bytes_slow(%u)" SIZE_FORMAT,
  2811               i, allocated_used_bytes(i), i, used_in_use_bytes));
  2813 #endif
  2816 void MetaspaceAux::verify_metrics() {
  2817   verify_capacity();
  2818   verify_used();
  2822 // Metaspace methods
  2824 size_t Metaspace::_first_chunk_word_size = 0;
  2825 size_t Metaspace::_first_class_chunk_word_size = 0;
  2827 size_t Metaspace::_commit_alignment = 0;
  2828 size_t Metaspace::_reserve_alignment = 0;
  2830 Metaspace::Metaspace(Mutex* lock, MetaspaceType type) {
  2831   initialize(lock, type);
  2834 Metaspace::~Metaspace() {
  2835   delete _vsm;
  2836   if (using_class_space()) {
  2837     delete _class_vsm;
  2841 VirtualSpaceList* Metaspace::_space_list = NULL;
  2842 VirtualSpaceList* Metaspace::_class_space_list = NULL;
  2844 ChunkManager* Metaspace::_chunk_manager_metadata = NULL;
  2845 ChunkManager* Metaspace::_chunk_manager_class = NULL;
  2847 #define VIRTUALSPACEMULTIPLIER 2
  2849 #ifdef _LP64
  2850 static const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
  2852 void Metaspace::set_narrow_klass_base_and_shift(address metaspace_base, address cds_base) {
  2853   // Figure out the narrow_klass_base and the narrow_klass_shift.  The
  2854   // narrow_klass_base is the lower of the metaspace base and the cds base
  2855   // (if cds is enabled).  The narrow_klass_shift depends on the distance
  2856   // between the lower base and higher address.
  2857   address lower_base;
  2858   address higher_address;
  2859   if (UseSharedSpaces) {
  2860     higher_address = MAX2((address)(cds_base + FileMapInfo::shared_spaces_size()),
  2861                           (address)(metaspace_base + compressed_class_space_size()));
  2862     lower_base = MIN2(metaspace_base, cds_base);
  2863   } else {
  2864     higher_address = metaspace_base + compressed_class_space_size();
  2865     lower_base = metaspace_base;
  2867     uint64_t klass_encoding_max = UnscaledClassSpaceMax << LogKlassAlignmentInBytes;
  2868     // If compressed class space fits in lower 32G, we don't need a base.
  2869     if (higher_address <= (address)klass_encoding_max) {
  2870       lower_base = 0; // effectively lower base is zero.
  2874   Universe::set_narrow_klass_base(lower_base);
  2876   if ((uint64_t)(higher_address - lower_base) <= UnscaledClassSpaceMax) {
  2877     Universe::set_narrow_klass_shift(0);
  2878   } else {
  2879     assert(!UseSharedSpaces, "Cannot shift with UseSharedSpaces");
  2880     Universe::set_narrow_klass_shift(LogKlassAlignmentInBytes);
  2884 // Return TRUE if the specified metaspace_base and cds_base are close enough
  2885 // to work with compressed klass pointers.
  2886 bool Metaspace::can_use_cds_with_metaspace_addr(char* metaspace_base, address cds_base) {
  2887   assert(cds_base != 0 && UseSharedSpaces, "Only use with CDS");
  2888   assert(UseCompressedClassPointers, "Only use with CompressedKlassPtrs");
  2889   address lower_base = MIN2((address)metaspace_base, cds_base);
  2890   address higher_address = MAX2((address)(cds_base + FileMapInfo::shared_spaces_size()),
  2891                                 (address)(metaspace_base + compressed_class_space_size()));
  2892   return ((uint64_t)(higher_address - lower_base) <= UnscaledClassSpaceMax);
  2895 // Try to allocate the metaspace at the requested addr.
  2896 void Metaspace::allocate_metaspace_compressed_klass_ptrs(char* requested_addr, address cds_base) {
  2897   assert(using_class_space(), "called improperly");
  2898   assert(UseCompressedClassPointers, "Only use with CompressedKlassPtrs");
  2899   assert(compressed_class_space_size() < KlassEncodingMetaspaceMax,
  2900          "Metaspace size is too big");
  2901   assert_is_ptr_aligned(requested_addr, _reserve_alignment);
  2902   assert_is_ptr_aligned(cds_base, _reserve_alignment);
  2903   assert_is_size_aligned(compressed_class_space_size(), _reserve_alignment);
  2905   // Don't use large pages for the class space.
  2906   bool large_pages = false;
  2908   ReservedSpace metaspace_rs = ReservedSpace(compressed_class_space_size(),
  2909                                              _reserve_alignment,
  2910                                              large_pages,
  2911                                              requested_addr, 0);
  2912   if (!metaspace_rs.is_reserved()) {
  2913     if (UseSharedSpaces) {
  2914       size_t increment = align_size_up(1*G, _reserve_alignment);
  2916       // Keep trying to allocate the metaspace, increasing the requested_addr
  2917       // by 1GB each time, until we reach an address that will no longer allow
  2918       // use of CDS with compressed klass pointers.
  2919       char *addr = requested_addr;
  2920       while (!metaspace_rs.is_reserved() && (addr + increment > addr) &&
  2921              can_use_cds_with_metaspace_addr(addr + increment, cds_base)) {
  2922         addr = addr + increment;
  2923         metaspace_rs = ReservedSpace(compressed_class_space_size(),
  2924                                      _reserve_alignment, large_pages, addr, 0);
  2928     // If no successful allocation then try to allocate the space anywhere.  If
  2929     // that fails then OOM doom.  At this point we cannot try allocating the
  2930     // metaspace as if UseCompressedClassPointers is off because too much
  2931     // initialization has happened that depends on UseCompressedClassPointers.
  2932     // So, UseCompressedClassPointers cannot be turned off at this point.
  2933     if (!metaspace_rs.is_reserved()) {
  2934       metaspace_rs = ReservedSpace(compressed_class_space_size(),
  2935                                    _reserve_alignment, large_pages);
  2936       if (!metaspace_rs.is_reserved()) {
  2937         vm_exit_during_initialization(err_msg("Could not allocate metaspace: %d bytes",
  2938                                               compressed_class_space_size()));
  2943   // If we got here then the metaspace got allocated.
  2944   MemTracker::record_virtual_memory_type((address)metaspace_rs.base(), mtClass);
  2946   // Verify that we can use shared spaces.  Otherwise, turn off CDS.
  2947   if (UseSharedSpaces && !can_use_cds_with_metaspace_addr(metaspace_rs.base(), cds_base)) {
  2948     FileMapInfo::stop_sharing_and_unmap(
  2949         "Could not allocate metaspace at a compatible address");
  2952   set_narrow_klass_base_and_shift((address)metaspace_rs.base(),
  2953                                   UseSharedSpaces ? (address)cds_base : 0);
  2955   initialize_class_space(metaspace_rs);
  2957   if (PrintCompressedOopsMode || (PrintMiscellaneous && Verbose)) {
  2958     gclog_or_tty->print_cr("Narrow klass base: " PTR_FORMAT ", Narrow klass shift: " SIZE_FORMAT,
  2959                             Universe::narrow_klass_base(), Universe::narrow_klass_shift());
  2960     gclog_or_tty->print_cr("Compressed class space size: " SIZE_FORMAT " Address: " PTR_FORMAT " Req Addr: " PTR_FORMAT,
  2961                            compressed_class_space_size(), metaspace_rs.base(), requested_addr);
  2965 // For UseCompressedClassPointers the class space is reserved above the top of
  2966 // the Java heap.  The argument passed in is at the base of the compressed space.
  2967 void Metaspace::initialize_class_space(ReservedSpace rs) {
  2968   // The reserved space size may be bigger because of alignment, esp with UseLargePages
  2969   assert(rs.size() >= CompressedClassSpaceSize,
  2970          err_msg(SIZE_FORMAT " != " UINTX_FORMAT, rs.size(), CompressedClassSpaceSize));
  2971   assert(using_class_space(), "Must be using class space");
  2972   _class_space_list = new VirtualSpaceList(rs);
  2973   _chunk_manager_class = new ChunkManager(SpecializedChunk, ClassSmallChunk, ClassMediumChunk);
  2975   if (!_class_space_list->initialization_succeeded()) {
  2976     vm_exit_during_initialization("Failed to setup compressed class space virtual space list.");
  2980 #endif
  2982 void Metaspace::ergo_initialize() {
  2983   if (DumpSharedSpaces) {
  2984     // Using large pages when dumping the shared archive is currently not implemented.
  2985     FLAG_SET_ERGO(bool, UseLargePagesInMetaspace, false);
  2988   size_t page_size = os::vm_page_size();
  2989   if (UseLargePages && UseLargePagesInMetaspace) {
  2990     page_size = os::large_page_size();
  2993   _commit_alignment  = page_size;
  2994   _reserve_alignment = MAX2(page_size, (size_t)os::vm_allocation_granularity());
  2996   // Do not use FLAG_SET_ERGO to update MaxMetaspaceSize, since this will
  2997   // override if MaxMetaspaceSize was set on the command line or not.
  2998   // This information is needed later to conform to the specification of the
  2999   // java.lang.management.MemoryUsage API.
  3000   //
  3001   // Ideally, we would be able to set the default value of MaxMetaspaceSize in
  3002   // globals.hpp to the aligned value, but this is not possible, since the
  3003   // alignment depends on other flags being parsed.
  3004   MaxMetaspaceSize = align_size_down_bounded(MaxMetaspaceSize, _reserve_alignment);
  3006   if (MetaspaceSize > MaxMetaspaceSize) {
  3007     MetaspaceSize = MaxMetaspaceSize;
  3010   MetaspaceSize = align_size_down_bounded(MetaspaceSize, _commit_alignment);
  3012   assert(MetaspaceSize <= MaxMetaspaceSize, "MetaspaceSize should be limited by MaxMetaspaceSize");
  3014   if (MetaspaceSize < 256*K) {
  3015     vm_exit_during_initialization("Too small initial Metaspace size");
  3018   MinMetaspaceExpansion = align_size_down_bounded(MinMetaspaceExpansion, _commit_alignment);
  3019   MaxMetaspaceExpansion = align_size_down_bounded(MaxMetaspaceExpansion, _commit_alignment);
  3021   CompressedClassSpaceSize = align_size_down_bounded(CompressedClassSpaceSize, _reserve_alignment);
  3022   set_compressed_class_space_size(CompressedClassSpaceSize);
  3025 void Metaspace::global_initialize() {
  3026   // Initialize the alignment for shared spaces.
  3027   int max_alignment = os::vm_page_size();
  3028   size_t cds_total = 0;
  3030   MetaspaceShared::set_max_alignment(max_alignment);
  3032   if (DumpSharedSpaces) {
  3033     SharedReadOnlySize  = align_size_up(SharedReadOnlySize,  max_alignment);
  3034     SharedReadWriteSize = align_size_up(SharedReadWriteSize, max_alignment);
  3035     SharedMiscDataSize  = align_size_up(SharedMiscDataSize,  max_alignment);
  3036     SharedMiscCodeSize  = align_size_up(SharedMiscCodeSize,  max_alignment);
  3038     // Initialize with the sum of the shared space sizes.  The read-only
  3039     // and read write metaspace chunks will be allocated out of this and the
  3040     // remainder is the misc code and data chunks.
  3041     cds_total = FileMapInfo::shared_spaces_size();
  3042     cds_total = align_size_up(cds_total, _reserve_alignment);
  3043     _space_list = new VirtualSpaceList(cds_total/wordSize);
  3044     _chunk_manager_metadata = new ChunkManager(SpecializedChunk, SmallChunk, MediumChunk);
  3046     if (!_space_list->initialization_succeeded()) {
  3047       vm_exit_during_initialization("Unable to dump shared archive.", NULL);
  3050 #ifdef _LP64
  3051     if (cds_total + compressed_class_space_size() > UnscaledClassSpaceMax) {
  3052       vm_exit_during_initialization("Unable to dump shared archive.",
  3053           err_msg("Size of archive (" SIZE_FORMAT ") + compressed class space ("
  3054                   SIZE_FORMAT ") == total (" SIZE_FORMAT ") is larger than compressed "
  3055                   "klass limit: " SIZE_FORMAT, cds_total, compressed_class_space_size(),
  3056                   cds_total + compressed_class_space_size(), UnscaledClassSpaceMax));
  3059     // Set the compressed klass pointer base so that decoding of these pointers works
  3060     // properly when creating the shared archive.
  3061     assert(UseCompressedOops && UseCompressedClassPointers,
  3062       "UseCompressedOops and UseCompressedClassPointers must be set");
  3063     Universe::set_narrow_klass_base((address)_space_list->current_virtual_space()->bottom());
  3064     if (TraceMetavirtualspaceAllocation && Verbose) {
  3065       gclog_or_tty->print_cr("Setting_narrow_klass_base to Address: " PTR_FORMAT,
  3066                              _space_list->current_virtual_space()->bottom());
  3069     Universe::set_narrow_klass_shift(0);
  3070 #endif
  3072   } else {
  3073     // If using shared space, open the file that contains the shared space
  3074     // and map in the memory before initializing the rest of metaspace (so
  3075     // the addresses don't conflict)
  3076     address cds_address = NULL;
  3077     if (UseSharedSpaces) {
  3078       FileMapInfo* mapinfo = new FileMapInfo();
  3079       memset(mapinfo, 0, sizeof(FileMapInfo));
  3081       // Open the shared archive file, read and validate the header. If
  3082       // initialization fails, shared spaces [UseSharedSpaces] are
  3083       // disabled and the file is closed.
  3084       // Map in spaces now also
  3085       if (mapinfo->initialize() && MetaspaceShared::map_shared_spaces(mapinfo)) {
  3086         FileMapInfo::set_current_info(mapinfo);
  3087         cds_total = FileMapInfo::shared_spaces_size();
  3088         cds_address = (address)mapinfo->region_base(0);
  3089       } else {
  3090         assert(!mapinfo->is_open() && !UseSharedSpaces,
  3091                "archive file not closed or shared spaces not disabled.");
  3095 #ifdef _LP64
  3096     // If UseCompressedClassPointers is set then allocate the metaspace area
  3097     // above the heap and above the CDS area (if it exists).
  3098     if (using_class_space()) {
  3099       if (UseSharedSpaces) {
  3100         char* cds_end = (char*)(cds_address + cds_total);
  3101         cds_end = (char *)align_ptr_up(cds_end, _reserve_alignment);
  3102         allocate_metaspace_compressed_klass_ptrs(cds_end, cds_address);
  3103       } else {
  3104         char* base = (char*)align_ptr_up(Universe::heap()->reserved_region().end(), _reserve_alignment);
  3105         allocate_metaspace_compressed_klass_ptrs(base, 0);
  3108 #endif
  3110     // Initialize these before initializing the VirtualSpaceList
  3111     _first_chunk_word_size = InitialBootClassLoaderMetaspaceSize / BytesPerWord;
  3112     _first_chunk_word_size = align_word_size_up(_first_chunk_word_size);
  3113     // Make the first class chunk bigger than a medium chunk so it's not put
  3114     // on the medium chunk list.   The next chunk will be small and progress
  3115     // from there.  This size calculated by -version.
  3116     _first_class_chunk_word_size = MIN2((size_t)MediumChunk*6,
  3117                                        (CompressedClassSpaceSize/BytesPerWord)*2);
  3118     _first_class_chunk_word_size = align_word_size_up(_first_class_chunk_word_size);
  3119     // Arbitrarily set the initial virtual space to a multiple
  3120     // of the boot class loader size.
  3121     size_t word_size = VIRTUALSPACEMULTIPLIER * _first_chunk_word_size;
  3122     word_size = align_size_up(word_size, Metaspace::reserve_alignment_words());
  3124     // Initialize the list of virtual spaces.
  3125     _space_list = new VirtualSpaceList(word_size);
  3126     _chunk_manager_metadata = new ChunkManager(SpecializedChunk, SmallChunk, MediumChunk);
  3128     if (!_space_list->initialization_succeeded()) {
  3129       vm_exit_during_initialization("Unable to setup metadata virtual space list.", NULL);
  3133   MetaspaceGC::initialize();
  3136 Metachunk* Metaspace::get_initialization_chunk(MetadataType mdtype,
  3137                                                size_t chunk_word_size,
  3138                                                size_t chunk_bunch) {
  3139   // Get a chunk from the chunk freelist
  3140   Metachunk* chunk = get_chunk_manager(mdtype)->chunk_freelist_allocate(chunk_word_size);
  3141   if (chunk != NULL) {
  3142     return chunk;
  3145   return get_space_list(mdtype)->get_new_chunk(chunk_word_size, chunk_word_size, chunk_bunch);
  3148 void Metaspace::initialize(Mutex* lock, MetaspaceType type) {
  3150   assert(space_list() != NULL,
  3151     "Metadata VirtualSpaceList has not been initialized");
  3152   assert(chunk_manager_metadata() != NULL,
  3153     "Metadata ChunkManager has not been initialized");
  3155   _vsm = new SpaceManager(NonClassType, lock);
  3156   if (_vsm == NULL) {
  3157     return;
  3159   size_t word_size;
  3160   size_t class_word_size;
  3161   vsm()->get_initial_chunk_sizes(type, &word_size, &class_word_size);
  3163   if (using_class_space()) {
  3164   assert(class_space_list() != NULL,
  3165     "Class VirtualSpaceList has not been initialized");
  3166   assert(chunk_manager_class() != NULL,
  3167     "Class ChunkManager has not been initialized");
  3169     // Allocate SpaceManager for classes.
  3170     _class_vsm = new SpaceManager(ClassType, lock);
  3171     if (_class_vsm == NULL) {
  3172       return;
  3176   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  3178   // Allocate chunk for metadata objects
  3179   Metachunk* new_chunk = get_initialization_chunk(NonClassType,
  3180                                                   word_size,
  3181                                                   vsm()->medium_chunk_bunch());
  3182   assert(!DumpSharedSpaces || new_chunk != NULL, "should have enough space for both chunks");
  3183   if (new_chunk != NULL) {
  3184     // Add to this manager's list of chunks in use and current_chunk().
  3185     vsm()->add_chunk(new_chunk, true);
  3188   // Allocate chunk for class metadata objects
  3189   if (using_class_space()) {
  3190     Metachunk* class_chunk = get_initialization_chunk(ClassType,
  3191                                                       class_word_size,
  3192                                                       class_vsm()->medium_chunk_bunch());
  3193     if (class_chunk != NULL) {
  3194       class_vsm()->add_chunk(class_chunk, true);
  3198   _alloc_record_head = NULL;
  3199   _alloc_record_tail = NULL;
  3202 size_t Metaspace::align_word_size_up(size_t word_size) {
  3203   size_t byte_size = word_size * wordSize;
  3204   return ReservedSpace::allocation_align_size_up(byte_size) / wordSize;
  3207 MetaWord* Metaspace::allocate(size_t word_size, MetadataType mdtype) {
  3208   // DumpSharedSpaces doesn't use class metadata area (yet)
  3209   // Also, don't use class_vsm() unless UseCompressedClassPointers is true.
  3210   if (is_class_space_allocation(mdtype)) {
  3211     return  class_vsm()->allocate(word_size);
  3212   } else {
  3213     return  vsm()->allocate(word_size);
  3217 MetaWord* Metaspace::expand_and_allocate(size_t word_size, MetadataType mdtype) {
  3218   size_t delta_bytes = MetaspaceGC::delta_capacity_until_GC(word_size * BytesPerWord);
  3219   assert(delta_bytes > 0, "Must be");
  3221   size_t after_inc = MetaspaceGC::inc_capacity_until_GC(delta_bytes);
  3222   size_t before_inc = after_inc - delta_bytes;
  3224   if (PrintGCDetails && Verbose) {
  3225     gclog_or_tty->print_cr("Increase capacity to GC from " SIZE_FORMAT
  3226         " to " SIZE_FORMAT, before_inc, after_inc);
  3229   return allocate(word_size, mdtype);
  3232 // Space allocated in the Metaspace.  This may
  3233 // be across several metadata virtual spaces.
  3234 char* Metaspace::bottom() const {
  3235   assert(DumpSharedSpaces, "only useful and valid for dumping shared spaces");
  3236   return (char*)vsm()->current_chunk()->bottom();
  3239 size_t Metaspace::used_words_slow(MetadataType mdtype) const {
  3240   if (mdtype == ClassType) {
  3241     return using_class_space() ? class_vsm()->sum_used_in_chunks_in_use() : 0;
  3242   } else {
  3243     return vsm()->sum_used_in_chunks_in_use();  // includes overhead!
  3247 size_t Metaspace::free_words_slow(MetadataType mdtype) const {
  3248   if (mdtype == ClassType) {
  3249     return using_class_space() ? class_vsm()->sum_free_in_chunks_in_use() : 0;
  3250   } else {
  3251     return vsm()->sum_free_in_chunks_in_use();
  3255 // Space capacity in the Metaspace.  It includes
  3256 // space in the list of chunks from which allocations
  3257 // have been made. Don't include space in the global freelist and
  3258 // in the space available in the dictionary which
  3259 // is already counted in some chunk.
  3260 size_t Metaspace::capacity_words_slow(MetadataType mdtype) const {
  3261   if (mdtype == ClassType) {
  3262     return using_class_space() ? class_vsm()->sum_capacity_in_chunks_in_use() : 0;
  3263   } else {
  3264     return vsm()->sum_capacity_in_chunks_in_use();
  3268 size_t Metaspace::used_bytes_slow(MetadataType mdtype) const {
  3269   return used_words_slow(mdtype) * BytesPerWord;
  3272 size_t Metaspace::capacity_bytes_slow(MetadataType mdtype) const {
  3273   return capacity_words_slow(mdtype) * BytesPerWord;
  3276 void Metaspace::deallocate(MetaWord* ptr, size_t word_size, bool is_class) {
  3277   if (SafepointSynchronize::is_at_safepoint()) {
  3278     assert(Thread::current()->is_VM_thread(), "should be the VM thread");
  3279     // Don't take Heap_lock
  3280     MutexLockerEx ml(vsm()->lock(), Mutex::_no_safepoint_check_flag);
  3281     if (word_size < TreeChunk<Metablock, FreeList<Metablock> >::min_size()) {
  3282       // Dark matter.  Too small for dictionary.
  3283 #ifdef ASSERT
  3284       Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
  3285 #endif
  3286       return;
  3288     if (is_class && using_class_space()) {
  3289       class_vsm()->deallocate(ptr, word_size);
  3290     } else {
  3291       vsm()->deallocate(ptr, word_size);
  3293   } else {
  3294     MutexLockerEx ml(vsm()->lock(), Mutex::_no_safepoint_check_flag);
  3296     if (word_size < TreeChunk<Metablock, FreeList<Metablock> >::min_size()) {
  3297       // Dark matter.  Too small for dictionary.
  3298 #ifdef ASSERT
  3299       Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
  3300 #endif
  3301       return;
  3303     if (is_class && using_class_space()) {
  3304       class_vsm()->deallocate(ptr, word_size);
  3305     } else {
  3306       vsm()->deallocate(ptr, word_size);
  3312 MetaWord* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size,
  3313                               bool read_only, MetaspaceObj::Type type, TRAPS) {
  3314   if (HAS_PENDING_EXCEPTION) {
  3315     assert(false, "Should not allocate with exception pending");
  3316     return NULL;  // caller does a CHECK_NULL too
  3319   assert(loader_data != NULL, "Should never pass around a NULL loader_data. "
  3320         "ClassLoaderData::the_null_class_loader_data() should have been used.");
  3322   // Allocate in metaspaces without taking out a lock, because it deadlocks
  3323   // with the SymbolTable_lock.  Dumping is single threaded for now.  We'll have
  3324   // to revisit this for application class data sharing.
  3325   if (DumpSharedSpaces) {
  3326     assert(type > MetaspaceObj::UnknownType && type < MetaspaceObj::_number_of_types, "sanity");
  3327     Metaspace* space = read_only ? loader_data->ro_metaspace() : loader_data->rw_metaspace();
  3328     MetaWord* result = space->allocate(word_size, NonClassType);
  3329     if (result == NULL) {
  3330       report_out_of_shared_space(read_only ? SharedReadOnly : SharedReadWrite);
  3333     space->record_allocation(result, type, space->vsm()->get_raw_word_size(word_size));
  3335     // Zero initialize.
  3336     Copy::fill_to_aligned_words((HeapWord*)result, word_size, 0);
  3338     return result;
  3341   MetadataType mdtype = (type == MetaspaceObj::ClassType) ? ClassType : NonClassType;
  3343   // Try to allocate metadata.
  3344   MetaWord* result = loader_data->metaspace_non_null()->allocate(word_size, mdtype);
  3346   if (result == NULL) {
  3347     // Allocation failed.
  3348     if (is_init_completed()) {
  3349       // Only start a GC if the bootstrapping has completed.
  3351       // Try to clean out some memory and retry.
  3352       result = Universe::heap()->collector_policy()->satisfy_failed_metadata_allocation(
  3353           loader_data, word_size, mdtype);
  3357   if (result == NULL) {
  3358     report_metadata_oome(loader_data, word_size, mdtype, CHECK_NULL);
  3361   // Zero initialize.
  3362   Copy::fill_to_aligned_words((HeapWord*)result, word_size, 0);
  3364   return result;
  3367 size_t Metaspace::class_chunk_size(size_t word_size) {
  3368   assert(using_class_space(), "Has to use class space");
  3369   return class_vsm()->calc_chunk_size(word_size);
  3372 void Metaspace::report_metadata_oome(ClassLoaderData* loader_data, size_t word_size, MetadataType mdtype, TRAPS) {
  3373   // If result is still null, we are out of memory.
  3374   if (Verbose && TraceMetadataChunkAllocation) {
  3375     gclog_or_tty->print_cr("Metaspace allocation failed for size "
  3376         SIZE_FORMAT, word_size);
  3377     if (loader_data->metaspace_or_null() != NULL) {
  3378       loader_data->dump(gclog_or_tty);
  3380     MetaspaceAux::dump(gclog_or_tty);
  3383   bool out_of_compressed_class_space = false;
  3384   if (is_class_space_allocation(mdtype)) {
  3385     Metaspace* metaspace = loader_data->metaspace_non_null();
  3386     out_of_compressed_class_space =
  3387       MetaspaceAux::committed_bytes(Metaspace::ClassType) +
  3388       (metaspace->class_chunk_size(word_size) * BytesPerWord) >
  3389       CompressedClassSpaceSize;
  3392   // -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support
  3393   const char* space_string = out_of_compressed_class_space ?
  3394     "Compressed class space" : "Metaspace";
  3396   report_java_out_of_memory(space_string);
  3398   if (JvmtiExport::should_post_resource_exhausted()) {
  3399     JvmtiExport::post_resource_exhausted(
  3400         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR,
  3401         space_string);
  3404   if (!is_init_completed()) {
  3405     vm_exit_during_initialization("OutOfMemoryError", space_string);
  3408   if (out_of_compressed_class_space) {
  3409     THROW_OOP(Universe::out_of_memory_error_class_metaspace());
  3410   } else {
  3411     THROW_OOP(Universe::out_of_memory_error_metaspace());
  3415 void Metaspace::record_allocation(void* ptr, MetaspaceObj::Type type, size_t word_size) {
  3416   assert(DumpSharedSpaces, "sanity");
  3418   AllocRecord *rec = new AllocRecord((address)ptr, type, (int)word_size * HeapWordSize);
  3419   if (_alloc_record_head == NULL) {
  3420     _alloc_record_head = _alloc_record_tail = rec;
  3421   } else {
  3422     _alloc_record_tail->_next = rec;
  3423     _alloc_record_tail = rec;
  3427 void Metaspace::iterate(Metaspace::AllocRecordClosure *closure) {
  3428   assert(DumpSharedSpaces, "unimplemented for !DumpSharedSpaces");
  3430   address last_addr = (address)bottom();
  3432   for (AllocRecord *rec = _alloc_record_head; rec; rec = rec->_next) {
  3433     address ptr = rec->_ptr;
  3434     if (last_addr < ptr) {
  3435       closure->doit(last_addr, MetaspaceObj::UnknownType, ptr - last_addr);
  3437     closure->doit(ptr, rec->_type, rec->_byte_size);
  3438     last_addr = ptr + rec->_byte_size;
  3441   address top = ((address)bottom()) + used_bytes_slow(Metaspace::NonClassType);
  3442   if (last_addr < top) {
  3443     closure->doit(last_addr, MetaspaceObj::UnknownType, top - last_addr);
  3447 void Metaspace::purge(MetadataType mdtype) {
  3448   get_space_list(mdtype)->purge(get_chunk_manager(mdtype));
  3451 void Metaspace::purge() {
  3452   MutexLockerEx cl(SpaceManager::expand_lock(),
  3453                    Mutex::_no_safepoint_check_flag);
  3454   purge(NonClassType);
  3455   if (using_class_space()) {
  3456     purge(ClassType);
  3460 void Metaspace::print_on(outputStream* out) const {
  3461   // Print both class virtual space counts and metaspace.
  3462   if (Verbose) {
  3463     vsm()->print_on(out);
  3464     if (using_class_space()) {
  3465       class_vsm()->print_on(out);
  3470 bool Metaspace::contains(const void* ptr) {
  3471   if (vsm()->contains(ptr)) return true;
  3472   if (using_class_space()) {
  3473     return class_vsm()->contains(ptr);
  3475   return false;
  3478 void Metaspace::verify() {
  3479   vsm()->verify();
  3480   if (using_class_space()) {
  3481     class_vsm()->verify();
  3485 void Metaspace::dump(outputStream* const out) const {
  3486   out->print_cr("\nVirtual space manager: " INTPTR_FORMAT, vsm());
  3487   vsm()->dump(out);
  3488   if (using_class_space()) {
  3489     out->print_cr("\nClass space manager: " INTPTR_FORMAT, class_vsm());
  3490     class_vsm()->dump(out);
  3494 /////////////// Unit tests ///////////////
  3496 #ifndef PRODUCT
  3498 class TestMetaspaceAuxTest : AllStatic {
  3499  public:
  3500   static void test_reserved() {
  3501     size_t reserved = MetaspaceAux::reserved_bytes();
  3503     assert(reserved > 0, "assert");
  3505     size_t committed  = MetaspaceAux::committed_bytes();
  3506     assert(committed <= reserved, "assert");
  3508     size_t reserved_metadata = MetaspaceAux::reserved_bytes(Metaspace::NonClassType);
  3509     assert(reserved_metadata > 0, "assert");
  3510     assert(reserved_metadata <= reserved, "assert");
  3512     if (UseCompressedClassPointers) {
  3513       size_t reserved_class    = MetaspaceAux::reserved_bytes(Metaspace::ClassType);
  3514       assert(reserved_class > 0, "assert");
  3515       assert(reserved_class < reserved, "assert");
  3519   static void test_committed() {
  3520     size_t committed = MetaspaceAux::committed_bytes();
  3522     assert(committed > 0, "assert");
  3524     size_t reserved  = MetaspaceAux::reserved_bytes();
  3525     assert(committed <= reserved, "assert");
  3527     size_t committed_metadata = MetaspaceAux::committed_bytes(Metaspace::NonClassType);
  3528     assert(committed_metadata > 0, "assert");
  3529     assert(committed_metadata <= committed, "assert");
  3531     if (UseCompressedClassPointers) {
  3532       size_t committed_class    = MetaspaceAux::committed_bytes(Metaspace::ClassType);
  3533       assert(committed_class > 0, "assert");
  3534       assert(committed_class < committed, "assert");
  3538   static void test_virtual_space_list_large_chunk() {
  3539     VirtualSpaceList* vs_list = new VirtualSpaceList(os::vm_allocation_granularity());
  3540     MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  3541     // A size larger than VirtualSpaceSize (256k) and add one page to make it _not_ be
  3542     // vm_allocation_granularity aligned on Windows.
  3543     size_t large_size = (size_t)(2*256*K + (os::vm_page_size()/BytesPerWord));
  3544     large_size += (os::vm_page_size()/BytesPerWord);
  3545     vs_list->get_new_chunk(large_size, large_size, 0);
  3548   static void test() {
  3549     test_reserved();
  3550     test_committed();
  3551     test_virtual_space_list_large_chunk();
  3553 };
  3555 void TestMetaspaceAux_test() {
  3556   TestMetaspaceAuxTest::test();
  3559 class TestVirtualSpaceNodeTest {
  3560   static void chunk_up(size_t words_left, size_t& num_medium_chunks,
  3561                                           size_t& num_small_chunks,
  3562                                           size_t& num_specialized_chunks) {
  3563     num_medium_chunks = words_left / MediumChunk;
  3564     words_left = words_left % MediumChunk;
  3566     num_small_chunks = words_left / SmallChunk;
  3567     words_left = words_left % SmallChunk;
  3568     // how many specialized chunks can we get?
  3569     num_specialized_chunks = words_left / SpecializedChunk;
  3570     assert(words_left % SpecializedChunk == 0, "should be nothing left");
  3573  public:
  3574   static void test() {
  3575     MutexLockerEx ml(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  3576     const size_t vsn_test_size_words = MediumChunk  * 4;
  3577     const size_t vsn_test_size_bytes = vsn_test_size_words * BytesPerWord;
  3579     // The chunk sizes must be multiples of eachother, or this will fail
  3580     STATIC_ASSERT(MediumChunk % SmallChunk == 0);
  3581     STATIC_ASSERT(SmallChunk % SpecializedChunk == 0);
  3583     { // No committed memory in VSN
  3584       ChunkManager cm(SpecializedChunk, SmallChunk, MediumChunk);
  3585       VirtualSpaceNode vsn(vsn_test_size_bytes);
  3586       vsn.initialize();
  3587       vsn.retire(&cm);
  3588       assert(cm.sum_free_chunks_count() == 0, "did not commit any memory in the VSN");
  3591     { // All of VSN is committed, half is used by chunks
  3592       ChunkManager cm(SpecializedChunk, SmallChunk, MediumChunk);
  3593       VirtualSpaceNode vsn(vsn_test_size_bytes);
  3594       vsn.initialize();
  3595       vsn.expand_by(vsn_test_size_words, vsn_test_size_words);
  3596       vsn.get_chunk_vs(MediumChunk);
  3597       vsn.get_chunk_vs(MediumChunk);
  3598       vsn.retire(&cm);
  3599       assert(cm.sum_free_chunks_count() == 2, "should have been memory left for 2 medium chunks");
  3600       assert(cm.sum_free_chunks() == 2*MediumChunk, "sizes should add up");
  3603     { // 4 pages of VSN is committed, some is used by chunks
  3604       ChunkManager cm(SpecializedChunk, SmallChunk, MediumChunk);
  3605       VirtualSpaceNode vsn(vsn_test_size_bytes);
  3606       const size_t page_chunks = 4 * (size_t)os::vm_page_size() / BytesPerWord;
  3607       assert(page_chunks < MediumChunk, "Test expects medium chunks to be at least 4*page_size");
  3608       vsn.initialize();
  3609       vsn.expand_by(page_chunks, page_chunks);
  3610       vsn.get_chunk_vs(SmallChunk);
  3611       vsn.get_chunk_vs(SpecializedChunk);
  3612       vsn.retire(&cm);
  3614       // committed - used = words left to retire
  3615       const size_t words_left = page_chunks - SmallChunk - SpecializedChunk;
  3617       size_t num_medium_chunks, num_small_chunks, num_spec_chunks;
  3618       chunk_up(words_left, num_medium_chunks, num_small_chunks, num_spec_chunks);
  3620       assert(num_medium_chunks == 0, "should not get any medium chunks");
  3621       assert(cm.sum_free_chunks_count() == (num_small_chunks + num_spec_chunks), "should be space for 3 chunks");
  3622       assert(cm.sum_free_chunks() == words_left, "sizes should add up");
  3625     { // Half of VSN is committed, a humongous chunk is used
  3626       ChunkManager cm(SpecializedChunk, SmallChunk, MediumChunk);
  3627       VirtualSpaceNode vsn(vsn_test_size_bytes);
  3628       vsn.initialize();
  3629       vsn.expand_by(MediumChunk * 2, MediumChunk * 2);
  3630       vsn.get_chunk_vs(MediumChunk + SpecializedChunk); // Humongous chunks will be aligned up to MediumChunk + SpecializedChunk
  3631       vsn.retire(&cm);
  3633       const size_t words_left = MediumChunk * 2 - (MediumChunk + SpecializedChunk);
  3634       size_t num_medium_chunks, num_small_chunks, num_spec_chunks;
  3635       chunk_up(words_left, num_medium_chunks, num_small_chunks, num_spec_chunks);
  3637       assert(num_medium_chunks == 0, "should not get any medium chunks");
  3638       assert(cm.sum_free_chunks_count() == (num_small_chunks + num_spec_chunks), "should be space for 3 chunks");
  3639       assert(cm.sum_free_chunks() == words_left, "sizes should add up");
  3644 #define assert_is_available_positive(word_size) \
  3645   assert(vsn.is_available(word_size), \
  3646     err_msg(#word_size ": " PTR_FORMAT " bytes were not available in " \
  3647             "VirtualSpaceNode [" PTR_FORMAT ", " PTR_FORMAT ")", \
  3648             (uintptr_t)(word_size * BytesPerWord), vsn.bottom(), vsn.end()));
  3650 #define assert_is_available_negative(word_size) \
  3651   assert(!vsn.is_available(word_size), \
  3652     err_msg(#word_size ": " PTR_FORMAT " bytes should not be available in " \
  3653             "VirtualSpaceNode [" PTR_FORMAT ", " PTR_FORMAT ")", \
  3654             (uintptr_t)(word_size * BytesPerWord), vsn.bottom(), vsn.end()));
  3656   static void test_is_available_positive() {
  3657     // Reserve some memory.
  3658     VirtualSpaceNode vsn(os::vm_allocation_granularity());
  3659     assert(vsn.initialize(), "Failed to setup VirtualSpaceNode");
  3661     // Commit some memory.
  3662     size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord;
  3663     bool expanded = vsn.expand_by(commit_word_size, commit_word_size);
  3664     assert(expanded, "Failed to commit");
  3666     // Check that is_available accepts the committed size.
  3667     assert_is_available_positive(commit_word_size);
  3669     // Check that is_available accepts half the committed size.
  3670     size_t expand_word_size = commit_word_size / 2;
  3671     assert_is_available_positive(expand_word_size);
  3674   static void test_is_available_negative() {
  3675     // Reserve some memory.
  3676     VirtualSpaceNode vsn(os::vm_allocation_granularity());
  3677     assert(vsn.initialize(), "Failed to setup VirtualSpaceNode");
  3679     // Commit some memory.
  3680     size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord;
  3681     bool expanded = vsn.expand_by(commit_word_size, commit_word_size);
  3682     assert(expanded, "Failed to commit");
  3684     // Check that is_available doesn't accept a too large size.
  3685     size_t two_times_commit_word_size = commit_word_size * 2;
  3686     assert_is_available_negative(two_times_commit_word_size);
  3689   static void test_is_available_overflow() {
  3690     // Reserve some memory.
  3691     VirtualSpaceNode vsn(os::vm_allocation_granularity());
  3692     assert(vsn.initialize(), "Failed to setup VirtualSpaceNode");
  3694     // Commit some memory.
  3695     size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord;
  3696     bool expanded = vsn.expand_by(commit_word_size, commit_word_size);
  3697     assert(expanded, "Failed to commit");
  3699     // Calculate a size that will overflow the virtual space size.
  3700     void* virtual_space_max = (void*)(uintptr_t)-1;
  3701     size_t bottom_to_max = pointer_delta(virtual_space_max, vsn.bottom(), 1);
  3702     size_t overflow_size = bottom_to_max + BytesPerWord;
  3703     size_t overflow_word_size = overflow_size / BytesPerWord;
  3705     // Check that is_available can handle the overflow.
  3706     assert_is_available_negative(overflow_word_size);
  3709   static void test_is_available() {
  3710     TestVirtualSpaceNodeTest::test_is_available_positive();
  3711     TestVirtualSpaceNodeTest::test_is_available_negative();
  3712     TestVirtualSpaceNodeTest::test_is_available_overflow();
  3714 };
  3716 void TestVirtualSpaceNode_test() {
  3717   TestVirtualSpaceNodeTest::test();
  3718   TestVirtualSpaceNodeTest::test_is_available();
  3721 #endif

mercurial