src/share/vm/memory/metaspace.cpp

Mon, 11 Dec 2017 02:39:24 -0800

author
mchinnathamb
date
Mon, 11 Dec 2017 02:39:24 -0800
changeset 9058
8c3e62bb99f3
parent 9057
b0f7174de2c5
child 9063
777ace6655eb
permissions
-rw-r--r--

8170395: Metaspace initialization queries the wrong chunk freelist
Reviewed-by: stuefe, stefank

     1 /*
     2  * Copyright (c) 2011, 2017, 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/metaspaceGCThresholdUpdater.hpp"
    36 #include "memory/metaspaceShared.hpp"
    37 #include "memory/metaspaceTracer.hpp"
    38 #include "memory/resourceArea.hpp"
    39 #include "memory/universe.hpp"
    40 #include "runtime/atomic.inline.hpp"
    41 #include "runtime/globals.hpp"
    42 #include "runtime/init.hpp"
    43 #include "runtime/java.hpp"
    44 #include "runtime/mutex.hpp"
    45 #include "runtime/orderAccess.inline.hpp"
    46 #include "services/memTracker.hpp"
    47 #include "services/memoryService.hpp"
    48 #include "utilities/copy.hpp"
    49 #include "utilities/debug.hpp"
    51 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
    53 typedef BinaryTreeDictionary<Metablock, FreeList<Metablock> > BlockTreeDictionary;
    54 typedef BinaryTreeDictionary<Metachunk, FreeList<Metachunk> > ChunkTreeDictionary;
    56 // Set this constant to enable slow integrity checking of the free chunk lists
    57 const bool metaspace_slow_verify = false;
    59 size_t const allocation_from_dictionary_limit = 4 * K;
    61 MetaWord* last_allocated = 0;
    63 size_t Metaspace::_compressed_class_space_size;
    64 const MetaspaceTracer* Metaspace::_tracer = NULL;
    66 // Used in declarations in SpaceManager and ChunkManager
    67 enum ChunkIndex {
    68   ZeroIndex = 0,
    69   SpecializedIndex = ZeroIndex,
    70   SmallIndex = SpecializedIndex + 1,
    71   MediumIndex = SmallIndex + 1,
    72   HumongousIndex = MediumIndex + 1,
    73   NumberOfFreeLists = 3,
    74   NumberOfInUseLists = 4
    75 };
    77 enum ChunkSizes {    // in words.
    78   ClassSpecializedChunk = 128,
    79   SpecializedChunk = 128,
    80   ClassSmallChunk = 256,
    81   SmallChunk = 512,
    82   ClassMediumChunk = 4 * K,
    83   MediumChunk = 8 * K
    84 };
    86 static ChunkIndex next_chunk_index(ChunkIndex i) {
    87   assert(i < NumberOfInUseLists, "Out of bound");
    88   return (ChunkIndex) (i+1);
    89 }
    91 volatile intptr_t MetaspaceGC::_capacity_until_GC = 0;
    92 uint MetaspaceGC::_shrink_factor = 0;
    93 bool MetaspaceGC::_should_concurrent_collect = false;
    95 typedef class FreeList<Metachunk> ChunkList;
    97 // Manages the global free lists of chunks.
    98 class ChunkManager : public CHeapObj<mtInternal> {
    99   friend class TestVirtualSpaceNodeTest;
   101   // Free list of chunks of different sizes.
   102   //   SpecializedChunk
   103   //   SmallChunk
   104   //   MediumChunk
   105   //   HumongousChunk
   106   ChunkList _free_chunks[NumberOfFreeLists];
   108   //   HumongousChunk
   109   ChunkTreeDictionary _humongous_dictionary;
   111   // ChunkManager in all lists of this type
   112   size_t _free_chunks_total;
   113   size_t _free_chunks_count;
   115   void dec_free_chunks_total(size_t v) {
   116     assert(_free_chunks_count > 0 &&
   117              _free_chunks_total > 0,
   118              "About to go negative");
   119     Atomic::add_ptr(-1, &_free_chunks_count);
   120     jlong minus_v = (jlong) - (jlong) v;
   121     Atomic::add_ptr(minus_v, &_free_chunks_total);
   122   }
   124   // Debug support
   126   size_t sum_free_chunks();
   127   size_t sum_free_chunks_count();
   129   void locked_verify_free_chunks_total();
   130   void slow_locked_verify_free_chunks_total() {
   131     if (metaspace_slow_verify) {
   132       locked_verify_free_chunks_total();
   133     }
   134   }
   135   void locked_verify_free_chunks_count();
   136   void slow_locked_verify_free_chunks_count() {
   137     if (metaspace_slow_verify) {
   138       locked_verify_free_chunks_count();
   139     }
   140   }
   141   void verify_free_chunks_count();
   143  public:
   145   ChunkManager(size_t specialized_size, size_t small_size, size_t medium_size)
   146       : _free_chunks_total(0), _free_chunks_count(0) {
   147     _free_chunks[SpecializedIndex].set_size(specialized_size);
   148     _free_chunks[SmallIndex].set_size(small_size);
   149     _free_chunks[MediumIndex].set_size(medium_size);
   150   }
   152   // add or delete (return) a chunk to the global freelist.
   153   Metachunk* chunk_freelist_allocate(size_t word_size);
   155   // Map a size to a list index assuming that there are lists
   156   // for special, small, medium, and humongous chunks.
   157   static ChunkIndex list_index(size_t size);
   159   // Remove the chunk from its freelist.  It is
   160   // expected to be on one of the _free_chunks[] lists.
   161   void remove_chunk(Metachunk* chunk);
   163   // Add the simple linked list of chunks to the freelist of chunks
   164   // of type index.
   165   void return_chunks(ChunkIndex index, Metachunk* chunks);
   167   // Total of the space in the free chunks list
   168   size_t free_chunks_total_words();
   169   size_t free_chunks_total_bytes();
   171   // Number of chunks in the free chunks list
   172   size_t free_chunks_count();
   174   void inc_free_chunks_total(size_t v, size_t count = 1) {
   175     Atomic::add_ptr(count, &_free_chunks_count);
   176     Atomic::add_ptr(v, &_free_chunks_total);
   177   }
   178   ChunkTreeDictionary* humongous_dictionary() {
   179     return &_humongous_dictionary;
   180   }
   182   ChunkList* free_chunks(ChunkIndex index);
   184   // Returns the list for the given chunk word size.
   185   ChunkList* find_free_chunks_list(size_t word_size);
   187   // Remove from a list by size.  Selects list based on size of chunk.
   188   Metachunk* free_chunks_get(size_t chunk_word_size);
   190 #define index_bounds_check(index)                                         \
   191   assert(index == SpecializedIndex ||                                     \
   192          index == SmallIndex ||                                           \
   193          index == MediumIndex ||                                          \
   194          index == HumongousIndex, err_msg("Bad index: %d", (int) index))
   196   size_t num_free_chunks(ChunkIndex index) const {
   197     index_bounds_check(index);
   199     if (index == HumongousIndex) {
   200       return _humongous_dictionary.total_free_blocks();
   201     }
   203     ssize_t count = _free_chunks[index].count();
   204     return count == -1 ? 0 : (size_t) count;
   205   }
   207   size_t size_free_chunks_in_bytes(ChunkIndex index) const {
   208     index_bounds_check(index);
   210     size_t word_size = 0;
   211     if (index == HumongousIndex) {
   212       word_size = _humongous_dictionary.total_size();
   213     } else {
   214       const size_t size_per_chunk_in_words = _free_chunks[index].size();
   215       word_size = size_per_chunk_in_words * num_free_chunks(index);
   216     }
   218     return word_size * BytesPerWord;
   219   }
   221   MetaspaceChunkFreeListSummary chunk_free_list_summary() const {
   222     return MetaspaceChunkFreeListSummary(num_free_chunks(SpecializedIndex),
   223                                          num_free_chunks(SmallIndex),
   224                                          num_free_chunks(MediumIndex),
   225                                          num_free_chunks(HumongousIndex),
   226                                          size_free_chunks_in_bytes(SpecializedIndex),
   227                                          size_free_chunks_in_bytes(SmallIndex),
   228                                          size_free_chunks_in_bytes(MediumIndex),
   229                                          size_free_chunks_in_bytes(HumongousIndex));
   230   }
   232   // Debug support
   233   void verify();
   234   void slow_verify() {
   235     if (metaspace_slow_verify) {
   236       verify();
   237     }
   238   }
   239   void locked_verify();
   240   void slow_locked_verify() {
   241     if (metaspace_slow_verify) {
   242       locked_verify();
   243     }
   244   }
   245   void verify_free_chunks_total();
   247   void locked_print_free_chunks(outputStream* st);
   248   void locked_print_sum_free_chunks(outputStream* st);
   250   void print_on(outputStream* st) const;
   251 };
   253 // Used to manage the free list of Metablocks (a block corresponds
   254 // to the allocation of a quantum of metadata).
   255 class BlockFreelist VALUE_OBJ_CLASS_SPEC {
   256   BlockTreeDictionary* _dictionary;
   258   // Only allocate and split from freelist if the size of the allocation
   259   // is at least 1/4th the size of the available block.
   260   const static int WasteMultiplier = 4;
   262   // Accessors
   263   BlockTreeDictionary* dictionary() const { return _dictionary; }
   265  public:
   266   BlockFreelist();
   267   ~BlockFreelist();
   269   // Get and return a block to the free list
   270   MetaWord* get_block(size_t word_size);
   271   void return_block(MetaWord* p, size_t word_size);
   273   size_t total_size() {
   274   if (dictionary() == NULL) {
   275     return 0;
   276   } else {
   277     return dictionary()->total_size();
   278   }
   279 }
   281   void print_on(outputStream* st) const;
   282 };
   284 // A VirtualSpaceList node.
   285 class VirtualSpaceNode : public CHeapObj<mtClass> {
   286   friend class VirtualSpaceList;
   288   // Link to next VirtualSpaceNode
   289   VirtualSpaceNode* _next;
   291   // total in the VirtualSpace
   292   MemRegion _reserved;
   293   ReservedSpace _rs;
   294   VirtualSpace _virtual_space;
   295   MetaWord* _top;
   296   // count of chunks contained in this VirtualSpace
   297   uintx _container_count;
   299   // Convenience functions to access the _virtual_space
   300   char* low()  const { return virtual_space()->low(); }
   301   char* high() const { return virtual_space()->high(); }
   303   // The first Metachunk will be allocated at the bottom of the
   304   // VirtualSpace
   305   Metachunk* first_chunk() { return (Metachunk*) bottom(); }
   307   // Committed but unused space in the virtual space
   308   size_t free_words_in_vs() const;
   309  public:
   311   VirtualSpaceNode(size_t byte_size);
   312   VirtualSpaceNode(ReservedSpace rs) : _top(NULL), _next(NULL), _rs(rs), _container_count(0) {}
   313   ~VirtualSpaceNode();
   315   // Convenience functions for logical bottom and end
   316   MetaWord* bottom() const { return (MetaWord*) _virtual_space.low(); }
   317   MetaWord* end() const { return (MetaWord*) _virtual_space.high(); }
   319   bool contains(const void* ptr) { return ptr >= low() && ptr < high(); }
   321   size_t reserved_words() const  { return _virtual_space.reserved_size() / BytesPerWord; }
   322   size_t committed_words() const { return _virtual_space.actual_committed_size() / BytesPerWord; }
   324   bool is_pre_committed() const { return _virtual_space.special(); }
   326   // address of next available space in _virtual_space;
   327   // Accessors
   328   VirtualSpaceNode* next() { return _next; }
   329   void set_next(VirtualSpaceNode* v) { _next = v; }
   331   void set_reserved(MemRegion const v) { _reserved = v; }
   332   void set_top(MetaWord* v) { _top = v; }
   334   // Accessors
   335   MemRegion* reserved() { return &_reserved; }
   336   VirtualSpace* virtual_space() const { return (VirtualSpace*) &_virtual_space; }
   338   // Returns true if "word_size" is available in the VirtualSpace
   339   bool is_available(size_t word_size) { return word_size <= pointer_delta(end(), _top, sizeof(MetaWord)); }
   341   MetaWord* top() const { return _top; }
   342   void inc_top(size_t word_size) { _top += word_size; }
   344   uintx container_count() { return _container_count; }
   345   void inc_container_count();
   346   void dec_container_count();
   347 #ifdef ASSERT
   348   uint container_count_slow();
   349   void verify_container_count();
   350 #endif
   352   // used and capacity in this single entry in the list
   353   size_t used_words_in_vs() const;
   354   size_t capacity_words_in_vs() const;
   356   bool initialize();
   358   // get space from the virtual space
   359   Metachunk* take_from_committed(size_t chunk_word_size);
   361   // Allocate a chunk from the virtual space and return it.
   362   Metachunk* get_chunk_vs(size_t chunk_word_size);
   364   // Expands/shrinks the committed space in a virtual space.  Delegates
   365   // to Virtualspace
   366   bool expand_by(size_t min_words, size_t preferred_words);
   368   // In preparation for deleting this node, remove all the chunks
   369   // in the node from any freelist.
   370   void purge(ChunkManager* chunk_manager);
   372   // If an allocation doesn't fit in the current node a new node is created.
   373   // Allocate chunks out of the remaining committed space in this node
   374   // to avoid wasting that memory.
   375   // This always adds up because all the chunk sizes are multiples of
   376   // the smallest chunk size.
   377   void retire(ChunkManager* chunk_manager);
   379 #ifdef ASSERT
   380   // Debug support
   381   void mangle();
   382 #endif
   384   void print_on(outputStream* st) const;
   385 };
   387 #define assert_is_ptr_aligned(ptr, alignment) \
   388   assert(is_ptr_aligned(ptr, alignment),      \
   389     err_msg(PTR_FORMAT " is not aligned to "  \
   390       SIZE_FORMAT, ptr, alignment))
   392 #define assert_is_size_aligned(size, alignment) \
   393   assert(is_size_aligned(size, alignment),      \
   394     err_msg(SIZE_FORMAT " is not aligned to "   \
   395        SIZE_FORMAT, size, alignment))
   398 // Decide if large pages should be committed when the memory is reserved.
   399 static bool should_commit_large_pages_when_reserving(size_t bytes) {
   400   if (UseLargePages && UseLargePagesInMetaspace && !os::can_commit_large_page_memory()) {
   401     size_t words = bytes / BytesPerWord;
   402     bool is_class = false; // We never reserve large pages for the class space.
   403     if (MetaspaceGC::can_expand(words, is_class) &&
   404         MetaspaceGC::allowed_expansion() >= words) {
   405       return true;
   406     }
   407   }
   409   return false;
   410 }
   412   // byte_size is the size of the associated virtualspace.
   413 VirtualSpaceNode::VirtualSpaceNode(size_t bytes) : _top(NULL), _next(NULL), _rs(), _container_count(0) {
   414   assert_is_size_aligned(bytes, Metaspace::reserve_alignment());
   416 #if INCLUDE_CDS
   417   // This allocates memory with mmap.  For DumpSharedspaces, try to reserve
   418   // configurable address, generally at the top of the Java heap so other
   419   // memory addresses don't conflict.
   420   if (DumpSharedSpaces) {
   421     bool large_pages = false; // No large pages when dumping the CDS archive.
   422     char* shared_base = (char*)align_ptr_up((char*)SharedBaseAddress, Metaspace::reserve_alignment());
   424     _rs = ReservedSpace(bytes, Metaspace::reserve_alignment(), large_pages, shared_base, 0);
   425     if (_rs.is_reserved()) {
   426       assert(shared_base == 0 || _rs.base() == shared_base, "should match");
   427     } else {
   428       // Get a mmap region anywhere if the SharedBaseAddress fails.
   429       _rs = ReservedSpace(bytes, Metaspace::reserve_alignment(), large_pages);
   430     }
   431     MetaspaceShared::set_shared_rs(&_rs);
   432   } else
   433 #endif
   434   {
   435     bool large_pages = should_commit_large_pages_when_reserving(bytes);
   437     _rs = ReservedSpace(bytes, Metaspace::reserve_alignment(), large_pages);
   438   }
   440   if (_rs.is_reserved()) {
   441     assert(_rs.base() != NULL, "Catch if we get a NULL address");
   442     assert(_rs.size() != 0, "Catch if we get a 0 size");
   443     assert_is_ptr_aligned(_rs.base(), Metaspace::reserve_alignment());
   444     assert_is_size_aligned(_rs.size(), Metaspace::reserve_alignment());
   446     MemTracker::record_virtual_memory_type((address)_rs.base(), mtClass);
   447   }
   448 }
   450 void VirtualSpaceNode::purge(ChunkManager* chunk_manager) {
   451   Metachunk* chunk = first_chunk();
   452   Metachunk* invalid_chunk = (Metachunk*) top();
   453   while (chunk < invalid_chunk ) {
   454     assert(chunk->is_tagged_free(), "Should be tagged free");
   455     MetaWord* next = ((MetaWord*)chunk) + chunk->word_size();
   456     chunk_manager->remove_chunk(chunk);
   457     assert(chunk->next() == NULL &&
   458            chunk->prev() == NULL,
   459            "Was not removed from its list");
   460     chunk = (Metachunk*) next;
   461   }
   462 }
   464 #ifdef ASSERT
   465 uint VirtualSpaceNode::container_count_slow() {
   466   uint count = 0;
   467   Metachunk* chunk = first_chunk();
   468   Metachunk* invalid_chunk = (Metachunk*) top();
   469   while (chunk < invalid_chunk ) {
   470     MetaWord* next = ((MetaWord*)chunk) + chunk->word_size();
   471     // Don't count the chunks on the free lists.  Those are
   472     // still part of the VirtualSpaceNode but not currently
   473     // counted.
   474     if (!chunk->is_tagged_free()) {
   475       count++;
   476     }
   477     chunk = (Metachunk*) next;
   478   }
   479   return count;
   480 }
   481 #endif
   483 // List of VirtualSpaces for metadata allocation.
   484 class VirtualSpaceList : public CHeapObj<mtClass> {
   485   friend class VirtualSpaceNode;
   487   enum VirtualSpaceSizes {
   488     VirtualSpaceSize = 256 * K
   489   };
   491   // Head of the list
   492   VirtualSpaceNode* _virtual_space_list;
   493   // virtual space currently being used for allocations
   494   VirtualSpaceNode* _current_virtual_space;
   496   // Is this VirtualSpaceList used for the compressed class space
   497   bool _is_class;
   499   // Sum of reserved and committed memory in the virtual spaces
   500   size_t _reserved_words;
   501   size_t _committed_words;
   503   // Number of virtual spaces
   504   size_t _virtual_space_count;
   506   ~VirtualSpaceList();
   508   VirtualSpaceNode* virtual_space_list() const { return _virtual_space_list; }
   510   void set_virtual_space_list(VirtualSpaceNode* v) {
   511     _virtual_space_list = v;
   512   }
   513   void set_current_virtual_space(VirtualSpaceNode* v) {
   514     _current_virtual_space = v;
   515   }
   517   void link_vs(VirtualSpaceNode* new_entry);
   519   // Get another virtual space and add it to the list.  This
   520   // is typically prompted by a failed attempt to allocate a chunk
   521   // and is typically followed by the allocation of a chunk.
   522   bool create_new_virtual_space(size_t vs_word_size);
   524   // Chunk up the unused committed space in the current
   525   // virtual space and add the chunks to the free list.
   526   void retire_current_virtual_space();
   528  public:
   529   VirtualSpaceList(size_t word_size);
   530   VirtualSpaceList(ReservedSpace rs);
   532   size_t free_bytes();
   534   Metachunk* get_new_chunk(size_t chunk_word_size,
   535                            size_t suggested_commit_granularity);
   537   bool expand_node_by(VirtualSpaceNode* node,
   538                       size_t min_words,
   539                       size_t preferred_words);
   541   bool expand_by(size_t min_words,
   542                  size_t preferred_words);
   544   VirtualSpaceNode* current_virtual_space() {
   545     return _current_virtual_space;
   546   }
   548   bool is_class() const { return _is_class; }
   550   bool initialization_succeeded() { return _virtual_space_list != NULL; }
   552   size_t reserved_words()  { return _reserved_words; }
   553   size_t reserved_bytes()  { return reserved_words() * BytesPerWord; }
   554   size_t committed_words() { return _committed_words; }
   555   size_t committed_bytes() { return committed_words() * BytesPerWord; }
   557   void inc_reserved_words(size_t v);
   558   void dec_reserved_words(size_t v);
   559   void inc_committed_words(size_t v);
   560   void dec_committed_words(size_t v);
   561   void inc_virtual_space_count();
   562   void dec_virtual_space_count();
   564   bool contains(const void* ptr);
   566   // Unlink empty VirtualSpaceNodes and free it.
   567   void purge(ChunkManager* chunk_manager);
   569   void print_on(outputStream* st) const;
   571   class VirtualSpaceListIterator : public StackObj {
   572     VirtualSpaceNode* _virtual_spaces;
   573    public:
   574     VirtualSpaceListIterator(VirtualSpaceNode* virtual_spaces) :
   575       _virtual_spaces(virtual_spaces) {}
   577     bool repeat() {
   578       return _virtual_spaces != NULL;
   579     }
   581     VirtualSpaceNode* get_next() {
   582       VirtualSpaceNode* result = _virtual_spaces;
   583       if (_virtual_spaces != NULL) {
   584         _virtual_spaces = _virtual_spaces->next();
   585       }
   586       return result;
   587     }
   588   };
   589 };
   591 class Metadebug : AllStatic {
   592   // Debugging support for Metaspaces
   593   static int _allocation_fail_alot_count;
   595  public:
   597   static void init_allocation_fail_alot_count();
   598 #ifdef ASSERT
   599   static bool test_metadata_failure();
   600 #endif
   601 };
   603 int Metadebug::_allocation_fail_alot_count = 0;
   605 //  SpaceManager - used by Metaspace to handle allocations
   606 class SpaceManager : public CHeapObj<mtClass> {
   607   friend class Metaspace;
   608   friend class Metadebug;
   610  private:
   612   // protects allocations
   613   Mutex* const _lock;
   615   // Type of metadata allocated.
   616   Metaspace::MetadataType _mdtype;
   618   // List of chunks in use by this SpaceManager.  Allocations
   619   // are done from the current chunk.  The list is used for deallocating
   620   // chunks when the SpaceManager is freed.
   621   Metachunk* _chunks_in_use[NumberOfInUseLists];
   622   Metachunk* _current_chunk;
   624   // Number of small chunks to allocate to a manager
   625   // If class space manager, small chunks are unlimited
   626   static uint const _small_chunk_limit;
   628   // Sum of all space in allocated chunks
   629   size_t _allocated_blocks_words;
   631   // Sum of all allocated chunks
   632   size_t _allocated_chunks_words;
   633   size_t _allocated_chunks_count;
   635   // Free lists of blocks are per SpaceManager since they
   636   // are assumed to be in chunks in use by the SpaceManager
   637   // and all chunks in use by a SpaceManager are freed when
   638   // the class loader using the SpaceManager is collected.
   639   BlockFreelist _block_freelists;
   641   // protects virtualspace and chunk expansions
   642   static const char*  _expand_lock_name;
   643   static const int    _expand_lock_rank;
   644   static Mutex* const _expand_lock;
   646  private:
   647   // Accessors
   648   Metachunk* chunks_in_use(ChunkIndex index) const { return _chunks_in_use[index]; }
   649   void set_chunks_in_use(ChunkIndex index, Metachunk* v) {
   650     _chunks_in_use[index] = v;
   651   }
   653   BlockFreelist* block_freelists() const {
   654     return (BlockFreelist*) &_block_freelists;
   655   }
   657   Metaspace::MetadataType mdtype() { return _mdtype; }
   659   VirtualSpaceList* vs_list()   const { return Metaspace::get_space_list(_mdtype); }
   660   ChunkManager* chunk_manager() const { return Metaspace::get_chunk_manager(_mdtype); }
   662   Metachunk* current_chunk() const { return _current_chunk; }
   663   void set_current_chunk(Metachunk* v) {
   664     _current_chunk = v;
   665   }
   667   Metachunk* find_current_chunk(size_t word_size);
   669   // Add chunk to the list of chunks in use
   670   void add_chunk(Metachunk* v, bool make_current);
   671   void retire_current_chunk();
   673   Mutex* lock() const { return _lock; }
   675   const char* chunk_size_name(ChunkIndex index) const;
   677  protected:
   678   void initialize();
   680  public:
   681   SpaceManager(Metaspace::MetadataType mdtype,
   682                Mutex* lock);
   683   ~SpaceManager();
   685   enum ChunkMultiples {
   686     MediumChunkMultiple = 4
   687   };
   689   static size_t specialized_chunk_size(bool is_class) { return is_class ? ClassSpecializedChunk : SpecializedChunk; }
   690   static size_t small_chunk_size(bool is_class)       { return is_class ? ClassSmallChunk : SmallChunk; }
   691   static size_t medium_chunk_size(bool is_class)      { return is_class ? ClassMediumChunk : MediumChunk; }
   693   static size_t smallest_chunk_size(bool is_class)    { return specialized_chunk_size(is_class); }
   695   // Accessors
   696   bool is_class() const { return _mdtype == Metaspace::ClassType; }
   698   size_t specialized_chunk_size() const { return specialized_chunk_size(is_class()); }
   699   size_t small_chunk_size()       const { return small_chunk_size(is_class()); }
   700   size_t medium_chunk_size()      const { return medium_chunk_size(is_class()); }
   702   size_t smallest_chunk_size()    const { return smallest_chunk_size(is_class()); }
   704   size_t medium_chunk_bunch()     const { return medium_chunk_size() * MediumChunkMultiple; }
   706   size_t allocated_blocks_words() const { return _allocated_blocks_words; }
   707   size_t allocated_blocks_bytes() const { return _allocated_blocks_words * BytesPerWord; }
   708   size_t allocated_chunks_words() const { return _allocated_chunks_words; }
   709   size_t allocated_chunks_count() const { return _allocated_chunks_count; }
   711   bool is_humongous(size_t word_size) { return word_size > medium_chunk_size(); }
   713   static Mutex* expand_lock() { return _expand_lock; }
   715   // Increment the per Metaspace and global running sums for Metachunks
   716   // by the given size.  This is used when a Metachunk to added to
   717   // the in-use list.
   718   void inc_size_metrics(size_t words);
   719   // Increment the per Metaspace and global running sums Metablocks by the given
   720   // size.  This is used when a Metablock is allocated.
   721   void inc_used_metrics(size_t words);
   722   // Delete the portion of the running sums for this SpaceManager. That is,
   723   // the globals running sums for the Metachunks and Metablocks are
   724   // decremented for all the Metachunks in-use by this SpaceManager.
   725   void dec_total_from_size_metrics();
   727   // Adjust the initial chunk size to match one of the fixed chunk list sizes,
   728   // or return the unadjusted size if the requested size is humongous.
   729   static size_t adjust_initial_chunk_size(size_t requested, bool is_class_space);
   730   size_t adjust_initial_chunk_size(size_t requested) const;
   732   // Get the initial chunks size for this metaspace type.
   733   size_t get_initial_chunk_size(Metaspace::MetaspaceType type) const;
   735   size_t sum_capacity_in_chunks_in_use() const;
   736   size_t sum_used_in_chunks_in_use() const;
   737   size_t sum_free_in_chunks_in_use() const;
   738   size_t sum_waste_in_chunks_in_use() const;
   739   size_t sum_waste_in_chunks_in_use(ChunkIndex index ) const;
   741   size_t sum_count_in_chunks_in_use();
   742   size_t sum_count_in_chunks_in_use(ChunkIndex i);
   744   Metachunk* get_new_chunk(size_t chunk_word_size);
   746   // Block allocation and deallocation.
   747   // Allocates a block from the current chunk
   748   MetaWord* allocate(size_t word_size);
   750   // Helper for allocations
   751   MetaWord* allocate_work(size_t word_size);
   753   // Returns a block to the per manager freelist
   754   void deallocate(MetaWord* p, size_t word_size);
   756   // Based on the allocation size and a minimum chunk size,
   757   // returned chunk size (for expanding space for chunk allocation).
   758   size_t calc_chunk_size(size_t allocation_word_size);
   760   // Called when an allocation from the current chunk fails.
   761   // Gets a new chunk (may require getting a new virtual space),
   762   // and allocates from that chunk.
   763   MetaWord* grow_and_allocate(size_t word_size);
   765   // Notify memory usage to MemoryService.
   766   void track_metaspace_memory_usage();
   768   // debugging support.
   770   void dump(outputStream* const out) const;
   771   void print_on(outputStream* st) const;
   772   void locked_print_chunks_in_use_on(outputStream* st) const;
   774   void verify();
   775   void verify_chunk_size(Metachunk* chunk);
   776   NOT_PRODUCT(void mangle_freed_chunks();)
   777 #ifdef ASSERT
   778   void verify_allocated_blocks_words();
   779 #endif
   781   size_t get_raw_word_size(size_t word_size) {
   782     size_t byte_size = word_size * BytesPerWord;
   784     size_t raw_bytes_size = MAX2(byte_size, sizeof(Metablock));
   785     raw_bytes_size = align_size_up(raw_bytes_size, Metachunk::object_alignment());
   787     size_t raw_word_size = raw_bytes_size / BytesPerWord;
   788     assert(raw_word_size * BytesPerWord == raw_bytes_size, "Size problem");
   790     return raw_word_size;
   791   }
   792 };
   794 uint const SpaceManager::_small_chunk_limit = 4;
   796 const char* SpaceManager::_expand_lock_name =
   797   "SpaceManager chunk allocation lock";
   798 const int SpaceManager::_expand_lock_rank = Monitor::leaf - 1;
   799 Mutex* const SpaceManager::_expand_lock =
   800   new Mutex(SpaceManager::_expand_lock_rank,
   801             SpaceManager::_expand_lock_name,
   802             Mutex::_allow_vm_block_flag);
   804 void VirtualSpaceNode::inc_container_count() {
   805   assert_lock_strong(SpaceManager::expand_lock());
   806   _container_count++;
   807   assert(_container_count == container_count_slow(),
   808          err_msg("Inconsistency in countainer_count _container_count " SIZE_FORMAT
   809                  " container_count_slow() " SIZE_FORMAT,
   810                  _container_count, container_count_slow()));
   811 }
   813 void VirtualSpaceNode::dec_container_count() {
   814   assert_lock_strong(SpaceManager::expand_lock());
   815   _container_count--;
   816 }
   818 #ifdef ASSERT
   819 void VirtualSpaceNode::verify_container_count() {
   820   assert(_container_count == container_count_slow(),
   821     err_msg("Inconsistency in countainer_count _container_count " SIZE_FORMAT
   822             " container_count_slow() " SIZE_FORMAT, _container_count, container_count_slow()));
   823 }
   824 #endif
   826 // BlockFreelist methods
   828 BlockFreelist::BlockFreelist() : _dictionary(NULL) {}
   830 BlockFreelist::~BlockFreelist() {
   831   if (_dictionary != NULL) {
   832     if (Verbose && TraceMetadataChunkAllocation) {
   833       _dictionary->print_free_lists(gclog_or_tty);
   834     }
   835     delete _dictionary;
   836   }
   837 }
   839 void BlockFreelist::return_block(MetaWord* p, size_t word_size) {
   840   Metablock* free_chunk = ::new (p) Metablock(word_size);
   841   if (dictionary() == NULL) {
   842    _dictionary = new BlockTreeDictionary();
   843   }
   844   dictionary()->return_chunk(free_chunk);
   845 }
   847 MetaWord* BlockFreelist::get_block(size_t word_size) {
   848   if (dictionary() == NULL) {
   849     return NULL;
   850   }
   852   if (word_size < TreeChunk<Metablock, FreeList<Metablock> >::min_size()) {
   853     // Dark matter.  Too small for dictionary.
   854     return NULL;
   855   }
   857   Metablock* free_block =
   858     dictionary()->get_chunk(word_size, FreeBlockDictionary<Metablock>::atLeast);
   859   if (free_block == NULL) {
   860     return NULL;
   861   }
   863   const size_t block_size = free_block->size();
   864   if (block_size > WasteMultiplier * word_size) {
   865     return_block((MetaWord*)free_block, block_size);
   866     return NULL;
   867   }
   869   MetaWord* new_block = (MetaWord*)free_block;
   870   assert(block_size >= word_size, "Incorrect size of block from freelist");
   871   const size_t unused = block_size - word_size;
   872   if (unused >= TreeChunk<Metablock, FreeList<Metablock> >::min_size()) {
   873     return_block(new_block + word_size, unused);
   874   }
   876   return new_block;
   877 }
   879 void BlockFreelist::print_on(outputStream* st) const {
   880   if (dictionary() == NULL) {
   881     return;
   882   }
   883   dictionary()->print_free_lists(st);
   884 }
   886 // VirtualSpaceNode methods
   888 VirtualSpaceNode::~VirtualSpaceNode() {
   889   _rs.release();
   890 #ifdef ASSERT
   891   size_t word_size = sizeof(*this) / BytesPerWord;
   892   Copy::fill_to_words((HeapWord*) this, word_size, 0xf1f1f1f1);
   893 #endif
   894 }
   896 size_t VirtualSpaceNode::used_words_in_vs() const {
   897   return pointer_delta(top(), bottom(), sizeof(MetaWord));
   898 }
   900 // Space committed in the VirtualSpace
   901 size_t VirtualSpaceNode::capacity_words_in_vs() const {
   902   return pointer_delta(end(), bottom(), sizeof(MetaWord));
   903 }
   905 size_t VirtualSpaceNode::free_words_in_vs() const {
   906   return pointer_delta(end(), top(), sizeof(MetaWord));
   907 }
   909 // Allocates the chunk from the virtual space only.
   910 // This interface is also used internally for debugging.  Not all
   911 // chunks removed here are necessarily used for allocation.
   912 Metachunk* VirtualSpaceNode::take_from_committed(size_t chunk_word_size) {
   913   // Bottom of the new chunk
   914   MetaWord* chunk_limit = top();
   915   assert(chunk_limit != NULL, "Not safe to call this method");
   917   // The virtual spaces are always expanded by the
   918   // commit granularity to enforce the following condition.
   919   // Without this the is_available check will not work correctly.
   920   assert(_virtual_space.committed_size() == _virtual_space.actual_committed_size(),
   921       "The committed memory doesn't match the expanded memory.");
   923   if (!is_available(chunk_word_size)) {
   924     if (TraceMetadataChunkAllocation) {
   925       gclog_or_tty->print("VirtualSpaceNode::take_from_committed() not available %d words ", chunk_word_size);
   926       // Dump some information about the virtual space that is nearly full
   927       print_on(gclog_or_tty);
   928     }
   929     return NULL;
   930   }
   932   // Take the space  (bump top on the current virtual space).
   933   inc_top(chunk_word_size);
   935   // Initialize the chunk
   936   Metachunk* result = ::new (chunk_limit) Metachunk(chunk_word_size, this);
   937   return result;
   938 }
   941 // Expand the virtual space (commit more of the reserved space)
   942 bool VirtualSpaceNode::expand_by(size_t min_words, size_t preferred_words) {
   943   size_t min_bytes = min_words * BytesPerWord;
   944   size_t preferred_bytes = preferred_words * BytesPerWord;
   946   size_t uncommitted = virtual_space()->reserved_size() - virtual_space()->actual_committed_size();
   948   if (uncommitted < min_bytes) {
   949     return false;
   950   }
   952   size_t commit = MIN2(preferred_bytes, uncommitted);
   953   bool result = virtual_space()->expand_by(commit, false);
   955   assert(result, "Failed to commit memory");
   957   return result;
   958 }
   960 Metachunk* VirtualSpaceNode::get_chunk_vs(size_t chunk_word_size) {
   961   assert_lock_strong(SpaceManager::expand_lock());
   962   Metachunk* result = take_from_committed(chunk_word_size);
   963   if (result != NULL) {
   964     inc_container_count();
   965   }
   966   return result;
   967 }
   969 bool VirtualSpaceNode::initialize() {
   971   if (!_rs.is_reserved()) {
   972     return false;
   973   }
   975   // These are necessary restriction to make sure that the virtual space always
   976   // grows in steps of Metaspace::commit_alignment(). If both base and size are
   977   // aligned only the middle alignment of the VirtualSpace is used.
   978   assert_is_ptr_aligned(_rs.base(), Metaspace::commit_alignment());
   979   assert_is_size_aligned(_rs.size(), Metaspace::commit_alignment());
   981   // ReservedSpaces marked as special will have the entire memory
   982   // pre-committed. Setting a committed size will make sure that
   983   // committed_size and actual_committed_size agrees.
   984   size_t pre_committed_size = _rs.special() ? _rs.size() : 0;
   986   bool result = virtual_space()->initialize_with_granularity(_rs, pre_committed_size,
   987                                             Metaspace::commit_alignment());
   988   if (result) {
   989     assert(virtual_space()->committed_size() == virtual_space()->actual_committed_size(),
   990         "Checking that the pre-committed memory was registered by the VirtualSpace");
   992     set_top((MetaWord*)virtual_space()->low());
   993     set_reserved(MemRegion((HeapWord*)_rs.base(),
   994                  (HeapWord*)(_rs.base() + _rs.size())));
   996     assert(reserved()->start() == (HeapWord*) _rs.base(),
   997       err_msg("Reserved start was not set properly " PTR_FORMAT
   998         " != " PTR_FORMAT, reserved()->start(), _rs.base()));
   999     assert(reserved()->word_size() == _rs.size() / BytesPerWord,
  1000       err_msg("Reserved size was not set properly " SIZE_FORMAT
  1001         " != " SIZE_FORMAT, reserved()->word_size(),
  1002         _rs.size() / BytesPerWord));
  1005   return result;
  1008 void VirtualSpaceNode::print_on(outputStream* st) const {
  1009   size_t used = used_words_in_vs();
  1010   size_t capacity = capacity_words_in_vs();
  1011   VirtualSpace* vs = virtual_space();
  1012   st->print_cr("   space @ " PTR_FORMAT " " SIZE_FORMAT "K, %3d%% used "
  1013            "[" PTR_FORMAT ", " PTR_FORMAT ", "
  1014            PTR_FORMAT ", " PTR_FORMAT ")",
  1015            vs, capacity / K,
  1016            capacity == 0 ? 0 : used * 100 / capacity,
  1017            bottom(), top(), end(),
  1018            vs->high_boundary());
  1021 #ifdef ASSERT
  1022 void VirtualSpaceNode::mangle() {
  1023   size_t word_size = capacity_words_in_vs();
  1024   Copy::fill_to_words((HeapWord*) low(), word_size, 0xf1f1f1f1);
  1026 #endif // ASSERT
  1028 // VirtualSpaceList methods
  1029 // Space allocated from the VirtualSpace
  1031 VirtualSpaceList::~VirtualSpaceList() {
  1032   VirtualSpaceListIterator iter(virtual_space_list());
  1033   while (iter.repeat()) {
  1034     VirtualSpaceNode* vsl = iter.get_next();
  1035     delete vsl;
  1039 void VirtualSpaceList::inc_reserved_words(size_t v) {
  1040   assert_lock_strong(SpaceManager::expand_lock());
  1041   _reserved_words = _reserved_words + v;
  1043 void VirtualSpaceList::dec_reserved_words(size_t v) {
  1044   assert_lock_strong(SpaceManager::expand_lock());
  1045   _reserved_words = _reserved_words - v;
  1048 #define assert_committed_below_limit()                             \
  1049   assert(MetaspaceAux::committed_bytes() <= MaxMetaspaceSize,      \
  1050       err_msg("Too much committed memory. Committed: " SIZE_FORMAT \
  1051               " limit (MaxMetaspaceSize): " SIZE_FORMAT,           \
  1052           MetaspaceAux::committed_bytes(), MaxMetaspaceSize));
  1054 void VirtualSpaceList::inc_committed_words(size_t v) {
  1055   assert_lock_strong(SpaceManager::expand_lock());
  1056   _committed_words = _committed_words + v;
  1058   assert_committed_below_limit();
  1060 void VirtualSpaceList::dec_committed_words(size_t v) {
  1061   assert_lock_strong(SpaceManager::expand_lock());
  1062   _committed_words = _committed_words - v;
  1064   assert_committed_below_limit();
  1067 void VirtualSpaceList::inc_virtual_space_count() {
  1068   assert_lock_strong(SpaceManager::expand_lock());
  1069   _virtual_space_count++;
  1071 void VirtualSpaceList::dec_virtual_space_count() {
  1072   assert_lock_strong(SpaceManager::expand_lock());
  1073   _virtual_space_count--;
  1076 void ChunkManager::remove_chunk(Metachunk* chunk) {
  1077   size_t word_size = chunk->word_size();
  1078   ChunkIndex index = list_index(word_size);
  1079   if (index != HumongousIndex) {
  1080     free_chunks(index)->remove_chunk(chunk);
  1081   } else {
  1082     humongous_dictionary()->remove_chunk(chunk);
  1085   // Chunk is being removed from the chunks free list.
  1086   dec_free_chunks_total(chunk->word_size());
  1089 // Walk the list of VirtualSpaceNodes and delete
  1090 // nodes with a 0 container_count.  Remove Metachunks in
  1091 // the node from their respective freelists.
  1092 void VirtualSpaceList::purge(ChunkManager* chunk_manager) {
  1093   assert(SafepointSynchronize::is_at_safepoint(), "must be called at safepoint for contains to work");
  1094   assert_lock_strong(SpaceManager::expand_lock());
  1095   // Don't use a VirtualSpaceListIterator because this
  1096   // list is being changed and a straightforward use of an iterator is not safe.
  1097   VirtualSpaceNode* purged_vsl = NULL;
  1098   VirtualSpaceNode* prev_vsl = virtual_space_list();
  1099   VirtualSpaceNode* next_vsl = prev_vsl;
  1100   while (next_vsl != NULL) {
  1101     VirtualSpaceNode* vsl = next_vsl;
  1102     next_vsl = vsl->next();
  1103     // Don't free the current virtual space since it will likely
  1104     // be needed soon.
  1105     if (vsl->container_count() == 0 && vsl != current_virtual_space()) {
  1106       // Unlink it from the list
  1107       if (prev_vsl == vsl) {
  1108         // This is the case of the current node being the first node.
  1109         assert(vsl == virtual_space_list(), "Expected to be the first node");
  1110         set_virtual_space_list(vsl->next());
  1111       } else {
  1112         prev_vsl->set_next(vsl->next());
  1115       vsl->purge(chunk_manager);
  1116       dec_reserved_words(vsl->reserved_words());
  1117       dec_committed_words(vsl->committed_words());
  1118       dec_virtual_space_count();
  1119       purged_vsl = vsl;
  1120       delete vsl;
  1121     } else {
  1122       prev_vsl = vsl;
  1125 #ifdef ASSERT
  1126   if (purged_vsl != NULL) {
  1127     // List should be stable enough to use an iterator here.
  1128     VirtualSpaceListIterator iter(virtual_space_list());
  1129     while (iter.repeat()) {
  1130       VirtualSpaceNode* vsl = iter.get_next();
  1131       assert(vsl != purged_vsl, "Purge of vsl failed");
  1134 #endif
  1138 // This function looks at the mmap regions in the metaspace without locking.
  1139 // The chunks are added with store ordering and not deleted except for at
  1140 // unloading time during a safepoint.
  1141 bool VirtualSpaceList::contains(const void* ptr) {
  1142   // List should be stable enough to use an iterator here because removing virtual
  1143   // space nodes is only allowed at a safepoint.
  1144   VirtualSpaceListIterator iter(virtual_space_list());
  1145   while (iter.repeat()) {
  1146     VirtualSpaceNode* vsn = iter.get_next();
  1147     if (vsn->contains(ptr)) {
  1148       return true;
  1151   return false;
  1154 void VirtualSpaceList::retire_current_virtual_space() {
  1155   assert_lock_strong(SpaceManager::expand_lock());
  1157   VirtualSpaceNode* vsn = current_virtual_space();
  1159   ChunkManager* cm = is_class() ? Metaspace::chunk_manager_class() :
  1160                                   Metaspace::chunk_manager_metadata();
  1162   vsn->retire(cm);
  1165 void VirtualSpaceNode::retire(ChunkManager* chunk_manager) {
  1166   for (int i = (int)MediumIndex; i >= (int)ZeroIndex; --i) {
  1167     ChunkIndex index = (ChunkIndex)i;
  1168     size_t chunk_size = chunk_manager->free_chunks(index)->size();
  1170     while (free_words_in_vs() >= chunk_size) {
  1171       DEBUG_ONLY(verify_container_count();)
  1172       Metachunk* chunk = get_chunk_vs(chunk_size);
  1173       assert(chunk != NULL, "allocation should have been successful");
  1175       chunk_manager->return_chunks(index, chunk);
  1176       chunk_manager->inc_free_chunks_total(chunk_size);
  1177       DEBUG_ONLY(verify_container_count();)
  1180   assert(free_words_in_vs() == 0, "should be empty now");
  1183 VirtualSpaceList::VirtualSpaceList(size_t word_size) :
  1184                                    _is_class(false),
  1185                                    _virtual_space_list(NULL),
  1186                                    _current_virtual_space(NULL),
  1187                                    _reserved_words(0),
  1188                                    _committed_words(0),
  1189                                    _virtual_space_count(0) {
  1190   MutexLockerEx cl(SpaceManager::expand_lock(),
  1191                    Mutex::_no_safepoint_check_flag);
  1192   create_new_virtual_space(word_size);
  1195 VirtualSpaceList::VirtualSpaceList(ReservedSpace rs) :
  1196                                    _is_class(true),
  1197                                    _virtual_space_list(NULL),
  1198                                    _current_virtual_space(NULL),
  1199                                    _reserved_words(0),
  1200                                    _committed_words(0),
  1201                                    _virtual_space_count(0) {
  1202   MutexLockerEx cl(SpaceManager::expand_lock(),
  1203                    Mutex::_no_safepoint_check_flag);
  1204   VirtualSpaceNode* class_entry = new VirtualSpaceNode(rs);
  1205   bool succeeded = class_entry->initialize();
  1206   if (succeeded) {
  1207     link_vs(class_entry);
  1211 size_t VirtualSpaceList::free_bytes() {
  1212   return current_virtual_space()->free_words_in_vs() * BytesPerWord;
  1215 // Allocate another meta virtual space and add it to the list.
  1216 bool VirtualSpaceList::create_new_virtual_space(size_t vs_word_size) {
  1217   assert_lock_strong(SpaceManager::expand_lock());
  1219   if (is_class()) {
  1220     assert(false, "We currently don't support more than one VirtualSpace for"
  1221                   " the compressed class space. The initialization of the"
  1222                   " CCS uses another code path and should not hit this path.");
  1223     return false;
  1226   if (vs_word_size == 0) {
  1227     assert(false, "vs_word_size should always be at least _reserve_alignment large.");
  1228     return false;
  1231   // Reserve the space
  1232   size_t vs_byte_size = vs_word_size * BytesPerWord;
  1233   assert_is_size_aligned(vs_byte_size, Metaspace::reserve_alignment());
  1235   // Allocate the meta virtual space and initialize it.
  1236   VirtualSpaceNode* new_entry = new VirtualSpaceNode(vs_byte_size);
  1237   if (!new_entry->initialize()) {
  1238     delete new_entry;
  1239     return false;
  1240   } else {
  1241     assert(new_entry->reserved_words() == vs_word_size,
  1242         "Reserved memory size differs from requested memory size");
  1243     // ensure lock-free iteration sees fully initialized node
  1244     OrderAccess::storestore();
  1245     link_vs(new_entry);
  1246     return true;
  1250 void VirtualSpaceList::link_vs(VirtualSpaceNode* new_entry) {
  1251   if (virtual_space_list() == NULL) {
  1252       set_virtual_space_list(new_entry);
  1253   } else {
  1254     current_virtual_space()->set_next(new_entry);
  1256   set_current_virtual_space(new_entry);
  1257   inc_reserved_words(new_entry->reserved_words());
  1258   inc_committed_words(new_entry->committed_words());
  1259   inc_virtual_space_count();
  1260 #ifdef ASSERT
  1261   new_entry->mangle();
  1262 #endif
  1263   if (TraceMetavirtualspaceAllocation && Verbose) {
  1264     VirtualSpaceNode* vsl = current_virtual_space();
  1265     vsl->print_on(gclog_or_tty);
  1269 bool VirtualSpaceList::expand_node_by(VirtualSpaceNode* node,
  1270                                       size_t min_words,
  1271                                       size_t preferred_words) {
  1272   size_t before = node->committed_words();
  1274   bool result = node->expand_by(min_words, preferred_words);
  1276   size_t after = node->committed_words();
  1278   // after and before can be the same if the memory was pre-committed.
  1279   assert(after >= before, "Inconsistency");
  1280   inc_committed_words(after - before);
  1282   return result;
  1285 bool VirtualSpaceList::expand_by(size_t min_words, size_t preferred_words) {
  1286   assert_is_size_aligned(min_words,       Metaspace::commit_alignment_words());
  1287   assert_is_size_aligned(preferred_words, Metaspace::commit_alignment_words());
  1288   assert(min_words <= preferred_words, "Invalid arguments");
  1290   if (!MetaspaceGC::can_expand(min_words, this->is_class())) {
  1291     return  false;
  1294   size_t allowed_expansion_words = MetaspaceGC::allowed_expansion();
  1295   if (allowed_expansion_words < min_words) {
  1296     return false;
  1299   size_t max_expansion_words = MIN2(preferred_words, allowed_expansion_words);
  1301   // Commit more memory from the the current virtual space.
  1302   bool vs_expanded = expand_node_by(current_virtual_space(),
  1303                                     min_words,
  1304                                     max_expansion_words);
  1305   if (vs_expanded) {
  1306     return true;
  1308   retire_current_virtual_space();
  1310   // Get another virtual space.
  1311   size_t grow_vs_words = MAX2((size_t)VirtualSpaceSize, preferred_words);
  1312   grow_vs_words = align_size_up(grow_vs_words, Metaspace::reserve_alignment_words());
  1314   if (create_new_virtual_space(grow_vs_words)) {
  1315     if (current_virtual_space()->is_pre_committed()) {
  1316       // The memory was pre-committed, so we are done here.
  1317       assert(min_words <= current_virtual_space()->committed_words(),
  1318           "The new VirtualSpace was pre-committed, so it"
  1319           "should be large enough to fit the alloc request.");
  1320       return true;
  1323     return expand_node_by(current_virtual_space(),
  1324                           min_words,
  1325                           max_expansion_words);
  1328   return false;
  1331 Metachunk* VirtualSpaceList::get_new_chunk(size_t chunk_word_size, size_t suggested_commit_granularity) {
  1333   // Allocate a chunk out of the current virtual space.
  1334   Metachunk* next = current_virtual_space()->get_chunk_vs(chunk_word_size);
  1336   if (next != NULL) {
  1337     return next;
  1340   // The expand amount is currently only determined by the requested sizes
  1341   // and not how much committed memory is left in the current virtual space.
  1343   size_t min_word_size       = align_size_up(chunk_word_size,              Metaspace::commit_alignment_words());
  1344   size_t preferred_word_size = align_size_up(suggested_commit_granularity, Metaspace::commit_alignment_words());
  1345   if (min_word_size >= preferred_word_size) {
  1346     // Can happen when humongous chunks are allocated.
  1347     preferred_word_size = min_word_size;
  1350   bool expanded = expand_by(min_word_size, preferred_word_size);
  1351   if (expanded) {
  1352     next = current_virtual_space()->get_chunk_vs(chunk_word_size);
  1353     assert(next != NULL, "The allocation was expected to succeed after the expansion");
  1356    return next;
  1359 void VirtualSpaceList::print_on(outputStream* st) const {
  1360   if (TraceMetadataChunkAllocation && Verbose) {
  1361     VirtualSpaceListIterator iter(virtual_space_list());
  1362     while (iter.repeat()) {
  1363       VirtualSpaceNode* node = iter.get_next();
  1364       node->print_on(st);
  1369 // MetaspaceGC methods
  1371 // VM_CollectForMetadataAllocation is the vm operation used to GC.
  1372 // Within the VM operation after the GC the attempt to allocate the metadata
  1373 // should succeed.  If the GC did not free enough space for the metaspace
  1374 // allocation, the HWM is increased so that another virtualspace will be
  1375 // allocated for the metadata.  With perm gen the increase in the perm
  1376 // gen had bounds, MinMetaspaceExpansion and MaxMetaspaceExpansion.  The
  1377 // metaspace policy uses those as the small and large steps for the HWM.
  1378 //
  1379 // After the GC the compute_new_size() for MetaspaceGC is called to
  1380 // resize the capacity of the metaspaces.  The current implementation
  1381 // is based on the flags MinMetaspaceFreeRatio and MaxMetaspaceFreeRatio used
  1382 // to resize the Java heap by some GC's.  New flags can be implemented
  1383 // if really needed.  MinMetaspaceFreeRatio is used to calculate how much
  1384 // free space is desirable in the metaspace capacity to decide how much
  1385 // to increase the HWM.  MaxMetaspaceFreeRatio is used to decide how much
  1386 // free space is desirable in the metaspace capacity before decreasing
  1387 // the HWM.
  1389 // Calculate the amount to increase the high water mark (HWM).
  1390 // Increase by a minimum amount (MinMetaspaceExpansion) so that
  1391 // another expansion is not requested too soon.  If that is not
  1392 // enough to satisfy the allocation, increase by MaxMetaspaceExpansion.
  1393 // If that is still not enough, expand by the size of the allocation
  1394 // plus some.
  1395 size_t MetaspaceGC::delta_capacity_until_GC(size_t bytes) {
  1396   size_t min_delta = MinMetaspaceExpansion;
  1397   size_t max_delta = MaxMetaspaceExpansion;
  1398   size_t delta = align_size_up(bytes, Metaspace::commit_alignment());
  1400   if (delta <= min_delta) {
  1401     delta = min_delta;
  1402   } else if (delta <= max_delta) {
  1403     // Don't want to hit the high water mark on the next
  1404     // allocation so make the delta greater than just enough
  1405     // for this allocation.
  1406     delta = max_delta;
  1407   } else {
  1408     // This allocation is large but the next ones are probably not
  1409     // so increase by the minimum.
  1410     delta = delta + min_delta;
  1413   assert_is_size_aligned(delta, Metaspace::commit_alignment());
  1415   return delta;
  1418 size_t MetaspaceGC::capacity_until_GC() {
  1419   size_t value = (size_t)OrderAccess::load_ptr_acquire(&_capacity_until_GC);
  1420   assert(value >= MetaspaceSize, "Not initialied properly?");
  1421   return value;
  1424 bool MetaspaceGC::inc_capacity_until_GC(size_t v, size_t* new_cap_until_GC, size_t* old_cap_until_GC) {
  1425   assert_is_size_aligned(v, Metaspace::commit_alignment());
  1427   size_t capacity_until_GC = (size_t) _capacity_until_GC;
  1428   size_t new_value = capacity_until_GC + v;
  1430   if (new_value < capacity_until_GC) {
  1431     // The addition wrapped around, set new_value to aligned max value.
  1432     new_value = align_size_down(max_uintx, Metaspace::commit_alignment());
  1435   intptr_t expected = (intptr_t) capacity_until_GC;
  1436   intptr_t actual = Atomic::cmpxchg_ptr((intptr_t) new_value, &_capacity_until_GC, expected);
  1438   if (expected != actual) {
  1439     return false;
  1442   if (new_cap_until_GC != NULL) {
  1443     *new_cap_until_GC = new_value;
  1445   if (old_cap_until_GC != NULL) {
  1446     *old_cap_until_GC = capacity_until_GC;
  1448   return true;
  1451 size_t MetaspaceGC::dec_capacity_until_GC(size_t v) {
  1452   assert_is_size_aligned(v, Metaspace::commit_alignment());
  1454   return (size_t)Atomic::add_ptr(-(intptr_t)v, &_capacity_until_GC);
  1457 void MetaspaceGC::initialize() {
  1458   // Set the high-water mark to MaxMetapaceSize during VM initializaton since
  1459   // we can't do a GC during initialization.
  1460   _capacity_until_GC = MaxMetaspaceSize;
  1463 void MetaspaceGC::post_initialize() {
  1464   // Reset the high-water mark once the VM initialization is done.
  1465   _capacity_until_GC = MAX2(MetaspaceAux::committed_bytes(), MetaspaceSize);
  1468 bool MetaspaceGC::can_expand(size_t word_size, bool is_class) {
  1469   // Check if the compressed class space is full.
  1470   if (is_class && Metaspace::using_class_space()) {
  1471     size_t class_committed = MetaspaceAux::committed_bytes(Metaspace::ClassType);
  1472     if (class_committed + word_size * BytesPerWord > CompressedClassSpaceSize) {
  1473       return false;
  1477   // Check if the user has imposed a limit on the metaspace memory.
  1478   size_t committed_bytes = MetaspaceAux::committed_bytes();
  1479   if (committed_bytes + word_size * BytesPerWord > MaxMetaspaceSize) {
  1480     return false;
  1483   return true;
  1486 size_t MetaspaceGC::allowed_expansion() {
  1487   size_t committed_bytes = MetaspaceAux::committed_bytes();
  1488   size_t capacity_until_gc = capacity_until_GC();
  1490   assert(capacity_until_gc >= committed_bytes,
  1491         err_msg("capacity_until_gc: " SIZE_FORMAT " < committed_bytes: " SIZE_FORMAT,
  1492                 capacity_until_gc, committed_bytes));
  1494   size_t left_until_max  = MaxMetaspaceSize - committed_bytes;
  1495   size_t left_until_GC = capacity_until_gc - committed_bytes;
  1496   size_t left_to_commit = MIN2(left_until_GC, left_until_max);
  1498   return left_to_commit / BytesPerWord;
  1501 void MetaspaceGC::compute_new_size() {
  1502   assert(_shrink_factor <= 100, "invalid shrink factor");
  1503   uint current_shrink_factor = _shrink_factor;
  1504   _shrink_factor = 0;
  1506   // Using committed_bytes() for used_after_gc is an overestimation, since the
  1507   // chunk free lists are included in committed_bytes() and the memory in an
  1508   // un-fragmented chunk free list is available for future allocations.
  1509   // However, if the chunk free lists becomes fragmented, then the memory may
  1510   // not be available for future allocations and the memory is therefore "in use".
  1511   // Including the chunk free lists in the definition of "in use" is therefore
  1512   // necessary. Not including the chunk free lists can cause capacity_until_GC to
  1513   // shrink below committed_bytes() and this has caused serious bugs in the past.
  1514   const size_t used_after_gc = MetaspaceAux::committed_bytes();
  1515   const size_t capacity_until_GC = MetaspaceGC::capacity_until_GC();
  1517   const double minimum_free_percentage = MinMetaspaceFreeRatio / 100.0;
  1518   const double maximum_used_percentage = 1.0 - minimum_free_percentage;
  1520   const double min_tmp = used_after_gc / maximum_used_percentage;
  1521   size_t minimum_desired_capacity =
  1522     (size_t)MIN2(min_tmp, double(max_uintx));
  1523   // Don't shrink less than the initial generation size
  1524   minimum_desired_capacity = MAX2(minimum_desired_capacity,
  1525                                   MetaspaceSize);
  1527   if (PrintGCDetails && Verbose) {
  1528     gclog_or_tty->print_cr("\nMetaspaceGC::compute_new_size: ");
  1529     gclog_or_tty->print_cr("  "
  1530                   "  minimum_free_percentage: %6.2f"
  1531                   "  maximum_used_percentage: %6.2f",
  1532                   minimum_free_percentage,
  1533                   maximum_used_percentage);
  1534     gclog_or_tty->print_cr("  "
  1535                   "   used_after_gc       : %6.1fKB",
  1536                   used_after_gc / (double) K);
  1540   size_t shrink_bytes = 0;
  1541   if (capacity_until_GC < minimum_desired_capacity) {
  1542     // If we have less capacity below the metaspace HWM, then
  1543     // increment the HWM.
  1544     size_t expand_bytes = minimum_desired_capacity - capacity_until_GC;
  1545     expand_bytes = align_size_up(expand_bytes, Metaspace::commit_alignment());
  1546     // Don't expand unless it's significant
  1547     if (expand_bytes >= MinMetaspaceExpansion) {
  1548       size_t new_capacity_until_GC = 0;
  1549       bool succeeded = MetaspaceGC::inc_capacity_until_GC(expand_bytes, &new_capacity_until_GC);
  1550       assert(succeeded, "Should always succesfully increment HWM when at safepoint");
  1552       Metaspace::tracer()->report_gc_threshold(capacity_until_GC,
  1553                                                new_capacity_until_GC,
  1554                                                MetaspaceGCThresholdUpdater::ComputeNewSize);
  1555       if (PrintGCDetails && Verbose) {
  1556         gclog_or_tty->print_cr("    expanding:"
  1557                       "  minimum_desired_capacity: %6.1fKB"
  1558                       "  expand_bytes: %6.1fKB"
  1559                       "  MinMetaspaceExpansion: %6.1fKB"
  1560                       "  new metaspace HWM:  %6.1fKB",
  1561                       minimum_desired_capacity / (double) K,
  1562                       expand_bytes / (double) K,
  1563                       MinMetaspaceExpansion / (double) K,
  1564                       new_capacity_until_GC / (double) K);
  1567     return;
  1570   // No expansion, now see if we want to shrink
  1571   // We would never want to shrink more than this
  1572   size_t max_shrink_bytes = capacity_until_GC - minimum_desired_capacity;
  1573   assert(max_shrink_bytes >= 0, err_msg("max_shrink_bytes " SIZE_FORMAT,
  1574     max_shrink_bytes));
  1576   // Should shrinking be considered?
  1577   if (MaxMetaspaceFreeRatio < 100) {
  1578     const double maximum_free_percentage = MaxMetaspaceFreeRatio / 100.0;
  1579     const double minimum_used_percentage = 1.0 - maximum_free_percentage;
  1580     const double max_tmp = used_after_gc / minimum_used_percentage;
  1581     size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(max_uintx));
  1582     maximum_desired_capacity = MAX2(maximum_desired_capacity,
  1583                                     MetaspaceSize);
  1584     if (PrintGCDetails && Verbose) {
  1585       gclog_or_tty->print_cr("  "
  1586                              "  maximum_free_percentage: %6.2f"
  1587                              "  minimum_used_percentage: %6.2f",
  1588                              maximum_free_percentage,
  1589                              minimum_used_percentage);
  1590       gclog_or_tty->print_cr("  "
  1591                              "  minimum_desired_capacity: %6.1fKB"
  1592                              "  maximum_desired_capacity: %6.1fKB",
  1593                              minimum_desired_capacity / (double) K,
  1594                              maximum_desired_capacity / (double) K);
  1597     assert(minimum_desired_capacity <= maximum_desired_capacity,
  1598            "sanity check");
  1600     if (capacity_until_GC > maximum_desired_capacity) {
  1601       // Capacity too large, compute shrinking size
  1602       shrink_bytes = capacity_until_GC - maximum_desired_capacity;
  1603       // We don't want shrink all the way back to initSize if people call
  1604       // System.gc(), because some programs do that between "phases" and then
  1605       // we'd just have to grow the heap up again for the next phase.  So we
  1606       // damp the shrinking: 0% on the first call, 10% on the second call, 40%
  1607       // on the third call, and 100% by the fourth call.  But if we recompute
  1608       // size without shrinking, it goes back to 0%.
  1609       shrink_bytes = shrink_bytes / 100 * current_shrink_factor;
  1611       shrink_bytes = align_size_down(shrink_bytes, Metaspace::commit_alignment());
  1613       assert(shrink_bytes <= max_shrink_bytes,
  1614         err_msg("invalid shrink size " SIZE_FORMAT " not <= " SIZE_FORMAT,
  1615           shrink_bytes, max_shrink_bytes));
  1616       if (current_shrink_factor == 0) {
  1617         _shrink_factor = 10;
  1618       } else {
  1619         _shrink_factor = MIN2(current_shrink_factor * 4, (uint) 100);
  1621       if (PrintGCDetails && Verbose) {
  1622         gclog_or_tty->print_cr("  "
  1623                       "  shrinking:"
  1624                       "  initSize: %.1fK"
  1625                       "  maximum_desired_capacity: %.1fK",
  1626                       MetaspaceSize / (double) K,
  1627                       maximum_desired_capacity / (double) K);
  1628         gclog_or_tty->print_cr("  "
  1629                       "  shrink_bytes: %.1fK"
  1630                       "  current_shrink_factor: %d"
  1631                       "  new shrink factor: %d"
  1632                       "  MinMetaspaceExpansion: %.1fK",
  1633                       shrink_bytes / (double) K,
  1634                       current_shrink_factor,
  1635                       _shrink_factor,
  1636                       MinMetaspaceExpansion / (double) K);
  1641   // Don't shrink unless it's significant
  1642   if (shrink_bytes >= MinMetaspaceExpansion &&
  1643       ((capacity_until_GC - shrink_bytes) >= MetaspaceSize)) {
  1644     size_t new_capacity_until_GC = MetaspaceGC::dec_capacity_until_GC(shrink_bytes);
  1645     Metaspace::tracer()->report_gc_threshold(capacity_until_GC,
  1646                                              new_capacity_until_GC,
  1647                                              MetaspaceGCThresholdUpdater::ComputeNewSize);
  1651 // Metadebug methods
  1653 void Metadebug::init_allocation_fail_alot_count() {
  1654   if (MetadataAllocationFailALot) {
  1655     _allocation_fail_alot_count =
  1656       1+(long)((double)MetadataAllocationFailALotInterval*os::random()/(max_jint+1.0));
  1660 #ifdef ASSERT
  1661 bool Metadebug::test_metadata_failure() {
  1662   if (MetadataAllocationFailALot &&
  1663       Threads::is_vm_complete()) {
  1664     if (_allocation_fail_alot_count > 0) {
  1665       _allocation_fail_alot_count--;
  1666     } else {
  1667       if (TraceMetadataChunkAllocation && Verbose) {
  1668         gclog_or_tty->print_cr("Metadata allocation failing for "
  1669                                "MetadataAllocationFailALot");
  1671       init_allocation_fail_alot_count();
  1672       return true;
  1675   return false;
  1677 #endif
  1679 // ChunkManager methods
  1681 size_t ChunkManager::free_chunks_total_words() {
  1682   return _free_chunks_total;
  1685 size_t ChunkManager::free_chunks_total_bytes() {
  1686   return free_chunks_total_words() * BytesPerWord;
  1689 size_t ChunkManager::free_chunks_count() {
  1690 #ifdef ASSERT
  1691   if (!UseConcMarkSweepGC && !SpaceManager::expand_lock()->is_locked()) {
  1692     MutexLockerEx cl(SpaceManager::expand_lock(),
  1693                      Mutex::_no_safepoint_check_flag);
  1694     // This lock is only needed in debug because the verification
  1695     // of the _free_chunks_totals walks the list of free chunks
  1696     slow_locked_verify_free_chunks_count();
  1698 #endif
  1699   return _free_chunks_count;
  1702 void ChunkManager::locked_verify_free_chunks_total() {
  1703   assert_lock_strong(SpaceManager::expand_lock());
  1704   assert(sum_free_chunks() == _free_chunks_total,
  1705     err_msg("_free_chunks_total " SIZE_FORMAT " is not the"
  1706            " same as sum " SIZE_FORMAT, _free_chunks_total,
  1707            sum_free_chunks()));
  1710 void ChunkManager::verify_free_chunks_total() {
  1711   MutexLockerEx cl(SpaceManager::expand_lock(),
  1712                      Mutex::_no_safepoint_check_flag);
  1713   locked_verify_free_chunks_total();
  1716 void ChunkManager::locked_verify_free_chunks_count() {
  1717   assert_lock_strong(SpaceManager::expand_lock());
  1718   assert(sum_free_chunks_count() == _free_chunks_count,
  1719     err_msg("_free_chunks_count " SIZE_FORMAT " is not the"
  1720            " same as sum " SIZE_FORMAT, _free_chunks_count,
  1721            sum_free_chunks_count()));
  1724 void ChunkManager::verify_free_chunks_count() {
  1725 #ifdef ASSERT
  1726   MutexLockerEx cl(SpaceManager::expand_lock(),
  1727                      Mutex::_no_safepoint_check_flag);
  1728   locked_verify_free_chunks_count();
  1729 #endif
  1732 void ChunkManager::verify() {
  1733   MutexLockerEx cl(SpaceManager::expand_lock(),
  1734                      Mutex::_no_safepoint_check_flag);
  1735   locked_verify();
  1738 void ChunkManager::locked_verify() {
  1739   locked_verify_free_chunks_count();
  1740   locked_verify_free_chunks_total();
  1743 void ChunkManager::locked_print_free_chunks(outputStream* st) {
  1744   assert_lock_strong(SpaceManager::expand_lock());
  1745   st->print_cr("Free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
  1746                 _free_chunks_total, _free_chunks_count);
  1749 void ChunkManager::locked_print_sum_free_chunks(outputStream* st) {
  1750   assert_lock_strong(SpaceManager::expand_lock());
  1751   st->print_cr("Sum free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
  1752                 sum_free_chunks(), sum_free_chunks_count());
  1754 ChunkList* ChunkManager::free_chunks(ChunkIndex index) {
  1755   return &_free_chunks[index];
  1758 // These methods that sum the free chunk lists are used in printing
  1759 // methods that are used in product builds.
  1760 size_t ChunkManager::sum_free_chunks() {
  1761   assert_lock_strong(SpaceManager::expand_lock());
  1762   size_t result = 0;
  1763   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
  1764     ChunkList* list = free_chunks(i);
  1766     if (list == NULL) {
  1767       continue;
  1770     result = result + list->count() * list->size();
  1772   result = result + humongous_dictionary()->total_size();
  1773   return result;
  1776 size_t ChunkManager::sum_free_chunks_count() {
  1777   assert_lock_strong(SpaceManager::expand_lock());
  1778   size_t count = 0;
  1779   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
  1780     ChunkList* list = free_chunks(i);
  1781     if (list == NULL) {
  1782       continue;
  1784     count = count + list->count();
  1786   count = count + humongous_dictionary()->total_free_blocks();
  1787   return count;
  1790 ChunkList* ChunkManager::find_free_chunks_list(size_t word_size) {
  1791   ChunkIndex index = list_index(word_size);
  1792   assert(index < HumongousIndex, "No humongous list");
  1793   return free_chunks(index);
  1796 Metachunk* ChunkManager::free_chunks_get(size_t word_size) {
  1797   assert_lock_strong(SpaceManager::expand_lock());
  1799   slow_locked_verify();
  1801   Metachunk* chunk = NULL;
  1802   if (list_index(word_size) != HumongousIndex) {
  1803     ChunkList* free_list = find_free_chunks_list(word_size);
  1804     assert(free_list != NULL, "Sanity check");
  1806     chunk = free_list->head();
  1808     if (chunk == NULL) {
  1809       return NULL;
  1812     // Remove the chunk as the head of the list.
  1813     free_list->remove_chunk(chunk);
  1815     if (TraceMetadataChunkAllocation && Verbose) {
  1816       gclog_or_tty->print_cr("ChunkManager::free_chunks_get: free_list "
  1817                              PTR_FORMAT " head " PTR_FORMAT " size " SIZE_FORMAT,
  1818                              free_list, chunk, chunk->word_size());
  1820   } else {
  1821     chunk = humongous_dictionary()->get_chunk(
  1822       word_size,
  1823       FreeBlockDictionary<Metachunk>::atLeast);
  1825     if (chunk == NULL) {
  1826       return NULL;
  1829     if (TraceMetadataHumongousAllocation) {
  1830       size_t waste = chunk->word_size() - word_size;
  1831       gclog_or_tty->print_cr("Free list allocate humongous chunk size "
  1832                              SIZE_FORMAT " for requested size " SIZE_FORMAT
  1833                              " waste " SIZE_FORMAT,
  1834                              chunk->word_size(), word_size, waste);
  1838   // Chunk is being removed from the chunks free list.
  1839   dec_free_chunks_total(chunk->word_size());
  1841   // Remove it from the links to this freelist
  1842   chunk->set_next(NULL);
  1843   chunk->set_prev(NULL);
  1844 #ifdef ASSERT
  1845   // Chunk is no longer on any freelist. Setting to false make container_count_slow()
  1846   // work.
  1847   chunk->set_is_tagged_free(false);
  1848 #endif
  1849   chunk->container()->inc_container_count();
  1851   slow_locked_verify();
  1852   return chunk;
  1855 Metachunk* ChunkManager::chunk_freelist_allocate(size_t word_size) {
  1856   assert_lock_strong(SpaceManager::expand_lock());
  1857   slow_locked_verify();
  1859   // Take from the beginning of the list
  1860   Metachunk* chunk = free_chunks_get(word_size);
  1861   if (chunk == NULL) {
  1862     return NULL;
  1865   assert((word_size <= chunk->word_size()) ||
  1866          list_index(chunk->word_size() == HumongousIndex),
  1867          "Non-humongous variable sized chunk");
  1868   if (TraceMetadataChunkAllocation) {
  1869     size_t list_count;
  1870     if (list_index(word_size) < HumongousIndex) {
  1871       ChunkList* list = find_free_chunks_list(word_size);
  1872       list_count = list->count();
  1873     } else {
  1874       list_count = humongous_dictionary()->total_count();
  1876     gclog_or_tty->print("ChunkManager::chunk_freelist_allocate: " PTR_FORMAT " chunk "
  1877                         PTR_FORMAT "  size " SIZE_FORMAT " count " SIZE_FORMAT " ",
  1878                         this, chunk, chunk->word_size(), list_count);
  1879     locked_print_free_chunks(gclog_or_tty);
  1882   return chunk;
  1885 void ChunkManager::print_on(outputStream* out) const {
  1886   if (PrintFLSStatistics != 0) {
  1887     const_cast<ChunkManager *>(this)->humongous_dictionary()->report_statistics();
  1891 // SpaceManager methods
  1893 size_t SpaceManager::adjust_initial_chunk_size(size_t requested, bool is_class_space) {
  1894   size_t chunk_sizes[] = {
  1895       specialized_chunk_size(is_class_space),
  1896       small_chunk_size(is_class_space),
  1897       medium_chunk_size(is_class_space)
  1898   };
  1900   // Adjust up to one of the fixed chunk sizes ...
  1901   for (size_t i = 0; i < ARRAY_SIZE(chunk_sizes); i++) {
  1902     if (requested <= chunk_sizes[i]) {
  1903       return chunk_sizes[i];
  1907   // ... or return the size as a humongous chunk.
  1908   return requested;
  1911 size_t SpaceManager::adjust_initial_chunk_size(size_t requested) const {
  1912   return adjust_initial_chunk_size(requested, is_class());
  1915 size_t SpaceManager::get_initial_chunk_size(Metaspace::MetaspaceType type) const {
  1916   size_t requested;
  1918   if (is_class()) {
  1919     switch (type) {
  1920     case Metaspace::BootMetaspaceType:       requested = Metaspace::first_class_chunk_word_size(); break;
  1921     case Metaspace::ROMetaspaceType:         requested = ClassSpecializedChunk; break;
  1922     case Metaspace::ReadWriteMetaspaceType:  requested = ClassSpecializedChunk; break;
  1923     case Metaspace::AnonymousMetaspaceType:  requested = ClassSpecializedChunk; break;
  1924     case Metaspace::ReflectionMetaspaceType: requested = ClassSpecializedChunk; break;
  1925     default:                                 requested = ClassSmallChunk; break;
  1927   } else {
  1928     switch (type) {
  1929     case Metaspace::BootMetaspaceType:       requested = Metaspace::first_chunk_word_size(); break;
  1930     case Metaspace::ROMetaspaceType:         requested = SharedReadOnlySize / wordSize; break;
  1931     case Metaspace::ReadWriteMetaspaceType:  requested = SharedReadWriteSize / wordSize; break;
  1932     case Metaspace::AnonymousMetaspaceType:  requested = SpecializedChunk; break;
  1933     case Metaspace::ReflectionMetaspaceType: requested = SpecializedChunk; break;
  1934     default:                                 requested = SmallChunk; break;
  1938   // Adjust to one of the fixed chunk sizes (unless humongous)
  1939   const size_t adjusted = adjust_initial_chunk_size(requested);
  1941   assert(adjusted != 0, err_msg("Incorrect initial chunk size. Requested: "
  1942          SIZE_FORMAT " adjusted: " SIZE_FORMAT, requested, adjusted));
  1944   return adjusted;
  1947 size_t SpaceManager::sum_free_in_chunks_in_use() const {
  1948   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1949   size_t free = 0;
  1950   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1951     Metachunk* chunk = chunks_in_use(i);
  1952     while (chunk != NULL) {
  1953       free += chunk->free_word_size();
  1954       chunk = chunk->next();
  1957   return free;
  1960 size_t SpaceManager::sum_waste_in_chunks_in_use() const {
  1961   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1962   size_t result = 0;
  1963   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1964    result += sum_waste_in_chunks_in_use(i);
  1967   return result;
  1970 size_t SpaceManager::sum_waste_in_chunks_in_use(ChunkIndex index) const {
  1971   size_t result = 0;
  1972   Metachunk* chunk = chunks_in_use(index);
  1973   // Count the free space in all the chunk but not the
  1974   // current chunk from which allocations are still being done.
  1975   while (chunk != NULL) {
  1976     if (chunk != current_chunk()) {
  1977       result += chunk->free_word_size();
  1979     chunk = chunk->next();
  1981   return result;
  1984 size_t SpaceManager::sum_capacity_in_chunks_in_use() const {
  1985   // For CMS use "allocated_chunks_words()" which does not need the
  1986   // Metaspace lock.  For the other collectors sum over the
  1987   // lists.  Use both methods as a check that "allocated_chunks_words()"
  1988   // is correct.  That is, sum_capacity_in_chunks() is too expensive
  1989   // to use in the product and allocated_chunks_words() should be used
  1990   // but allow for  checking that allocated_chunks_words() returns the same
  1991   // value as sum_capacity_in_chunks_in_use() which is the definitive
  1992   // answer.
  1993   if (UseConcMarkSweepGC) {
  1994     return allocated_chunks_words();
  1995   } else {
  1996     MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1997     size_t sum = 0;
  1998     for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1999       Metachunk* chunk = chunks_in_use(i);
  2000       while (chunk != NULL) {
  2001         sum += chunk->word_size();
  2002         chunk = chunk->next();
  2005   return sum;
  2009 size_t SpaceManager::sum_count_in_chunks_in_use() {
  2010   size_t count = 0;
  2011   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2012     count = count + sum_count_in_chunks_in_use(i);
  2015   return count;
  2018 size_t SpaceManager::sum_count_in_chunks_in_use(ChunkIndex i) {
  2019   size_t count = 0;
  2020   Metachunk* chunk = chunks_in_use(i);
  2021   while (chunk != NULL) {
  2022     count++;
  2023     chunk = chunk->next();
  2025   return count;
  2029 size_t SpaceManager::sum_used_in_chunks_in_use() const {
  2030   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  2031   size_t used = 0;
  2032   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2033     Metachunk* chunk = chunks_in_use(i);
  2034     while (chunk != NULL) {
  2035       used += chunk->used_word_size();
  2036       chunk = chunk->next();
  2039   return used;
  2042 void SpaceManager::locked_print_chunks_in_use_on(outputStream* st) const {
  2044   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2045     Metachunk* chunk = chunks_in_use(i);
  2046     st->print("SpaceManager: %s " PTR_FORMAT,
  2047                  chunk_size_name(i), chunk);
  2048     if (chunk != NULL) {
  2049       st->print_cr(" free " SIZE_FORMAT,
  2050                    chunk->free_word_size());
  2051     } else {
  2052       st->cr();
  2056   chunk_manager()->locked_print_free_chunks(st);
  2057   chunk_manager()->locked_print_sum_free_chunks(st);
  2060 size_t SpaceManager::calc_chunk_size(size_t word_size) {
  2062   // Decide between a small chunk and a medium chunk.  Up to
  2063   // _small_chunk_limit small chunks can be allocated but
  2064   // once a medium chunk has been allocated, no more small
  2065   // chunks will be allocated.
  2066   size_t chunk_word_size;
  2067   if (chunks_in_use(MediumIndex) == NULL &&
  2068       sum_count_in_chunks_in_use(SmallIndex) < _small_chunk_limit) {
  2069     chunk_word_size = (size_t) small_chunk_size();
  2070     if (word_size + Metachunk::overhead() > small_chunk_size()) {
  2071       chunk_word_size = medium_chunk_size();
  2073   } else {
  2074     chunk_word_size = medium_chunk_size();
  2077   // Might still need a humongous chunk.  Enforce
  2078   // humongous allocations sizes to be aligned up to
  2079   // the smallest chunk size.
  2080   size_t if_humongous_sized_chunk =
  2081     align_size_up(word_size + Metachunk::overhead(),
  2082                   smallest_chunk_size());
  2083   chunk_word_size =
  2084     MAX2((size_t) chunk_word_size, if_humongous_sized_chunk);
  2086   assert(!SpaceManager::is_humongous(word_size) ||
  2087          chunk_word_size == if_humongous_sized_chunk,
  2088          err_msg("Size calculation is wrong, word_size " SIZE_FORMAT
  2089                  " chunk_word_size " SIZE_FORMAT,
  2090                  word_size, chunk_word_size));
  2091   if (TraceMetadataHumongousAllocation &&
  2092       SpaceManager::is_humongous(word_size)) {
  2093     gclog_or_tty->print_cr("Metadata humongous allocation:");
  2094     gclog_or_tty->print_cr("  word_size " PTR_FORMAT, word_size);
  2095     gclog_or_tty->print_cr("  chunk_word_size " PTR_FORMAT,
  2096                            chunk_word_size);
  2097     gclog_or_tty->print_cr("    chunk overhead " PTR_FORMAT,
  2098                            Metachunk::overhead());
  2100   return chunk_word_size;
  2103 void SpaceManager::track_metaspace_memory_usage() {
  2104   if (is_init_completed()) {
  2105     if (is_class()) {
  2106       MemoryService::track_compressed_class_memory_usage();
  2108     MemoryService::track_metaspace_memory_usage();
  2112 MetaWord* SpaceManager::grow_and_allocate(size_t word_size) {
  2113   assert(vs_list()->current_virtual_space() != NULL,
  2114          "Should have been set");
  2115   assert(current_chunk() == NULL ||
  2116          current_chunk()->allocate(word_size) == NULL,
  2117          "Don't need to expand");
  2118   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  2120   if (TraceMetadataChunkAllocation && Verbose) {
  2121     size_t words_left = 0;
  2122     size_t words_used = 0;
  2123     if (current_chunk() != NULL) {
  2124       words_left = current_chunk()->free_word_size();
  2125       words_used = current_chunk()->used_word_size();
  2127     gclog_or_tty->print_cr("SpaceManager::grow_and_allocate for " SIZE_FORMAT
  2128                            " words " SIZE_FORMAT " words used " SIZE_FORMAT
  2129                            " words left",
  2130                             word_size, words_used, words_left);
  2133   // Get another chunk out of the virtual space
  2134   size_t chunk_word_size = calc_chunk_size(word_size);
  2135   Metachunk* next = get_new_chunk(chunk_word_size);
  2137   MetaWord* mem = NULL;
  2139   // If a chunk was available, add it to the in-use chunk list
  2140   // and do an allocation from it.
  2141   if (next != NULL) {
  2142     // Add to this manager's list of chunks in use.
  2143     add_chunk(next, false);
  2144     mem = next->allocate(word_size);
  2147   // Track metaspace memory usage statistic.
  2148   track_metaspace_memory_usage();
  2150   return mem;
  2153 void SpaceManager::print_on(outputStream* st) const {
  2155   for (ChunkIndex i = ZeroIndex;
  2156        i < NumberOfInUseLists ;
  2157        i = next_chunk_index(i) ) {
  2158     st->print_cr("  chunks_in_use " PTR_FORMAT " chunk size " PTR_FORMAT,
  2159                  chunks_in_use(i),
  2160                  chunks_in_use(i) == NULL ? 0 : chunks_in_use(i)->word_size());
  2162   st->print_cr("    waste:  Small " SIZE_FORMAT " Medium " SIZE_FORMAT
  2163                " Humongous " SIZE_FORMAT,
  2164                sum_waste_in_chunks_in_use(SmallIndex),
  2165                sum_waste_in_chunks_in_use(MediumIndex),
  2166                sum_waste_in_chunks_in_use(HumongousIndex));
  2167   // block free lists
  2168   if (block_freelists() != NULL) {
  2169     st->print_cr("total in block free lists " SIZE_FORMAT,
  2170       block_freelists()->total_size());
  2174 SpaceManager::SpaceManager(Metaspace::MetadataType mdtype,
  2175                            Mutex* lock) :
  2176   _mdtype(mdtype),
  2177   _allocated_blocks_words(0),
  2178   _allocated_chunks_words(0),
  2179   _allocated_chunks_count(0),
  2180   _lock(lock)
  2182   initialize();
  2185 void SpaceManager::inc_size_metrics(size_t words) {
  2186   assert_lock_strong(SpaceManager::expand_lock());
  2187   // Total of allocated Metachunks and allocated Metachunks count
  2188   // for each SpaceManager
  2189   _allocated_chunks_words = _allocated_chunks_words + words;
  2190   _allocated_chunks_count++;
  2191   // Global total of capacity in allocated Metachunks
  2192   MetaspaceAux::inc_capacity(mdtype(), words);
  2193   // Global total of allocated Metablocks.
  2194   // used_words_slow() includes the overhead in each
  2195   // Metachunk so include it in the used when the
  2196   // Metachunk is first added (so only added once per
  2197   // Metachunk).
  2198   MetaspaceAux::inc_used(mdtype(), Metachunk::overhead());
  2201 void SpaceManager::inc_used_metrics(size_t words) {
  2202   // Add to the per SpaceManager total
  2203   Atomic::add_ptr(words, &_allocated_blocks_words);
  2204   // Add to the global total
  2205   MetaspaceAux::inc_used(mdtype(), words);
  2208 void SpaceManager::dec_total_from_size_metrics() {
  2209   MetaspaceAux::dec_capacity(mdtype(), allocated_chunks_words());
  2210   MetaspaceAux::dec_used(mdtype(), allocated_blocks_words());
  2211   // Also deduct the overhead per Metachunk
  2212   MetaspaceAux::dec_used(mdtype(), allocated_chunks_count() * Metachunk::overhead());
  2215 void SpaceManager::initialize() {
  2216   Metadebug::init_allocation_fail_alot_count();
  2217   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2218     _chunks_in_use[i] = NULL;
  2220   _current_chunk = NULL;
  2221   if (TraceMetadataChunkAllocation && Verbose) {
  2222     gclog_or_tty->print_cr("SpaceManager(): " PTR_FORMAT, this);
  2226 void ChunkManager::return_chunks(ChunkIndex index, Metachunk* chunks) {
  2227   if (chunks == NULL) {
  2228     return;
  2230   ChunkList* list = free_chunks(index);
  2231   assert(list->size() == chunks->word_size(), "Mismatch in chunk sizes");
  2232   assert_lock_strong(SpaceManager::expand_lock());
  2233   Metachunk* cur = chunks;
  2235   // This returns chunks one at a time.  If a new
  2236   // class List can be created that is a base class
  2237   // of FreeList then something like FreeList::prepend()
  2238   // can be used in place of this loop
  2239   while (cur != NULL) {
  2240     assert(cur->container() != NULL, "Container should have been set");
  2241     cur->container()->dec_container_count();
  2242     // Capture the next link before it is changed
  2243     // by the call to return_chunk_at_head();
  2244     Metachunk* next = cur->next();
  2245     DEBUG_ONLY(cur->set_is_tagged_free(true);)
  2246     list->return_chunk_at_head(cur);
  2247     cur = next;
  2251 SpaceManager::~SpaceManager() {
  2252   // This call this->_lock which can't be done while holding expand_lock()
  2253   assert(sum_capacity_in_chunks_in_use() == allocated_chunks_words(),
  2254     err_msg("sum_capacity_in_chunks_in_use() " SIZE_FORMAT
  2255             " allocated_chunks_words() " SIZE_FORMAT,
  2256             sum_capacity_in_chunks_in_use(), allocated_chunks_words()));
  2258   MutexLockerEx fcl(SpaceManager::expand_lock(),
  2259                     Mutex::_no_safepoint_check_flag);
  2261   chunk_manager()->slow_locked_verify();
  2263   dec_total_from_size_metrics();
  2265   if (TraceMetadataChunkAllocation && Verbose) {
  2266     gclog_or_tty->print_cr("~SpaceManager(): " PTR_FORMAT, this);
  2267     locked_print_chunks_in_use_on(gclog_or_tty);
  2270   // Do not mangle freed Metachunks.  The chunk size inside Metachunks
  2271   // is during the freeing of a VirtualSpaceNodes.
  2273   // Have to update before the chunks_in_use lists are emptied
  2274   // below.
  2275   chunk_manager()->inc_free_chunks_total(allocated_chunks_words(),
  2276                                          sum_count_in_chunks_in_use());
  2278   // Add all the chunks in use by this space manager
  2279   // to the global list of free chunks.
  2281   // Follow each list of chunks-in-use and add them to the
  2282   // free lists.  Each list is NULL terminated.
  2284   for (ChunkIndex i = ZeroIndex; i < HumongousIndex; i = next_chunk_index(i)) {
  2285     if (TraceMetadataChunkAllocation && Verbose) {
  2286       gclog_or_tty->print_cr("returned %d %s chunks to freelist",
  2287                              sum_count_in_chunks_in_use(i),
  2288                              chunk_size_name(i));
  2290     Metachunk* chunks = chunks_in_use(i);
  2291     chunk_manager()->return_chunks(i, chunks);
  2292     set_chunks_in_use(i, NULL);
  2293     if (TraceMetadataChunkAllocation && Verbose) {
  2294       gclog_or_tty->print_cr("updated freelist count %d %s",
  2295                              chunk_manager()->free_chunks(i)->count(),
  2296                              chunk_size_name(i));
  2298     assert(i != HumongousIndex, "Humongous chunks are handled explicitly later");
  2301   // The medium chunk case may be optimized by passing the head and
  2302   // tail of the medium chunk list to add_at_head().  The tail is often
  2303   // the current chunk but there are probably exceptions.
  2305   // Humongous chunks
  2306   if (TraceMetadataChunkAllocation && Verbose) {
  2307     gclog_or_tty->print_cr("returned %d %s humongous chunks to dictionary",
  2308                             sum_count_in_chunks_in_use(HumongousIndex),
  2309                             chunk_size_name(HumongousIndex));
  2310     gclog_or_tty->print("Humongous chunk dictionary: ");
  2312   // Humongous chunks are never the current chunk.
  2313   Metachunk* humongous_chunks = chunks_in_use(HumongousIndex);
  2315   while (humongous_chunks != NULL) {
  2316 #ifdef ASSERT
  2317     humongous_chunks->set_is_tagged_free(true);
  2318 #endif
  2319     if (TraceMetadataChunkAllocation && Verbose) {
  2320       gclog_or_tty->print(PTR_FORMAT " (" SIZE_FORMAT ") ",
  2321                           humongous_chunks,
  2322                           humongous_chunks->word_size());
  2324     assert(humongous_chunks->word_size() == (size_t)
  2325            align_size_up(humongous_chunks->word_size(),
  2326                              smallest_chunk_size()),
  2327            err_msg("Humongous chunk size is wrong: word size " SIZE_FORMAT
  2328                    " granularity %d",
  2329                    humongous_chunks->word_size(), smallest_chunk_size()));
  2330     Metachunk* next_humongous_chunks = humongous_chunks->next();
  2331     humongous_chunks->container()->dec_container_count();
  2332     chunk_manager()->humongous_dictionary()->return_chunk(humongous_chunks);
  2333     humongous_chunks = next_humongous_chunks;
  2335   if (TraceMetadataChunkAllocation && Verbose) {
  2336     gclog_or_tty->cr();
  2337     gclog_or_tty->print_cr("updated dictionary count %d %s",
  2338                      chunk_manager()->humongous_dictionary()->total_count(),
  2339                      chunk_size_name(HumongousIndex));
  2341   chunk_manager()->slow_locked_verify();
  2344 const char* SpaceManager::chunk_size_name(ChunkIndex index) const {
  2345   switch (index) {
  2346     case SpecializedIndex:
  2347       return "Specialized";
  2348     case SmallIndex:
  2349       return "Small";
  2350     case MediumIndex:
  2351       return "Medium";
  2352     case HumongousIndex:
  2353       return "Humongous";
  2354     default:
  2355       return NULL;
  2359 ChunkIndex ChunkManager::list_index(size_t size) {
  2360   switch (size) {
  2361     case SpecializedChunk:
  2362       assert(SpecializedChunk == ClassSpecializedChunk,
  2363              "Need branch for ClassSpecializedChunk");
  2364       return SpecializedIndex;
  2365     case SmallChunk:
  2366     case ClassSmallChunk:
  2367       return SmallIndex;
  2368     case MediumChunk:
  2369     case ClassMediumChunk:
  2370       return MediumIndex;
  2371     default:
  2372       assert(size > MediumChunk || size > ClassMediumChunk,
  2373              "Not a humongous chunk");
  2374       return HumongousIndex;
  2378 void SpaceManager::deallocate(MetaWord* p, size_t word_size) {
  2379   assert_lock_strong(_lock);
  2380   size_t raw_word_size = get_raw_word_size(word_size);
  2381   size_t min_size = TreeChunk<Metablock, FreeList<Metablock> >::min_size();
  2382   assert(raw_word_size >= min_size,
  2383          err_msg("Should not deallocate dark matter " SIZE_FORMAT "<" SIZE_FORMAT, word_size, min_size));
  2384   block_freelists()->return_block(p, raw_word_size);
  2387 // Adds a chunk to the list of chunks in use.
  2388 void SpaceManager::add_chunk(Metachunk* new_chunk, bool make_current) {
  2390   assert(new_chunk != NULL, "Should not be NULL");
  2391   assert(new_chunk->next() == NULL, "Should not be on a list");
  2393   new_chunk->reset_empty();
  2395   // Find the correct list and and set the current
  2396   // chunk for that list.
  2397   ChunkIndex index = ChunkManager::list_index(new_chunk->word_size());
  2399   if (index != HumongousIndex) {
  2400     retire_current_chunk();
  2401     set_current_chunk(new_chunk);
  2402     new_chunk->set_next(chunks_in_use(index));
  2403     set_chunks_in_use(index, new_chunk);
  2404   } else {
  2405     // For null class loader data and DumpSharedSpaces, the first chunk isn't
  2406     // small, so small will be null.  Link this first chunk as the current
  2407     // chunk.
  2408     if (make_current) {
  2409       // Set as the current chunk but otherwise treat as a humongous chunk.
  2410       set_current_chunk(new_chunk);
  2412     // Link at head.  The _current_chunk only points to a humongous chunk for
  2413     // the null class loader metaspace (class and data virtual space managers)
  2414     // any humongous chunks so will not point to the tail
  2415     // of the humongous chunks list.
  2416     new_chunk->set_next(chunks_in_use(HumongousIndex));
  2417     set_chunks_in_use(HumongousIndex, new_chunk);
  2419     assert(new_chunk->word_size() > medium_chunk_size(), "List inconsistency");
  2422   // Add to the running sum of capacity
  2423   inc_size_metrics(new_chunk->word_size());
  2425   assert(new_chunk->is_empty(), "Not ready for reuse");
  2426   if (TraceMetadataChunkAllocation && Verbose) {
  2427     gclog_or_tty->print("SpaceManager::add_chunk: %d) ",
  2428                         sum_count_in_chunks_in_use());
  2429     new_chunk->print_on(gclog_or_tty);
  2430     chunk_manager()->locked_print_free_chunks(gclog_or_tty);
  2434 void SpaceManager::retire_current_chunk() {
  2435   if (current_chunk() != NULL) {
  2436     size_t remaining_words = current_chunk()->free_word_size();
  2437     if (remaining_words >= TreeChunk<Metablock, FreeList<Metablock> >::min_size()) {
  2438       block_freelists()->return_block(current_chunk()->allocate(remaining_words), remaining_words);
  2439       inc_used_metrics(remaining_words);
  2444 Metachunk* SpaceManager::get_new_chunk(size_t chunk_word_size) {
  2445   // Get a chunk from the chunk freelist
  2446   Metachunk* next = chunk_manager()->chunk_freelist_allocate(chunk_word_size);
  2448   if (next == NULL) {
  2449     next = vs_list()->get_new_chunk(chunk_word_size,
  2450                                     medium_chunk_bunch());
  2453   if (TraceMetadataHumongousAllocation && next != NULL &&
  2454       SpaceManager::is_humongous(next->word_size())) {
  2455     gclog_or_tty->print_cr("  new humongous chunk word size "
  2456                            PTR_FORMAT, next->word_size());
  2459   return next;
  2462 MetaWord* SpaceManager::allocate(size_t word_size) {
  2463   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  2465   size_t raw_word_size = get_raw_word_size(word_size);
  2466   BlockFreelist* fl =  block_freelists();
  2467   MetaWord* p = NULL;
  2468   // Allocation from the dictionary is expensive in the sense that
  2469   // the dictionary has to be searched for a size.  Don't allocate
  2470   // from the dictionary until it starts to get fat.  Is this
  2471   // a reasonable policy?  Maybe an skinny dictionary is fast enough
  2472   // for allocations.  Do some profiling.  JJJ
  2473   if (fl->total_size() > allocation_from_dictionary_limit) {
  2474     p = fl->get_block(raw_word_size);
  2476   if (p == NULL) {
  2477     p = allocate_work(raw_word_size);
  2480   return p;
  2483 // Returns the address of spaced allocated for "word_size".
  2484 // This methods does not know about blocks (Metablocks)
  2485 MetaWord* SpaceManager::allocate_work(size_t word_size) {
  2486   assert_lock_strong(_lock);
  2487 #ifdef ASSERT
  2488   if (Metadebug::test_metadata_failure()) {
  2489     return NULL;
  2491 #endif
  2492   // Is there space in the current chunk?
  2493   MetaWord* result = NULL;
  2495   // For DumpSharedSpaces, only allocate out of the current chunk which is
  2496   // never null because we gave it the size we wanted.   Caller reports out
  2497   // of memory if this returns null.
  2498   if (DumpSharedSpaces) {
  2499     assert(current_chunk() != NULL, "should never happen");
  2500     inc_used_metrics(word_size);
  2501     return current_chunk()->allocate(word_size); // caller handles null result
  2504   if (current_chunk() != NULL) {
  2505     result = current_chunk()->allocate(word_size);
  2508   if (result == NULL) {
  2509     result = grow_and_allocate(word_size);
  2512   if (result != NULL) {
  2513     inc_used_metrics(word_size);
  2514     assert(result != (MetaWord*) chunks_in_use(MediumIndex),
  2515            "Head of the list is being allocated");
  2518   return result;
  2521 void SpaceManager::verify() {
  2522   // If there are blocks in the dictionary, then
  2523   // verfication of chunks does not work since
  2524   // being in the dictionary alters a chunk.
  2525   if (block_freelists()->total_size() == 0) {
  2526     for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2527       Metachunk* curr = chunks_in_use(i);
  2528       while (curr != NULL) {
  2529         curr->verify();
  2530         verify_chunk_size(curr);
  2531         curr = curr->next();
  2537 void SpaceManager::verify_chunk_size(Metachunk* chunk) {
  2538   assert(is_humongous(chunk->word_size()) ||
  2539          chunk->word_size() == medium_chunk_size() ||
  2540          chunk->word_size() == small_chunk_size() ||
  2541          chunk->word_size() == specialized_chunk_size(),
  2542          "Chunk size is wrong");
  2543   return;
  2546 #ifdef ASSERT
  2547 void SpaceManager::verify_allocated_blocks_words() {
  2548   // Verification is only guaranteed at a safepoint.
  2549   assert(SafepointSynchronize::is_at_safepoint() || !Universe::is_fully_initialized(),
  2550     "Verification can fail if the applications is running");
  2551   assert(allocated_blocks_words() == sum_used_in_chunks_in_use(),
  2552     err_msg("allocation total is not consistent " SIZE_FORMAT
  2553             " vs " SIZE_FORMAT,
  2554             allocated_blocks_words(), sum_used_in_chunks_in_use()));
  2557 #endif
  2559 void SpaceManager::dump(outputStream* const out) const {
  2560   size_t curr_total = 0;
  2561   size_t waste = 0;
  2562   uint i = 0;
  2563   size_t used = 0;
  2564   size_t capacity = 0;
  2566   // Add up statistics for all chunks in this SpaceManager.
  2567   for (ChunkIndex index = ZeroIndex;
  2568        index < NumberOfInUseLists;
  2569        index = next_chunk_index(index)) {
  2570     for (Metachunk* curr = chunks_in_use(index);
  2571          curr != NULL;
  2572          curr = curr->next()) {
  2573       out->print("%d) ", i++);
  2574       curr->print_on(out);
  2575       curr_total += curr->word_size();
  2576       used += curr->used_word_size();
  2577       capacity += curr->word_size();
  2578       waste += curr->free_word_size() + curr->overhead();;
  2582   if (TraceMetadataChunkAllocation && Verbose) {
  2583     block_freelists()->print_on(out);
  2586   size_t free = current_chunk() == NULL ? 0 : current_chunk()->free_word_size();
  2587   // Free space isn't wasted.
  2588   waste -= free;
  2590   out->print_cr("total of all chunks "  SIZE_FORMAT " used " SIZE_FORMAT
  2591                 " free " SIZE_FORMAT " capacity " SIZE_FORMAT
  2592                 " waste " SIZE_FORMAT, curr_total, used, free, capacity, waste);
  2595 #ifndef PRODUCT
  2596 void SpaceManager::mangle_freed_chunks() {
  2597   for (ChunkIndex index = ZeroIndex;
  2598        index < NumberOfInUseLists;
  2599        index = next_chunk_index(index)) {
  2600     for (Metachunk* curr = chunks_in_use(index);
  2601          curr != NULL;
  2602          curr = curr->next()) {
  2603       curr->mangle();
  2607 #endif // PRODUCT
  2609 // MetaspaceAux
  2612 size_t MetaspaceAux::_capacity_words[] = {0, 0};
  2613 size_t MetaspaceAux::_used_words[] = {0, 0};
  2615 size_t MetaspaceAux::free_bytes(Metaspace::MetadataType mdtype) {
  2616   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
  2617   return list == NULL ? 0 : list->free_bytes();
  2620 size_t MetaspaceAux::free_bytes() {
  2621   return free_bytes(Metaspace::ClassType) + free_bytes(Metaspace::NonClassType);
  2624 void MetaspaceAux::dec_capacity(Metaspace::MetadataType mdtype, size_t words) {
  2625   assert_lock_strong(SpaceManager::expand_lock());
  2626   assert(words <= capacity_words(mdtype),
  2627     err_msg("About to decrement below 0: words " SIZE_FORMAT
  2628             " is greater than _capacity_words[%u] " SIZE_FORMAT,
  2629             words, mdtype, capacity_words(mdtype)));
  2630   _capacity_words[mdtype] -= words;
  2633 void MetaspaceAux::inc_capacity(Metaspace::MetadataType mdtype, size_t words) {
  2634   assert_lock_strong(SpaceManager::expand_lock());
  2635   // Needs to be atomic
  2636   _capacity_words[mdtype] += words;
  2639 void MetaspaceAux::dec_used(Metaspace::MetadataType mdtype, size_t words) {
  2640   assert(words <= used_words(mdtype),
  2641     err_msg("About to decrement below 0: words " SIZE_FORMAT
  2642             " is greater than _used_words[%u] " SIZE_FORMAT,
  2643             words, mdtype, used_words(mdtype)));
  2644   // For CMS deallocation of the Metaspaces occurs during the
  2645   // sweep which is a concurrent phase.  Protection by the expand_lock()
  2646   // is not enough since allocation is on a per Metaspace basis
  2647   // and protected by the Metaspace lock.
  2648   jlong minus_words = (jlong) - (jlong) words;
  2649   Atomic::add_ptr(minus_words, &_used_words[mdtype]);
  2652 void MetaspaceAux::inc_used(Metaspace::MetadataType mdtype, size_t words) {
  2653   // _used_words tracks allocations for
  2654   // each piece of metadata.  Those allocations are
  2655   // generally done concurrently by different application
  2656   // threads so must be done atomically.
  2657   Atomic::add_ptr(words, &_used_words[mdtype]);
  2660 size_t MetaspaceAux::used_bytes_slow(Metaspace::MetadataType mdtype) {
  2661   size_t used = 0;
  2662   ClassLoaderDataGraphMetaspaceIterator iter;
  2663   while (iter.repeat()) {
  2664     Metaspace* msp = iter.get_next();
  2665     // Sum allocated_blocks_words for each metaspace
  2666     if (msp != NULL) {
  2667       used += msp->used_words_slow(mdtype);
  2670   return used * BytesPerWord;
  2673 size_t MetaspaceAux::free_bytes_slow(Metaspace::MetadataType mdtype) {
  2674   size_t free = 0;
  2675   ClassLoaderDataGraphMetaspaceIterator iter;
  2676   while (iter.repeat()) {
  2677     Metaspace* msp = iter.get_next();
  2678     if (msp != NULL) {
  2679       free += msp->free_words_slow(mdtype);
  2682   return free * BytesPerWord;
  2685 size_t MetaspaceAux::capacity_bytes_slow(Metaspace::MetadataType mdtype) {
  2686   if ((mdtype == Metaspace::ClassType) && !Metaspace::using_class_space()) {
  2687     return 0;
  2689   // Don't count the space in the freelists.  That space will be
  2690   // added to the capacity calculation as needed.
  2691   size_t capacity = 0;
  2692   ClassLoaderDataGraphMetaspaceIterator iter;
  2693   while (iter.repeat()) {
  2694     Metaspace* msp = iter.get_next();
  2695     if (msp != NULL) {
  2696       capacity += msp->capacity_words_slow(mdtype);
  2699   return capacity * BytesPerWord;
  2702 size_t MetaspaceAux::capacity_bytes_slow() {
  2703 #ifdef PRODUCT
  2704   // Use capacity_bytes() in PRODUCT instead of this function.
  2705   guarantee(false, "Should not call capacity_bytes_slow() in the PRODUCT");
  2706 #endif
  2707   size_t class_capacity = capacity_bytes_slow(Metaspace::ClassType);
  2708   size_t non_class_capacity = capacity_bytes_slow(Metaspace::NonClassType);
  2709   assert(capacity_bytes() == class_capacity + non_class_capacity,
  2710       err_msg("bad accounting: capacity_bytes() " SIZE_FORMAT
  2711         " class_capacity + non_class_capacity " SIZE_FORMAT
  2712         " class_capacity " SIZE_FORMAT " non_class_capacity " SIZE_FORMAT,
  2713         capacity_bytes(), class_capacity + non_class_capacity,
  2714         class_capacity, non_class_capacity));
  2716   return class_capacity + non_class_capacity;
  2719 size_t MetaspaceAux::reserved_bytes(Metaspace::MetadataType mdtype) {
  2720   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
  2721   return list == NULL ? 0 : list->reserved_bytes();
  2724 size_t MetaspaceAux::committed_bytes(Metaspace::MetadataType mdtype) {
  2725   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
  2726   return list == NULL ? 0 : list->committed_bytes();
  2729 size_t MetaspaceAux::min_chunk_size_words() { return Metaspace::first_chunk_word_size(); }
  2731 size_t MetaspaceAux::free_chunks_total_words(Metaspace::MetadataType mdtype) {
  2732   ChunkManager* chunk_manager = Metaspace::get_chunk_manager(mdtype);
  2733   if (chunk_manager == NULL) {
  2734     return 0;
  2736   chunk_manager->slow_verify();
  2737   return chunk_manager->free_chunks_total_words();
  2740 size_t MetaspaceAux::free_chunks_total_bytes(Metaspace::MetadataType mdtype) {
  2741   return free_chunks_total_words(mdtype) * BytesPerWord;
  2744 size_t MetaspaceAux::free_chunks_total_words() {
  2745   return free_chunks_total_words(Metaspace::ClassType) +
  2746          free_chunks_total_words(Metaspace::NonClassType);
  2749 size_t MetaspaceAux::free_chunks_total_bytes() {
  2750   return free_chunks_total_words() * BytesPerWord;
  2753 bool MetaspaceAux::has_chunk_free_list(Metaspace::MetadataType mdtype) {
  2754   return Metaspace::get_chunk_manager(mdtype) != NULL;
  2757 MetaspaceChunkFreeListSummary MetaspaceAux::chunk_free_list_summary(Metaspace::MetadataType mdtype) {
  2758   if (!has_chunk_free_list(mdtype)) {
  2759     return MetaspaceChunkFreeListSummary();
  2762   const ChunkManager* cm = Metaspace::get_chunk_manager(mdtype);
  2763   return cm->chunk_free_list_summary();
  2766 void MetaspaceAux::print_metaspace_change(size_t prev_metadata_used) {
  2767   gclog_or_tty->print(", [Metaspace:");
  2768   if (PrintGCDetails && Verbose) {
  2769     gclog_or_tty->print(" "  SIZE_FORMAT
  2770                         "->" SIZE_FORMAT
  2771                         "("  SIZE_FORMAT ")",
  2772                         prev_metadata_used,
  2773                         used_bytes(),
  2774                         reserved_bytes());
  2775   } else {
  2776     gclog_or_tty->print(" "  SIZE_FORMAT "K"
  2777                         "->" SIZE_FORMAT "K"
  2778                         "("  SIZE_FORMAT "K)",
  2779                         prev_metadata_used/K,
  2780                         used_bytes()/K,
  2781                         reserved_bytes()/K);
  2784   gclog_or_tty->print("]");
  2787 // This is printed when PrintGCDetails
  2788 void MetaspaceAux::print_on(outputStream* out) {
  2789   Metaspace::MetadataType nct = Metaspace::NonClassType;
  2791   out->print_cr(" Metaspace       "
  2792                 "used "      SIZE_FORMAT "K, "
  2793                 "capacity "  SIZE_FORMAT "K, "
  2794                 "committed " SIZE_FORMAT "K, "
  2795                 "reserved "  SIZE_FORMAT "K",
  2796                 used_bytes()/K,
  2797                 capacity_bytes()/K,
  2798                 committed_bytes()/K,
  2799                 reserved_bytes()/K);
  2801   if (Metaspace::using_class_space()) {
  2802     Metaspace::MetadataType ct = Metaspace::ClassType;
  2803     out->print_cr("  class space    "
  2804                   "used "      SIZE_FORMAT "K, "
  2805                   "capacity "  SIZE_FORMAT "K, "
  2806                   "committed " SIZE_FORMAT "K, "
  2807                   "reserved "  SIZE_FORMAT "K",
  2808                   used_bytes(ct)/K,
  2809                   capacity_bytes(ct)/K,
  2810                   committed_bytes(ct)/K,
  2811                   reserved_bytes(ct)/K);
  2815 // Print information for class space and data space separately.
  2816 // This is almost the same as above.
  2817 void MetaspaceAux::print_on(outputStream* out, Metaspace::MetadataType mdtype) {
  2818   size_t free_chunks_capacity_bytes = free_chunks_total_bytes(mdtype);
  2819   size_t capacity_bytes = capacity_bytes_slow(mdtype);
  2820   size_t used_bytes = used_bytes_slow(mdtype);
  2821   size_t free_bytes = free_bytes_slow(mdtype);
  2822   size_t used_and_free = used_bytes + free_bytes +
  2823                            free_chunks_capacity_bytes;
  2824   out->print_cr("  Chunk accounting: used in chunks " SIZE_FORMAT
  2825              "K + unused in chunks " SIZE_FORMAT "K  + "
  2826              " capacity in free chunks " SIZE_FORMAT "K = " SIZE_FORMAT
  2827              "K  capacity in allocated chunks " SIZE_FORMAT "K",
  2828              used_bytes / K,
  2829              free_bytes / K,
  2830              free_chunks_capacity_bytes / K,
  2831              used_and_free / K,
  2832              capacity_bytes / K);
  2833   // Accounting can only be correct if we got the values during a safepoint
  2834   assert(!SafepointSynchronize::is_at_safepoint() || used_and_free == capacity_bytes, "Accounting is wrong");
  2837 // Print total fragmentation for class metaspaces
  2838 void MetaspaceAux::print_class_waste(outputStream* out) {
  2839   assert(Metaspace::using_class_space(), "class metaspace not used");
  2840   size_t cls_specialized_waste = 0, cls_small_waste = 0, cls_medium_waste = 0;
  2841   size_t cls_specialized_count = 0, cls_small_count = 0, cls_medium_count = 0, cls_humongous_count = 0;
  2842   ClassLoaderDataGraphMetaspaceIterator iter;
  2843   while (iter.repeat()) {
  2844     Metaspace* msp = iter.get_next();
  2845     if (msp != NULL) {
  2846       cls_specialized_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
  2847       cls_specialized_count += msp->class_vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
  2848       cls_small_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SmallIndex);
  2849       cls_small_count += msp->class_vsm()->sum_count_in_chunks_in_use(SmallIndex);
  2850       cls_medium_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(MediumIndex);
  2851       cls_medium_count += msp->class_vsm()->sum_count_in_chunks_in_use(MediumIndex);
  2852       cls_humongous_count += msp->class_vsm()->sum_count_in_chunks_in_use(HumongousIndex);
  2855   out->print_cr(" class: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
  2856                 SIZE_FORMAT " small(s) " SIZE_FORMAT ", "
  2857                 SIZE_FORMAT " medium(s) " SIZE_FORMAT ", "
  2858                 "large count " SIZE_FORMAT,
  2859                 cls_specialized_count, cls_specialized_waste,
  2860                 cls_small_count, cls_small_waste,
  2861                 cls_medium_count, cls_medium_waste, cls_humongous_count);
  2864 // Print total fragmentation for data and class metaspaces separately
  2865 void MetaspaceAux::print_waste(outputStream* out) {
  2866   size_t specialized_waste = 0, small_waste = 0, medium_waste = 0;
  2867   size_t specialized_count = 0, small_count = 0, medium_count = 0, humongous_count = 0;
  2869   ClassLoaderDataGraphMetaspaceIterator iter;
  2870   while (iter.repeat()) {
  2871     Metaspace* msp = iter.get_next();
  2872     if (msp != NULL) {
  2873       specialized_waste += msp->vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
  2874       specialized_count += msp->vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
  2875       small_waste += msp->vsm()->sum_waste_in_chunks_in_use(SmallIndex);
  2876       small_count += msp->vsm()->sum_count_in_chunks_in_use(SmallIndex);
  2877       medium_waste += msp->vsm()->sum_waste_in_chunks_in_use(MediumIndex);
  2878       medium_count += msp->vsm()->sum_count_in_chunks_in_use(MediumIndex);
  2879       humongous_count += msp->vsm()->sum_count_in_chunks_in_use(HumongousIndex);
  2882   out->print_cr("Total fragmentation waste (words) doesn't count free space");
  2883   out->print_cr("  data: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
  2884                         SIZE_FORMAT " small(s) " SIZE_FORMAT ", "
  2885                         SIZE_FORMAT " medium(s) " SIZE_FORMAT ", "
  2886                         "large count " SIZE_FORMAT,
  2887              specialized_count, specialized_waste, small_count,
  2888              small_waste, medium_count, medium_waste, humongous_count);
  2889   if (Metaspace::using_class_space()) {
  2890     print_class_waste(out);
  2894 // Dump global metaspace things from the end of ClassLoaderDataGraph
  2895 void MetaspaceAux::dump(outputStream* out) {
  2896   out->print_cr("All Metaspace:");
  2897   out->print("data space: "); print_on(out, Metaspace::NonClassType);
  2898   out->print("class space: "); print_on(out, Metaspace::ClassType);
  2899   print_waste(out);
  2902 void MetaspaceAux::verify_free_chunks() {
  2903   Metaspace::chunk_manager_metadata()->verify();
  2904   if (Metaspace::using_class_space()) {
  2905     Metaspace::chunk_manager_class()->verify();
  2909 void MetaspaceAux::verify_capacity() {
  2910 #ifdef ASSERT
  2911   size_t running_sum_capacity_bytes = capacity_bytes();
  2912   // For purposes of the running sum of capacity, verify against capacity
  2913   size_t capacity_in_use_bytes = capacity_bytes_slow();
  2914   assert(running_sum_capacity_bytes == capacity_in_use_bytes,
  2915     err_msg("capacity_words() * BytesPerWord " SIZE_FORMAT
  2916             " capacity_bytes_slow()" SIZE_FORMAT,
  2917             running_sum_capacity_bytes, capacity_in_use_bytes));
  2918   for (Metaspace::MetadataType i = Metaspace::ClassType;
  2919        i < Metaspace:: MetadataTypeCount;
  2920        i = (Metaspace::MetadataType)(i + 1)) {
  2921     size_t capacity_in_use_bytes = capacity_bytes_slow(i);
  2922     assert(capacity_bytes(i) == capacity_in_use_bytes,
  2923       err_msg("capacity_bytes(%u) " SIZE_FORMAT
  2924               " capacity_bytes_slow(%u)" SIZE_FORMAT,
  2925               i, capacity_bytes(i), i, capacity_in_use_bytes));
  2927 #endif
  2930 void MetaspaceAux::verify_used() {
  2931 #ifdef ASSERT
  2932   size_t running_sum_used_bytes = used_bytes();
  2933   // For purposes of the running sum of used, verify against used
  2934   size_t used_in_use_bytes = used_bytes_slow();
  2935   assert(used_bytes() == used_in_use_bytes,
  2936     err_msg("used_bytes() " SIZE_FORMAT
  2937             " used_bytes_slow()" SIZE_FORMAT,
  2938             used_bytes(), used_in_use_bytes));
  2939   for (Metaspace::MetadataType i = Metaspace::ClassType;
  2940        i < Metaspace:: MetadataTypeCount;
  2941        i = (Metaspace::MetadataType)(i + 1)) {
  2942     size_t used_in_use_bytes = used_bytes_slow(i);
  2943     assert(used_bytes(i) == used_in_use_bytes,
  2944       err_msg("used_bytes(%u) " SIZE_FORMAT
  2945               " used_bytes_slow(%u)" SIZE_FORMAT,
  2946               i, used_bytes(i), i, used_in_use_bytes));
  2948 #endif
  2951 void MetaspaceAux::verify_metrics() {
  2952   verify_capacity();
  2953   verify_used();
  2957 // Metaspace methods
  2959 size_t Metaspace::_first_chunk_word_size = 0;
  2960 size_t Metaspace::_first_class_chunk_word_size = 0;
  2962 size_t Metaspace::_commit_alignment = 0;
  2963 size_t Metaspace::_reserve_alignment = 0;
  2965 Metaspace::Metaspace(Mutex* lock, MetaspaceType type) {
  2966   initialize(lock, type);
  2969 Metaspace::~Metaspace() {
  2970   delete _vsm;
  2971   if (using_class_space()) {
  2972     delete _class_vsm;
  2976 VirtualSpaceList* Metaspace::_space_list = NULL;
  2977 VirtualSpaceList* Metaspace::_class_space_list = NULL;
  2979 ChunkManager* Metaspace::_chunk_manager_metadata = NULL;
  2980 ChunkManager* Metaspace::_chunk_manager_class = NULL;
  2982 #define VIRTUALSPACEMULTIPLIER 2
  2984 #ifdef _LP64
  2985 static const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
  2987 void Metaspace::set_narrow_klass_base_and_shift(address metaspace_base, address cds_base) {
  2988   // Figure out the narrow_klass_base and the narrow_klass_shift.  The
  2989   // narrow_klass_base is the lower of the metaspace base and the cds base
  2990   // (if cds is enabled).  The narrow_klass_shift depends on the distance
  2991   // between the lower base and higher address.
  2992   address lower_base;
  2993   address higher_address;
  2994 #if INCLUDE_CDS
  2995   if (UseSharedSpaces) {
  2996     higher_address = MAX2((address)(cds_base + FileMapInfo::shared_spaces_size()),
  2997                           (address)(metaspace_base + compressed_class_space_size()));
  2998     lower_base = MIN2(metaspace_base, cds_base);
  2999   } else
  3000 #endif
  3002     higher_address = metaspace_base + compressed_class_space_size();
  3003     lower_base = metaspace_base;
  3005     uint64_t klass_encoding_max = UnscaledClassSpaceMax << LogKlassAlignmentInBytes;
  3006     // If compressed class space fits in lower 32G, we don't need a base.
  3007     if (higher_address <= (address)klass_encoding_max) {
  3008       lower_base = 0; // effectively lower base is zero.
  3012   Universe::set_narrow_klass_base(lower_base);
  3014   if ((uint64_t)(higher_address - lower_base) <= UnscaledClassSpaceMax) {
  3015     Universe::set_narrow_klass_shift(0);
  3016   } else {
  3017     assert(!UseSharedSpaces, "Cannot shift with UseSharedSpaces");
  3018     Universe::set_narrow_klass_shift(LogKlassAlignmentInBytes);
  3022 #if INCLUDE_CDS
  3023 // Return TRUE if the specified metaspace_base and cds_base are close enough
  3024 // to work with compressed klass pointers.
  3025 bool Metaspace::can_use_cds_with_metaspace_addr(char* metaspace_base, address cds_base) {
  3026   assert(cds_base != 0 && UseSharedSpaces, "Only use with CDS");
  3027   assert(UseCompressedClassPointers, "Only use with CompressedKlassPtrs");
  3028   address lower_base = MIN2((address)metaspace_base, cds_base);
  3029   address higher_address = MAX2((address)(cds_base + FileMapInfo::shared_spaces_size()),
  3030                                 (address)(metaspace_base + compressed_class_space_size()));
  3031   return ((uint64_t)(higher_address - lower_base) <= UnscaledClassSpaceMax);
  3033 #endif
  3035 // Try to allocate the metaspace at the requested addr.
  3036 void Metaspace::allocate_metaspace_compressed_klass_ptrs(char* requested_addr, address cds_base) {
  3037   assert(using_class_space(), "called improperly");
  3038   assert(UseCompressedClassPointers, "Only use with CompressedKlassPtrs");
  3039   assert(compressed_class_space_size() < KlassEncodingMetaspaceMax,
  3040          "Metaspace size is too big");
  3041   assert_is_ptr_aligned(requested_addr, _reserve_alignment);
  3042   assert_is_ptr_aligned(cds_base, _reserve_alignment);
  3043   assert_is_size_aligned(compressed_class_space_size(), _reserve_alignment);
  3045   // Don't use large pages for the class space.
  3046   bool large_pages = false;
  3048   ReservedSpace metaspace_rs = ReservedSpace(compressed_class_space_size(),
  3049                                              _reserve_alignment,
  3050                                              large_pages,
  3051                                              requested_addr, 0);
  3052   if (!metaspace_rs.is_reserved()) {
  3053 #if INCLUDE_CDS
  3054     if (UseSharedSpaces) {
  3055       size_t increment = align_size_up(1*G, _reserve_alignment);
  3057       // Keep trying to allocate the metaspace, increasing the requested_addr
  3058       // by 1GB each time, until we reach an address that will no longer allow
  3059       // use of CDS with compressed klass pointers.
  3060       char *addr = requested_addr;
  3061       while (!metaspace_rs.is_reserved() && (addr + increment > addr) &&
  3062              can_use_cds_with_metaspace_addr(addr + increment, cds_base)) {
  3063         addr = addr + increment;
  3064         metaspace_rs = ReservedSpace(compressed_class_space_size(),
  3065                                      _reserve_alignment, large_pages, addr, 0);
  3068 #endif
  3069     // If no successful allocation then try to allocate the space anywhere.  If
  3070     // that fails then OOM doom.  At this point we cannot try allocating the
  3071     // metaspace as if UseCompressedClassPointers is off because too much
  3072     // initialization has happened that depends on UseCompressedClassPointers.
  3073     // So, UseCompressedClassPointers cannot be turned off at this point.
  3074     if (!metaspace_rs.is_reserved()) {
  3075       metaspace_rs = ReservedSpace(compressed_class_space_size(),
  3076                                    _reserve_alignment, large_pages);
  3077       if (!metaspace_rs.is_reserved()) {
  3078         vm_exit_during_initialization(err_msg("Could not allocate metaspace: %d bytes",
  3079                                               compressed_class_space_size()));
  3084   // If we got here then the metaspace got allocated.
  3085   MemTracker::record_virtual_memory_type((address)metaspace_rs.base(), mtClass);
  3087 #if INCLUDE_CDS
  3088   // Verify that we can use shared spaces.  Otherwise, turn off CDS.
  3089   if (UseSharedSpaces && !can_use_cds_with_metaspace_addr(metaspace_rs.base(), cds_base)) {
  3090     FileMapInfo::stop_sharing_and_unmap(
  3091         "Could not allocate metaspace at a compatible address");
  3093 #endif
  3094   set_narrow_klass_base_and_shift((address)metaspace_rs.base(),
  3095                                   UseSharedSpaces ? (address)cds_base : 0);
  3097   initialize_class_space(metaspace_rs);
  3099   if (PrintCompressedOopsMode || (PrintMiscellaneous && Verbose)) {
  3100     gclog_or_tty->print_cr("Narrow klass base: " PTR_FORMAT ", Narrow klass shift: " SIZE_FORMAT,
  3101                             Universe::narrow_klass_base(), Universe::narrow_klass_shift());
  3102     gclog_or_tty->print_cr("Compressed class space size: " SIZE_FORMAT " Address: " PTR_FORMAT " Req Addr: " PTR_FORMAT,
  3103                            compressed_class_space_size(), metaspace_rs.base(), requested_addr);
  3107 // For UseCompressedClassPointers the class space is reserved above the top of
  3108 // the Java heap.  The argument passed in is at the base of the compressed space.
  3109 void Metaspace::initialize_class_space(ReservedSpace rs) {
  3110   // The reserved space size may be bigger because of alignment, esp with UseLargePages
  3111   assert(rs.size() >= CompressedClassSpaceSize,
  3112          err_msg(SIZE_FORMAT " != " UINTX_FORMAT, rs.size(), CompressedClassSpaceSize));
  3113   assert(using_class_space(), "Must be using class space");
  3114   _class_space_list = new VirtualSpaceList(rs);
  3115   _chunk_manager_class = new ChunkManager(ClassSpecializedChunk, ClassSmallChunk, ClassMediumChunk);
  3117   if (!_class_space_list->initialization_succeeded()) {
  3118     vm_exit_during_initialization("Failed to setup compressed class space virtual space list.");
  3122 #endif
  3124 void Metaspace::ergo_initialize() {
  3125   if (DumpSharedSpaces) {
  3126     // Using large pages when dumping the shared archive is currently not implemented.
  3127     FLAG_SET_ERGO(bool, UseLargePagesInMetaspace, false);
  3130   size_t page_size = os::vm_page_size();
  3131   if (UseLargePages && UseLargePagesInMetaspace) {
  3132     page_size = os::large_page_size();
  3135   _commit_alignment  = page_size;
  3136   _reserve_alignment = MAX2(page_size, (size_t)os::vm_allocation_granularity());
  3138   // Do not use FLAG_SET_ERGO to update MaxMetaspaceSize, since this will
  3139   // override if MaxMetaspaceSize was set on the command line or not.
  3140   // This information is needed later to conform to the specification of the
  3141   // java.lang.management.MemoryUsage API.
  3142   //
  3143   // Ideally, we would be able to set the default value of MaxMetaspaceSize in
  3144   // globals.hpp to the aligned value, but this is not possible, since the
  3145   // alignment depends on other flags being parsed.
  3146   MaxMetaspaceSize = align_size_down_bounded(MaxMetaspaceSize, _reserve_alignment);
  3148   if (MetaspaceSize > MaxMetaspaceSize) {
  3149     MetaspaceSize = MaxMetaspaceSize;
  3152   MetaspaceSize = align_size_down_bounded(MetaspaceSize, _commit_alignment);
  3154   assert(MetaspaceSize <= MaxMetaspaceSize, "MetaspaceSize should be limited by MaxMetaspaceSize");
  3156   if (MetaspaceSize < 256*K) {
  3157     vm_exit_during_initialization("Too small initial Metaspace size");
  3160   MinMetaspaceExpansion = align_size_down_bounded(MinMetaspaceExpansion, _commit_alignment);
  3161   MaxMetaspaceExpansion = align_size_down_bounded(MaxMetaspaceExpansion, _commit_alignment);
  3163   CompressedClassSpaceSize = align_size_down_bounded(CompressedClassSpaceSize, _reserve_alignment);
  3164   set_compressed_class_space_size(CompressedClassSpaceSize);
  3166   // Initial virtual space size will be calculated at global_initialize()
  3167   uintx min_metaspace_sz =
  3168       VIRTUALSPACEMULTIPLIER * InitialBootClassLoaderMetaspaceSize;
  3169   if (UseCompressedClassPointers) {
  3170     if ((min_metaspace_sz + CompressedClassSpaceSize) >  MaxMetaspaceSize) {
  3171       if (min_metaspace_sz >= MaxMetaspaceSize) {
  3172         vm_exit_during_initialization("MaxMetaspaceSize is too small.");
  3173       } else {
  3174         FLAG_SET_ERGO(uintx, CompressedClassSpaceSize,
  3175                       MaxMetaspaceSize - min_metaspace_sz);
  3178   } else if (min_metaspace_sz >= MaxMetaspaceSize) {
  3179     FLAG_SET_ERGO(uintx, InitialBootClassLoaderMetaspaceSize,
  3180                   min_metaspace_sz);
  3185 void Metaspace::global_initialize() {
  3186   MetaspaceGC::initialize();
  3188   // Initialize the alignment for shared spaces.
  3189   int max_alignment = os::vm_allocation_granularity();
  3190   size_t cds_total = 0;
  3192   MetaspaceShared::set_max_alignment(max_alignment);
  3194   if (DumpSharedSpaces) {
  3195 #if INCLUDE_CDS
  3196     MetaspaceShared::estimate_regions_size();
  3198     SharedReadOnlySize  = align_size_up(SharedReadOnlySize,  max_alignment);
  3199     SharedReadWriteSize = align_size_up(SharedReadWriteSize, max_alignment);
  3200     SharedMiscDataSize  = align_size_up(SharedMiscDataSize,  max_alignment);
  3201     SharedMiscCodeSize  = align_size_up(SharedMiscCodeSize,  max_alignment);
  3203     // the min_misc_code_size estimate is based on MetaspaceShared::generate_vtable_methods()
  3204     uintx min_misc_code_size = align_size_up(
  3205       (MetaspaceShared::num_virtuals * MetaspaceShared::vtbl_list_size) *
  3206         (sizeof(void*) + MetaspaceShared::vtbl_method_size) + MetaspaceShared::vtbl_common_code_size,
  3207           max_alignment);
  3209     if (SharedMiscCodeSize < min_misc_code_size) {
  3210       report_out_of_shared_space(SharedMiscCode);
  3213     // Initialize with the sum of the shared space sizes.  The read-only
  3214     // and read write metaspace chunks will be allocated out of this and the
  3215     // remainder is the misc code and data chunks.
  3216     cds_total = FileMapInfo::shared_spaces_size();
  3217     cds_total = align_size_up(cds_total, _reserve_alignment);
  3218     _space_list = new VirtualSpaceList(cds_total/wordSize);
  3219     _chunk_manager_metadata = new ChunkManager(SpecializedChunk, SmallChunk, MediumChunk);
  3221     if (!_space_list->initialization_succeeded()) {
  3222       vm_exit_during_initialization("Unable to dump shared archive.", NULL);
  3225 #ifdef _LP64
  3226     if (cds_total + compressed_class_space_size() > UnscaledClassSpaceMax) {
  3227       vm_exit_during_initialization("Unable to dump shared archive.",
  3228           err_msg("Size of archive (" SIZE_FORMAT ") + compressed class space ("
  3229                   SIZE_FORMAT ") == total (" SIZE_FORMAT ") is larger than compressed "
  3230                   "klass limit: " SIZE_FORMAT, cds_total, compressed_class_space_size(),
  3231                   cds_total + compressed_class_space_size(), UnscaledClassSpaceMax));
  3234     // Set the compressed klass pointer base so that decoding of these pointers works
  3235     // properly when creating the shared archive.
  3236     assert(UseCompressedOops && UseCompressedClassPointers,
  3237       "UseCompressedOops and UseCompressedClassPointers must be set");
  3238     Universe::set_narrow_klass_base((address)_space_list->current_virtual_space()->bottom());
  3239     if (TraceMetavirtualspaceAllocation && Verbose) {
  3240       gclog_or_tty->print_cr("Setting_narrow_klass_base to Address: " PTR_FORMAT,
  3241                              _space_list->current_virtual_space()->bottom());
  3244     Universe::set_narrow_klass_shift(0);
  3245 #endif // _LP64
  3246 #endif // INCLUDE_CDS
  3247   } else {
  3248 #if INCLUDE_CDS
  3249     // If using shared space, open the file that contains the shared space
  3250     // and map in the memory before initializing the rest of metaspace (so
  3251     // the addresses don't conflict)
  3252     address cds_address = NULL;
  3253     if (UseSharedSpaces) {
  3254       FileMapInfo* mapinfo = new FileMapInfo();
  3256       // Open the shared archive file, read and validate the header. If
  3257       // initialization fails, shared spaces [UseSharedSpaces] are
  3258       // disabled and the file is closed.
  3259       // Map in spaces now also
  3260       if (mapinfo->initialize() && MetaspaceShared::map_shared_spaces(mapinfo)) {
  3261         cds_total = FileMapInfo::shared_spaces_size();
  3262         cds_address = (address)mapinfo->region_base(0);
  3263       } else {
  3264         assert(!mapinfo->is_open() && !UseSharedSpaces,
  3265                "archive file not closed or shared spaces not disabled.");
  3268 #endif // INCLUDE_CDS
  3269 #ifdef _LP64
  3270     // If UseCompressedClassPointers is set then allocate the metaspace area
  3271     // above the heap and above the CDS area (if it exists).
  3272     if (using_class_space()) {
  3273       if (UseSharedSpaces) {
  3274 #if INCLUDE_CDS
  3275         char* cds_end = (char*)(cds_address + cds_total);
  3276         cds_end = (char *)align_ptr_up(cds_end, _reserve_alignment);
  3277         allocate_metaspace_compressed_klass_ptrs(cds_end, cds_address);
  3278 #endif
  3279       } else {
  3280         char* base = (char*)align_ptr_up(Universe::heap()->reserved_region().end(), _reserve_alignment);
  3281         allocate_metaspace_compressed_klass_ptrs(base, 0);
  3284 #endif // _LP64
  3286     // Initialize these before initializing the VirtualSpaceList
  3287     _first_chunk_word_size = InitialBootClassLoaderMetaspaceSize / BytesPerWord;
  3288     _first_chunk_word_size = align_word_size_up(_first_chunk_word_size);
  3289     // Make the first class chunk bigger than a medium chunk so it's not put
  3290     // on the medium chunk list.   The next chunk will be small and progress
  3291     // from there.  This size calculated by -version.
  3292     _first_class_chunk_word_size = MIN2((size_t)MediumChunk*6,
  3293                                        (CompressedClassSpaceSize/BytesPerWord)*2);
  3294     _first_class_chunk_word_size = align_word_size_up(_first_class_chunk_word_size);
  3295     // Arbitrarily set the initial virtual space to a multiple
  3296     // of the boot class loader size.
  3297     size_t word_size = VIRTUALSPACEMULTIPLIER * _first_chunk_word_size;
  3298     word_size = align_size_up(word_size, Metaspace::reserve_alignment_words());
  3300     // Initialize the list of virtual spaces.
  3301     _space_list = new VirtualSpaceList(word_size);
  3302     _chunk_manager_metadata = new ChunkManager(SpecializedChunk, SmallChunk, MediumChunk);
  3304     if (!_space_list->initialization_succeeded()) {
  3305       vm_exit_during_initialization("Unable to setup metadata virtual space list.", NULL);
  3309   _tracer = new MetaspaceTracer();
  3312 void Metaspace::post_initialize() {
  3313   MetaspaceGC::post_initialize();
  3316 void Metaspace::initialize_first_chunk(MetaspaceType type, MetadataType mdtype) {
  3317   Metachunk* chunk = get_initialization_chunk(type, mdtype);
  3318   if (chunk != NULL) {
  3319     // Add to this manager's list of chunks in use and current_chunk().
  3320     get_space_manager(mdtype)->add_chunk(chunk, true);
  3324 Metachunk* Metaspace::get_initialization_chunk(MetaspaceType type, MetadataType mdtype) {
  3325   size_t chunk_word_size = get_space_manager(mdtype)->get_initial_chunk_size(type);
  3327   // Get a chunk from the chunk freelist
  3328   Metachunk* chunk = get_chunk_manager(mdtype)->chunk_freelist_allocate(chunk_word_size);
  3330   if (chunk == NULL) {
  3331     chunk = get_space_list(mdtype)->get_new_chunk(chunk_word_size,
  3332                                                   get_space_manager(mdtype)->medium_chunk_bunch());
  3335   // For dumping shared archive, report error if allocation has failed.
  3336   if (DumpSharedSpaces && chunk == NULL) {
  3337     report_insufficient_metaspace(MetaspaceAux::committed_bytes() + chunk_word_size * BytesPerWord);
  3340   return chunk;
  3343 void Metaspace::verify_global_initialization() {
  3344   assert(space_list() != NULL, "Metadata VirtualSpaceList has not been initialized");
  3345   assert(chunk_manager_metadata() != NULL, "Metadata ChunkManager has not been initialized");
  3347   if (using_class_space()) {
  3348     assert(class_space_list() != NULL, "Class VirtualSpaceList has not been initialized");
  3349     assert(chunk_manager_class() != NULL, "Class ChunkManager has not been initialized");
  3353 void Metaspace::initialize(Mutex* lock, MetaspaceType type) {
  3354   verify_global_initialization();
  3356   // Allocate SpaceManager for metadata objects.
  3357   _vsm = new SpaceManager(NonClassType, lock);
  3359   if (using_class_space()) {
  3360     // Allocate SpaceManager for classes.
  3361     _class_vsm = new SpaceManager(ClassType, lock);
  3364   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  3366   // Allocate chunk for metadata objects
  3367   initialize_first_chunk(type, NonClassType);
  3369   // Allocate chunk for class metadata objects
  3370   if (using_class_space()) {
  3371     initialize_first_chunk(type, ClassType);
  3374   _alloc_record_head = NULL;
  3375   _alloc_record_tail = NULL;
  3378 size_t Metaspace::align_word_size_up(size_t word_size) {
  3379   size_t byte_size = word_size * wordSize;
  3380   return ReservedSpace::allocation_align_size_up(byte_size) / wordSize;
  3383 MetaWord* Metaspace::allocate(size_t word_size, MetadataType mdtype) {
  3384   // DumpSharedSpaces doesn't use class metadata area (yet)
  3385   // Also, don't use class_vsm() unless UseCompressedClassPointers is true.
  3386   if (is_class_space_allocation(mdtype)) {
  3387     return  class_vsm()->allocate(word_size);
  3388   } else {
  3389     return  vsm()->allocate(word_size);
  3393 MetaWord* Metaspace::expand_and_allocate(size_t word_size, MetadataType mdtype) {
  3394   size_t delta_bytes = MetaspaceGC::delta_capacity_until_GC(word_size * BytesPerWord);
  3395   assert(delta_bytes > 0, "Must be");
  3397   size_t before = 0;
  3398   size_t after = 0;
  3399   MetaWord* res;
  3400   bool incremented;
  3402   // Each thread increments the HWM at most once. Even if the thread fails to increment
  3403   // the HWM, an allocation is still attempted. This is because another thread must then
  3404   // have incremented the HWM and therefore the allocation might still succeed.
  3405   do {
  3406     incremented = MetaspaceGC::inc_capacity_until_GC(delta_bytes, &after, &before);
  3407     res = allocate(word_size, mdtype);
  3408   } while (!incremented && res == NULL);
  3410   if (incremented) {
  3411     tracer()->report_gc_threshold(before, after,
  3412                                   MetaspaceGCThresholdUpdater::ExpandAndAllocate);
  3413     if (PrintGCDetails && Verbose) {
  3414       gclog_or_tty->print_cr("Increase capacity to GC from " SIZE_FORMAT
  3415           " to " SIZE_FORMAT, before, after);
  3419   return res;
  3422 // Space allocated in the Metaspace.  This may
  3423 // be across several metadata virtual spaces.
  3424 char* Metaspace::bottom() const {
  3425   assert(DumpSharedSpaces, "only useful and valid for dumping shared spaces");
  3426   return (char*)vsm()->current_chunk()->bottom();
  3429 size_t Metaspace::used_words_slow(MetadataType mdtype) const {
  3430   if (mdtype == ClassType) {
  3431     return using_class_space() ? class_vsm()->sum_used_in_chunks_in_use() : 0;
  3432   } else {
  3433     return vsm()->sum_used_in_chunks_in_use();  // includes overhead!
  3437 size_t Metaspace::free_words_slow(MetadataType mdtype) const {
  3438   if (mdtype == ClassType) {
  3439     return using_class_space() ? class_vsm()->sum_free_in_chunks_in_use() : 0;
  3440   } else {
  3441     return vsm()->sum_free_in_chunks_in_use();
  3445 // Space capacity in the Metaspace.  It includes
  3446 // space in the list of chunks from which allocations
  3447 // have been made. Don't include space in the global freelist and
  3448 // in the space available in the dictionary which
  3449 // is already counted in some chunk.
  3450 size_t Metaspace::capacity_words_slow(MetadataType mdtype) const {
  3451   if (mdtype == ClassType) {
  3452     return using_class_space() ? class_vsm()->sum_capacity_in_chunks_in_use() : 0;
  3453   } else {
  3454     return vsm()->sum_capacity_in_chunks_in_use();
  3458 size_t Metaspace::used_bytes_slow(MetadataType mdtype) const {
  3459   return used_words_slow(mdtype) * BytesPerWord;
  3462 size_t Metaspace::capacity_bytes_slow(MetadataType mdtype) const {
  3463   return capacity_words_slow(mdtype) * BytesPerWord;
  3466 void Metaspace::deallocate(MetaWord* ptr, size_t word_size, bool is_class) {
  3467   if (SafepointSynchronize::is_at_safepoint()) {
  3468     if (DumpSharedSpaces && PrintSharedSpaces) {
  3469       record_deallocation(ptr, vsm()->get_raw_word_size(word_size));
  3472     assert(Thread::current()->is_VM_thread(), "should be the VM thread");
  3473     // Don't take Heap_lock
  3474     MutexLockerEx ml(vsm()->lock(), Mutex::_no_safepoint_check_flag);
  3475     if (word_size < TreeChunk<Metablock, FreeList<Metablock> >::min_size()) {
  3476       // Dark matter.  Too small for dictionary.
  3477 #ifdef ASSERT
  3478       Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
  3479 #endif
  3480       return;
  3482     if (is_class && using_class_space()) {
  3483       class_vsm()->deallocate(ptr, word_size);
  3484     } else {
  3485       vsm()->deallocate(ptr, word_size);
  3487   } else {
  3488     MutexLockerEx ml(vsm()->lock(), Mutex::_no_safepoint_check_flag);
  3490     if (word_size < TreeChunk<Metablock, FreeList<Metablock> >::min_size()) {
  3491       // Dark matter.  Too small for dictionary.
  3492 #ifdef ASSERT
  3493       Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
  3494 #endif
  3495       return;
  3497     if (is_class && using_class_space()) {
  3498       class_vsm()->deallocate(ptr, word_size);
  3499     } else {
  3500       vsm()->deallocate(ptr, word_size);
  3506 MetaWord* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size,
  3507                               bool read_only, MetaspaceObj::Type type, TRAPS) {
  3508   if (HAS_PENDING_EXCEPTION) {
  3509     assert(false, "Should not allocate with exception pending");
  3510     return NULL;  // caller does a CHECK_NULL too
  3513   assert(loader_data != NULL, "Should never pass around a NULL loader_data. "
  3514         "ClassLoaderData::the_null_class_loader_data() should have been used.");
  3516   // Allocate in metaspaces without taking out a lock, because it deadlocks
  3517   // with the SymbolTable_lock.  Dumping is single threaded for now.  We'll have
  3518   // to revisit this for application class data sharing.
  3519   if (DumpSharedSpaces) {
  3520     assert(type > MetaspaceObj::UnknownType && type < MetaspaceObj::_number_of_types, "sanity");
  3521     Metaspace* space = read_only ? loader_data->ro_metaspace() : loader_data->rw_metaspace();
  3522     MetaWord* result = space->allocate(word_size, NonClassType);
  3523     if (result == NULL) {
  3524       report_out_of_shared_space(read_only ? SharedReadOnly : SharedReadWrite);
  3526     if (PrintSharedSpaces) {
  3527       space->record_allocation(result, type, space->vsm()->get_raw_word_size(word_size));
  3530     // Zero initialize.
  3531     Copy::fill_to_aligned_words((HeapWord*)result, word_size, 0);
  3533     return result;
  3536   MetadataType mdtype = (type == MetaspaceObj::ClassType) ? ClassType : NonClassType;
  3538   // Try to allocate metadata.
  3539   MetaWord* result = loader_data->metaspace_non_null()->allocate(word_size, mdtype);
  3541   if (result == NULL) {
  3542     tracer()->report_metaspace_allocation_failure(loader_data, word_size, type, mdtype);
  3544     // Allocation failed.
  3545     if (is_init_completed()) {
  3546       // Only start a GC if the bootstrapping has completed.
  3548       // Try to clean out some memory and retry.
  3549       result = Universe::heap()->collector_policy()->satisfy_failed_metadata_allocation(
  3550           loader_data, word_size, mdtype);
  3554   if (result == NULL) {
  3555     report_metadata_oome(loader_data, word_size, type, mdtype, CHECK_NULL);
  3558   // Zero initialize.
  3559   Copy::fill_to_aligned_words((HeapWord*)result, word_size, 0);
  3561   return result;
  3564 size_t Metaspace::class_chunk_size(size_t word_size) {
  3565   assert(using_class_space(), "Has to use class space");
  3566   return class_vsm()->calc_chunk_size(word_size);
  3569 void Metaspace::report_metadata_oome(ClassLoaderData* loader_data, size_t word_size, MetaspaceObj::Type type, MetadataType mdtype, TRAPS) {
  3570   tracer()->report_metadata_oom(loader_data, word_size, type, mdtype);
  3572   // If result is still null, we are out of memory.
  3573   if (Verbose && TraceMetadataChunkAllocation) {
  3574     gclog_or_tty->print_cr("Metaspace allocation failed for size "
  3575         SIZE_FORMAT, word_size);
  3576     if (loader_data->metaspace_or_null() != NULL) {
  3577       loader_data->dump(gclog_or_tty);
  3579     MetaspaceAux::dump(gclog_or_tty);
  3582   bool out_of_compressed_class_space = false;
  3583   if (is_class_space_allocation(mdtype)) {
  3584     Metaspace* metaspace = loader_data->metaspace_non_null();
  3585     out_of_compressed_class_space =
  3586       MetaspaceAux::committed_bytes(Metaspace::ClassType) +
  3587       (metaspace->class_chunk_size(word_size) * BytesPerWord) >
  3588       CompressedClassSpaceSize;
  3591   // -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support
  3592   const char* space_string = out_of_compressed_class_space ?
  3593     "Compressed class space" : "Metaspace";
  3595   report_java_out_of_memory(space_string);
  3597   if (JvmtiExport::should_post_resource_exhausted()) {
  3598     JvmtiExport::post_resource_exhausted(
  3599         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR,
  3600         space_string);
  3603   if (!is_init_completed()) {
  3604     vm_exit_during_initialization("OutOfMemoryError", space_string);
  3607   if (out_of_compressed_class_space) {
  3608     THROW_OOP(Universe::out_of_memory_error_class_metaspace());
  3609   } else {
  3610     THROW_OOP(Universe::out_of_memory_error_metaspace());
  3614 const char* Metaspace::metadata_type_name(Metaspace::MetadataType mdtype) {
  3615   switch (mdtype) {
  3616     case Metaspace::ClassType: return "Class";
  3617     case Metaspace::NonClassType: return "Metadata";
  3618     default:
  3619       assert(false, err_msg("Got bad mdtype: %d", (int) mdtype));
  3620       return NULL;
  3624 void Metaspace::record_allocation(void* ptr, MetaspaceObj::Type type, size_t word_size) {
  3625   assert(DumpSharedSpaces, "sanity");
  3627   int byte_size = (int)word_size * HeapWordSize;
  3628   AllocRecord *rec = new AllocRecord((address)ptr, type, byte_size);
  3630   if (_alloc_record_head == NULL) {
  3631     _alloc_record_head = _alloc_record_tail = rec;
  3632   } else if (_alloc_record_tail->_ptr + _alloc_record_tail->_byte_size == (address)ptr) {
  3633     _alloc_record_tail->_next = rec;
  3634     _alloc_record_tail = rec;
  3635   } else {
  3636     // slow linear search, but this doesn't happen that often, and only when dumping
  3637     for (AllocRecord *old = _alloc_record_head; old; old = old->_next) {
  3638       if (old->_ptr == ptr) {
  3639         assert(old->_type == MetaspaceObj::DeallocatedType, "sanity");
  3640         int remain_bytes = old->_byte_size - byte_size;
  3641         assert(remain_bytes >= 0, "sanity");
  3642         old->_type = type;
  3644         if (remain_bytes == 0) {
  3645           delete(rec);
  3646         } else {
  3647           address remain_ptr = address(ptr) + byte_size;
  3648           rec->_ptr = remain_ptr;
  3649           rec->_byte_size = remain_bytes;
  3650           rec->_type = MetaspaceObj::DeallocatedType;
  3651           rec->_next = old->_next;
  3652           old->_byte_size = byte_size;
  3653           old->_next = rec;
  3655         return;
  3658     assert(0, "reallocating a freed pointer that was not recorded");
  3662 void Metaspace::record_deallocation(void* ptr, size_t word_size) {
  3663   assert(DumpSharedSpaces, "sanity");
  3665   for (AllocRecord *rec = _alloc_record_head; rec; rec = rec->_next) {
  3666     if (rec->_ptr == ptr) {
  3667       assert(rec->_byte_size == (int)word_size * HeapWordSize, "sanity");
  3668       rec->_type = MetaspaceObj::DeallocatedType;
  3669       return;
  3673   assert(0, "deallocating a pointer that was not recorded");
  3676 void Metaspace::iterate(Metaspace::AllocRecordClosure *closure) {
  3677   assert(DumpSharedSpaces, "unimplemented for !DumpSharedSpaces");
  3679   address last_addr = (address)bottom();
  3681   for (AllocRecord *rec = _alloc_record_head; rec; rec = rec->_next) {
  3682     address ptr = rec->_ptr;
  3683     if (last_addr < ptr) {
  3684       closure->doit(last_addr, MetaspaceObj::UnknownType, ptr - last_addr);
  3686     closure->doit(ptr, rec->_type, rec->_byte_size);
  3687     last_addr = ptr + rec->_byte_size;
  3690   address top = ((address)bottom()) + used_bytes_slow(Metaspace::NonClassType);
  3691   if (last_addr < top) {
  3692     closure->doit(last_addr, MetaspaceObj::UnknownType, top - last_addr);
  3696 void Metaspace::purge(MetadataType mdtype) {
  3697   get_space_list(mdtype)->purge(get_chunk_manager(mdtype));
  3700 void Metaspace::purge() {
  3701   MutexLockerEx cl(SpaceManager::expand_lock(),
  3702                    Mutex::_no_safepoint_check_flag);
  3703   purge(NonClassType);
  3704   if (using_class_space()) {
  3705     purge(ClassType);
  3709 void Metaspace::print_on(outputStream* out) const {
  3710   // Print both class virtual space counts and metaspace.
  3711   if (Verbose) {
  3712     vsm()->print_on(out);
  3713     if (using_class_space()) {
  3714       class_vsm()->print_on(out);
  3719 bool Metaspace::contains(const void* ptr) {
  3720   if (UseSharedSpaces && MetaspaceShared::is_in_shared_space(ptr)) {
  3721     return true;
  3724   if (using_class_space() && get_space_list(ClassType)->contains(ptr)) {
  3725      return true;
  3728   return get_space_list(NonClassType)->contains(ptr);
  3731 void Metaspace::verify() {
  3732   vsm()->verify();
  3733   if (using_class_space()) {
  3734     class_vsm()->verify();
  3738 void Metaspace::dump(outputStream* const out) const {
  3739   out->print_cr("\nVirtual space manager: " INTPTR_FORMAT, vsm());
  3740   vsm()->dump(out);
  3741   if (using_class_space()) {
  3742     out->print_cr("\nClass space manager: " INTPTR_FORMAT, class_vsm());
  3743     class_vsm()->dump(out);
  3747 /////////////// Unit tests ///////////////
  3749 #ifndef PRODUCT
  3751 class TestMetaspaceAuxTest : AllStatic {
  3752  public:
  3753   static void test_reserved() {
  3754     size_t reserved = MetaspaceAux::reserved_bytes();
  3756     assert(reserved > 0, "assert");
  3758     size_t committed  = MetaspaceAux::committed_bytes();
  3759     assert(committed <= reserved, "assert");
  3761     size_t reserved_metadata = MetaspaceAux::reserved_bytes(Metaspace::NonClassType);
  3762     assert(reserved_metadata > 0, "assert");
  3763     assert(reserved_metadata <= reserved, "assert");
  3765     if (UseCompressedClassPointers) {
  3766       size_t reserved_class    = MetaspaceAux::reserved_bytes(Metaspace::ClassType);
  3767       assert(reserved_class > 0, "assert");
  3768       assert(reserved_class < reserved, "assert");
  3772   static void test_committed() {
  3773     size_t committed = MetaspaceAux::committed_bytes();
  3775     assert(committed > 0, "assert");
  3777     size_t reserved  = MetaspaceAux::reserved_bytes();
  3778     assert(committed <= reserved, "assert");
  3780     size_t committed_metadata = MetaspaceAux::committed_bytes(Metaspace::NonClassType);
  3781     assert(committed_metadata > 0, "assert");
  3782     assert(committed_metadata <= committed, "assert");
  3784     if (UseCompressedClassPointers) {
  3785       size_t committed_class    = MetaspaceAux::committed_bytes(Metaspace::ClassType);
  3786       assert(committed_class > 0, "assert");
  3787       assert(committed_class < committed, "assert");
  3791   static void test_virtual_space_list_large_chunk() {
  3792     VirtualSpaceList* vs_list = new VirtualSpaceList(os::vm_allocation_granularity());
  3793     MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  3794     // A size larger than VirtualSpaceSize (256k) and add one page to make it _not_ be
  3795     // vm_allocation_granularity aligned on Windows.
  3796     size_t large_size = (size_t)(2*256*K + (os::vm_page_size()/BytesPerWord));
  3797     large_size += (os::vm_page_size()/BytesPerWord);
  3798     vs_list->get_new_chunk(large_size, 0);
  3801   static void test() {
  3802     test_reserved();
  3803     test_committed();
  3804     test_virtual_space_list_large_chunk();
  3806 };
  3808 void TestMetaspaceAux_test() {
  3809   TestMetaspaceAuxTest::test();
  3812 class TestVirtualSpaceNodeTest {
  3813   static void chunk_up(size_t words_left, size_t& num_medium_chunks,
  3814                                           size_t& num_small_chunks,
  3815                                           size_t& num_specialized_chunks) {
  3816     num_medium_chunks = words_left / MediumChunk;
  3817     words_left = words_left % MediumChunk;
  3819     num_small_chunks = words_left / SmallChunk;
  3820     words_left = words_left % SmallChunk;
  3821     // how many specialized chunks can we get?
  3822     num_specialized_chunks = words_left / SpecializedChunk;
  3823     assert(words_left % SpecializedChunk == 0, "should be nothing left");
  3826  public:
  3827   static void test() {
  3828     MutexLockerEx ml(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  3829     const size_t vsn_test_size_words = MediumChunk  * 4;
  3830     const size_t vsn_test_size_bytes = vsn_test_size_words * BytesPerWord;
  3832     // The chunk sizes must be multiples of eachother, or this will fail
  3833     STATIC_ASSERT(MediumChunk % SmallChunk == 0);
  3834     STATIC_ASSERT(SmallChunk % SpecializedChunk == 0);
  3836     { // No committed memory in VSN
  3837       ChunkManager cm(SpecializedChunk, SmallChunk, MediumChunk);
  3838       VirtualSpaceNode vsn(vsn_test_size_bytes);
  3839       vsn.initialize();
  3840       vsn.retire(&cm);
  3841       assert(cm.sum_free_chunks_count() == 0, "did not commit any memory in the VSN");
  3844     { // All of VSN is committed, half is used by chunks
  3845       ChunkManager cm(SpecializedChunk, SmallChunk, MediumChunk);
  3846       VirtualSpaceNode vsn(vsn_test_size_bytes);
  3847       vsn.initialize();
  3848       vsn.expand_by(vsn_test_size_words, vsn_test_size_words);
  3849       vsn.get_chunk_vs(MediumChunk);
  3850       vsn.get_chunk_vs(MediumChunk);
  3851       vsn.retire(&cm);
  3852       assert(cm.sum_free_chunks_count() == 2, "should have been memory left for 2 medium chunks");
  3853       assert(cm.sum_free_chunks() == 2*MediumChunk, "sizes should add up");
  3856     { // 4 pages of VSN is committed, some is used by chunks
  3857       ChunkManager cm(SpecializedChunk, SmallChunk, MediumChunk);
  3858       VirtualSpaceNode vsn(vsn_test_size_bytes);
  3859       const size_t page_chunks = 4 * (size_t)os::vm_page_size() / BytesPerWord;
  3860       assert(page_chunks < MediumChunk, "Test expects medium chunks to be at least 4*page_size");
  3861       vsn.initialize();
  3862       vsn.expand_by(page_chunks, page_chunks);
  3863       vsn.get_chunk_vs(SmallChunk);
  3864       vsn.get_chunk_vs(SpecializedChunk);
  3865       vsn.retire(&cm);
  3867       // committed - used = words left to retire
  3868       const size_t words_left = page_chunks - SmallChunk - SpecializedChunk;
  3870       size_t num_medium_chunks, num_small_chunks, num_spec_chunks;
  3871       chunk_up(words_left, num_medium_chunks, num_small_chunks, num_spec_chunks);
  3873       assert(num_medium_chunks == 0, "should not get any medium chunks");
  3874       assert(cm.sum_free_chunks_count() == (num_small_chunks + num_spec_chunks), "should be space for 3 chunks");
  3875       assert(cm.sum_free_chunks() == words_left, "sizes should add up");
  3878     { // Half of VSN is committed, a humongous chunk is used
  3879       ChunkManager cm(SpecializedChunk, SmallChunk, MediumChunk);
  3880       VirtualSpaceNode vsn(vsn_test_size_bytes);
  3881       vsn.initialize();
  3882       vsn.expand_by(MediumChunk * 2, MediumChunk * 2);
  3883       vsn.get_chunk_vs(MediumChunk + SpecializedChunk); // Humongous chunks will be aligned up to MediumChunk + SpecializedChunk
  3884       vsn.retire(&cm);
  3886       const size_t words_left = MediumChunk * 2 - (MediumChunk + SpecializedChunk);
  3887       size_t num_medium_chunks, num_small_chunks, num_spec_chunks;
  3888       chunk_up(words_left, num_medium_chunks, num_small_chunks, num_spec_chunks);
  3890       assert(num_medium_chunks == 0, "should not get any medium chunks");
  3891       assert(cm.sum_free_chunks_count() == (num_small_chunks + num_spec_chunks), "should be space for 3 chunks");
  3892       assert(cm.sum_free_chunks() == words_left, "sizes should add up");
  3897 #define assert_is_available_positive(word_size) \
  3898   assert(vsn.is_available(word_size), \
  3899     err_msg(#word_size ": " PTR_FORMAT " bytes were not available in " \
  3900             "VirtualSpaceNode [" PTR_FORMAT ", " PTR_FORMAT ")", \
  3901             (uintptr_t)(word_size * BytesPerWord), vsn.bottom(), vsn.end()));
  3903 #define assert_is_available_negative(word_size) \
  3904   assert(!vsn.is_available(word_size), \
  3905     err_msg(#word_size ": " PTR_FORMAT " bytes should not be available in " \
  3906             "VirtualSpaceNode [" PTR_FORMAT ", " PTR_FORMAT ")", \
  3907             (uintptr_t)(word_size * BytesPerWord), vsn.bottom(), vsn.end()));
  3909   static void test_is_available_positive() {
  3910     // Reserve some memory.
  3911     VirtualSpaceNode vsn(os::vm_allocation_granularity());
  3912     assert(vsn.initialize(), "Failed to setup VirtualSpaceNode");
  3914     // Commit some memory.
  3915     size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord;
  3916     bool expanded = vsn.expand_by(commit_word_size, commit_word_size);
  3917     assert(expanded, "Failed to commit");
  3919     // Check that is_available accepts the committed size.
  3920     assert_is_available_positive(commit_word_size);
  3922     // Check that is_available accepts half the committed size.
  3923     size_t expand_word_size = commit_word_size / 2;
  3924     assert_is_available_positive(expand_word_size);
  3927   static void test_is_available_negative() {
  3928     // Reserve some memory.
  3929     VirtualSpaceNode vsn(os::vm_allocation_granularity());
  3930     assert(vsn.initialize(), "Failed to setup VirtualSpaceNode");
  3932     // Commit some memory.
  3933     size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord;
  3934     bool expanded = vsn.expand_by(commit_word_size, commit_word_size);
  3935     assert(expanded, "Failed to commit");
  3937     // Check that is_available doesn't accept a too large size.
  3938     size_t two_times_commit_word_size = commit_word_size * 2;
  3939     assert_is_available_negative(two_times_commit_word_size);
  3942   static void test_is_available_overflow() {
  3943     // Reserve some memory.
  3944     VirtualSpaceNode vsn(os::vm_allocation_granularity());
  3945     assert(vsn.initialize(), "Failed to setup VirtualSpaceNode");
  3947     // Commit some memory.
  3948     size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord;
  3949     bool expanded = vsn.expand_by(commit_word_size, commit_word_size);
  3950     assert(expanded, "Failed to commit");
  3952     // Calculate a size that will overflow the virtual space size.
  3953     void* virtual_space_max = (void*)(uintptr_t)-1;
  3954     size_t bottom_to_max = pointer_delta(virtual_space_max, vsn.bottom(), 1);
  3955     size_t overflow_size = bottom_to_max + BytesPerWord;
  3956     size_t overflow_word_size = overflow_size / BytesPerWord;
  3958     // Check that is_available can handle the overflow.
  3959     assert_is_available_negative(overflow_word_size);
  3962   static void test_is_available() {
  3963     TestVirtualSpaceNodeTest::test_is_available_positive();
  3964     TestVirtualSpaceNodeTest::test_is_available_negative();
  3965     TestVirtualSpaceNodeTest::test_is_available_overflow();
  3967 };
  3969 void TestVirtualSpaceNode_test() {
  3970   TestVirtualSpaceNodeTest::test();
  3971   TestVirtualSpaceNodeTest::test_is_available();
  3974 // The following test is placed here instead of a gtest / unittest file
  3975 // because the ChunkManager class is only available in this file.
  3976 class SpaceManagerTest : AllStatic {
  3977   friend void SpaceManager_test_adjust_initial_chunk_size();
  3979   static void test_adjust_initial_chunk_size(bool is_class) {
  3980     const size_t smallest = SpaceManager::smallest_chunk_size(is_class);
  3981     const size_t normal   = SpaceManager::small_chunk_size(is_class);
  3982     const size_t medium   = SpaceManager::medium_chunk_size(is_class);
  3984 #define test_adjust_initial_chunk_size(value, expected, is_class_value)          \
  3985     do {                                                                         \
  3986       size_t v = value;                                                          \
  3987       size_t e = expected;                                                       \
  3988       assert(SpaceManager::adjust_initial_chunk_size(v, (is_class_value)) == e,  \
  3989              err_msg("Expected: " SIZE_FORMAT " got: " SIZE_FORMAT, e, v));      \
  3990     } while (0)
  3992     // Smallest (specialized)
  3993     test_adjust_initial_chunk_size(1,            smallest, is_class);
  3994     test_adjust_initial_chunk_size(smallest - 1, smallest, is_class);
  3995     test_adjust_initial_chunk_size(smallest,     smallest, is_class);
  3997     // Small
  3998     test_adjust_initial_chunk_size(smallest + 1, normal, is_class);
  3999     test_adjust_initial_chunk_size(normal - 1,   normal, is_class);
  4000     test_adjust_initial_chunk_size(normal,       normal, is_class);
  4002     // Medium
  4003     test_adjust_initial_chunk_size(normal + 1, medium, is_class);
  4004     test_adjust_initial_chunk_size(medium - 1, medium, is_class);
  4005     test_adjust_initial_chunk_size(medium,     medium, is_class);
  4007     // Humongous
  4008     test_adjust_initial_chunk_size(medium + 1, medium + 1, is_class);
  4010 #undef test_adjust_initial_chunk_size
  4013   static void test_adjust_initial_chunk_size() {
  4014     test_adjust_initial_chunk_size(false);
  4015     test_adjust_initial_chunk_size(true);
  4017 };
  4019 void SpaceManager_test_adjust_initial_chunk_size() {
  4020   SpaceManagerTest::test_adjust_initial_chunk_size();
  4023 #endif

mercurial