src/share/vm/memory/metaspace.cpp

Mon, 07 Oct 2013 15:51:17 +0200

author
stefank
date
Mon, 07 Oct 2013 15:51:17 +0200
changeset 5864
a6414751d537
parent 5863
85c1ca43713f
child 5941
bdfbb1fb19ca
permissions
-rw-r--r--

8025996: Track metaspace usage when metaspace is expanded
Reviewed-by: coleenp, ehelin

     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/metablock.hpp"
    34 #include "memory/metachunk.hpp"
    35 #include "memory/metaspace.hpp"
    36 #include "memory/metaspaceShared.hpp"
    37 #include "memory/resourceArea.hpp"
    38 #include "memory/universe.hpp"
    39 #include "runtime/atomic.inline.hpp"
    40 #include "runtime/globals.hpp"
    41 #include "runtime/init.hpp"
    42 #include "runtime/java.hpp"
    43 #include "runtime/mutex.hpp"
    44 #include "runtime/orderAccess.hpp"
    45 #include "services/memTracker.hpp"
    46 #include "services/memoryService.hpp"
    47 #include "utilities/copy.hpp"
    48 #include "utilities/debug.hpp"
    50 typedef BinaryTreeDictionary<Metablock, FreeList> BlockTreeDictionary;
    51 typedef BinaryTreeDictionary<Metachunk, FreeList> ChunkTreeDictionary;
    52 // Define this macro to enable slow integrity checking of
    53 // the free chunk lists
    54 const bool metaspace_slow_verify = false;
    56 // Parameters for stress mode testing
    57 const uint metadata_deallocate_a_lot_block = 10;
    58 const uint metadata_deallocate_a_lock_chunk = 3;
    59 size_t const allocation_from_dictionary_limit = 4 * K;
    61 MetaWord* last_allocated = 0;
    63 size_t Metaspace::_class_metaspace_size;
    65 // Used in declarations in SpaceManager and ChunkManager
    66 enum ChunkIndex {
    67   ZeroIndex = 0,
    68   SpecializedIndex = ZeroIndex,
    69   SmallIndex = SpecializedIndex + 1,
    70   MediumIndex = SmallIndex + 1,
    71   HumongousIndex = MediumIndex + 1,
    72   NumberOfFreeLists = 3,
    73   NumberOfInUseLists = 4
    74 };
    76 enum ChunkSizes {    // in words.
    77   ClassSpecializedChunk = 128,
    78   SpecializedChunk = 128,
    79   ClassSmallChunk = 256,
    80   SmallChunk = 512,
    81   ClassMediumChunk = 4 * K,
    82   MediumChunk = 8 * K,
    83   HumongousChunkGranularity = 8
    84 };
    86 static ChunkIndex next_chunk_index(ChunkIndex i) {
    87   assert(i < NumberOfInUseLists, "Out of bound");
    88   return (ChunkIndex) (i+1);
    89 }
    91 volatile intptr_t MetaspaceGC::_capacity_until_GC = 0;
    92 uint MetaspaceGC::_shrink_factor = 0;
    93 bool MetaspaceGC::_should_concurrent_collect = false;
    95 // Blocks of space for metadata are allocated out of Metachunks.
    96 //
    97 // Metachunk are allocated out of MetadataVirtualspaces and once
    98 // allocated there is no explicit link between a Metachunk and
    99 // the MetadataVirtualspaces from which it was allocated.
   100 //
   101 // Each SpaceManager maintains a
   102 // list of the chunks it is using and the current chunk.  The current
   103 // chunk is the chunk from which allocations are done.  Space freed in
   104 // a chunk is placed on the free list of blocks (BlockFreelist) and
   105 // reused from there.
   107 typedef class FreeList<Metachunk> ChunkList;
   109 // Manages the global free lists of chunks.
   110 // Has three lists of free chunks, and a total size and
   111 // count that includes all three
   113 class ChunkManager : public CHeapObj<mtInternal> {
   115   // Free list of chunks of different sizes.
   116   //   SpecializedChunk
   117   //   SmallChunk
   118   //   MediumChunk
   119   //   HumongousChunk
   120   ChunkList _free_chunks[NumberOfFreeLists];
   123   //   HumongousChunk
   124   ChunkTreeDictionary _humongous_dictionary;
   126   // ChunkManager in all lists of this type
   127   size_t _free_chunks_total;
   128   size_t _free_chunks_count;
   130   void dec_free_chunks_total(size_t v) {
   131     assert(_free_chunks_count > 0 &&
   132              _free_chunks_total > 0,
   133              "About to go negative");
   134     Atomic::add_ptr(-1, &_free_chunks_count);
   135     jlong minus_v = (jlong) - (jlong) v;
   136     Atomic::add_ptr(minus_v, &_free_chunks_total);
   137   }
   139   // Debug support
   141   size_t sum_free_chunks();
   142   size_t sum_free_chunks_count();
   144   void locked_verify_free_chunks_total();
   145   void slow_locked_verify_free_chunks_total() {
   146     if (metaspace_slow_verify) {
   147       locked_verify_free_chunks_total();
   148     }
   149   }
   150   void locked_verify_free_chunks_count();
   151   void slow_locked_verify_free_chunks_count() {
   152     if (metaspace_slow_verify) {
   153       locked_verify_free_chunks_count();
   154     }
   155   }
   156   void verify_free_chunks_count();
   158  public:
   160   ChunkManager(size_t specialized_size, size_t small_size, size_t medium_size)
   161       : _free_chunks_total(0), _free_chunks_count(0) {
   162     _free_chunks[SpecializedIndex].set_size(specialized_size);
   163     _free_chunks[SmallIndex].set_size(small_size);
   164     _free_chunks[MediumIndex].set_size(medium_size);
   165   }
   167   // add or delete (return) a chunk to the global freelist.
   168   Metachunk* chunk_freelist_allocate(size_t word_size);
   169   void chunk_freelist_deallocate(Metachunk* chunk);
   171   // Map a size to a list index assuming that there are lists
   172   // for special, small, medium, and humongous chunks.
   173   static ChunkIndex list_index(size_t size);
   175   // Remove the chunk from its freelist.  It is
   176   // expected to be on one of the _free_chunks[] lists.
   177   void remove_chunk(Metachunk* chunk);
   179   // Add the simple linked list of chunks to the freelist of chunks
   180   // of type index.
   181   void return_chunks(ChunkIndex index, Metachunk* chunks);
   183   // Total of the space in the free chunks list
   184   size_t free_chunks_total_words();
   185   size_t free_chunks_total_bytes();
   187   // Number of chunks in the free chunks list
   188   size_t free_chunks_count();
   190   void inc_free_chunks_total(size_t v, size_t count = 1) {
   191     Atomic::add_ptr(count, &_free_chunks_count);
   192     Atomic::add_ptr(v, &_free_chunks_total);
   193   }
   194   ChunkTreeDictionary* humongous_dictionary() {
   195     return &_humongous_dictionary;
   196   }
   198   ChunkList* free_chunks(ChunkIndex index);
   200   // Returns the list for the given chunk word size.
   201   ChunkList* find_free_chunks_list(size_t word_size);
   203   // Add and remove from a list by size.  Selects
   204   // list based on size of chunk.
   205   void free_chunks_put(Metachunk* chuck);
   206   Metachunk* free_chunks_get(size_t chunk_word_size);
   208   // Debug support
   209   void verify();
   210   void slow_verify() {
   211     if (metaspace_slow_verify) {
   212       verify();
   213     }
   214   }
   215   void locked_verify();
   216   void slow_locked_verify() {
   217     if (metaspace_slow_verify) {
   218       locked_verify();
   219     }
   220   }
   221   void verify_free_chunks_total();
   223   void locked_print_free_chunks(outputStream* st);
   224   void locked_print_sum_free_chunks(outputStream* st);
   226   void print_on(outputStream* st) const;
   227 };
   229 // Used to manage the free list of Metablocks (a block corresponds
   230 // to the allocation of a quantum of metadata).
   231 class BlockFreelist VALUE_OBJ_CLASS_SPEC {
   232   BlockTreeDictionary* _dictionary;
   233   static Metablock* initialize_free_chunk(MetaWord* p, size_t word_size);
   235   // Only allocate and split from freelist if the size of the allocation
   236   // is at least 1/4th the size of the available block.
   237   const static int WasteMultiplier = 4;
   239   // Accessors
   240   BlockTreeDictionary* dictionary() const { return _dictionary; }
   242  public:
   243   BlockFreelist();
   244   ~BlockFreelist();
   246   // Get and return a block to the free list
   247   MetaWord* get_block(size_t word_size);
   248   void return_block(MetaWord* p, size_t word_size);
   250   size_t total_size() {
   251   if (dictionary() == NULL) {
   252     return 0;
   253   } else {
   254     return dictionary()->total_size();
   255   }
   256 }
   258   void print_on(outputStream* st) const;
   259 };
   261 class VirtualSpaceNode : public CHeapObj<mtClass> {
   262   friend class VirtualSpaceList;
   264   // Link to next VirtualSpaceNode
   265   VirtualSpaceNode* _next;
   267   // total in the VirtualSpace
   268   MemRegion _reserved;
   269   ReservedSpace _rs;
   270   VirtualSpace _virtual_space;
   271   MetaWord* _top;
   272   // count of chunks contained in this VirtualSpace
   273   uintx _container_count;
   275   // Convenience functions to access the _virtual_space
   276   char* low()  const { return virtual_space()->low(); }
   277   char* high() const { return virtual_space()->high(); }
   279   // The first Metachunk will be allocated at the bottom of the
   280   // VirtualSpace
   281   Metachunk* first_chunk() { return (Metachunk*) bottom(); }
   283  public:
   285   VirtualSpaceNode(size_t byte_size);
   286   VirtualSpaceNode(ReservedSpace rs) : _top(NULL), _next(NULL), _rs(rs), _container_count(0) {}
   287   ~VirtualSpaceNode();
   289   // Convenience functions for logical bottom and end
   290   MetaWord* bottom() const { return (MetaWord*) _virtual_space.low(); }
   291   MetaWord* end() const { return (MetaWord*) _virtual_space.high(); }
   293   size_t reserved_words() const  { return _virtual_space.reserved_size() / BytesPerWord; }
   294   size_t committed_words() const { return _virtual_space.actual_committed_size() / BytesPerWord; }
   296   bool is_pre_committed() const { return _virtual_space.special(); }
   298   // address of next available space in _virtual_space;
   299   // Accessors
   300   VirtualSpaceNode* next() { return _next; }
   301   void set_next(VirtualSpaceNode* v) { _next = v; }
   303   void set_reserved(MemRegion const v) { _reserved = v; }
   304   void set_top(MetaWord* v) { _top = v; }
   306   // Accessors
   307   MemRegion* reserved() { return &_reserved; }
   308   VirtualSpace* virtual_space() const { return (VirtualSpace*) &_virtual_space; }
   310   // Returns true if "word_size" is available in the VirtualSpace
   311   bool is_available(size_t word_size) { return _top + word_size <= end(); }
   313   MetaWord* top() const { return _top; }
   314   void inc_top(size_t word_size) { _top += word_size; }
   316   uintx container_count() { return _container_count; }
   317   void inc_container_count();
   318   void dec_container_count();
   319 #ifdef ASSERT
   320   uint container_count_slow();
   321   void verify_container_count();
   322 #endif
   324   // used and capacity in this single entry in the list
   325   size_t used_words_in_vs() const;
   326   size_t capacity_words_in_vs() const;
   327   size_t free_words_in_vs() const;
   329   bool initialize();
   331   // get space from the virtual space
   332   Metachunk* take_from_committed(size_t chunk_word_size);
   334   // Allocate a chunk from the virtual space and return it.
   335   Metachunk* get_chunk_vs(size_t chunk_word_size);
   337   // Expands/shrinks the committed space in a virtual space.  Delegates
   338   // to Virtualspace
   339   bool expand_by(size_t min_words, size_t preferred_words);
   341   // In preparation for deleting this node, remove all the chunks
   342   // in the node from any freelist.
   343   void purge(ChunkManager* chunk_manager);
   345 #ifdef ASSERT
   346   // Debug support
   347   void mangle();
   348 #endif
   350   void print_on(outputStream* st) const;
   351 };
   353 #define assert_is_ptr_aligned(ptr, alignment) \
   354   assert(is_ptr_aligned(ptr, alignment),      \
   355     err_msg(PTR_FORMAT " is not aligned to "  \
   356       SIZE_FORMAT, ptr, alignment))
   358 #define assert_is_size_aligned(size, alignment) \
   359   assert(is_size_aligned(size, alignment),      \
   360     err_msg(SIZE_FORMAT " is not aligned to "   \
   361        SIZE_FORMAT, size, alignment))
   364 // Decide if large pages should be committed when the memory is reserved.
   365 static bool should_commit_large_pages_when_reserving(size_t bytes) {
   366   if (UseLargePages && UseLargePagesInMetaspace && !os::can_commit_large_page_memory()) {
   367     size_t words = bytes / BytesPerWord;
   368     bool is_class = false; // We never reserve large pages for the class space.
   369     if (MetaspaceGC::can_expand(words, is_class) &&
   370         MetaspaceGC::allowed_expansion() >= words) {
   371       return true;
   372     }
   373   }
   375   return false;
   376 }
   378   // byte_size is the size of the associated virtualspace.
   379 VirtualSpaceNode::VirtualSpaceNode(size_t bytes) : _top(NULL), _next(NULL), _rs(), _container_count(0) {
   380   assert_is_size_aligned(bytes, Metaspace::reserve_alignment());
   382   // This allocates memory with mmap.  For DumpSharedspaces, try to reserve
   383   // configurable address, generally at the top of the Java heap so other
   384   // memory addresses don't conflict.
   385   if (DumpSharedSpaces) {
   386     bool large_pages = false; // No large pages when dumping the CDS archive.
   387     char* shared_base = (char*)align_ptr_up((char*)SharedBaseAddress, Metaspace::reserve_alignment());
   389     _rs = ReservedSpace(bytes, Metaspace::reserve_alignment(), large_pages, shared_base, 0);
   390     if (_rs.is_reserved()) {
   391       assert(shared_base == 0 || _rs.base() == shared_base, "should match");
   392     } else {
   393       // Get a mmap region anywhere if the SharedBaseAddress fails.
   394       _rs = ReservedSpace(bytes, Metaspace::reserve_alignment(), large_pages);
   395     }
   396     MetaspaceShared::set_shared_rs(&_rs);
   397   } else {
   398     bool large_pages = should_commit_large_pages_when_reserving(bytes);
   400     _rs = ReservedSpace(bytes, Metaspace::reserve_alignment(), large_pages);
   401   }
   403   if (_rs.is_reserved()) {
   404     assert(_rs.base() != NULL, "Catch if we get a NULL address");
   405     assert(_rs.size() != 0, "Catch if we get a 0 size");
   406     assert_is_ptr_aligned(_rs.base(), Metaspace::reserve_alignment());
   407     assert_is_size_aligned(_rs.size(), Metaspace::reserve_alignment());
   409     MemTracker::record_virtual_memory_type((address)_rs.base(), mtClass);
   410   }
   411 }
   413 void VirtualSpaceNode::purge(ChunkManager* chunk_manager) {
   414   Metachunk* chunk = first_chunk();
   415   Metachunk* invalid_chunk = (Metachunk*) top();
   416   while (chunk < invalid_chunk ) {
   417     assert(chunk->is_free(), "Should be marked free");
   418       MetaWord* next = ((MetaWord*)chunk) + chunk->word_size();
   419       chunk_manager->remove_chunk(chunk);
   420       assert(chunk->next() == NULL &&
   421              chunk->prev() == NULL,
   422              "Was not removed from its list");
   423       chunk = (Metachunk*) next;
   424   }
   425 }
   427 #ifdef ASSERT
   428 uint VirtualSpaceNode::container_count_slow() {
   429   uint count = 0;
   430   Metachunk* chunk = first_chunk();
   431   Metachunk* invalid_chunk = (Metachunk*) top();
   432   while (chunk < invalid_chunk ) {
   433     MetaWord* next = ((MetaWord*)chunk) + chunk->word_size();
   434     // Don't count the chunks on the free lists.  Those are
   435     // still part of the VirtualSpaceNode but not currently
   436     // counted.
   437     if (!chunk->is_free()) {
   438       count++;
   439     }
   440     chunk = (Metachunk*) next;
   441   }
   442   return count;
   443 }
   444 #endif
   446 // List of VirtualSpaces for metadata allocation.
   447 class VirtualSpaceList : public CHeapObj<mtClass> {
   448   friend class VirtualSpaceNode;
   450   enum VirtualSpaceSizes {
   451     VirtualSpaceSize = 256 * K
   452   };
   454   // Head of the list
   455   VirtualSpaceNode* _virtual_space_list;
   456   // virtual space currently being used for allocations
   457   VirtualSpaceNode* _current_virtual_space;
   459   // Is this VirtualSpaceList used for the compressed class space
   460   bool _is_class;
   462   // Sum of reserved and committed memory in the virtual spaces
   463   size_t _reserved_words;
   464   size_t _committed_words;
   466   // Number of virtual spaces
   467   size_t _virtual_space_count;
   469   ~VirtualSpaceList();
   471   VirtualSpaceNode* virtual_space_list() const { return _virtual_space_list; }
   473   void set_virtual_space_list(VirtualSpaceNode* v) {
   474     _virtual_space_list = v;
   475   }
   476   void set_current_virtual_space(VirtualSpaceNode* v) {
   477     _current_virtual_space = v;
   478   }
   480   void link_vs(VirtualSpaceNode* new_entry);
   482   // Get another virtual space and add it to the list.  This
   483   // is typically prompted by a failed attempt to allocate a chunk
   484   // and is typically followed by the allocation of a chunk.
   485   bool create_new_virtual_space(size_t vs_word_size);
   487  public:
   488   VirtualSpaceList(size_t word_size);
   489   VirtualSpaceList(ReservedSpace rs);
   491   size_t free_bytes();
   493   Metachunk* get_new_chunk(size_t word_size,
   494                            size_t grow_chunks_by_words,
   495                            size_t medium_chunk_bunch);
   497   bool expand_node_by(VirtualSpaceNode* node,
   498                       size_t min_words,
   499                       size_t preferred_words);
   501   bool expand_by(size_t min_words,
   502                  size_t preferred_words);
   504   VirtualSpaceNode* current_virtual_space() {
   505     return _current_virtual_space;
   506   }
   508   bool is_class() const { return _is_class; }
   510   bool initialization_succeeded() { return _virtual_space_list != NULL; }
   512   size_t reserved_words()  { return _reserved_words; }
   513   size_t reserved_bytes()  { return reserved_words() * BytesPerWord; }
   514   size_t committed_words() { return _committed_words; }
   515   size_t committed_bytes() { return committed_words() * BytesPerWord; }
   517   void inc_reserved_words(size_t v);
   518   void dec_reserved_words(size_t v);
   519   void inc_committed_words(size_t v);
   520   void dec_committed_words(size_t v);
   521   void inc_virtual_space_count();
   522   void dec_virtual_space_count();
   524   // Unlink empty VirtualSpaceNodes and free it.
   525   void purge(ChunkManager* chunk_manager);
   527   bool contains(const void *ptr);
   529   void print_on(outputStream* st) const;
   531   class VirtualSpaceListIterator : public StackObj {
   532     VirtualSpaceNode* _virtual_spaces;
   533    public:
   534     VirtualSpaceListIterator(VirtualSpaceNode* virtual_spaces) :
   535       _virtual_spaces(virtual_spaces) {}
   537     bool repeat() {
   538       return _virtual_spaces != NULL;
   539     }
   541     VirtualSpaceNode* get_next() {
   542       VirtualSpaceNode* result = _virtual_spaces;
   543       if (_virtual_spaces != NULL) {
   544         _virtual_spaces = _virtual_spaces->next();
   545       }
   546       return result;
   547     }
   548   };
   549 };
   551 class Metadebug : AllStatic {
   552   // Debugging support for Metaspaces
   553   static int _deallocate_block_a_lot_count;
   554   static int _deallocate_chunk_a_lot_count;
   555   static int _allocation_fail_alot_count;
   557  public:
   558   static int deallocate_block_a_lot_count() {
   559     return _deallocate_block_a_lot_count;
   560   }
   561   static void set_deallocate_block_a_lot_count(int v) {
   562     _deallocate_block_a_lot_count = v;
   563   }
   564   static void inc_deallocate_block_a_lot_count() {
   565     _deallocate_block_a_lot_count++;
   566   }
   567   static int deallocate_chunk_a_lot_count() {
   568     return _deallocate_chunk_a_lot_count;
   569   }
   570   static void reset_deallocate_chunk_a_lot_count() {
   571     _deallocate_chunk_a_lot_count = 1;
   572   }
   573   static void inc_deallocate_chunk_a_lot_count() {
   574     _deallocate_chunk_a_lot_count++;
   575   }
   577   static void init_allocation_fail_alot_count();
   578 #ifdef ASSERT
   579   static bool test_metadata_failure();
   580 #endif
   582   static void deallocate_chunk_a_lot(SpaceManager* sm,
   583                                      size_t chunk_word_size);
   584   static void deallocate_block_a_lot(SpaceManager* sm,
   585                                      size_t chunk_word_size);
   587 };
   589 int Metadebug::_deallocate_block_a_lot_count = 0;
   590 int Metadebug::_deallocate_chunk_a_lot_count = 0;
   591 int Metadebug::_allocation_fail_alot_count = 0;
   593 //  SpaceManager - used by Metaspace to handle allocations
   594 class SpaceManager : public CHeapObj<mtClass> {
   595   friend class Metaspace;
   596   friend class Metadebug;
   598  private:
   600   // protects allocations and contains.
   601   Mutex* const _lock;
   603   // Type of metadata allocated.
   604   Metaspace::MetadataType _mdtype;
   606   // List of chunks in use by this SpaceManager.  Allocations
   607   // are done from the current chunk.  The list is used for deallocating
   608   // chunks when the SpaceManager is freed.
   609   Metachunk* _chunks_in_use[NumberOfInUseLists];
   610   Metachunk* _current_chunk;
   612   // Number of small chunks to allocate to a manager
   613   // If class space manager, small chunks are unlimited
   614   static uint const _small_chunk_limit;
   616   // Sum of all space in allocated chunks
   617   size_t _allocated_blocks_words;
   619   // Sum of all allocated chunks
   620   size_t _allocated_chunks_words;
   621   size_t _allocated_chunks_count;
   623   // Free lists of blocks are per SpaceManager since they
   624   // are assumed to be in chunks in use by the SpaceManager
   625   // and all chunks in use by a SpaceManager are freed when
   626   // the class loader using the SpaceManager is collected.
   627   BlockFreelist _block_freelists;
   629   // protects virtualspace and chunk expansions
   630   static const char*  _expand_lock_name;
   631   static const int    _expand_lock_rank;
   632   static Mutex* const _expand_lock;
   634  private:
   635   // Accessors
   636   Metachunk* chunks_in_use(ChunkIndex index) const { return _chunks_in_use[index]; }
   637   void set_chunks_in_use(ChunkIndex index, Metachunk* v) { _chunks_in_use[index] = v; }
   639   BlockFreelist* block_freelists() const {
   640     return (BlockFreelist*) &_block_freelists;
   641   }
   643   Metaspace::MetadataType mdtype() { return _mdtype; }
   645   VirtualSpaceList* vs_list()   const { return Metaspace::get_space_list(_mdtype); }
   646   ChunkManager* chunk_manager() const { return Metaspace::get_chunk_manager(_mdtype); }
   648   Metachunk* current_chunk() const { return _current_chunk; }
   649   void set_current_chunk(Metachunk* v) {
   650     _current_chunk = v;
   651   }
   653   Metachunk* find_current_chunk(size_t word_size);
   655   // Add chunk to the list of chunks in use
   656   void add_chunk(Metachunk* v, bool make_current);
   657   void retire_current_chunk();
   659   Mutex* lock() const { return _lock; }
   661   const char* chunk_size_name(ChunkIndex index) const;
   663  protected:
   664   void initialize();
   666  public:
   667   SpaceManager(Metaspace::MetadataType mdtype,
   668                Mutex* lock);
   669   ~SpaceManager();
   671   enum ChunkMultiples {
   672     MediumChunkMultiple = 4
   673   };
   675   bool is_class() { return _mdtype == Metaspace::ClassType; }
   677   // Accessors
   678   size_t specialized_chunk_size() { return SpecializedChunk; }
   679   size_t small_chunk_size() { return (size_t) is_class() ? ClassSmallChunk : SmallChunk; }
   680   size_t medium_chunk_size() { return (size_t) is_class() ? ClassMediumChunk : MediumChunk; }
   681   size_t medium_chunk_bunch() { return medium_chunk_size() * MediumChunkMultiple; }
   683   size_t allocated_blocks_words() const { return _allocated_blocks_words; }
   684   size_t allocated_blocks_bytes() const { return _allocated_blocks_words * BytesPerWord; }
   685   size_t allocated_chunks_words() const { return _allocated_chunks_words; }
   686   size_t allocated_chunks_count() const { return _allocated_chunks_count; }
   688   bool is_humongous(size_t word_size) { return word_size > medium_chunk_size(); }
   690   static Mutex* expand_lock() { return _expand_lock; }
   692   // Increment the per Metaspace and global running sums for Metachunks
   693   // by the given size.  This is used when a Metachunk to added to
   694   // the in-use list.
   695   void inc_size_metrics(size_t words);
   696   // Increment the per Metaspace and global running sums Metablocks by the given
   697   // size.  This is used when a Metablock is allocated.
   698   void inc_used_metrics(size_t words);
   699   // Delete the portion of the running sums for this SpaceManager. That is,
   700   // the globals running sums for the Metachunks and Metablocks are
   701   // decremented for all the Metachunks in-use by this SpaceManager.
   702   void dec_total_from_size_metrics();
   704   // Set the sizes for the initial chunks.
   705   void get_initial_chunk_sizes(Metaspace::MetaspaceType type,
   706                                size_t* chunk_word_size,
   707                                size_t* class_chunk_word_size);
   709   size_t sum_capacity_in_chunks_in_use() const;
   710   size_t sum_used_in_chunks_in_use() const;
   711   size_t sum_free_in_chunks_in_use() const;
   712   size_t sum_waste_in_chunks_in_use() const;
   713   size_t sum_waste_in_chunks_in_use(ChunkIndex index ) const;
   715   size_t sum_count_in_chunks_in_use();
   716   size_t sum_count_in_chunks_in_use(ChunkIndex i);
   718   Metachunk* get_new_chunk(size_t word_size, size_t grow_chunks_by_words);
   720   // Block allocation and deallocation.
   721   // Allocates a block from the current chunk
   722   MetaWord* allocate(size_t word_size);
   724   // Helper for allocations
   725   MetaWord* allocate_work(size_t word_size);
   727   // Returns a block to the per manager freelist
   728   void deallocate(MetaWord* p, size_t word_size);
   730   // Based on the allocation size and a minimum chunk size,
   731   // returned chunk size (for expanding space for chunk allocation).
   732   size_t calc_chunk_size(size_t allocation_word_size);
   734   // Called when an allocation from the current chunk fails.
   735   // Gets a new chunk (may require getting a new virtual space),
   736   // and allocates from that chunk.
   737   MetaWord* grow_and_allocate(size_t word_size);
   739   // Notify memory usage to MemoryService.
   740   void track_metaspace_memory_usage();
   742   // debugging support.
   744   void dump(outputStream* const out) const;
   745   void print_on(outputStream* st) const;
   746   void locked_print_chunks_in_use_on(outputStream* st) const;
   748   void verify();
   749   void verify_chunk_size(Metachunk* chunk);
   750   NOT_PRODUCT(void mangle_freed_chunks();)
   751 #ifdef ASSERT
   752   void verify_allocated_blocks_words();
   753 #endif
   755   size_t get_raw_word_size(size_t word_size) {
   756     // If only the dictionary is going to be used (i.e., no
   757     // indexed free list), then there is a minimum size requirement.
   758     // MinChunkSize is a placeholder for the real minimum size JJJ
   759     size_t byte_size = word_size * BytesPerWord;
   761     size_t raw_bytes_size = MAX2(byte_size,
   762                                  Metablock::min_block_byte_size());
   763     raw_bytes_size = ARENA_ALIGN(raw_bytes_size);
   764     size_t raw_word_size = raw_bytes_size / BytesPerWord;
   765     assert(raw_word_size * BytesPerWord == raw_bytes_size, "Size problem");
   767     return raw_word_size;
   768   }
   769 };
   771 uint const SpaceManager::_small_chunk_limit = 4;
   773 const char* SpaceManager::_expand_lock_name =
   774   "SpaceManager chunk allocation lock";
   775 const int SpaceManager::_expand_lock_rank = Monitor::leaf - 1;
   776 Mutex* const SpaceManager::_expand_lock =
   777   new Mutex(SpaceManager::_expand_lock_rank,
   778             SpaceManager::_expand_lock_name,
   779             Mutex::_allow_vm_block_flag);
   781 void VirtualSpaceNode::inc_container_count() {
   782   assert_lock_strong(SpaceManager::expand_lock());
   783   _container_count++;
   784   assert(_container_count == container_count_slow(),
   785          err_msg("Inconsistency in countainer_count _container_count " SIZE_FORMAT
   786                  " container_count_slow() " SIZE_FORMAT,
   787                  _container_count, container_count_slow()));
   788 }
   790 void VirtualSpaceNode::dec_container_count() {
   791   assert_lock_strong(SpaceManager::expand_lock());
   792   _container_count--;
   793 }
   795 #ifdef ASSERT
   796 void VirtualSpaceNode::verify_container_count() {
   797   assert(_container_count == container_count_slow(),
   798     err_msg("Inconsistency in countainer_count _container_count " SIZE_FORMAT
   799             " container_count_slow() " SIZE_FORMAT, _container_count, container_count_slow()));
   800 }
   801 #endif
   803 // BlockFreelist methods
   805 BlockFreelist::BlockFreelist() : _dictionary(NULL) {}
   807 BlockFreelist::~BlockFreelist() {
   808   if (_dictionary != NULL) {
   809     if (Verbose && TraceMetadataChunkAllocation) {
   810       _dictionary->print_free_lists(gclog_or_tty);
   811     }
   812     delete _dictionary;
   813   }
   814 }
   816 Metablock* BlockFreelist::initialize_free_chunk(MetaWord* p, size_t word_size) {
   817   Metablock* block = (Metablock*) p;
   818   block->set_word_size(word_size);
   819   block->set_prev(NULL);
   820   block->set_next(NULL);
   822   return block;
   823 }
   825 void BlockFreelist::return_block(MetaWord* p, size_t word_size) {
   826   Metablock* free_chunk = initialize_free_chunk(p, 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>::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>::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->capacity_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_lock_strong(SpaceManager::expand_lock());
  1080   // Don't use a VirtualSpaceListIterator because this
  1081   // list is being changed and a straightforward use of an iterator is not safe.
  1082   VirtualSpaceNode* purged_vsl = NULL;
  1083   VirtualSpaceNode* prev_vsl = virtual_space_list();
  1084   VirtualSpaceNode* next_vsl = prev_vsl;
  1085   while (next_vsl != NULL) {
  1086     VirtualSpaceNode* vsl = next_vsl;
  1087     next_vsl = vsl->next();
  1088     // Don't free the current virtual space since it will likely
  1089     // be needed soon.
  1090     if (vsl->container_count() == 0 && vsl != current_virtual_space()) {
  1091       // Unlink it from the list
  1092       if (prev_vsl == vsl) {
  1093         // This is the case of the current node being the first node.
  1094         assert(vsl == virtual_space_list(), "Expected to be the first node");
  1095         set_virtual_space_list(vsl->next());
  1096       } else {
  1097         prev_vsl->set_next(vsl->next());
  1100       vsl->purge(chunk_manager);
  1101       dec_reserved_words(vsl->reserved_words());
  1102       dec_committed_words(vsl->committed_words());
  1103       dec_virtual_space_count();
  1104       purged_vsl = vsl;
  1105       delete vsl;
  1106     } else {
  1107       prev_vsl = vsl;
  1110 #ifdef ASSERT
  1111   if (purged_vsl != NULL) {
  1112   // List should be stable enough to use an iterator here.
  1113   VirtualSpaceListIterator iter(virtual_space_list());
  1114     while (iter.repeat()) {
  1115       VirtualSpaceNode* vsl = iter.get_next();
  1116       assert(vsl != purged_vsl, "Purge of vsl failed");
  1119 #endif
  1122 VirtualSpaceList::VirtualSpaceList(size_t word_size) :
  1123                                    _is_class(false),
  1124                                    _virtual_space_list(NULL),
  1125                                    _current_virtual_space(NULL),
  1126                                    _reserved_words(0),
  1127                                    _committed_words(0),
  1128                                    _virtual_space_count(0) {
  1129   MutexLockerEx cl(SpaceManager::expand_lock(),
  1130                    Mutex::_no_safepoint_check_flag);
  1131   create_new_virtual_space(word_size);
  1134 VirtualSpaceList::VirtualSpaceList(ReservedSpace rs) :
  1135                                    _is_class(true),
  1136                                    _virtual_space_list(NULL),
  1137                                    _current_virtual_space(NULL),
  1138                                    _reserved_words(0),
  1139                                    _committed_words(0),
  1140                                    _virtual_space_count(0) {
  1141   MutexLockerEx cl(SpaceManager::expand_lock(),
  1142                    Mutex::_no_safepoint_check_flag);
  1143   VirtualSpaceNode* class_entry = new VirtualSpaceNode(rs);
  1144   bool succeeded = class_entry->initialize();
  1145   if (succeeded) {
  1146     link_vs(class_entry);
  1150 size_t VirtualSpaceList::free_bytes() {
  1151   return virtual_space_list()->free_words_in_vs() * BytesPerWord;
  1154 // Allocate another meta virtual space and add it to the list.
  1155 bool VirtualSpaceList::create_new_virtual_space(size_t vs_word_size) {
  1156   assert_lock_strong(SpaceManager::expand_lock());
  1158   if (is_class()) {
  1159     assert(false, "We currently don't support more than one VirtualSpace for"
  1160                   " the compressed class space. The initialization of the"
  1161                   " CCS uses another code path and should not hit this path.");
  1162     return false;
  1165   if (vs_word_size == 0) {
  1166     assert(false, "vs_word_size should always be at least _reserve_alignment large.");
  1167     return false;
  1170   // Reserve the space
  1171   size_t vs_byte_size = vs_word_size * BytesPerWord;
  1172   assert_is_size_aligned(vs_byte_size, Metaspace::reserve_alignment());
  1174   // Allocate the meta virtual space and initialize it.
  1175   VirtualSpaceNode* new_entry = new VirtualSpaceNode(vs_byte_size);
  1176   if (!new_entry->initialize()) {
  1177     delete new_entry;
  1178     return false;
  1179   } else {
  1180     assert(new_entry->reserved_words() == vs_word_size,
  1181         "Reserved memory size differs from requested memory size");
  1182     // ensure lock-free iteration sees fully initialized node
  1183     OrderAccess::storestore();
  1184     link_vs(new_entry);
  1185     return true;
  1189 void VirtualSpaceList::link_vs(VirtualSpaceNode* new_entry) {
  1190   if (virtual_space_list() == NULL) {
  1191       set_virtual_space_list(new_entry);
  1192   } else {
  1193     current_virtual_space()->set_next(new_entry);
  1195   set_current_virtual_space(new_entry);
  1196   inc_reserved_words(new_entry->reserved_words());
  1197   inc_committed_words(new_entry->committed_words());
  1198   inc_virtual_space_count();
  1199 #ifdef ASSERT
  1200   new_entry->mangle();
  1201 #endif
  1202   if (TraceMetavirtualspaceAllocation && Verbose) {
  1203     VirtualSpaceNode* vsl = current_virtual_space();
  1204     vsl->print_on(gclog_or_tty);
  1208 bool VirtualSpaceList::expand_node_by(VirtualSpaceNode* node,
  1209                                       size_t min_words,
  1210                                       size_t preferred_words) {
  1211   size_t before = node->committed_words();
  1213   bool result = node->expand_by(min_words, preferred_words);
  1215   size_t after = node->committed_words();
  1217   // after and before can be the same if the memory was pre-committed.
  1218   assert(after >= before, "Inconsistency");
  1219   inc_committed_words(after - before);
  1221   return result;
  1224 bool VirtualSpaceList::expand_by(size_t min_words, size_t preferred_words) {
  1225   assert_is_size_aligned(min_words,       Metaspace::commit_alignment_words());
  1226   assert_is_size_aligned(preferred_words, Metaspace::commit_alignment_words());
  1227   assert(min_words <= preferred_words, "Invalid arguments");
  1229   if (!MetaspaceGC::can_expand(min_words, this->is_class())) {
  1230     return  false;
  1233   size_t allowed_expansion_words = MetaspaceGC::allowed_expansion();
  1234   if (allowed_expansion_words < min_words) {
  1235     return false;
  1238   size_t max_expansion_words = MIN2(preferred_words, allowed_expansion_words);
  1240   // Commit more memory from the the current virtual space.
  1241   bool vs_expanded = expand_node_by(current_virtual_space(),
  1242                                     min_words,
  1243                                     max_expansion_words);
  1244   if (vs_expanded) {
  1245     return true;
  1248   // Get another virtual space.
  1249   size_t grow_vs_words = MAX2((size_t)VirtualSpaceSize, preferred_words);
  1250   grow_vs_words = align_size_up(grow_vs_words, Metaspace::reserve_alignment_words());
  1252   if (create_new_virtual_space(grow_vs_words)) {
  1253     if (current_virtual_space()->is_pre_committed()) {
  1254       // The memory was pre-committed, so we are done here.
  1255       assert(min_words <= current_virtual_space()->committed_words(),
  1256           "The new VirtualSpace was pre-committed, so it"
  1257           "should be large enough to fit the alloc request.");
  1258       return true;
  1261     return expand_node_by(current_virtual_space(),
  1262                           min_words,
  1263                           max_expansion_words);
  1266   return false;
  1269 Metachunk* VirtualSpaceList::get_new_chunk(size_t word_size,
  1270                                            size_t grow_chunks_by_words,
  1271                                            size_t medium_chunk_bunch) {
  1273   // Allocate a chunk out of the current virtual space.
  1274   Metachunk* next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
  1276   if (next != NULL) {
  1277     return next;
  1280   // The expand amount is currently only determined by the requested sizes
  1281   // and not how much committed memory is left in the current virtual space.
  1283   size_t min_word_size       = align_size_up(grow_chunks_by_words, Metaspace::commit_alignment_words());
  1284   size_t preferred_word_size = align_size_up(medium_chunk_bunch,   Metaspace::commit_alignment_words());
  1285   if (min_word_size >= preferred_word_size) {
  1286     // Can happen when humongous chunks are allocated.
  1287     preferred_word_size = min_word_size;
  1290   bool expanded = expand_by(min_word_size, preferred_word_size);
  1291   if (expanded) {
  1292     next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
  1293     assert(next != NULL, "The allocation was expected to succeed after the expansion");
  1296    return next;
  1299 void VirtualSpaceList::print_on(outputStream* st) const {
  1300   if (TraceMetadataChunkAllocation && Verbose) {
  1301     VirtualSpaceListIterator iter(virtual_space_list());
  1302     while (iter.repeat()) {
  1303       VirtualSpaceNode* node = iter.get_next();
  1304       node->print_on(st);
  1309 bool VirtualSpaceList::contains(const void *ptr) {
  1310   VirtualSpaceNode* list = virtual_space_list();
  1311   VirtualSpaceListIterator iter(list);
  1312   while (iter.repeat()) {
  1313     VirtualSpaceNode* node = iter.get_next();
  1314     if (node->reserved()->contains(ptr)) {
  1315       return true;
  1318   return false;
  1322 // MetaspaceGC methods
  1324 // VM_CollectForMetadataAllocation is the vm operation used to GC.
  1325 // Within the VM operation after the GC the attempt to allocate the metadata
  1326 // should succeed.  If the GC did not free enough space for the metaspace
  1327 // allocation, the HWM is increased so that another virtualspace will be
  1328 // allocated for the metadata.  With perm gen the increase in the perm
  1329 // gen had bounds, MinMetaspaceExpansion and MaxMetaspaceExpansion.  The
  1330 // metaspace policy uses those as the small and large steps for the HWM.
  1331 //
  1332 // After the GC the compute_new_size() for MetaspaceGC is called to
  1333 // resize the capacity of the metaspaces.  The current implementation
  1334 // is based on the flags MinMetaspaceFreeRatio and MaxMetaspaceFreeRatio used
  1335 // to resize the Java heap by some GC's.  New flags can be implemented
  1336 // if really needed.  MinMetaspaceFreeRatio is used to calculate how much
  1337 // free space is desirable in the metaspace capacity to decide how much
  1338 // to increase the HWM.  MaxMetaspaceFreeRatio is used to decide how much
  1339 // free space is desirable in the metaspace capacity before decreasing
  1340 // the HWM.
  1342 // Calculate the amount to increase the high water mark (HWM).
  1343 // Increase by a minimum amount (MinMetaspaceExpansion) so that
  1344 // another expansion is not requested too soon.  If that is not
  1345 // enough to satisfy the allocation, increase by MaxMetaspaceExpansion.
  1346 // If that is still not enough, expand by the size of the allocation
  1347 // plus some.
  1348 size_t MetaspaceGC::delta_capacity_until_GC(size_t bytes) {
  1349   size_t min_delta = MinMetaspaceExpansion;
  1350   size_t max_delta = MaxMetaspaceExpansion;
  1351   size_t delta = align_size_up(bytes, Metaspace::commit_alignment());
  1353   if (delta <= min_delta) {
  1354     delta = min_delta;
  1355   } else if (delta <= max_delta) {
  1356     // Don't want to hit the high water mark on the next
  1357     // allocation so make the delta greater than just enough
  1358     // for this allocation.
  1359     delta = max_delta;
  1360   } else {
  1361     // This allocation is large but the next ones are probably not
  1362     // so increase by the minimum.
  1363     delta = delta + min_delta;
  1366   assert_is_size_aligned(delta, Metaspace::commit_alignment());
  1368   return delta;
  1371 size_t MetaspaceGC::capacity_until_GC() {
  1372   size_t value = (size_t)OrderAccess::load_ptr_acquire(&_capacity_until_GC);
  1373   assert(value >= MetaspaceSize, "Not initialied properly?");
  1374   return value;
  1377 size_t MetaspaceGC::inc_capacity_until_GC(size_t v) {
  1378   assert_is_size_aligned(v, Metaspace::commit_alignment());
  1380   return (size_t)Atomic::add_ptr(v, &_capacity_until_GC);
  1383 size_t MetaspaceGC::dec_capacity_until_GC(size_t v) {
  1384   assert_is_size_aligned(v, Metaspace::commit_alignment());
  1386   return (size_t)Atomic::add_ptr(-(intptr_t)v, &_capacity_until_GC);
  1389 bool MetaspaceGC::can_expand(size_t word_size, bool is_class) {
  1390   // Check if the compressed class space is full.
  1391   if (is_class && Metaspace::using_class_space()) {
  1392     size_t class_committed = MetaspaceAux::committed_bytes(Metaspace::ClassType);
  1393     if (class_committed + word_size * BytesPerWord > CompressedClassSpaceSize) {
  1394       return false;
  1398   // Check if the user has imposed a limit on the metaspace memory.
  1399   size_t committed_bytes = MetaspaceAux::committed_bytes();
  1400   if (committed_bytes + word_size * BytesPerWord > MaxMetaspaceSize) {
  1401     return false;
  1404   return true;
  1407 size_t MetaspaceGC::allowed_expansion() {
  1408   size_t committed_bytes = MetaspaceAux::committed_bytes();
  1410   size_t left_until_max  = MaxMetaspaceSize - committed_bytes;
  1412   // Always grant expansion if we are initiating the JVM,
  1413   // or if the GC_locker is preventing GCs.
  1414   if (!is_init_completed() || GC_locker::is_active_and_needs_gc()) {
  1415     return left_until_max / BytesPerWord;
  1418   size_t capacity_until_gc = capacity_until_GC();
  1420   if (capacity_until_gc <= committed_bytes) {
  1421     return 0;
  1424   size_t left_until_GC = capacity_until_gc - committed_bytes;
  1425   size_t left_to_commit = MIN2(left_until_GC, left_until_max);
  1427   return left_to_commit / BytesPerWord;
  1430 void MetaspaceGC::compute_new_size() {
  1431   assert(_shrink_factor <= 100, "invalid shrink factor");
  1432   uint current_shrink_factor = _shrink_factor;
  1433   _shrink_factor = 0;
  1435   const size_t used_after_gc = MetaspaceAux::allocated_capacity_bytes();
  1436   const size_t capacity_until_GC = MetaspaceGC::capacity_until_GC();
  1438   const double minimum_free_percentage = MinMetaspaceFreeRatio / 100.0;
  1439   const double maximum_used_percentage = 1.0 - minimum_free_percentage;
  1441   const double min_tmp = used_after_gc / maximum_used_percentage;
  1442   size_t minimum_desired_capacity =
  1443     (size_t)MIN2(min_tmp, double(max_uintx));
  1444   // Don't shrink less than the initial generation size
  1445   minimum_desired_capacity = MAX2(minimum_desired_capacity,
  1446                                   MetaspaceSize);
  1448   if (PrintGCDetails && Verbose) {
  1449     gclog_or_tty->print_cr("\nMetaspaceGC::compute_new_size: ");
  1450     gclog_or_tty->print_cr("  "
  1451                   "  minimum_free_percentage: %6.2f"
  1452                   "  maximum_used_percentage: %6.2f",
  1453                   minimum_free_percentage,
  1454                   maximum_used_percentage);
  1455     gclog_or_tty->print_cr("  "
  1456                   "   used_after_gc       : %6.1fKB",
  1457                   used_after_gc / (double) K);
  1461   size_t shrink_bytes = 0;
  1462   if (capacity_until_GC < minimum_desired_capacity) {
  1463     // If we have less capacity below the metaspace HWM, then
  1464     // increment the HWM.
  1465     size_t expand_bytes = minimum_desired_capacity - capacity_until_GC;
  1466     expand_bytes = align_size_up(expand_bytes, Metaspace::commit_alignment());
  1467     // Don't expand unless it's significant
  1468     if (expand_bytes >= MinMetaspaceExpansion) {
  1469       MetaspaceGC::inc_capacity_until_GC(expand_bytes);
  1471     if (PrintGCDetails && Verbose) {
  1472       size_t new_capacity_until_GC = capacity_until_GC;
  1473       gclog_or_tty->print_cr("    expanding:"
  1474                     "  minimum_desired_capacity: %6.1fKB"
  1475                     "  expand_bytes: %6.1fKB"
  1476                     "  MinMetaspaceExpansion: %6.1fKB"
  1477                     "  new metaspace HWM:  %6.1fKB",
  1478                     minimum_desired_capacity / (double) K,
  1479                     expand_bytes / (double) K,
  1480                     MinMetaspaceExpansion / (double) K,
  1481                     new_capacity_until_GC / (double) K);
  1483     return;
  1486   // No expansion, now see if we want to shrink
  1487   // We would never want to shrink more than this
  1488   size_t max_shrink_bytes = capacity_until_GC - minimum_desired_capacity;
  1489   assert(max_shrink_bytes >= 0, err_msg("max_shrink_bytes " SIZE_FORMAT,
  1490     max_shrink_bytes));
  1492   // Should shrinking be considered?
  1493   if (MaxMetaspaceFreeRatio < 100) {
  1494     const double maximum_free_percentage = MaxMetaspaceFreeRatio / 100.0;
  1495     const double minimum_used_percentage = 1.0 - maximum_free_percentage;
  1496     const double max_tmp = used_after_gc / minimum_used_percentage;
  1497     size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(max_uintx));
  1498     maximum_desired_capacity = MAX2(maximum_desired_capacity,
  1499                                     MetaspaceSize);
  1500     if (PrintGCDetails && Verbose) {
  1501       gclog_or_tty->print_cr("  "
  1502                              "  maximum_free_percentage: %6.2f"
  1503                              "  minimum_used_percentage: %6.2f",
  1504                              maximum_free_percentage,
  1505                              minimum_used_percentage);
  1506       gclog_or_tty->print_cr("  "
  1507                              "  minimum_desired_capacity: %6.1fKB"
  1508                              "  maximum_desired_capacity: %6.1fKB",
  1509                              minimum_desired_capacity / (double) K,
  1510                              maximum_desired_capacity / (double) K);
  1513     assert(minimum_desired_capacity <= maximum_desired_capacity,
  1514            "sanity check");
  1516     if (capacity_until_GC > maximum_desired_capacity) {
  1517       // Capacity too large, compute shrinking size
  1518       shrink_bytes = capacity_until_GC - maximum_desired_capacity;
  1519       // We don't want shrink all the way back to initSize if people call
  1520       // System.gc(), because some programs do that between "phases" and then
  1521       // we'd just have to grow the heap up again for the next phase.  So we
  1522       // damp the shrinking: 0% on the first call, 10% on the second call, 40%
  1523       // on the third call, and 100% by the fourth call.  But if we recompute
  1524       // size without shrinking, it goes back to 0%.
  1525       shrink_bytes = shrink_bytes / 100 * current_shrink_factor;
  1527       shrink_bytes = align_size_down(shrink_bytes, Metaspace::commit_alignment());
  1529       assert(shrink_bytes <= max_shrink_bytes,
  1530         err_msg("invalid shrink size " SIZE_FORMAT " not <= " SIZE_FORMAT,
  1531           shrink_bytes, max_shrink_bytes));
  1532       if (current_shrink_factor == 0) {
  1533         _shrink_factor = 10;
  1534       } else {
  1535         _shrink_factor = MIN2(current_shrink_factor * 4, (uint) 100);
  1537       if (PrintGCDetails && Verbose) {
  1538         gclog_or_tty->print_cr("  "
  1539                       "  shrinking:"
  1540                       "  initSize: %.1fK"
  1541                       "  maximum_desired_capacity: %.1fK",
  1542                       MetaspaceSize / (double) K,
  1543                       maximum_desired_capacity / (double) K);
  1544         gclog_or_tty->print_cr("  "
  1545                       "  shrink_bytes: %.1fK"
  1546                       "  current_shrink_factor: %d"
  1547                       "  new shrink factor: %d"
  1548                       "  MinMetaspaceExpansion: %.1fK",
  1549                       shrink_bytes / (double) K,
  1550                       current_shrink_factor,
  1551                       _shrink_factor,
  1552                       MinMetaspaceExpansion / (double) K);
  1557   // Don't shrink unless it's significant
  1558   if (shrink_bytes >= MinMetaspaceExpansion &&
  1559       ((capacity_until_GC - shrink_bytes) >= MetaspaceSize)) {
  1560     MetaspaceGC::dec_capacity_until_GC(shrink_bytes);
  1564 // Metadebug methods
  1566 void Metadebug::deallocate_chunk_a_lot(SpaceManager* sm,
  1567                                        size_t chunk_word_size){
  1568 #ifdef ASSERT
  1569   VirtualSpaceList* vsl = sm->vs_list();
  1570   if (MetaDataDeallocateALot &&
  1571       Metadebug::deallocate_chunk_a_lot_count() % MetaDataDeallocateALotInterval == 0 ) {
  1572     Metadebug::reset_deallocate_chunk_a_lot_count();
  1573     for (uint i = 0; i < metadata_deallocate_a_lock_chunk; i++) {
  1574       Metachunk* dummy_chunk = vsl->current_virtual_space()->take_from_committed(chunk_word_size);
  1575       if (dummy_chunk == NULL) {
  1576         break;
  1578       sm->chunk_manager()->chunk_freelist_deallocate(dummy_chunk);
  1580       if (TraceMetadataChunkAllocation && Verbose) {
  1581         gclog_or_tty->print("Metadebug::deallocate_chunk_a_lot: %d) ",
  1582                                sm->sum_count_in_chunks_in_use());
  1583         dummy_chunk->print_on(gclog_or_tty);
  1584         gclog_or_tty->print_cr("  Free chunks total %d  count %d",
  1585                                sm->chunk_manager()->free_chunks_total_words(),
  1586                                sm->chunk_manager()->free_chunks_count());
  1589   } else {
  1590     Metadebug::inc_deallocate_chunk_a_lot_count();
  1592 #endif
  1595 void Metadebug::deallocate_block_a_lot(SpaceManager* sm,
  1596                                        size_t raw_word_size){
  1597 #ifdef ASSERT
  1598   if (MetaDataDeallocateALot &&
  1599         Metadebug::deallocate_block_a_lot_count() % MetaDataDeallocateALotInterval == 0 ) {
  1600     Metadebug::set_deallocate_block_a_lot_count(0);
  1601     for (uint i = 0; i < metadata_deallocate_a_lot_block; i++) {
  1602       MetaWord* dummy_block = sm->allocate_work(raw_word_size);
  1603       if (dummy_block == 0) {
  1604         break;
  1606       sm->deallocate(dummy_block, raw_word_size);
  1608   } else {
  1609     Metadebug::inc_deallocate_block_a_lot_count();
  1611 #endif
  1614 void Metadebug::init_allocation_fail_alot_count() {
  1615   if (MetadataAllocationFailALot) {
  1616     _allocation_fail_alot_count =
  1617       1+(long)((double)MetadataAllocationFailALotInterval*os::random()/(max_jint+1.0));
  1621 #ifdef ASSERT
  1622 bool Metadebug::test_metadata_failure() {
  1623   if (MetadataAllocationFailALot &&
  1624       Threads::is_vm_complete()) {
  1625     if (_allocation_fail_alot_count > 0) {
  1626       _allocation_fail_alot_count--;
  1627     } else {
  1628       if (TraceMetadataChunkAllocation && Verbose) {
  1629         gclog_or_tty->print_cr("Metadata allocation failing for "
  1630                                "MetadataAllocationFailALot");
  1632       init_allocation_fail_alot_count();
  1633       return true;
  1636   return false;
  1638 #endif
  1640 // ChunkManager methods
  1642 size_t ChunkManager::free_chunks_total_words() {
  1643   return _free_chunks_total;
  1646 size_t ChunkManager::free_chunks_total_bytes() {
  1647   return free_chunks_total_words() * BytesPerWord;
  1650 size_t ChunkManager::free_chunks_count() {
  1651 #ifdef ASSERT
  1652   if (!UseConcMarkSweepGC && !SpaceManager::expand_lock()->is_locked()) {
  1653     MutexLockerEx cl(SpaceManager::expand_lock(),
  1654                      Mutex::_no_safepoint_check_flag);
  1655     // This lock is only needed in debug because the verification
  1656     // of the _free_chunks_totals walks the list of free chunks
  1657     slow_locked_verify_free_chunks_count();
  1659 #endif
  1660   return _free_chunks_count;
  1663 void ChunkManager::locked_verify_free_chunks_total() {
  1664   assert_lock_strong(SpaceManager::expand_lock());
  1665   assert(sum_free_chunks() == _free_chunks_total,
  1666     err_msg("_free_chunks_total " SIZE_FORMAT " is not the"
  1667            " same as sum " SIZE_FORMAT, _free_chunks_total,
  1668            sum_free_chunks()));
  1671 void ChunkManager::verify_free_chunks_total() {
  1672   MutexLockerEx cl(SpaceManager::expand_lock(),
  1673                      Mutex::_no_safepoint_check_flag);
  1674   locked_verify_free_chunks_total();
  1677 void ChunkManager::locked_verify_free_chunks_count() {
  1678   assert_lock_strong(SpaceManager::expand_lock());
  1679   assert(sum_free_chunks_count() == _free_chunks_count,
  1680     err_msg("_free_chunks_count " SIZE_FORMAT " is not the"
  1681            " same as sum " SIZE_FORMAT, _free_chunks_count,
  1682            sum_free_chunks_count()));
  1685 void ChunkManager::verify_free_chunks_count() {
  1686 #ifdef ASSERT
  1687   MutexLockerEx cl(SpaceManager::expand_lock(),
  1688                      Mutex::_no_safepoint_check_flag);
  1689   locked_verify_free_chunks_count();
  1690 #endif
  1693 void ChunkManager::verify() {
  1694   MutexLockerEx cl(SpaceManager::expand_lock(),
  1695                      Mutex::_no_safepoint_check_flag);
  1696   locked_verify();
  1699 void ChunkManager::locked_verify() {
  1700   locked_verify_free_chunks_count();
  1701   locked_verify_free_chunks_total();
  1704 void ChunkManager::locked_print_free_chunks(outputStream* st) {
  1705   assert_lock_strong(SpaceManager::expand_lock());
  1706   st->print_cr("Free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
  1707                 _free_chunks_total, _free_chunks_count);
  1710 void ChunkManager::locked_print_sum_free_chunks(outputStream* st) {
  1711   assert_lock_strong(SpaceManager::expand_lock());
  1712   st->print_cr("Sum free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
  1713                 sum_free_chunks(), sum_free_chunks_count());
  1715 ChunkList* ChunkManager::free_chunks(ChunkIndex index) {
  1716   return &_free_chunks[index];
  1719 // These methods that sum the free chunk lists are used in printing
  1720 // methods that are used in product builds.
  1721 size_t ChunkManager::sum_free_chunks() {
  1722   assert_lock_strong(SpaceManager::expand_lock());
  1723   size_t result = 0;
  1724   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
  1725     ChunkList* list = free_chunks(i);
  1727     if (list == NULL) {
  1728       continue;
  1731     result = result + list->count() * list->size();
  1733   result = result + humongous_dictionary()->total_size();
  1734   return result;
  1737 size_t ChunkManager::sum_free_chunks_count() {
  1738   assert_lock_strong(SpaceManager::expand_lock());
  1739   size_t count = 0;
  1740   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
  1741     ChunkList* list = free_chunks(i);
  1742     if (list == NULL) {
  1743       continue;
  1745     count = count + list->count();
  1747   count = count + humongous_dictionary()->total_free_blocks();
  1748   return count;
  1751 ChunkList* ChunkManager::find_free_chunks_list(size_t word_size) {
  1752   ChunkIndex index = list_index(word_size);
  1753   assert(index < HumongousIndex, "No humongous list");
  1754   return free_chunks(index);
  1757 void ChunkManager::free_chunks_put(Metachunk* chunk) {
  1758   assert_lock_strong(SpaceManager::expand_lock());
  1759   ChunkList* free_list = find_free_chunks_list(chunk->word_size());
  1760   chunk->set_next(free_list->head());
  1761   free_list->set_head(chunk);
  1762   // chunk is being returned to the chunk free list
  1763   inc_free_chunks_total(chunk->capacity_word_size());
  1764   slow_locked_verify();
  1767 void ChunkManager::chunk_freelist_deallocate(Metachunk* chunk) {
  1768   // The deallocation of a chunk originates in the freelist
  1769   // manangement code for a Metaspace and does not hold the
  1770   // lock.
  1771   assert(chunk != NULL, "Deallocating NULL");
  1772   assert_lock_strong(SpaceManager::expand_lock());
  1773   slow_locked_verify();
  1774   if (TraceMetadataChunkAllocation) {
  1775     gclog_or_tty->print_cr("ChunkManager::chunk_freelist_deallocate: chunk "
  1776                            PTR_FORMAT "  size " SIZE_FORMAT,
  1777                            chunk, chunk->word_size());
  1779   free_chunks_put(chunk);
  1782 Metachunk* ChunkManager::free_chunks_get(size_t word_size) {
  1783   assert_lock_strong(SpaceManager::expand_lock());
  1785   slow_locked_verify();
  1787   Metachunk* chunk = NULL;
  1788   if (list_index(word_size) != HumongousIndex) {
  1789     ChunkList* free_list = find_free_chunks_list(word_size);
  1790     assert(free_list != NULL, "Sanity check");
  1792     chunk = free_list->head();
  1794     if (chunk == NULL) {
  1795       return NULL;
  1798     // Remove the chunk as the head of the list.
  1799     free_list->remove_chunk(chunk);
  1801     if (TraceMetadataChunkAllocation && Verbose) {
  1802       gclog_or_tty->print_cr("ChunkManager::free_chunks_get: free_list "
  1803                              PTR_FORMAT " head " PTR_FORMAT " size " SIZE_FORMAT,
  1804                              free_list, chunk, chunk->word_size());
  1806   } else {
  1807     chunk = humongous_dictionary()->get_chunk(
  1808       word_size,
  1809       FreeBlockDictionary<Metachunk>::atLeast);
  1811     if (chunk == NULL) {
  1812       return NULL;
  1815     if (TraceMetadataHumongousAllocation) {
  1816       size_t waste = chunk->word_size() - word_size;
  1817       gclog_or_tty->print_cr("Free list allocate humongous chunk size "
  1818                              SIZE_FORMAT " for requested size " SIZE_FORMAT
  1819                              " waste " SIZE_FORMAT,
  1820                              chunk->word_size(), word_size, waste);
  1824   // Chunk is being removed from the chunks free list.
  1825   dec_free_chunks_total(chunk->capacity_word_size());
  1827   // Remove it from the links to this freelist
  1828   chunk->set_next(NULL);
  1829   chunk->set_prev(NULL);
  1830 #ifdef ASSERT
  1831   // Chunk is no longer on any freelist. Setting to false make container_count_slow()
  1832   // work.
  1833   chunk->set_is_free(false);
  1834 #endif
  1835   chunk->container()->inc_container_count();
  1837   slow_locked_verify();
  1838   return chunk;
  1841 Metachunk* ChunkManager::chunk_freelist_allocate(size_t word_size) {
  1842   assert_lock_strong(SpaceManager::expand_lock());
  1843   slow_locked_verify();
  1845   // Take from the beginning of the list
  1846   Metachunk* chunk = free_chunks_get(word_size);
  1847   if (chunk == NULL) {
  1848     return NULL;
  1851   assert((word_size <= chunk->word_size()) ||
  1852          list_index(chunk->word_size() == HumongousIndex),
  1853          "Non-humongous variable sized chunk");
  1854   if (TraceMetadataChunkAllocation) {
  1855     size_t list_count;
  1856     if (list_index(word_size) < HumongousIndex) {
  1857       ChunkList* list = find_free_chunks_list(word_size);
  1858       list_count = list->count();
  1859     } else {
  1860       list_count = humongous_dictionary()->total_count();
  1862     gclog_or_tty->print("ChunkManager::chunk_freelist_allocate: " PTR_FORMAT " chunk "
  1863                         PTR_FORMAT "  size " SIZE_FORMAT " count " SIZE_FORMAT " ",
  1864                         this, chunk, chunk->word_size(), list_count);
  1865     locked_print_free_chunks(gclog_or_tty);
  1868   return chunk;
  1871 void ChunkManager::print_on(outputStream* out) const {
  1872   if (PrintFLSStatistics != 0) {
  1873     const_cast<ChunkManager *>(this)->humongous_dictionary()->report_statistics();
  1877 // SpaceManager methods
  1879 void SpaceManager::get_initial_chunk_sizes(Metaspace::MetaspaceType type,
  1880                                            size_t* chunk_word_size,
  1881                                            size_t* class_chunk_word_size) {
  1882   switch (type) {
  1883   case Metaspace::BootMetaspaceType:
  1884     *chunk_word_size = Metaspace::first_chunk_word_size();
  1885     *class_chunk_word_size = Metaspace::first_class_chunk_word_size();
  1886     break;
  1887   case Metaspace::ROMetaspaceType:
  1888     *chunk_word_size = SharedReadOnlySize / wordSize;
  1889     *class_chunk_word_size = ClassSpecializedChunk;
  1890     break;
  1891   case Metaspace::ReadWriteMetaspaceType:
  1892     *chunk_word_size = SharedReadWriteSize / wordSize;
  1893     *class_chunk_word_size = ClassSpecializedChunk;
  1894     break;
  1895   case Metaspace::AnonymousMetaspaceType:
  1896   case Metaspace::ReflectionMetaspaceType:
  1897     *chunk_word_size = SpecializedChunk;
  1898     *class_chunk_word_size = ClassSpecializedChunk;
  1899     break;
  1900   default:
  1901     *chunk_word_size = SmallChunk;
  1902     *class_chunk_word_size = ClassSmallChunk;
  1903     break;
  1905   assert(*chunk_word_size != 0 && *class_chunk_word_size != 0,
  1906     err_msg("Initial chunks sizes bad: data  " SIZE_FORMAT
  1907             " class " SIZE_FORMAT,
  1908             *chunk_word_size, *class_chunk_word_size));
  1911 size_t SpaceManager::sum_free_in_chunks_in_use() const {
  1912   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1913   size_t free = 0;
  1914   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1915     Metachunk* chunk = chunks_in_use(i);
  1916     while (chunk != NULL) {
  1917       free += chunk->free_word_size();
  1918       chunk = chunk->next();
  1921   return free;
  1924 size_t SpaceManager::sum_waste_in_chunks_in_use() const {
  1925   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1926   size_t result = 0;
  1927   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1928    result += sum_waste_in_chunks_in_use(i);
  1931   return result;
  1934 size_t SpaceManager::sum_waste_in_chunks_in_use(ChunkIndex index) const {
  1935   size_t result = 0;
  1936   Metachunk* chunk = chunks_in_use(index);
  1937   // Count the free space in all the chunk but not the
  1938   // current chunk from which allocations are still being done.
  1939   while (chunk != NULL) {
  1940     if (chunk != current_chunk()) {
  1941       result += chunk->free_word_size();
  1943     chunk = chunk->next();
  1945   return result;
  1948 size_t SpaceManager::sum_capacity_in_chunks_in_use() const {
  1949   // For CMS use "allocated_chunks_words()" which does not need the
  1950   // Metaspace lock.  For the other collectors sum over the
  1951   // lists.  Use both methods as a check that "allocated_chunks_words()"
  1952   // is correct.  That is, sum_capacity_in_chunks() is too expensive
  1953   // to use in the product and allocated_chunks_words() should be used
  1954   // but allow for  checking that allocated_chunks_words() returns the same
  1955   // value as sum_capacity_in_chunks_in_use() which is the definitive
  1956   // answer.
  1957   if (UseConcMarkSweepGC) {
  1958     return allocated_chunks_words();
  1959   } else {
  1960     MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1961     size_t sum = 0;
  1962     for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1963       Metachunk* chunk = chunks_in_use(i);
  1964       while (chunk != NULL) {
  1965         sum += chunk->capacity_word_size();
  1966         chunk = chunk->next();
  1969   return sum;
  1973 size_t SpaceManager::sum_count_in_chunks_in_use() {
  1974   size_t count = 0;
  1975   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1976     count = count + sum_count_in_chunks_in_use(i);
  1979   return count;
  1982 size_t SpaceManager::sum_count_in_chunks_in_use(ChunkIndex i) {
  1983   size_t count = 0;
  1984   Metachunk* chunk = chunks_in_use(i);
  1985   while (chunk != NULL) {
  1986     count++;
  1987     chunk = chunk->next();
  1989   return count;
  1993 size_t SpaceManager::sum_used_in_chunks_in_use() const {
  1994   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1995   size_t used = 0;
  1996   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1997     Metachunk* chunk = chunks_in_use(i);
  1998     while (chunk != NULL) {
  1999       used += chunk->used_word_size();
  2000       chunk = chunk->next();
  2003   return used;
  2006 void SpaceManager::locked_print_chunks_in_use_on(outputStream* st) const {
  2008   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2009     Metachunk* chunk = chunks_in_use(i);
  2010     st->print("SpaceManager: %s " PTR_FORMAT,
  2011                  chunk_size_name(i), chunk);
  2012     if (chunk != NULL) {
  2013       st->print_cr(" free " SIZE_FORMAT,
  2014                    chunk->free_word_size());
  2015     } else {
  2016       st->print_cr("");
  2020   chunk_manager()->locked_print_free_chunks(st);
  2021   chunk_manager()->locked_print_sum_free_chunks(st);
  2024 size_t SpaceManager::calc_chunk_size(size_t word_size) {
  2026   // Decide between a small chunk and a medium chunk.  Up to
  2027   // _small_chunk_limit small chunks can be allocated but
  2028   // once a medium chunk has been allocated, no more small
  2029   // chunks will be allocated.
  2030   size_t chunk_word_size;
  2031   if (chunks_in_use(MediumIndex) == NULL &&
  2032       sum_count_in_chunks_in_use(SmallIndex) < _small_chunk_limit) {
  2033     chunk_word_size = (size_t) small_chunk_size();
  2034     if (word_size + Metachunk::overhead() > small_chunk_size()) {
  2035       chunk_word_size = medium_chunk_size();
  2037   } else {
  2038     chunk_word_size = medium_chunk_size();
  2041   // Might still need a humongous chunk.  Enforce an
  2042   // eight word granularity to facilitate reuse (some
  2043   // wastage but better chance of reuse).
  2044   size_t if_humongous_sized_chunk =
  2045     align_size_up(word_size + Metachunk::overhead(),
  2046                   HumongousChunkGranularity);
  2047   chunk_word_size =
  2048     MAX2((size_t) chunk_word_size, if_humongous_sized_chunk);
  2050   assert(!SpaceManager::is_humongous(word_size) ||
  2051          chunk_word_size == if_humongous_sized_chunk,
  2052          err_msg("Size calculation is wrong, word_size " SIZE_FORMAT
  2053                  " chunk_word_size " SIZE_FORMAT,
  2054                  word_size, chunk_word_size));
  2055   if (TraceMetadataHumongousAllocation &&
  2056       SpaceManager::is_humongous(word_size)) {
  2057     gclog_or_tty->print_cr("Metadata humongous allocation:");
  2058     gclog_or_tty->print_cr("  word_size " PTR_FORMAT, word_size);
  2059     gclog_or_tty->print_cr("  chunk_word_size " PTR_FORMAT,
  2060                            chunk_word_size);
  2061     gclog_or_tty->print_cr("    chunk overhead " PTR_FORMAT,
  2062                            Metachunk::overhead());
  2064   return chunk_word_size;
  2067 void SpaceManager::track_metaspace_memory_usage() {
  2068   if (is_init_completed()) {
  2069     if (is_class()) {
  2070       MemoryService::track_compressed_class_memory_usage();
  2072     MemoryService::track_metaspace_memory_usage();
  2076 MetaWord* SpaceManager::grow_and_allocate(size_t word_size) {
  2077   assert(vs_list()->current_virtual_space() != NULL,
  2078          "Should have been set");
  2079   assert(current_chunk() == NULL ||
  2080          current_chunk()->allocate(word_size) == NULL,
  2081          "Don't need to expand");
  2082   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  2084   if (TraceMetadataChunkAllocation && Verbose) {
  2085     size_t words_left = 0;
  2086     size_t words_used = 0;
  2087     if (current_chunk() != NULL) {
  2088       words_left = current_chunk()->free_word_size();
  2089       words_used = current_chunk()->used_word_size();
  2091     gclog_or_tty->print_cr("SpaceManager::grow_and_allocate for " SIZE_FORMAT
  2092                            " words " SIZE_FORMAT " words used " SIZE_FORMAT
  2093                            " words left",
  2094                             word_size, words_used, words_left);
  2097   // Get another chunk out of the virtual space
  2098   size_t grow_chunks_by_words = calc_chunk_size(word_size);
  2099   Metachunk* next = get_new_chunk(word_size, grow_chunks_by_words);
  2101   if (next != NULL) {
  2102     Metadebug::deallocate_chunk_a_lot(this, grow_chunks_by_words);
  2105   MetaWord* mem = NULL;
  2107   // If a chunk was available, add it to the in-use chunk list
  2108   // and do an allocation from it.
  2109   if (next != NULL) {
  2110     // Add to this manager's list of chunks in use.
  2111     add_chunk(next, false);
  2112     mem = next->allocate(word_size);
  2115   // Track metaspace memory usage statistic.
  2116   track_metaspace_memory_usage();
  2118   return mem;
  2121 void SpaceManager::print_on(outputStream* st) const {
  2123   for (ChunkIndex i = ZeroIndex;
  2124        i < NumberOfInUseLists ;
  2125        i = next_chunk_index(i) ) {
  2126     st->print_cr("  chunks_in_use " PTR_FORMAT " chunk size " PTR_FORMAT,
  2127                  chunks_in_use(i),
  2128                  chunks_in_use(i) == NULL ? 0 : chunks_in_use(i)->word_size());
  2130   st->print_cr("    waste:  Small " SIZE_FORMAT " Medium " SIZE_FORMAT
  2131                " Humongous " SIZE_FORMAT,
  2132                sum_waste_in_chunks_in_use(SmallIndex),
  2133                sum_waste_in_chunks_in_use(MediumIndex),
  2134                sum_waste_in_chunks_in_use(HumongousIndex));
  2135   // block free lists
  2136   if (block_freelists() != NULL) {
  2137     st->print_cr("total in block free lists " SIZE_FORMAT,
  2138       block_freelists()->total_size());
  2142 SpaceManager::SpaceManager(Metaspace::MetadataType mdtype,
  2143                            Mutex* lock) :
  2144   _mdtype(mdtype),
  2145   _allocated_blocks_words(0),
  2146   _allocated_chunks_words(0),
  2147   _allocated_chunks_count(0),
  2148   _lock(lock)
  2150   initialize();
  2153 void SpaceManager::inc_size_metrics(size_t words) {
  2154   assert_lock_strong(SpaceManager::expand_lock());
  2155   // Total of allocated Metachunks and allocated Metachunks count
  2156   // for each SpaceManager
  2157   _allocated_chunks_words = _allocated_chunks_words + words;
  2158   _allocated_chunks_count++;
  2159   // Global total of capacity in allocated Metachunks
  2160   MetaspaceAux::inc_capacity(mdtype(), words);
  2161   // Global total of allocated Metablocks.
  2162   // used_words_slow() includes the overhead in each
  2163   // Metachunk so include it in the used when the
  2164   // Metachunk is first added (so only added once per
  2165   // Metachunk).
  2166   MetaspaceAux::inc_used(mdtype(), Metachunk::overhead());
  2169 void SpaceManager::inc_used_metrics(size_t words) {
  2170   // Add to the per SpaceManager total
  2171   Atomic::add_ptr(words, &_allocated_blocks_words);
  2172   // Add to the global total
  2173   MetaspaceAux::inc_used(mdtype(), words);
  2176 void SpaceManager::dec_total_from_size_metrics() {
  2177   MetaspaceAux::dec_capacity(mdtype(), allocated_chunks_words());
  2178   MetaspaceAux::dec_used(mdtype(), allocated_blocks_words());
  2179   // Also deduct the overhead per Metachunk
  2180   MetaspaceAux::dec_used(mdtype(), allocated_chunks_count() * Metachunk::overhead());
  2183 void SpaceManager::initialize() {
  2184   Metadebug::init_allocation_fail_alot_count();
  2185   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2186     _chunks_in_use[i] = NULL;
  2188   _current_chunk = NULL;
  2189   if (TraceMetadataChunkAllocation && Verbose) {
  2190     gclog_or_tty->print_cr("SpaceManager(): " PTR_FORMAT, this);
  2194 void ChunkManager::return_chunks(ChunkIndex index, Metachunk* chunks) {
  2195   if (chunks == NULL) {
  2196     return;
  2198   ChunkList* list = free_chunks(index);
  2199   assert(list->size() == chunks->word_size(), "Mismatch in chunk sizes");
  2200   assert_lock_strong(SpaceManager::expand_lock());
  2201   Metachunk* cur = chunks;
  2203   // This returns chunks one at a time.  If a new
  2204   // class List can be created that is a base class
  2205   // of FreeList then something like FreeList::prepend()
  2206   // can be used in place of this loop
  2207   while (cur != NULL) {
  2208     assert(cur->container() != NULL, "Container should have been set");
  2209     cur->container()->dec_container_count();
  2210     // Capture the next link before it is changed
  2211     // by the call to return_chunk_at_head();
  2212     Metachunk* next = cur->next();
  2213     cur->set_is_free(true);
  2214     list->return_chunk_at_head(cur);
  2215     cur = next;
  2219 SpaceManager::~SpaceManager() {
  2220   // This call this->_lock which can't be done while holding expand_lock()
  2221   assert(sum_capacity_in_chunks_in_use() == allocated_chunks_words(),
  2222     err_msg("sum_capacity_in_chunks_in_use() " SIZE_FORMAT
  2223             " allocated_chunks_words() " SIZE_FORMAT,
  2224             sum_capacity_in_chunks_in_use(), allocated_chunks_words()));
  2226   MutexLockerEx fcl(SpaceManager::expand_lock(),
  2227                     Mutex::_no_safepoint_check_flag);
  2229   chunk_manager()->slow_locked_verify();
  2231   dec_total_from_size_metrics();
  2233   if (TraceMetadataChunkAllocation && Verbose) {
  2234     gclog_or_tty->print_cr("~SpaceManager(): " PTR_FORMAT, this);
  2235     locked_print_chunks_in_use_on(gclog_or_tty);
  2238   // Do not mangle freed Metachunks.  The chunk size inside Metachunks
  2239   // is during the freeing of a VirtualSpaceNodes.
  2241   // Have to update before the chunks_in_use lists are emptied
  2242   // below.
  2243   chunk_manager()->inc_free_chunks_total(allocated_chunks_words(),
  2244                                          sum_count_in_chunks_in_use());
  2246   // Add all the chunks in use by this space manager
  2247   // to the global list of free chunks.
  2249   // Follow each list of chunks-in-use and add them to the
  2250   // free lists.  Each list is NULL terminated.
  2252   for (ChunkIndex i = ZeroIndex; i < HumongousIndex; i = next_chunk_index(i)) {
  2253     if (TraceMetadataChunkAllocation && Verbose) {
  2254       gclog_or_tty->print_cr("returned %d %s chunks to freelist",
  2255                              sum_count_in_chunks_in_use(i),
  2256                              chunk_size_name(i));
  2258     Metachunk* chunks = chunks_in_use(i);
  2259     chunk_manager()->return_chunks(i, chunks);
  2260     set_chunks_in_use(i, NULL);
  2261     if (TraceMetadataChunkAllocation && Verbose) {
  2262       gclog_or_tty->print_cr("updated freelist count %d %s",
  2263                              chunk_manager()->free_chunks(i)->count(),
  2264                              chunk_size_name(i));
  2266     assert(i != HumongousIndex, "Humongous chunks are handled explicitly later");
  2269   // The medium chunk case may be optimized by passing the head and
  2270   // tail of the medium chunk list to add_at_head().  The tail is often
  2271   // the current chunk but there are probably exceptions.
  2273   // Humongous chunks
  2274   if (TraceMetadataChunkAllocation && Verbose) {
  2275     gclog_or_tty->print_cr("returned %d %s humongous chunks to dictionary",
  2276                             sum_count_in_chunks_in_use(HumongousIndex),
  2277                             chunk_size_name(HumongousIndex));
  2278     gclog_or_tty->print("Humongous chunk dictionary: ");
  2280   // Humongous chunks are never the current chunk.
  2281   Metachunk* humongous_chunks = chunks_in_use(HumongousIndex);
  2283   while (humongous_chunks != NULL) {
  2284 #ifdef ASSERT
  2285     humongous_chunks->set_is_free(true);
  2286 #endif
  2287     if (TraceMetadataChunkAllocation && Verbose) {
  2288       gclog_or_tty->print(PTR_FORMAT " (" SIZE_FORMAT ") ",
  2289                           humongous_chunks,
  2290                           humongous_chunks->word_size());
  2292     assert(humongous_chunks->word_size() == (size_t)
  2293            align_size_up(humongous_chunks->word_size(),
  2294                              HumongousChunkGranularity),
  2295            err_msg("Humongous chunk size is wrong: word size " SIZE_FORMAT
  2296                    " granularity %d",
  2297                    humongous_chunks->word_size(), HumongousChunkGranularity));
  2298     Metachunk* next_humongous_chunks = humongous_chunks->next();
  2299     humongous_chunks->container()->dec_container_count();
  2300     chunk_manager()->humongous_dictionary()->return_chunk(humongous_chunks);
  2301     humongous_chunks = next_humongous_chunks;
  2303   if (TraceMetadataChunkAllocation && Verbose) {
  2304     gclog_or_tty->print_cr("");
  2305     gclog_or_tty->print_cr("updated dictionary count %d %s",
  2306                      chunk_manager()->humongous_dictionary()->total_count(),
  2307                      chunk_size_name(HumongousIndex));
  2309   chunk_manager()->slow_locked_verify();
  2312 const char* SpaceManager::chunk_size_name(ChunkIndex index) const {
  2313   switch (index) {
  2314     case SpecializedIndex:
  2315       return "Specialized";
  2316     case SmallIndex:
  2317       return "Small";
  2318     case MediumIndex:
  2319       return "Medium";
  2320     case HumongousIndex:
  2321       return "Humongous";
  2322     default:
  2323       return NULL;
  2327 ChunkIndex ChunkManager::list_index(size_t size) {
  2328   switch (size) {
  2329     case SpecializedChunk:
  2330       assert(SpecializedChunk == ClassSpecializedChunk,
  2331              "Need branch for ClassSpecializedChunk");
  2332       return SpecializedIndex;
  2333     case SmallChunk:
  2334     case ClassSmallChunk:
  2335       return SmallIndex;
  2336     case MediumChunk:
  2337     case ClassMediumChunk:
  2338       return MediumIndex;
  2339     default:
  2340       assert(size > MediumChunk || size > ClassMediumChunk,
  2341              "Not a humongous chunk");
  2342       return HumongousIndex;
  2346 void SpaceManager::deallocate(MetaWord* p, size_t word_size) {
  2347   assert_lock_strong(_lock);
  2348   size_t raw_word_size = get_raw_word_size(word_size);
  2349   size_t min_size = TreeChunk<Metablock, FreeList>::min_size();
  2350   assert(raw_word_size >= min_size,
  2351          err_msg("Should not deallocate dark matter " SIZE_FORMAT "<" SIZE_FORMAT, word_size, min_size));
  2352   block_freelists()->return_block(p, raw_word_size);
  2355 // Adds a chunk to the list of chunks in use.
  2356 void SpaceManager::add_chunk(Metachunk* new_chunk, bool make_current) {
  2358   assert(new_chunk != NULL, "Should not be NULL");
  2359   assert(new_chunk->next() == NULL, "Should not be on a list");
  2361   new_chunk->reset_empty();
  2363   // Find the correct list and and set the current
  2364   // chunk for that list.
  2365   ChunkIndex index = ChunkManager::list_index(new_chunk->word_size());
  2367   if (index != HumongousIndex) {
  2368     retire_current_chunk();
  2369     set_current_chunk(new_chunk);
  2370     new_chunk->set_next(chunks_in_use(index));
  2371     set_chunks_in_use(index, new_chunk);
  2372   } else {
  2373     // For null class loader data and DumpSharedSpaces, the first chunk isn't
  2374     // small, so small will be null.  Link this first chunk as the current
  2375     // chunk.
  2376     if (make_current) {
  2377       // Set as the current chunk but otherwise treat as a humongous chunk.
  2378       set_current_chunk(new_chunk);
  2380     // Link at head.  The _current_chunk only points to a humongous chunk for
  2381     // the null class loader metaspace (class and data virtual space managers)
  2382     // any humongous chunks so will not point to the tail
  2383     // of the humongous chunks list.
  2384     new_chunk->set_next(chunks_in_use(HumongousIndex));
  2385     set_chunks_in_use(HumongousIndex, new_chunk);
  2387     assert(new_chunk->word_size() > medium_chunk_size(), "List inconsistency");
  2390   // Add to the running sum of capacity
  2391   inc_size_metrics(new_chunk->word_size());
  2393   assert(new_chunk->is_empty(), "Not ready for reuse");
  2394   if (TraceMetadataChunkAllocation && Verbose) {
  2395     gclog_or_tty->print("SpaceManager::add_chunk: %d) ",
  2396                         sum_count_in_chunks_in_use());
  2397     new_chunk->print_on(gclog_or_tty);
  2398     chunk_manager()->locked_print_free_chunks(gclog_or_tty);
  2402 void SpaceManager::retire_current_chunk() {
  2403   if (current_chunk() != NULL) {
  2404     size_t remaining_words = current_chunk()->free_word_size();
  2405     if (remaining_words >= TreeChunk<Metablock, FreeList>::min_size()) {
  2406       block_freelists()->return_block(current_chunk()->allocate(remaining_words), remaining_words);
  2407       inc_used_metrics(remaining_words);
  2412 Metachunk* SpaceManager::get_new_chunk(size_t word_size,
  2413                                        size_t grow_chunks_by_words) {
  2414   // Get a chunk from the chunk freelist
  2415   Metachunk* next = chunk_manager()->chunk_freelist_allocate(grow_chunks_by_words);
  2417   if (next == NULL) {
  2418     next = vs_list()->get_new_chunk(word_size,
  2419                                     grow_chunks_by_words,
  2420                                     medium_chunk_bunch());
  2423   if (TraceMetadataHumongousAllocation && next != NULL &&
  2424       SpaceManager::is_humongous(next->word_size())) {
  2425     gclog_or_tty->print_cr("  new humongous chunk word size "
  2426                            PTR_FORMAT, next->word_size());
  2429   return next;
  2432 MetaWord* SpaceManager::allocate(size_t word_size) {
  2433   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  2435   size_t raw_word_size = get_raw_word_size(word_size);
  2436   BlockFreelist* fl =  block_freelists();
  2437   MetaWord* p = NULL;
  2438   // Allocation from the dictionary is expensive in the sense that
  2439   // the dictionary has to be searched for a size.  Don't allocate
  2440   // from the dictionary until it starts to get fat.  Is this
  2441   // a reasonable policy?  Maybe an skinny dictionary is fast enough
  2442   // for allocations.  Do some profiling.  JJJ
  2443   if (fl->total_size() > allocation_from_dictionary_limit) {
  2444     p = fl->get_block(raw_word_size);
  2446   if (p == NULL) {
  2447     p = allocate_work(raw_word_size);
  2449   Metadebug::deallocate_block_a_lot(this, raw_word_size);
  2451   return p;
  2454 // Returns the address of spaced allocated for "word_size".
  2455 // This methods does not know about blocks (Metablocks)
  2456 MetaWord* SpaceManager::allocate_work(size_t word_size) {
  2457   assert_lock_strong(_lock);
  2458 #ifdef ASSERT
  2459   if (Metadebug::test_metadata_failure()) {
  2460     return NULL;
  2462 #endif
  2463   // Is there space in the current chunk?
  2464   MetaWord* result = NULL;
  2466   // For DumpSharedSpaces, only allocate out of the current chunk which is
  2467   // never null because we gave it the size we wanted.   Caller reports out
  2468   // of memory if this returns null.
  2469   if (DumpSharedSpaces) {
  2470     assert(current_chunk() != NULL, "should never happen");
  2471     inc_used_metrics(word_size);
  2472     return current_chunk()->allocate(word_size); // caller handles null result
  2475   if (current_chunk() != NULL) {
  2476     result = current_chunk()->allocate(word_size);
  2479   if (result == NULL) {
  2480     result = grow_and_allocate(word_size);
  2483   if (result != NULL) {
  2484     inc_used_metrics(word_size);
  2485     assert(result != (MetaWord*) chunks_in_use(MediumIndex),
  2486            "Head of the list is being allocated");
  2489   return result;
  2492 void SpaceManager::verify() {
  2493   // If there are blocks in the dictionary, then
  2494   // verfication of chunks does not work since
  2495   // being in the dictionary alters a chunk.
  2496   if (block_freelists()->total_size() == 0) {
  2497     for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2498       Metachunk* curr = chunks_in_use(i);
  2499       while (curr != NULL) {
  2500         curr->verify();
  2501         verify_chunk_size(curr);
  2502         curr = curr->next();
  2508 void SpaceManager::verify_chunk_size(Metachunk* chunk) {
  2509   assert(is_humongous(chunk->word_size()) ||
  2510          chunk->word_size() == medium_chunk_size() ||
  2511          chunk->word_size() == small_chunk_size() ||
  2512          chunk->word_size() == specialized_chunk_size(),
  2513          "Chunk size is wrong");
  2514   return;
  2517 #ifdef ASSERT
  2518 void SpaceManager::verify_allocated_blocks_words() {
  2519   // Verification is only guaranteed at a safepoint.
  2520   assert(SafepointSynchronize::is_at_safepoint() || !Universe::is_fully_initialized(),
  2521     "Verification can fail if the applications is running");
  2522   assert(allocated_blocks_words() == sum_used_in_chunks_in_use(),
  2523     err_msg("allocation total is not consistent " SIZE_FORMAT
  2524             " vs " SIZE_FORMAT,
  2525             allocated_blocks_words(), sum_used_in_chunks_in_use()));
  2528 #endif
  2530 void SpaceManager::dump(outputStream* const out) const {
  2531   size_t curr_total = 0;
  2532   size_t waste = 0;
  2533   uint i = 0;
  2534   size_t used = 0;
  2535   size_t capacity = 0;
  2537   // Add up statistics for all chunks in this SpaceManager.
  2538   for (ChunkIndex index = ZeroIndex;
  2539        index < NumberOfInUseLists;
  2540        index = next_chunk_index(index)) {
  2541     for (Metachunk* curr = chunks_in_use(index);
  2542          curr != NULL;
  2543          curr = curr->next()) {
  2544       out->print("%d) ", i++);
  2545       curr->print_on(out);
  2546       curr_total += curr->word_size();
  2547       used += curr->used_word_size();
  2548       capacity += curr->capacity_word_size();
  2549       waste += curr->free_word_size() + curr->overhead();;
  2553   if (TraceMetadataChunkAllocation && Verbose) {
  2554     block_freelists()->print_on(out);
  2557   size_t free = current_chunk() == NULL ? 0 : current_chunk()->free_word_size();
  2558   // Free space isn't wasted.
  2559   waste -= free;
  2561   out->print_cr("total of all chunks "  SIZE_FORMAT " used " SIZE_FORMAT
  2562                 " free " SIZE_FORMAT " capacity " SIZE_FORMAT
  2563                 " waste " SIZE_FORMAT, curr_total, used, free, capacity, waste);
  2566 #ifndef PRODUCT
  2567 void SpaceManager::mangle_freed_chunks() {
  2568   for (ChunkIndex index = ZeroIndex;
  2569        index < NumberOfInUseLists;
  2570        index = next_chunk_index(index)) {
  2571     for (Metachunk* curr = chunks_in_use(index);
  2572          curr != NULL;
  2573          curr = curr->next()) {
  2574       curr->mangle();
  2578 #endif // PRODUCT
  2580 // MetaspaceAux
  2583 size_t MetaspaceAux::_allocated_capacity_words[] = {0, 0};
  2584 size_t MetaspaceAux::_allocated_used_words[] = {0, 0};
  2586 size_t MetaspaceAux::free_bytes(Metaspace::MetadataType mdtype) {
  2587   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
  2588   return list == NULL ? 0 : list->free_bytes();
  2591 size_t MetaspaceAux::free_bytes() {
  2592   return free_bytes(Metaspace::ClassType) + free_bytes(Metaspace::NonClassType);
  2595 void MetaspaceAux::dec_capacity(Metaspace::MetadataType mdtype, size_t words) {
  2596   assert_lock_strong(SpaceManager::expand_lock());
  2597   assert(words <= allocated_capacity_words(mdtype),
  2598     err_msg("About to decrement below 0: words " SIZE_FORMAT
  2599             " is greater than _allocated_capacity_words[%u] " SIZE_FORMAT,
  2600             words, mdtype, allocated_capacity_words(mdtype)));
  2601   _allocated_capacity_words[mdtype] -= words;
  2604 void MetaspaceAux::inc_capacity(Metaspace::MetadataType mdtype, size_t words) {
  2605   assert_lock_strong(SpaceManager::expand_lock());
  2606   // Needs to be atomic
  2607   _allocated_capacity_words[mdtype] += words;
  2610 void MetaspaceAux::dec_used(Metaspace::MetadataType mdtype, size_t words) {
  2611   assert(words <= allocated_used_words(mdtype),
  2612     err_msg("About to decrement below 0: words " SIZE_FORMAT
  2613             " is greater than _allocated_used_words[%u] " SIZE_FORMAT,
  2614             words, mdtype, allocated_used_words(mdtype)));
  2615   // For CMS deallocation of the Metaspaces occurs during the
  2616   // sweep which is a concurrent phase.  Protection by the expand_lock()
  2617   // is not enough since allocation is on a per Metaspace basis
  2618   // and protected by the Metaspace lock.
  2619   jlong minus_words = (jlong) - (jlong) words;
  2620   Atomic::add_ptr(minus_words, &_allocated_used_words[mdtype]);
  2623 void MetaspaceAux::inc_used(Metaspace::MetadataType mdtype, size_t words) {
  2624   // _allocated_used_words tracks allocations for
  2625   // each piece of metadata.  Those allocations are
  2626   // generally done concurrently by different application
  2627   // threads so must be done atomically.
  2628   Atomic::add_ptr(words, &_allocated_used_words[mdtype]);
  2631 size_t MetaspaceAux::used_bytes_slow(Metaspace::MetadataType mdtype) {
  2632   size_t used = 0;
  2633   ClassLoaderDataGraphMetaspaceIterator iter;
  2634   while (iter.repeat()) {
  2635     Metaspace* msp = iter.get_next();
  2636     // Sum allocated_blocks_words for each metaspace
  2637     if (msp != NULL) {
  2638       used += msp->used_words_slow(mdtype);
  2641   return used * BytesPerWord;
  2644 size_t MetaspaceAux::free_bytes_slow(Metaspace::MetadataType mdtype) {
  2645   size_t free = 0;
  2646   ClassLoaderDataGraphMetaspaceIterator iter;
  2647   while (iter.repeat()) {
  2648     Metaspace* msp = iter.get_next();
  2649     if (msp != NULL) {
  2650       free += msp->free_words_slow(mdtype);
  2653   return free * BytesPerWord;
  2656 size_t MetaspaceAux::capacity_bytes_slow(Metaspace::MetadataType mdtype) {
  2657   if ((mdtype == Metaspace::ClassType) && !Metaspace::using_class_space()) {
  2658     return 0;
  2660   // Don't count the space in the freelists.  That space will be
  2661   // added to the capacity calculation as needed.
  2662   size_t capacity = 0;
  2663   ClassLoaderDataGraphMetaspaceIterator iter;
  2664   while (iter.repeat()) {
  2665     Metaspace* msp = iter.get_next();
  2666     if (msp != NULL) {
  2667       capacity += msp->capacity_words_slow(mdtype);
  2670   return capacity * BytesPerWord;
  2673 size_t MetaspaceAux::capacity_bytes_slow() {
  2674 #ifdef PRODUCT
  2675   // Use allocated_capacity_bytes() in PRODUCT instead of this function.
  2676   guarantee(false, "Should not call capacity_bytes_slow() in the PRODUCT");
  2677 #endif
  2678   size_t class_capacity = capacity_bytes_slow(Metaspace::ClassType);
  2679   size_t non_class_capacity = capacity_bytes_slow(Metaspace::NonClassType);
  2680   assert(allocated_capacity_bytes() == class_capacity + non_class_capacity,
  2681       err_msg("bad accounting: allocated_capacity_bytes() " SIZE_FORMAT
  2682         " class_capacity + non_class_capacity " SIZE_FORMAT
  2683         " class_capacity " SIZE_FORMAT " non_class_capacity " SIZE_FORMAT,
  2684         allocated_capacity_bytes(), class_capacity + non_class_capacity,
  2685         class_capacity, non_class_capacity));
  2687   return class_capacity + non_class_capacity;
  2690 size_t MetaspaceAux::reserved_bytes(Metaspace::MetadataType mdtype) {
  2691   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
  2692   return list == NULL ? 0 : list->reserved_bytes();
  2695 size_t MetaspaceAux::committed_bytes(Metaspace::MetadataType mdtype) {
  2696   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
  2697   return list == NULL ? 0 : list->committed_bytes();
  2700 size_t MetaspaceAux::min_chunk_size_words() { return Metaspace::first_chunk_word_size(); }
  2702 size_t MetaspaceAux::free_chunks_total_words(Metaspace::MetadataType mdtype) {
  2703   ChunkManager* chunk_manager = Metaspace::get_chunk_manager(mdtype);
  2704   if (chunk_manager == NULL) {
  2705     return 0;
  2707   chunk_manager->slow_verify();
  2708   return chunk_manager->free_chunks_total_words();
  2711 size_t MetaspaceAux::free_chunks_total_bytes(Metaspace::MetadataType mdtype) {
  2712   return free_chunks_total_words(mdtype) * BytesPerWord;
  2715 size_t MetaspaceAux::free_chunks_total_words() {
  2716   return free_chunks_total_words(Metaspace::ClassType) +
  2717          free_chunks_total_words(Metaspace::NonClassType);
  2720 size_t MetaspaceAux::free_chunks_total_bytes() {
  2721   return free_chunks_total_words() * BytesPerWord;
  2724 void MetaspaceAux::print_metaspace_change(size_t prev_metadata_used) {
  2725   gclog_or_tty->print(", [Metaspace:");
  2726   if (PrintGCDetails && Verbose) {
  2727     gclog_or_tty->print(" "  SIZE_FORMAT
  2728                         "->" SIZE_FORMAT
  2729                         "("  SIZE_FORMAT ")",
  2730                         prev_metadata_used,
  2731                         allocated_used_bytes(),
  2732                         reserved_bytes());
  2733   } else {
  2734     gclog_or_tty->print(" "  SIZE_FORMAT "K"
  2735                         "->" SIZE_FORMAT "K"
  2736                         "("  SIZE_FORMAT "K)",
  2737                         prev_metadata_used/K,
  2738                         allocated_used_bytes()/K,
  2739                         reserved_bytes()/K);
  2742   gclog_or_tty->print("]");
  2745 // This is printed when PrintGCDetails
  2746 void MetaspaceAux::print_on(outputStream* out) {
  2747   Metaspace::MetadataType nct = Metaspace::NonClassType;
  2749   out->print_cr(" Metaspace       "
  2750                 "used "      SIZE_FORMAT "K, "
  2751                 "capacity "  SIZE_FORMAT "K, "
  2752                 "committed " SIZE_FORMAT "K, "
  2753                 "reserved "  SIZE_FORMAT "K",
  2754                 allocated_used_bytes()/K,
  2755                 allocated_capacity_bytes()/K,
  2756                 committed_bytes()/K,
  2757                 reserved_bytes()/K);
  2759   if (Metaspace::using_class_space()) {
  2760     Metaspace::MetadataType ct = Metaspace::ClassType;
  2761     out->print_cr("  class space    "
  2762                   "used "      SIZE_FORMAT "K, "
  2763                   "capacity "  SIZE_FORMAT "K, "
  2764                   "committed " SIZE_FORMAT "K, "
  2765                   "reserved "  SIZE_FORMAT "K",
  2766                   allocated_used_bytes(ct)/K,
  2767                   allocated_capacity_bytes(ct)/K,
  2768                   committed_bytes(ct)/K,
  2769                   reserved_bytes(ct)/K);
  2773 // Print information for class space and data space separately.
  2774 // This is almost the same as above.
  2775 void MetaspaceAux::print_on(outputStream* out, Metaspace::MetadataType mdtype) {
  2776   size_t free_chunks_capacity_bytes = free_chunks_total_bytes(mdtype);
  2777   size_t capacity_bytes = capacity_bytes_slow(mdtype);
  2778   size_t used_bytes = used_bytes_slow(mdtype);
  2779   size_t free_bytes = free_bytes_slow(mdtype);
  2780   size_t used_and_free = used_bytes + free_bytes +
  2781                            free_chunks_capacity_bytes;
  2782   out->print_cr("  Chunk accounting: used in chunks " SIZE_FORMAT
  2783              "K + unused in chunks " SIZE_FORMAT "K  + "
  2784              " capacity in free chunks " SIZE_FORMAT "K = " SIZE_FORMAT
  2785              "K  capacity in allocated chunks " SIZE_FORMAT "K",
  2786              used_bytes / K,
  2787              free_bytes / K,
  2788              free_chunks_capacity_bytes / K,
  2789              used_and_free / K,
  2790              capacity_bytes / K);
  2791   // Accounting can only be correct if we got the values during a safepoint
  2792   assert(!SafepointSynchronize::is_at_safepoint() || used_and_free == capacity_bytes, "Accounting is wrong");
  2795 // Print total fragmentation for class metaspaces
  2796 void MetaspaceAux::print_class_waste(outputStream* out) {
  2797   assert(Metaspace::using_class_space(), "class metaspace not used");
  2798   size_t cls_specialized_waste = 0, cls_small_waste = 0, cls_medium_waste = 0;
  2799   size_t cls_specialized_count = 0, cls_small_count = 0, cls_medium_count = 0, cls_humongous_count = 0;
  2800   ClassLoaderDataGraphMetaspaceIterator iter;
  2801   while (iter.repeat()) {
  2802     Metaspace* msp = iter.get_next();
  2803     if (msp != NULL) {
  2804       cls_specialized_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
  2805       cls_specialized_count += msp->class_vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
  2806       cls_small_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SmallIndex);
  2807       cls_small_count += msp->class_vsm()->sum_count_in_chunks_in_use(SmallIndex);
  2808       cls_medium_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(MediumIndex);
  2809       cls_medium_count += msp->class_vsm()->sum_count_in_chunks_in_use(MediumIndex);
  2810       cls_humongous_count += msp->class_vsm()->sum_count_in_chunks_in_use(HumongousIndex);
  2813   out->print_cr(" class: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
  2814                 SIZE_FORMAT " small(s) " SIZE_FORMAT ", "
  2815                 SIZE_FORMAT " medium(s) " SIZE_FORMAT ", "
  2816                 "large count " SIZE_FORMAT,
  2817                 cls_specialized_count, cls_specialized_waste,
  2818                 cls_small_count, cls_small_waste,
  2819                 cls_medium_count, cls_medium_waste, cls_humongous_count);
  2822 // Print total fragmentation for data and class metaspaces separately
  2823 void MetaspaceAux::print_waste(outputStream* out) {
  2824   size_t specialized_waste = 0, small_waste = 0, medium_waste = 0;
  2825   size_t specialized_count = 0, small_count = 0, medium_count = 0, humongous_count = 0;
  2827   ClassLoaderDataGraphMetaspaceIterator iter;
  2828   while (iter.repeat()) {
  2829     Metaspace* msp = iter.get_next();
  2830     if (msp != NULL) {
  2831       specialized_waste += msp->vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
  2832       specialized_count += msp->vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
  2833       small_waste += msp->vsm()->sum_waste_in_chunks_in_use(SmallIndex);
  2834       small_count += msp->vsm()->sum_count_in_chunks_in_use(SmallIndex);
  2835       medium_waste += msp->vsm()->sum_waste_in_chunks_in_use(MediumIndex);
  2836       medium_count += msp->vsm()->sum_count_in_chunks_in_use(MediumIndex);
  2837       humongous_count += msp->vsm()->sum_count_in_chunks_in_use(HumongousIndex);
  2840   out->print_cr("Total fragmentation waste (words) doesn't count free space");
  2841   out->print_cr("  data: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
  2842                         SIZE_FORMAT " small(s) " SIZE_FORMAT ", "
  2843                         SIZE_FORMAT " medium(s) " SIZE_FORMAT ", "
  2844                         "large count " SIZE_FORMAT,
  2845              specialized_count, specialized_waste, small_count,
  2846              small_waste, medium_count, medium_waste, humongous_count);
  2847   if (Metaspace::using_class_space()) {
  2848     print_class_waste(out);
  2852 // Dump global metaspace things from the end of ClassLoaderDataGraph
  2853 void MetaspaceAux::dump(outputStream* out) {
  2854   out->print_cr("All Metaspace:");
  2855   out->print("data space: "); print_on(out, Metaspace::NonClassType);
  2856   out->print("class space: "); print_on(out, Metaspace::ClassType);
  2857   print_waste(out);
  2860 void MetaspaceAux::verify_free_chunks() {
  2861   Metaspace::chunk_manager_metadata()->verify();
  2862   if (Metaspace::using_class_space()) {
  2863     Metaspace::chunk_manager_class()->verify();
  2867 void MetaspaceAux::verify_capacity() {
  2868 #ifdef ASSERT
  2869   size_t running_sum_capacity_bytes = allocated_capacity_bytes();
  2870   // For purposes of the running sum of capacity, verify against capacity
  2871   size_t capacity_in_use_bytes = capacity_bytes_slow();
  2872   assert(running_sum_capacity_bytes == capacity_in_use_bytes,
  2873     err_msg("allocated_capacity_words() * BytesPerWord " SIZE_FORMAT
  2874             " capacity_bytes_slow()" SIZE_FORMAT,
  2875             running_sum_capacity_bytes, capacity_in_use_bytes));
  2876   for (Metaspace::MetadataType i = Metaspace::ClassType;
  2877        i < Metaspace:: MetadataTypeCount;
  2878        i = (Metaspace::MetadataType)(i + 1)) {
  2879     size_t capacity_in_use_bytes = capacity_bytes_slow(i);
  2880     assert(allocated_capacity_bytes(i) == capacity_in_use_bytes,
  2881       err_msg("allocated_capacity_bytes(%u) " SIZE_FORMAT
  2882               " capacity_bytes_slow(%u)" SIZE_FORMAT,
  2883               i, allocated_capacity_bytes(i), i, capacity_in_use_bytes));
  2885 #endif
  2888 void MetaspaceAux::verify_used() {
  2889 #ifdef ASSERT
  2890   size_t running_sum_used_bytes = allocated_used_bytes();
  2891   // For purposes of the running sum of used, verify against used
  2892   size_t used_in_use_bytes = used_bytes_slow();
  2893   assert(allocated_used_bytes() == used_in_use_bytes,
  2894     err_msg("allocated_used_bytes() " SIZE_FORMAT
  2895             " used_bytes_slow()" SIZE_FORMAT,
  2896             allocated_used_bytes(), used_in_use_bytes));
  2897   for (Metaspace::MetadataType i = Metaspace::ClassType;
  2898        i < Metaspace:: MetadataTypeCount;
  2899        i = (Metaspace::MetadataType)(i + 1)) {
  2900     size_t used_in_use_bytes = used_bytes_slow(i);
  2901     assert(allocated_used_bytes(i) == used_in_use_bytes,
  2902       err_msg("allocated_used_bytes(%u) " SIZE_FORMAT
  2903               " used_bytes_slow(%u)" SIZE_FORMAT,
  2904               i, allocated_used_bytes(i), i, used_in_use_bytes));
  2906 #endif
  2909 void MetaspaceAux::verify_metrics() {
  2910   verify_capacity();
  2911   verify_used();
  2915 // Metaspace methods
  2917 size_t Metaspace::_first_chunk_word_size = 0;
  2918 size_t Metaspace::_first_class_chunk_word_size = 0;
  2920 size_t Metaspace::_commit_alignment = 0;
  2921 size_t Metaspace::_reserve_alignment = 0;
  2923 Metaspace::Metaspace(Mutex* lock, MetaspaceType type) {
  2924   initialize(lock, type);
  2927 Metaspace::~Metaspace() {
  2928   delete _vsm;
  2929   if (using_class_space()) {
  2930     delete _class_vsm;
  2934 VirtualSpaceList* Metaspace::_space_list = NULL;
  2935 VirtualSpaceList* Metaspace::_class_space_list = NULL;
  2937 ChunkManager* Metaspace::_chunk_manager_metadata = NULL;
  2938 ChunkManager* Metaspace::_chunk_manager_class = NULL;
  2940 #define VIRTUALSPACEMULTIPLIER 2
  2942 #ifdef _LP64
  2943 void Metaspace::set_narrow_klass_base_and_shift(address metaspace_base, address cds_base) {
  2944   // Figure out the narrow_klass_base and the narrow_klass_shift.  The
  2945   // narrow_klass_base is the lower of the metaspace base and the cds base
  2946   // (if cds is enabled).  The narrow_klass_shift depends on the distance
  2947   // between the lower base and higher address.
  2948   address lower_base;
  2949   address higher_address;
  2950   if (UseSharedSpaces) {
  2951     higher_address = MAX2((address)(cds_base + FileMapInfo::shared_spaces_size()),
  2952                           (address)(metaspace_base + class_metaspace_size()));
  2953     lower_base = MIN2(metaspace_base, cds_base);
  2954   } else {
  2955     higher_address = metaspace_base + class_metaspace_size();
  2956     lower_base = metaspace_base;
  2958   Universe::set_narrow_klass_base(lower_base);
  2959   if ((uint64_t)(higher_address - lower_base) < (uint64_t)max_juint) {
  2960     Universe::set_narrow_klass_shift(0);
  2961   } else {
  2962     assert(!UseSharedSpaces, "Cannot shift with UseSharedSpaces");
  2963     Universe::set_narrow_klass_shift(LogKlassAlignmentInBytes);
  2967 // Return TRUE if the specified metaspace_base and cds_base are close enough
  2968 // to work with compressed klass pointers.
  2969 bool Metaspace::can_use_cds_with_metaspace_addr(char* metaspace_base, address cds_base) {
  2970   assert(cds_base != 0 && UseSharedSpaces, "Only use with CDS");
  2971   assert(UseCompressedClassPointers, "Only use with CompressedKlassPtrs");
  2972   address lower_base = MIN2((address)metaspace_base, cds_base);
  2973   address higher_address = MAX2((address)(cds_base + FileMapInfo::shared_spaces_size()),
  2974                                 (address)(metaspace_base + class_metaspace_size()));
  2975   return ((uint64_t)(higher_address - lower_base) < (uint64_t)max_juint);
  2978 // Try to allocate the metaspace at the requested addr.
  2979 void Metaspace::allocate_metaspace_compressed_klass_ptrs(char* requested_addr, address cds_base) {
  2980   assert(using_class_space(), "called improperly");
  2981   assert(UseCompressedClassPointers, "Only use with CompressedKlassPtrs");
  2982   assert(class_metaspace_size() < KlassEncodingMetaspaceMax,
  2983          "Metaspace size is too big");
  2984   assert_is_ptr_aligned(requested_addr,          _reserve_alignment);
  2985   assert_is_ptr_aligned(cds_base,                _reserve_alignment);
  2986   assert_is_size_aligned(class_metaspace_size(), _reserve_alignment);
  2988   // Don't use large pages for the class space.
  2989   bool large_pages = false;
  2991   ReservedSpace metaspace_rs = ReservedSpace(class_metaspace_size(),
  2992                                              _reserve_alignment,
  2993                                              large_pages,
  2994                                              requested_addr, 0);
  2995   if (!metaspace_rs.is_reserved()) {
  2996     if (UseSharedSpaces) {
  2997       size_t increment = align_size_up(1*G, _reserve_alignment);
  2999       // Keep trying to allocate the metaspace, increasing the requested_addr
  3000       // by 1GB each time, until we reach an address that will no longer allow
  3001       // use of CDS with compressed klass pointers.
  3002       char *addr = requested_addr;
  3003       while (!metaspace_rs.is_reserved() && (addr + increment > addr) &&
  3004              can_use_cds_with_metaspace_addr(addr + increment, cds_base)) {
  3005         addr = addr + increment;
  3006         metaspace_rs = ReservedSpace(class_metaspace_size(),
  3007                                      _reserve_alignment, large_pages, addr, 0);
  3011     // If no successful allocation then try to allocate the space anywhere.  If
  3012     // that fails then OOM doom.  At this point we cannot try allocating the
  3013     // metaspace as if UseCompressedClassPointers is off because too much
  3014     // initialization has happened that depends on UseCompressedClassPointers.
  3015     // So, UseCompressedClassPointers cannot be turned off at this point.
  3016     if (!metaspace_rs.is_reserved()) {
  3017       metaspace_rs = ReservedSpace(class_metaspace_size(),
  3018                                    _reserve_alignment, large_pages);
  3019       if (!metaspace_rs.is_reserved()) {
  3020         vm_exit_during_initialization(err_msg("Could not allocate metaspace: %d bytes",
  3021                                               class_metaspace_size()));
  3026   // If we got here then the metaspace got allocated.
  3027   MemTracker::record_virtual_memory_type((address)metaspace_rs.base(), mtClass);
  3029   // Verify that we can use shared spaces.  Otherwise, turn off CDS.
  3030   if (UseSharedSpaces && !can_use_cds_with_metaspace_addr(metaspace_rs.base(), cds_base)) {
  3031     FileMapInfo::stop_sharing_and_unmap(
  3032         "Could not allocate metaspace at a compatible address");
  3035   set_narrow_klass_base_and_shift((address)metaspace_rs.base(),
  3036                                   UseSharedSpaces ? (address)cds_base : 0);
  3038   initialize_class_space(metaspace_rs);
  3040   if (PrintCompressedOopsMode || (PrintMiscellaneous && Verbose)) {
  3041     gclog_or_tty->print_cr("Narrow klass base: " PTR_FORMAT ", Narrow klass shift: " SIZE_FORMAT,
  3042                             Universe::narrow_klass_base(), Universe::narrow_klass_shift());
  3043     gclog_or_tty->print_cr("Metaspace Size: " SIZE_FORMAT " Address: " PTR_FORMAT " Req Addr: " PTR_FORMAT,
  3044                            class_metaspace_size(), metaspace_rs.base(), requested_addr);
  3048 // For UseCompressedClassPointers the class space is reserved above the top of
  3049 // the Java heap.  The argument passed in is at the base of the compressed space.
  3050 void Metaspace::initialize_class_space(ReservedSpace rs) {
  3051   // The reserved space size may be bigger because of alignment, esp with UseLargePages
  3052   assert(rs.size() >= CompressedClassSpaceSize,
  3053          err_msg(SIZE_FORMAT " != " UINTX_FORMAT, rs.size(), CompressedClassSpaceSize));
  3054   assert(using_class_space(), "Must be using class space");
  3055   _class_space_list = new VirtualSpaceList(rs);
  3056   _chunk_manager_class = new ChunkManager(SpecializedChunk, ClassSmallChunk, ClassMediumChunk);
  3058   if (!_class_space_list->initialization_succeeded()) {
  3059     vm_exit_during_initialization("Failed to setup compressed class space virtual space list.");
  3063 #endif
  3065 // Align down. If the aligning result in 0, return 'alignment'.
  3066 static size_t restricted_align_down(size_t size, size_t alignment) {
  3067   return MAX2(alignment, align_size_down_(size, alignment));
  3070 void Metaspace::ergo_initialize() {
  3071   if (DumpSharedSpaces) {
  3072     // Using large pages when dumping the shared archive is currently not implemented.
  3073     FLAG_SET_ERGO(bool, UseLargePagesInMetaspace, false);
  3076   size_t page_size = os::vm_page_size();
  3077   if (UseLargePages && UseLargePagesInMetaspace) {
  3078     page_size = os::large_page_size();
  3081   _commit_alignment  = page_size;
  3082   _reserve_alignment = MAX2(page_size, (size_t)os::vm_allocation_granularity());
  3084   // Do not use FLAG_SET_ERGO to update MaxMetaspaceSize, since this will
  3085   // override if MaxMetaspaceSize was set on the command line or not.
  3086   // This information is needed later to conform to the specification of the
  3087   // java.lang.management.MemoryUsage API.
  3088   //
  3089   // Ideally, we would be able to set the default value of MaxMetaspaceSize in
  3090   // globals.hpp to the aligned value, but this is not possible, since the
  3091   // alignment depends on other flags being parsed.
  3092   MaxMetaspaceSize = restricted_align_down(MaxMetaspaceSize, _reserve_alignment);
  3094   if (MetaspaceSize > MaxMetaspaceSize) {
  3095     MetaspaceSize = MaxMetaspaceSize;
  3098   MetaspaceSize = restricted_align_down(MetaspaceSize, _commit_alignment);
  3100   assert(MetaspaceSize <= MaxMetaspaceSize, "MetaspaceSize should be limited by MaxMetaspaceSize");
  3102   if (MetaspaceSize < 256*K) {
  3103     vm_exit_during_initialization("Too small initial Metaspace size");
  3106   MinMetaspaceExpansion = restricted_align_down(MinMetaspaceExpansion, _commit_alignment);
  3107   MaxMetaspaceExpansion = restricted_align_down(MaxMetaspaceExpansion, _commit_alignment);
  3109   CompressedClassSpaceSize = restricted_align_down(CompressedClassSpaceSize, _reserve_alignment);
  3110   set_class_metaspace_size(CompressedClassSpaceSize);
  3113 void Metaspace::global_initialize() {
  3114   // Initialize the alignment for shared spaces.
  3115   int max_alignment = os::vm_page_size();
  3116   size_t cds_total = 0;
  3118   MetaspaceShared::set_max_alignment(max_alignment);
  3120   if (DumpSharedSpaces) {
  3121     SharedReadOnlySize  = align_size_up(SharedReadOnlySize,  max_alignment);
  3122     SharedReadWriteSize = align_size_up(SharedReadWriteSize, max_alignment);
  3123     SharedMiscDataSize  = align_size_up(SharedMiscDataSize,  max_alignment);
  3124     SharedMiscCodeSize  = align_size_up(SharedMiscCodeSize,  max_alignment);
  3126     // Initialize with the sum of the shared space sizes.  The read-only
  3127     // and read write metaspace chunks will be allocated out of this and the
  3128     // remainder is the misc code and data chunks.
  3129     cds_total = FileMapInfo::shared_spaces_size();
  3130     cds_total = align_size_up(cds_total, _reserve_alignment);
  3131     _space_list = new VirtualSpaceList(cds_total/wordSize);
  3132     _chunk_manager_metadata = new ChunkManager(SpecializedChunk, SmallChunk, MediumChunk);
  3134     if (!_space_list->initialization_succeeded()) {
  3135       vm_exit_during_initialization("Unable to dump shared archive.", NULL);
  3138 #ifdef _LP64
  3139     if (cds_total + class_metaspace_size() > (uint64_t)max_juint) {
  3140       vm_exit_during_initialization("Unable to dump shared archive.",
  3141           err_msg("Size of archive (" SIZE_FORMAT ") + compressed class space ("
  3142                   SIZE_FORMAT ") == total (" SIZE_FORMAT ") is larger than compressed "
  3143                   "klass limit: " SIZE_FORMAT, cds_total, class_metaspace_size(),
  3144                   cds_total + class_metaspace_size(), (size_t)max_juint));
  3147     // Set the compressed klass pointer base so that decoding of these pointers works
  3148     // properly when creating the shared archive.
  3149     assert(UseCompressedOops && UseCompressedClassPointers,
  3150       "UseCompressedOops and UseCompressedClassPointers must be set");
  3151     Universe::set_narrow_klass_base((address)_space_list->current_virtual_space()->bottom());
  3152     if (TraceMetavirtualspaceAllocation && Verbose) {
  3153       gclog_or_tty->print_cr("Setting_narrow_klass_base to Address: " PTR_FORMAT,
  3154                              _space_list->current_virtual_space()->bottom());
  3157     Universe::set_narrow_klass_shift(0);
  3158 #endif
  3160   } else {
  3161     // If using shared space, open the file that contains the shared space
  3162     // and map in the memory before initializing the rest of metaspace (so
  3163     // the addresses don't conflict)
  3164     address cds_address = NULL;
  3165     if (UseSharedSpaces) {
  3166       FileMapInfo* mapinfo = new FileMapInfo();
  3167       memset(mapinfo, 0, sizeof(FileMapInfo));
  3169       // Open the shared archive file, read and validate the header. If
  3170       // initialization fails, shared spaces [UseSharedSpaces] are
  3171       // disabled and the file is closed.
  3172       // Map in spaces now also
  3173       if (mapinfo->initialize() && MetaspaceShared::map_shared_spaces(mapinfo)) {
  3174         FileMapInfo::set_current_info(mapinfo);
  3175         cds_total = FileMapInfo::shared_spaces_size();
  3176         cds_address = (address)mapinfo->region_base(0);
  3177       } else {
  3178         assert(!mapinfo->is_open() && !UseSharedSpaces,
  3179                "archive file not closed or shared spaces not disabled.");
  3183 #ifdef _LP64
  3184     // If UseCompressedClassPointers is set then allocate the metaspace area
  3185     // above the heap and above the CDS area (if it exists).
  3186     if (using_class_space()) {
  3187       if (UseSharedSpaces) {
  3188         char* cds_end = (char*)(cds_address + cds_total);
  3189         cds_end = (char *)align_ptr_up(cds_end, _reserve_alignment);
  3190         allocate_metaspace_compressed_klass_ptrs(cds_end, cds_address);
  3191       } else {
  3192         allocate_metaspace_compressed_klass_ptrs((char *)CompressedKlassPointersBase, 0);
  3195 #endif
  3197     // Initialize these before initializing the VirtualSpaceList
  3198     _first_chunk_word_size = InitialBootClassLoaderMetaspaceSize / BytesPerWord;
  3199     _first_chunk_word_size = align_word_size_up(_first_chunk_word_size);
  3200     // Make the first class chunk bigger than a medium chunk so it's not put
  3201     // on the medium chunk list.   The next chunk will be small and progress
  3202     // from there.  This size calculated by -version.
  3203     _first_class_chunk_word_size = MIN2((size_t)MediumChunk*6,
  3204                                        (CompressedClassSpaceSize/BytesPerWord)*2);
  3205     _first_class_chunk_word_size = align_word_size_up(_first_class_chunk_word_size);
  3206     // Arbitrarily set the initial virtual space to a multiple
  3207     // of the boot class loader size.
  3208     size_t word_size = VIRTUALSPACEMULTIPLIER * _first_chunk_word_size;
  3209     word_size = align_size_up(word_size, Metaspace::reserve_alignment_words());
  3211     // Initialize the list of virtual spaces.
  3212     _space_list = new VirtualSpaceList(word_size);
  3213     _chunk_manager_metadata = new ChunkManager(SpecializedChunk, SmallChunk, MediumChunk);
  3215     if (!_space_list->initialization_succeeded()) {
  3216       vm_exit_during_initialization("Unable to setup metadata virtual space list.", NULL);
  3220   MetaspaceGC::initialize();
  3223 Metachunk* Metaspace::get_initialization_chunk(MetadataType mdtype,
  3224                                                size_t chunk_word_size,
  3225                                                size_t chunk_bunch) {
  3226   // Get a chunk from the chunk freelist
  3227   Metachunk* chunk = get_chunk_manager(mdtype)->chunk_freelist_allocate(chunk_word_size);
  3228   if (chunk != NULL) {
  3229     return chunk;
  3232   return get_space_list(mdtype)->get_new_chunk(chunk_word_size, chunk_word_size, chunk_bunch);
  3235 void Metaspace::initialize(Mutex* lock, MetaspaceType type) {
  3237   assert(space_list() != NULL,
  3238     "Metadata VirtualSpaceList has not been initialized");
  3239   assert(chunk_manager_metadata() != NULL,
  3240     "Metadata ChunkManager has not been initialized");
  3242   _vsm = new SpaceManager(NonClassType, lock);
  3243   if (_vsm == NULL) {
  3244     return;
  3246   size_t word_size;
  3247   size_t class_word_size;
  3248   vsm()->get_initial_chunk_sizes(type, &word_size, &class_word_size);
  3250   if (using_class_space()) {
  3251   assert(class_space_list() != NULL,
  3252     "Class VirtualSpaceList has not been initialized");
  3253   assert(chunk_manager_class() != NULL,
  3254     "Class ChunkManager has not been initialized");
  3256     // Allocate SpaceManager for classes.
  3257     _class_vsm = new SpaceManager(ClassType, lock);
  3258     if (_class_vsm == NULL) {
  3259       return;
  3263   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  3265   // Allocate chunk for metadata objects
  3266   Metachunk* new_chunk = get_initialization_chunk(NonClassType,
  3267                                                   word_size,
  3268                                                   vsm()->medium_chunk_bunch());
  3269   assert(!DumpSharedSpaces || new_chunk != NULL, "should have enough space for both chunks");
  3270   if (new_chunk != NULL) {
  3271     // Add to this manager's list of chunks in use and current_chunk().
  3272     vsm()->add_chunk(new_chunk, true);
  3275   // Allocate chunk for class metadata objects
  3276   if (using_class_space()) {
  3277     Metachunk* class_chunk = get_initialization_chunk(ClassType,
  3278                                                       class_word_size,
  3279                                                       class_vsm()->medium_chunk_bunch());
  3280     if (class_chunk != NULL) {
  3281       class_vsm()->add_chunk(class_chunk, true);
  3285   _alloc_record_head = NULL;
  3286   _alloc_record_tail = NULL;
  3289 size_t Metaspace::align_word_size_up(size_t word_size) {
  3290   size_t byte_size = word_size * wordSize;
  3291   return ReservedSpace::allocation_align_size_up(byte_size) / wordSize;
  3294 MetaWord* Metaspace::allocate(size_t word_size, MetadataType mdtype) {
  3295   // DumpSharedSpaces doesn't use class metadata area (yet)
  3296   // Also, don't use class_vsm() unless UseCompressedClassPointers is true.
  3297   if (is_class_space_allocation(mdtype)) {
  3298     return  class_vsm()->allocate(word_size);
  3299   } else {
  3300     return  vsm()->allocate(word_size);
  3304 MetaWord* Metaspace::expand_and_allocate(size_t word_size, MetadataType mdtype) {
  3305   size_t delta_bytes = MetaspaceGC::delta_capacity_until_GC(word_size * BytesPerWord);
  3306   assert(delta_bytes > 0, "Must be");
  3308   size_t after_inc = MetaspaceGC::inc_capacity_until_GC(delta_bytes);
  3309   size_t before_inc = after_inc - delta_bytes;
  3311   if (PrintGCDetails && Verbose) {
  3312     gclog_or_tty->print_cr("Increase capacity to GC from " SIZE_FORMAT
  3313         " to " SIZE_FORMAT, before_inc, after_inc);
  3316   return allocate(word_size, mdtype);
  3319 // Space allocated in the Metaspace.  This may
  3320 // be across several metadata virtual spaces.
  3321 char* Metaspace::bottom() const {
  3322   assert(DumpSharedSpaces, "only useful and valid for dumping shared spaces");
  3323   return (char*)vsm()->current_chunk()->bottom();
  3326 size_t Metaspace::used_words_slow(MetadataType mdtype) const {
  3327   if (mdtype == ClassType) {
  3328     return using_class_space() ? class_vsm()->sum_used_in_chunks_in_use() : 0;
  3329   } else {
  3330     return vsm()->sum_used_in_chunks_in_use();  // includes overhead!
  3334 size_t Metaspace::free_words_slow(MetadataType mdtype) const {
  3335   if (mdtype == ClassType) {
  3336     return using_class_space() ? class_vsm()->sum_free_in_chunks_in_use() : 0;
  3337   } else {
  3338     return vsm()->sum_free_in_chunks_in_use();
  3342 // Space capacity in the Metaspace.  It includes
  3343 // space in the list of chunks from which allocations
  3344 // have been made. Don't include space in the global freelist and
  3345 // in the space available in the dictionary which
  3346 // is already counted in some chunk.
  3347 size_t Metaspace::capacity_words_slow(MetadataType mdtype) const {
  3348   if (mdtype == ClassType) {
  3349     return using_class_space() ? class_vsm()->sum_capacity_in_chunks_in_use() : 0;
  3350   } else {
  3351     return vsm()->sum_capacity_in_chunks_in_use();
  3355 size_t Metaspace::used_bytes_slow(MetadataType mdtype) const {
  3356   return used_words_slow(mdtype) * BytesPerWord;
  3359 size_t Metaspace::capacity_bytes_slow(MetadataType mdtype) const {
  3360   return capacity_words_slow(mdtype) * BytesPerWord;
  3363 void Metaspace::deallocate(MetaWord* ptr, size_t word_size, bool is_class) {
  3364   if (SafepointSynchronize::is_at_safepoint()) {
  3365     assert(Thread::current()->is_VM_thread(), "should be the VM thread");
  3366     // Don't take Heap_lock
  3367     MutexLockerEx ml(vsm()->lock(), Mutex::_no_safepoint_check_flag);
  3368     if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
  3369       // Dark matter.  Too small for dictionary.
  3370 #ifdef ASSERT
  3371       Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
  3372 #endif
  3373       return;
  3375     if (is_class && using_class_space()) {
  3376       class_vsm()->deallocate(ptr, word_size);
  3377     } else {
  3378       vsm()->deallocate(ptr, word_size);
  3380   } else {
  3381     MutexLockerEx ml(vsm()->lock(), Mutex::_no_safepoint_check_flag);
  3383     if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
  3384       // Dark matter.  Too small for dictionary.
  3385 #ifdef ASSERT
  3386       Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
  3387 #endif
  3388       return;
  3390     if (is_class && using_class_space()) {
  3391       class_vsm()->deallocate(ptr, word_size);
  3392     } else {
  3393       vsm()->deallocate(ptr, word_size);
  3399 Metablock* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size,
  3400                               bool read_only, MetaspaceObj::Type type, TRAPS) {
  3401   if (HAS_PENDING_EXCEPTION) {
  3402     assert(false, "Should not allocate with exception pending");
  3403     return NULL;  // caller does a CHECK_NULL too
  3406   assert(loader_data != NULL, "Should never pass around a NULL loader_data. "
  3407         "ClassLoaderData::the_null_class_loader_data() should have been used.");
  3409   // Allocate in metaspaces without taking out a lock, because it deadlocks
  3410   // with the SymbolTable_lock.  Dumping is single threaded for now.  We'll have
  3411   // to revisit this for application class data sharing.
  3412   if (DumpSharedSpaces) {
  3413     assert(type > MetaspaceObj::UnknownType && type < MetaspaceObj::_number_of_types, "sanity");
  3414     Metaspace* space = read_only ? loader_data->ro_metaspace() : loader_data->rw_metaspace();
  3415     MetaWord* result = space->allocate(word_size, NonClassType);
  3416     if (result == NULL) {
  3417       report_out_of_shared_space(read_only ? SharedReadOnly : SharedReadWrite);
  3418     } else {
  3419       space->record_allocation(result, type, space->vsm()->get_raw_word_size(word_size));
  3421     return Metablock::initialize(result, word_size);
  3424   MetadataType mdtype = (type == MetaspaceObj::ClassType) ? ClassType : NonClassType;
  3426   // Try to allocate metadata.
  3427   MetaWord* result = loader_data->metaspace_non_null()->allocate(word_size, mdtype);
  3429   if (result == NULL) {
  3430     // Allocation failed.
  3431     if (is_init_completed()) {
  3432       // Only start a GC if the bootstrapping has completed.
  3434       // Try to clean out some memory and retry.
  3435       result = Universe::heap()->collector_policy()->satisfy_failed_metadata_allocation(
  3436           loader_data, word_size, mdtype);
  3440   if (result == NULL) {
  3441     report_metadata_oome(loader_data, word_size, mdtype, THREAD);
  3442     // Will not reach here.
  3443     return NULL;
  3446   return Metablock::initialize(result, word_size);
  3449 void Metaspace::report_metadata_oome(ClassLoaderData* loader_data, size_t word_size, MetadataType mdtype, TRAPS) {
  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   // -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support
  3461   const char* space_string = is_class_space_allocation(mdtype) ? "Compressed class space" :
  3462                                                                  "Metadata space";
  3463   report_java_out_of_memory(space_string);
  3465   if (JvmtiExport::should_post_resource_exhausted()) {
  3466     JvmtiExport::post_resource_exhausted(
  3467         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR,
  3468         space_string);
  3471   if (!is_init_completed()) {
  3472     vm_exit_during_initialization("OutOfMemoryError", space_string);
  3475   if (is_class_space_allocation(mdtype)) {
  3476     THROW_OOP(Universe::out_of_memory_error_class_metaspace());
  3477   } else {
  3478     THROW_OOP(Universe::out_of_memory_error_metaspace());
  3482 void Metaspace::record_allocation(void* ptr, MetaspaceObj::Type type, size_t word_size) {
  3483   assert(DumpSharedSpaces, "sanity");
  3485   AllocRecord *rec = new AllocRecord((address)ptr, type, (int)word_size * HeapWordSize);
  3486   if (_alloc_record_head == NULL) {
  3487     _alloc_record_head = _alloc_record_tail = rec;
  3488   } else {
  3489     _alloc_record_tail->_next = rec;
  3490     _alloc_record_tail = rec;
  3494 void Metaspace::iterate(Metaspace::AllocRecordClosure *closure) {
  3495   assert(DumpSharedSpaces, "unimplemented for !DumpSharedSpaces");
  3497   address last_addr = (address)bottom();
  3499   for (AllocRecord *rec = _alloc_record_head; rec; rec = rec->_next) {
  3500     address ptr = rec->_ptr;
  3501     if (last_addr < ptr) {
  3502       closure->doit(last_addr, MetaspaceObj::UnknownType, ptr - last_addr);
  3504     closure->doit(ptr, rec->_type, rec->_byte_size);
  3505     last_addr = ptr + rec->_byte_size;
  3508   address top = ((address)bottom()) + used_bytes_slow(Metaspace::NonClassType);
  3509   if (last_addr < top) {
  3510     closure->doit(last_addr, MetaspaceObj::UnknownType, top - last_addr);
  3514 void Metaspace::purge(MetadataType mdtype) {
  3515   get_space_list(mdtype)->purge(get_chunk_manager(mdtype));
  3518 void Metaspace::purge() {
  3519   MutexLockerEx cl(SpaceManager::expand_lock(),
  3520                    Mutex::_no_safepoint_check_flag);
  3521   purge(NonClassType);
  3522   if (using_class_space()) {
  3523     purge(ClassType);
  3527 void Metaspace::print_on(outputStream* out) const {
  3528   // Print both class virtual space counts and metaspace.
  3529   if (Verbose) {
  3530     vsm()->print_on(out);
  3531     if (using_class_space()) {
  3532       class_vsm()->print_on(out);
  3537 bool Metaspace::contains(const void * ptr) {
  3538   if (MetaspaceShared::is_in_shared_space(ptr)) {
  3539     return true;
  3541   // This is checked while unlocked.  As long as the virtualspaces are added
  3542   // at the end, the pointer will be in one of them.  The virtual spaces
  3543   // aren't deleted presently.  When they are, some sort of locking might
  3544   // be needed.  Note, locking this can cause inversion problems with the
  3545   // caller in MetaspaceObj::is_metadata() function.
  3546   return space_list()->contains(ptr) ||
  3547          (using_class_space() && class_space_list()->contains(ptr));
  3550 void Metaspace::verify() {
  3551   vsm()->verify();
  3552   if (using_class_space()) {
  3553     class_vsm()->verify();
  3557 void Metaspace::dump(outputStream* const out) const {
  3558   out->print_cr("\nVirtual space manager: " INTPTR_FORMAT, vsm());
  3559   vsm()->dump(out);
  3560   if (using_class_space()) {
  3561     out->print_cr("\nClass space manager: " INTPTR_FORMAT, class_vsm());
  3562     class_vsm()->dump(out);
  3566 /////////////// Unit tests ///////////////
  3568 #ifndef PRODUCT
  3570 class TestMetaspaceAuxTest : AllStatic {
  3571  public:
  3572   static void test_reserved() {
  3573     size_t reserved = MetaspaceAux::reserved_bytes();
  3575     assert(reserved > 0, "assert");
  3577     size_t committed  = MetaspaceAux::committed_bytes();
  3578     assert(committed <= reserved, "assert");
  3580     size_t reserved_metadata = MetaspaceAux::reserved_bytes(Metaspace::NonClassType);
  3581     assert(reserved_metadata > 0, "assert");
  3582     assert(reserved_metadata <= reserved, "assert");
  3584     if (UseCompressedClassPointers) {
  3585       size_t reserved_class    = MetaspaceAux::reserved_bytes(Metaspace::ClassType);
  3586       assert(reserved_class > 0, "assert");
  3587       assert(reserved_class < reserved, "assert");
  3591   static void test_committed() {
  3592     size_t committed = MetaspaceAux::committed_bytes();
  3594     assert(committed > 0, "assert");
  3596     size_t reserved  = MetaspaceAux::reserved_bytes();
  3597     assert(committed <= reserved, "assert");
  3599     size_t committed_metadata = MetaspaceAux::committed_bytes(Metaspace::NonClassType);
  3600     assert(committed_metadata > 0, "assert");
  3601     assert(committed_metadata <= committed, "assert");
  3603     if (UseCompressedClassPointers) {
  3604       size_t committed_class    = MetaspaceAux::committed_bytes(Metaspace::ClassType);
  3605       assert(committed_class > 0, "assert");
  3606       assert(committed_class < committed, "assert");
  3610   static void test_virtual_space_list_large_chunk() {
  3611     VirtualSpaceList* vs_list = new VirtualSpaceList(os::vm_allocation_granularity());
  3612     MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  3613     // A size larger than VirtualSpaceSize (256k) and add one page to make it _not_ be
  3614     // vm_allocation_granularity aligned on Windows.
  3615     size_t large_size = (size_t)(2*256*K + (os::vm_page_size()/BytesPerWord));
  3616     large_size += (os::vm_page_size()/BytesPerWord);
  3617     vs_list->get_new_chunk(large_size, large_size, 0);
  3620   static void test() {
  3621     test_reserved();
  3622     test_committed();
  3623     test_virtual_space_list_large_chunk();
  3625 };
  3627 void TestMetaspaceAux_test() {
  3628   TestMetaspaceAuxTest::test();
  3631 #endif

mercurial