src/share/vm/memory/metaspace.cpp

Thu, 15 May 2014 18:23:26 -0400

author
coleenp
date
Thu, 15 May 2014 18:23:26 -0400
changeset 6678
7384f6a12fc1
parent 6609
270d7cb38f40
child 6680
78bbf4d43a14
permissions
-rw-r--r--

8038212: Method::is_valid_method() check has performance regression impact for stackwalking
Summary: Only prune metaspace virtual spaces at safepoint so walking them is safe outside a safepoint.
Reviewed-by: mgerdin, mgronlun, hseigel, stefank

     1 /*
     2  * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    24 #include "precompiled.hpp"
    25 #include "gc_interface/collectedHeap.hpp"
    26 #include "memory/allocation.hpp"
    27 #include "memory/binaryTreeDictionary.hpp"
    28 #include "memory/freeList.hpp"
    29 #include "memory/collectorPolicy.hpp"
    30 #include "memory/filemap.hpp"
    31 #include "memory/freeList.hpp"
    32 #include "memory/gcLocker.hpp"
    33 #include "memory/metachunk.hpp"
    34 #include "memory/metaspace.hpp"
    35 #include "memory/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.hpp"
    46 #include "services/memTracker.hpp"
    47 #include "services/memoryService.hpp"
    48 #include "utilities/copy.hpp"
    49 #include "utilities/debug.hpp"
    51 typedef BinaryTreeDictionary<Metablock, FreeList<Metablock> > BlockTreeDictionary;
    52 typedef BinaryTreeDictionary<Metachunk, FreeList<Metachunk> > ChunkTreeDictionary;
    54 // Set this constant to enable slow integrity checking of the free chunk lists
    55 const bool metaspace_slow_verify = false;
    57 size_t const allocation_from_dictionary_limit = 4 * K;
    59 MetaWord* last_allocated = 0;
    61 size_t Metaspace::_compressed_class_space_size;
    62 const MetaspaceTracer* Metaspace::_tracer = NULL;
    64 // Used in declarations in SpaceManager and ChunkManager
    65 enum ChunkIndex {
    66   ZeroIndex = 0,
    67   SpecializedIndex = ZeroIndex,
    68   SmallIndex = SpecializedIndex + 1,
    69   MediumIndex = SmallIndex + 1,
    70   HumongousIndex = MediumIndex + 1,
    71   NumberOfFreeLists = 3,
    72   NumberOfInUseLists = 4
    73 };
    75 enum ChunkSizes {    // in words.
    76   ClassSpecializedChunk = 128,
    77   SpecializedChunk = 128,
    78   ClassSmallChunk = 256,
    79   SmallChunk = 512,
    80   ClassMediumChunk = 4 * K,
    81   MediumChunk = 8 * K
    82 };
    84 static ChunkIndex next_chunk_index(ChunkIndex i) {
    85   assert(i < NumberOfInUseLists, "Out of bound");
    86   return (ChunkIndex) (i+1);
    87 }
    89 volatile intptr_t MetaspaceGC::_capacity_until_GC = 0;
    90 uint MetaspaceGC::_shrink_factor = 0;
    91 bool MetaspaceGC::_should_concurrent_collect = false;
    93 typedef class FreeList<Metachunk> ChunkList;
    95 // Manages the global free lists of chunks.
    96 class ChunkManager : public CHeapObj<mtInternal> {
    97   friend class TestVirtualSpaceNodeTest;
    99   // Free list of chunks of different sizes.
   100   //   SpecializedChunk
   101   //   SmallChunk
   102   //   MediumChunk
   103   //   HumongousChunk
   104   ChunkList _free_chunks[NumberOfFreeLists];
   106   //   HumongousChunk
   107   ChunkTreeDictionary _humongous_dictionary;
   109   // ChunkManager in all lists of this type
   110   size_t _free_chunks_total;
   111   size_t _free_chunks_count;
   113   void dec_free_chunks_total(size_t v) {
   114     assert(_free_chunks_count > 0 &&
   115              _free_chunks_total > 0,
   116              "About to go negative");
   117     Atomic::add_ptr(-1, &_free_chunks_count);
   118     jlong minus_v = (jlong) - (jlong) v;
   119     Atomic::add_ptr(minus_v, &_free_chunks_total);
   120   }
   122   // Debug support
   124   size_t sum_free_chunks();
   125   size_t sum_free_chunks_count();
   127   void locked_verify_free_chunks_total();
   128   void slow_locked_verify_free_chunks_total() {
   129     if (metaspace_slow_verify) {
   130       locked_verify_free_chunks_total();
   131     }
   132   }
   133   void locked_verify_free_chunks_count();
   134   void slow_locked_verify_free_chunks_count() {
   135     if (metaspace_slow_verify) {
   136       locked_verify_free_chunks_count();
   137     }
   138   }
   139   void verify_free_chunks_count();
   141  public:
   143   ChunkManager(size_t specialized_size, size_t small_size, size_t medium_size)
   144       : _free_chunks_total(0), _free_chunks_count(0) {
   145     _free_chunks[SpecializedIndex].set_size(specialized_size);
   146     _free_chunks[SmallIndex].set_size(small_size);
   147     _free_chunks[MediumIndex].set_size(medium_size);
   148   }
   150   // add or delete (return) a chunk to the global freelist.
   151   Metachunk* chunk_freelist_allocate(size_t word_size);
   153   // Map a size to a list index assuming that there are lists
   154   // for special, small, medium, and humongous chunks.
   155   static ChunkIndex list_index(size_t size);
   157   // Remove the chunk from its freelist.  It is
   158   // expected to be on one of the _free_chunks[] lists.
   159   void remove_chunk(Metachunk* chunk);
   161   // Add the simple linked list of chunks to the freelist of chunks
   162   // of type index.
   163   void return_chunks(ChunkIndex index, Metachunk* chunks);
   165   // Total of the space in the free chunks list
   166   size_t free_chunks_total_words();
   167   size_t free_chunks_total_bytes();
   169   // Number of chunks in the free chunks list
   170   size_t free_chunks_count();
   172   void inc_free_chunks_total(size_t v, size_t count = 1) {
   173     Atomic::add_ptr(count, &_free_chunks_count);
   174     Atomic::add_ptr(v, &_free_chunks_total);
   175   }
   176   ChunkTreeDictionary* humongous_dictionary() {
   177     return &_humongous_dictionary;
   178   }
   180   ChunkList* free_chunks(ChunkIndex index);
   182   // Returns the list for the given chunk word size.
   183   ChunkList* find_free_chunks_list(size_t word_size);
   185   // Remove from a list by size.  Selects list based on size of chunk.
   186   Metachunk* free_chunks_get(size_t chunk_word_size);
   188 #define index_bounds_check(index)                                         \
   189   assert(index == SpecializedIndex ||                                     \
   190          index == SmallIndex ||                                           \
   191          index == MediumIndex ||                                          \
   192          index == HumongousIndex, err_msg("Bad index: %d", (int) index))
   194   size_t num_free_chunks(ChunkIndex index) const {
   195     index_bounds_check(index);
   197     if (index == HumongousIndex) {
   198       return _humongous_dictionary.total_free_blocks();
   199     }
   201     ssize_t count = _free_chunks[index].count();
   202     return count == -1 ? 0 : (size_t) count;
   203   }
   205   size_t size_free_chunks_in_bytes(ChunkIndex index) const {
   206     index_bounds_check(index);
   208     size_t word_size = 0;
   209     if (index == HumongousIndex) {
   210       word_size = _humongous_dictionary.total_size();
   211     } else {
   212       const size_t size_per_chunk_in_words = _free_chunks[index].size();
   213       word_size = size_per_chunk_in_words * num_free_chunks(index);
   214     }
   216     return word_size * BytesPerWord;
   217   }
   219   MetaspaceChunkFreeListSummary chunk_free_list_summary() const {
   220     return MetaspaceChunkFreeListSummary(num_free_chunks(SpecializedIndex),
   221                                          num_free_chunks(SmallIndex),
   222                                          num_free_chunks(MediumIndex),
   223                                          num_free_chunks(HumongousIndex),
   224                                          size_free_chunks_in_bytes(SpecializedIndex),
   225                                          size_free_chunks_in_bytes(SmallIndex),
   226                                          size_free_chunks_in_bytes(MediumIndex),
   227                                          size_free_chunks_in_bytes(HumongousIndex));
   228   }
   230   // Debug support
   231   void verify();
   232   void slow_verify() {
   233     if (metaspace_slow_verify) {
   234       verify();
   235     }
   236   }
   237   void locked_verify();
   238   void slow_locked_verify() {
   239     if (metaspace_slow_verify) {
   240       locked_verify();
   241     }
   242   }
   243   void verify_free_chunks_total();
   245   void locked_print_free_chunks(outputStream* st);
   246   void locked_print_sum_free_chunks(outputStream* st);
   248   void print_on(outputStream* st) const;
   249 };
   251 // Used to manage the free list of Metablocks (a block corresponds
   252 // to the allocation of a quantum of metadata).
   253 class BlockFreelist VALUE_OBJ_CLASS_SPEC {
   254   BlockTreeDictionary* _dictionary;
   256   // Only allocate and split from freelist if the size of the allocation
   257   // is at least 1/4th the size of the available block.
   258   const static int WasteMultiplier = 4;
   260   // Accessors
   261   BlockTreeDictionary* dictionary() const { return _dictionary; }
   263  public:
   264   BlockFreelist();
   265   ~BlockFreelist();
   267   // Get and return a block to the free list
   268   MetaWord* get_block(size_t word_size);
   269   void return_block(MetaWord* p, size_t word_size);
   271   size_t total_size() {
   272   if (dictionary() == NULL) {
   273     return 0;
   274   } else {
   275     return dictionary()->total_size();
   276   }
   277 }
   279   void print_on(outputStream* st) const;
   280 };
   282 // A VirtualSpaceList node.
   283 class VirtualSpaceNode : public CHeapObj<mtClass> {
   284   friend class VirtualSpaceList;
   286   // Link to next VirtualSpaceNode
   287   VirtualSpaceNode* _next;
   289   // total in the VirtualSpace
   290   MemRegion _reserved;
   291   ReservedSpace _rs;
   292   VirtualSpace _virtual_space;
   293   MetaWord* _top;
   294   // count of chunks contained in this VirtualSpace
   295   uintx _container_count;
   297   // Convenience functions to access the _virtual_space
   298   char* low()  const { return virtual_space()->low(); }
   299   char* high() const { return virtual_space()->high(); }
   301   // The first Metachunk will be allocated at the bottom of the
   302   // VirtualSpace
   303   Metachunk* first_chunk() { return (Metachunk*) bottom(); }
   305   // Committed but unused space in the virtual space
   306   size_t free_words_in_vs() const;
   307  public:
   309   VirtualSpaceNode(size_t byte_size);
   310   VirtualSpaceNode(ReservedSpace rs) : _top(NULL), _next(NULL), _rs(rs), _container_count(0) {}
   311   ~VirtualSpaceNode();
   313   // Convenience functions for logical bottom and end
   314   MetaWord* bottom() const { return (MetaWord*) _virtual_space.low(); }
   315   MetaWord* end() const { return (MetaWord*) _virtual_space.high(); }
   317   bool contains(const void* ptr) { return ptr >= low() && ptr < high(); }
   319   size_t reserved_words() const  { return _virtual_space.reserved_size() / BytesPerWord; }
   320   size_t committed_words() const { return _virtual_space.actual_committed_size() / BytesPerWord; }
   322   bool is_pre_committed() const { return _virtual_space.special(); }
   324   // address of next available space in _virtual_space;
   325   // Accessors
   326   VirtualSpaceNode* next() { return _next; }
   327   void set_next(VirtualSpaceNode* v) { _next = v; }
   329   void set_reserved(MemRegion const v) { _reserved = v; }
   330   void set_top(MetaWord* v) { _top = v; }
   332   // Accessors
   333   MemRegion* reserved() { return &_reserved; }
   334   VirtualSpace* virtual_space() const { return (VirtualSpace*) &_virtual_space; }
   336   // Returns true if "word_size" is available in the VirtualSpace
   337   bool is_available(size_t word_size) { return word_size <= pointer_delta(end(), _top, sizeof(MetaWord)); }
   339   MetaWord* top() const { return _top; }
   340   void inc_top(size_t word_size) { _top += word_size; }
   342   uintx container_count() { return _container_count; }
   343   void inc_container_count();
   344   void dec_container_count();
   345 #ifdef ASSERT
   346   uint container_count_slow();
   347   void verify_container_count();
   348 #endif
   350   // used and capacity in this single entry in the list
   351   size_t used_words_in_vs() const;
   352   size_t capacity_words_in_vs() const;
   354   bool initialize();
   356   // get space from the virtual space
   357   Metachunk* take_from_committed(size_t chunk_word_size);
   359   // Allocate a chunk from the virtual space and return it.
   360   Metachunk* get_chunk_vs(size_t chunk_word_size);
   362   // Expands/shrinks the committed space in a virtual space.  Delegates
   363   // to Virtualspace
   364   bool expand_by(size_t min_words, size_t preferred_words);
   366   // In preparation for deleting this node, remove all the chunks
   367   // in the node from any freelist.
   368   void purge(ChunkManager* chunk_manager);
   370   // If an allocation doesn't fit in the current node a new node is created.
   371   // Allocate chunks out of the remaining committed space in this node
   372   // to avoid wasting that memory.
   373   // This always adds up because all the chunk sizes are multiples of
   374   // the smallest chunk size.
   375   void retire(ChunkManager* chunk_manager);
   377 #ifdef ASSERT
   378   // Debug support
   379   void mangle();
   380 #endif
   382   void print_on(outputStream* st) const;
   383 };
   385 #define assert_is_ptr_aligned(ptr, alignment) \
   386   assert(is_ptr_aligned(ptr, alignment),      \
   387     err_msg(PTR_FORMAT " is not aligned to "  \
   388       SIZE_FORMAT, ptr, alignment))
   390 #define assert_is_size_aligned(size, alignment) \
   391   assert(is_size_aligned(size, alignment),      \
   392     err_msg(SIZE_FORMAT " is not aligned to "   \
   393        SIZE_FORMAT, size, alignment))
   396 // Decide if large pages should be committed when the memory is reserved.
   397 static bool should_commit_large_pages_when_reserving(size_t bytes) {
   398   if (UseLargePages && UseLargePagesInMetaspace && !os::can_commit_large_page_memory()) {
   399     size_t words = bytes / BytesPerWord;
   400     bool is_class = false; // We never reserve large pages for the class space.
   401     if (MetaspaceGC::can_expand(words, is_class) &&
   402         MetaspaceGC::allowed_expansion() >= words) {
   403       return true;
   404     }
   405   }
   407   return false;
   408 }
   410   // byte_size is the size of the associated virtualspace.
   411 VirtualSpaceNode::VirtualSpaceNode(size_t bytes) : _top(NULL), _next(NULL), _rs(), _container_count(0) {
   412   assert_is_size_aligned(bytes, Metaspace::reserve_alignment());
   414   // This allocates memory with mmap.  For DumpSharedspaces, try to reserve
   415   // configurable address, generally at the top of the Java heap so other
   416   // memory addresses don't conflict.
   417   if (DumpSharedSpaces) {
   418     bool large_pages = false; // No large pages when dumping the CDS archive.
   419     char* shared_base = (char*)align_ptr_up((char*)SharedBaseAddress, Metaspace::reserve_alignment());
   421     _rs = ReservedSpace(bytes, Metaspace::reserve_alignment(), large_pages, shared_base, 0);
   422     if (_rs.is_reserved()) {
   423       assert(shared_base == 0 || _rs.base() == shared_base, "should match");
   424     } else {
   425       // Get a mmap region anywhere if the SharedBaseAddress fails.
   426       _rs = ReservedSpace(bytes, Metaspace::reserve_alignment(), large_pages);
   427     }
   428     MetaspaceShared::set_shared_rs(&_rs);
   429   } else {
   430     bool large_pages = should_commit_large_pages_when_reserving(bytes);
   432     _rs = ReservedSpace(bytes, Metaspace::reserve_alignment(), large_pages);
   433   }
   435   if (_rs.is_reserved()) {
   436     assert(_rs.base() != NULL, "Catch if we get a NULL address");
   437     assert(_rs.size() != 0, "Catch if we get a 0 size");
   438     assert_is_ptr_aligned(_rs.base(), Metaspace::reserve_alignment());
   439     assert_is_size_aligned(_rs.size(), Metaspace::reserve_alignment());
   441     MemTracker::record_virtual_memory_type((address)_rs.base(), mtClass);
   442   }
   443 }
   445 void VirtualSpaceNode::purge(ChunkManager* chunk_manager) {
   446   Metachunk* chunk = first_chunk();
   447   Metachunk* invalid_chunk = (Metachunk*) top();
   448   while (chunk < invalid_chunk ) {
   449     assert(chunk->is_tagged_free(), "Should be tagged free");
   450     MetaWord* next = ((MetaWord*)chunk) + chunk->word_size();
   451     chunk_manager->remove_chunk(chunk);
   452     assert(chunk->next() == NULL &&
   453            chunk->prev() == NULL,
   454            "Was not removed from its list");
   455     chunk = (Metachunk*) next;
   456   }
   457 }
   459 #ifdef ASSERT
   460 uint VirtualSpaceNode::container_count_slow() {
   461   uint count = 0;
   462   Metachunk* chunk = first_chunk();
   463   Metachunk* invalid_chunk = (Metachunk*) top();
   464   while (chunk < invalid_chunk ) {
   465     MetaWord* next = ((MetaWord*)chunk) + chunk->word_size();
   466     // Don't count the chunks on the free lists.  Those are
   467     // still part of the VirtualSpaceNode but not currently
   468     // counted.
   469     if (!chunk->is_tagged_free()) {
   470       count++;
   471     }
   472     chunk = (Metachunk*) next;
   473   }
   474   return count;
   475 }
   476 #endif
   478 // List of VirtualSpaces for metadata allocation.
   479 class VirtualSpaceList : public CHeapObj<mtClass> {
   480   friend class VirtualSpaceNode;
   482   enum VirtualSpaceSizes {
   483     VirtualSpaceSize = 256 * K
   484   };
   486   // Head of the list
   487   VirtualSpaceNode* _virtual_space_list;
   488   // virtual space currently being used for allocations
   489   VirtualSpaceNode* _current_virtual_space;
   491   // Is this VirtualSpaceList used for the compressed class space
   492   bool _is_class;
   494   // Sum of reserved and committed memory in the virtual spaces
   495   size_t _reserved_words;
   496   size_t _committed_words;
   498   // Number of virtual spaces
   499   size_t _virtual_space_count;
   501   ~VirtualSpaceList();
   503   VirtualSpaceNode* virtual_space_list() const { return _virtual_space_list; }
   505   void set_virtual_space_list(VirtualSpaceNode* v) {
   506     _virtual_space_list = v;
   507   }
   508   void set_current_virtual_space(VirtualSpaceNode* v) {
   509     _current_virtual_space = v;
   510   }
   512   void link_vs(VirtualSpaceNode* new_entry);
   514   // Get another virtual space and add it to the list.  This
   515   // is typically prompted by a failed attempt to allocate a chunk
   516   // and is typically followed by the allocation of a chunk.
   517   bool create_new_virtual_space(size_t vs_word_size);
   519   // Chunk up the unused committed space in the current
   520   // virtual space and add the chunks to the free list.
   521   void retire_current_virtual_space();
   523  public:
   524   VirtualSpaceList(size_t word_size);
   525   VirtualSpaceList(ReservedSpace rs);
   527   size_t free_bytes();
   529   Metachunk* get_new_chunk(size_t word_size,
   530                            size_t grow_chunks_by_words,
   531                            size_t medium_chunk_bunch);
   533   bool expand_node_by(VirtualSpaceNode* node,
   534                       size_t min_words,
   535                       size_t preferred_words);
   537   bool expand_by(size_t min_words,
   538                  size_t preferred_words);
   540   VirtualSpaceNode* current_virtual_space() {
   541     return _current_virtual_space;
   542   }
   544   bool is_class() const { return _is_class; }
   546   bool initialization_succeeded() { return _virtual_space_list != NULL; }
   548   size_t reserved_words()  { return _reserved_words; }
   549   size_t reserved_bytes()  { return reserved_words() * BytesPerWord; }
   550   size_t committed_words() { return _committed_words; }
   551   size_t committed_bytes() { return committed_words() * BytesPerWord; }
   553   void inc_reserved_words(size_t v);
   554   void dec_reserved_words(size_t v);
   555   void inc_committed_words(size_t v);
   556   void dec_committed_words(size_t v);
   557   void inc_virtual_space_count();
   558   void dec_virtual_space_count();
   560   bool contains(const void* ptr);
   562   // Unlink empty VirtualSpaceNodes and free it.
   563   void purge(ChunkManager* chunk_manager);
   565   void print_on(outputStream* st) const;
   567   class VirtualSpaceListIterator : public StackObj {
   568     VirtualSpaceNode* _virtual_spaces;
   569    public:
   570     VirtualSpaceListIterator(VirtualSpaceNode* virtual_spaces) :
   571       _virtual_spaces(virtual_spaces) {}
   573     bool repeat() {
   574       return _virtual_spaces != NULL;
   575     }
   577     VirtualSpaceNode* get_next() {
   578       VirtualSpaceNode* result = _virtual_spaces;
   579       if (_virtual_spaces != NULL) {
   580         _virtual_spaces = _virtual_spaces->next();
   581       }
   582       return result;
   583     }
   584   };
   585 };
   587 class Metadebug : AllStatic {
   588   // Debugging support for Metaspaces
   589   static int _allocation_fail_alot_count;
   591  public:
   593   static void init_allocation_fail_alot_count();
   594 #ifdef ASSERT
   595   static bool test_metadata_failure();
   596 #endif
   597 };
   599 int Metadebug::_allocation_fail_alot_count = 0;
   601 //  SpaceManager - used by Metaspace to handle allocations
   602 class SpaceManager : public CHeapObj<mtClass> {
   603   friend class Metaspace;
   604   friend class Metadebug;
   606  private:
   608   // protects allocations
   609   Mutex* const _lock;
   611   // Type of metadata allocated.
   612   Metaspace::MetadataType _mdtype;
   614   // List of chunks in use by this SpaceManager.  Allocations
   615   // are done from the current chunk.  The list is used for deallocating
   616   // chunks when the SpaceManager is freed.
   617   Metachunk* _chunks_in_use[NumberOfInUseLists];
   618   Metachunk* _current_chunk;
   620   // Number of small chunks to allocate to a manager
   621   // If class space manager, small chunks are unlimited
   622   static uint const _small_chunk_limit;
   624   // Sum of all space in allocated chunks
   625   size_t _allocated_blocks_words;
   627   // Sum of all allocated chunks
   628   size_t _allocated_chunks_words;
   629   size_t _allocated_chunks_count;
   631   // Free lists of blocks are per SpaceManager since they
   632   // are assumed to be in chunks in use by the SpaceManager
   633   // and all chunks in use by a SpaceManager are freed when
   634   // the class loader using the SpaceManager is collected.
   635   BlockFreelist _block_freelists;
   637   // protects virtualspace and chunk expansions
   638   static const char*  _expand_lock_name;
   639   static const int    _expand_lock_rank;
   640   static Mutex* const _expand_lock;
   642  private:
   643   // Accessors
   644   Metachunk* chunks_in_use(ChunkIndex index) const { return _chunks_in_use[index]; }
   645   void set_chunks_in_use(ChunkIndex index, Metachunk* v) {
   646     _chunks_in_use[index] = v;
   647   }
   649   BlockFreelist* block_freelists() const {
   650     return (BlockFreelist*) &_block_freelists;
   651   }
   653   Metaspace::MetadataType mdtype() { return _mdtype; }
   655   VirtualSpaceList* vs_list()   const { return Metaspace::get_space_list(_mdtype); }
   656   ChunkManager* chunk_manager() const { return Metaspace::get_chunk_manager(_mdtype); }
   658   Metachunk* current_chunk() const { return _current_chunk; }
   659   void set_current_chunk(Metachunk* v) {
   660     _current_chunk = v;
   661   }
   663   Metachunk* find_current_chunk(size_t word_size);
   665   // Add chunk to the list of chunks in use
   666   void add_chunk(Metachunk* v, bool make_current);
   667   void retire_current_chunk();
   669   Mutex* lock() const { return _lock; }
   671   const char* chunk_size_name(ChunkIndex index) const;
   673  protected:
   674   void initialize();
   676  public:
   677   SpaceManager(Metaspace::MetadataType mdtype,
   678                Mutex* lock);
   679   ~SpaceManager();
   681   enum ChunkMultiples {
   682     MediumChunkMultiple = 4
   683   };
   685   bool is_class() { return _mdtype == Metaspace::ClassType; }
   687   // Accessors
   688   size_t specialized_chunk_size() { return (size_t) is_class() ? ClassSpecializedChunk : SpecializedChunk; }
   689   size_t small_chunk_size()       { return (size_t) is_class() ? ClassSmallChunk : SmallChunk; }
   690   size_t medium_chunk_size()      { return (size_t) is_class() ? ClassMediumChunk : MediumChunk; }
   691   size_t medium_chunk_bunch()     { return medium_chunk_size() * MediumChunkMultiple; }
   693   size_t smallest_chunk_size()  { return specialized_chunk_size(); }
   695   size_t allocated_blocks_words() const { return _allocated_blocks_words; }
   696   size_t allocated_blocks_bytes() const { return _allocated_blocks_words * BytesPerWord; }
   697   size_t allocated_chunks_words() const { return _allocated_chunks_words; }
   698   size_t allocated_chunks_count() const { return _allocated_chunks_count; }
   700   bool is_humongous(size_t word_size) { return word_size > medium_chunk_size(); }
   702   static Mutex* expand_lock() { return _expand_lock; }
   704   // Increment the per Metaspace and global running sums for Metachunks
   705   // by the given size.  This is used when a Metachunk to added to
   706   // the in-use list.
   707   void inc_size_metrics(size_t words);
   708   // Increment the per Metaspace and global running sums Metablocks by the given
   709   // size.  This is used when a Metablock is allocated.
   710   void inc_used_metrics(size_t words);
   711   // Delete the portion of the running sums for this SpaceManager. That is,
   712   // the globals running sums for the Metachunks and Metablocks are
   713   // decremented for all the Metachunks in-use by this SpaceManager.
   714   void dec_total_from_size_metrics();
   716   // Set the sizes for the initial chunks.
   717   void get_initial_chunk_sizes(Metaspace::MetaspaceType type,
   718                                size_t* chunk_word_size,
   719                                size_t* class_chunk_word_size);
   721   size_t sum_capacity_in_chunks_in_use() const;
   722   size_t sum_used_in_chunks_in_use() const;
   723   size_t sum_free_in_chunks_in_use() const;
   724   size_t sum_waste_in_chunks_in_use() const;
   725   size_t sum_waste_in_chunks_in_use(ChunkIndex index ) const;
   727   size_t sum_count_in_chunks_in_use();
   728   size_t sum_count_in_chunks_in_use(ChunkIndex i);
   730   Metachunk* get_new_chunk(size_t word_size, size_t grow_chunks_by_words);
   732   // Block allocation and deallocation.
   733   // Allocates a block from the current chunk
   734   MetaWord* allocate(size_t word_size);
   736   // Helper for allocations
   737   MetaWord* allocate_work(size_t word_size);
   739   // Returns a block to the per manager freelist
   740   void deallocate(MetaWord* p, size_t word_size);
   742   // Based on the allocation size and a minimum chunk size,
   743   // returned chunk size (for expanding space for chunk allocation).
   744   size_t calc_chunk_size(size_t allocation_word_size);
   746   // Called when an allocation from the current chunk fails.
   747   // Gets a new chunk (may require getting a new virtual space),
   748   // and allocates from that chunk.
   749   MetaWord* grow_and_allocate(size_t word_size);
   751   // Notify memory usage to MemoryService.
   752   void track_metaspace_memory_usage();
   754   // debugging support.
   756   void dump(outputStream* const out) const;
   757   void print_on(outputStream* st) const;
   758   void locked_print_chunks_in_use_on(outputStream* st) const;
   760   void verify();
   761   void verify_chunk_size(Metachunk* chunk);
   762   NOT_PRODUCT(void mangle_freed_chunks();)
   763 #ifdef ASSERT
   764   void verify_allocated_blocks_words();
   765 #endif
   767   size_t get_raw_word_size(size_t word_size) {
   768     size_t byte_size = word_size * BytesPerWord;
   770     size_t raw_bytes_size = MAX2(byte_size, sizeof(Metablock));
   771     raw_bytes_size = align_size_up(raw_bytes_size, Metachunk::object_alignment());
   773     size_t raw_word_size = raw_bytes_size / BytesPerWord;
   774     assert(raw_word_size * BytesPerWord == raw_bytes_size, "Size problem");
   776     return raw_word_size;
   777   }
   778 };
   780 uint const SpaceManager::_small_chunk_limit = 4;
   782 const char* SpaceManager::_expand_lock_name =
   783   "SpaceManager chunk allocation lock";
   784 const int SpaceManager::_expand_lock_rank = Monitor::leaf - 1;
   785 Mutex* const SpaceManager::_expand_lock =
   786   new Mutex(SpaceManager::_expand_lock_rank,
   787             SpaceManager::_expand_lock_name,
   788             Mutex::_allow_vm_block_flag);
   790 void VirtualSpaceNode::inc_container_count() {
   791   assert_lock_strong(SpaceManager::expand_lock());
   792   _container_count++;
   793   assert(_container_count == container_count_slow(),
   794          err_msg("Inconsistency in countainer_count _container_count " SIZE_FORMAT
   795                  " container_count_slow() " SIZE_FORMAT,
   796                  _container_count, container_count_slow()));
   797 }
   799 void VirtualSpaceNode::dec_container_count() {
   800   assert_lock_strong(SpaceManager::expand_lock());
   801   _container_count--;
   802 }
   804 #ifdef ASSERT
   805 void VirtualSpaceNode::verify_container_count() {
   806   assert(_container_count == container_count_slow(),
   807     err_msg("Inconsistency in countainer_count _container_count " SIZE_FORMAT
   808             " container_count_slow() " SIZE_FORMAT, _container_count, container_count_slow()));
   809 }
   810 #endif
   812 // BlockFreelist methods
   814 BlockFreelist::BlockFreelist() : _dictionary(NULL) {}
   816 BlockFreelist::~BlockFreelist() {
   817   if (_dictionary != NULL) {
   818     if (Verbose && TraceMetadataChunkAllocation) {
   819       _dictionary->print_free_lists(gclog_or_tty);
   820     }
   821     delete _dictionary;
   822   }
   823 }
   825 void BlockFreelist::return_block(MetaWord* p, size_t word_size) {
   826   Metablock* free_chunk = ::new (p) Metablock(word_size);
   827   if (dictionary() == NULL) {
   828    _dictionary = new BlockTreeDictionary();
   829   }
   830   dictionary()->return_chunk(free_chunk);
   831 }
   833 MetaWord* BlockFreelist::get_block(size_t word_size) {
   834   if (dictionary() == NULL) {
   835     return NULL;
   836   }
   838   if (word_size < TreeChunk<Metablock, FreeList<Metablock> >::min_size()) {
   839     // Dark matter.  Too small for dictionary.
   840     return NULL;
   841   }
   843   Metablock* free_block =
   844     dictionary()->get_chunk(word_size, FreeBlockDictionary<Metablock>::atLeast);
   845   if (free_block == NULL) {
   846     return NULL;
   847   }
   849   const size_t block_size = free_block->size();
   850   if (block_size > WasteMultiplier * word_size) {
   851     return_block((MetaWord*)free_block, block_size);
   852     return NULL;
   853   }
   855   MetaWord* new_block = (MetaWord*)free_block;
   856   assert(block_size >= word_size, "Incorrect size of block from freelist");
   857   const size_t unused = block_size - word_size;
   858   if (unused >= TreeChunk<Metablock, FreeList<Metablock> >::min_size()) {
   859     return_block(new_block + word_size, unused);
   860   }
   862   return new_block;
   863 }
   865 void BlockFreelist::print_on(outputStream* st) const {
   866   if (dictionary() == NULL) {
   867     return;
   868   }
   869   dictionary()->print_free_lists(st);
   870 }
   872 // VirtualSpaceNode methods
   874 VirtualSpaceNode::~VirtualSpaceNode() {
   875   _rs.release();
   876 #ifdef ASSERT
   877   size_t word_size = sizeof(*this) / BytesPerWord;
   878   Copy::fill_to_words((HeapWord*) this, word_size, 0xf1f1f1f1);
   879 #endif
   880 }
   882 size_t VirtualSpaceNode::used_words_in_vs() const {
   883   return pointer_delta(top(), bottom(), sizeof(MetaWord));
   884 }
   886 // Space committed in the VirtualSpace
   887 size_t VirtualSpaceNode::capacity_words_in_vs() const {
   888   return pointer_delta(end(), bottom(), sizeof(MetaWord));
   889 }
   891 size_t VirtualSpaceNode::free_words_in_vs() const {
   892   return pointer_delta(end(), top(), sizeof(MetaWord));
   893 }
   895 // Allocates the chunk from the virtual space only.
   896 // This interface is also used internally for debugging.  Not all
   897 // chunks removed here are necessarily used for allocation.
   898 Metachunk* VirtualSpaceNode::take_from_committed(size_t chunk_word_size) {
   899   // Bottom of the new chunk
   900   MetaWord* chunk_limit = top();
   901   assert(chunk_limit != NULL, "Not safe to call this method");
   903   // The virtual spaces are always expanded by the
   904   // commit granularity to enforce the following condition.
   905   // Without this the is_available check will not work correctly.
   906   assert(_virtual_space.committed_size() == _virtual_space.actual_committed_size(),
   907       "The committed memory doesn't match the expanded memory.");
   909   if (!is_available(chunk_word_size)) {
   910     if (TraceMetadataChunkAllocation) {
   911       gclog_or_tty->print("VirtualSpaceNode::take_from_committed() not available %d words ", chunk_word_size);
   912       // Dump some information about the virtual space that is nearly full
   913       print_on(gclog_or_tty);
   914     }
   915     return NULL;
   916   }
   918   // Take the space  (bump top on the current virtual space).
   919   inc_top(chunk_word_size);
   921   // Initialize the chunk
   922   Metachunk* result = ::new (chunk_limit) Metachunk(chunk_word_size, this);
   923   return result;
   924 }
   927 // Expand the virtual space (commit more of the reserved space)
   928 bool VirtualSpaceNode::expand_by(size_t min_words, size_t preferred_words) {
   929   size_t min_bytes = min_words * BytesPerWord;
   930   size_t preferred_bytes = preferred_words * BytesPerWord;
   932   size_t uncommitted = virtual_space()->reserved_size() - virtual_space()->actual_committed_size();
   934   if (uncommitted < min_bytes) {
   935     return false;
   936   }
   938   size_t commit = MIN2(preferred_bytes, uncommitted);
   939   bool result = virtual_space()->expand_by(commit, false);
   941   assert(result, "Failed to commit memory");
   943   return result;
   944 }
   946 Metachunk* VirtualSpaceNode::get_chunk_vs(size_t chunk_word_size) {
   947   assert_lock_strong(SpaceManager::expand_lock());
   948   Metachunk* result = take_from_committed(chunk_word_size);
   949   if (result != NULL) {
   950     inc_container_count();
   951   }
   952   return result;
   953 }
   955 bool VirtualSpaceNode::initialize() {
   957   if (!_rs.is_reserved()) {
   958     return false;
   959   }
   961   // These are necessary restriction to make sure that the virtual space always
   962   // grows in steps of Metaspace::commit_alignment(). If both base and size are
   963   // aligned only the middle alignment of the VirtualSpace is used.
   964   assert_is_ptr_aligned(_rs.base(), Metaspace::commit_alignment());
   965   assert_is_size_aligned(_rs.size(), Metaspace::commit_alignment());
   967   // ReservedSpaces marked as special will have the entire memory
   968   // pre-committed. Setting a committed size will make sure that
   969   // committed_size and actual_committed_size agrees.
   970   size_t pre_committed_size = _rs.special() ? _rs.size() : 0;
   972   bool result = virtual_space()->initialize_with_granularity(_rs, pre_committed_size,
   973                                             Metaspace::commit_alignment());
   974   if (result) {
   975     assert(virtual_space()->committed_size() == virtual_space()->actual_committed_size(),
   976         "Checking that the pre-committed memory was registered by the VirtualSpace");
   978     set_top((MetaWord*)virtual_space()->low());
   979     set_reserved(MemRegion((HeapWord*)_rs.base(),
   980                  (HeapWord*)(_rs.base() + _rs.size())));
   982     assert(reserved()->start() == (HeapWord*) _rs.base(),
   983       err_msg("Reserved start was not set properly " PTR_FORMAT
   984         " != " PTR_FORMAT, reserved()->start(), _rs.base()));
   985     assert(reserved()->word_size() == _rs.size() / BytesPerWord,
   986       err_msg("Reserved size was not set properly " SIZE_FORMAT
   987         " != " SIZE_FORMAT, reserved()->word_size(),
   988         _rs.size() / BytesPerWord));
   989   }
   991   return result;
   992 }
   994 void VirtualSpaceNode::print_on(outputStream* st) const {
   995   size_t used = used_words_in_vs();
   996   size_t capacity = capacity_words_in_vs();
   997   VirtualSpace* vs = virtual_space();
   998   st->print_cr("   space @ " PTR_FORMAT " " SIZE_FORMAT "K, %3d%% used "
   999            "[" PTR_FORMAT ", " PTR_FORMAT ", "
  1000            PTR_FORMAT ", " PTR_FORMAT ")",
  1001            vs, capacity / K,
  1002            capacity == 0 ? 0 : used * 100 / capacity,
  1003            bottom(), top(), end(),
  1004            vs->high_boundary());
  1007 #ifdef ASSERT
  1008 void VirtualSpaceNode::mangle() {
  1009   size_t word_size = capacity_words_in_vs();
  1010   Copy::fill_to_words((HeapWord*) low(), word_size, 0xf1f1f1f1);
  1012 #endif // ASSERT
  1014 // VirtualSpaceList methods
  1015 // Space allocated from the VirtualSpace
  1017 VirtualSpaceList::~VirtualSpaceList() {
  1018   VirtualSpaceListIterator iter(virtual_space_list());
  1019   while (iter.repeat()) {
  1020     VirtualSpaceNode* vsl = iter.get_next();
  1021     delete vsl;
  1025 void VirtualSpaceList::inc_reserved_words(size_t v) {
  1026   assert_lock_strong(SpaceManager::expand_lock());
  1027   _reserved_words = _reserved_words + v;
  1029 void VirtualSpaceList::dec_reserved_words(size_t v) {
  1030   assert_lock_strong(SpaceManager::expand_lock());
  1031   _reserved_words = _reserved_words - v;
  1034 #define assert_committed_below_limit()                             \
  1035   assert(MetaspaceAux::committed_bytes() <= MaxMetaspaceSize,      \
  1036       err_msg("Too much committed memory. Committed: " SIZE_FORMAT \
  1037               " limit (MaxMetaspaceSize): " SIZE_FORMAT,           \
  1038           MetaspaceAux::committed_bytes(), MaxMetaspaceSize));
  1040 void VirtualSpaceList::inc_committed_words(size_t v) {
  1041   assert_lock_strong(SpaceManager::expand_lock());
  1042   _committed_words = _committed_words + v;
  1044   assert_committed_below_limit();
  1046 void VirtualSpaceList::dec_committed_words(size_t v) {
  1047   assert_lock_strong(SpaceManager::expand_lock());
  1048   _committed_words = _committed_words - v;
  1050   assert_committed_below_limit();
  1053 void VirtualSpaceList::inc_virtual_space_count() {
  1054   assert_lock_strong(SpaceManager::expand_lock());
  1055   _virtual_space_count++;
  1057 void VirtualSpaceList::dec_virtual_space_count() {
  1058   assert_lock_strong(SpaceManager::expand_lock());
  1059   _virtual_space_count--;
  1062 void ChunkManager::remove_chunk(Metachunk* chunk) {
  1063   size_t word_size = chunk->word_size();
  1064   ChunkIndex index = list_index(word_size);
  1065   if (index != HumongousIndex) {
  1066     free_chunks(index)->remove_chunk(chunk);
  1067   } else {
  1068     humongous_dictionary()->remove_chunk(chunk);
  1071   // Chunk is being removed from the chunks free list.
  1072   dec_free_chunks_total(chunk->word_size());
  1075 // Walk the list of VirtualSpaceNodes and delete
  1076 // nodes with a 0 container_count.  Remove Metachunks in
  1077 // the node from their respective freelists.
  1078 void VirtualSpaceList::purge(ChunkManager* chunk_manager) {
  1079   assert(SafepointSynchronize::is_at_safepoint(), "must be called at safepoint for contains to work");
  1080   assert_lock_strong(SpaceManager::expand_lock());
  1081   // Don't use a VirtualSpaceListIterator because this
  1082   // list is being changed and a straightforward use of an iterator is not safe.
  1083   VirtualSpaceNode* purged_vsl = NULL;
  1084   VirtualSpaceNode* prev_vsl = virtual_space_list();
  1085   VirtualSpaceNode* next_vsl = prev_vsl;
  1086   while (next_vsl != NULL) {
  1087     VirtualSpaceNode* vsl = next_vsl;
  1088     next_vsl = vsl->next();
  1089     // Don't free the current virtual space since it will likely
  1090     // be needed soon.
  1091     if (vsl->container_count() == 0 && vsl != current_virtual_space()) {
  1092       // Unlink it from the list
  1093       if (prev_vsl == vsl) {
  1094         // This is the case of the current node being the first node.
  1095         assert(vsl == virtual_space_list(), "Expected to be the first node");
  1096         set_virtual_space_list(vsl->next());
  1097       } else {
  1098         prev_vsl->set_next(vsl->next());
  1101       vsl->purge(chunk_manager);
  1102       dec_reserved_words(vsl->reserved_words());
  1103       dec_committed_words(vsl->committed_words());
  1104       dec_virtual_space_count();
  1105       purged_vsl = vsl;
  1106       delete vsl;
  1107     } else {
  1108       prev_vsl = vsl;
  1111 #ifdef ASSERT
  1112   if (purged_vsl != NULL) {
  1113     // List should be stable enough to use an iterator here.
  1114     VirtualSpaceListIterator iter(virtual_space_list());
  1115     while (iter.repeat()) {
  1116       VirtualSpaceNode* vsl = iter.get_next();
  1117       assert(vsl != purged_vsl, "Purge of vsl failed");
  1120 #endif
  1124 // This function looks at the mmap regions in the metaspace without locking.
  1125 // The chunks are added with store ordering and not deleted except for at
  1126 // unloading time during a safepoint.
  1127 bool VirtualSpaceList::contains(const void* ptr) {
  1128   // List should be stable enough to use an iterator here because removing virtual
  1129   // space nodes is only allowed at a safepoint.
  1130   VirtualSpaceListIterator iter(virtual_space_list());
  1131   while (iter.repeat()) {
  1132     VirtualSpaceNode* vsn = iter.get_next();
  1133     if (vsn->contains(ptr)) {
  1134       return true;
  1137   return false;
  1140 void VirtualSpaceList::retire_current_virtual_space() {
  1141   assert_lock_strong(SpaceManager::expand_lock());
  1143   VirtualSpaceNode* vsn = current_virtual_space();
  1145   ChunkManager* cm = is_class() ? Metaspace::chunk_manager_class() :
  1146                                   Metaspace::chunk_manager_metadata();
  1148   vsn->retire(cm);
  1151 void VirtualSpaceNode::retire(ChunkManager* chunk_manager) {
  1152   for (int i = (int)MediumIndex; i >= (int)ZeroIndex; --i) {
  1153     ChunkIndex index = (ChunkIndex)i;
  1154     size_t chunk_size = chunk_manager->free_chunks(index)->size();
  1156     while (free_words_in_vs() >= chunk_size) {
  1157       DEBUG_ONLY(verify_container_count();)
  1158       Metachunk* chunk = get_chunk_vs(chunk_size);
  1159       assert(chunk != NULL, "allocation should have been successful");
  1161       chunk_manager->return_chunks(index, chunk);
  1162       chunk_manager->inc_free_chunks_total(chunk_size);
  1163       DEBUG_ONLY(verify_container_count();)
  1166   assert(free_words_in_vs() == 0, "should be empty now");
  1169 VirtualSpaceList::VirtualSpaceList(size_t word_size) :
  1170                                    _is_class(false),
  1171                                    _virtual_space_list(NULL),
  1172                                    _current_virtual_space(NULL),
  1173                                    _reserved_words(0),
  1174                                    _committed_words(0),
  1175                                    _virtual_space_count(0) {
  1176   MutexLockerEx cl(SpaceManager::expand_lock(),
  1177                    Mutex::_no_safepoint_check_flag);
  1178   create_new_virtual_space(word_size);
  1181 VirtualSpaceList::VirtualSpaceList(ReservedSpace rs) :
  1182                                    _is_class(true),
  1183                                    _virtual_space_list(NULL),
  1184                                    _current_virtual_space(NULL),
  1185                                    _reserved_words(0),
  1186                                    _committed_words(0),
  1187                                    _virtual_space_count(0) {
  1188   MutexLockerEx cl(SpaceManager::expand_lock(),
  1189                    Mutex::_no_safepoint_check_flag);
  1190   VirtualSpaceNode* class_entry = new VirtualSpaceNode(rs);
  1191   bool succeeded = class_entry->initialize();
  1192   if (succeeded) {
  1193     link_vs(class_entry);
  1197 size_t VirtualSpaceList::free_bytes() {
  1198   return virtual_space_list()->free_words_in_vs() * BytesPerWord;
  1201 // Allocate another meta virtual space and add it to the list.
  1202 bool VirtualSpaceList::create_new_virtual_space(size_t vs_word_size) {
  1203   assert_lock_strong(SpaceManager::expand_lock());
  1205   if (is_class()) {
  1206     assert(false, "We currently don't support more than one VirtualSpace for"
  1207                   " the compressed class space. The initialization of the"
  1208                   " CCS uses another code path and should not hit this path.");
  1209     return false;
  1212   if (vs_word_size == 0) {
  1213     assert(false, "vs_word_size should always be at least _reserve_alignment large.");
  1214     return false;
  1217   // Reserve the space
  1218   size_t vs_byte_size = vs_word_size * BytesPerWord;
  1219   assert_is_size_aligned(vs_byte_size, Metaspace::reserve_alignment());
  1221   // Allocate the meta virtual space and initialize it.
  1222   VirtualSpaceNode* new_entry = new VirtualSpaceNode(vs_byte_size);
  1223   if (!new_entry->initialize()) {
  1224     delete new_entry;
  1225     return false;
  1226   } else {
  1227     assert(new_entry->reserved_words() == vs_word_size,
  1228         "Reserved memory size differs from requested memory size");
  1229     // ensure lock-free iteration sees fully initialized node
  1230     OrderAccess::storestore();
  1231     link_vs(new_entry);
  1232     return true;
  1236 void VirtualSpaceList::link_vs(VirtualSpaceNode* new_entry) {
  1237   if (virtual_space_list() == NULL) {
  1238       set_virtual_space_list(new_entry);
  1239   } else {
  1240     current_virtual_space()->set_next(new_entry);
  1242   set_current_virtual_space(new_entry);
  1243   inc_reserved_words(new_entry->reserved_words());
  1244   inc_committed_words(new_entry->committed_words());
  1245   inc_virtual_space_count();
  1246 #ifdef ASSERT
  1247   new_entry->mangle();
  1248 #endif
  1249   if (TraceMetavirtualspaceAllocation && Verbose) {
  1250     VirtualSpaceNode* vsl = current_virtual_space();
  1251     vsl->print_on(gclog_or_tty);
  1255 bool VirtualSpaceList::expand_node_by(VirtualSpaceNode* node,
  1256                                       size_t min_words,
  1257                                       size_t preferred_words) {
  1258   size_t before = node->committed_words();
  1260   bool result = node->expand_by(min_words, preferred_words);
  1262   size_t after = node->committed_words();
  1264   // after and before can be the same if the memory was pre-committed.
  1265   assert(after >= before, "Inconsistency");
  1266   inc_committed_words(after - before);
  1268   return result;
  1271 bool VirtualSpaceList::expand_by(size_t min_words, size_t preferred_words) {
  1272   assert_is_size_aligned(min_words,       Metaspace::commit_alignment_words());
  1273   assert_is_size_aligned(preferred_words, Metaspace::commit_alignment_words());
  1274   assert(min_words <= preferred_words, "Invalid arguments");
  1276   if (!MetaspaceGC::can_expand(min_words, this->is_class())) {
  1277     return  false;
  1280   size_t allowed_expansion_words = MetaspaceGC::allowed_expansion();
  1281   if (allowed_expansion_words < min_words) {
  1282     return false;
  1285   size_t max_expansion_words = MIN2(preferred_words, allowed_expansion_words);
  1287   // Commit more memory from the the current virtual space.
  1288   bool vs_expanded = expand_node_by(current_virtual_space(),
  1289                                     min_words,
  1290                                     max_expansion_words);
  1291   if (vs_expanded) {
  1292     return true;
  1294   retire_current_virtual_space();
  1296   // Get another virtual space.
  1297   size_t grow_vs_words = MAX2((size_t)VirtualSpaceSize, preferred_words);
  1298   grow_vs_words = align_size_up(grow_vs_words, Metaspace::reserve_alignment_words());
  1300   if (create_new_virtual_space(grow_vs_words)) {
  1301     if (current_virtual_space()->is_pre_committed()) {
  1302       // The memory was pre-committed, so we are done here.
  1303       assert(min_words <= current_virtual_space()->committed_words(),
  1304           "The new VirtualSpace was pre-committed, so it"
  1305           "should be large enough to fit the alloc request.");
  1306       return true;
  1309     return expand_node_by(current_virtual_space(),
  1310                           min_words,
  1311                           max_expansion_words);
  1314   return false;
  1317 Metachunk* VirtualSpaceList::get_new_chunk(size_t word_size,
  1318                                            size_t grow_chunks_by_words,
  1319                                            size_t medium_chunk_bunch) {
  1321   // Allocate a chunk out of the current virtual space.
  1322   Metachunk* next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
  1324   if (next != NULL) {
  1325     return next;
  1328   // The expand amount is currently only determined by the requested sizes
  1329   // and not how much committed memory is left in the current virtual space.
  1331   size_t min_word_size       = align_size_up(grow_chunks_by_words, Metaspace::commit_alignment_words());
  1332   size_t preferred_word_size = align_size_up(medium_chunk_bunch,   Metaspace::commit_alignment_words());
  1333   if (min_word_size >= preferred_word_size) {
  1334     // Can happen when humongous chunks are allocated.
  1335     preferred_word_size = min_word_size;
  1338   bool expanded = expand_by(min_word_size, preferred_word_size);
  1339   if (expanded) {
  1340     next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
  1341     assert(next != NULL, "The allocation was expected to succeed after the expansion");
  1344    return next;
  1347 void VirtualSpaceList::print_on(outputStream* st) const {
  1348   if (TraceMetadataChunkAllocation && Verbose) {
  1349     VirtualSpaceListIterator iter(virtual_space_list());
  1350     while (iter.repeat()) {
  1351       VirtualSpaceNode* node = iter.get_next();
  1352       node->print_on(st);
  1357 // MetaspaceGC methods
  1359 // VM_CollectForMetadataAllocation is the vm operation used to GC.
  1360 // Within the VM operation after the GC the attempt to allocate the metadata
  1361 // should succeed.  If the GC did not free enough space for the metaspace
  1362 // allocation, the HWM is increased so that another virtualspace will be
  1363 // allocated for the metadata.  With perm gen the increase in the perm
  1364 // gen had bounds, MinMetaspaceExpansion and MaxMetaspaceExpansion.  The
  1365 // metaspace policy uses those as the small and large steps for the HWM.
  1366 //
  1367 // After the GC the compute_new_size() for MetaspaceGC is called to
  1368 // resize the capacity of the metaspaces.  The current implementation
  1369 // is based on the flags MinMetaspaceFreeRatio and MaxMetaspaceFreeRatio used
  1370 // to resize the Java heap by some GC's.  New flags can be implemented
  1371 // if really needed.  MinMetaspaceFreeRatio is used to calculate how much
  1372 // free space is desirable in the metaspace capacity to decide how much
  1373 // to increase the HWM.  MaxMetaspaceFreeRatio is used to decide how much
  1374 // free space is desirable in the metaspace capacity before decreasing
  1375 // the HWM.
  1377 // Calculate the amount to increase the high water mark (HWM).
  1378 // Increase by a minimum amount (MinMetaspaceExpansion) so that
  1379 // another expansion is not requested too soon.  If that is not
  1380 // enough to satisfy the allocation, increase by MaxMetaspaceExpansion.
  1381 // If that is still not enough, expand by the size of the allocation
  1382 // plus some.
  1383 size_t MetaspaceGC::delta_capacity_until_GC(size_t bytes) {
  1384   size_t min_delta = MinMetaspaceExpansion;
  1385   size_t max_delta = MaxMetaspaceExpansion;
  1386   size_t delta = align_size_up(bytes, Metaspace::commit_alignment());
  1388   if (delta <= min_delta) {
  1389     delta = min_delta;
  1390   } else if (delta <= max_delta) {
  1391     // Don't want to hit the high water mark on the next
  1392     // allocation so make the delta greater than just enough
  1393     // for this allocation.
  1394     delta = max_delta;
  1395   } else {
  1396     // This allocation is large but the next ones are probably not
  1397     // so increase by the minimum.
  1398     delta = delta + min_delta;
  1401   assert_is_size_aligned(delta, Metaspace::commit_alignment());
  1403   return delta;
  1406 size_t MetaspaceGC::capacity_until_GC() {
  1407   size_t value = (size_t)OrderAccess::load_ptr_acquire(&_capacity_until_GC);
  1408   assert(value >= MetaspaceSize, "Not initialied properly?");
  1409   return value;
  1412 size_t MetaspaceGC::inc_capacity_until_GC(size_t v) {
  1413   assert_is_size_aligned(v, Metaspace::commit_alignment());
  1415   return (size_t)Atomic::add_ptr(v, &_capacity_until_GC);
  1418 size_t MetaspaceGC::dec_capacity_until_GC(size_t v) {
  1419   assert_is_size_aligned(v, Metaspace::commit_alignment());
  1421   return (size_t)Atomic::add_ptr(-(intptr_t)v, &_capacity_until_GC);
  1424 bool MetaspaceGC::can_expand(size_t word_size, bool is_class) {
  1425   // Check if the compressed class space is full.
  1426   if (is_class && Metaspace::using_class_space()) {
  1427     size_t class_committed = MetaspaceAux::committed_bytes(Metaspace::ClassType);
  1428     if (class_committed + word_size * BytesPerWord > CompressedClassSpaceSize) {
  1429       return false;
  1433   // Check if the user has imposed a limit on the metaspace memory.
  1434   size_t committed_bytes = MetaspaceAux::committed_bytes();
  1435   if (committed_bytes + word_size * BytesPerWord > MaxMetaspaceSize) {
  1436     return false;
  1439   return true;
  1442 size_t MetaspaceGC::allowed_expansion() {
  1443   size_t committed_bytes = MetaspaceAux::committed_bytes();
  1445   size_t left_until_max  = MaxMetaspaceSize - committed_bytes;
  1447   // Always grant expansion if we are initiating the JVM,
  1448   // or if the GC_locker is preventing GCs.
  1449   if (!is_init_completed() || GC_locker::is_active_and_needs_gc()) {
  1450     return left_until_max / BytesPerWord;
  1453   size_t capacity_until_gc = capacity_until_GC();
  1455   if (capacity_until_gc <= committed_bytes) {
  1456     return 0;
  1459   size_t left_until_GC = capacity_until_gc - committed_bytes;
  1460   size_t left_to_commit = MIN2(left_until_GC, left_until_max);
  1462   return left_to_commit / BytesPerWord;
  1465 void MetaspaceGC::compute_new_size() {
  1466   assert(_shrink_factor <= 100, "invalid shrink factor");
  1467   uint current_shrink_factor = _shrink_factor;
  1468   _shrink_factor = 0;
  1470   const size_t used_after_gc = MetaspaceAux::capacity_bytes();
  1471   const size_t capacity_until_GC = MetaspaceGC::capacity_until_GC();
  1473   const double minimum_free_percentage = MinMetaspaceFreeRatio / 100.0;
  1474   const double maximum_used_percentage = 1.0 - minimum_free_percentage;
  1476   const double min_tmp = used_after_gc / maximum_used_percentage;
  1477   size_t minimum_desired_capacity =
  1478     (size_t)MIN2(min_tmp, double(max_uintx));
  1479   // Don't shrink less than the initial generation size
  1480   minimum_desired_capacity = MAX2(minimum_desired_capacity,
  1481                                   MetaspaceSize);
  1483   if (PrintGCDetails && Verbose) {
  1484     gclog_or_tty->print_cr("\nMetaspaceGC::compute_new_size: ");
  1485     gclog_or_tty->print_cr("  "
  1486                   "  minimum_free_percentage: %6.2f"
  1487                   "  maximum_used_percentage: %6.2f",
  1488                   minimum_free_percentage,
  1489                   maximum_used_percentage);
  1490     gclog_or_tty->print_cr("  "
  1491                   "   used_after_gc       : %6.1fKB",
  1492                   used_after_gc / (double) K);
  1496   size_t shrink_bytes = 0;
  1497   if (capacity_until_GC < minimum_desired_capacity) {
  1498     // If we have less capacity below the metaspace HWM, then
  1499     // increment the HWM.
  1500     size_t expand_bytes = minimum_desired_capacity - capacity_until_GC;
  1501     expand_bytes = align_size_up(expand_bytes, Metaspace::commit_alignment());
  1502     // Don't expand unless it's significant
  1503     if (expand_bytes >= MinMetaspaceExpansion) {
  1504       size_t new_capacity_until_GC = MetaspaceGC::inc_capacity_until_GC(expand_bytes);
  1505       Metaspace::tracer()->report_gc_threshold(capacity_until_GC,
  1506                                                new_capacity_until_GC,
  1507                                                MetaspaceGCThresholdUpdater::ComputeNewSize);
  1508       if (PrintGCDetails && Verbose) {
  1509         gclog_or_tty->print_cr("    expanding:"
  1510                       "  minimum_desired_capacity: %6.1fKB"
  1511                       "  expand_bytes: %6.1fKB"
  1512                       "  MinMetaspaceExpansion: %6.1fKB"
  1513                       "  new metaspace HWM:  %6.1fKB",
  1514                       minimum_desired_capacity / (double) K,
  1515                       expand_bytes / (double) K,
  1516                       MinMetaspaceExpansion / (double) K,
  1517                       new_capacity_until_GC / (double) K);
  1520     return;
  1523   // No expansion, now see if we want to shrink
  1524   // We would never want to shrink more than this
  1525   size_t max_shrink_bytes = capacity_until_GC - minimum_desired_capacity;
  1526   assert(max_shrink_bytes >= 0, err_msg("max_shrink_bytes " SIZE_FORMAT,
  1527     max_shrink_bytes));
  1529   // Should shrinking be considered?
  1530   if (MaxMetaspaceFreeRatio < 100) {
  1531     const double maximum_free_percentage = MaxMetaspaceFreeRatio / 100.0;
  1532     const double minimum_used_percentage = 1.0 - maximum_free_percentage;
  1533     const double max_tmp = used_after_gc / minimum_used_percentage;
  1534     size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(max_uintx));
  1535     maximum_desired_capacity = MAX2(maximum_desired_capacity,
  1536                                     MetaspaceSize);
  1537     if (PrintGCDetails && Verbose) {
  1538       gclog_or_tty->print_cr("  "
  1539                              "  maximum_free_percentage: %6.2f"
  1540                              "  minimum_used_percentage: %6.2f",
  1541                              maximum_free_percentage,
  1542                              minimum_used_percentage);
  1543       gclog_or_tty->print_cr("  "
  1544                              "  minimum_desired_capacity: %6.1fKB"
  1545                              "  maximum_desired_capacity: %6.1fKB",
  1546                              minimum_desired_capacity / (double) K,
  1547                              maximum_desired_capacity / (double) K);
  1550     assert(minimum_desired_capacity <= maximum_desired_capacity,
  1551            "sanity check");
  1553     if (capacity_until_GC > maximum_desired_capacity) {
  1554       // Capacity too large, compute shrinking size
  1555       shrink_bytes = capacity_until_GC - maximum_desired_capacity;
  1556       // We don't want shrink all the way back to initSize if people call
  1557       // System.gc(), because some programs do that between "phases" and then
  1558       // we'd just have to grow the heap up again for the next phase.  So we
  1559       // damp the shrinking: 0% on the first call, 10% on the second call, 40%
  1560       // on the third call, and 100% by the fourth call.  But if we recompute
  1561       // size without shrinking, it goes back to 0%.
  1562       shrink_bytes = shrink_bytes / 100 * current_shrink_factor;
  1564       shrink_bytes = align_size_down(shrink_bytes, Metaspace::commit_alignment());
  1566       assert(shrink_bytes <= max_shrink_bytes,
  1567         err_msg("invalid shrink size " SIZE_FORMAT " not <= " SIZE_FORMAT,
  1568           shrink_bytes, max_shrink_bytes));
  1569       if (current_shrink_factor == 0) {
  1570         _shrink_factor = 10;
  1571       } else {
  1572         _shrink_factor = MIN2(current_shrink_factor * 4, (uint) 100);
  1574       if (PrintGCDetails && Verbose) {
  1575         gclog_or_tty->print_cr("  "
  1576                       "  shrinking:"
  1577                       "  initSize: %.1fK"
  1578                       "  maximum_desired_capacity: %.1fK",
  1579                       MetaspaceSize / (double) K,
  1580                       maximum_desired_capacity / (double) K);
  1581         gclog_or_tty->print_cr("  "
  1582                       "  shrink_bytes: %.1fK"
  1583                       "  current_shrink_factor: %d"
  1584                       "  new shrink factor: %d"
  1585                       "  MinMetaspaceExpansion: %.1fK",
  1586                       shrink_bytes / (double) K,
  1587                       current_shrink_factor,
  1588                       _shrink_factor,
  1589                       MinMetaspaceExpansion / (double) K);
  1594   // Don't shrink unless it's significant
  1595   if (shrink_bytes >= MinMetaspaceExpansion &&
  1596       ((capacity_until_GC - shrink_bytes) >= MetaspaceSize)) {
  1597     size_t new_capacity_until_GC = MetaspaceGC::dec_capacity_until_GC(shrink_bytes);
  1598     Metaspace::tracer()->report_gc_threshold(capacity_until_GC,
  1599                                              new_capacity_until_GC,
  1600                                              MetaspaceGCThresholdUpdater::ComputeNewSize);
  1604 // Metadebug methods
  1606 void Metadebug::init_allocation_fail_alot_count() {
  1607   if (MetadataAllocationFailALot) {
  1608     _allocation_fail_alot_count =
  1609       1+(long)((double)MetadataAllocationFailALotInterval*os::random()/(max_jint+1.0));
  1613 #ifdef ASSERT
  1614 bool Metadebug::test_metadata_failure() {
  1615   if (MetadataAllocationFailALot &&
  1616       Threads::is_vm_complete()) {
  1617     if (_allocation_fail_alot_count > 0) {
  1618       _allocation_fail_alot_count--;
  1619     } else {
  1620       if (TraceMetadataChunkAllocation && Verbose) {
  1621         gclog_or_tty->print_cr("Metadata allocation failing for "
  1622                                "MetadataAllocationFailALot");
  1624       init_allocation_fail_alot_count();
  1625       return true;
  1628   return false;
  1630 #endif
  1632 // ChunkManager methods
  1634 size_t ChunkManager::free_chunks_total_words() {
  1635   return _free_chunks_total;
  1638 size_t ChunkManager::free_chunks_total_bytes() {
  1639   return free_chunks_total_words() * BytesPerWord;
  1642 size_t ChunkManager::free_chunks_count() {
  1643 #ifdef ASSERT
  1644   if (!UseConcMarkSweepGC && !SpaceManager::expand_lock()->is_locked()) {
  1645     MutexLockerEx cl(SpaceManager::expand_lock(),
  1646                      Mutex::_no_safepoint_check_flag);
  1647     // This lock is only needed in debug because the verification
  1648     // of the _free_chunks_totals walks the list of free chunks
  1649     slow_locked_verify_free_chunks_count();
  1651 #endif
  1652   return _free_chunks_count;
  1655 void ChunkManager::locked_verify_free_chunks_total() {
  1656   assert_lock_strong(SpaceManager::expand_lock());
  1657   assert(sum_free_chunks() == _free_chunks_total,
  1658     err_msg("_free_chunks_total " SIZE_FORMAT " is not the"
  1659            " same as sum " SIZE_FORMAT, _free_chunks_total,
  1660            sum_free_chunks()));
  1663 void ChunkManager::verify_free_chunks_total() {
  1664   MutexLockerEx cl(SpaceManager::expand_lock(),
  1665                      Mutex::_no_safepoint_check_flag);
  1666   locked_verify_free_chunks_total();
  1669 void ChunkManager::locked_verify_free_chunks_count() {
  1670   assert_lock_strong(SpaceManager::expand_lock());
  1671   assert(sum_free_chunks_count() == _free_chunks_count,
  1672     err_msg("_free_chunks_count " SIZE_FORMAT " is not the"
  1673            " same as sum " SIZE_FORMAT, _free_chunks_count,
  1674            sum_free_chunks_count()));
  1677 void ChunkManager::verify_free_chunks_count() {
  1678 #ifdef ASSERT
  1679   MutexLockerEx cl(SpaceManager::expand_lock(),
  1680                      Mutex::_no_safepoint_check_flag);
  1681   locked_verify_free_chunks_count();
  1682 #endif
  1685 void ChunkManager::verify() {
  1686   MutexLockerEx cl(SpaceManager::expand_lock(),
  1687                      Mutex::_no_safepoint_check_flag);
  1688   locked_verify();
  1691 void ChunkManager::locked_verify() {
  1692   locked_verify_free_chunks_count();
  1693   locked_verify_free_chunks_total();
  1696 void ChunkManager::locked_print_free_chunks(outputStream* st) {
  1697   assert_lock_strong(SpaceManager::expand_lock());
  1698   st->print_cr("Free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
  1699                 _free_chunks_total, _free_chunks_count);
  1702 void ChunkManager::locked_print_sum_free_chunks(outputStream* st) {
  1703   assert_lock_strong(SpaceManager::expand_lock());
  1704   st->print_cr("Sum free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
  1705                 sum_free_chunks(), sum_free_chunks_count());
  1707 ChunkList* ChunkManager::free_chunks(ChunkIndex index) {
  1708   return &_free_chunks[index];
  1711 // These methods that sum the free chunk lists are used in printing
  1712 // methods that are used in product builds.
  1713 size_t ChunkManager::sum_free_chunks() {
  1714   assert_lock_strong(SpaceManager::expand_lock());
  1715   size_t result = 0;
  1716   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
  1717     ChunkList* list = free_chunks(i);
  1719     if (list == NULL) {
  1720       continue;
  1723     result = result + list->count() * list->size();
  1725   result = result + humongous_dictionary()->total_size();
  1726   return result;
  1729 size_t ChunkManager::sum_free_chunks_count() {
  1730   assert_lock_strong(SpaceManager::expand_lock());
  1731   size_t count = 0;
  1732   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
  1733     ChunkList* list = free_chunks(i);
  1734     if (list == NULL) {
  1735       continue;
  1737     count = count + list->count();
  1739   count = count + humongous_dictionary()->total_free_blocks();
  1740   return count;
  1743 ChunkList* ChunkManager::find_free_chunks_list(size_t word_size) {
  1744   ChunkIndex index = list_index(word_size);
  1745   assert(index < HumongousIndex, "No humongous list");
  1746   return free_chunks(index);
  1749 Metachunk* ChunkManager::free_chunks_get(size_t word_size) {
  1750   assert_lock_strong(SpaceManager::expand_lock());
  1752   slow_locked_verify();
  1754   Metachunk* chunk = NULL;
  1755   if (list_index(word_size) != HumongousIndex) {
  1756     ChunkList* free_list = find_free_chunks_list(word_size);
  1757     assert(free_list != NULL, "Sanity check");
  1759     chunk = free_list->head();
  1761     if (chunk == NULL) {
  1762       return NULL;
  1765     // Remove the chunk as the head of the list.
  1766     free_list->remove_chunk(chunk);
  1768     if (TraceMetadataChunkAllocation && Verbose) {
  1769       gclog_or_tty->print_cr("ChunkManager::free_chunks_get: free_list "
  1770                              PTR_FORMAT " head " PTR_FORMAT " size " SIZE_FORMAT,
  1771                              free_list, chunk, chunk->word_size());
  1773   } else {
  1774     chunk = humongous_dictionary()->get_chunk(
  1775       word_size,
  1776       FreeBlockDictionary<Metachunk>::atLeast);
  1778     if (chunk == NULL) {
  1779       return NULL;
  1782     if (TraceMetadataHumongousAllocation) {
  1783       size_t waste = chunk->word_size() - word_size;
  1784       gclog_or_tty->print_cr("Free list allocate humongous chunk size "
  1785                              SIZE_FORMAT " for requested size " SIZE_FORMAT
  1786                              " waste " SIZE_FORMAT,
  1787                              chunk->word_size(), word_size, waste);
  1791   // Chunk is being removed from the chunks free list.
  1792   dec_free_chunks_total(chunk->word_size());
  1794   // Remove it from the links to this freelist
  1795   chunk->set_next(NULL);
  1796   chunk->set_prev(NULL);
  1797 #ifdef ASSERT
  1798   // Chunk is no longer on any freelist. Setting to false make container_count_slow()
  1799   // work.
  1800   chunk->set_is_tagged_free(false);
  1801 #endif
  1802   chunk->container()->inc_container_count();
  1804   slow_locked_verify();
  1805   return chunk;
  1808 Metachunk* ChunkManager::chunk_freelist_allocate(size_t word_size) {
  1809   assert_lock_strong(SpaceManager::expand_lock());
  1810   slow_locked_verify();
  1812   // Take from the beginning of the list
  1813   Metachunk* chunk = free_chunks_get(word_size);
  1814   if (chunk == NULL) {
  1815     return NULL;
  1818   assert((word_size <= chunk->word_size()) ||
  1819          list_index(chunk->word_size() == HumongousIndex),
  1820          "Non-humongous variable sized chunk");
  1821   if (TraceMetadataChunkAllocation) {
  1822     size_t list_count;
  1823     if (list_index(word_size) < HumongousIndex) {
  1824       ChunkList* list = find_free_chunks_list(word_size);
  1825       list_count = list->count();
  1826     } else {
  1827       list_count = humongous_dictionary()->total_count();
  1829     gclog_or_tty->print("ChunkManager::chunk_freelist_allocate: " PTR_FORMAT " chunk "
  1830                         PTR_FORMAT "  size " SIZE_FORMAT " count " SIZE_FORMAT " ",
  1831                         this, chunk, chunk->word_size(), list_count);
  1832     locked_print_free_chunks(gclog_or_tty);
  1835   return chunk;
  1838 void ChunkManager::print_on(outputStream* out) const {
  1839   if (PrintFLSStatistics != 0) {
  1840     const_cast<ChunkManager *>(this)->humongous_dictionary()->report_statistics();
  1844 // SpaceManager methods
  1846 void SpaceManager::get_initial_chunk_sizes(Metaspace::MetaspaceType type,
  1847                                            size_t* chunk_word_size,
  1848                                            size_t* class_chunk_word_size) {
  1849   switch (type) {
  1850   case Metaspace::BootMetaspaceType:
  1851     *chunk_word_size = Metaspace::first_chunk_word_size();
  1852     *class_chunk_word_size = Metaspace::first_class_chunk_word_size();
  1853     break;
  1854   case Metaspace::ROMetaspaceType:
  1855     *chunk_word_size = SharedReadOnlySize / wordSize;
  1856     *class_chunk_word_size = ClassSpecializedChunk;
  1857     break;
  1858   case Metaspace::ReadWriteMetaspaceType:
  1859     *chunk_word_size = SharedReadWriteSize / wordSize;
  1860     *class_chunk_word_size = ClassSpecializedChunk;
  1861     break;
  1862   case Metaspace::AnonymousMetaspaceType:
  1863   case Metaspace::ReflectionMetaspaceType:
  1864     *chunk_word_size = SpecializedChunk;
  1865     *class_chunk_word_size = ClassSpecializedChunk;
  1866     break;
  1867   default:
  1868     *chunk_word_size = SmallChunk;
  1869     *class_chunk_word_size = ClassSmallChunk;
  1870     break;
  1872   assert(*chunk_word_size != 0 && *class_chunk_word_size != 0,
  1873     err_msg("Initial chunks sizes bad: data  " SIZE_FORMAT
  1874             " class " SIZE_FORMAT,
  1875             *chunk_word_size, *class_chunk_word_size));
  1878 size_t SpaceManager::sum_free_in_chunks_in_use() const {
  1879   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1880   size_t free = 0;
  1881   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1882     Metachunk* chunk = chunks_in_use(i);
  1883     while (chunk != NULL) {
  1884       free += chunk->free_word_size();
  1885       chunk = chunk->next();
  1888   return free;
  1891 size_t SpaceManager::sum_waste_in_chunks_in_use() const {
  1892   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1893   size_t result = 0;
  1894   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1895    result += sum_waste_in_chunks_in_use(i);
  1898   return result;
  1901 size_t SpaceManager::sum_waste_in_chunks_in_use(ChunkIndex index) const {
  1902   size_t result = 0;
  1903   Metachunk* chunk = chunks_in_use(index);
  1904   // Count the free space in all the chunk but not the
  1905   // current chunk from which allocations are still being done.
  1906   while (chunk != NULL) {
  1907     if (chunk != current_chunk()) {
  1908       result += chunk->free_word_size();
  1910     chunk = chunk->next();
  1912   return result;
  1915 size_t SpaceManager::sum_capacity_in_chunks_in_use() const {
  1916   // For CMS use "allocated_chunks_words()" which does not need the
  1917   // Metaspace lock.  For the other collectors sum over the
  1918   // lists.  Use both methods as a check that "allocated_chunks_words()"
  1919   // is correct.  That is, sum_capacity_in_chunks() is too expensive
  1920   // to use in the product and allocated_chunks_words() should be used
  1921   // but allow for  checking that allocated_chunks_words() returns the same
  1922   // value as sum_capacity_in_chunks_in_use() which is the definitive
  1923   // answer.
  1924   if (UseConcMarkSweepGC) {
  1925     return allocated_chunks_words();
  1926   } else {
  1927     MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1928     size_t sum = 0;
  1929     for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1930       Metachunk* chunk = chunks_in_use(i);
  1931       while (chunk != NULL) {
  1932         sum += chunk->word_size();
  1933         chunk = chunk->next();
  1936   return sum;
  1940 size_t SpaceManager::sum_count_in_chunks_in_use() {
  1941   size_t count = 0;
  1942   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1943     count = count + sum_count_in_chunks_in_use(i);
  1946   return count;
  1949 size_t SpaceManager::sum_count_in_chunks_in_use(ChunkIndex i) {
  1950   size_t count = 0;
  1951   Metachunk* chunk = chunks_in_use(i);
  1952   while (chunk != NULL) {
  1953     count++;
  1954     chunk = chunk->next();
  1956   return count;
  1960 size_t SpaceManager::sum_used_in_chunks_in_use() const {
  1961   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1962   size_t used = 0;
  1963   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1964     Metachunk* chunk = chunks_in_use(i);
  1965     while (chunk != NULL) {
  1966       used += chunk->used_word_size();
  1967       chunk = chunk->next();
  1970   return used;
  1973 void SpaceManager::locked_print_chunks_in_use_on(outputStream* st) const {
  1975   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1976     Metachunk* chunk = chunks_in_use(i);
  1977     st->print("SpaceManager: %s " PTR_FORMAT,
  1978                  chunk_size_name(i), chunk);
  1979     if (chunk != NULL) {
  1980       st->print_cr(" free " SIZE_FORMAT,
  1981                    chunk->free_word_size());
  1982     } else {
  1983       st->print_cr("");
  1987   chunk_manager()->locked_print_free_chunks(st);
  1988   chunk_manager()->locked_print_sum_free_chunks(st);
  1991 size_t SpaceManager::calc_chunk_size(size_t word_size) {
  1993   // Decide between a small chunk and a medium chunk.  Up to
  1994   // _small_chunk_limit small chunks can be allocated but
  1995   // once a medium chunk has been allocated, no more small
  1996   // chunks will be allocated.
  1997   size_t chunk_word_size;
  1998   if (chunks_in_use(MediumIndex) == NULL &&
  1999       sum_count_in_chunks_in_use(SmallIndex) < _small_chunk_limit) {
  2000     chunk_word_size = (size_t) small_chunk_size();
  2001     if (word_size + Metachunk::overhead() > small_chunk_size()) {
  2002       chunk_word_size = medium_chunk_size();
  2004   } else {
  2005     chunk_word_size = medium_chunk_size();
  2008   // Might still need a humongous chunk.  Enforce
  2009   // humongous allocations sizes to be aligned up to
  2010   // the smallest chunk size.
  2011   size_t if_humongous_sized_chunk =
  2012     align_size_up(word_size + Metachunk::overhead(),
  2013                   smallest_chunk_size());
  2014   chunk_word_size =
  2015     MAX2((size_t) chunk_word_size, if_humongous_sized_chunk);
  2017   assert(!SpaceManager::is_humongous(word_size) ||
  2018          chunk_word_size == if_humongous_sized_chunk,
  2019          err_msg("Size calculation is wrong, word_size " SIZE_FORMAT
  2020                  " chunk_word_size " SIZE_FORMAT,
  2021                  word_size, chunk_word_size));
  2022   if (TraceMetadataHumongousAllocation &&
  2023       SpaceManager::is_humongous(word_size)) {
  2024     gclog_or_tty->print_cr("Metadata humongous allocation:");
  2025     gclog_or_tty->print_cr("  word_size " PTR_FORMAT, word_size);
  2026     gclog_or_tty->print_cr("  chunk_word_size " PTR_FORMAT,
  2027                            chunk_word_size);
  2028     gclog_or_tty->print_cr("    chunk overhead " PTR_FORMAT,
  2029                            Metachunk::overhead());
  2031   return chunk_word_size;
  2034 void SpaceManager::track_metaspace_memory_usage() {
  2035   if (is_init_completed()) {
  2036     if (is_class()) {
  2037       MemoryService::track_compressed_class_memory_usage();
  2039     MemoryService::track_metaspace_memory_usage();
  2043 MetaWord* SpaceManager::grow_and_allocate(size_t word_size) {
  2044   assert(vs_list()->current_virtual_space() != NULL,
  2045          "Should have been set");
  2046   assert(current_chunk() == NULL ||
  2047          current_chunk()->allocate(word_size) == NULL,
  2048          "Don't need to expand");
  2049   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  2051   if (TraceMetadataChunkAllocation && Verbose) {
  2052     size_t words_left = 0;
  2053     size_t words_used = 0;
  2054     if (current_chunk() != NULL) {
  2055       words_left = current_chunk()->free_word_size();
  2056       words_used = current_chunk()->used_word_size();
  2058     gclog_or_tty->print_cr("SpaceManager::grow_and_allocate for " SIZE_FORMAT
  2059                            " words " SIZE_FORMAT " words used " SIZE_FORMAT
  2060                            " words left",
  2061                             word_size, words_used, words_left);
  2064   // Get another chunk out of the virtual space
  2065   size_t grow_chunks_by_words = calc_chunk_size(word_size);
  2066   Metachunk* next = get_new_chunk(word_size, grow_chunks_by_words);
  2068   MetaWord* mem = NULL;
  2070   // If a chunk was available, add it to the in-use chunk list
  2071   // and do an allocation from it.
  2072   if (next != NULL) {
  2073     // Add to this manager's list of chunks in use.
  2074     add_chunk(next, false);
  2075     mem = next->allocate(word_size);
  2078   // Track metaspace memory usage statistic.
  2079   track_metaspace_memory_usage();
  2081   return mem;
  2084 void SpaceManager::print_on(outputStream* st) const {
  2086   for (ChunkIndex i = ZeroIndex;
  2087        i < NumberOfInUseLists ;
  2088        i = next_chunk_index(i) ) {
  2089     st->print_cr("  chunks_in_use " PTR_FORMAT " chunk size " PTR_FORMAT,
  2090                  chunks_in_use(i),
  2091                  chunks_in_use(i) == NULL ? 0 : chunks_in_use(i)->word_size());
  2093   st->print_cr("    waste:  Small " SIZE_FORMAT " Medium " SIZE_FORMAT
  2094                " Humongous " SIZE_FORMAT,
  2095                sum_waste_in_chunks_in_use(SmallIndex),
  2096                sum_waste_in_chunks_in_use(MediumIndex),
  2097                sum_waste_in_chunks_in_use(HumongousIndex));
  2098   // block free lists
  2099   if (block_freelists() != NULL) {
  2100     st->print_cr("total in block free lists " SIZE_FORMAT,
  2101       block_freelists()->total_size());
  2105 SpaceManager::SpaceManager(Metaspace::MetadataType mdtype,
  2106                            Mutex* lock) :
  2107   _mdtype(mdtype),
  2108   _allocated_blocks_words(0),
  2109   _allocated_chunks_words(0),
  2110   _allocated_chunks_count(0),
  2111   _lock(lock)
  2113   initialize();
  2116 void SpaceManager::inc_size_metrics(size_t words) {
  2117   assert_lock_strong(SpaceManager::expand_lock());
  2118   // Total of allocated Metachunks and allocated Metachunks count
  2119   // for each SpaceManager
  2120   _allocated_chunks_words = _allocated_chunks_words + words;
  2121   _allocated_chunks_count++;
  2122   // Global total of capacity in allocated Metachunks
  2123   MetaspaceAux::inc_capacity(mdtype(), words);
  2124   // Global total of allocated Metablocks.
  2125   // used_words_slow() includes the overhead in each
  2126   // Metachunk so include it in the used when the
  2127   // Metachunk is first added (so only added once per
  2128   // Metachunk).
  2129   MetaspaceAux::inc_used(mdtype(), Metachunk::overhead());
  2132 void SpaceManager::inc_used_metrics(size_t words) {
  2133   // Add to the per SpaceManager total
  2134   Atomic::add_ptr(words, &_allocated_blocks_words);
  2135   // Add to the global total
  2136   MetaspaceAux::inc_used(mdtype(), words);
  2139 void SpaceManager::dec_total_from_size_metrics() {
  2140   MetaspaceAux::dec_capacity(mdtype(), allocated_chunks_words());
  2141   MetaspaceAux::dec_used(mdtype(), allocated_blocks_words());
  2142   // Also deduct the overhead per Metachunk
  2143   MetaspaceAux::dec_used(mdtype(), allocated_chunks_count() * Metachunk::overhead());
  2146 void SpaceManager::initialize() {
  2147   Metadebug::init_allocation_fail_alot_count();
  2148   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2149     _chunks_in_use[i] = NULL;
  2151   _current_chunk = NULL;
  2152   if (TraceMetadataChunkAllocation && Verbose) {
  2153     gclog_or_tty->print_cr("SpaceManager(): " PTR_FORMAT, this);
  2157 void ChunkManager::return_chunks(ChunkIndex index, Metachunk* chunks) {
  2158   if (chunks == NULL) {
  2159     return;
  2161   ChunkList* list = free_chunks(index);
  2162   assert(list->size() == chunks->word_size(), "Mismatch in chunk sizes");
  2163   assert_lock_strong(SpaceManager::expand_lock());
  2164   Metachunk* cur = chunks;
  2166   // This returns chunks one at a time.  If a new
  2167   // class List can be created that is a base class
  2168   // of FreeList then something like FreeList::prepend()
  2169   // can be used in place of this loop
  2170   while (cur != NULL) {
  2171     assert(cur->container() != NULL, "Container should have been set");
  2172     cur->container()->dec_container_count();
  2173     // Capture the next link before it is changed
  2174     // by the call to return_chunk_at_head();
  2175     Metachunk* next = cur->next();
  2176     DEBUG_ONLY(cur->set_is_tagged_free(true);)
  2177     list->return_chunk_at_head(cur);
  2178     cur = next;
  2182 SpaceManager::~SpaceManager() {
  2183   // This call this->_lock which can't be done while holding expand_lock()
  2184   assert(sum_capacity_in_chunks_in_use() == allocated_chunks_words(),
  2185     err_msg("sum_capacity_in_chunks_in_use() " SIZE_FORMAT
  2186             " allocated_chunks_words() " SIZE_FORMAT,
  2187             sum_capacity_in_chunks_in_use(), allocated_chunks_words()));
  2189   MutexLockerEx fcl(SpaceManager::expand_lock(),
  2190                     Mutex::_no_safepoint_check_flag);
  2192   chunk_manager()->slow_locked_verify();
  2194   dec_total_from_size_metrics();
  2196   if (TraceMetadataChunkAllocation && Verbose) {
  2197     gclog_or_tty->print_cr("~SpaceManager(): " PTR_FORMAT, this);
  2198     locked_print_chunks_in_use_on(gclog_or_tty);
  2201   // Do not mangle freed Metachunks.  The chunk size inside Metachunks
  2202   // is during the freeing of a VirtualSpaceNodes.
  2204   // Have to update before the chunks_in_use lists are emptied
  2205   // below.
  2206   chunk_manager()->inc_free_chunks_total(allocated_chunks_words(),
  2207                                          sum_count_in_chunks_in_use());
  2209   // Add all the chunks in use by this space manager
  2210   // to the global list of free chunks.
  2212   // Follow each list of chunks-in-use and add them to the
  2213   // free lists.  Each list is NULL terminated.
  2215   for (ChunkIndex i = ZeroIndex; i < HumongousIndex; i = next_chunk_index(i)) {
  2216     if (TraceMetadataChunkAllocation && Verbose) {
  2217       gclog_or_tty->print_cr("returned %d %s chunks to freelist",
  2218                              sum_count_in_chunks_in_use(i),
  2219                              chunk_size_name(i));
  2221     Metachunk* chunks = chunks_in_use(i);
  2222     chunk_manager()->return_chunks(i, chunks);
  2223     set_chunks_in_use(i, NULL);
  2224     if (TraceMetadataChunkAllocation && Verbose) {
  2225       gclog_or_tty->print_cr("updated freelist count %d %s",
  2226                              chunk_manager()->free_chunks(i)->count(),
  2227                              chunk_size_name(i));
  2229     assert(i != HumongousIndex, "Humongous chunks are handled explicitly later");
  2232   // The medium chunk case may be optimized by passing the head and
  2233   // tail of the medium chunk list to add_at_head().  The tail is often
  2234   // the current chunk but there are probably exceptions.
  2236   // Humongous chunks
  2237   if (TraceMetadataChunkAllocation && Verbose) {
  2238     gclog_or_tty->print_cr("returned %d %s humongous chunks to dictionary",
  2239                             sum_count_in_chunks_in_use(HumongousIndex),
  2240                             chunk_size_name(HumongousIndex));
  2241     gclog_or_tty->print("Humongous chunk dictionary: ");
  2243   // Humongous chunks are never the current chunk.
  2244   Metachunk* humongous_chunks = chunks_in_use(HumongousIndex);
  2246   while (humongous_chunks != NULL) {
  2247 #ifdef ASSERT
  2248     humongous_chunks->set_is_tagged_free(true);
  2249 #endif
  2250     if (TraceMetadataChunkAllocation && Verbose) {
  2251       gclog_or_tty->print(PTR_FORMAT " (" SIZE_FORMAT ") ",
  2252                           humongous_chunks,
  2253                           humongous_chunks->word_size());
  2255     assert(humongous_chunks->word_size() == (size_t)
  2256            align_size_up(humongous_chunks->word_size(),
  2257                              smallest_chunk_size()),
  2258            err_msg("Humongous chunk size is wrong: word size " SIZE_FORMAT
  2259                    " granularity %d",
  2260                    humongous_chunks->word_size(), smallest_chunk_size()));
  2261     Metachunk* next_humongous_chunks = humongous_chunks->next();
  2262     humongous_chunks->container()->dec_container_count();
  2263     chunk_manager()->humongous_dictionary()->return_chunk(humongous_chunks);
  2264     humongous_chunks = next_humongous_chunks;
  2266   if (TraceMetadataChunkAllocation && Verbose) {
  2267     gclog_or_tty->print_cr("");
  2268     gclog_or_tty->print_cr("updated dictionary count %d %s",
  2269                      chunk_manager()->humongous_dictionary()->total_count(),
  2270                      chunk_size_name(HumongousIndex));
  2272   chunk_manager()->slow_locked_verify();
  2275 const char* SpaceManager::chunk_size_name(ChunkIndex index) const {
  2276   switch (index) {
  2277     case SpecializedIndex:
  2278       return "Specialized";
  2279     case SmallIndex:
  2280       return "Small";
  2281     case MediumIndex:
  2282       return "Medium";
  2283     case HumongousIndex:
  2284       return "Humongous";
  2285     default:
  2286       return NULL;
  2290 ChunkIndex ChunkManager::list_index(size_t size) {
  2291   switch (size) {
  2292     case SpecializedChunk:
  2293       assert(SpecializedChunk == ClassSpecializedChunk,
  2294              "Need branch for ClassSpecializedChunk");
  2295       return SpecializedIndex;
  2296     case SmallChunk:
  2297     case ClassSmallChunk:
  2298       return SmallIndex;
  2299     case MediumChunk:
  2300     case ClassMediumChunk:
  2301       return MediumIndex;
  2302     default:
  2303       assert(size > MediumChunk || size > ClassMediumChunk,
  2304              "Not a humongous chunk");
  2305       return HumongousIndex;
  2309 void SpaceManager::deallocate(MetaWord* p, size_t word_size) {
  2310   assert_lock_strong(_lock);
  2311   size_t raw_word_size = get_raw_word_size(word_size);
  2312   size_t min_size = TreeChunk<Metablock, FreeList<Metablock> >::min_size();
  2313   assert(raw_word_size >= min_size,
  2314          err_msg("Should not deallocate dark matter " SIZE_FORMAT "<" SIZE_FORMAT, word_size, min_size));
  2315   block_freelists()->return_block(p, raw_word_size);
  2318 // Adds a chunk to the list of chunks in use.
  2319 void SpaceManager::add_chunk(Metachunk* new_chunk, bool make_current) {
  2321   assert(new_chunk != NULL, "Should not be NULL");
  2322   assert(new_chunk->next() == NULL, "Should not be on a list");
  2324   new_chunk->reset_empty();
  2326   // Find the correct list and and set the current
  2327   // chunk for that list.
  2328   ChunkIndex index = ChunkManager::list_index(new_chunk->word_size());
  2330   if (index != HumongousIndex) {
  2331     retire_current_chunk();
  2332     set_current_chunk(new_chunk);
  2333     new_chunk->set_next(chunks_in_use(index));
  2334     set_chunks_in_use(index, new_chunk);
  2335   } else {
  2336     // For null class loader data and DumpSharedSpaces, the first chunk isn't
  2337     // small, so small will be null.  Link this first chunk as the current
  2338     // chunk.
  2339     if (make_current) {
  2340       // Set as the current chunk but otherwise treat as a humongous chunk.
  2341       set_current_chunk(new_chunk);
  2343     // Link at head.  The _current_chunk only points to a humongous chunk for
  2344     // the null class loader metaspace (class and data virtual space managers)
  2345     // any humongous chunks so will not point to the tail
  2346     // of the humongous chunks list.
  2347     new_chunk->set_next(chunks_in_use(HumongousIndex));
  2348     set_chunks_in_use(HumongousIndex, new_chunk);
  2350     assert(new_chunk->word_size() > medium_chunk_size(), "List inconsistency");
  2353   // Add to the running sum of capacity
  2354   inc_size_metrics(new_chunk->word_size());
  2356   assert(new_chunk->is_empty(), "Not ready for reuse");
  2357   if (TraceMetadataChunkAllocation && Verbose) {
  2358     gclog_or_tty->print("SpaceManager::add_chunk: %d) ",
  2359                         sum_count_in_chunks_in_use());
  2360     new_chunk->print_on(gclog_or_tty);
  2361     chunk_manager()->locked_print_free_chunks(gclog_or_tty);
  2365 void SpaceManager::retire_current_chunk() {
  2366   if (current_chunk() != NULL) {
  2367     size_t remaining_words = current_chunk()->free_word_size();
  2368     if (remaining_words >= TreeChunk<Metablock, FreeList<Metablock> >::min_size()) {
  2369       block_freelists()->return_block(current_chunk()->allocate(remaining_words), remaining_words);
  2370       inc_used_metrics(remaining_words);
  2375 Metachunk* SpaceManager::get_new_chunk(size_t word_size,
  2376                                        size_t grow_chunks_by_words) {
  2377   // Get a chunk from the chunk freelist
  2378   Metachunk* next = chunk_manager()->chunk_freelist_allocate(grow_chunks_by_words);
  2380   if (next == NULL) {
  2381     next = vs_list()->get_new_chunk(word_size,
  2382                                     grow_chunks_by_words,
  2383                                     medium_chunk_bunch());
  2386   if (TraceMetadataHumongousAllocation && next != NULL &&
  2387       SpaceManager::is_humongous(next->word_size())) {
  2388     gclog_or_tty->print_cr("  new humongous chunk word size "
  2389                            PTR_FORMAT, next->word_size());
  2392   return next;
  2395 MetaWord* SpaceManager::allocate(size_t word_size) {
  2396   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  2398   size_t raw_word_size = get_raw_word_size(word_size);
  2399   BlockFreelist* fl =  block_freelists();
  2400   MetaWord* p = NULL;
  2401   // Allocation from the dictionary is expensive in the sense that
  2402   // the dictionary has to be searched for a size.  Don't allocate
  2403   // from the dictionary until it starts to get fat.  Is this
  2404   // a reasonable policy?  Maybe an skinny dictionary is fast enough
  2405   // for allocations.  Do some profiling.  JJJ
  2406   if (fl->total_size() > allocation_from_dictionary_limit) {
  2407     p = fl->get_block(raw_word_size);
  2409   if (p == NULL) {
  2410     p = allocate_work(raw_word_size);
  2413   return p;
  2416 // Returns the address of spaced allocated for "word_size".
  2417 // This methods does not know about blocks (Metablocks)
  2418 MetaWord* SpaceManager::allocate_work(size_t word_size) {
  2419   assert_lock_strong(_lock);
  2420 #ifdef ASSERT
  2421   if (Metadebug::test_metadata_failure()) {
  2422     return NULL;
  2424 #endif
  2425   // Is there space in the current chunk?
  2426   MetaWord* result = NULL;
  2428   // For DumpSharedSpaces, only allocate out of the current chunk which is
  2429   // never null because we gave it the size we wanted.   Caller reports out
  2430   // of memory if this returns null.
  2431   if (DumpSharedSpaces) {
  2432     assert(current_chunk() != NULL, "should never happen");
  2433     inc_used_metrics(word_size);
  2434     return current_chunk()->allocate(word_size); // caller handles null result
  2437   if (current_chunk() != NULL) {
  2438     result = current_chunk()->allocate(word_size);
  2441   if (result == NULL) {
  2442     result = grow_and_allocate(word_size);
  2445   if (result != NULL) {
  2446     inc_used_metrics(word_size);
  2447     assert(result != (MetaWord*) chunks_in_use(MediumIndex),
  2448            "Head of the list is being allocated");
  2451   return result;
  2454 void SpaceManager::verify() {
  2455   // If there are blocks in the dictionary, then
  2456   // verfication of chunks does not work since
  2457   // being in the dictionary alters a chunk.
  2458   if (block_freelists()->total_size() == 0) {
  2459     for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2460       Metachunk* curr = chunks_in_use(i);
  2461       while (curr != NULL) {
  2462         curr->verify();
  2463         verify_chunk_size(curr);
  2464         curr = curr->next();
  2470 void SpaceManager::verify_chunk_size(Metachunk* chunk) {
  2471   assert(is_humongous(chunk->word_size()) ||
  2472          chunk->word_size() == medium_chunk_size() ||
  2473          chunk->word_size() == small_chunk_size() ||
  2474          chunk->word_size() == specialized_chunk_size(),
  2475          "Chunk size is wrong");
  2476   return;
  2479 #ifdef ASSERT
  2480 void SpaceManager::verify_allocated_blocks_words() {
  2481   // Verification is only guaranteed at a safepoint.
  2482   assert(SafepointSynchronize::is_at_safepoint() || !Universe::is_fully_initialized(),
  2483     "Verification can fail if the applications is running");
  2484   assert(allocated_blocks_words() == sum_used_in_chunks_in_use(),
  2485     err_msg("allocation total is not consistent " SIZE_FORMAT
  2486             " vs " SIZE_FORMAT,
  2487             allocated_blocks_words(), sum_used_in_chunks_in_use()));
  2490 #endif
  2492 void SpaceManager::dump(outputStream* const out) const {
  2493   size_t curr_total = 0;
  2494   size_t waste = 0;
  2495   uint i = 0;
  2496   size_t used = 0;
  2497   size_t capacity = 0;
  2499   // Add up statistics for all chunks in this SpaceManager.
  2500   for (ChunkIndex index = ZeroIndex;
  2501        index < NumberOfInUseLists;
  2502        index = next_chunk_index(index)) {
  2503     for (Metachunk* curr = chunks_in_use(index);
  2504          curr != NULL;
  2505          curr = curr->next()) {
  2506       out->print("%d) ", i++);
  2507       curr->print_on(out);
  2508       curr_total += curr->word_size();
  2509       used += curr->used_word_size();
  2510       capacity += curr->word_size();
  2511       waste += curr->free_word_size() + curr->overhead();;
  2515   if (TraceMetadataChunkAllocation && Verbose) {
  2516     block_freelists()->print_on(out);
  2519   size_t free = current_chunk() == NULL ? 0 : current_chunk()->free_word_size();
  2520   // Free space isn't wasted.
  2521   waste -= free;
  2523   out->print_cr("total of all chunks "  SIZE_FORMAT " used " SIZE_FORMAT
  2524                 " free " SIZE_FORMAT " capacity " SIZE_FORMAT
  2525                 " waste " SIZE_FORMAT, curr_total, used, free, capacity, waste);
  2528 #ifndef PRODUCT
  2529 void SpaceManager::mangle_freed_chunks() {
  2530   for (ChunkIndex index = ZeroIndex;
  2531        index < NumberOfInUseLists;
  2532        index = next_chunk_index(index)) {
  2533     for (Metachunk* curr = chunks_in_use(index);
  2534          curr != NULL;
  2535          curr = curr->next()) {
  2536       curr->mangle();
  2540 #endif // PRODUCT
  2542 // MetaspaceAux
  2545 size_t MetaspaceAux::_capacity_words[] = {0, 0};
  2546 size_t MetaspaceAux::_used_words[] = {0, 0};
  2548 size_t MetaspaceAux::free_bytes(Metaspace::MetadataType mdtype) {
  2549   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
  2550   return list == NULL ? 0 : list->free_bytes();
  2553 size_t MetaspaceAux::free_bytes() {
  2554   return free_bytes(Metaspace::ClassType) + free_bytes(Metaspace::NonClassType);
  2557 void MetaspaceAux::dec_capacity(Metaspace::MetadataType mdtype, size_t words) {
  2558   assert_lock_strong(SpaceManager::expand_lock());
  2559   assert(words <= capacity_words(mdtype),
  2560     err_msg("About to decrement below 0: words " SIZE_FORMAT
  2561             " is greater than _capacity_words[%u] " SIZE_FORMAT,
  2562             words, mdtype, capacity_words(mdtype)));
  2563   _capacity_words[mdtype] -= words;
  2566 void MetaspaceAux::inc_capacity(Metaspace::MetadataType mdtype, size_t words) {
  2567   assert_lock_strong(SpaceManager::expand_lock());
  2568   // Needs to be atomic
  2569   _capacity_words[mdtype] += words;
  2572 void MetaspaceAux::dec_used(Metaspace::MetadataType mdtype, size_t words) {
  2573   assert(words <= used_words(mdtype),
  2574     err_msg("About to decrement below 0: words " SIZE_FORMAT
  2575             " is greater than _used_words[%u] " SIZE_FORMAT,
  2576             words, mdtype, used_words(mdtype)));
  2577   // For CMS deallocation of the Metaspaces occurs during the
  2578   // sweep which is a concurrent phase.  Protection by the expand_lock()
  2579   // is not enough since allocation is on a per Metaspace basis
  2580   // and protected by the Metaspace lock.
  2581   jlong minus_words = (jlong) - (jlong) words;
  2582   Atomic::add_ptr(minus_words, &_used_words[mdtype]);
  2585 void MetaspaceAux::inc_used(Metaspace::MetadataType mdtype, size_t words) {
  2586   // _used_words tracks allocations for
  2587   // each piece of metadata.  Those allocations are
  2588   // generally done concurrently by different application
  2589   // threads so must be done atomically.
  2590   Atomic::add_ptr(words, &_used_words[mdtype]);
  2593 size_t MetaspaceAux::used_bytes_slow(Metaspace::MetadataType mdtype) {
  2594   size_t used = 0;
  2595   ClassLoaderDataGraphMetaspaceIterator iter;
  2596   while (iter.repeat()) {
  2597     Metaspace* msp = iter.get_next();
  2598     // Sum allocated_blocks_words for each metaspace
  2599     if (msp != NULL) {
  2600       used += msp->used_words_slow(mdtype);
  2603   return used * BytesPerWord;
  2606 size_t MetaspaceAux::free_bytes_slow(Metaspace::MetadataType mdtype) {
  2607   size_t free = 0;
  2608   ClassLoaderDataGraphMetaspaceIterator iter;
  2609   while (iter.repeat()) {
  2610     Metaspace* msp = iter.get_next();
  2611     if (msp != NULL) {
  2612       free += msp->free_words_slow(mdtype);
  2615   return free * BytesPerWord;
  2618 size_t MetaspaceAux::capacity_bytes_slow(Metaspace::MetadataType mdtype) {
  2619   if ((mdtype == Metaspace::ClassType) && !Metaspace::using_class_space()) {
  2620     return 0;
  2622   // Don't count the space in the freelists.  That space will be
  2623   // added to the capacity calculation as needed.
  2624   size_t capacity = 0;
  2625   ClassLoaderDataGraphMetaspaceIterator iter;
  2626   while (iter.repeat()) {
  2627     Metaspace* msp = iter.get_next();
  2628     if (msp != NULL) {
  2629       capacity += msp->capacity_words_slow(mdtype);
  2632   return capacity * BytesPerWord;
  2635 size_t MetaspaceAux::capacity_bytes_slow() {
  2636 #ifdef PRODUCT
  2637   // Use capacity_bytes() in PRODUCT instead of this function.
  2638   guarantee(false, "Should not call capacity_bytes_slow() in the PRODUCT");
  2639 #endif
  2640   size_t class_capacity = capacity_bytes_slow(Metaspace::ClassType);
  2641   size_t non_class_capacity = capacity_bytes_slow(Metaspace::NonClassType);
  2642   assert(capacity_bytes() == class_capacity + non_class_capacity,
  2643       err_msg("bad accounting: capacity_bytes() " SIZE_FORMAT
  2644         " class_capacity + non_class_capacity " SIZE_FORMAT
  2645         " class_capacity " SIZE_FORMAT " non_class_capacity " SIZE_FORMAT,
  2646         capacity_bytes(), class_capacity + non_class_capacity,
  2647         class_capacity, non_class_capacity));
  2649   return class_capacity + non_class_capacity;
  2652 size_t MetaspaceAux::reserved_bytes(Metaspace::MetadataType mdtype) {
  2653   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
  2654   return list == NULL ? 0 : list->reserved_bytes();
  2657 size_t MetaspaceAux::committed_bytes(Metaspace::MetadataType mdtype) {
  2658   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
  2659   return list == NULL ? 0 : list->committed_bytes();
  2662 size_t MetaspaceAux::min_chunk_size_words() { return Metaspace::first_chunk_word_size(); }
  2664 size_t MetaspaceAux::free_chunks_total_words(Metaspace::MetadataType mdtype) {
  2665   ChunkManager* chunk_manager = Metaspace::get_chunk_manager(mdtype);
  2666   if (chunk_manager == NULL) {
  2667     return 0;
  2669   chunk_manager->slow_verify();
  2670   return chunk_manager->free_chunks_total_words();
  2673 size_t MetaspaceAux::free_chunks_total_bytes(Metaspace::MetadataType mdtype) {
  2674   return free_chunks_total_words(mdtype) * BytesPerWord;
  2677 size_t MetaspaceAux::free_chunks_total_words() {
  2678   return free_chunks_total_words(Metaspace::ClassType) +
  2679          free_chunks_total_words(Metaspace::NonClassType);
  2682 size_t MetaspaceAux::free_chunks_total_bytes() {
  2683   return free_chunks_total_words() * BytesPerWord;
  2686 bool MetaspaceAux::has_chunk_free_list(Metaspace::MetadataType mdtype) {
  2687   return Metaspace::get_chunk_manager(mdtype) != NULL;
  2690 MetaspaceChunkFreeListSummary MetaspaceAux::chunk_free_list_summary(Metaspace::MetadataType mdtype) {
  2691   if (!has_chunk_free_list(mdtype)) {
  2692     return MetaspaceChunkFreeListSummary();
  2695   const ChunkManager* cm = Metaspace::get_chunk_manager(mdtype);
  2696   return cm->chunk_free_list_summary();
  2699 void MetaspaceAux::print_metaspace_change(size_t prev_metadata_used) {
  2700   gclog_or_tty->print(", [Metaspace:");
  2701   if (PrintGCDetails && Verbose) {
  2702     gclog_or_tty->print(" "  SIZE_FORMAT
  2703                         "->" SIZE_FORMAT
  2704                         "("  SIZE_FORMAT ")",
  2705                         prev_metadata_used,
  2706                         used_bytes(),
  2707                         reserved_bytes());
  2708   } else {
  2709     gclog_or_tty->print(" "  SIZE_FORMAT "K"
  2710                         "->" SIZE_FORMAT "K"
  2711                         "("  SIZE_FORMAT "K)",
  2712                         prev_metadata_used/K,
  2713                         used_bytes()/K,
  2714                         reserved_bytes()/K);
  2717   gclog_or_tty->print("]");
  2720 // This is printed when PrintGCDetails
  2721 void MetaspaceAux::print_on(outputStream* out) {
  2722   Metaspace::MetadataType nct = Metaspace::NonClassType;
  2724   out->print_cr(" Metaspace       "
  2725                 "used "      SIZE_FORMAT "K, "
  2726                 "capacity "  SIZE_FORMAT "K, "
  2727                 "committed " SIZE_FORMAT "K, "
  2728                 "reserved "  SIZE_FORMAT "K",
  2729                 used_bytes()/K,
  2730                 capacity_bytes()/K,
  2731                 committed_bytes()/K,
  2732                 reserved_bytes()/K);
  2734   if (Metaspace::using_class_space()) {
  2735     Metaspace::MetadataType ct = Metaspace::ClassType;
  2736     out->print_cr("  class space    "
  2737                   "used "      SIZE_FORMAT "K, "
  2738                   "capacity "  SIZE_FORMAT "K, "
  2739                   "committed " SIZE_FORMAT "K, "
  2740                   "reserved "  SIZE_FORMAT "K",
  2741                   used_bytes(ct)/K,
  2742                   capacity_bytes(ct)/K,
  2743                   committed_bytes(ct)/K,
  2744                   reserved_bytes(ct)/K);
  2748 // Print information for class space and data space separately.
  2749 // This is almost the same as above.
  2750 void MetaspaceAux::print_on(outputStream* out, Metaspace::MetadataType mdtype) {
  2751   size_t free_chunks_capacity_bytes = free_chunks_total_bytes(mdtype);
  2752   size_t capacity_bytes = capacity_bytes_slow(mdtype);
  2753   size_t used_bytes = used_bytes_slow(mdtype);
  2754   size_t free_bytes = free_bytes_slow(mdtype);
  2755   size_t used_and_free = used_bytes + free_bytes +
  2756                            free_chunks_capacity_bytes;
  2757   out->print_cr("  Chunk accounting: used in chunks " SIZE_FORMAT
  2758              "K + unused in chunks " SIZE_FORMAT "K  + "
  2759              " capacity in free chunks " SIZE_FORMAT "K = " SIZE_FORMAT
  2760              "K  capacity in allocated chunks " SIZE_FORMAT "K",
  2761              used_bytes / K,
  2762              free_bytes / K,
  2763              free_chunks_capacity_bytes / K,
  2764              used_and_free / K,
  2765              capacity_bytes / K);
  2766   // Accounting can only be correct if we got the values during a safepoint
  2767   assert(!SafepointSynchronize::is_at_safepoint() || used_and_free == capacity_bytes, "Accounting is wrong");
  2770 // Print total fragmentation for class metaspaces
  2771 void MetaspaceAux::print_class_waste(outputStream* out) {
  2772   assert(Metaspace::using_class_space(), "class metaspace not used");
  2773   size_t cls_specialized_waste = 0, cls_small_waste = 0, cls_medium_waste = 0;
  2774   size_t cls_specialized_count = 0, cls_small_count = 0, cls_medium_count = 0, cls_humongous_count = 0;
  2775   ClassLoaderDataGraphMetaspaceIterator iter;
  2776   while (iter.repeat()) {
  2777     Metaspace* msp = iter.get_next();
  2778     if (msp != NULL) {
  2779       cls_specialized_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
  2780       cls_specialized_count += msp->class_vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
  2781       cls_small_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SmallIndex);
  2782       cls_small_count += msp->class_vsm()->sum_count_in_chunks_in_use(SmallIndex);
  2783       cls_medium_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(MediumIndex);
  2784       cls_medium_count += msp->class_vsm()->sum_count_in_chunks_in_use(MediumIndex);
  2785       cls_humongous_count += msp->class_vsm()->sum_count_in_chunks_in_use(HumongousIndex);
  2788   out->print_cr(" class: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
  2789                 SIZE_FORMAT " small(s) " SIZE_FORMAT ", "
  2790                 SIZE_FORMAT " medium(s) " SIZE_FORMAT ", "
  2791                 "large count " SIZE_FORMAT,
  2792                 cls_specialized_count, cls_specialized_waste,
  2793                 cls_small_count, cls_small_waste,
  2794                 cls_medium_count, cls_medium_waste, cls_humongous_count);
  2797 // Print total fragmentation for data and class metaspaces separately
  2798 void MetaspaceAux::print_waste(outputStream* out) {
  2799   size_t specialized_waste = 0, small_waste = 0, medium_waste = 0;
  2800   size_t specialized_count = 0, small_count = 0, medium_count = 0, humongous_count = 0;
  2802   ClassLoaderDataGraphMetaspaceIterator iter;
  2803   while (iter.repeat()) {
  2804     Metaspace* msp = iter.get_next();
  2805     if (msp != NULL) {
  2806       specialized_waste += msp->vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
  2807       specialized_count += msp->vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
  2808       small_waste += msp->vsm()->sum_waste_in_chunks_in_use(SmallIndex);
  2809       small_count += msp->vsm()->sum_count_in_chunks_in_use(SmallIndex);
  2810       medium_waste += msp->vsm()->sum_waste_in_chunks_in_use(MediumIndex);
  2811       medium_count += msp->vsm()->sum_count_in_chunks_in_use(MediumIndex);
  2812       humongous_count += msp->vsm()->sum_count_in_chunks_in_use(HumongousIndex);
  2815   out->print_cr("Total fragmentation waste (words) doesn't count free space");
  2816   out->print_cr("  data: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
  2817                         SIZE_FORMAT " small(s) " SIZE_FORMAT ", "
  2818                         SIZE_FORMAT " medium(s) " SIZE_FORMAT ", "
  2819                         "large count " SIZE_FORMAT,
  2820              specialized_count, specialized_waste, small_count,
  2821              small_waste, medium_count, medium_waste, humongous_count);
  2822   if (Metaspace::using_class_space()) {
  2823     print_class_waste(out);
  2827 // Dump global metaspace things from the end of ClassLoaderDataGraph
  2828 void MetaspaceAux::dump(outputStream* out) {
  2829   out->print_cr("All Metaspace:");
  2830   out->print("data space: "); print_on(out, Metaspace::NonClassType);
  2831   out->print("class space: "); print_on(out, Metaspace::ClassType);
  2832   print_waste(out);
  2835 void MetaspaceAux::verify_free_chunks() {
  2836   Metaspace::chunk_manager_metadata()->verify();
  2837   if (Metaspace::using_class_space()) {
  2838     Metaspace::chunk_manager_class()->verify();
  2842 void MetaspaceAux::verify_capacity() {
  2843 #ifdef ASSERT
  2844   size_t running_sum_capacity_bytes = capacity_bytes();
  2845   // For purposes of the running sum of capacity, verify against capacity
  2846   size_t capacity_in_use_bytes = capacity_bytes_slow();
  2847   assert(running_sum_capacity_bytes == capacity_in_use_bytes,
  2848     err_msg("capacity_words() * BytesPerWord " SIZE_FORMAT
  2849             " capacity_bytes_slow()" SIZE_FORMAT,
  2850             running_sum_capacity_bytes, capacity_in_use_bytes));
  2851   for (Metaspace::MetadataType i = Metaspace::ClassType;
  2852        i < Metaspace:: MetadataTypeCount;
  2853        i = (Metaspace::MetadataType)(i + 1)) {
  2854     size_t capacity_in_use_bytes = capacity_bytes_slow(i);
  2855     assert(capacity_bytes(i) == capacity_in_use_bytes,
  2856       err_msg("capacity_bytes(%u) " SIZE_FORMAT
  2857               " capacity_bytes_slow(%u)" SIZE_FORMAT,
  2858               i, capacity_bytes(i), i, capacity_in_use_bytes));
  2860 #endif
  2863 void MetaspaceAux::verify_used() {
  2864 #ifdef ASSERT
  2865   size_t running_sum_used_bytes = used_bytes();
  2866   // For purposes of the running sum of used, verify against used
  2867   size_t used_in_use_bytes = used_bytes_slow();
  2868   assert(used_bytes() == used_in_use_bytes,
  2869     err_msg("used_bytes() " SIZE_FORMAT
  2870             " used_bytes_slow()" SIZE_FORMAT,
  2871             used_bytes(), used_in_use_bytes));
  2872   for (Metaspace::MetadataType i = Metaspace::ClassType;
  2873        i < Metaspace:: MetadataTypeCount;
  2874        i = (Metaspace::MetadataType)(i + 1)) {
  2875     size_t used_in_use_bytes = used_bytes_slow(i);
  2876     assert(used_bytes(i) == used_in_use_bytes,
  2877       err_msg("used_bytes(%u) " SIZE_FORMAT
  2878               " used_bytes_slow(%u)" SIZE_FORMAT,
  2879               i, used_bytes(i), i, used_in_use_bytes));
  2881 #endif
  2884 void MetaspaceAux::verify_metrics() {
  2885   verify_capacity();
  2886   verify_used();
  2890 // Metaspace methods
  2892 size_t Metaspace::_first_chunk_word_size = 0;
  2893 size_t Metaspace::_first_class_chunk_word_size = 0;
  2895 size_t Metaspace::_commit_alignment = 0;
  2896 size_t Metaspace::_reserve_alignment = 0;
  2898 Metaspace::Metaspace(Mutex* lock, MetaspaceType type) {
  2899   initialize(lock, type);
  2902 Metaspace::~Metaspace() {
  2903   delete _vsm;
  2904   if (using_class_space()) {
  2905     delete _class_vsm;
  2909 VirtualSpaceList* Metaspace::_space_list = NULL;
  2910 VirtualSpaceList* Metaspace::_class_space_list = NULL;
  2912 ChunkManager* Metaspace::_chunk_manager_metadata = NULL;
  2913 ChunkManager* Metaspace::_chunk_manager_class = NULL;
  2915 #define VIRTUALSPACEMULTIPLIER 2
  2917 #ifdef _LP64
  2918 static const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
  2920 void Metaspace::set_narrow_klass_base_and_shift(address metaspace_base, address cds_base) {
  2921   // Figure out the narrow_klass_base and the narrow_klass_shift.  The
  2922   // narrow_klass_base is the lower of the metaspace base and the cds base
  2923   // (if cds is enabled).  The narrow_klass_shift depends on the distance
  2924   // between the lower base and higher address.
  2925   address lower_base;
  2926   address higher_address;
  2927   if (UseSharedSpaces) {
  2928     higher_address = MAX2((address)(cds_base + FileMapInfo::shared_spaces_size()),
  2929                           (address)(metaspace_base + compressed_class_space_size()));
  2930     lower_base = MIN2(metaspace_base, cds_base);
  2931   } else {
  2932     higher_address = metaspace_base + compressed_class_space_size();
  2933     lower_base = metaspace_base;
  2935     uint64_t klass_encoding_max = UnscaledClassSpaceMax << LogKlassAlignmentInBytes;
  2936     // If compressed class space fits in lower 32G, we don't need a base.
  2937     if (higher_address <= (address)klass_encoding_max) {
  2938       lower_base = 0; // effectively lower base is zero.
  2942   Universe::set_narrow_klass_base(lower_base);
  2944   if ((uint64_t)(higher_address - lower_base) <= UnscaledClassSpaceMax) {
  2945     Universe::set_narrow_klass_shift(0);
  2946   } else {
  2947     assert(!UseSharedSpaces, "Cannot shift with UseSharedSpaces");
  2948     Universe::set_narrow_klass_shift(LogKlassAlignmentInBytes);
  2952 // Return TRUE if the specified metaspace_base and cds_base are close enough
  2953 // to work with compressed klass pointers.
  2954 bool Metaspace::can_use_cds_with_metaspace_addr(char* metaspace_base, address cds_base) {
  2955   assert(cds_base != 0 && UseSharedSpaces, "Only use with CDS");
  2956   assert(UseCompressedClassPointers, "Only use with CompressedKlassPtrs");
  2957   address lower_base = MIN2((address)metaspace_base, cds_base);
  2958   address higher_address = MAX2((address)(cds_base + FileMapInfo::shared_spaces_size()),
  2959                                 (address)(metaspace_base + compressed_class_space_size()));
  2960   return ((uint64_t)(higher_address - lower_base) <= UnscaledClassSpaceMax);
  2963 // Try to allocate the metaspace at the requested addr.
  2964 void Metaspace::allocate_metaspace_compressed_klass_ptrs(char* requested_addr, address cds_base) {
  2965   assert(using_class_space(), "called improperly");
  2966   assert(UseCompressedClassPointers, "Only use with CompressedKlassPtrs");
  2967   assert(compressed_class_space_size() < KlassEncodingMetaspaceMax,
  2968          "Metaspace size is too big");
  2969   assert_is_ptr_aligned(requested_addr, _reserve_alignment);
  2970   assert_is_ptr_aligned(cds_base, _reserve_alignment);
  2971   assert_is_size_aligned(compressed_class_space_size(), _reserve_alignment);
  2973   // Don't use large pages for the class space.
  2974   bool large_pages = false;
  2976   ReservedSpace metaspace_rs = ReservedSpace(compressed_class_space_size(),
  2977                                              _reserve_alignment,
  2978                                              large_pages,
  2979                                              requested_addr, 0);
  2980   if (!metaspace_rs.is_reserved()) {
  2981     if (UseSharedSpaces) {
  2982       size_t increment = align_size_up(1*G, _reserve_alignment);
  2984       // Keep trying to allocate the metaspace, increasing the requested_addr
  2985       // by 1GB each time, until we reach an address that will no longer allow
  2986       // use of CDS with compressed klass pointers.
  2987       char *addr = requested_addr;
  2988       while (!metaspace_rs.is_reserved() && (addr + increment > addr) &&
  2989              can_use_cds_with_metaspace_addr(addr + increment, cds_base)) {
  2990         addr = addr + increment;
  2991         metaspace_rs = ReservedSpace(compressed_class_space_size(),
  2992                                      _reserve_alignment, large_pages, addr, 0);
  2996     // If no successful allocation then try to allocate the space anywhere.  If
  2997     // that fails then OOM doom.  At this point we cannot try allocating the
  2998     // metaspace as if UseCompressedClassPointers is off because too much
  2999     // initialization has happened that depends on UseCompressedClassPointers.
  3000     // So, UseCompressedClassPointers cannot be turned off at this point.
  3001     if (!metaspace_rs.is_reserved()) {
  3002       metaspace_rs = ReservedSpace(compressed_class_space_size(),
  3003                                    _reserve_alignment, large_pages);
  3004       if (!metaspace_rs.is_reserved()) {
  3005         vm_exit_during_initialization(err_msg("Could not allocate metaspace: %d bytes",
  3006                                               compressed_class_space_size()));
  3011   // If we got here then the metaspace got allocated.
  3012   MemTracker::record_virtual_memory_type((address)metaspace_rs.base(), mtClass);
  3014   // Verify that we can use shared spaces.  Otherwise, turn off CDS.
  3015   if (UseSharedSpaces && !can_use_cds_with_metaspace_addr(metaspace_rs.base(), cds_base)) {
  3016     FileMapInfo::stop_sharing_and_unmap(
  3017         "Could not allocate metaspace at a compatible address");
  3020   set_narrow_klass_base_and_shift((address)metaspace_rs.base(),
  3021                                   UseSharedSpaces ? (address)cds_base : 0);
  3023   initialize_class_space(metaspace_rs);
  3025   if (PrintCompressedOopsMode || (PrintMiscellaneous && Verbose)) {
  3026     gclog_or_tty->print_cr("Narrow klass base: " PTR_FORMAT ", Narrow klass shift: " SIZE_FORMAT,
  3027                             Universe::narrow_klass_base(), Universe::narrow_klass_shift());
  3028     gclog_or_tty->print_cr("Compressed class space size: " SIZE_FORMAT " Address: " PTR_FORMAT " Req Addr: " PTR_FORMAT,
  3029                            compressed_class_space_size(), metaspace_rs.base(), requested_addr);
  3033 // For UseCompressedClassPointers the class space is reserved above the top of
  3034 // the Java heap.  The argument passed in is at the base of the compressed space.
  3035 void Metaspace::initialize_class_space(ReservedSpace rs) {
  3036   // The reserved space size may be bigger because of alignment, esp with UseLargePages
  3037   assert(rs.size() >= CompressedClassSpaceSize,
  3038          err_msg(SIZE_FORMAT " != " UINTX_FORMAT, rs.size(), CompressedClassSpaceSize));
  3039   assert(using_class_space(), "Must be using class space");
  3040   _class_space_list = new VirtualSpaceList(rs);
  3041   _chunk_manager_class = new ChunkManager(SpecializedChunk, ClassSmallChunk, ClassMediumChunk);
  3043   if (!_class_space_list->initialization_succeeded()) {
  3044     vm_exit_during_initialization("Failed to setup compressed class space virtual space list.");
  3048 #endif
  3050 void Metaspace::ergo_initialize() {
  3051   if (DumpSharedSpaces) {
  3052     // Using large pages when dumping the shared archive is currently not implemented.
  3053     FLAG_SET_ERGO(bool, UseLargePagesInMetaspace, false);
  3056   size_t page_size = os::vm_page_size();
  3057   if (UseLargePages && UseLargePagesInMetaspace) {
  3058     page_size = os::large_page_size();
  3061   _commit_alignment  = page_size;
  3062   _reserve_alignment = MAX2(page_size, (size_t)os::vm_allocation_granularity());
  3064   // Do not use FLAG_SET_ERGO to update MaxMetaspaceSize, since this will
  3065   // override if MaxMetaspaceSize was set on the command line or not.
  3066   // This information is needed later to conform to the specification of the
  3067   // java.lang.management.MemoryUsage API.
  3068   //
  3069   // Ideally, we would be able to set the default value of MaxMetaspaceSize in
  3070   // globals.hpp to the aligned value, but this is not possible, since the
  3071   // alignment depends on other flags being parsed.
  3072   MaxMetaspaceSize = align_size_down_bounded(MaxMetaspaceSize, _reserve_alignment);
  3074   if (MetaspaceSize > MaxMetaspaceSize) {
  3075     MetaspaceSize = MaxMetaspaceSize;
  3078   MetaspaceSize = align_size_down_bounded(MetaspaceSize, _commit_alignment);
  3080   assert(MetaspaceSize <= MaxMetaspaceSize, "MetaspaceSize should be limited by MaxMetaspaceSize");
  3082   if (MetaspaceSize < 256*K) {
  3083     vm_exit_during_initialization("Too small initial Metaspace size");
  3086   MinMetaspaceExpansion = align_size_down_bounded(MinMetaspaceExpansion, _commit_alignment);
  3087   MaxMetaspaceExpansion = align_size_down_bounded(MaxMetaspaceExpansion, _commit_alignment);
  3089   CompressedClassSpaceSize = align_size_down_bounded(CompressedClassSpaceSize, _reserve_alignment);
  3090   set_compressed_class_space_size(CompressedClassSpaceSize);
  3093 void Metaspace::global_initialize() {
  3094   // Initialize the alignment for shared spaces.
  3095   int max_alignment = os::vm_page_size();
  3096   size_t cds_total = 0;
  3098   MetaspaceShared::set_max_alignment(max_alignment);
  3100   if (DumpSharedSpaces) {
  3101     SharedReadOnlySize  = align_size_up(SharedReadOnlySize,  max_alignment);
  3102     SharedReadWriteSize = align_size_up(SharedReadWriteSize, max_alignment);
  3103     SharedMiscDataSize  = align_size_up(SharedMiscDataSize,  max_alignment);
  3104     SharedMiscCodeSize  = align_size_up(SharedMiscCodeSize,  max_alignment);
  3106     // Initialize with the sum of the shared space sizes.  The read-only
  3107     // and read write metaspace chunks will be allocated out of this and the
  3108     // remainder is the misc code and data chunks.
  3109     cds_total = FileMapInfo::shared_spaces_size();
  3110     cds_total = align_size_up(cds_total, _reserve_alignment);
  3111     _space_list = new VirtualSpaceList(cds_total/wordSize);
  3112     _chunk_manager_metadata = new ChunkManager(SpecializedChunk, SmallChunk, MediumChunk);
  3114     if (!_space_list->initialization_succeeded()) {
  3115       vm_exit_during_initialization("Unable to dump shared archive.", NULL);
  3118 #ifdef _LP64
  3119     if (cds_total + compressed_class_space_size() > UnscaledClassSpaceMax) {
  3120       vm_exit_during_initialization("Unable to dump shared archive.",
  3121           err_msg("Size of archive (" SIZE_FORMAT ") + compressed class space ("
  3122                   SIZE_FORMAT ") == total (" SIZE_FORMAT ") is larger than compressed "
  3123                   "klass limit: " SIZE_FORMAT, cds_total, compressed_class_space_size(),
  3124                   cds_total + compressed_class_space_size(), UnscaledClassSpaceMax));
  3127     // Set the compressed klass pointer base so that decoding of these pointers works
  3128     // properly when creating the shared archive.
  3129     assert(UseCompressedOops && UseCompressedClassPointers,
  3130       "UseCompressedOops and UseCompressedClassPointers must be set");
  3131     Universe::set_narrow_klass_base((address)_space_list->current_virtual_space()->bottom());
  3132     if (TraceMetavirtualspaceAllocation && Verbose) {
  3133       gclog_or_tty->print_cr("Setting_narrow_klass_base to Address: " PTR_FORMAT,
  3134                              _space_list->current_virtual_space()->bottom());
  3137     Universe::set_narrow_klass_shift(0);
  3138 #endif
  3140   } else {
  3141     // If using shared space, open the file that contains the shared space
  3142     // and map in the memory before initializing the rest of metaspace (so
  3143     // the addresses don't conflict)
  3144     address cds_address = NULL;
  3145     if (UseSharedSpaces) {
  3146       FileMapInfo* mapinfo = new FileMapInfo();
  3147       memset(mapinfo, 0, sizeof(FileMapInfo));
  3149       // Open the shared archive file, read and validate the header. If
  3150       // initialization fails, shared spaces [UseSharedSpaces] are
  3151       // disabled and the file is closed.
  3152       // Map in spaces now also
  3153       if (mapinfo->initialize() && MetaspaceShared::map_shared_spaces(mapinfo)) {
  3154         FileMapInfo::set_current_info(mapinfo);
  3155         cds_total = FileMapInfo::shared_spaces_size();
  3156         cds_address = (address)mapinfo->region_base(0);
  3157       } else {
  3158         assert(!mapinfo->is_open() && !UseSharedSpaces,
  3159                "archive file not closed or shared spaces not disabled.");
  3163 #ifdef _LP64
  3164     // If UseCompressedClassPointers is set then allocate the metaspace area
  3165     // above the heap and above the CDS area (if it exists).
  3166     if (using_class_space()) {
  3167       if (UseSharedSpaces) {
  3168         char* cds_end = (char*)(cds_address + cds_total);
  3169         cds_end = (char *)align_ptr_up(cds_end, _reserve_alignment);
  3170         allocate_metaspace_compressed_klass_ptrs(cds_end, cds_address);
  3171       } else {
  3172         char* base = (char*)align_ptr_up(Universe::heap()->reserved_region().end(), _reserve_alignment);
  3173         allocate_metaspace_compressed_klass_ptrs(base, 0);
  3176 #endif
  3178     // Initialize these before initializing the VirtualSpaceList
  3179     _first_chunk_word_size = InitialBootClassLoaderMetaspaceSize / BytesPerWord;
  3180     _first_chunk_word_size = align_word_size_up(_first_chunk_word_size);
  3181     // Make the first class chunk bigger than a medium chunk so it's not put
  3182     // on the medium chunk list.   The next chunk will be small and progress
  3183     // from there.  This size calculated by -version.
  3184     _first_class_chunk_word_size = MIN2((size_t)MediumChunk*6,
  3185                                        (CompressedClassSpaceSize/BytesPerWord)*2);
  3186     _first_class_chunk_word_size = align_word_size_up(_first_class_chunk_word_size);
  3187     // Arbitrarily set the initial virtual space to a multiple
  3188     // of the boot class loader size.
  3189     size_t word_size = VIRTUALSPACEMULTIPLIER * _first_chunk_word_size;
  3190     word_size = align_size_up(word_size, Metaspace::reserve_alignment_words());
  3192     // Initialize the list of virtual spaces.
  3193     _space_list = new VirtualSpaceList(word_size);
  3194     _chunk_manager_metadata = new ChunkManager(SpecializedChunk, SmallChunk, MediumChunk);
  3196     if (!_space_list->initialization_succeeded()) {
  3197       vm_exit_during_initialization("Unable to setup metadata virtual space list.", NULL);
  3201   MetaspaceGC::initialize();
  3202   _tracer = new MetaspaceTracer();
  3205 Metachunk* Metaspace::get_initialization_chunk(MetadataType mdtype,
  3206                                                size_t chunk_word_size,
  3207                                                size_t chunk_bunch) {
  3208   // Get a chunk from the chunk freelist
  3209   Metachunk* chunk = get_chunk_manager(mdtype)->chunk_freelist_allocate(chunk_word_size);
  3210   if (chunk != NULL) {
  3211     return chunk;
  3214   return get_space_list(mdtype)->get_new_chunk(chunk_word_size, chunk_word_size, chunk_bunch);
  3217 void Metaspace::initialize(Mutex* lock, MetaspaceType type) {
  3219   assert(space_list() != NULL,
  3220     "Metadata VirtualSpaceList has not been initialized");
  3221   assert(chunk_manager_metadata() != NULL,
  3222     "Metadata ChunkManager has not been initialized");
  3224   _vsm = new SpaceManager(NonClassType, lock);
  3225   if (_vsm == NULL) {
  3226     return;
  3228   size_t word_size;
  3229   size_t class_word_size;
  3230   vsm()->get_initial_chunk_sizes(type, &word_size, &class_word_size);
  3232   if (using_class_space()) {
  3233   assert(class_space_list() != NULL,
  3234     "Class VirtualSpaceList has not been initialized");
  3235   assert(chunk_manager_class() != NULL,
  3236     "Class ChunkManager has not been initialized");
  3238     // Allocate SpaceManager for classes.
  3239     _class_vsm = new SpaceManager(ClassType, lock);
  3240     if (_class_vsm == NULL) {
  3241       return;
  3245   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  3247   // Allocate chunk for metadata objects
  3248   Metachunk* new_chunk = get_initialization_chunk(NonClassType,
  3249                                                   word_size,
  3250                                                   vsm()->medium_chunk_bunch());
  3251   assert(!DumpSharedSpaces || new_chunk != NULL, "should have enough space for both chunks");
  3252   if (new_chunk != NULL) {
  3253     // Add to this manager's list of chunks in use and current_chunk().
  3254     vsm()->add_chunk(new_chunk, true);
  3257   // Allocate chunk for class metadata objects
  3258   if (using_class_space()) {
  3259     Metachunk* class_chunk = get_initialization_chunk(ClassType,
  3260                                                       class_word_size,
  3261                                                       class_vsm()->medium_chunk_bunch());
  3262     if (class_chunk != NULL) {
  3263       class_vsm()->add_chunk(class_chunk, true);
  3267   _alloc_record_head = NULL;
  3268   _alloc_record_tail = NULL;
  3271 size_t Metaspace::align_word_size_up(size_t word_size) {
  3272   size_t byte_size = word_size * wordSize;
  3273   return ReservedSpace::allocation_align_size_up(byte_size) / wordSize;
  3276 MetaWord* Metaspace::allocate(size_t word_size, MetadataType mdtype) {
  3277   // DumpSharedSpaces doesn't use class metadata area (yet)
  3278   // Also, don't use class_vsm() unless UseCompressedClassPointers is true.
  3279   if (is_class_space_allocation(mdtype)) {
  3280     return  class_vsm()->allocate(word_size);
  3281   } else {
  3282     return  vsm()->allocate(word_size);
  3286 MetaWord* Metaspace::expand_and_allocate(size_t word_size, MetadataType mdtype) {
  3287   size_t delta_bytes = MetaspaceGC::delta_capacity_until_GC(word_size * BytesPerWord);
  3288   assert(delta_bytes > 0, "Must be");
  3290   size_t after_inc = MetaspaceGC::inc_capacity_until_GC(delta_bytes);
  3292   // capacity_until_GC might be updated concurrently, must calculate previous value.
  3293   size_t before_inc = after_inc - delta_bytes;
  3295   tracer()->report_gc_threshold(before_inc, after_inc,
  3296                                 MetaspaceGCThresholdUpdater::ExpandAndAllocate);
  3297   if (PrintGCDetails && Verbose) {
  3298     gclog_or_tty->print_cr("Increase capacity to GC from " SIZE_FORMAT
  3299         " to " SIZE_FORMAT, before_inc, after_inc);
  3302   return allocate(word_size, mdtype);
  3305 // Space allocated in the Metaspace.  This may
  3306 // be across several metadata virtual spaces.
  3307 char* Metaspace::bottom() const {
  3308   assert(DumpSharedSpaces, "only useful and valid for dumping shared spaces");
  3309   return (char*)vsm()->current_chunk()->bottom();
  3312 size_t Metaspace::used_words_slow(MetadataType mdtype) const {
  3313   if (mdtype == ClassType) {
  3314     return using_class_space() ? class_vsm()->sum_used_in_chunks_in_use() : 0;
  3315   } else {
  3316     return vsm()->sum_used_in_chunks_in_use();  // includes overhead!
  3320 size_t Metaspace::free_words_slow(MetadataType mdtype) const {
  3321   if (mdtype == ClassType) {
  3322     return using_class_space() ? class_vsm()->sum_free_in_chunks_in_use() : 0;
  3323   } else {
  3324     return vsm()->sum_free_in_chunks_in_use();
  3328 // Space capacity in the Metaspace.  It includes
  3329 // space in the list of chunks from which allocations
  3330 // have been made. Don't include space in the global freelist and
  3331 // in the space available in the dictionary which
  3332 // is already counted in some chunk.
  3333 size_t Metaspace::capacity_words_slow(MetadataType mdtype) const {
  3334   if (mdtype == ClassType) {
  3335     return using_class_space() ? class_vsm()->sum_capacity_in_chunks_in_use() : 0;
  3336   } else {
  3337     return vsm()->sum_capacity_in_chunks_in_use();
  3341 size_t Metaspace::used_bytes_slow(MetadataType mdtype) const {
  3342   return used_words_slow(mdtype) * BytesPerWord;
  3345 size_t Metaspace::capacity_bytes_slow(MetadataType mdtype) const {
  3346   return capacity_words_slow(mdtype) * BytesPerWord;
  3349 void Metaspace::deallocate(MetaWord* ptr, size_t word_size, bool is_class) {
  3350   if (SafepointSynchronize::is_at_safepoint()) {
  3351     assert(Thread::current()->is_VM_thread(), "should be the VM thread");
  3352     // Don't take Heap_lock
  3353     MutexLockerEx ml(vsm()->lock(), Mutex::_no_safepoint_check_flag);
  3354     if (word_size < TreeChunk<Metablock, FreeList<Metablock> >::min_size()) {
  3355       // Dark matter.  Too small for dictionary.
  3356 #ifdef ASSERT
  3357       Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
  3358 #endif
  3359       return;
  3361     if (is_class && using_class_space()) {
  3362       class_vsm()->deallocate(ptr, word_size);
  3363     } else {
  3364       vsm()->deallocate(ptr, word_size);
  3366   } else {
  3367     MutexLockerEx ml(vsm()->lock(), Mutex::_no_safepoint_check_flag);
  3369     if (word_size < TreeChunk<Metablock, FreeList<Metablock> >::min_size()) {
  3370       // Dark matter.  Too small for dictionary.
  3371 #ifdef ASSERT
  3372       Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
  3373 #endif
  3374       return;
  3376     if (is_class && using_class_space()) {
  3377       class_vsm()->deallocate(ptr, word_size);
  3378     } else {
  3379       vsm()->deallocate(ptr, word_size);
  3385 MetaWord* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size,
  3386                               bool read_only, MetaspaceObj::Type type, TRAPS) {
  3387   if (HAS_PENDING_EXCEPTION) {
  3388     assert(false, "Should not allocate with exception pending");
  3389     return NULL;  // caller does a CHECK_NULL too
  3392   assert(loader_data != NULL, "Should never pass around a NULL loader_data. "
  3393         "ClassLoaderData::the_null_class_loader_data() should have been used.");
  3395   // Allocate in metaspaces without taking out a lock, because it deadlocks
  3396   // with the SymbolTable_lock.  Dumping is single threaded for now.  We'll have
  3397   // to revisit this for application class data sharing.
  3398   if (DumpSharedSpaces) {
  3399     assert(type > MetaspaceObj::UnknownType && type < MetaspaceObj::_number_of_types, "sanity");
  3400     Metaspace* space = read_only ? loader_data->ro_metaspace() : loader_data->rw_metaspace();
  3401     MetaWord* result = space->allocate(word_size, NonClassType);
  3402     if (result == NULL) {
  3403       report_out_of_shared_space(read_only ? SharedReadOnly : SharedReadWrite);
  3406     space->record_allocation(result, type, space->vsm()->get_raw_word_size(word_size));
  3408     // Zero initialize.
  3409     Copy::fill_to_aligned_words((HeapWord*)result, word_size, 0);
  3411     return result;
  3414   MetadataType mdtype = (type == MetaspaceObj::ClassType) ? ClassType : NonClassType;
  3416   // Try to allocate metadata.
  3417   MetaWord* result = loader_data->metaspace_non_null()->allocate(word_size, mdtype);
  3419   if (result == NULL) {
  3420     tracer()->report_metaspace_allocation_failure(loader_data, word_size, type, mdtype);
  3422     // Allocation failed.
  3423     if (is_init_completed()) {
  3424       // Only start a GC if the bootstrapping has completed.
  3426       // Try to clean out some memory and retry.
  3427       result = Universe::heap()->collector_policy()->satisfy_failed_metadata_allocation(
  3428           loader_data, word_size, mdtype);
  3432   if (result == NULL) {
  3433     report_metadata_oome(loader_data, word_size, type, mdtype, CHECK_NULL);
  3436   // Zero initialize.
  3437   Copy::fill_to_aligned_words((HeapWord*)result, word_size, 0);
  3439   return result;
  3442 size_t Metaspace::class_chunk_size(size_t word_size) {
  3443   assert(using_class_space(), "Has to use class space");
  3444   return class_vsm()->calc_chunk_size(word_size);
  3447 void Metaspace::report_metadata_oome(ClassLoaderData* loader_data, size_t word_size, MetaspaceObj::Type type, MetadataType mdtype, TRAPS) {
  3448   tracer()->report_metadata_oom(loader_data, word_size, type, mdtype);
  3450   // If result is still null, we are out of memory.
  3451   if (Verbose && TraceMetadataChunkAllocation) {
  3452     gclog_or_tty->print_cr("Metaspace allocation failed for size "
  3453         SIZE_FORMAT, word_size);
  3454     if (loader_data->metaspace_or_null() != NULL) {
  3455       loader_data->dump(gclog_or_tty);
  3457     MetaspaceAux::dump(gclog_or_tty);
  3460   bool out_of_compressed_class_space = false;
  3461   if (is_class_space_allocation(mdtype)) {
  3462     Metaspace* metaspace = loader_data->metaspace_non_null();
  3463     out_of_compressed_class_space =
  3464       MetaspaceAux::committed_bytes(Metaspace::ClassType) +
  3465       (metaspace->class_chunk_size(word_size) * BytesPerWord) >
  3466       CompressedClassSpaceSize;
  3469   // -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support
  3470   const char* space_string = out_of_compressed_class_space ?
  3471     "Compressed class space" : "Metaspace";
  3473   report_java_out_of_memory(space_string);
  3475   if (JvmtiExport::should_post_resource_exhausted()) {
  3476     JvmtiExport::post_resource_exhausted(
  3477         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR,
  3478         space_string);
  3481   if (!is_init_completed()) {
  3482     vm_exit_during_initialization("OutOfMemoryError", space_string);
  3485   if (out_of_compressed_class_space) {
  3486     THROW_OOP(Universe::out_of_memory_error_class_metaspace());
  3487   } else {
  3488     THROW_OOP(Universe::out_of_memory_error_metaspace());
  3492 const char* Metaspace::metadata_type_name(Metaspace::MetadataType mdtype) {
  3493   switch (mdtype) {
  3494     case Metaspace::ClassType: return "Class";
  3495     case Metaspace::NonClassType: return "Metadata";
  3496     default:
  3497       assert(false, err_msg("Got bad mdtype: %d", (int) mdtype));
  3498       return NULL;
  3502 void Metaspace::record_allocation(void* ptr, MetaspaceObj::Type type, size_t word_size) {
  3503   assert(DumpSharedSpaces, "sanity");
  3505   AllocRecord *rec = new AllocRecord((address)ptr, type, (int)word_size * HeapWordSize);
  3506   if (_alloc_record_head == NULL) {
  3507     _alloc_record_head = _alloc_record_tail = rec;
  3508   } else {
  3509     _alloc_record_tail->_next = rec;
  3510     _alloc_record_tail = rec;
  3514 void Metaspace::iterate(Metaspace::AllocRecordClosure *closure) {
  3515   assert(DumpSharedSpaces, "unimplemented for !DumpSharedSpaces");
  3517   address last_addr = (address)bottom();
  3519   for (AllocRecord *rec = _alloc_record_head; rec; rec = rec->_next) {
  3520     address ptr = rec->_ptr;
  3521     if (last_addr < ptr) {
  3522       closure->doit(last_addr, MetaspaceObj::UnknownType, ptr - last_addr);
  3524     closure->doit(ptr, rec->_type, rec->_byte_size);
  3525     last_addr = ptr + rec->_byte_size;
  3528   address top = ((address)bottom()) + used_bytes_slow(Metaspace::NonClassType);
  3529   if (last_addr < top) {
  3530     closure->doit(last_addr, MetaspaceObj::UnknownType, top - last_addr);
  3534 void Metaspace::purge(MetadataType mdtype) {
  3535   get_space_list(mdtype)->purge(get_chunk_manager(mdtype));
  3538 void Metaspace::purge() {
  3539   MutexLockerEx cl(SpaceManager::expand_lock(),
  3540                    Mutex::_no_safepoint_check_flag);
  3541   purge(NonClassType);
  3542   if (using_class_space()) {
  3543     purge(ClassType);
  3547 void Metaspace::print_on(outputStream* out) const {
  3548   // Print both class virtual space counts and metaspace.
  3549   if (Verbose) {
  3550     vsm()->print_on(out);
  3551     if (using_class_space()) {
  3552       class_vsm()->print_on(out);
  3557 bool Metaspace::contains(const void* ptr) {
  3558   if (UseSharedSpaces && MetaspaceShared::is_in_shared_space(ptr)) {
  3559     return true;
  3562   if (using_class_space() && get_space_list(ClassType)->contains(ptr)) {
  3563      return true;
  3566   return get_space_list(NonClassType)->contains(ptr);
  3569 void Metaspace::verify() {
  3570   vsm()->verify();
  3571   if (using_class_space()) {
  3572     class_vsm()->verify();
  3576 void Metaspace::dump(outputStream* const out) const {
  3577   out->print_cr("\nVirtual space manager: " INTPTR_FORMAT, vsm());
  3578   vsm()->dump(out);
  3579   if (using_class_space()) {
  3580     out->print_cr("\nClass space manager: " INTPTR_FORMAT, class_vsm());
  3581     class_vsm()->dump(out);
  3585 /////////////// Unit tests ///////////////
  3587 #ifndef PRODUCT
  3589 class TestMetaspaceAuxTest : AllStatic {
  3590  public:
  3591   static void test_reserved() {
  3592     size_t reserved = MetaspaceAux::reserved_bytes();
  3594     assert(reserved > 0, "assert");
  3596     size_t committed  = MetaspaceAux::committed_bytes();
  3597     assert(committed <= reserved, "assert");
  3599     size_t reserved_metadata = MetaspaceAux::reserved_bytes(Metaspace::NonClassType);
  3600     assert(reserved_metadata > 0, "assert");
  3601     assert(reserved_metadata <= reserved, "assert");
  3603     if (UseCompressedClassPointers) {
  3604       size_t reserved_class    = MetaspaceAux::reserved_bytes(Metaspace::ClassType);
  3605       assert(reserved_class > 0, "assert");
  3606       assert(reserved_class < reserved, "assert");
  3610   static void test_committed() {
  3611     size_t committed = MetaspaceAux::committed_bytes();
  3613     assert(committed > 0, "assert");
  3615     size_t reserved  = MetaspaceAux::reserved_bytes();
  3616     assert(committed <= reserved, "assert");
  3618     size_t committed_metadata = MetaspaceAux::committed_bytes(Metaspace::NonClassType);
  3619     assert(committed_metadata > 0, "assert");
  3620     assert(committed_metadata <= committed, "assert");
  3622     if (UseCompressedClassPointers) {
  3623       size_t committed_class    = MetaspaceAux::committed_bytes(Metaspace::ClassType);
  3624       assert(committed_class > 0, "assert");
  3625       assert(committed_class < committed, "assert");
  3629   static void test_virtual_space_list_large_chunk() {
  3630     VirtualSpaceList* vs_list = new VirtualSpaceList(os::vm_allocation_granularity());
  3631     MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  3632     // A size larger than VirtualSpaceSize (256k) and add one page to make it _not_ be
  3633     // vm_allocation_granularity aligned on Windows.
  3634     size_t large_size = (size_t)(2*256*K + (os::vm_page_size()/BytesPerWord));
  3635     large_size += (os::vm_page_size()/BytesPerWord);
  3636     vs_list->get_new_chunk(large_size, large_size, 0);
  3639   static void test() {
  3640     test_reserved();
  3641     test_committed();
  3642     test_virtual_space_list_large_chunk();
  3644 };
  3646 void TestMetaspaceAux_test() {
  3647   TestMetaspaceAuxTest::test();
  3650 class TestVirtualSpaceNodeTest {
  3651   static void chunk_up(size_t words_left, size_t& num_medium_chunks,
  3652                                           size_t& num_small_chunks,
  3653                                           size_t& num_specialized_chunks) {
  3654     num_medium_chunks = words_left / MediumChunk;
  3655     words_left = words_left % MediumChunk;
  3657     num_small_chunks = words_left / SmallChunk;
  3658     words_left = words_left % SmallChunk;
  3659     // how many specialized chunks can we get?
  3660     num_specialized_chunks = words_left / SpecializedChunk;
  3661     assert(words_left % SpecializedChunk == 0, "should be nothing left");
  3664  public:
  3665   static void test() {
  3666     MutexLockerEx ml(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  3667     const size_t vsn_test_size_words = MediumChunk  * 4;
  3668     const size_t vsn_test_size_bytes = vsn_test_size_words * BytesPerWord;
  3670     // The chunk sizes must be multiples of eachother, or this will fail
  3671     STATIC_ASSERT(MediumChunk % SmallChunk == 0);
  3672     STATIC_ASSERT(SmallChunk % SpecializedChunk == 0);
  3674     { // No committed memory in VSN
  3675       ChunkManager cm(SpecializedChunk, SmallChunk, MediumChunk);
  3676       VirtualSpaceNode vsn(vsn_test_size_bytes);
  3677       vsn.initialize();
  3678       vsn.retire(&cm);
  3679       assert(cm.sum_free_chunks_count() == 0, "did not commit any memory in the VSN");
  3682     { // All of VSN is committed, half is used by chunks
  3683       ChunkManager cm(SpecializedChunk, SmallChunk, MediumChunk);
  3684       VirtualSpaceNode vsn(vsn_test_size_bytes);
  3685       vsn.initialize();
  3686       vsn.expand_by(vsn_test_size_words, vsn_test_size_words);
  3687       vsn.get_chunk_vs(MediumChunk);
  3688       vsn.get_chunk_vs(MediumChunk);
  3689       vsn.retire(&cm);
  3690       assert(cm.sum_free_chunks_count() == 2, "should have been memory left for 2 medium chunks");
  3691       assert(cm.sum_free_chunks() == 2*MediumChunk, "sizes should add up");
  3694     { // 4 pages of VSN is committed, some is used by chunks
  3695       ChunkManager cm(SpecializedChunk, SmallChunk, MediumChunk);
  3696       VirtualSpaceNode vsn(vsn_test_size_bytes);
  3697       const size_t page_chunks = 4 * (size_t)os::vm_page_size() / BytesPerWord;
  3698       assert(page_chunks < MediumChunk, "Test expects medium chunks to be at least 4*page_size");
  3699       vsn.initialize();
  3700       vsn.expand_by(page_chunks, page_chunks);
  3701       vsn.get_chunk_vs(SmallChunk);
  3702       vsn.get_chunk_vs(SpecializedChunk);
  3703       vsn.retire(&cm);
  3705       // committed - used = words left to retire
  3706       const size_t words_left = page_chunks - SmallChunk - SpecializedChunk;
  3708       size_t num_medium_chunks, num_small_chunks, num_spec_chunks;
  3709       chunk_up(words_left, num_medium_chunks, num_small_chunks, num_spec_chunks);
  3711       assert(num_medium_chunks == 0, "should not get any medium chunks");
  3712       assert(cm.sum_free_chunks_count() == (num_small_chunks + num_spec_chunks), "should be space for 3 chunks");
  3713       assert(cm.sum_free_chunks() == words_left, "sizes should add up");
  3716     { // Half of VSN is committed, a humongous chunk is used
  3717       ChunkManager cm(SpecializedChunk, SmallChunk, MediumChunk);
  3718       VirtualSpaceNode vsn(vsn_test_size_bytes);
  3719       vsn.initialize();
  3720       vsn.expand_by(MediumChunk * 2, MediumChunk * 2);
  3721       vsn.get_chunk_vs(MediumChunk + SpecializedChunk); // Humongous chunks will be aligned up to MediumChunk + SpecializedChunk
  3722       vsn.retire(&cm);
  3724       const size_t words_left = MediumChunk * 2 - (MediumChunk + SpecializedChunk);
  3725       size_t num_medium_chunks, num_small_chunks, num_spec_chunks;
  3726       chunk_up(words_left, num_medium_chunks, num_small_chunks, num_spec_chunks);
  3728       assert(num_medium_chunks == 0, "should not get any medium chunks");
  3729       assert(cm.sum_free_chunks_count() == (num_small_chunks + num_spec_chunks), "should be space for 3 chunks");
  3730       assert(cm.sum_free_chunks() == words_left, "sizes should add up");
  3735 #define assert_is_available_positive(word_size) \
  3736   assert(vsn.is_available(word_size), \
  3737     err_msg(#word_size ": " PTR_FORMAT " bytes were not available in " \
  3738             "VirtualSpaceNode [" PTR_FORMAT ", " PTR_FORMAT ")", \
  3739             (uintptr_t)(word_size * BytesPerWord), vsn.bottom(), vsn.end()));
  3741 #define assert_is_available_negative(word_size) \
  3742   assert(!vsn.is_available(word_size), \
  3743     err_msg(#word_size ": " PTR_FORMAT " bytes should not be available in " \
  3744             "VirtualSpaceNode [" PTR_FORMAT ", " PTR_FORMAT ")", \
  3745             (uintptr_t)(word_size * BytesPerWord), vsn.bottom(), vsn.end()));
  3747   static void test_is_available_positive() {
  3748     // Reserve some memory.
  3749     VirtualSpaceNode vsn(os::vm_allocation_granularity());
  3750     assert(vsn.initialize(), "Failed to setup VirtualSpaceNode");
  3752     // Commit some memory.
  3753     size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord;
  3754     bool expanded = vsn.expand_by(commit_word_size, commit_word_size);
  3755     assert(expanded, "Failed to commit");
  3757     // Check that is_available accepts the committed size.
  3758     assert_is_available_positive(commit_word_size);
  3760     // Check that is_available accepts half the committed size.
  3761     size_t expand_word_size = commit_word_size / 2;
  3762     assert_is_available_positive(expand_word_size);
  3765   static void test_is_available_negative() {
  3766     // Reserve some memory.
  3767     VirtualSpaceNode vsn(os::vm_allocation_granularity());
  3768     assert(vsn.initialize(), "Failed to setup VirtualSpaceNode");
  3770     // Commit some memory.
  3771     size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord;
  3772     bool expanded = vsn.expand_by(commit_word_size, commit_word_size);
  3773     assert(expanded, "Failed to commit");
  3775     // Check that is_available doesn't accept a too large size.
  3776     size_t two_times_commit_word_size = commit_word_size * 2;
  3777     assert_is_available_negative(two_times_commit_word_size);
  3780   static void test_is_available_overflow() {
  3781     // Reserve some memory.
  3782     VirtualSpaceNode vsn(os::vm_allocation_granularity());
  3783     assert(vsn.initialize(), "Failed to setup VirtualSpaceNode");
  3785     // Commit some memory.
  3786     size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord;
  3787     bool expanded = vsn.expand_by(commit_word_size, commit_word_size);
  3788     assert(expanded, "Failed to commit");
  3790     // Calculate a size that will overflow the virtual space size.
  3791     void* virtual_space_max = (void*)(uintptr_t)-1;
  3792     size_t bottom_to_max = pointer_delta(virtual_space_max, vsn.bottom(), 1);
  3793     size_t overflow_size = bottom_to_max + BytesPerWord;
  3794     size_t overflow_word_size = overflow_size / BytesPerWord;
  3796     // Check that is_available can handle the overflow.
  3797     assert_is_available_negative(overflow_word_size);
  3800   static void test_is_available() {
  3801     TestVirtualSpaceNodeTest::test_is_available_positive();
  3802     TestVirtualSpaceNodeTest::test_is_available_negative();
  3803     TestVirtualSpaceNodeTest::test_is_available_overflow();
  3805 };
  3807 void TestVirtualSpaceNode_test() {
  3808   TestVirtualSpaceNodeTest::test();
  3809   TestVirtualSpaceNodeTest::test_is_available();
  3811 #endif

mercurial