src/share/vm/memory/metaspace.cpp

Thu, 21 Mar 2013 09:07:43 +0100

author
mgerdin
date
Thu, 21 Mar 2013 09:07:43 +0100
changeset 4790
7f0cb32dd233
parent 4786
19f9fabd94cc
child 4791
47902e9acb3a
permissions
-rw-r--r--

8004241: NPG: Metaspace occupies more memory than specified by -XX:MaxMetaspaceSize option
Summary: Enforce MaxMetaspaceSize for both metaspace parts, check MaxMetaspaceSize against "reserved", not "capacity"
Reviewed-by: jmasa, johnc

     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/binaryTreeDictionary.hpp"
    27 #include "memory/freeList.hpp"
    28 #include "memory/collectorPolicy.hpp"
    29 #include "memory/filemap.hpp"
    30 #include "memory/freeList.hpp"
    31 #include "memory/metablock.hpp"
    32 #include "memory/metachunk.hpp"
    33 #include "memory/metaspace.hpp"
    34 #include "memory/metaspaceShared.hpp"
    35 #include "memory/resourceArea.hpp"
    36 #include "memory/universe.hpp"
    37 #include "runtime/globals.hpp"
    38 #include "runtime/mutex.hpp"
    39 #include "runtime/orderAccess.hpp"
    40 #include "services/memTracker.hpp"
    41 #include "utilities/copy.hpp"
    42 #include "utilities/debug.hpp"
    44 typedef BinaryTreeDictionary<Metablock, FreeList> BlockTreeDictionary;
    45 typedef BinaryTreeDictionary<Metachunk, FreeList> ChunkTreeDictionary;
    46 // Define this macro to enable slow integrity checking of
    47 // the free chunk lists
    48 const bool metaspace_slow_verify = false;
    51 // Parameters for stress mode testing
    52 const uint metadata_deallocate_a_lot_block = 10;
    53 const uint metadata_deallocate_a_lock_chunk = 3;
    54 size_t const allocation_from_dictionary_limit = 64 * K;
    56 MetaWord* last_allocated = 0;
    58 // Used in declarations in SpaceManager and ChunkManager
    59 enum ChunkIndex {
    60   ZeroIndex = 0,
    61   SpecializedIndex = ZeroIndex,
    62   SmallIndex = SpecializedIndex + 1,
    63   MediumIndex = SmallIndex + 1,
    64   HumongousIndex = MediumIndex + 1,
    65   NumberOfFreeLists = 3,
    66   NumberOfInUseLists = 4
    67 };
    69 enum ChunkSizes {    // in words.
    70   ClassSpecializedChunk = 128,
    71   SpecializedChunk = 128,
    72   ClassSmallChunk = 256,
    73   SmallChunk = 512,
    74   ClassMediumChunk = 1 * K,
    75   MediumChunk = 8 * K,
    76   HumongousChunkGranularity = 8
    77 };
    79 static ChunkIndex next_chunk_index(ChunkIndex i) {
    80   assert(i < NumberOfInUseLists, "Out of bound");
    81   return (ChunkIndex) (i+1);
    82 }
    84 // Originally _capacity_until_GC was set to MetaspaceSize here but
    85 // the default MetaspaceSize before argument processing was being
    86 // used which was not the desired value.  See the code
    87 // in should_expand() to see how the initialization is handled
    88 // now.
    89 size_t MetaspaceGC::_capacity_until_GC = 0;
    90 bool MetaspaceGC::_expand_after_GC = false;
    91 uint MetaspaceGC::_shrink_factor = 0;
    92 bool MetaspaceGC::_should_concurrent_collect = false;
    94 // Blocks of space for metadata are allocated out of Metachunks.
    95 //
    96 // Metachunk are allocated out of MetadataVirtualspaces and once
    97 // allocated there is no explicit link between a Metachunk and
    98 // the MetadataVirtualspaces from which it was allocated.
    99 //
   100 // Each SpaceManager maintains a
   101 // list of the chunks it is using and the current chunk.  The current
   102 // chunk is the chunk from which allocations are done.  Space freed in
   103 // a chunk is placed on the free list of blocks (BlockFreelist) and
   104 // reused from there.
   106 // Pointer to list of Metachunks.
   107 class ChunkList VALUE_OBJ_CLASS_SPEC {
   108   // List of free chunks
   109   Metachunk* _head;
   111  public:
   112   // Constructor
   113   ChunkList() : _head(NULL) {}
   115   // Accessors
   116   Metachunk* head() { return _head; }
   117   void set_head(Metachunk* v) { _head = v; }
   119   // Link at head of the list
   120   void add_at_head(Metachunk* head, Metachunk* tail);
   121   void add_at_head(Metachunk* head);
   123   size_t sum_list_size();
   124   size_t sum_list_count();
   125   size_t sum_list_capacity();
   126 };
   128 // Manages the global free lists of chunks.
   129 // Has three lists of free chunks, and a total size and
   130 // count that includes all three
   132 class ChunkManager VALUE_OBJ_CLASS_SPEC {
   134   // Free list of chunks of different sizes.
   135   //   SmallChunk
   136   //   MediumChunk
   137   //   HumongousChunk
   138   ChunkList _free_chunks[NumberOfFreeLists];
   141   //   HumongousChunk
   142   ChunkTreeDictionary _humongous_dictionary;
   144   // ChunkManager in all lists of this type
   145   size_t _free_chunks_total;
   146   size_t _free_chunks_count;
   148   void dec_free_chunks_total(size_t v) {
   149     assert(_free_chunks_count > 0 &&
   150              _free_chunks_total > 0,
   151              "About to go negative");
   152     Atomic::add_ptr(-1, &_free_chunks_count);
   153     jlong minus_v = (jlong) - (jlong) v;
   154     Atomic::add_ptr(minus_v, &_free_chunks_total);
   155   }
   157   // Debug support
   159   size_t sum_free_chunks();
   160   size_t sum_free_chunks_count();
   162   void locked_verify_free_chunks_total();
   163   void slow_locked_verify_free_chunks_total() {
   164     if (metaspace_slow_verify) {
   165       locked_verify_free_chunks_total();
   166     }
   167   }
   168   void locked_verify_free_chunks_count();
   169   void slow_locked_verify_free_chunks_count() {
   170     if (metaspace_slow_verify) {
   171       locked_verify_free_chunks_count();
   172     }
   173   }
   174   void verify_free_chunks_count();
   176  public:
   178   ChunkManager() : _free_chunks_total(0), _free_chunks_count(0) {}
   180   // add or delete (return) a chunk to the global freelist.
   181   Metachunk* chunk_freelist_allocate(size_t word_size);
   182   void chunk_freelist_deallocate(Metachunk* chunk);
   184   // Map a size to a list index assuming that there are lists
   185   // for special, small, medium, and humongous chunks.
   186   static ChunkIndex list_index(size_t size);
   188   // Total of the space in the free chunks list
   189   size_t free_chunks_total();
   190   size_t free_chunks_total_in_bytes();
   192   // Number of chunks in the free chunks list
   193   size_t free_chunks_count();
   195   void inc_free_chunks_total(size_t v, size_t count = 1) {
   196     Atomic::add_ptr(count, &_free_chunks_count);
   197     Atomic::add_ptr(v, &_free_chunks_total);
   198   }
   199   ChunkTreeDictionary* humongous_dictionary() {
   200     return &_humongous_dictionary;
   201   }
   203   ChunkList* free_chunks(ChunkIndex index);
   205   // Returns the list for the given chunk word size.
   206   ChunkList* find_free_chunks_list(size_t word_size);
   208   // Add and remove from a list by size.  Selects
   209   // list based on size of chunk.
   210   void free_chunks_put(Metachunk* chuck);
   211   Metachunk* free_chunks_get(size_t chunk_word_size);
   213   // Debug support
   214   void verify();
   215   void slow_verify() {
   216     if (metaspace_slow_verify) {
   217       verify();
   218     }
   219   }
   220   void locked_verify();
   221   void slow_locked_verify() {
   222     if (metaspace_slow_verify) {
   223       locked_verify();
   224     }
   225   }
   226   void verify_free_chunks_total();
   228   void locked_print_free_chunks(outputStream* st);
   229   void locked_print_sum_free_chunks(outputStream* st);
   231   void print_on(outputStream* st);
   232 };
   235 // Used to manage the free list of Metablocks (a block corresponds
   236 // to the allocation of a quantum of metadata).
   237 class BlockFreelist VALUE_OBJ_CLASS_SPEC {
   238   BlockTreeDictionary* _dictionary;
   239   static Metablock* initialize_free_chunk(MetaWord* p, size_t word_size);
   241   // Accessors
   242   BlockTreeDictionary* dictionary() const { return _dictionary; }
   244  public:
   245   BlockFreelist();
   246   ~BlockFreelist();
   248   // Get and return a block to the free list
   249   MetaWord* get_block(size_t word_size);
   250   void return_block(MetaWord* p, size_t word_size);
   252   size_t total_size() {
   253   if (dictionary() == NULL) {
   254     return 0;
   255   } else {
   256     return dictionary()->total_size();
   257   }
   258 }
   260   void print_on(outputStream* st) const;
   261 };
   263 class VirtualSpaceNode : public CHeapObj<mtClass> {
   264   friend class VirtualSpaceList;
   266   // Link to next VirtualSpaceNode
   267   VirtualSpaceNode* _next;
   269   // total in the VirtualSpace
   270   MemRegion _reserved;
   271   ReservedSpace _rs;
   272   VirtualSpace _virtual_space;
   273   MetaWord* _top;
   275   // Convenience functions for logical bottom and end
   276   MetaWord* bottom() const { return (MetaWord*) _virtual_space.low(); }
   277   MetaWord* end() const { return (MetaWord*) _virtual_space.high(); }
   279   // Convenience functions to access the _virtual_space
   280   char* low()  const { return virtual_space()->low(); }
   281   char* high() const { return virtual_space()->high(); }
   283  public:
   285   VirtualSpaceNode(size_t byte_size);
   286   VirtualSpaceNode(ReservedSpace rs) : _top(NULL), _next(NULL), _rs(rs) {}
   287   ~VirtualSpaceNode();
   289   // address of next available space in _virtual_space;
   290   // Accessors
   291   VirtualSpaceNode* next() { return _next; }
   292   void set_next(VirtualSpaceNode* v) { _next = v; }
   294   void set_reserved(MemRegion const v) { _reserved = v; }
   295   void set_top(MetaWord* v) { _top = v; }
   297   // Accessors
   298   MemRegion* reserved() { return &_reserved; }
   299   VirtualSpace* virtual_space() const { return (VirtualSpace*) &_virtual_space; }
   301   // Returns true if "word_size" is available in the virtual space
   302   bool is_available(size_t word_size) { return _top + word_size <= end(); }
   304   MetaWord* top() const { return _top; }
   305   void inc_top(size_t word_size) { _top += word_size; }
   307   // used and capacity in this single entry in the list
   308   size_t used_words_in_vs() const;
   309   size_t capacity_words_in_vs() const;
   311   bool initialize();
   313   // get space from the virtual space
   314   Metachunk* take_from_committed(size_t chunk_word_size);
   316   // Allocate a chunk from the virtual space and return it.
   317   Metachunk* get_chunk_vs(size_t chunk_word_size);
   318   Metachunk* get_chunk_vs_with_expand(size_t chunk_word_size);
   320   // Expands/shrinks the committed space in a virtual space.  Delegates
   321   // to Virtualspace
   322   bool expand_by(size_t words, bool pre_touch = false);
   323   bool shrink_by(size_t words);
   325 #ifdef ASSERT
   326   // Debug support
   327   static void verify_virtual_space_total();
   328   static void verify_virtual_space_count();
   329   void mangle();
   330 #endif
   332   void print_on(outputStream* st) const;
   333 };
   335   // byte_size is the size of the associated virtualspace.
   336 VirtualSpaceNode::VirtualSpaceNode(size_t byte_size) : _top(NULL), _next(NULL), _rs(0) {
   337   // This allocates memory with mmap.  For DumpSharedspaces, allocate the
   338   // space at low memory so that other shared images don't conflict.
   339   // This is the same address as memory needed for UseCompressedOops but
   340   // compressed oops don't work with CDS (offsets in metadata are wrong), so
   341   // borrow the same address.
   342   if (DumpSharedSpaces) {
   343     char* shared_base = (char*)HeapBaseMinAddress;
   344     _rs = ReservedSpace(byte_size, 0, false, shared_base, 0);
   345     if (_rs.is_reserved()) {
   346       assert(_rs.base() == shared_base, "should match");
   347     } else {
   348       // If we are dumping the heap, then allocate a wasted block of address
   349       // space in order to push the heap to a lower address.  This extra
   350       // address range allows for other (or larger) libraries to be loaded
   351       // without them occupying the space required for the shared spaces.
   352       uintx reserved = 0;
   353       uintx block_size = 64*1024*1024;
   354       while (reserved < SharedDummyBlockSize) {
   355         char* dummy = os::reserve_memory(block_size);
   356         reserved += block_size;
   357       }
   358       _rs = ReservedSpace(byte_size);
   359     }
   360     MetaspaceShared::set_shared_rs(&_rs);
   361   } else {
   362     _rs = ReservedSpace(byte_size);
   363   }
   365   MemTracker::record_virtual_memory_type((address)_rs.base(), mtClass);
   366 }
   368 // List of VirtualSpaces for metadata allocation.
   369 // It has a  _next link for singly linked list and a MemRegion
   370 // for total space in the VirtualSpace.
   371 class VirtualSpaceList : public CHeapObj<mtClass> {
   372   friend class VirtualSpaceNode;
   374   enum VirtualSpaceSizes {
   375     VirtualSpaceSize = 256 * K
   376   };
   378   // Global list of virtual spaces
   379   // Head of the list
   380   VirtualSpaceNode* _virtual_space_list;
   381   // virtual space currently being used for allocations
   382   VirtualSpaceNode* _current_virtual_space;
   383   // Free chunk list for all other metadata
   384   ChunkManager      _chunk_manager;
   386   // Can this virtual list allocate >1 spaces?  Also, used to determine
   387   // whether to allocate unlimited small chunks in this virtual space
   388   bool _is_class;
   389   bool can_grow() const { return !is_class() || !UseCompressedKlassPointers; }
   391   // Sum of space in all virtual spaces and number of virtual spaces
   392   size_t _virtual_space_total;
   393   size_t _virtual_space_count;
   395   ~VirtualSpaceList();
   397   VirtualSpaceNode* virtual_space_list() const { return _virtual_space_list; }
   399   void set_virtual_space_list(VirtualSpaceNode* v) {
   400     _virtual_space_list = v;
   401   }
   402   void set_current_virtual_space(VirtualSpaceNode* v) {
   403     _current_virtual_space = v;
   404   }
   406   void link_vs(VirtualSpaceNode* new_entry, size_t vs_word_size);
   408   // Get another virtual space and add it to the list.  This
   409   // is typically prompted by a failed attempt to allocate a chunk
   410   // and is typically followed by the allocation of a chunk.
   411   bool grow_vs(size_t vs_word_size);
   413  public:
   414   VirtualSpaceList(size_t word_size);
   415   VirtualSpaceList(ReservedSpace rs);
   417   Metachunk* get_new_chunk(size_t word_size,
   418                            size_t grow_chunks_by_words,
   419                            size_t medium_chunk_bunch);
   421   // Get the first chunk for a Metaspace.  Used for
   422   // special cases such as the boot class loader, reflection
   423   // class loader and anonymous class loader.
   424   Metachunk* get_initialization_chunk(size_t word_size, size_t chunk_bunch);
   426   VirtualSpaceNode* current_virtual_space() {
   427     return _current_virtual_space;
   428   }
   430   ChunkManager* chunk_manager() { return &_chunk_manager; }
   431   bool is_class() const { return _is_class; }
   433   // Allocate the first virtualspace.
   434   void initialize(size_t word_size);
   436   size_t virtual_space_total() { return _virtual_space_total; }
   437   void inc_virtual_space_total(size_t v) {
   438     Atomic::add_ptr(v, &_virtual_space_total);
   439   }
   441   size_t virtual_space_count() { return _virtual_space_count; }
   442   void inc_virtual_space_count() {
   443     Atomic::inc_ptr(&_virtual_space_count);
   444   }
   446   // Used and capacity in the entire list of virtual spaces.
   447   // These are global values shared by all Metaspaces
   448   size_t capacity_words_sum();
   449   size_t capacity_bytes_sum() { return capacity_words_sum() * BytesPerWord; }
   450   size_t used_words_sum();
   451   size_t used_bytes_sum() { return used_words_sum() * BytesPerWord; }
   453   bool contains(const void *ptr);
   455   void print_on(outputStream* st) const;
   457   class VirtualSpaceListIterator : public StackObj {
   458     VirtualSpaceNode* _virtual_spaces;
   459    public:
   460     VirtualSpaceListIterator(VirtualSpaceNode* virtual_spaces) :
   461       _virtual_spaces(virtual_spaces) {}
   463     bool repeat() {
   464       return _virtual_spaces != NULL;
   465     }
   467     VirtualSpaceNode* get_next() {
   468       VirtualSpaceNode* result = _virtual_spaces;
   469       if (_virtual_spaces != NULL) {
   470         _virtual_spaces = _virtual_spaces->next();
   471       }
   472       return result;
   473     }
   474   };
   475 };
   477 class Metadebug : AllStatic {
   478   // Debugging support for Metaspaces
   479   static int _deallocate_block_a_lot_count;
   480   static int _deallocate_chunk_a_lot_count;
   481   static int _allocation_fail_alot_count;
   483  public:
   484   static int deallocate_block_a_lot_count() {
   485     return _deallocate_block_a_lot_count;
   486   }
   487   static void set_deallocate_block_a_lot_count(int v) {
   488     _deallocate_block_a_lot_count = v;
   489   }
   490   static void inc_deallocate_block_a_lot_count() {
   491     _deallocate_block_a_lot_count++;
   492   }
   493   static int deallocate_chunk_a_lot_count() {
   494     return _deallocate_chunk_a_lot_count;
   495   }
   496   static void reset_deallocate_chunk_a_lot_count() {
   497     _deallocate_chunk_a_lot_count = 1;
   498   }
   499   static void inc_deallocate_chunk_a_lot_count() {
   500     _deallocate_chunk_a_lot_count++;
   501   }
   503   static void init_allocation_fail_alot_count();
   504 #ifdef ASSERT
   505   static bool test_metadata_failure();
   506 #endif
   508   static void deallocate_chunk_a_lot(SpaceManager* sm,
   509                                      size_t chunk_word_size);
   510   static void deallocate_block_a_lot(SpaceManager* sm,
   511                                      size_t chunk_word_size);
   513 };
   515 int Metadebug::_deallocate_block_a_lot_count = 0;
   516 int Metadebug::_deallocate_chunk_a_lot_count = 0;
   517 int Metadebug::_allocation_fail_alot_count = 0;
   519 //  SpaceManager - used by Metaspace to handle allocations
   520 class SpaceManager : public CHeapObj<mtClass> {
   521   friend class Metaspace;
   522   friend class Metadebug;
   524  private:
   526   // protects allocations and contains.
   527   Mutex* const _lock;
   529   // Chunk related size
   530   size_t _medium_chunk_bunch;
   532   // List of chunks in use by this SpaceManager.  Allocations
   533   // are done from the current chunk.  The list is used for deallocating
   534   // chunks when the SpaceManager is freed.
   535   Metachunk* _chunks_in_use[NumberOfInUseLists];
   536   Metachunk* _current_chunk;
   538   // Virtual space where allocation comes from.
   539   VirtualSpaceList* _vs_list;
   541   // Number of small chunks to allocate to a manager
   542   // If class space manager, small chunks are unlimited
   543   static uint const _small_chunk_limit;
   544   bool has_small_chunk_limit() { return !vs_list()->is_class(); }
   546   // Sum of all space in allocated chunks
   547   size_t _allocation_total;
   549   // Free lists of blocks are per SpaceManager since they
   550   // are assumed to be in chunks in use by the SpaceManager
   551   // and all chunks in use by a SpaceManager are freed when
   552   // the class loader using the SpaceManager is collected.
   553   BlockFreelist _block_freelists;
   555   // protects virtualspace and chunk expansions
   556   static const char*  _expand_lock_name;
   557   static const int    _expand_lock_rank;
   558   static Mutex* const _expand_lock;
   560  private:
   561   // Accessors
   562   Metachunk* chunks_in_use(ChunkIndex index) const { return _chunks_in_use[index]; }
   563   void set_chunks_in_use(ChunkIndex index, Metachunk* v) { _chunks_in_use[index] = v; }
   565   BlockFreelist* block_freelists() const {
   566     return (BlockFreelist*) &_block_freelists;
   567   }
   569   VirtualSpaceList* vs_list() const    { return _vs_list; }
   571   Metachunk* current_chunk() const { return _current_chunk; }
   572   void set_current_chunk(Metachunk* v) {
   573     _current_chunk = v;
   574   }
   576   Metachunk* find_current_chunk(size_t word_size);
   578   // Add chunk to the list of chunks in use
   579   void add_chunk(Metachunk* v, bool make_current);
   581   Mutex* lock() const { return _lock; }
   583   const char* chunk_size_name(ChunkIndex index) const;
   585  protected:
   586   void initialize();
   588  public:
   589   SpaceManager(Mutex* lock,
   590                VirtualSpaceList* vs_list);
   591   ~SpaceManager();
   593   enum ChunkMultiples {
   594     MediumChunkMultiple = 4
   595   };
   597   // Accessors
   598   size_t specialized_chunk_size() { return SpecializedChunk; }
   599   size_t small_chunk_size() { return (size_t) vs_list()->is_class() ? ClassSmallChunk : SmallChunk; }
   600   size_t medium_chunk_size() { return (size_t) vs_list()->is_class() ? ClassMediumChunk : MediumChunk; }
   601   size_t medium_chunk_bunch() { return medium_chunk_size() * MediumChunkMultiple; }
   603   size_t allocation_total() const { return _allocation_total; }
   604   void inc_allocation_total(size_t v) { Atomic::add_ptr(v, &_allocation_total); }
   605   bool is_humongous(size_t word_size) { return word_size > medium_chunk_size(); }
   607   static Mutex* expand_lock() { return _expand_lock; }
   609   // Set the sizes for the initial chunks.
   610   void get_initial_chunk_sizes(Metaspace::MetaspaceType type,
   611                                size_t* chunk_word_size,
   612                                size_t* class_chunk_word_size);
   614   size_t sum_capacity_in_chunks_in_use() const;
   615   size_t sum_used_in_chunks_in_use() const;
   616   size_t sum_free_in_chunks_in_use() const;
   617   size_t sum_waste_in_chunks_in_use() const;
   618   size_t sum_waste_in_chunks_in_use(ChunkIndex index ) const;
   620   size_t sum_count_in_chunks_in_use();
   621   size_t sum_count_in_chunks_in_use(ChunkIndex i);
   623   Metachunk* get_new_chunk(size_t word_size, size_t grow_chunks_by_words);
   625   // Block allocation and deallocation.
   626   // Allocates a block from the current chunk
   627   MetaWord* allocate(size_t word_size);
   629   // Helper for allocations
   630   MetaWord* allocate_work(size_t word_size);
   632   // Returns a block to the per manager freelist
   633   void deallocate(MetaWord* p, size_t word_size);
   635   // Based on the allocation size and a minimum chunk size,
   636   // returned chunk size (for expanding space for chunk allocation).
   637   size_t calc_chunk_size(size_t allocation_word_size);
   639   // Called when an allocation from the current chunk fails.
   640   // Gets a new chunk (may require getting a new virtual space),
   641   // and allocates from that chunk.
   642   MetaWord* grow_and_allocate(size_t word_size);
   644   // debugging support.
   646   void dump(outputStream* const out) const;
   647   void print_on(outputStream* st) const;
   648   void locked_print_chunks_in_use_on(outputStream* st) const;
   650   void verify();
   651   void verify_chunk_size(Metachunk* chunk);
   652   NOT_PRODUCT(void mangle_freed_chunks();)
   653 #ifdef ASSERT
   654   void verify_allocation_total();
   655 #endif
   656 };
   658 uint const SpaceManager::_small_chunk_limit = 4;
   660 const char* SpaceManager::_expand_lock_name =
   661   "SpaceManager chunk allocation lock";
   662 const int SpaceManager::_expand_lock_rank = Monitor::leaf - 1;
   663 Mutex* const SpaceManager::_expand_lock =
   664   new Mutex(SpaceManager::_expand_lock_rank,
   665             SpaceManager::_expand_lock_name,
   666             Mutex::_allow_vm_block_flag);
   668 // BlockFreelist methods
   670 BlockFreelist::BlockFreelist() : _dictionary(NULL) {}
   672 BlockFreelist::~BlockFreelist() {
   673   if (_dictionary != NULL) {
   674     if (Verbose && TraceMetadataChunkAllocation) {
   675       _dictionary->print_free_lists(gclog_or_tty);
   676     }
   677     delete _dictionary;
   678   }
   679 }
   681 Metablock* BlockFreelist::initialize_free_chunk(MetaWord* p, size_t word_size) {
   682   Metablock* block = (Metablock*) p;
   683   block->set_word_size(word_size);
   684   block->set_prev(NULL);
   685   block->set_next(NULL);
   687   return block;
   688 }
   690 void BlockFreelist::return_block(MetaWord* p, size_t word_size) {
   691   Metablock* free_chunk = initialize_free_chunk(p, word_size);
   692   if (dictionary() == NULL) {
   693    _dictionary = new BlockTreeDictionary();
   694   }
   695   dictionary()->return_chunk(free_chunk);
   696 }
   698 MetaWord* BlockFreelist::get_block(size_t word_size) {
   699   if (dictionary() == NULL) {
   700     return NULL;
   701   }
   703   if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
   704     // Dark matter.  Too small for dictionary.
   705     return NULL;
   706   }
   708   Metablock* free_block =
   709     dictionary()->get_chunk(word_size, FreeBlockDictionary<Metablock>::exactly);
   710   if (free_block == NULL) {
   711     return NULL;
   712   }
   714   return (MetaWord*) free_block;
   715 }
   717 void BlockFreelist::print_on(outputStream* st) const {
   718   if (dictionary() == NULL) {
   719     return;
   720   }
   721   dictionary()->print_free_lists(st);
   722 }
   724 // VirtualSpaceNode methods
   726 VirtualSpaceNode::~VirtualSpaceNode() {
   727   _rs.release();
   728 }
   730 size_t VirtualSpaceNode::used_words_in_vs() const {
   731   return pointer_delta(top(), bottom(), sizeof(MetaWord));
   732 }
   734 // Space committed in the VirtualSpace
   735 size_t VirtualSpaceNode::capacity_words_in_vs() const {
   736   return pointer_delta(end(), bottom(), sizeof(MetaWord));
   737 }
   740 // Allocates the chunk from the virtual space only.
   741 // This interface is also used internally for debugging.  Not all
   742 // chunks removed here are necessarily used for allocation.
   743 Metachunk* VirtualSpaceNode::take_from_committed(size_t chunk_word_size) {
   744   // Bottom of the new chunk
   745   MetaWord* chunk_limit = top();
   746   assert(chunk_limit != NULL, "Not safe to call this method");
   748   if (!is_available(chunk_word_size)) {
   749     if (TraceMetadataChunkAllocation) {
   750       tty->print("VirtualSpaceNode::take_from_committed() not available %d words ", chunk_word_size);
   751       // Dump some information about the virtual space that is nearly full
   752       print_on(tty);
   753     }
   754     return NULL;
   755   }
   757   // Take the space  (bump top on the current virtual space).
   758   inc_top(chunk_word_size);
   760   // Point the chunk at the space
   761   Metachunk* result = Metachunk::initialize(chunk_limit, chunk_word_size);
   762   return result;
   763 }
   766 // Expand the virtual space (commit more of the reserved space)
   767 bool VirtualSpaceNode::expand_by(size_t words, bool pre_touch) {
   768   size_t bytes = words * BytesPerWord;
   769   bool result =  virtual_space()->expand_by(bytes, pre_touch);
   770   if (TraceMetavirtualspaceAllocation && !result) {
   771     gclog_or_tty->print_cr("VirtualSpaceNode::expand_by() failed "
   772                            "for byte size " SIZE_FORMAT, bytes);
   773     virtual_space()->print();
   774   }
   775   return result;
   776 }
   778 // Shrink the virtual space (commit more of the reserved space)
   779 bool VirtualSpaceNode::shrink_by(size_t words) {
   780   size_t bytes = words * BytesPerWord;
   781   virtual_space()->shrink_by(bytes);
   782   return true;
   783 }
   785 // Add another chunk to the chunk list.
   787 Metachunk* VirtualSpaceNode::get_chunk_vs(size_t chunk_word_size) {
   788   assert_lock_strong(SpaceManager::expand_lock());
   789   Metachunk* result = NULL;
   791   return take_from_committed(chunk_word_size);
   792 }
   794 Metachunk* VirtualSpaceNode::get_chunk_vs_with_expand(size_t chunk_word_size) {
   795   assert_lock_strong(SpaceManager::expand_lock());
   797   Metachunk* new_chunk = get_chunk_vs(chunk_word_size);
   799   if (new_chunk == NULL) {
   800     // Only a small part of the virtualspace is committed when first
   801     // allocated so committing more here can be expected.
   802     size_t page_size_words = os::vm_page_size() / BytesPerWord;
   803     size_t aligned_expand_vs_by_words = align_size_up(chunk_word_size,
   804                                                     page_size_words);
   805     expand_by(aligned_expand_vs_by_words, false);
   806     new_chunk = get_chunk_vs(chunk_word_size);
   807   }
   808   return new_chunk;
   809 }
   811 bool VirtualSpaceNode::initialize() {
   813   if (!_rs.is_reserved()) {
   814     return false;
   815   }
   817   // An allocation out of this Virtualspace that is larger
   818   // than an initial commit size can waste that initial committed
   819   // space.
   820   size_t committed_byte_size = 0;
   821   bool result = virtual_space()->initialize(_rs, committed_byte_size);
   822   if (result) {
   823     set_top((MetaWord*)virtual_space()->low());
   824     set_reserved(MemRegion((HeapWord*)_rs.base(),
   825                  (HeapWord*)(_rs.base() + _rs.size())));
   827     assert(reserved()->start() == (HeapWord*) _rs.base(),
   828       err_msg("Reserved start was not set properly " PTR_FORMAT
   829         " != " PTR_FORMAT, reserved()->start(), _rs.base()));
   830     assert(reserved()->word_size() == _rs.size() / BytesPerWord,
   831       err_msg("Reserved size was not set properly " SIZE_FORMAT
   832         " != " SIZE_FORMAT, reserved()->word_size(),
   833         _rs.size() / BytesPerWord));
   834   }
   836   return result;
   837 }
   839 void VirtualSpaceNode::print_on(outputStream* st) const {
   840   size_t used = used_words_in_vs();
   841   size_t capacity = capacity_words_in_vs();
   842   VirtualSpace* vs = virtual_space();
   843   st->print_cr("   space @ " PTR_FORMAT " " SIZE_FORMAT "K, %3d%% used "
   844            "[" PTR_FORMAT ", " PTR_FORMAT ", "
   845            PTR_FORMAT ", " PTR_FORMAT ")",
   846            vs, capacity / K,
   847            capacity == 0 ? 0 : used * 100 / capacity,
   848            bottom(), top(), end(),
   849            vs->high_boundary());
   850 }
   852 #ifdef ASSERT
   853 void VirtualSpaceNode::mangle() {
   854   size_t word_size = capacity_words_in_vs();
   855   Copy::fill_to_words((HeapWord*) low(), word_size, 0xf1f1f1f1);
   856 }
   857 #endif // ASSERT
   859 // VirtualSpaceList methods
   860 // Space allocated from the VirtualSpace
   862 VirtualSpaceList::~VirtualSpaceList() {
   863   VirtualSpaceListIterator iter(virtual_space_list());
   864   while (iter.repeat()) {
   865     VirtualSpaceNode* vsl = iter.get_next();
   866     delete vsl;
   867   }
   868 }
   870 size_t VirtualSpaceList::used_words_sum() {
   871   size_t allocated_by_vs = 0;
   872   VirtualSpaceListIterator iter(virtual_space_list());
   873   while (iter.repeat()) {
   874     VirtualSpaceNode* vsl = iter.get_next();
   875     // Sum used region [bottom, top) in each virtualspace
   876     allocated_by_vs += vsl->used_words_in_vs();
   877   }
   878   assert(allocated_by_vs >= chunk_manager()->free_chunks_total(),
   879     err_msg("Total in free chunks " SIZE_FORMAT
   880             " greater than total from virtual_spaces " SIZE_FORMAT,
   881             allocated_by_vs, chunk_manager()->free_chunks_total()));
   882   size_t used =
   883     allocated_by_vs - chunk_manager()->free_chunks_total();
   884   return used;
   885 }
   887 // Space available in all MetadataVirtualspaces allocated
   888 // for metadata.  This is the upper limit on the capacity
   889 // of chunks allocated out of all the MetadataVirtualspaces.
   890 size_t VirtualSpaceList::capacity_words_sum() {
   891   size_t capacity = 0;
   892   VirtualSpaceListIterator iter(virtual_space_list());
   893   while (iter.repeat()) {
   894     VirtualSpaceNode* vsl = iter.get_next();
   895     capacity += vsl->capacity_words_in_vs();
   896   }
   897   return capacity;
   898 }
   900 VirtualSpaceList::VirtualSpaceList(size_t word_size ) :
   901                                    _is_class(false),
   902                                    _virtual_space_list(NULL),
   903                                    _current_virtual_space(NULL),
   904                                    _virtual_space_total(0),
   905                                    _virtual_space_count(0) {
   906   MutexLockerEx cl(SpaceManager::expand_lock(),
   907                    Mutex::_no_safepoint_check_flag);
   908   bool initialization_succeeded = grow_vs(word_size);
   910   assert(initialization_succeeded,
   911     " VirtualSpaceList initialization should not fail");
   912 }
   914 VirtualSpaceList::VirtualSpaceList(ReservedSpace rs) :
   915                                    _is_class(true),
   916                                    _virtual_space_list(NULL),
   917                                    _current_virtual_space(NULL),
   918                                    _virtual_space_total(0),
   919                                    _virtual_space_count(0) {
   920   MutexLockerEx cl(SpaceManager::expand_lock(),
   921                    Mutex::_no_safepoint_check_flag);
   922   VirtualSpaceNode* class_entry = new VirtualSpaceNode(rs);
   923   bool succeeded = class_entry->initialize();
   924   assert(succeeded, " VirtualSpaceList initialization should not fail");
   925   link_vs(class_entry, rs.size()/BytesPerWord);
   926 }
   928 // Allocate another meta virtual space and add it to the list.
   929 bool VirtualSpaceList::grow_vs(size_t vs_word_size) {
   930   assert_lock_strong(SpaceManager::expand_lock());
   931   if (vs_word_size == 0) {
   932     return false;
   933   }
   934   // Reserve the space
   935   size_t vs_byte_size = vs_word_size * BytesPerWord;
   936   assert(vs_byte_size % os::vm_page_size() == 0, "Not aligned");
   938   // Allocate the meta virtual space and initialize it.
   939   VirtualSpaceNode* new_entry = new VirtualSpaceNode(vs_byte_size);
   940   if (!new_entry->initialize()) {
   941     delete new_entry;
   942     return false;
   943   } else {
   944     // ensure lock-free iteration sees fully initialized node
   945     OrderAccess::storestore();
   946     link_vs(new_entry, vs_word_size);
   947     return true;
   948   }
   949 }
   951 void VirtualSpaceList::link_vs(VirtualSpaceNode* new_entry, size_t vs_word_size) {
   952   if (virtual_space_list() == NULL) {
   953       set_virtual_space_list(new_entry);
   954   } else {
   955     current_virtual_space()->set_next(new_entry);
   956   }
   957   set_current_virtual_space(new_entry);
   958   inc_virtual_space_total(vs_word_size);
   959   inc_virtual_space_count();
   960 #ifdef ASSERT
   961   new_entry->mangle();
   962 #endif
   963   if (TraceMetavirtualspaceAllocation && Verbose) {
   964     VirtualSpaceNode* vsl = current_virtual_space();
   965     vsl->print_on(tty);
   966   }
   967 }
   969 Metachunk* VirtualSpaceList::get_new_chunk(size_t word_size,
   970                                            size_t grow_chunks_by_words,
   971                                            size_t medium_chunk_bunch) {
   973   // Get a chunk from the chunk freelist
   974   Metachunk* next = chunk_manager()->chunk_freelist_allocate(grow_chunks_by_words);
   976   // Allocate a chunk out of the current virtual space.
   977   if (next == NULL) {
   978     next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
   979   }
   981   if (next == NULL) {
   982     // Not enough room in current virtual space.  Try to commit
   983     // more space.
   984     size_t expand_vs_by_words = MAX2(medium_chunk_bunch,
   985                                      grow_chunks_by_words);
   986     size_t page_size_words = os::vm_page_size() / BytesPerWord;
   987     size_t aligned_expand_vs_by_words = align_size_up(expand_vs_by_words,
   988                                                         page_size_words);
   989     bool vs_expanded =
   990       current_virtual_space()->expand_by(aligned_expand_vs_by_words, false);
   991     if (!vs_expanded) {
   992       // Should the capacity of the metaspaces be expanded for
   993       // this allocation?  If it's the virtual space for classes and is
   994       // being used for CompressedHeaders, don't allocate a new virtualspace.
   995       if (can_grow() && MetaspaceGC::should_expand(this, word_size)) {
   996         // Get another virtual space.
   997           size_t grow_vs_words =
   998             MAX2((size_t)VirtualSpaceSize, aligned_expand_vs_by_words);
   999         if (grow_vs(grow_vs_words)) {
  1000           // Got it.  It's on the list now.  Get a chunk from it.
  1001           next = current_virtual_space()->get_chunk_vs_with_expand(grow_chunks_by_words);
  1003       } else {
  1004         // Allocation will fail and induce a GC
  1005         if (TraceMetadataChunkAllocation && Verbose) {
  1006           gclog_or_tty->print_cr("VirtualSpaceList::get_new_chunk():"
  1007             " Fail instead of expand the metaspace");
  1010     } else {
  1011       // The virtual space expanded, get a new chunk
  1012       next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
  1013       assert(next != NULL, "Just expanded, should succeed");
  1017   assert(next == NULL || (next->next() == NULL && next->prev() == NULL),
  1018          "New chunk is still on some list");
  1019   return next;
  1022 Metachunk* VirtualSpaceList::get_initialization_chunk(size_t chunk_word_size,
  1023                                                       size_t chunk_bunch) {
  1024   // Get a chunk from the chunk freelist
  1025   Metachunk* new_chunk = get_new_chunk(chunk_word_size,
  1026                                        chunk_word_size,
  1027                                        chunk_bunch);
  1028   return new_chunk;
  1031 void VirtualSpaceList::print_on(outputStream* st) const {
  1032   if (TraceMetadataChunkAllocation && Verbose) {
  1033     VirtualSpaceListIterator iter(virtual_space_list());
  1034     while (iter.repeat()) {
  1035       VirtualSpaceNode* node = iter.get_next();
  1036       node->print_on(st);
  1041 bool VirtualSpaceList::contains(const void *ptr) {
  1042   VirtualSpaceNode* list = virtual_space_list();
  1043   VirtualSpaceListIterator iter(list);
  1044   while (iter.repeat()) {
  1045     VirtualSpaceNode* node = iter.get_next();
  1046     if (node->reserved()->contains(ptr)) {
  1047       return true;
  1050   return false;
  1054 // MetaspaceGC methods
  1056 // VM_CollectForMetadataAllocation is the vm operation used to GC.
  1057 // Within the VM operation after the GC the attempt to allocate the metadata
  1058 // should succeed.  If the GC did not free enough space for the metaspace
  1059 // allocation, the HWM is increased so that another virtualspace will be
  1060 // allocated for the metadata.  With perm gen the increase in the perm
  1061 // gen had bounds, MinMetaspaceExpansion and MaxMetaspaceExpansion.  The
  1062 // metaspace policy uses those as the small and large steps for the HWM.
  1063 //
  1064 // After the GC the compute_new_size() for MetaspaceGC is called to
  1065 // resize the capacity of the metaspaces.  The current implementation
  1066 // is based on the flags MinMetaspaceFreeRatio and MaxHeapFreeRatio used
  1067 // to resize the Java heap by some GC's.  New flags can be implemented
  1068 // if really needed.  MinHeapFreeRatio is used to calculate how much
  1069 // free space is desirable in the metaspace capacity to decide how much
  1070 // to increase the HWM.  MaxMetaspaceFreeRatio is used to decide how much
  1071 // free space is desirable in the metaspace capacity before decreasing
  1072 // the HWM.
  1074 // Calculate the amount to increase the high water mark (HWM).
  1075 // Increase by a minimum amount (MinMetaspaceExpansion) so that
  1076 // another expansion is not requested too soon.  If that is not
  1077 // enough to satisfy the allocation (i.e. big enough for a word_size
  1078 // allocation), increase by MaxMetaspaceExpansion.  If that is still
  1079 // not enough, expand by the size of the allocation (word_size) plus
  1080 // some.
  1081 size_t MetaspaceGC::delta_capacity_until_GC(size_t word_size) {
  1082   size_t before_inc = MetaspaceGC::capacity_until_GC();
  1083   size_t min_delta_words = MinMetaspaceExpansion / BytesPerWord;
  1084   size_t max_delta_words = MaxMetaspaceExpansion / BytesPerWord;
  1085   size_t page_size_words = os::vm_page_size() / BytesPerWord;
  1086   size_t size_delta_words = align_size_up(word_size, page_size_words);
  1087   size_t delta_words = MAX2(size_delta_words, min_delta_words);
  1088   if (delta_words > min_delta_words) {
  1089     // Don't want to hit the high water mark on the next
  1090     // allocation so make the delta greater than just enough
  1091     // for this allocation.
  1092     delta_words = MAX2(delta_words, max_delta_words);
  1093     if (delta_words > max_delta_words) {
  1094       // This allocation is large but the next ones are probably not
  1095       // so increase by the minimum.
  1096       delta_words = delta_words + min_delta_words;
  1099   return delta_words;
  1102 bool MetaspaceGC::should_expand(VirtualSpaceList* vsl, size_t word_size) {
  1103   // If the user wants a limit, impose one.
  1104   if (!FLAG_IS_DEFAULT(MaxMetaspaceSize) &&
  1105       MetaspaceAux::reserved_in_bytes() >= MaxMetaspaceSize) {
  1106     return false;
  1109   // Class virtual space should always be expanded.  Call GC for the other
  1110   // metadata virtual space.
  1111   if (vsl == Metaspace::class_space_list()) return true;
  1113   // If this is part of an allocation after a GC, expand
  1114   // unconditionally.
  1115   if(MetaspaceGC::expand_after_GC()) {
  1116     return true;
  1119   size_t metaspace_size_words = MetaspaceSize / BytesPerWord;
  1121   // If the capacity is below the minimum capacity, allow the
  1122   // expansion.  Also set the high-water-mark (capacity_until_GC)
  1123   // to that minimum capacity so that a GC will not be induced
  1124   // until that minimum capacity is exceeded.
  1125   if (vsl->capacity_words_sum() < metaspace_size_words ||
  1126       capacity_until_GC() == 0) {
  1127     set_capacity_until_GC(metaspace_size_words);
  1128     return true;
  1129   } else {
  1130     if (vsl->capacity_words_sum() < capacity_until_GC()) {
  1131       return true;
  1132     } else {
  1133       if (TraceMetadataChunkAllocation && Verbose) {
  1134         gclog_or_tty->print_cr("  allocation request size " SIZE_FORMAT
  1135                         "  capacity_until_GC " SIZE_FORMAT
  1136                         "  capacity_words_sum " SIZE_FORMAT
  1137                         "  used_words_sum " SIZE_FORMAT
  1138                         "  free chunks " SIZE_FORMAT
  1139                         "  free chunks count %d",
  1140                         word_size,
  1141                         capacity_until_GC(),
  1142                         vsl->capacity_words_sum(),
  1143                         vsl->used_words_sum(),
  1144                         vsl->chunk_manager()->free_chunks_total(),
  1145                         vsl->chunk_manager()->free_chunks_count());
  1147       return false;
  1152 // Variables are in bytes
  1154 void MetaspaceGC::compute_new_size() {
  1155   assert(_shrink_factor <= 100, "invalid shrink factor");
  1156   uint current_shrink_factor = _shrink_factor;
  1157   _shrink_factor = 0;
  1159   VirtualSpaceList *vsl = Metaspace::space_list();
  1161   size_t capacity_after_gc = vsl->capacity_bytes_sum();
  1162   // Check to see if these two can be calculated without walking the CLDG
  1163   size_t used_after_gc = vsl->used_bytes_sum();
  1164   size_t capacity_until_GC = vsl->capacity_bytes_sum();
  1165   size_t free_after_gc = capacity_until_GC - used_after_gc;
  1167   const double minimum_free_percentage = MinMetaspaceFreeRatio / 100.0;
  1168   const double maximum_used_percentage = 1.0 - minimum_free_percentage;
  1170   const double min_tmp = used_after_gc / maximum_used_percentage;
  1171   size_t minimum_desired_capacity =
  1172     (size_t)MIN2(min_tmp, double(max_uintx));
  1173   // Don't shrink less than the initial generation size
  1174   minimum_desired_capacity = MAX2(minimum_desired_capacity,
  1175                                   MetaspaceSize);
  1177   if (PrintGCDetails && Verbose) {
  1178     const double free_percentage = ((double)free_after_gc) / capacity_until_GC;
  1179     gclog_or_tty->print_cr("\nMetaspaceGC::compute_new_size: ");
  1180     gclog_or_tty->print_cr("  "
  1181                   "  minimum_free_percentage: %6.2f"
  1182                   "  maximum_used_percentage: %6.2f",
  1183                   minimum_free_percentage,
  1184                   maximum_used_percentage);
  1185     double d_free_after_gc = free_after_gc / (double) K;
  1186     gclog_or_tty->print_cr("  "
  1187                   "   free_after_gc       : %6.1fK"
  1188                   "   used_after_gc       : %6.1fK"
  1189                   "   capacity_after_gc   : %6.1fK"
  1190                   "   metaspace HWM     : %6.1fK",
  1191                   free_after_gc / (double) K,
  1192                   used_after_gc / (double) K,
  1193                   capacity_after_gc / (double) K,
  1194                   capacity_until_GC / (double) K);
  1195     gclog_or_tty->print_cr("  "
  1196                   "   free_percentage: %6.2f",
  1197                   free_percentage);
  1201   if (capacity_until_GC < minimum_desired_capacity) {
  1202     // If we have less capacity below the metaspace HWM, then
  1203     // increment the HWM.
  1204     size_t expand_bytes = minimum_desired_capacity - capacity_until_GC;
  1205     // Don't expand unless it's significant
  1206     if (expand_bytes >= MinMetaspaceExpansion) {
  1207       size_t expand_words = expand_bytes / BytesPerWord;
  1208       MetaspaceGC::inc_capacity_until_GC(expand_words);
  1210     if (PrintGCDetails && Verbose) {
  1211       size_t new_capacity_until_GC = MetaspaceGC::capacity_until_GC_in_bytes();
  1212       gclog_or_tty->print_cr("    expanding:"
  1213                     "  minimum_desired_capacity: %6.1fK"
  1214                     "  expand_words: %6.1fK"
  1215                     "  MinMetaspaceExpansion: %6.1fK"
  1216                     "  new metaspace HWM:  %6.1fK",
  1217                     minimum_desired_capacity / (double) K,
  1218                     expand_bytes / (double) K,
  1219                     MinMetaspaceExpansion / (double) K,
  1220                     new_capacity_until_GC / (double) K);
  1222     return;
  1225   // No expansion, now see if we want to shrink
  1226   size_t shrink_words = 0;
  1227   // We would never want to shrink more than this
  1228   size_t max_shrink_words = capacity_until_GC - minimum_desired_capacity;
  1229   assert(max_shrink_words >= 0, err_msg("max_shrink_words " SIZE_FORMAT,
  1230     max_shrink_words));
  1232   // Should shrinking be considered?
  1233   if (MaxMetaspaceFreeRatio < 100) {
  1234     const double maximum_free_percentage = MaxMetaspaceFreeRatio / 100.0;
  1235     const double minimum_used_percentage = 1.0 - maximum_free_percentage;
  1236     const double max_tmp = used_after_gc / minimum_used_percentage;
  1237     size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(max_uintx));
  1238     maximum_desired_capacity = MAX2(maximum_desired_capacity,
  1239                                     MetaspaceSize);
  1240     if (PrintGC && Verbose) {
  1241       gclog_or_tty->print_cr("  "
  1242                              "  maximum_free_percentage: %6.2f"
  1243                              "  minimum_used_percentage: %6.2f",
  1244                              maximum_free_percentage,
  1245                              minimum_used_percentage);
  1246       gclog_or_tty->print_cr("  "
  1247                              "  capacity_until_GC: %6.1fK"
  1248                              "  minimum_desired_capacity: %6.1fK"
  1249                              "  maximum_desired_capacity: %6.1fK",
  1250                              capacity_until_GC / (double) K,
  1251                              minimum_desired_capacity / (double) K,
  1252                              maximum_desired_capacity / (double) K);
  1255     assert(minimum_desired_capacity <= maximum_desired_capacity,
  1256            "sanity check");
  1258     if (capacity_until_GC > maximum_desired_capacity) {
  1259       // Capacity too large, compute shrinking size
  1260       shrink_words = capacity_until_GC - maximum_desired_capacity;
  1261       // We don't want shrink all the way back to initSize if people call
  1262       // System.gc(), because some programs do that between "phases" and then
  1263       // we'd just have to grow the heap up again for the next phase.  So we
  1264       // damp the shrinking: 0% on the first call, 10% on the second call, 40%
  1265       // on the third call, and 100% by the fourth call.  But if we recompute
  1266       // size without shrinking, it goes back to 0%.
  1267       shrink_words = shrink_words / 100 * current_shrink_factor;
  1268       assert(shrink_words <= max_shrink_words,
  1269         err_msg("invalid shrink size " SIZE_FORMAT " not <= " SIZE_FORMAT,
  1270           shrink_words, max_shrink_words));
  1271       if (current_shrink_factor == 0) {
  1272         _shrink_factor = 10;
  1273       } else {
  1274         _shrink_factor = MIN2(current_shrink_factor * 4, (uint) 100);
  1276       if (PrintGCDetails && Verbose) {
  1277         gclog_or_tty->print_cr("  "
  1278                       "  shrinking:"
  1279                       "  initSize: %.1fK"
  1280                       "  maximum_desired_capacity: %.1fK",
  1281                       MetaspaceSize / (double) K,
  1282                       maximum_desired_capacity / (double) K);
  1283         gclog_or_tty->print_cr("  "
  1284                       "  shrink_words: %.1fK"
  1285                       "  current_shrink_factor: %d"
  1286                       "  new shrink factor: %d"
  1287                       "  MinMetaspaceExpansion: %.1fK",
  1288                       shrink_words / (double) K,
  1289                       current_shrink_factor,
  1290                       _shrink_factor,
  1291                       MinMetaspaceExpansion / (double) K);
  1297   // Don't shrink unless it's significant
  1298   if (shrink_words >= MinMetaspaceExpansion) {
  1299     VirtualSpaceNode* csp = vsl->current_virtual_space();
  1300     size_t available_to_shrink = csp->capacity_words_in_vs() -
  1301       csp->used_words_in_vs();
  1302     shrink_words = MIN2(shrink_words, available_to_shrink);
  1303     csp->shrink_by(shrink_words);
  1304     MetaspaceGC::dec_capacity_until_GC(shrink_words);
  1305     if (PrintGCDetails && Verbose) {
  1306       size_t new_capacity_until_GC = MetaspaceGC::capacity_until_GC_in_bytes();
  1307       gclog_or_tty->print_cr("  metaspace HWM: %.1fK", new_capacity_until_GC / (double) K);
  1310   assert(used_after_gc <= vsl->capacity_bytes_sum(),
  1311          "sanity check");
  1315 // Metadebug methods
  1317 void Metadebug::deallocate_chunk_a_lot(SpaceManager* sm,
  1318                                        size_t chunk_word_size){
  1319 #ifdef ASSERT
  1320   VirtualSpaceList* vsl = sm->vs_list();
  1321   if (MetaDataDeallocateALot &&
  1322       Metadebug::deallocate_chunk_a_lot_count() % MetaDataDeallocateALotInterval == 0 ) {
  1323     Metadebug::reset_deallocate_chunk_a_lot_count();
  1324     for (uint i = 0; i < metadata_deallocate_a_lock_chunk; i++) {
  1325       Metachunk* dummy_chunk = vsl->current_virtual_space()->take_from_committed(chunk_word_size);
  1326       if (dummy_chunk == NULL) {
  1327         break;
  1329       vsl->chunk_manager()->chunk_freelist_deallocate(dummy_chunk);
  1331       if (TraceMetadataChunkAllocation && Verbose) {
  1332         gclog_or_tty->print("Metadebug::deallocate_chunk_a_lot: %d) ",
  1333                                sm->sum_count_in_chunks_in_use());
  1334         dummy_chunk->print_on(gclog_or_tty);
  1335         gclog_or_tty->print_cr("  Free chunks total %d  count %d",
  1336                                vsl->chunk_manager()->free_chunks_total(),
  1337                                vsl->chunk_manager()->free_chunks_count());
  1340   } else {
  1341     Metadebug::inc_deallocate_chunk_a_lot_count();
  1343 #endif
  1346 void Metadebug::deallocate_block_a_lot(SpaceManager* sm,
  1347                                        size_t raw_word_size){
  1348 #ifdef ASSERT
  1349   if (MetaDataDeallocateALot &&
  1350         Metadebug::deallocate_block_a_lot_count() % MetaDataDeallocateALotInterval == 0 ) {
  1351     Metadebug::set_deallocate_block_a_lot_count(0);
  1352     for (uint i = 0; i < metadata_deallocate_a_lot_block; i++) {
  1353       MetaWord* dummy_block = sm->allocate_work(raw_word_size);
  1354       if (dummy_block == 0) {
  1355         break;
  1357       sm->deallocate(dummy_block, raw_word_size);
  1359   } else {
  1360     Metadebug::inc_deallocate_block_a_lot_count();
  1362 #endif
  1365 void Metadebug::init_allocation_fail_alot_count() {
  1366   if (MetadataAllocationFailALot) {
  1367     _allocation_fail_alot_count =
  1368       1+(long)((double)MetadataAllocationFailALotInterval*os::random()/(max_jint+1.0));
  1372 #ifdef ASSERT
  1373 bool Metadebug::test_metadata_failure() {
  1374   if (MetadataAllocationFailALot &&
  1375       Threads::is_vm_complete()) {
  1376     if (_allocation_fail_alot_count > 0) {
  1377       _allocation_fail_alot_count--;
  1378     } else {
  1379       if (TraceMetadataChunkAllocation && Verbose) {
  1380         gclog_or_tty->print_cr("Metadata allocation failing for "
  1381                                "MetadataAllocationFailALot");
  1383       init_allocation_fail_alot_count();
  1384       return true;
  1387   return false;
  1389 #endif
  1391 // ChunkList methods
  1393 size_t ChunkList::sum_list_size() {
  1394   size_t result = 0;
  1395   Metachunk* cur = head();
  1396   while (cur != NULL) {
  1397     result += cur->word_size();
  1398     cur = cur->next();
  1400   return result;
  1403 size_t ChunkList::sum_list_count() {
  1404   size_t result = 0;
  1405   Metachunk* cur = head();
  1406   while (cur != NULL) {
  1407     result++;
  1408     cur = cur->next();
  1410   return result;
  1413 size_t ChunkList::sum_list_capacity() {
  1414   size_t result = 0;
  1415   Metachunk* cur = head();
  1416   while (cur != NULL) {
  1417     result += cur->capacity_word_size();
  1418     cur = cur->next();
  1420   return result;
  1423 void ChunkList::add_at_head(Metachunk* head, Metachunk* tail) {
  1424   assert_lock_strong(SpaceManager::expand_lock());
  1425   assert(head == tail || tail->next() == NULL,
  1426          "Not the tail or the head has already been added to a list");
  1428   if (TraceMetadataChunkAllocation && Verbose) {
  1429     gclog_or_tty->print("ChunkList::add_at_head(head, tail): ");
  1430     Metachunk* cur = head;
  1431     while (cur != NULL) {
  1432       gclog_or_tty->print(PTR_FORMAT " (" SIZE_FORMAT ") ", cur, cur->word_size());
  1433       cur = cur->next();
  1435     gclog_or_tty->print_cr("");
  1438   if (tail != NULL) {
  1439     tail->set_next(_head);
  1441   set_head(head);
  1444 void ChunkList::add_at_head(Metachunk* list) {
  1445   if (list == NULL) {
  1446     // Nothing to add
  1447     return;
  1449   assert_lock_strong(SpaceManager::expand_lock());
  1450   Metachunk* head = list;
  1451   Metachunk* tail = list;
  1452   Metachunk* cur = head->next();
  1453   // Search for the tail since it is not passed.
  1454   while (cur != NULL) {
  1455     tail = cur;
  1456     cur = cur->next();
  1458   add_at_head(head, tail);
  1461 // ChunkManager methods
  1463 // Verification of _free_chunks_total and _free_chunks_count does not
  1464 // work with the CMS collector because its use of additional locks
  1465 // complicate the mutex deadlock detection but it can still be useful
  1466 // for detecting errors in the chunk accounting with other collectors.
  1468 size_t ChunkManager::free_chunks_total() {
  1469 #ifdef ASSERT
  1470   if (!UseConcMarkSweepGC && !SpaceManager::expand_lock()->is_locked()) {
  1471     MutexLockerEx cl(SpaceManager::expand_lock(),
  1472                      Mutex::_no_safepoint_check_flag);
  1473     slow_locked_verify_free_chunks_total();
  1475 #endif
  1476   return _free_chunks_total;
  1479 size_t ChunkManager::free_chunks_total_in_bytes() {
  1480   return free_chunks_total() * BytesPerWord;
  1483 size_t ChunkManager::free_chunks_count() {
  1484 #ifdef ASSERT
  1485   if (!UseConcMarkSweepGC && !SpaceManager::expand_lock()->is_locked()) {
  1486     MutexLockerEx cl(SpaceManager::expand_lock(),
  1487                      Mutex::_no_safepoint_check_flag);
  1488     // This lock is only needed in debug because the verification
  1489     // of the _free_chunks_totals walks the list of free chunks
  1490     slow_locked_verify_free_chunks_count();
  1492 #endif
  1493   return _free_chunks_count;
  1496 void ChunkManager::locked_verify_free_chunks_total() {
  1497   assert_lock_strong(SpaceManager::expand_lock());
  1498   assert(sum_free_chunks() == _free_chunks_total,
  1499     err_msg("_free_chunks_total " SIZE_FORMAT " is not the"
  1500            " same as sum " SIZE_FORMAT, _free_chunks_total,
  1501            sum_free_chunks()));
  1504 void ChunkManager::verify_free_chunks_total() {
  1505   MutexLockerEx cl(SpaceManager::expand_lock(),
  1506                      Mutex::_no_safepoint_check_flag);
  1507   locked_verify_free_chunks_total();
  1510 void ChunkManager::locked_verify_free_chunks_count() {
  1511   assert_lock_strong(SpaceManager::expand_lock());
  1512   assert(sum_free_chunks_count() == _free_chunks_count,
  1513     err_msg("_free_chunks_count " SIZE_FORMAT " is not the"
  1514            " same as sum " SIZE_FORMAT, _free_chunks_count,
  1515            sum_free_chunks_count()));
  1518 void ChunkManager::verify_free_chunks_count() {
  1519 #ifdef ASSERT
  1520   MutexLockerEx cl(SpaceManager::expand_lock(),
  1521                      Mutex::_no_safepoint_check_flag);
  1522   locked_verify_free_chunks_count();
  1523 #endif
  1526 void ChunkManager::verify() {
  1527   MutexLockerEx cl(SpaceManager::expand_lock(),
  1528                      Mutex::_no_safepoint_check_flag);
  1529   locked_verify();
  1532 void ChunkManager::locked_verify() {
  1533   locked_verify_free_chunks_count();
  1534   locked_verify_free_chunks_total();
  1537 void ChunkManager::locked_print_free_chunks(outputStream* st) {
  1538   assert_lock_strong(SpaceManager::expand_lock());
  1539   st->print_cr("Free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
  1540                 _free_chunks_total, _free_chunks_count);
  1543 void ChunkManager::locked_print_sum_free_chunks(outputStream* st) {
  1544   assert_lock_strong(SpaceManager::expand_lock());
  1545   st->print_cr("Sum free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
  1546                 sum_free_chunks(), sum_free_chunks_count());
  1548 ChunkList* ChunkManager::free_chunks(ChunkIndex index) {
  1549   return &_free_chunks[index];
  1552 // These methods that sum the free chunk lists are used in printing
  1553 // methods that are used in product builds.
  1554 size_t ChunkManager::sum_free_chunks() {
  1555   assert_lock_strong(SpaceManager::expand_lock());
  1556   size_t result = 0;
  1557   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
  1558     ChunkList* list = free_chunks(i);
  1560     if (list == NULL) {
  1561       continue;
  1564     result = result + list->sum_list_capacity();
  1566   result = result + humongous_dictionary()->total_size();
  1567   return result;
  1570 size_t ChunkManager::sum_free_chunks_count() {
  1571   assert_lock_strong(SpaceManager::expand_lock());
  1572   size_t count = 0;
  1573   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
  1574     ChunkList* list = free_chunks(i);
  1575     if (list == NULL) {
  1576       continue;
  1578     count = count + list->sum_list_count();
  1580   count = count + humongous_dictionary()->total_free_blocks();
  1581   return count;
  1584 ChunkList* ChunkManager::find_free_chunks_list(size_t word_size) {
  1585   ChunkIndex index = list_index(word_size);
  1586   assert(index < HumongousIndex, "No humongous list");
  1587   return free_chunks(index);
  1590 void ChunkManager::free_chunks_put(Metachunk* chunk) {
  1591   assert_lock_strong(SpaceManager::expand_lock());
  1592   ChunkList* free_list = find_free_chunks_list(chunk->word_size());
  1593   chunk->set_next(free_list->head());
  1594   free_list->set_head(chunk);
  1595   // chunk is being returned to the chunk free list
  1596   inc_free_chunks_total(chunk->capacity_word_size());
  1597   slow_locked_verify();
  1600 void ChunkManager::chunk_freelist_deallocate(Metachunk* chunk) {
  1601   // The deallocation of a chunk originates in the freelist
  1602   // manangement code for a Metaspace and does not hold the
  1603   // lock.
  1604   assert(chunk != NULL, "Deallocating NULL");
  1605   assert_lock_strong(SpaceManager::expand_lock());
  1606   slow_locked_verify();
  1607   if (TraceMetadataChunkAllocation) {
  1608     tty->print_cr("ChunkManager::chunk_freelist_deallocate: chunk "
  1609                   PTR_FORMAT "  size " SIZE_FORMAT,
  1610                   chunk, chunk->word_size());
  1612   free_chunks_put(chunk);
  1615 Metachunk* ChunkManager::free_chunks_get(size_t word_size) {
  1616   assert_lock_strong(SpaceManager::expand_lock());
  1618   slow_locked_verify();
  1620   Metachunk* chunk = NULL;
  1621   if (list_index(word_size) != HumongousIndex) {
  1622     ChunkList* free_list = find_free_chunks_list(word_size);
  1623     assert(free_list != NULL, "Sanity check");
  1625     chunk = free_list->head();
  1626     debug_only(Metachunk* debug_head = chunk;)
  1628     if (chunk == NULL) {
  1629       return NULL;
  1632     // Remove the chunk as the head of the list.
  1633     free_list->set_head(chunk->next());
  1635     // Chunk is being removed from the chunks free list.
  1636     dec_free_chunks_total(chunk->capacity_word_size());
  1638     if (TraceMetadataChunkAllocation && Verbose) {
  1639       tty->print_cr("ChunkManager::free_chunks_get: free_list "
  1640                     PTR_FORMAT " head " PTR_FORMAT " size " SIZE_FORMAT,
  1641                     free_list, chunk, chunk->word_size());
  1643   } else {
  1644     chunk = humongous_dictionary()->get_chunk(
  1645       word_size,
  1646       FreeBlockDictionary<Metachunk>::atLeast);
  1648     if (chunk != NULL) {
  1649       if (TraceMetadataHumongousAllocation) {
  1650         size_t waste = chunk->word_size() - word_size;
  1651         tty->print_cr("Free list allocate humongous chunk size " SIZE_FORMAT
  1652                       " for requested size " SIZE_FORMAT
  1653                       " waste " SIZE_FORMAT,
  1654                       chunk->word_size(), word_size, waste);
  1656       // Chunk is being removed from the chunks free list.
  1657       dec_free_chunks_total(chunk->capacity_word_size());
  1658 #ifdef ASSERT
  1659       chunk->set_is_free(false);
  1660 #endif
  1661     } else {
  1662       return NULL;
  1666   // Remove it from the links to this freelist
  1667   chunk->set_next(NULL);
  1668   chunk->set_prev(NULL);
  1669   slow_locked_verify();
  1670   return chunk;
  1673 Metachunk* ChunkManager::chunk_freelist_allocate(size_t word_size) {
  1674   assert_lock_strong(SpaceManager::expand_lock());
  1675   slow_locked_verify();
  1677   // Take from the beginning of the list
  1678   Metachunk* chunk = free_chunks_get(word_size);
  1679   if (chunk == NULL) {
  1680     return NULL;
  1683   assert((word_size <= chunk->word_size()) ||
  1684          list_index(chunk->word_size() == HumongousIndex),
  1685          "Non-humongous variable sized chunk");
  1686   if (TraceMetadataChunkAllocation) {
  1687     size_t list_count;
  1688     if (list_index(word_size) < HumongousIndex) {
  1689       ChunkList* list = find_free_chunks_list(word_size);
  1690       list_count = list->sum_list_count();
  1691     } else {
  1692       list_count = humongous_dictionary()->total_count();
  1694     tty->print("ChunkManager::chunk_freelist_allocate: " PTR_FORMAT " chunk "
  1695                PTR_FORMAT "  size " SIZE_FORMAT " count " SIZE_FORMAT " ",
  1696                this, chunk, chunk->word_size(), list_count);
  1697     locked_print_free_chunks(tty);
  1700   return chunk;
  1703 void ChunkManager::print_on(outputStream* out) {
  1704   if (PrintFLSStatistics != 0) {
  1705     humongous_dictionary()->report_statistics();
  1709 // SpaceManager methods
  1711 void SpaceManager::get_initial_chunk_sizes(Metaspace::MetaspaceType type,
  1712                                            size_t* chunk_word_size,
  1713                                            size_t* class_chunk_word_size) {
  1714   switch (type) {
  1715   case Metaspace::BootMetaspaceType:
  1716     *chunk_word_size = Metaspace::first_chunk_word_size();
  1717     *class_chunk_word_size = Metaspace::first_class_chunk_word_size();
  1718     break;
  1719   case Metaspace::ROMetaspaceType:
  1720     *chunk_word_size = SharedReadOnlySize / wordSize;
  1721     *class_chunk_word_size = ClassSpecializedChunk;
  1722     break;
  1723   case Metaspace::ReadWriteMetaspaceType:
  1724     *chunk_word_size = SharedReadWriteSize / wordSize;
  1725     *class_chunk_word_size = ClassSpecializedChunk;
  1726     break;
  1727   case Metaspace::AnonymousMetaspaceType:
  1728   case Metaspace::ReflectionMetaspaceType:
  1729     *chunk_word_size = SpecializedChunk;
  1730     *class_chunk_word_size = ClassSpecializedChunk;
  1731     break;
  1732   default:
  1733     *chunk_word_size = SmallChunk;
  1734     *class_chunk_word_size = ClassSmallChunk;
  1735     break;
  1737   assert(*chunk_word_size != 0 && *class_chunk_word_size != 0,
  1738     err_msg("Initial chunks sizes bad: data  " SIZE_FORMAT
  1739             " class " SIZE_FORMAT,
  1740             *chunk_word_size, *class_chunk_word_size));
  1743 size_t SpaceManager::sum_free_in_chunks_in_use() const {
  1744   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1745   size_t free = 0;
  1746   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1747     Metachunk* chunk = chunks_in_use(i);
  1748     while (chunk != NULL) {
  1749       free += chunk->free_word_size();
  1750       chunk = chunk->next();
  1753   return free;
  1756 size_t SpaceManager::sum_waste_in_chunks_in_use() const {
  1757   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1758   size_t result = 0;
  1759   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1760    result += sum_waste_in_chunks_in_use(i);
  1763   return result;
  1766 size_t SpaceManager::sum_waste_in_chunks_in_use(ChunkIndex index) const {
  1767   size_t result = 0;
  1768   Metachunk* chunk = chunks_in_use(index);
  1769   // Count the free space in all the chunk but not the
  1770   // current chunk from which allocations are still being done.
  1771   if (chunk != NULL) {
  1772     Metachunk* prev = chunk;
  1773     while (chunk != NULL && chunk != current_chunk()) {
  1774       result += chunk->free_word_size();
  1775       prev = chunk;
  1776       chunk = chunk->next();
  1779   return result;
  1782 size_t SpaceManager::sum_capacity_in_chunks_in_use() const {
  1783   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1784   size_t sum = 0;
  1785   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1786     Metachunk* chunk = chunks_in_use(i);
  1787     while (chunk != NULL) {
  1788       // Just changed this sum += chunk->capacity_word_size();
  1789       // sum += chunk->word_size() - Metachunk::overhead();
  1790       sum += chunk->capacity_word_size();
  1791       chunk = chunk->next();
  1794   return sum;
  1797 size_t SpaceManager::sum_count_in_chunks_in_use() {
  1798   size_t count = 0;
  1799   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1800     count = count + sum_count_in_chunks_in_use(i);
  1803   return count;
  1806 size_t SpaceManager::sum_count_in_chunks_in_use(ChunkIndex i) {
  1807   size_t count = 0;
  1808   Metachunk* chunk = chunks_in_use(i);
  1809   while (chunk != NULL) {
  1810     count++;
  1811     chunk = chunk->next();
  1813   return count;
  1817 size_t SpaceManager::sum_used_in_chunks_in_use() const {
  1818   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1819   size_t used = 0;
  1820   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1821     Metachunk* chunk = chunks_in_use(i);
  1822     while (chunk != NULL) {
  1823       used += chunk->used_word_size();
  1824       chunk = chunk->next();
  1827   return used;
  1830 void SpaceManager::locked_print_chunks_in_use_on(outputStream* st) const {
  1832   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1833     Metachunk* chunk = chunks_in_use(i);
  1834     st->print("SpaceManager: %s " PTR_FORMAT,
  1835                  chunk_size_name(i), chunk);
  1836     if (chunk != NULL) {
  1837       st->print_cr(" free " SIZE_FORMAT,
  1838                    chunk->free_word_size());
  1839     } else {
  1840       st->print_cr("");
  1844   vs_list()->chunk_manager()->locked_print_free_chunks(st);
  1845   vs_list()->chunk_manager()->locked_print_sum_free_chunks(st);
  1848 size_t SpaceManager::calc_chunk_size(size_t word_size) {
  1850   // Decide between a small chunk and a medium chunk.  Up to
  1851   // _small_chunk_limit small chunks can be allocated but
  1852   // once a medium chunk has been allocated, no more small
  1853   // chunks will be allocated.
  1854   size_t chunk_word_size;
  1855   if (chunks_in_use(MediumIndex) == NULL &&
  1856       (!has_small_chunk_limit() ||
  1857        sum_count_in_chunks_in_use(SmallIndex) < _small_chunk_limit)) {
  1858     chunk_word_size = (size_t) small_chunk_size();
  1859     if (word_size + Metachunk::overhead() > small_chunk_size()) {
  1860       chunk_word_size = medium_chunk_size();
  1862   } else {
  1863     chunk_word_size = medium_chunk_size();
  1866   // Might still need a humongous chunk.  Enforce an
  1867   // eight word granularity to facilitate reuse (some
  1868   // wastage but better chance of reuse).
  1869   size_t if_humongous_sized_chunk =
  1870     align_size_up(word_size + Metachunk::overhead(),
  1871                   HumongousChunkGranularity);
  1872   chunk_word_size =
  1873     MAX2((size_t) chunk_word_size, if_humongous_sized_chunk);
  1875   assert(!SpaceManager::is_humongous(word_size) ||
  1876          chunk_word_size == if_humongous_sized_chunk,
  1877          err_msg("Size calculation is wrong, word_size " SIZE_FORMAT
  1878                  " chunk_word_size " SIZE_FORMAT,
  1879                  word_size, chunk_word_size));
  1880   if (TraceMetadataHumongousAllocation &&
  1881       SpaceManager::is_humongous(word_size)) {
  1882     gclog_or_tty->print_cr("Metadata humongous allocation:");
  1883     gclog_or_tty->print_cr("  word_size " PTR_FORMAT, word_size);
  1884     gclog_or_tty->print_cr("  chunk_word_size " PTR_FORMAT,
  1885                            chunk_word_size);
  1886     gclog_or_tty->print_cr("    chunk overhead " PTR_FORMAT,
  1887                            Metachunk::overhead());
  1889   return chunk_word_size;
  1892 MetaWord* SpaceManager::grow_and_allocate(size_t word_size) {
  1893   assert(vs_list()->current_virtual_space() != NULL,
  1894          "Should have been set");
  1895   assert(current_chunk() == NULL ||
  1896          current_chunk()->allocate(word_size) == NULL,
  1897          "Don't need to expand");
  1898   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  1900   if (TraceMetadataChunkAllocation && Verbose) {
  1901     size_t words_left = 0;
  1902     size_t words_used = 0;
  1903     if (current_chunk() != NULL) {
  1904       words_left = current_chunk()->free_word_size();
  1905       words_used = current_chunk()->used_word_size();
  1907     gclog_or_tty->print_cr("SpaceManager::grow_and_allocate for " SIZE_FORMAT
  1908                            " words " SIZE_FORMAT " words used " SIZE_FORMAT
  1909                            " words left",
  1910                             word_size, words_used, words_left);
  1913   // Get another chunk out of the virtual space
  1914   size_t grow_chunks_by_words = calc_chunk_size(word_size);
  1915   Metachunk* next = get_new_chunk(word_size, grow_chunks_by_words);
  1917   // If a chunk was available, add it to the in-use chunk list
  1918   // and do an allocation from it.
  1919   if (next != NULL) {
  1920     Metadebug::deallocate_chunk_a_lot(this, grow_chunks_by_words);
  1921     // Add to this manager's list of chunks in use.
  1922     add_chunk(next, false);
  1923     return next->allocate(word_size);
  1925   return NULL;
  1928 void SpaceManager::print_on(outputStream* st) const {
  1930   for (ChunkIndex i = ZeroIndex;
  1931        i < NumberOfInUseLists ;
  1932        i = next_chunk_index(i) ) {
  1933     st->print_cr("  chunks_in_use " PTR_FORMAT " chunk size " PTR_FORMAT,
  1934                  chunks_in_use(i),
  1935                  chunks_in_use(i) == NULL ? 0 : chunks_in_use(i)->word_size());
  1937   st->print_cr("    waste:  Small " SIZE_FORMAT " Medium " SIZE_FORMAT
  1938                " Humongous " SIZE_FORMAT,
  1939                sum_waste_in_chunks_in_use(SmallIndex),
  1940                sum_waste_in_chunks_in_use(MediumIndex),
  1941                sum_waste_in_chunks_in_use(HumongousIndex));
  1942   // block free lists
  1943   if (block_freelists() != NULL) {
  1944     st->print_cr("total in block free lists " SIZE_FORMAT,
  1945       block_freelists()->total_size());
  1949 SpaceManager::SpaceManager(Mutex* lock,
  1950                            VirtualSpaceList* vs_list) :
  1951   _vs_list(vs_list),
  1952   _allocation_total(0),
  1953   _lock(lock)
  1955   initialize();
  1958 void SpaceManager::initialize() {
  1959   Metadebug::init_allocation_fail_alot_count();
  1960   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1961     _chunks_in_use[i] = NULL;
  1963   _current_chunk = NULL;
  1964   if (TraceMetadataChunkAllocation && Verbose) {
  1965     gclog_or_tty->print_cr("SpaceManager(): " PTR_FORMAT, this);
  1969 SpaceManager::~SpaceManager() {
  1970   // This call this->_lock which can't be done while holding expand_lock()
  1971   const size_t in_use_before = sum_capacity_in_chunks_in_use();
  1973   MutexLockerEx fcl(SpaceManager::expand_lock(),
  1974                     Mutex::_no_safepoint_check_flag);
  1976   ChunkManager* chunk_manager = vs_list()->chunk_manager();
  1978   chunk_manager->slow_locked_verify();
  1980   if (TraceMetadataChunkAllocation && Verbose) {
  1981     gclog_or_tty->print_cr("~SpaceManager(): " PTR_FORMAT, this);
  1982     locked_print_chunks_in_use_on(gclog_or_tty);
  1985   // Mangle freed memory.
  1986   NOT_PRODUCT(mangle_freed_chunks();)
  1988   // Have to update before the chunks_in_use lists are emptied
  1989   // below.
  1990   chunk_manager->inc_free_chunks_total(in_use_before,
  1991                                        sum_count_in_chunks_in_use());
  1993   // Add all the chunks in use by this space manager
  1994   // to the global list of free chunks.
  1996   // Follow each list of chunks-in-use and add them to the
  1997   // free lists.  Each list is NULL terminated.
  1999   for (ChunkIndex i = ZeroIndex; i < HumongousIndex; i = next_chunk_index(i)) {
  2000     if (TraceMetadataChunkAllocation && Verbose) {
  2001       gclog_or_tty->print_cr("returned %d %s chunks to freelist",
  2002                              sum_count_in_chunks_in_use(i),
  2003                              chunk_size_name(i));
  2005     Metachunk* chunks = chunks_in_use(i);
  2006     chunk_manager->free_chunks(i)->add_at_head(chunks);
  2007     set_chunks_in_use(i, NULL);
  2008     if (TraceMetadataChunkAllocation && Verbose) {
  2009       gclog_or_tty->print_cr("updated freelist count %d %s",
  2010                              chunk_manager->free_chunks(i)->sum_list_count(),
  2011                              chunk_size_name(i));
  2013     assert(i != HumongousIndex, "Humongous chunks are handled explicitly later");
  2016   // The medium chunk case may be optimized by passing the head and
  2017   // tail of the medium chunk list to add_at_head().  The tail is often
  2018   // the current chunk but there are probably exceptions.
  2020   // Humongous chunks
  2021   if (TraceMetadataChunkAllocation && Verbose) {
  2022     gclog_or_tty->print_cr("returned %d %s humongous chunks to dictionary",
  2023                             sum_count_in_chunks_in_use(HumongousIndex),
  2024                             chunk_size_name(HumongousIndex));
  2025     gclog_or_tty->print("Humongous chunk dictionary: ");
  2027   // Humongous chunks are never the current chunk.
  2028   Metachunk* humongous_chunks = chunks_in_use(HumongousIndex);
  2030   while (humongous_chunks != NULL) {
  2031 #ifdef ASSERT
  2032     humongous_chunks->set_is_free(true);
  2033 #endif
  2034     if (TraceMetadataChunkAllocation && Verbose) {
  2035       gclog_or_tty->print(PTR_FORMAT " (" SIZE_FORMAT ") ",
  2036                           humongous_chunks,
  2037                           humongous_chunks->word_size());
  2039     assert(humongous_chunks->word_size() == (size_t)
  2040            align_size_up(humongous_chunks->word_size(),
  2041                              HumongousChunkGranularity),
  2042            err_msg("Humongous chunk size is wrong: word size " SIZE_FORMAT
  2043                    " granularity %d",
  2044                    humongous_chunks->word_size(), HumongousChunkGranularity));
  2045     Metachunk* next_humongous_chunks = humongous_chunks->next();
  2046     chunk_manager->humongous_dictionary()->return_chunk(humongous_chunks);
  2047     humongous_chunks = next_humongous_chunks;
  2049   if (TraceMetadataChunkAllocation && Verbose) {
  2050     gclog_or_tty->print_cr("");
  2051     gclog_or_tty->print_cr("updated dictionary count %d %s",
  2052                      chunk_manager->humongous_dictionary()->total_count(),
  2053                      chunk_size_name(HumongousIndex));
  2055   set_chunks_in_use(HumongousIndex, NULL);
  2056   chunk_manager->slow_locked_verify();
  2059 const char* SpaceManager::chunk_size_name(ChunkIndex index) const {
  2060   switch (index) {
  2061     case SpecializedIndex:
  2062       return "Specialized";
  2063     case SmallIndex:
  2064       return "Small";
  2065     case MediumIndex:
  2066       return "Medium";
  2067     case HumongousIndex:
  2068       return "Humongous";
  2069     default:
  2070       return NULL;
  2074 ChunkIndex ChunkManager::list_index(size_t size) {
  2075   switch (size) {
  2076     case SpecializedChunk:
  2077       assert(SpecializedChunk == ClassSpecializedChunk,
  2078              "Need branch for ClassSpecializedChunk");
  2079       return SpecializedIndex;
  2080     case SmallChunk:
  2081     case ClassSmallChunk:
  2082       return SmallIndex;
  2083     case MediumChunk:
  2084     case ClassMediumChunk:
  2085       return MediumIndex;
  2086     default:
  2087       assert(size > MediumChunk || size > ClassMediumChunk,
  2088              "Not a humongous chunk");
  2089       return HumongousIndex;
  2093 void SpaceManager::deallocate(MetaWord* p, size_t word_size) {
  2094   assert_lock_strong(_lock);
  2095   size_t min_size = TreeChunk<Metablock, FreeList>::min_size();
  2096   assert(word_size >= min_size,
  2097     err_msg("Should not deallocate dark matter " SIZE_FORMAT, word_size));
  2098   block_freelists()->return_block(p, word_size);
  2101 // Adds a chunk to the list of chunks in use.
  2102 void SpaceManager::add_chunk(Metachunk* new_chunk, bool make_current) {
  2104   assert(new_chunk != NULL, "Should not be NULL");
  2105   assert(new_chunk->next() == NULL, "Should not be on a list");
  2107   new_chunk->reset_empty();
  2109   // Find the correct list and and set the current
  2110   // chunk for that list.
  2111   ChunkIndex index = ChunkManager::list_index(new_chunk->word_size());
  2113   if (index != HumongousIndex) {
  2114     set_current_chunk(new_chunk);
  2115     new_chunk->set_next(chunks_in_use(index));
  2116     set_chunks_in_use(index, new_chunk);
  2117   } else {
  2118     // For null class loader data and DumpSharedSpaces, the first chunk isn't
  2119     // small, so small will be null.  Link this first chunk as the current
  2120     // chunk.
  2121     if (make_current) {
  2122       // Set as the current chunk but otherwise treat as a humongous chunk.
  2123       set_current_chunk(new_chunk);
  2125     // Link at head.  The _current_chunk only points to a humongous chunk for
  2126     // the null class loader metaspace (class and data virtual space managers)
  2127     // any humongous chunks so will not point to the tail
  2128     // of the humongous chunks list.
  2129     new_chunk->set_next(chunks_in_use(HumongousIndex));
  2130     set_chunks_in_use(HumongousIndex, new_chunk);
  2132     assert(new_chunk->word_size() > medium_chunk_size(), "List inconsistency");
  2135   assert(new_chunk->is_empty(), "Not ready for reuse");
  2136   if (TraceMetadataChunkAllocation && Verbose) {
  2137     gclog_or_tty->print("SpaceManager::add_chunk: %d) ",
  2138                         sum_count_in_chunks_in_use());
  2139     new_chunk->print_on(gclog_or_tty);
  2140     vs_list()->chunk_manager()->locked_print_free_chunks(tty);
  2144 Metachunk* SpaceManager::get_new_chunk(size_t word_size,
  2145                                        size_t grow_chunks_by_words) {
  2147   Metachunk* next = vs_list()->get_new_chunk(word_size,
  2148                                              grow_chunks_by_words,
  2149                                              medium_chunk_bunch());
  2151   if (TraceMetadataHumongousAllocation &&
  2152       SpaceManager::is_humongous(next->word_size())) {
  2153     gclog_or_tty->print_cr("  new humongous chunk word size " PTR_FORMAT,
  2154                            next->word_size());
  2157   return next;
  2160 MetaWord* SpaceManager::allocate(size_t word_size) {
  2161   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  2163   // If only the dictionary is going to be used (i.e., no
  2164   // indexed free list), then there is a minimum size requirement.
  2165   // MinChunkSize is a placeholder for the real minimum size JJJ
  2166   size_t byte_size = word_size * BytesPerWord;
  2168   size_t byte_size_with_overhead = byte_size + Metablock::overhead();
  2170   size_t raw_bytes_size = MAX2(byte_size_with_overhead,
  2171                                Metablock::min_block_byte_size());
  2172   raw_bytes_size = ARENA_ALIGN(raw_bytes_size);
  2173   size_t raw_word_size = raw_bytes_size / BytesPerWord;
  2174   assert(raw_word_size * BytesPerWord == raw_bytes_size, "Size problem");
  2176   BlockFreelist* fl =  block_freelists();
  2177   MetaWord* p = NULL;
  2178   // Allocation from the dictionary is expensive in the sense that
  2179   // the dictionary has to be searched for a size.  Don't allocate
  2180   // from the dictionary until it starts to get fat.  Is this
  2181   // a reasonable policy?  Maybe an skinny dictionary is fast enough
  2182   // for allocations.  Do some profiling.  JJJ
  2183   if (fl->total_size() > allocation_from_dictionary_limit) {
  2184     p = fl->get_block(raw_word_size);
  2186   if (p == NULL) {
  2187     p = allocate_work(raw_word_size);
  2189   Metadebug::deallocate_block_a_lot(this, raw_word_size);
  2191   return p;
  2194 // Returns the address of spaced allocated for "word_size".
  2195 // This methods does not know about blocks (Metablocks)
  2196 MetaWord* SpaceManager::allocate_work(size_t word_size) {
  2197   assert_lock_strong(_lock);
  2198 #ifdef ASSERT
  2199   if (Metadebug::test_metadata_failure()) {
  2200     return NULL;
  2202 #endif
  2203   // Is there space in the current chunk?
  2204   MetaWord* result = NULL;
  2206   // For DumpSharedSpaces, only allocate out of the current chunk which is
  2207   // never null because we gave it the size we wanted.   Caller reports out
  2208   // of memory if this returns null.
  2209   if (DumpSharedSpaces) {
  2210     assert(current_chunk() != NULL, "should never happen");
  2211     inc_allocation_total(word_size);
  2212     return current_chunk()->allocate(word_size); // caller handles null result
  2214   if (current_chunk() != NULL) {
  2215     result = current_chunk()->allocate(word_size);
  2218   if (result == NULL) {
  2219     result = grow_and_allocate(word_size);
  2221   if (result > 0) {
  2222     inc_allocation_total(word_size);
  2223     assert(result != (MetaWord*) chunks_in_use(MediumIndex),
  2224            "Head of the list is being allocated");
  2227   return result;
  2230 void SpaceManager::verify() {
  2231   // If there are blocks in the dictionary, then
  2232   // verfication of chunks does not work since
  2233   // being in the dictionary alters a chunk.
  2234   if (block_freelists()->total_size() == 0) {
  2235     for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2236       Metachunk* curr = chunks_in_use(i);
  2237       while (curr != NULL) {
  2238         curr->verify();
  2239         verify_chunk_size(curr);
  2240         curr = curr->next();
  2246 void SpaceManager::verify_chunk_size(Metachunk* chunk) {
  2247   assert(is_humongous(chunk->word_size()) ||
  2248          chunk->word_size() == medium_chunk_size() ||
  2249          chunk->word_size() == small_chunk_size() ||
  2250          chunk->word_size() == specialized_chunk_size(),
  2251          "Chunk size is wrong");
  2252   return;
  2255 #ifdef ASSERT
  2256 void SpaceManager::verify_allocation_total() {
  2257   // Verification is only guaranteed at a safepoint.
  2258   if (SafepointSynchronize::is_at_safepoint()) {
  2259     gclog_or_tty->print_cr("Chunk " PTR_FORMAT " allocation_total " SIZE_FORMAT
  2260                            " sum_used_in_chunks_in_use " SIZE_FORMAT,
  2261                            this,
  2262                            allocation_total(),
  2263                            sum_used_in_chunks_in_use());
  2265   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  2266   assert(allocation_total() == sum_used_in_chunks_in_use(),
  2267     err_msg("allocation total is not consistent " SIZE_FORMAT
  2268             " vs " SIZE_FORMAT,
  2269             allocation_total(), sum_used_in_chunks_in_use()));
  2272 #endif
  2274 void SpaceManager::dump(outputStream* const out) const {
  2275   size_t curr_total = 0;
  2276   size_t waste = 0;
  2277   uint i = 0;
  2278   size_t used = 0;
  2279   size_t capacity = 0;
  2281   // Add up statistics for all chunks in this SpaceManager.
  2282   for (ChunkIndex index = ZeroIndex;
  2283        index < NumberOfInUseLists;
  2284        index = next_chunk_index(index)) {
  2285     for (Metachunk* curr = chunks_in_use(index);
  2286          curr != NULL;
  2287          curr = curr->next()) {
  2288       out->print("%d) ", i++);
  2289       curr->print_on(out);
  2290       if (TraceMetadataChunkAllocation && Verbose) {
  2291         block_freelists()->print_on(out);
  2293       curr_total += curr->word_size();
  2294       used += curr->used_word_size();
  2295       capacity += curr->capacity_word_size();
  2296       waste += curr->free_word_size() + curr->overhead();;
  2300   size_t free = current_chunk() == NULL ? 0 : current_chunk()->free_word_size();
  2301   // Free space isn't wasted.
  2302   waste -= free;
  2304   out->print_cr("total of all chunks "  SIZE_FORMAT " used " SIZE_FORMAT
  2305                 " free " SIZE_FORMAT " capacity " SIZE_FORMAT
  2306                 " waste " SIZE_FORMAT, curr_total, used, free, capacity, waste);
  2309 #ifndef PRODUCT
  2310 void SpaceManager::mangle_freed_chunks() {
  2311   for (ChunkIndex index = ZeroIndex;
  2312        index < NumberOfInUseLists;
  2313        index = next_chunk_index(index)) {
  2314     for (Metachunk* curr = chunks_in_use(index);
  2315          curr != NULL;
  2316          curr = curr->next()) {
  2317       curr->mangle();
  2321 #endif // PRODUCT
  2323 // MetaspaceAux
  2325 size_t MetaspaceAux::used_in_bytes(Metaspace::MetadataType mdtype) {
  2326   size_t used = 0;
  2327   ClassLoaderDataGraphMetaspaceIterator iter;
  2328   while (iter.repeat()) {
  2329     Metaspace* msp = iter.get_next();
  2330     // Sum allocation_total for each metaspace
  2331     if (msp != NULL) {
  2332       used += msp->used_words(mdtype);
  2335   return used * BytesPerWord;
  2338 size_t MetaspaceAux::free_in_bytes(Metaspace::MetadataType mdtype) {
  2339   size_t free = 0;
  2340   ClassLoaderDataGraphMetaspaceIterator iter;
  2341   while (iter.repeat()) {
  2342     Metaspace* msp = iter.get_next();
  2343     if (msp != NULL) {
  2344       free += msp->free_words(mdtype);
  2347   return free * BytesPerWord;
  2350 size_t MetaspaceAux::capacity_in_bytes(Metaspace::MetadataType mdtype) {
  2351   size_t capacity = free_chunks_total(mdtype);
  2352   ClassLoaderDataGraphMetaspaceIterator iter;
  2353   while (iter.repeat()) {
  2354     Metaspace* msp = iter.get_next();
  2355     if (msp != NULL) {
  2356       capacity += msp->capacity_words(mdtype);
  2359   return capacity * BytesPerWord;
  2362 size_t MetaspaceAux::reserved_in_bytes(Metaspace::MetadataType mdtype) {
  2363   size_t reserved = (mdtype == Metaspace::ClassType) ?
  2364                        Metaspace::class_space_list()->virtual_space_total() :
  2365                        Metaspace::space_list()->virtual_space_total();
  2366   return reserved * BytesPerWord;
  2369 size_t MetaspaceAux::min_chunk_size() { return Metaspace::first_chunk_word_size(); }
  2371 size_t MetaspaceAux::free_chunks_total(Metaspace::MetadataType mdtype) {
  2372   ChunkManager* chunk = (mdtype == Metaspace::ClassType) ?
  2373                             Metaspace::class_space_list()->chunk_manager() :
  2374                             Metaspace::space_list()->chunk_manager();
  2375   chunk->slow_verify();
  2376   return chunk->free_chunks_total();
  2379 size_t MetaspaceAux::free_chunks_total_in_bytes(Metaspace::MetadataType mdtype) {
  2380   return free_chunks_total(mdtype) * BytesPerWord;
  2383 void MetaspaceAux::print_metaspace_change(size_t prev_metadata_used) {
  2384   gclog_or_tty->print(", [Metaspace:");
  2385   if (PrintGCDetails && Verbose) {
  2386     gclog_or_tty->print(" "  SIZE_FORMAT
  2387                         "->" SIZE_FORMAT
  2388                         "("  SIZE_FORMAT "/" SIZE_FORMAT ")",
  2389                         prev_metadata_used,
  2390                         used_in_bytes(),
  2391                         capacity_in_bytes(),
  2392                         reserved_in_bytes());
  2393   } else {
  2394     gclog_or_tty->print(" "  SIZE_FORMAT "K"
  2395                         "->" SIZE_FORMAT "K"
  2396                         "("  SIZE_FORMAT "K/" SIZE_FORMAT "K)",
  2397                         prev_metadata_used / K,
  2398                         used_in_bytes()/ K,
  2399                         capacity_in_bytes()/K,
  2400                         reserved_in_bytes()/ K);
  2403   gclog_or_tty->print("]");
  2406 // This is printed when PrintGCDetails
  2407 void MetaspaceAux::print_on(outputStream* out) {
  2408   Metaspace::MetadataType ct = Metaspace::ClassType;
  2409   Metaspace::MetadataType nct = Metaspace::NonClassType;
  2411   out->print_cr(" Metaspace total "
  2412                 SIZE_FORMAT "K, used " SIZE_FORMAT "K,"
  2413                 " reserved " SIZE_FORMAT "K",
  2414                 capacity_in_bytes()/K, used_in_bytes()/K, reserved_in_bytes()/K);
  2415   out->print_cr("  data space     "
  2416                 SIZE_FORMAT "K, used " SIZE_FORMAT "K,"
  2417                 " reserved " SIZE_FORMAT "K",
  2418                 capacity_in_bytes(nct)/K, used_in_bytes(nct)/K, reserved_in_bytes(nct)/K);
  2419   out->print_cr("  class space    "
  2420                 SIZE_FORMAT "K, used " SIZE_FORMAT "K,"
  2421                 " reserved " SIZE_FORMAT "K",
  2422                 capacity_in_bytes(ct)/K, used_in_bytes(ct)/K, reserved_in_bytes(ct)/K);
  2425 // Print information for class space and data space separately.
  2426 // This is almost the same as above.
  2427 void MetaspaceAux::print_on(outputStream* out, Metaspace::MetadataType mdtype) {
  2428   size_t free_chunks_capacity_bytes = free_chunks_total_in_bytes(mdtype);
  2429   size_t capacity_bytes = capacity_in_bytes(mdtype);
  2430   size_t used_bytes = used_in_bytes(mdtype);
  2431   size_t free_bytes = free_in_bytes(mdtype);
  2432   size_t used_and_free = used_bytes + free_bytes +
  2433                            free_chunks_capacity_bytes;
  2434   out->print_cr("  Chunk accounting: used in chunks " SIZE_FORMAT
  2435              "K + unused in chunks " SIZE_FORMAT "K  + "
  2436              " capacity in free chunks " SIZE_FORMAT "K = " SIZE_FORMAT
  2437              "K  capacity in allocated chunks " SIZE_FORMAT "K",
  2438              used_bytes / K,
  2439              free_bytes / K,
  2440              free_chunks_capacity_bytes / K,
  2441              used_and_free / K,
  2442              capacity_bytes / K);
  2443   // Accounting can only be correct if we got the values during a safepoint
  2444   assert(!SafepointSynchronize::is_at_safepoint() || used_and_free == capacity_bytes, "Accounting is wrong");
  2447 // Print total fragmentation for class and data metaspaces separately
  2448 void MetaspaceAux::print_waste(outputStream* out) {
  2450   size_t specialized_waste = 0, small_waste = 0, medium_waste = 0, large_waste = 0;
  2451   size_t specialized_count = 0, small_count = 0, medium_count = 0, large_count = 0;
  2452   size_t cls_specialized_waste = 0, cls_small_waste = 0, cls_medium_waste = 0, cls_large_waste = 0;
  2453   size_t cls_specialized_count = 0, cls_small_count = 0, cls_medium_count = 0, cls_large_count = 0;
  2455   ClassLoaderDataGraphMetaspaceIterator iter;
  2456   while (iter.repeat()) {
  2457     Metaspace* msp = iter.get_next();
  2458     if (msp != NULL) {
  2459       specialized_waste += msp->vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
  2460       specialized_count += msp->vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
  2461       small_waste += msp->vsm()->sum_waste_in_chunks_in_use(SmallIndex);
  2462       small_count += msp->vsm()->sum_count_in_chunks_in_use(SmallIndex);
  2463       medium_waste += msp->vsm()->sum_waste_in_chunks_in_use(MediumIndex);
  2464       medium_count += msp->vsm()->sum_count_in_chunks_in_use(MediumIndex);
  2465       large_waste += msp->vsm()->sum_waste_in_chunks_in_use(HumongousIndex);
  2466       large_count += msp->vsm()->sum_count_in_chunks_in_use(HumongousIndex);
  2468       cls_specialized_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
  2469       cls_specialized_count += msp->class_vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
  2470       cls_small_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SmallIndex);
  2471       cls_small_count += msp->class_vsm()->sum_count_in_chunks_in_use(SmallIndex);
  2472       cls_medium_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(MediumIndex);
  2473       cls_medium_count += msp->class_vsm()->sum_count_in_chunks_in_use(MediumIndex);
  2474       cls_large_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(HumongousIndex);
  2475       cls_large_count += msp->class_vsm()->sum_count_in_chunks_in_use(HumongousIndex);
  2478   out->print_cr("Total fragmentation waste (words) doesn't count free space");
  2479   out->print_cr("  data: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
  2480                         SIZE_FORMAT " small(s) " SIZE_FORMAT ", "
  2481                         SIZE_FORMAT " medium(s) " SIZE_FORMAT,
  2482              specialized_count, specialized_waste, small_count,
  2483              small_waste, medium_count, medium_waste);
  2484   out->print_cr(" class: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
  2485                            SIZE_FORMAT " small(s) " SIZE_FORMAT,
  2486              cls_specialized_count, cls_specialized_waste,
  2487              cls_small_count, cls_small_waste);
  2490 // Dump global metaspace things from the end of ClassLoaderDataGraph
  2491 void MetaspaceAux::dump(outputStream* out) {
  2492   out->print_cr("All Metaspace:");
  2493   out->print("data space: "); print_on(out, Metaspace::NonClassType);
  2494   out->print("class space: "); print_on(out, Metaspace::ClassType);
  2495   print_waste(out);
  2498 void MetaspaceAux::verify_free_chunks() {
  2499   Metaspace::space_list()->chunk_manager()->verify();
  2500   Metaspace::class_space_list()->chunk_manager()->verify();
  2503 // Metaspace methods
  2505 size_t Metaspace::_first_chunk_word_size = 0;
  2506 size_t Metaspace::_first_class_chunk_word_size = 0;
  2508 Metaspace::Metaspace(Mutex* lock, MetaspaceType type) {
  2509   initialize(lock, type);
  2512 Metaspace::~Metaspace() {
  2513   delete _vsm;
  2514   delete _class_vsm;
  2517 VirtualSpaceList* Metaspace::_space_list = NULL;
  2518 VirtualSpaceList* Metaspace::_class_space_list = NULL;
  2520 #define VIRTUALSPACEMULTIPLIER 2
  2522 void Metaspace::global_initialize() {
  2523   // Initialize the alignment for shared spaces.
  2524   int max_alignment = os::vm_page_size();
  2525   MetaspaceShared::set_max_alignment(max_alignment);
  2527   if (DumpSharedSpaces) {
  2528     SharedReadOnlySize = align_size_up(SharedReadOnlySize, max_alignment);
  2529     SharedReadWriteSize = align_size_up(SharedReadWriteSize, max_alignment);
  2530     SharedMiscDataSize  = align_size_up(SharedMiscDataSize, max_alignment);
  2531     SharedMiscCodeSize  = align_size_up(SharedMiscCodeSize, max_alignment);
  2533     // Initialize with the sum of the shared space sizes.  The read-only
  2534     // and read write metaspace chunks will be allocated out of this and the
  2535     // remainder is the misc code and data chunks.
  2536     size_t total = align_size_up(SharedReadOnlySize + SharedReadWriteSize +
  2537                                  SharedMiscDataSize + SharedMiscCodeSize,
  2538                                  os::vm_allocation_granularity());
  2539     size_t word_size = total/wordSize;
  2540     _space_list = new VirtualSpaceList(word_size);
  2541   } else {
  2542     // If using shared space, open the file that contains the shared space
  2543     // and map in the memory before initializing the rest of metaspace (so
  2544     // the addresses don't conflict)
  2545     if (UseSharedSpaces) {
  2546       FileMapInfo* mapinfo = new FileMapInfo();
  2547       memset(mapinfo, 0, sizeof(FileMapInfo));
  2549       // Open the shared archive file, read and validate the header. If
  2550       // initialization fails, shared spaces [UseSharedSpaces] are
  2551       // disabled and the file is closed.
  2552       // Map in spaces now also
  2553       if (mapinfo->initialize() && MetaspaceShared::map_shared_spaces(mapinfo)) {
  2554         FileMapInfo::set_current_info(mapinfo);
  2555       } else {
  2556         assert(!mapinfo->is_open() && !UseSharedSpaces,
  2557                "archive file not closed or shared spaces not disabled.");
  2561     // Initialize these before initializing the VirtualSpaceList
  2562     _first_chunk_word_size = InitialBootClassLoaderMetaspaceSize / BytesPerWord;
  2563     _first_chunk_word_size = align_word_size_up(_first_chunk_word_size);
  2564     // Make the first class chunk bigger than a medium chunk so it's not put
  2565     // on the medium chunk list.   The next chunk will be small and progress
  2566     // from there.  This size calculated by -version.
  2567     _first_class_chunk_word_size = MIN2((size_t)MediumChunk*6,
  2568                                        (ClassMetaspaceSize/BytesPerWord)*2);
  2569     _first_class_chunk_word_size = align_word_size_up(_first_class_chunk_word_size);
  2570     // Arbitrarily set the initial virtual space to a multiple
  2571     // of the boot class loader size.
  2572     size_t word_size = VIRTUALSPACEMULTIPLIER * first_chunk_word_size();
  2573     // Initialize the list of virtual spaces.
  2574     _space_list = new VirtualSpaceList(word_size);
  2578 // For UseCompressedKlassPointers the class space is reserved as a piece of the
  2579 // Java heap because the compression algorithm is the same for each.  The
  2580 // argument passed in is at the top of the compressed space
  2581 void Metaspace::initialize_class_space(ReservedSpace rs) {
  2582   // The reserved space size may be bigger because of alignment, esp with UseLargePages
  2583   assert(rs.size() >= ClassMetaspaceSize,
  2584          err_msg(SIZE_FORMAT " != " UINTX_FORMAT, rs.size(), ClassMetaspaceSize));
  2585   _class_space_list = new VirtualSpaceList(rs);
  2588 void Metaspace::initialize(Mutex* lock,
  2589                            MetaspaceType type) {
  2591   assert(space_list() != NULL,
  2592     "Metadata VirtualSpaceList has not been initialized");
  2594   _vsm = new SpaceManager(lock, space_list());
  2595   if (_vsm == NULL) {
  2596     return;
  2598   size_t word_size;
  2599   size_t class_word_size;
  2600   vsm()->get_initial_chunk_sizes(type,
  2601                                  &word_size,
  2602                                  &class_word_size);
  2604   assert(class_space_list() != NULL,
  2605     "Class VirtualSpaceList has not been initialized");
  2607   // Allocate SpaceManager for classes.
  2608   _class_vsm = new SpaceManager(lock, class_space_list());
  2609   if (_class_vsm == NULL) {
  2610     return;
  2613   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  2615   // Allocate chunk for metadata objects
  2616   Metachunk* new_chunk =
  2617      space_list()->get_initialization_chunk(word_size,
  2618                                             vsm()->medium_chunk_bunch());
  2619   assert(!DumpSharedSpaces || new_chunk != NULL, "should have enough space for both chunks");
  2620   if (new_chunk != NULL) {
  2621     // Add to this manager's list of chunks in use and current_chunk().
  2622     vsm()->add_chunk(new_chunk, true);
  2625   // Allocate chunk for class metadata objects
  2626   Metachunk* class_chunk =
  2627      class_space_list()->get_initialization_chunk(class_word_size,
  2628                                                   class_vsm()->medium_chunk_bunch());
  2629   if (class_chunk != NULL) {
  2630     class_vsm()->add_chunk(class_chunk, true);
  2634 size_t Metaspace::align_word_size_up(size_t word_size) {
  2635   size_t byte_size = word_size * wordSize;
  2636   return ReservedSpace::allocation_align_size_up(byte_size) / wordSize;
  2639 MetaWord* Metaspace::allocate(size_t word_size, MetadataType mdtype) {
  2640   // DumpSharedSpaces doesn't use class metadata area (yet)
  2641   if (mdtype == ClassType && !DumpSharedSpaces) {
  2642     return  class_vsm()->allocate(word_size);
  2643   } else {
  2644     return  vsm()->allocate(word_size);
  2648 MetaWord* Metaspace::expand_and_allocate(size_t word_size, MetadataType mdtype) {
  2649   MetaWord* result;
  2650   MetaspaceGC::set_expand_after_GC(true);
  2651   size_t before_inc = MetaspaceGC::capacity_until_GC();
  2652   size_t delta_words = MetaspaceGC::delta_capacity_until_GC(word_size);
  2653   MetaspaceGC::inc_capacity_until_GC(delta_words);
  2654   if (PrintGCDetails && Verbose) {
  2655     gclog_or_tty->print_cr("Increase capacity to GC from " SIZE_FORMAT
  2656       " to " SIZE_FORMAT, before_inc, MetaspaceGC::capacity_until_GC());
  2659   result = allocate(word_size, mdtype);
  2661   return result;
  2664 // Space allocated in the Metaspace.  This may
  2665 // be across several metadata virtual spaces.
  2666 char* Metaspace::bottom() const {
  2667   assert(DumpSharedSpaces, "only useful and valid for dumping shared spaces");
  2668   return (char*)vsm()->current_chunk()->bottom();
  2671 size_t Metaspace::used_words(MetadataType mdtype) const {
  2672   // return vsm()->allocation_total();
  2673   return mdtype == ClassType ? class_vsm()->sum_used_in_chunks_in_use() :
  2674                                vsm()->sum_used_in_chunks_in_use();  // includes overhead!
  2677 size_t Metaspace::free_words(MetadataType mdtype) const {
  2678   return mdtype == ClassType ? class_vsm()->sum_free_in_chunks_in_use() :
  2679                                vsm()->sum_free_in_chunks_in_use();
  2682 // Space capacity in the Metaspace.  It includes
  2683 // space in the list of chunks from which allocations
  2684 // have been made. Don't include space in the global freelist and
  2685 // in the space available in the dictionary which
  2686 // is already counted in some chunk.
  2687 size_t Metaspace::capacity_words(MetadataType mdtype) const {
  2688   return mdtype == ClassType ? class_vsm()->sum_capacity_in_chunks_in_use() :
  2689                                vsm()->sum_capacity_in_chunks_in_use();
  2692 void Metaspace::deallocate(MetaWord* ptr, size_t word_size, bool is_class) {
  2693   if (SafepointSynchronize::is_at_safepoint()) {
  2694     assert(Thread::current()->is_VM_thread(), "should be the VM thread");
  2695     // Don't take Heap_lock
  2696     MutexLocker ml(vsm()->lock());
  2697     if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
  2698       // Dark matter.  Too small for dictionary.
  2699 #ifdef ASSERT
  2700       Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
  2701 #endif
  2702       return;
  2704     if (is_class) {
  2705        class_vsm()->deallocate(ptr, word_size);
  2706     } else {
  2707       vsm()->deallocate(ptr, word_size);
  2709   } else {
  2710     MutexLocker ml(vsm()->lock());
  2712     if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
  2713       // Dark matter.  Too small for dictionary.
  2714 #ifdef ASSERT
  2715       Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
  2716 #endif
  2717       return;
  2719     if (is_class) {
  2720       class_vsm()->deallocate(ptr, word_size);
  2721     } else {
  2722       vsm()->deallocate(ptr, word_size);
  2727 Metablock* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size,
  2728                               bool read_only, MetadataType mdtype, TRAPS) {
  2729   if (HAS_PENDING_EXCEPTION) {
  2730     assert(false, "Should not allocate with exception pending");
  2731     return NULL;  // caller does a CHECK_NULL too
  2734   // SSS: Should we align the allocations and make sure the sizes are aligned.
  2735   MetaWord* result = NULL;
  2737   assert(loader_data != NULL, "Should never pass around a NULL loader_data. "
  2738         "ClassLoaderData::the_null_class_loader_data() should have been used.");
  2739   // Allocate in metaspaces without taking out a lock, because it deadlocks
  2740   // with the SymbolTable_lock.  Dumping is single threaded for now.  We'll have
  2741   // to revisit this for application class data sharing.
  2742   if (DumpSharedSpaces) {
  2743     if (read_only) {
  2744       result = loader_data->ro_metaspace()->allocate(word_size, NonClassType);
  2745     } else {
  2746       result = loader_data->rw_metaspace()->allocate(word_size, NonClassType);
  2748     if (result == NULL) {
  2749       report_out_of_shared_space(read_only ? SharedReadOnly : SharedReadWrite);
  2751     return Metablock::initialize(result, word_size);
  2754   result = loader_data->metaspace_non_null()->allocate(word_size, mdtype);
  2756   if (result == NULL) {
  2757     // Try to clean out some memory and retry.
  2758     result =
  2759       Universe::heap()->collector_policy()->satisfy_failed_metadata_allocation(
  2760         loader_data, word_size, mdtype);
  2762     // If result is still null, we are out of memory.
  2763     if (result == NULL) {
  2764       if (Verbose && TraceMetadataChunkAllocation) {
  2765         gclog_or_tty->print_cr("Metaspace allocation failed for size "
  2766           SIZE_FORMAT, word_size);
  2767         if (loader_data->metaspace_or_null() != NULL) loader_data->metaspace_or_null()->dump(gclog_or_tty);
  2768         MetaspaceAux::dump(gclog_or_tty);
  2770       // -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support
  2771       report_java_out_of_memory("Metadata space");
  2773       if (JvmtiExport::should_post_resource_exhausted()) {
  2774         JvmtiExport::post_resource_exhausted(
  2775             JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR,
  2776             "Metadata space");
  2778       THROW_OOP_0(Universe::out_of_memory_error_perm_gen());
  2781   return Metablock::initialize(result, word_size);
  2784 void Metaspace::print_on(outputStream* out) const {
  2785   // Print both class virtual space counts and metaspace.
  2786   if (Verbose) {
  2787       vsm()->print_on(out);
  2788       class_vsm()->print_on(out);
  2792 bool Metaspace::contains(const void * ptr) {
  2793   if (MetaspaceShared::is_in_shared_space(ptr)) {
  2794     return true;
  2796   // This is checked while unlocked.  As long as the virtualspaces are added
  2797   // at the end, the pointer will be in one of them.  The virtual spaces
  2798   // aren't deleted presently.  When they are, some sort of locking might
  2799   // be needed.  Note, locking this can cause inversion problems with the
  2800   // caller in MetaspaceObj::is_metadata() function.
  2801   return space_list()->contains(ptr) || class_space_list()->contains(ptr);
  2804 void Metaspace::verify() {
  2805   vsm()->verify();
  2806   class_vsm()->verify();
  2809 void Metaspace::dump(outputStream* const out) const {
  2810   if (UseMallocOnly) {
  2811     // Just print usage for now
  2812     out->print_cr("usage %d", used_words(Metaspace::NonClassType));
  2814   out->print_cr("\nVirtual space manager: " INTPTR_FORMAT, vsm());
  2815   vsm()->dump(out);
  2816   out->print_cr("\nClass space manager: " INTPTR_FORMAT, class_vsm());
  2817   class_vsm()->dump(out);

mercurial