src/share/vm/memory/metaspace.cpp

Fri, 15 Mar 2013 11:53:28 -0400

author
zgu
date
Fri, 15 Mar 2013 11:53:28 -0400
changeset 4752
82f49e8e2c28
parent 4712
3efdfd6ddbf2
child 4754
82ab039b9680
permissions
-rw-r--r--

8009614: nsk/split_verifier/stress/ifelse/ifelse002_30 fails with 'assert((size & (granularity - 1)) == 0) failed: size not aligned to os::vm_allocation_granularity()
Summary: Align up vm allocation size to os defined granularity
Reviewed-by: dholmes, coleenp

     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   // align up to vm allocation granularity
   338   byte_size = align_size_up(byte_size, os::vm_allocation_granularity());
   340   // This allocates memory with mmap.  For DumpSharedspaces, allocate the
   341   // space at low memory so that other shared images don't conflict.
   342   // This is the same address as memory needed for UseCompressedOops but
   343   // compressed oops don't work with CDS (offsets in metadata are wrong), so
   344   // borrow the same address.
   345   if (DumpSharedSpaces) {
   346     char* shared_base = (char*)HeapBaseMinAddress;
   347     _rs = ReservedSpace(byte_size, 0, false, shared_base, 0);
   348     if (_rs.is_reserved()) {
   349       assert(_rs.base() == shared_base, "should match");
   350     } else {
   351       // If we are dumping the heap, then allocate a wasted block of address
   352       // space in order to push the heap to a lower address.  This extra
   353       // address range allows for other (or larger) libraries to be loaded
   354       // without them occupying the space required for the shared spaces.
   355       uintx reserved = 0;
   356       uintx block_size = 64*1024*1024;
   357       while (reserved < SharedDummyBlockSize) {
   358         char* dummy = os::reserve_memory(block_size);
   359         reserved += block_size;
   360       }
   361       _rs = ReservedSpace(byte_size);
   362     }
   363     MetaspaceShared::set_shared_rs(&_rs);
   364   } else {
   365     _rs = ReservedSpace(byte_size);
   366   }
   368   MemTracker::record_virtual_memory_type((address)_rs.base(), mtClass);
   369 }
   371 // List of VirtualSpaces for metadata allocation.
   372 // It has a  _next link for singly linked list and a MemRegion
   373 // for total space in the VirtualSpace.
   374 class VirtualSpaceList : public CHeapObj<mtClass> {
   375   friend class VirtualSpaceNode;
   377   enum VirtualSpaceSizes {
   378     VirtualSpaceSize = 256 * K
   379   };
   381   // Global list of virtual spaces
   382   // Head of the list
   383   VirtualSpaceNode* _virtual_space_list;
   384   // virtual space currently being used for allocations
   385   VirtualSpaceNode* _current_virtual_space;
   386   // Free chunk list for all other metadata
   387   ChunkManager      _chunk_manager;
   389   // Can this virtual list allocate >1 spaces?  Also, used to determine
   390   // whether to allocate unlimited small chunks in this virtual space
   391   bool _is_class;
   392   bool can_grow() const { return !is_class() || !UseCompressedKlassPointers; }
   394   // Sum of space in all virtual spaces and number of virtual spaces
   395   size_t _virtual_space_total;
   396   size_t _virtual_space_count;
   398   ~VirtualSpaceList();
   400   VirtualSpaceNode* virtual_space_list() const { return _virtual_space_list; }
   402   void set_virtual_space_list(VirtualSpaceNode* v) {
   403     _virtual_space_list = v;
   404   }
   405   void set_current_virtual_space(VirtualSpaceNode* v) {
   406     _current_virtual_space = v;
   407   }
   409   void link_vs(VirtualSpaceNode* new_entry, size_t vs_word_size);
   411   // Get another virtual space and add it to the list.  This
   412   // is typically prompted by a failed attempt to allocate a chunk
   413   // and is typically followed by the allocation of a chunk.
   414   bool grow_vs(size_t vs_word_size);
   416  public:
   417   VirtualSpaceList(size_t word_size);
   418   VirtualSpaceList(ReservedSpace rs);
   420   Metachunk* get_new_chunk(size_t word_size,
   421                            size_t grow_chunks_by_words,
   422                            size_t medium_chunk_bunch);
   424   // Get the first chunk for a Metaspace.  Used for
   425   // special cases such as the boot class loader, reflection
   426   // class loader and anonymous class loader.
   427   Metachunk* get_initialization_chunk(size_t word_size, size_t chunk_bunch);
   429   VirtualSpaceNode* current_virtual_space() {
   430     return _current_virtual_space;
   431   }
   433   ChunkManager* chunk_manager() { return &_chunk_manager; }
   434   bool is_class() const { return _is_class; }
   436   // Allocate the first virtualspace.
   437   void initialize(size_t word_size);
   439   size_t virtual_space_total() { return _virtual_space_total; }
   440   void inc_virtual_space_total(size_t v) {
   441     Atomic::add_ptr(v, &_virtual_space_total);
   442   }
   444   size_t virtual_space_count() { return _virtual_space_count; }
   445   void inc_virtual_space_count() {
   446     Atomic::inc_ptr(&_virtual_space_count);
   447   }
   449   // Used and capacity in the entire list of virtual spaces.
   450   // These are global values shared by all Metaspaces
   451   size_t capacity_words_sum();
   452   size_t capacity_bytes_sum() { return capacity_words_sum() * BytesPerWord; }
   453   size_t used_words_sum();
   454   size_t used_bytes_sum() { return used_words_sum() * BytesPerWord; }
   456   bool contains(const void *ptr);
   458   void print_on(outputStream* st) const;
   460   class VirtualSpaceListIterator : public StackObj {
   461     VirtualSpaceNode* _virtual_spaces;
   462    public:
   463     VirtualSpaceListIterator(VirtualSpaceNode* virtual_spaces) :
   464       _virtual_spaces(virtual_spaces) {}
   466     bool repeat() {
   467       return _virtual_spaces != NULL;
   468     }
   470     VirtualSpaceNode* get_next() {
   471       VirtualSpaceNode* result = _virtual_spaces;
   472       if (_virtual_spaces != NULL) {
   473         _virtual_spaces = _virtual_spaces->next();
   474       }
   475       return result;
   476     }
   477   };
   478 };
   480 class Metadebug : AllStatic {
   481   // Debugging support for Metaspaces
   482   static int _deallocate_block_a_lot_count;
   483   static int _deallocate_chunk_a_lot_count;
   484   static int _allocation_fail_alot_count;
   486  public:
   487   static int deallocate_block_a_lot_count() {
   488     return _deallocate_block_a_lot_count;
   489   }
   490   static void set_deallocate_block_a_lot_count(int v) {
   491     _deallocate_block_a_lot_count = v;
   492   }
   493   static void inc_deallocate_block_a_lot_count() {
   494     _deallocate_block_a_lot_count++;
   495   }
   496   static int deallocate_chunk_a_lot_count() {
   497     return _deallocate_chunk_a_lot_count;
   498   }
   499   static void reset_deallocate_chunk_a_lot_count() {
   500     _deallocate_chunk_a_lot_count = 1;
   501   }
   502   static void inc_deallocate_chunk_a_lot_count() {
   503     _deallocate_chunk_a_lot_count++;
   504   }
   506   static void init_allocation_fail_alot_count();
   507 #ifdef ASSERT
   508   static bool test_metadata_failure();
   509 #endif
   511   static void deallocate_chunk_a_lot(SpaceManager* sm,
   512                                      size_t chunk_word_size);
   513   static void deallocate_block_a_lot(SpaceManager* sm,
   514                                      size_t chunk_word_size);
   516 };
   518 int Metadebug::_deallocate_block_a_lot_count = 0;
   519 int Metadebug::_deallocate_chunk_a_lot_count = 0;
   520 int Metadebug::_allocation_fail_alot_count = 0;
   522 //  SpaceManager - used by Metaspace to handle allocations
   523 class SpaceManager : public CHeapObj<mtClass> {
   524   friend class Metaspace;
   525   friend class Metadebug;
   527  private:
   529   // protects allocations and contains.
   530   Mutex* const _lock;
   532   // Chunk related size
   533   size_t _medium_chunk_bunch;
   535   // List of chunks in use by this SpaceManager.  Allocations
   536   // are done from the current chunk.  The list is used for deallocating
   537   // chunks when the SpaceManager is freed.
   538   Metachunk* _chunks_in_use[NumberOfInUseLists];
   539   Metachunk* _current_chunk;
   541   // Virtual space where allocation comes from.
   542   VirtualSpaceList* _vs_list;
   544   // Number of small chunks to allocate to a manager
   545   // If class space manager, small chunks are unlimited
   546   static uint const _small_chunk_limit;
   547   bool has_small_chunk_limit() { return !vs_list()->is_class(); }
   549   // Sum of all space in allocated chunks
   550   size_t _allocation_total;
   552   // Free lists of blocks are per SpaceManager since they
   553   // are assumed to be in chunks in use by the SpaceManager
   554   // and all chunks in use by a SpaceManager are freed when
   555   // the class loader using the SpaceManager is collected.
   556   BlockFreelist _block_freelists;
   558   // protects virtualspace and chunk expansions
   559   static const char*  _expand_lock_name;
   560   static const int    _expand_lock_rank;
   561   static Mutex* const _expand_lock;
   563  private:
   564   // Accessors
   565   Metachunk* chunks_in_use(ChunkIndex index) const { return _chunks_in_use[index]; }
   566   void set_chunks_in_use(ChunkIndex index, Metachunk* v) { _chunks_in_use[index] = v; }
   568   BlockFreelist* block_freelists() const {
   569     return (BlockFreelist*) &_block_freelists;
   570   }
   572   VirtualSpaceList* vs_list() const    { return _vs_list; }
   574   Metachunk* current_chunk() const { return _current_chunk; }
   575   void set_current_chunk(Metachunk* v) {
   576     _current_chunk = v;
   577   }
   579   Metachunk* find_current_chunk(size_t word_size);
   581   // Add chunk to the list of chunks in use
   582   void add_chunk(Metachunk* v, bool make_current);
   584   Mutex* lock() const { return _lock; }
   586   const char* chunk_size_name(ChunkIndex index) const;
   588  protected:
   589   void initialize();
   591  public:
   592   SpaceManager(Mutex* lock,
   593                VirtualSpaceList* vs_list);
   594   ~SpaceManager();
   596   enum ChunkMultiples {
   597     MediumChunkMultiple = 4
   598   };
   600   // Accessors
   601   size_t specialized_chunk_size() { return SpecializedChunk; }
   602   size_t small_chunk_size() { return (size_t) vs_list()->is_class() ? ClassSmallChunk : SmallChunk; }
   603   size_t medium_chunk_size() { return (size_t) vs_list()->is_class() ? ClassMediumChunk : MediumChunk; }
   604   size_t medium_chunk_bunch() { return medium_chunk_size() * MediumChunkMultiple; }
   606   size_t allocation_total() const { return _allocation_total; }
   607   void inc_allocation_total(size_t v) { Atomic::add_ptr(v, &_allocation_total); }
   608   bool is_humongous(size_t word_size) { return word_size > medium_chunk_size(); }
   610   static Mutex* expand_lock() { return _expand_lock; }
   612   // Set the sizes for the initial chunks.
   613   void get_initial_chunk_sizes(Metaspace::MetaspaceType type,
   614                                size_t* chunk_word_size,
   615                                size_t* class_chunk_word_size);
   617   size_t sum_capacity_in_chunks_in_use() const;
   618   size_t sum_used_in_chunks_in_use() const;
   619   size_t sum_free_in_chunks_in_use() const;
   620   size_t sum_waste_in_chunks_in_use() const;
   621   size_t sum_waste_in_chunks_in_use(ChunkIndex index ) const;
   623   size_t sum_count_in_chunks_in_use();
   624   size_t sum_count_in_chunks_in_use(ChunkIndex i);
   626   Metachunk* get_new_chunk(size_t word_size, size_t grow_chunks_by_words);
   628   // Block allocation and deallocation.
   629   // Allocates a block from the current chunk
   630   MetaWord* allocate(size_t word_size);
   632   // Helper for allocations
   633   MetaWord* allocate_work(size_t word_size);
   635   // Returns a block to the per manager freelist
   636   void deallocate(MetaWord* p, size_t word_size);
   638   // Based on the allocation size and a minimum chunk size,
   639   // returned chunk size (for expanding space for chunk allocation).
   640   size_t calc_chunk_size(size_t allocation_word_size);
   642   // Called when an allocation from the current chunk fails.
   643   // Gets a new chunk (may require getting a new virtual space),
   644   // and allocates from that chunk.
   645   MetaWord* grow_and_allocate(size_t word_size);
   647   // debugging support.
   649   void dump(outputStream* const out) const;
   650   void print_on(outputStream* st) const;
   651   void locked_print_chunks_in_use_on(outputStream* st) const;
   653   void verify();
   654   void verify_chunk_size(Metachunk* chunk);
   655   NOT_PRODUCT(void mangle_freed_chunks();)
   656 #ifdef ASSERT
   657   void verify_allocation_total();
   658 #endif
   659 };
   661 uint const SpaceManager::_small_chunk_limit = 4;
   663 const char* SpaceManager::_expand_lock_name =
   664   "SpaceManager chunk allocation lock";
   665 const int SpaceManager::_expand_lock_rank = Monitor::leaf - 1;
   666 Mutex* const SpaceManager::_expand_lock =
   667   new Mutex(SpaceManager::_expand_lock_rank,
   668             SpaceManager::_expand_lock_name,
   669             Mutex::_allow_vm_block_flag);
   671 // BlockFreelist methods
   673 BlockFreelist::BlockFreelist() : _dictionary(NULL) {}
   675 BlockFreelist::~BlockFreelist() {
   676   if (_dictionary != NULL) {
   677     if (Verbose && TraceMetadataChunkAllocation) {
   678       _dictionary->print_free_lists(gclog_or_tty);
   679     }
   680     delete _dictionary;
   681   }
   682 }
   684 Metablock* BlockFreelist::initialize_free_chunk(MetaWord* p, size_t word_size) {
   685   Metablock* block = (Metablock*) p;
   686   block->set_word_size(word_size);
   687   block->set_prev(NULL);
   688   block->set_next(NULL);
   690   return block;
   691 }
   693 void BlockFreelist::return_block(MetaWord* p, size_t word_size) {
   694   Metablock* free_chunk = initialize_free_chunk(p, word_size);
   695   if (dictionary() == NULL) {
   696    _dictionary = new BlockTreeDictionary();
   697   }
   698   dictionary()->return_chunk(free_chunk);
   699 }
   701 MetaWord* BlockFreelist::get_block(size_t word_size) {
   702   if (dictionary() == NULL) {
   703     return NULL;
   704   }
   706   if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
   707     // Dark matter.  Too small for dictionary.
   708     return NULL;
   709   }
   711   Metablock* free_block =
   712     dictionary()->get_chunk(word_size, FreeBlockDictionary<Metablock>::exactly);
   713   if (free_block == NULL) {
   714     return NULL;
   715   }
   717   return (MetaWord*) free_block;
   718 }
   720 void BlockFreelist::print_on(outputStream* st) const {
   721   if (dictionary() == NULL) {
   722     return;
   723   }
   724   dictionary()->print_free_lists(st);
   725 }
   727 // VirtualSpaceNode methods
   729 VirtualSpaceNode::~VirtualSpaceNode() {
   730   _rs.release();
   731 }
   733 size_t VirtualSpaceNode::used_words_in_vs() const {
   734   return pointer_delta(top(), bottom(), sizeof(MetaWord));
   735 }
   737 // Space committed in the VirtualSpace
   738 size_t VirtualSpaceNode::capacity_words_in_vs() const {
   739   return pointer_delta(end(), bottom(), sizeof(MetaWord));
   740 }
   743 // Allocates the chunk from the virtual space only.
   744 // This interface is also used internally for debugging.  Not all
   745 // chunks removed here are necessarily used for allocation.
   746 Metachunk* VirtualSpaceNode::take_from_committed(size_t chunk_word_size) {
   747   // Bottom of the new chunk
   748   MetaWord* chunk_limit = top();
   749   assert(chunk_limit != NULL, "Not safe to call this method");
   751   if (!is_available(chunk_word_size)) {
   752     if (TraceMetadataChunkAllocation) {
   753       tty->print("VirtualSpaceNode::take_from_committed() not available %d words ", chunk_word_size);
   754       // Dump some information about the virtual space that is nearly full
   755       print_on(tty);
   756     }
   757     return NULL;
   758   }
   760   // Take the space  (bump top on the current virtual space).
   761   inc_top(chunk_word_size);
   763   // Point the chunk at the space
   764   Metachunk* result = Metachunk::initialize(chunk_limit, chunk_word_size);
   765   return result;
   766 }
   769 // Expand the virtual space (commit more of the reserved space)
   770 bool VirtualSpaceNode::expand_by(size_t words, bool pre_touch) {
   771   size_t bytes = words * BytesPerWord;
   772   bool result =  virtual_space()->expand_by(bytes, pre_touch);
   773   if (TraceMetavirtualspaceAllocation && !result) {
   774     gclog_or_tty->print_cr("VirtualSpaceNode::expand_by() failed "
   775                            "for byte size " SIZE_FORMAT, bytes);
   776     virtual_space()->print();
   777   }
   778   return result;
   779 }
   781 // Shrink the virtual space (commit more of the reserved space)
   782 bool VirtualSpaceNode::shrink_by(size_t words) {
   783   size_t bytes = words * BytesPerWord;
   784   virtual_space()->shrink_by(bytes);
   785   return true;
   786 }
   788 // Add another chunk to the chunk list.
   790 Metachunk* VirtualSpaceNode::get_chunk_vs(size_t chunk_word_size) {
   791   assert_lock_strong(SpaceManager::expand_lock());
   792   Metachunk* result = NULL;
   794   return take_from_committed(chunk_word_size);
   795 }
   797 Metachunk* VirtualSpaceNode::get_chunk_vs_with_expand(size_t chunk_word_size) {
   798   assert_lock_strong(SpaceManager::expand_lock());
   800   Metachunk* new_chunk = get_chunk_vs(chunk_word_size);
   802   if (new_chunk == NULL) {
   803     // Only a small part of the virtualspace is committed when first
   804     // allocated so committing more here can be expected.
   805     size_t page_size_words = os::vm_page_size() / BytesPerWord;
   806     size_t aligned_expand_vs_by_words = align_size_up(chunk_word_size,
   807                                                     page_size_words);
   808     expand_by(aligned_expand_vs_by_words, false);
   809     new_chunk = get_chunk_vs(chunk_word_size);
   810   }
   811   return new_chunk;
   812 }
   814 bool VirtualSpaceNode::initialize() {
   816   if (!_rs.is_reserved()) {
   817     return false;
   818   }
   820   // An allocation out of this Virtualspace that is larger
   821   // than an initial commit size can waste that initial committed
   822   // space.
   823   size_t committed_byte_size = 0;
   824   bool result = virtual_space()->initialize(_rs, committed_byte_size);
   825   if (result) {
   826     set_top((MetaWord*)virtual_space()->low());
   827     set_reserved(MemRegion((HeapWord*)_rs.base(),
   828                  (HeapWord*)(_rs.base() + _rs.size())));
   830     assert(reserved()->start() == (HeapWord*) _rs.base(),
   831       err_msg("Reserved start was not set properly " PTR_FORMAT
   832         " != " PTR_FORMAT, reserved()->start(), _rs.base()));
   833     assert(reserved()->word_size() == _rs.size() / BytesPerWord,
   834       err_msg("Reserved size was not set properly " SIZE_FORMAT
   835         " != " SIZE_FORMAT, reserved()->word_size(),
   836         _rs.size() / BytesPerWord));
   837   }
   839   return result;
   840 }
   842 void VirtualSpaceNode::print_on(outputStream* st) const {
   843   size_t used = used_words_in_vs();
   844   size_t capacity = capacity_words_in_vs();
   845   VirtualSpace* vs = virtual_space();
   846   st->print_cr("   space @ " PTR_FORMAT " " SIZE_FORMAT "K, %3d%% used "
   847            "[" PTR_FORMAT ", " PTR_FORMAT ", "
   848            PTR_FORMAT ", " PTR_FORMAT ")",
   849            vs, capacity / K,
   850            capacity == 0 ? 0 : used * 100 / capacity,
   851            bottom(), top(), end(),
   852            vs->high_boundary());
   853 }
   855 #ifdef ASSERT
   856 void VirtualSpaceNode::mangle() {
   857   size_t word_size = capacity_words_in_vs();
   858   Copy::fill_to_words((HeapWord*) low(), word_size, 0xf1f1f1f1);
   859 }
   860 #endif // ASSERT
   862 // VirtualSpaceList methods
   863 // Space allocated from the VirtualSpace
   865 VirtualSpaceList::~VirtualSpaceList() {
   866   VirtualSpaceListIterator iter(virtual_space_list());
   867   while (iter.repeat()) {
   868     VirtualSpaceNode* vsl = iter.get_next();
   869     delete vsl;
   870   }
   871 }
   873 size_t VirtualSpaceList::used_words_sum() {
   874   size_t allocated_by_vs = 0;
   875   VirtualSpaceListIterator iter(virtual_space_list());
   876   while (iter.repeat()) {
   877     VirtualSpaceNode* vsl = iter.get_next();
   878     // Sum used region [bottom, top) in each virtualspace
   879     allocated_by_vs += vsl->used_words_in_vs();
   880   }
   881   assert(allocated_by_vs >= chunk_manager()->free_chunks_total(),
   882     err_msg("Total in free chunks " SIZE_FORMAT
   883             " greater than total from virtual_spaces " SIZE_FORMAT,
   884             allocated_by_vs, chunk_manager()->free_chunks_total()));
   885   size_t used =
   886     allocated_by_vs - chunk_manager()->free_chunks_total();
   887   return used;
   888 }
   890 // Space available in all MetadataVirtualspaces allocated
   891 // for metadata.  This is the upper limit on the capacity
   892 // of chunks allocated out of all the MetadataVirtualspaces.
   893 size_t VirtualSpaceList::capacity_words_sum() {
   894   size_t capacity = 0;
   895   VirtualSpaceListIterator iter(virtual_space_list());
   896   while (iter.repeat()) {
   897     VirtualSpaceNode* vsl = iter.get_next();
   898     capacity += vsl->capacity_words_in_vs();
   899   }
   900   return capacity;
   901 }
   903 VirtualSpaceList::VirtualSpaceList(size_t word_size ) :
   904                                    _is_class(false),
   905                                    _virtual_space_list(NULL),
   906                                    _current_virtual_space(NULL),
   907                                    _virtual_space_total(0),
   908                                    _virtual_space_count(0) {
   909   MutexLockerEx cl(SpaceManager::expand_lock(),
   910                    Mutex::_no_safepoint_check_flag);
   911   bool initialization_succeeded = grow_vs(word_size);
   913   assert(initialization_succeeded,
   914     " VirtualSpaceList initialization should not fail");
   915 }
   917 VirtualSpaceList::VirtualSpaceList(ReservedSpace rs) :
   918                                    _is_class(true),
   919                                    _virtual_space_list(NULL),
   920                                    _current_virtual_space(NULL),
   921                                    _virtual_space_total(0),
   922                                    _virtual_space_count(0) {
   923   MutexLockerEx cl(SpaceManager::expand_lock(),
   924                    Mutex::_no_safepoint_check_flag);
   925   VirtualSpaceNode* class_entry = new VirtualSpaceNode(rs);
   926   bool succeeded = class_entry->initialize();
   927   assert(succeeded, " VirtualSpaceList initialization should not fail");
   928   link_vs(class_entry, rs.size()/BytesPerWord);
   929 }
   931 // Allocate another meta virtual space and add it to the list.
   932 bool VirtualSpaceList::grow_vs(size_t vs_word_size) {
   933   assert_lock_strong(SpaceManager::expand_lock());
   934   if (vs_word_size == 0) {
   935     return false;
   936   }
   937   // Reserve the space
   938   size_t vs_byte_size = vs_word_size * BytesPerWord;
   939   assert(vs_byte_size % os::vm_page_size() == 0, "Not aligned");
   941   // Allocate the meta virtual space and initialize it.
   942   VirtualSpaceNode* new_entry = new VirtualSpaceNode(vs_byte_size);
   943   if (!new_entry->initialize()) {
   944     delete new_entry;
   945     return false;
   946   } else {
   947     // ensure lock-free iteration sees fully initialized node
   948     OrderAccess::storestore();
   949     link_vs(new_entry, vs_word_size);
   950     return true;
   951   }
   952 }
   954 void VirtualSpaceList::link_vs(VirtualSpaceNode* new_entry, size_t vs_word_size) {
   955   if (virtual_space_list() == NULL) {
   956       set_virtual_space_list(new_entry);
   957   } else {
   958     current_virtual_space()->set_next(new_entry);
   959   }
   960   set_current_virtual_space(new_entry);
   961   inc_virtual_space_total(vs_word_size);
   962   inc_virtual_space_count();
   963 #ifdef ASSERT
   964   new_entry->mangle();
   965 #endif
   966   if (TraceMetavirtualspaceAllocation && Verbose) {
   967     VirtualSpaceNode* vsl = current_virtual_space();
   968     vsl->print_on(tty);
   969   }
   970 }
   972 Metachunk* VirtualSpaceList::get_new_chunk(size_t word_size,
   973                                            size_t grow_chunks_by_words,
   974                                            size_t medium_chunk_bunch) {
   976   // Get a chunk from the chunk freelist
   977   Metachunk* next = chunk_manager()->chunk_freelist_allocate(grow_chunks_by_words);
   979   // Allocate a chunk out of the current virtual space.
   980   if (next == NULL) {
   981     next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
   982   }
   984   if (next == NULL) {
   985     // Not enough room in current virtual space.  Try to commit
   986     // more space.
   987     size_t expand_vs_by_words = MAX2(medium_chunk_bunch,
   988                                      grow_chunks_by_words);
   989     size_t page_size_words = os::vm_page_size() / BytesPerWord;
   990     size_t aligned_expand_vs_by_words = align_size_up(expand_vs_by_words,
   991                                                         page_size_words);
   992     bool vs_expanded =
   993       current_virtual_space()->expand_by(aligned_expand_vs_by_words, false);
   994     if (!vs_expanded) {
   995       // Should the capacity of the metaspaces be expanded for
   996       // this allocation?  If it's the virtual space for classes and is
   997       // being used for CompressedHeaders, don't allocate a new virtualspace.
   998       if (can_grow() && MetaspaceGC::should_expand(this, word_size)) {
   999         // Get another virtual space.
  1000           size_t grow_vs_words =
  1001             MAX2((size_t)VirtualSpaceSize, aligned_expand_vs_by_words);
  1002         if (grow_vs(grow_vs_words)) {
  1003           // Got it.  It's on the list now.  Get a chunk from it.
  1004           next = current_virtual_space()->get_chunk_vs_with_expand(grow_chunks_by_words);
  1006       } else {
  1007         // Allocation will fail and induce a GC
  1008         if (TraceMetadataChunkAllocation && Verbose) {
  1009           gclog_or_tty->print_cr("VirtualSpaceList::get_new_chunk():"
  1010             " Fail instead of expand the metaspace");
  1013     } else {
  1014       // The virtual space expanded, get a new chunk
  1015       next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
  1016       assert(next != NULL, "Just expanded, should succeed");
  1020   assert(next == NULL || (next->next() == NULL && next->prev() == NULL),
  1021          "New chunk is still on some list");
  1022   return next;
  1025 Metachunk* VirtualSpaceList::get_initialization_chunk(size_t chunk_word_size,
  1026                                                       size_t chunk_bunch) {
  1027   // Get a chunk from the chunk freelist
  1028   Metachunk* new_chunk = get_new_chunk(chunk_word_size,
  1029                                        chunk_word_size,
  1030                                        chunk_bunch);
  1031   return new_chunk;
  1034 void VirtualSpaceList::print_on(outputStream* st) const {
  1035   if (TraceMetadataChunkAllocation && Verbose) {
  1036     VirtualSpaceListIterator iter(virtual_space_list());
  1037     while (iter.repeat()) {
  1038       VirtualSpaceNode* node = iter.get_next();
  1039       node->print_on(st);
  1044 bool VirtualSpaceList::contains(const void *ptr) {
  1045   VirtualSpaceNode* list = virtual_space_list();
  1046   VirtualSpaceListIterator iter(list);
  1047   while (iter.repeat()) {
  1048     VirtualSpaceNode* node = iter.get_next();
  1049     if (node->reserved()->contains(ptr)) {
  1050       return true;
  1053   return false;
  1057 // MetaspaceGC methods
  1059 // VM_CollectForMetadataAllocation is the vm operation used to GC.
  1060 // Within the VM operation after the GC the attempt to allocate the metadata
  1061 // should succeed.  If the GC did not free enough space for the metaspace
  1062 // allocation, the HWM is increased so that another virtualspace will be
  1063 // allocated for the metadata.  With perm gen the increase in the perm
  1064 // gen had bounds, MinMetaspaceExpansion and MaxMetaspaceExpansion.  The
  1065 // metaspace policy uses those as the small and large steps for the HWM.
  1066 //
  1067 // After the GC the compute_new_size() for MetaspaceGC is called to
  1068 // resize the capacity of the metaspaces.  The current implementation
  1069 // is based on the flags MinMetaspaceFreeRatio and MaxHeapFreeRatio used
  1070 // to resize the Java heap by some GC's.  New flags can be implemented
  1071 // if really needed.  MinHeapFreeRatio is used to calculate how much
  1072 // free space is desirable in the metaspace capacity to decide how much
  1073 // to increase the HWM.  MaxMetaspaceFreeRatio is used to decide how much
  1074 // free space is desirable in the metaspace capacity before decreasing
  1075 // the HWM.
  1077 // Calculate the amount to increase the high water mark (HWM).
  1078 // Increase by a minimum amount (MinMetaspaceExpansion) so that
  1079 // another expansion is not requested too soon.  If that is not
  1080 // enough to satisfy the allocation (i.e. big enough for a word_size
  1081 // allocation), increase by MaxMetaspaceExpansion.  If that is still
  1082 // not enough, expand by the size of the allocation (word_size) plus
  1083 // some.
  1084 size_t MetaspaceGC::delta_capacity_until_GC(size_t word_size) {
  1085   size_t before_inc = MetaspaceGC::capacity_until_GC();
  1086   size_t min_delta_words = MinMetaspaceExpansion / BytesPerWord;
  1087   size_t max_delta_words = MaxMetaspaceExpansion / BytesPerWord;
  1088   size_t page_size_words = os::vm_page_size() / BytesPerWord;
  1089   size_t size_delta_words = align_size_up(word_size, page_size_words);
  1090   size_t delta_words = MAX2(size_delta_words, min_delta_words);
  1091   if (delta_words > min_delta_words) {
  1092     // Don't want to hit the high water mark on the next
  1093     // allocation so make the delta greater than just enough
  1094     // for this allocation.
  1095     delta_words = MAX2(delta_words, max_delta_words);
  1096     if (delta_words > max_delta_words) {
  1097       // This allocation is large but the next ones are probably not
  1098       // so increase by the minimum.
  1099       delta_words = delta_words + min_delta_words;
  1102   return delta_words;
  1105 bool MetaspaceGC::should_expand(VirtualSpaceList* vsl, size_t word_size) {
  1107   // Class virtual space should always be expanded.  Call GC for the other
  1108   // metadata virtual space.
  1109   if (vsl == Metaspace::class_space_list()) return true;
  1111   // If the user wants a limit, impose one.
  1112   size_t max_metaspace_size_words = MaxMetaspaceSize / BytesPerWord;
  1113   size_t metaspace_size_words = MetaspaceSize / BytesPerWord;
  1114   if (!FLAG_IS_DEFAULT(MaxMetaspaceSize) &&
  1115       vsl->capacity_words_sum() >= max_metaspace_size_words) {
  1116     return false;
  1119   // If this is part of an allocation after a GC, expand
  1120   // unconditionally.
  1121   if(MetaspaceGC::expand_after_GC()) {
  1122     return true;
  1125   // If the capacity is below the minimum capacity, allow the
  1126   // expansion.  Also set the high-water-mark (capacity_until_GC)
  1127   // to that minimum capacity so that a GC will not be induced
  1128   // until that minimum capacity is exceeded.
  1129   if (vsl->capacity_words_sum() < metaspace_size_words ||
  1130       capacity_until_GC() == 0) {
  1131     set_capacity_until_GC(metaspace_size_words);
  1132     return true;
  1133   } else {
  1134     if (vsl->capacity_words_sum() < capacity_until_GC()) {
  1135       return true;
  1136     } else {
  1137       if (TraceMetadataChunkAllocation && Verbose) {
  1138         gclog_or_tty->print_cr("  allocation request size " SIZE_FORMAT
  1139                         "  capacity_until_GC " SIZE_FORMAT
  1140                         "  capacity_words_sum " SIZE_FORMAT
  1141                         "  used_words_sum " SIZE_FORMAT
  1142                         "  free chunks " SIZE_FORMAT
  1143                         "  free chunks count %d",
  1144                         word_size,
  1145                         capacity_until_GC(),
  1146                         vsl->capacity_words_sum(),
  1147                         vsl->used_words_sum(),
  1148                         vsl->chunk_manager()->free_chunks_total(),
  1149                         vsl->chunk_manager()->free_chunks_count());
  1151       return false;
  1156 // Variables are in bytes
  1158 void MetaspaceGC::compute_new_size() {
  1159   assert(_shrink_factor <= 100, "invalid shrink factor");
  1160   uint current_shrink_factor = _shrink_factor;
  1161   _shrink_factor = 0;
  1163   VirtualSpaceList *vsl = Metaspace::space_list();
  1165   size_t capacity_after_gc = vsl->capacity_bytes_sum();
  1166   // Check to see if these two can be calculated without walking the CLDG
  1167   size_t used_after_gc = vsl->used_bytes_sum();
  1168   size_t capacity_until_GC = vsl->capacity_bytes_sum();
  1169   size_t free_after_gc = capacity_until_GC - used_after_gc;
  1171   const double minimum_free_percentage = MinMetaspaceFreeRatio / 100.0;
  1172   const double maximum_used_percentage = 1.0 - minimum_free_percentage;
  1174   const double min_tmp = used_after_gc / maximum_used_percentage;
  1175   size_t minimum_desired_capacity =
  1176     (size_t)MIN2(min_tmp, double(max_uintx));
  1177   // Don't shrink less than the initial generation size
  1178   minimum_desired_capacity = MAX2(minimum_desired_capacity,
  1179                                   MetaspaceSize);
  1181   if (PrintGCDetails && Verbose) {
  1182     const double free_percentage = ((double)free_after_gc) / capacity_until_GC;
  1183     gclog_or_tty->print_cr("\nMetaspaceGC::compute_new_size: ");
  1184     gclog_or_tty->print_cr("  "
  1185                   "  minimum_free_percentage: %6.2f"
  1186                   "  maximum_used_percentage: %6.2f",
  1187                   minimum_free_percentage,
  1188                   maximum_used_percentage);
  1189     double d_free_after_gc = free_after_gc / (double) K;
  1190     gclog_or_tty->print_cr("  "
  1191                   "   free_after_gc       : %6.1fK"
  1192                   "   used_after_gc       : %6.1fK"
  1193                   "   capacity_after_gc   : %6.1fK"
  1194                   "   metaspace HWM     : %6.1fK",
  1195                   free_after_gc / (double) K,
  1196                   used_after_gc / (double) K,
  1197                   capacity_after_gc / (double) K,
  1198                   capacity_until_GC / (double) K);
  1199     gclog_or_tty->print_cr("  "
  1200                   "   free_percentage: %6.2f",
  1201                   free_percentage);
  1205   if (capacity_until_GC < minimum_desired_capacity) {
  1206     // If we have less capacity below the metaspace HWM, then
  1207     // increment the HWM.
  1208     size_t expand_bytes = minimum_desired_capacity - capacity_until_GC;
  1209     // Don't expand unless it's significant
  1210     if (expand_bytes >= MinMetaspaceExpansion) {
  1211       size_t expand_words = expand_bytes / BytesPerWord;
  1212       MetaspaceGC::inc_capacity_until_GC(expand_words);
  1214     if (PrintGCDetails && Verbose) {
  1215       size_t new_capacity_until_GC = MetaspaceGC::capacity_until_GC_in_bytes();
  1216       gclog_or_tty->print_cr("    expanding:"
  1217                     "  minimum_desired_capacity: %6.1fK"
  1218                     "  expand_words: %6.1fK"
  1219                     "  MinMetaspaceExpansion: %6.1fK"
  1220                     "  new metaspace HWM:  %6.1fK",
  1221                     minimum_desired_capacity / (double) K,
  1222                     expand_bytes / (double) K,
  1223                     MinMetaspaceExpansion / (double) K,
  1224                     new_capacity_until_GC / (double) K);
  1226     return;
  1229   // No expansion, now see if we want to shrink
  1230   size_t shrink_words = 0;
  1231   // We would never want to shrink more than this
  1232   size_t max_shrink_words = capacity_until_GC - minimum_desired_capacity;
  1233   assert(max_shrink_words >= 0, err_msg("max_shrink_words " SIZE_FORMAT,
  1234     max_shrink_words));
  1236   // Should shrinking be considered?
  1237   if (MaxMetaspaceFreeRatio < 100) {
  1238     const double maximum_free_percentage = MaxMetaspaceFreeRatio / 100.0;
  1239     const double minimum_used_percentage = 1.0 - maximum_free_percentage;
  1240     const double max_tmp = used_after_gc / minimum_used_percentage;
  1241     size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(max_uintx));
  1242     maximum_desired_capacity = MAX2(maximum_desired_capacity,
  1243                                     MetaspaceSize);
  1244     if (PrintGC && Verbose) {
  1245       gclog_or_tty->print_cr("  "
  1246                              "  maximum_free_percentage: %6.2f"
  1247                              "  minimum_used_percentage: %6.2f",
  1248                              maximum_free_percentage,
  1249                              minimum_used_percentage);
  1250       gclog_or_tty->print_cr("  "
  1251                              "  capacity_until_GC: %6.1fK"
  1252                              "  minimum_desired_capacity: %6.1fK"
  1253                              "  maximum_desired_capacity: %6.1fK",
  1254                              capacity_until_GC / (double) K,
  1255                              minimum_desired_capacity / (double) K,
  1256                              maximum_desired_capacity / (double) K);
  1259     assert(minimum_desired_capacity <= maximum_desired_capacity,
  1260            "sanity check");
  1262     if (capacity_until_GC > maximum_desired_capacity) {
  1263       // Capacity too large, compute shrinking size
  1264       shrink_words = capacity_until_GC - maximum_desired_capacity;
  1265       // We don't want shrink all the way back to initSize if people call
  1266       // System.gc(), because some programs do that between "phases" and then
  1267       // we'd just have to grow the heap up again for the next phase.  So we
  1268       // damp the shrinking: 0% on the first call, 10% on the second call, 40%
  1269       // on the third call, and 100% by the fourth call.  But if we recompute
  1270       // size without shrinking, it goes back to 0%.
  1271       shrink_words = shrink_words / 100 * current_shrink_factor;
  1272       assert(shrink_words <= max_shrink_words,
  1273         err_msg("invalid shrink size " SIZE_FORMAT " not <= " SIZE_FORMAT,
  1274           shrink_words, max_shrink_words));
  1275       if (current_shrink_factor == 0) {
  1276         _shrink_factor = 10;
  1277       } else {
  1278         _shrink_factor = MIN2(current_shrink_factor * 4, (uint) 100);
  1280       if (PrintGCDetails && Verbose) {
  1281         gclog_or_tty->print_cr("  "
  1282                       "  shrinking:"
  1283                       "  initSize: %.1fK"
  1284                       "  maximum_desired_capacity: %.1fK",
  1285                       MetaspaceSize / (double) K,
  1286                       maximum_desired_capacity / (double) K);
  1287         gclog_or_tty->print_cr("  "
  1288                       "  shrink_words: %.1fK"
  1289                       "  current_shrink_factor: %d"
  1290                       "  new shrink factor: %d"
  1291                       "  MinMetaspaceExpansion: %.1fK",
  1292                       shrink_words / (double) K,
  1293                       current_shrink_factor,
  1294                       _shrink_factor,
  1295                       MinMetaspaceExpansion / (double) K);
  1301   // Don't shrink unless it's significant
  1302   if (shrink_words >= MinMetaspaceExpansion) {
  1303     VirtualSpaceNode* csp = vsl->current_virtual_space();
  1304     size_t available_to_shrink = csp->capacity_words_in_vs() -
  1305       csp->used_words_in_vs();
  1306     shrink_words = MIN2(shrink_words, available_to_shrink);
  1307     csp->shrink_by(shrink_words);
  1308     MetaspaceGC::dec_capacity_until_GC(shrink_words);
  1309     if (PrintGCDetails && Verbose) {
  1310       size_t new_capacity_until_GC = MetaspaceGC::capacity_until_GC_in_bytes();
  1311       gclog_or_tty->print_cr("  metaspace HWM: %.1fK", new_capacity_until_GC / (double) K);
  1314   assert(vsl->used_bytes_sum() == used_after_gc &&
  1315          used_after_gc <= vsl->capacity_bytes_sum(),
  1316          "sanity check");
  1320 // Metadebug methods
  1322 void Metadebug::deallocate_chunk_a_lot(SpaceManager* sm,
  1323                                        size_t chunk_word_size){
  1324 #ifdef ASSERT
  1325   VirtualSpaceList* vsl = sm->vs_list();
  1326   if (MetaDataDeallocateALot &&
  1327       Metadebug::deallocate_chunk_a_lot_count() % MetaDataDeallocateALotInterval == 0 ) {
  1328     Metadebug::reset_deallocate_chunk_a_lot_count();
  1329     for (uint i = 0; i < metadata_deallocate_a_lock_chunk; i++) {
  1330       Metachunk* dummy_chunk = vsl->current_virtual_space()->take_from_committed(chunk_word_size);
  1331       if (dummy_chunk == NULL) {
  1332         break;
  1334       vsl->chunk_manager()->chunk_freelist_deallocate(dummy_chunk);
  1336       if (TraceMetadataChunkAllocation && Verbose) {
  1337         gclog_or_tty->print("Metadebug::deallocate_chunk_a_lot: %d) ",
  1338                                sm->sum_count_in_chunks_in_use());
  1339         dummy_chunk->print_on(gclog_or_tty);
  1340         gclog_or_tty->print_cr("  Free chunks total %d  count %d",
  1341                                vsl->chunk_manager()->free_chunks_total(),
  1342                                vsl->chunk_manager()->free_chunks_count());
  1345   } else {
  1346     Metadebug::inc_deallocate_chunk_a_lot_count();
  1348 #endif
  1351 void Metadebug::deallocate_block_a_lot(SpaceManager* sm,
  1352                                        size_t raw_word_size){
  1353 #ifdef ASSERT
  1354   if (MetaDataDeallocateALot &&
  1355         Metadebug::deallocate_block_a_lot_count() % MetaDataDeallocateALotInterval == 0 ) {
  1356     Metadebug::set_deallocate_block_a_lot_count(0);
  1357     for (uint i = 0; i < metadata_deallocate_a_lot_block; i++) {
  1358       MetaWord* dummy_block = sm->allocate_work(raw_word_size);
  1359       if (dummy_block == 0) {
  1360         break;
  1362       sm->deallocate(dummy_block, raw_word_size);
  1364   } else {
  1365     Metadebug::inc_deallocate_block_a_lot_count();
  1367 #endif
  1370 void Metadebug::init_allocation_fail_alot_count() {
  1371   if (MetadataAllocationFailALot) {
  1372     _allocation_fail_alot_count =
  1373       1+(long)((double)MetadataAllocationFailALotInterval*os::random()/(max_jint+1.0));
  1377 #ifdef ASSERT
  1378 bool Metadebug::test_metadata_failure() {
  1379   if (MetadataAllocationFailALot &&
  1380       Threads::is_vm_complete()) {
  1381     if (_allocation_fail_alot_count > 0) {
  1382       _allocation_fail_alot_count--;
  1383     } else {
  1384       if (TraceMetadataChunkAllocation && Verbose) {
  1385         gclog_or_tty->print_cr("Metadata allocation failing for "
  1386                                "MetadataAllocationFailALot");
  1388       init_allocation_fail_alot_count();
  1389       return true;
  1392   return false;
  1394 #endif
  1396 // ChunkList methods
  1398 size_t ChunkList::sum_list_size() {
  1399   size_t result = 0;
  1400   Metachunk* cur = head();
  1401   while (cur != NULL) {
  1402     result += cur->word_size();
  1403     cur = cur->next();
  1405   return result;
  1408 size_t ChunkList::sum_list_count() {
  1409   size_t result = 0;
  1410   Metachunk* cur = head();
  1411   while (cur != NULL) {
  1412     result++;
  1413     cur = cur->next();
  1415   return result;
  1418 size_t ChunkList::sum_list_capacity() {
  1419   size_t result = 0;
  1420   Metachunk* cur = head();
  1421   while (cur != NULL) {
  1422     result += cur->capacity_word_size();
  1423     cur = cur->next();
  1425   return result;
  1428 void ChunkList::add_at_head(Metachunk* head, Metachunk* tail) {
  1429   assert_lock_strong(SpaceManager::expand_lock());
  1430   assert(head == tail || tail->next() == NULL,
  1431          "Not the tail or the head has already been added to a list");
  1433   if (TraceMetadataChunkAllocation && Verbose) {
  1434     gclog_or_tty->print("ChunkList::add_at_head(head, tail): ");
  1435     Metachunk* cur = head;
  1436     while (cur != NULL) {
  1437       gclog_or_tty->print(PTR_FORMAT " (" SIZE_FORMAT ") ", cur, cur->word_size());
  1438       cur = cur->next();
  1440     gclog_or_tty->print_cr("");
  1443   if (tail != NULL) {
  1444     tail->set_next(_head);
  1446   set_head(head);
  1449 void ChunkList::add_at_head(Metachunk* list) {
  1450   if (list == NULL) {
  1451     // Nothing to add
  1452     return;
  1454   assert_lock_strong(SpaceManager::expand_lock());
  1455   Metachunk* head = list;
  1456   Metachunk* tail = list;
  1457   Metachunk* cur = head->next();
  1458   // Search for the tail since it is not passed.
  1459   while (cur != NULL) {
  1460     tail = cur;
  1461     cur = cur->next();
  1463   add_at_head(head, tail);
  1466 // ChunkManager methods
  1468 // Verification of _free_chunks_total and _free_chunks_count does not
  1469 // work with the CMS collector because its use of additional locks
  1470 // complicate the mutex deadlock detection but it can still be useful
  1471 // for detecting errors in the chunk accounting with other collectors.
  1473 size_t ChunkManager::free_chunks_total() {
  1474 #ifdef ASSERT
  1475   if (!UseConcMarkSweepGC && !SpaceManager::expand_lock()->is_locked()) {
  1476     MutexLockerEx cl(SpaceManager::expand_lock(),
  1477                      Mutex::_no_safepoint_check_flag);
  1478     slow_locked_verify_free_chunks_total();
  1480 #endif
  1481   return _free_chunks_total;
  1484 size_t ChunkManager::free_chunks_total_in_bytes() {
  1485   return free_chunks_total() * BytesPerWord;
  1488 size_t ChunkManager::free_chunks_count() {
  1489 #ifdef ASSERT
  1490   if (!UseConcMarkSweepGC && !SpaceManager::expand_lock()->is_locked()) {
  1491     MutexLockerEx cl(SpaceManager::expand_lock(),
  1492                      Mutex::_no_safepoint_check_flag);
  1493     // This lock is only needed in debug because the verification
  1494     // of the _free_chunks_totals walks the list of free chunks
  1495     slow_locked_verify_free_chunks_count();
  1497 #endif
  1498   return _free_chunks_count;
  1501 void ChunkManager::locked_verify_free_chunks_total() {
  1502   assert_lock_strong(SpaceManager::expand_lock());
  1503   assert(sum_free_chunks() == _free_chunks_total,
  1504     err_msg("_free_chunks_total " SIZE_FORMAT " is not the"
  1505            " same as sum " SIZE_FORMAT, _free_chunks_total,
  1506            sum_free_chunks()));
  1509 void ChunkManager::verify_free_chunks_total() {
  1510   MutexLockerEx cl(SpaceManager::expand_lock(),
  1511                      Mutex::_no_safepoint_check_flag);
  1512   locked_verify_free_chunks_total();
  1515 void ChunkManager::locked_verify_free_chunks_count() {
  1516   assert_lock_strong(SpaceManager::expand_lock());
  1517   assert(sum_free_chunks_count() == _free_chunks_count,
  1518     err_msg("_free_chunks_count " SIZE_FORMAT " is not the"
  1519            " same as sum " SIZE_FORMAT, _free_chunks_count,
  1520            sum_free_chunks_count()));
  1523 void ChunkManager::verify_free_chunks_count() {
  1524 #ifdef ASSERT
  1525   MutexLockerEx cl(SpaceManager::expand_lock(),
  1526                      Mutex::_no_safepoint_check_flag);
  1527   locked_verify_free_chunks_count();
  1528 #endif
  1531 void ChunkManager::verify() {
  1532   MutexLockerEx cl(SpaceManager::expand_lock(),
  1533                      Mutex::_no_safepoint_check_flag);
  1534   locked_verify();
  1537 void ChunkManager::locked_verify() {
  1538   locked_verify_free_chunks_count();
  1539   locked_verify_free_chunks_total();
  1542 void ChunkManager::locked_print_free_chunks(outputStream* st) {
  1543   assert_lock_strong(SpaceManager::expand_lock());
  1544   st->print_cr("Free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
  1545                 _free_chunks_total, _free_chunks_count);
  1548 void ChunkManager::locked_print_sum_free_chunks(outputStream* st) {
  1549   assert_lock_strong(SpaceManager::expand_lock());
  1550   st->print_cr("Sum free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
  1551                 sum_free_chunks(), sum_free_chunks_count());
  1553 ChunkList* ChunkManager::free_chunks(ChunkIndex index) {
  1554   return &_free_chunks[index];
  1557 // These methods that sum the free chunk lists are used in printing
  1558 // methods that are used in product builds.
  1559 size_t ChunkManager::sum_free_chunks() {
  1560   assert_lock_strong(SpaceManager::expand_lock());
  1561   size_t result = 0;
  1562   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
  1563     ChunkList* list = free_chunks(i);
  1565     if (list == NULL) {
  1566       continue;
  1569     result = result + list->sum_list_capacity();
  1571   result = result + humongous_dictionary()->total_size();
  1572   return result;
  1575 size_t ChunkManager::sum_free_chunks_count() {
  1576   assert_lock_strong(SpaceManager::expand_lock());
  1577   size_t count = 0;
  1578   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
  1579     ChunkList* list = free_chunks(i);
  1580     if (list == NULL) {
  1581       continue;
  1583     count = count + list->sum_list_count();
  1585   count = count + humongous_dictionary()->total_free_blocks();
  1586   return count;
  1589 ChunkList* ChunkManager::find_free_chunks_list(size_t word_size) {
  1590   ChunkIndex index = list_index(word_size);
  1591   assert(index < HumongousIndex, "No humongous list");
  1592   return free_chunks(index);
  1595 void ChunkManager::free_chunks_put(Metachunk* chunk) {
  1596   assert_lock_strong(SpaceManager::expand_lock());
  1597   ChunkList* free_list = find_free_chunks_list(chunk->word_size());
  1598   chunk->set_next(free_list->head());
  1599   free_list->set_head(chunk);
  1600   // chunk is being returned to the chunk free list
  1601   inc_free_chunks_total(chunk->capacity_word_size());
  1602   slow_locked_verify();
  1605 void ChunkManager::chunk_freelist_deallocate(Metachunk* chunk) {
  1606   // The deallocation of a chunk originates in the freelist
  1607   // manangement code for a Metaspace and does not hold the
  1608   // lock.
  1609   assert(chunk != NULL, "Deallocating NULL");
  1610   assert_lock_strong(SpaceManager::expand_lock());
  1611   slow_locked_verify();
  1612   if (TraceMetadataChunkAllocation) {
  1613     tty->print_cr("ChunkManager::chunk_freelist_deallocate: chunk "
  1614                   PTR_FORMAT "  size " SIZE_FORMAT,
  1615                   chunk, chunk->word_size());
  1617   free_chunks_put(chunk);
  1620 Metachunk* ChunkManager::free_chunks_get(size_t word_size) {
  1621   assert_lock_strong(SpaceManager::expand_lock());
  1623   slow_locked_verify();
  1625   Metachunk* chunk = NULL;
  1626   if (list_index(word_size) != HumongousIndex) {
  1627     ChunkList* free_list = find_free_chunks_list(word_size);
  1628     assert(free_list != NULL, "Sanity check");
  1630     chunk = free_list->head();
  1631     debug_only(Metachunk* debug_head = chunk;)
  1633     if (chunk == NULL) {
  1634       return NULL;
  1637     // Remove the chunk as the head of the list.
  1638     free_list->set_head(chunk->next());
  1640     // Chunk is being removed from the chunks free list.
  1641     dec_free_chunks_total(chunk->capacity_word_size());
  1643     if (TraceMetadataChunkAllocation && Verbose) {
  1644       tty->print_cr("ChunkManager::free_chunks_get: free_list "
  1645                     PTR_FORMAT " head " PTR_FORMAT " size " SIZE_FORMAT,
  1646                     free_list, chunk, chunk->word_size());
  1648   } else {
  1649     chunk = humongous_dictionary()->get_chunk(
  1650       word_size,
  1651       FreeBlockDictionary<Metachunk>::atLeast);
  1653     if (chunk != NULL) {
  1654       if (TraceMetadataHumongousAllocation) {
  1655         size_t waste = chunk->word_size() - word_size;
  1656         tty->print_cr("Free list allocate humongous chunk size " SIZE_FORMAT
  1657                       " for requested size " SIZE_FORMAT
  1658                       " waste " SIZE_FORMAT,
  1659                       chunk->word_size(), word_size, waste);
  1661       // Chunk is being removed from the chunks free list.
  1662       dec_free_chunks_total(chunk->capacity_word_size());
  1663 #ifdef ASSERT
  1664       chunk->set_is_free(false);
  1665 #endif
  1666     } else {
  1667       return NULL;
  1671   // Remove it from the links to this freelist
  1672   chunk->set_next(NULL);
  1673   chunk->set_prev(NULL);
  1674   slow_locked_verify();
  1675   return chunk;
  1678 Metachunk* ChunkManager::chunk_freelist_allocate(size_t word_size) {
  1679   assert_lock_strong(SpaceManager::expand_lock());
  1680   slow_locked_verify();
  1682   // Take from the beginning of the list
  1683   Metachunk* chunk = free_chunks_get(word_size);
  1684   if (chunk == NULL) {
  1685     return NULL;
  1688   assert((word_size <= chunk->word_size()) ||
  1689          list_index(chunk->word_size() == HumongousIndex),
  1690          "Non-humongous variable sized chunk");
  1691   if (TraceMetadataChunkAllocation) {
  1692     size_t list_count;
  1693     if (list_index(word_size) < HumongousIndex) {
  1694       ChunkList* list = find_free_chunks_list(word_size);
  1695       list_count = list->sum_list_count();
  1696     } else {
  1697       list_count = humongous_dictionary()->total_count();
  1699     tty->print("ChunkManager::chunk_freelist_allocate: " PTR_FORMAT " chunk "
  1700                PTR_FORMAT "  size " SIZE_FORMAT " count " SIZE_FORMAT " ",
  1701                this, chunk, chunk->word_size(), list_count);
  1702     locked_print_free_chunks(tty);
  1705   return chunk;
  1708 void ChunkManager::print_on(outputStream* out) {
  1709   if (PrintFLSStatistics != 0) {
  1710     humongous_dictionary()->report_statistics();
  1714 // SpaceManager methods
  1716 void SpaceManager::get_initial_chunk_sizes(Metaspace::MetaspaceType type,
  1717                                            size_t* chunk_word_size,
  1718                                            size_t* class_chunk_word_size) {
  1719   switch (type) {
  1720   case Metaspace::BootMetaspaceType:
  1721     *chunk_word_size = Metaspace::first_chunk_word_size();
  1722     *class_chunk_word_size = Metaspace::first_class_chunk_word_size();
  1723     break;
  1724   case Metaspace::ROMetaspaceType:
  1725     *chunk_word_size = SharedReadOnlySize / wordSize;
  1726     *class_chunk_word_size = ClassSpecializedChunk;
  1727     break;
  1728   case Metaspace::ReadWriteMetaspaceType:
  1729     *chunk_word_size = SharedReadWriteSize / wordSize;
  1730     *class_chunk_word_size = ClassSpecializedChunk;
  1731     break;
  1732   case Metaspace::AnonymousMetaspaceType:
  1733   case Metaspace::ReflectionMetaspaceType:
  1734     *chunk_word_size = SpecializedChunk;
  1735     *class_chunk_word_size = ClassSpecializedChunk;
  1736     break;
  1737   default:
  1738     *chunk_word_size = SmallChunk;
  1739     *class_chunk_word_size = ClassSmallChunk;
  1740     break;
  1742   assert(*chunk_word_size != 0 && *class_chunk_word_size != 0,
  1743     err_msg("Initial chunks sizes bad: data  " SIZE_FORMAT
  1744             " class " SIZE_FORMAT,
  1745             *chunk_word_size, *class_chunk_word_size));
  1748 size_t SpaceManager::sum_free_in_chunks_in_use() const {
  1749   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1750   size_t free = 0;
  1751   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1752     Metachunk* chunk = chunks_in_use(i);
  1753     while (chunk != NULL) {
  1754       free += chunk->free_word_size();
  1755       chunk = chunk->next();
  1758   return free;
  1761 size_t SpaceManager::sum_waste_in_chunks_in_use() const {
  1762   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1763   size_t result = 0;
  1764   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1765    result += sum_waste_in_chunks_in_use(i);
  1768   return result;
  1771 size_t SpaceManager::sum_waste_in_chunks_in_use(ChunkIndex index) const {
  1772   size_t result = 0;
  1773   Metachunk* chunk = chunks_in_use(index);
  1774   // Count the free space in all the chunk but not the
  1775   // current chunk from which allocations are still being done.
  1776   if (chunk != NULL) {
  1777     Metachunk* prev = chunk;
  1778     while (chunk != NULL && chunk != current_chunk()) {
  1779       result += chunk->free_word_size();
  1780       prev = chunk;
  1781       chunk = chunk->next();
  1784   return result;
  1787 size_t SpaceManager::sum_capacity_in_chunks_in_use() const {
  1788   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1789   size_t sum = 0;
  1790   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1791     Metachunk* chunk = chunks_in_use(i);
  1792     while (chunk != NULL) {
  1793       // Just changed this sum += chunk->capacity_word_size();
  1794       // sum += chunk->word_size() - Metachunk::overhead();
  1795       sum += chunk->capacity_word_size();
  1796       chunk = chunk->next();
  1799   return sum;
  1802 size_t SpaceManager::sum_count_in_chunks_in_use() {
  1803   size_t count = 0;
  1804   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1805     count = count + sum_count_in_chunks_in_use(i);
  1808   return count;
  1811 size_t SpaceManager::sum_count_in_chunks_in_use(ChunkIndex i) {
  1812   size_t count = 0;
  1813   Metachunk* chunk = chunks_in_use(i);
  1814   while (chunk != NULL) {
  1815     count++;
  1816     chunk = chunk->next();
  1818   return count;
  1822 size_t SpaceManager::sum_used_in_chunks_in_use() const {
  1823   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1824   size_t used = 0;
  1825   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1826     Metachunk* chunk = chunks_in_use(i);
  1827     while (chunk != NULL) {
  1828       used += chunk->used_word_size();
  1829       chunk = chunk->next();
  1832   return used;
  1835 void SpaceManager::locked_print_chunks_in_use_on(outputStream* st) const {
  1837   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1838     Metachunk* chunk = chunks_in_use(i);
  1839     st->print("SpaceManager: %s " PTR_FORMAT,
  1840                  chunk_size_name(i), chunk);
  1841     if (chunk != NULL) {
  1842       st->print_cr(" free " SIZE_FORMAT,
  1843                    chunk->free_word_size());
  1844     } else {
  1845       st->print_cr("");
  1849   vs_list()->chunk_manager()->locked_print_free_chunks(st);
  1850   vs_list()->chunk_manager()->locked_print_sum_free_chunks(st);
  1853 size_t SpaceManager::calc_chunk_size(size_t word_size) {
  1855   // Decide between a small chunk and a medium chunk.  Up to
  1856   // _small_chunk_limit small chunks can be allocated but
  1857   // once a medium chunk has been allocated, no more small
  1858   // chunks will be allocated.
  1859   size_t chunk_word_size;
  1860   if (chunks_in_use(MediumIndex) == NULL &&
  1861       (!has_small_chunk_limit() ||
  1862        sum_count_in_chunks_in_use(SmallIndex) < _small_chunk_limit)) {
  1863     chunk_word_size = (size_t) small_chunk_size();
  1864     if (word_size + Metachunk::overhead() > small_chunk_size()) {
  1865       chunk_word_size = medium_chunk_size();
  1867   } else {
  1868     chunk_word_size = medium_chunk_size();
  1871   // Might still need a humongous chunk.  Enforce an
  1872   // eight word granularity to facilitate reuse (some
  1873   // wastage but better chance of reuse).
  1874   size_t if_humongous_sized_chunk =
  1875     align_size_up(word_size + Metachunk::overhead(),
  1876                   HumongousChunkGranularity);
  1877   chunk_word_size =
  1878     MAX2((size_t) chunk_word_size, if_humongous_sized_chunk);
  1880   assert(!SpaceManager::is_humongous(word_size) ||
  1881          chunk_word_size == if_humongous_sized_chunk,
  1882          err_msg("Size calculation is wrong, word_size " SIZE_FORMAT
  1883                  " chunk_word_size " SIZE_FORMAT,
  1884                  word_size, chunk_word_size));
  1885   if (TraceMetadataHumongousAllocation &&
  1886       SpaceManager::is_humongous(word_size)) {
  1887     gclog_or_tty->print_cr("Metadata humongous allocation:");
  1888     gclog_or_tty->print_cr("  word_size " PTR_FORMAT, word_size);
  1889     gclog_or_tty->print_cr("  chunk_word_size " PTR_FORMAT,
  1890                            chunk_word_size);
  1891     gclog_or_tty->print_cr("    chunk overhead " PTR_FORMAT,
  1892                            Metachunk::overhead());
  1894   return chunk_word_size;
  1897 MetaWord* SpaceManager::grow_and_allocate(size_t word_size) {
  1898   assert(vs_list()->current_virtual_space() != NULL,
  1899          "Should have been set");
  1900   assert(current_chunk() == NULL ||
  1901          current_chunk()->allocate(word_size) == NULL,
  1902          "Don't need to expand");
  1903   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  1905   if (TraceMetadataChunkAllocation && Verbose) {
  1906     size_t words_left = 0;
  1907     size_t words_used = 0;
  1908     if (current_chunk() != NULL) {
  1909       words_left = current_chunk()->free_word_size();
  1910       words_used = current_chunk()->used_word_size();
  1912     gclog_or_tty->print_cr("SpaceManager::grow_and_allocate for " SIZE_FORMAT
  1913                            " words " SIZE_FORMAT " words used " SIZE_FORMAT
  1914                            " words left",
  1915                             word_size, words_used, words_left);
  1918   // Get another chunk out of the virtual space
  1919   size_t grow_chunks_by_words = calc_chunk_size(word_size);
  1920   Metachunk* next = get_new_chunk(word_size, grow_chunks_by_words);
  1922   // If a chunk was available, add it to the in-use chunk list
  1923   // and do an allocation from it.
  1924   if (next != NULL) {
  1925     Metadebug::deallocate_chunk_a_lot(this, grow_chunks_by_words);
  1926     // Add to this manager's list of chunks in use.
  1927     add_chunk(next, false);
  1928     return next->allocate(word_size);
  1930   return NULL;
  1933 void SpaceManager::print_on(outputStream* st) const {
  1935   for (ChunkIndex i = ZeroIndex;
  1936        i < NumberOfInUseLists ;
  1937        i = next_chunk_index(i) ) {
  1938     st->print_cr("  chunks_in_use " PTR_FORMAT " chunk size " PTR_FORMAT,
  1939                  chunks_in_use(i),
  1940                  chunks_in_use(i) == NULL ? 0 : chunks_in_use(i)->word_size());
  1942   st->print_cr("    waste:  Small " SIZE_FORMAT " Medium " SIZE_FORMAT
  1943                " Humongous " SIZE_FORMAT,
  1944                sum_waste_in_chunks_in_use(SmallIndex),
  1945                sum_waste_in_chunks_in_use(MediumIndex),
  1946                sum_waste_in_chunks_in_use(HumongousIndex));
  1947   // block free lists
  1948   if (block_freelists() != NULL) {
  1949     st->print_cr("total in block free lists " SIZE_FORMAT,
  1950       block_freelists()->total_size());
  1954 SpaceManager::SpaceManager(Mutex* lock,
  1955                            VirtualSpaceList* vs_list) :
  1956   _vs_list(vs_list),
  1957   _allocation_total(0),
  1958   _lock(lock)
  1960   initialize();
  1963 void SpaceManager::initialize() {
  1964   Metadebug::init_allocation_fail_alot_count();
  1965   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1966     _chunks_in_use[i] = NULL;
  1968   _current_chunk = NULL;
  1969   if (TraceMetadataChunkAllocation && Verbose) {
  1970     gclog_or_tty->print_cr("SpaceManager(): " PTR_FORMAT, this);
  1974 SpaceManager::~SpaceManager() {
  1975   MutexLockerEx fcl(SpaceManager::expand_lock(),
  1976                     Mutex::_no_safepoint_check_flag);
  1978   ChunkManager* chunk_manager = vs_list()->chunk_manager();
  1980   chunk_manager->slow_locked_verify();
  1982   if (TraceMetadataChunkAllocation && Verbose) {
  1983     gclog_or_tty->print_cr("~SpaceManager(): " PTR_FORMAT, this);
  1984     locked_print_chunks_in_use_on(gclog_or_tty);
  1987   // Mangle freed memory.
  1988   NOT_PRODUCT(mangle_freed_chunks();)
  1990   // Have to update before the chunks_in_use lists are emptied
  1991   // below.
  1992   chunk_manager->inc_free_chunks_total(sum_capacity_in_chunks_in_use(),
  1993                                        sum_count_in_chunks_in_use());
  1995   // Add all the chunks in use by this space manager
  1996   // to the global list of free chunks.
  1998   // Follow each list of chunks-in-use and add them to the
  1999   // free lists.  Each list is NULL terminated.
  2001   for (ChunkIndex i = ZeroIndex; i < HumongousIndex; i = next_chunk_index(i)) {
  2002     if (TraceMetadataChunkAllocation && Verbose) {
  2003       gclog_or_tty->print_cr("returned %d %s chunks to freelist",
  2004                              sum_count_in_chunks_in_use(i),
  2005                              chunk_size_name(i));
  2007     Metachunk* chunks = chunks_in_use(i);
  2008     chunk_manager->free_chunks(i)->add_at_head(chunks);
  2009     set_chunks_in_use(i, NULL);
  2010     if (TraceMetadataChunkAllocation && Verbose) {
  2011       gclog_or_tty->print_cr("updated freelist count %d %s",
  2012                              chunk_manager->free_chunks(i)->sum_list_count(),
  2013                              chunk_size_name(i));
  2015     assert(i != HumongousIndex, "Humongous chunks are handled explicitly later");
  2018   // The medium chunk case may be optimized by passing the head and
  2019   // tail of the medium chunk list to add_at_head().  The tail is often
  2020   // the current chunk but there are probably exceptions.
  2022   // Humongous chunks
  2023   if (TraceMetadataChunkAllocation && Verbose) {
  2024     gclog_or_tty->print_cr("returned %d %s humongous chunks to dictionary",
  2025                             sum_count_in_chunks_in_use(HumongousIndex),
  2026                             chunk_size_name(HumongousIndex));
  2027     gclog_or_tty->print("Humongous chunk dictionary: ");
  2029   // Humongous chunks are never the current chunk.
  2030   Metachunk* humongous_chunks = chunks_in_use(HumongousIndex);
  2032   while (humongous_chunks != NULL) {
  2033 #ifdef ASSERT
  2034     humongous_chunks->set_is_free(true);
  2035 #endif
  2036     if (TraceMetadataChunkAllocation && Verbose) {
  2037       gclog_or_tty->print(PTR_FORMAT " (" SIZE_FORMAT ") ",
  2038                           humongous_chunks,
  2039                           humongous_chunks->word_size());
  2041     assert(humongous_chunks->word_size() == (size_t)
  2042            align_size_up(humongous_chunks->word_size(),
  2043                              HumongousChunkGranularity),
  2044            err_msg("Humongous chunk size is wrong: word size " SIZE_FORMAT
  2045                    " granularity %d",
  2046                    humongous_chunks->word_size(), HumongousChunkGranularity));
  2047     Metachunk* next_humongous_chunks = humongous_chunks->next();
  2048     chunk_manager->humongous_dictionary()->return_chunk(humongous_chunks);
  2049     humongous_chunks = next_humongous_chunks;
  2051   if (TraceMetadataChunkAllocation && Verbose) {
  2052     gclog_or_tty->print_cr("");
  2053     gclog_or_tty->print_cr("updated dictionary count %d %s",
  2054                      chunk_manager->humongous_dictionary()->total_count(),
  2055                      chunk_size_name(HumongousIndex));
  2057   set_chunks_in_use(HumongousIndex, NULL);
  2058   chunk_manager->slow_locked_verify();
  2061 const char* SpaceManager::chunk_size_name(ChunkIndex index) const {
  2062   switch (index) {
  2063     case SpecializedIndex:
  2064       return "Specialized";
  2065     case SmallIndex:
  2066       return "Small";
  2067     case MediumIndex:
  2068       return "Medium";
  2069     case HumongousIndex:
  2070       return "Humongous";
  2071     default:
  2072       return NULL;
  2076 ChunkIndex ChunkManager::list_index(size_t size) {
  2077   switch (size) {
  2078     case SpecializedChunk:
  2079       assert(SpecializedChunk == ClassSpecializedChunk,
  2080              "Need branch for ClassSpecializedChunk");
  2081       return SpecializedIndex;
  2082     case SmallChunk:
  2083     case ClassSmallChunk:
  2084       return SmallIndex;
  2085     case MediumChunk:
  2086     case ClassMediumChunk:
  2087       return MediumIndex;
  2088     default:
  2089       assert(size > MediumChunk || size > ClassMediumChunk,
  2090              "Not a humongous chunk");
  2091       return HumongousIndex;
  2095 void SpaceManager::deallocate(MetaWord* p, size_t word_size) {
  2096   assert_lock_strong(_lock);
  2097   size_t min_size = TreeChunk<Metablock, FreeList>::min_size();
  2098   assert(word_size >= min_size,
  2099     err_msg("Should not deallocate dark matter " SIZE_FORMAT, word_size));
  2100   block_freelists()->return_block(p, word_size);
  2103 // Adds a chunk to the list of chunks in use.
  2104 void SpaceManager::add_chunk(Metachunk* new_chunk, bool make_current) {
  2106   assert(new_chunk != NULL, "Should not be NULL");
  2107   assert(new_chunk->next() == NULL, "Should not be on a list");
  2109   new_chunk->reset_empty();
  2111   // Find the correct list and and set the current
  2112   // chunk for that list.
  2113   ChunkIndex index = ChunkManager::list_index(new_chunk->word_size());
  2115   if (index != HumongousIndex) {
  2116     set_current_chunk(new_chunk);
  2117     new_chunk->set_next(chunks_in_use(index));
  2118     set_chunks_in_use(index, new_chunk);
  2119   } else {
  2120     // For null class loader data and DumpSharedSpaces, the first chunk isn't
  2121     // small, so small will be null.  Link this first chunk as the current
  2122     // chunk.
  2123     if (make_current) {
  2124       // Set as the current chunk but otherwise treat as a humongous chunk.
  2125       set_current_chunk(new_chunk);
  2127     // Link at head.  The _current_chunk only points to a humongous chunk for
  2128     // the null class loader metaspace (class and data virtual space managers)
  2129     // any humongous chunks so will not point to the tail
  2130     // of the humongous chunks list.
  2131     new_chunk->set_next(chunks_in_use(HumongousIndex));
  2132     set_chunks_in_use(HumongousIndex, new_chunk);
  2134     assert(new_chunk->word_size() > medium_chunk_size(), "List inconsistency");
  2137   assert(new_chunk->is_empty(), "Not ready for reuse");
  2138   if (TraceMetadataChunkAllocation && Verbose) {
  2139     gclog_or_tty->print("SpaceManager::add_chunk: %d) ",
  2140                         sum_count_in_chunks_in_use());
  2141     new_chunk->print_on(gclog_or_tty);
  2142     vs_list()->chunk_manager()->locked_print_free_chunks(tty);
  2146 Metachunk* SpaceManager::get_new_chunk(size_t word_size,
  2147                                        size_t grow_chunks_by_words) {
  2149   Metachunk* next = vs_list()->get_new_chunk(word_size,
  2150                                              grow_chunks_by_words,
  2151                                              medium_chunk_bunch());
  2153   if (TraceMetadataHumongousAllocation &&
  2154       SpaceManager::is_humongous(next->word_size())) {
  2155     gclog_or_tty->print_cr("  new humongous chunk word size " PTR_FORMAT,
  2156                            next->word_size());
  2159   return next;
  2162 MetaWord* SpaceManager::allocate(size_t word_size) {
  2163   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  2165   // If only the dictionary is going to be used (i.e., no
  2166   // indexed free list), then there is a minimum size requirement.
  2167   // MinChunkSize is a placeholder for the real minimum size JJJ
  2168   size_t byte_size = word_size * BytesPerWord;
  2170   size_t byte_size_with_overhead = byte_size + Metablock::overhead();
  2172   size_t raw_bytes_size = MAX2(byte_size_with_overhead,
  2173                                Metablock::min_block_byte_size());
  2174   raw_bytes_size = ARENA_ALIGN(raw_bytes_size);
  2175   size_t raw_word_size = raw_bytes_size / BytesPerWord;
  2176   assert(raw_word_size * BytesPerWord == raw_bytes_size, "Size problem");
  2178   BlockFreelist* fl =  block_freelists();
  2179   MetaWord* p = NULL;
  2180   // Allocation from the dictionary is expensive in the sense that
  2181   // the dictionary has to be searched for a size.  Don't allocate
  2182   // from the dictionary until it starts to get fat.  Is this
  2183   // a reasonable policy?  Maybe an skinny dictionary is fast enough
  2184   // for allocations.  Do some profiling.  JJJ
  2185   if (fl->total_size() > allocation_from_dictionary_limit) {
  2186     p = fl->get_block(raw_word_size);
  2188   if (p == NULL) {
  2189     p = allocate_work(raw_word_size);
  2191   Metadebug::deallocate_block_a_lot(this, raw_word_size);
  2193   return p;
  2196 // Returns the address of spaced allocated for "word_size".
  2197 // This methods does not know about blocks (Metablocks)
  2198 MetaWord* SpaceManager::allocate_work(size_t word_size) {
  2199   assert_lock_strong(_lock);
  2200 #ifdef ASSERT
  2201   if (Metadebug::test_metadata_failure()) {
  2202     return NULL;
  2204 #endif
  2205   // Is there space in the current chunk?
  2206   MetaWord* result = NULL;
  2208   // For DumpSharedSpaces, only allocate out of the current chunk which is
  2209   // never null because we gave it the size we wanted.   Caller reports out
  2210   // of memory if this returns null.
  2211   if (DumpSharedSpaces) {
  2212     assert(current_chunk() != NULL, "should never happen");
  2213     inc_allocation_total(word_size);
  2214     return current_chunk()->allocate(word_size); // caller handles null result
  2216   if (current_chunk() != NULL) {
  2217     result = current_chunk()->allocate(word_size);
  2220   if (result == NULL) {
  2221     result = grow_and_allocate(word_size);
  2223   if (result > 0) {
  2224     inc_allocation_total(word_size);
  2225     assert(result != (MetaWord*) chunks_in_use(MediumIndex),
  2226            "Head of the list is being allocated");
  2229   return result;
  2232 void SpaceManager::verify() {
  2233   // If there are blocks in the dictionary, then
  2234   // verfication of chunks does not work since
  2235   // being in the dictionary alters a chunk.
  2236   if (block_freelists()->total_size() == 0) {
  2237     for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2238       Metachunk* curr = chunks_in_use(i);
  2239       while (curr != NULL) {
  2240         curr->verify();
  2241         verify_chunk_size(curr);
  2242         curr = curr->next();
  2248 void SpaceManager::verify_chunk_size(Metachunk* chunk) {
  2249   assert(is_humongous(chunk->word_size()) ||
  2250          chunk->word_size() == medium_chunk_size() ||
  2251          chunk->word_size() == small_chunk_size() ||
  2252          chunk->word_size() == specialized_chunk_size(),
  2253          "Chunk size is wrong");
  2254   return;
  2257 #ifdef ASSERT
  2258 void SpaceManager::verify_allocation_total() {
  2259   // Verification is only guaranteed at a safepoint.
  2260   if (SafepointSynchronize::is_at_safepoint()) {
  2261     gclog_or_tty->print_cr("Chunk " PTR_FORMAT " allocation_total " SIZE_FORMAT
  2262                            " sum_used_in_chunks_in_use " SIZE_FORMAT,
  2263                            this,
  2264                            allocation_total(),
  2265                            sum_used_in_chunks_in_use());
  2267   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  2268   assert(allocation_total() == sum_used_in_chunks_in_use(),
  2269     err_msg("allocation total is not consistent " SIZE_FORMAT
  2270             " vs " SIZE_FORMAT,
  2271             allocation_total(), sum_used_in_chunks_in_use()));
  2274 #endif
  2276 void SpaceManager::dump(outputStream* const out) const {
  2277   size_t curr_total = 0;
  2278   size_t waste = 0;
  2279   uint i = 0;
  2280   size_t used = 0;
  2281   size_t capacity = 0;
  2283   // Add up statistics for all chunks in this SpaceManager.
  2284   for (ChunkIndex index = ZeroIndex;
  2285        index < NumberOfInUseLists;
  2286        index = next_chunk_index(index)) {
  2287     for (Metachunk* curr = chunks_in_use(index);
  2288          curr != NULL;
  2289          curr = curr->next()) {
  2290       out->print("%d) ", i++);
  2291       curr->print_on(out);
  2292       if (TraceMetadataChunkAllocation && Verbose) {
  2293         block_freelists()->print_on(out);
  2295       curr_total += curr->word_size();
  2296       used += curr->used_word_size();
  2297       capacity += curr->capacity_word_size();
  2298       waste += curr->free_word_size() + curr->overhead();;
  2302   size_t free = current_chunk() == NULL ? 0 : current_chunk()->free_word_size();
  2303   // Free space isn't wasted.
  2304   waste -= free;
  2306   out->print_cr("total of all chunks "  SIZE_FORMAT " used " SIZE_FORMAT
  2307                 " free " SIZE_FORMAT " capacity " SIZE_FORMAT
  2308                 " waste " SIZE_FORMAT, curr_total, used, free, capacity, waste);
  2311 #ifndef PRODUCT
  2312 void SpaceManager::mangle_freed_chunks() {
  2313   for (ChunkIndex index = ZeroIndex;
  2314        index < NumberOfInUseLists;
  2315        index = next_chunk_index(index)) {
  2316     for (Metachunk* curr = chunks_in_use(index);
  2317          curr != NULL;
  2318          curr = curr->next()) {
  2319       curr->mangle();
  2323 #endif // PRODUCT
  2325 // MetaspaceAux
  2327 size_t MetaspaceAux::used_in_bytes(Metaspace::MetadataType mdtype) {
  2328   size_t used = 0;
  2329   ClassLoaderDataGraphMetaspaceIterator iter;
  2330   while (iter.repeat()) {
  2331     Metaspace* msp = iter.get_next();
  2332     // Sum allocation_total for each metaspace
  2333     if (msp != NULL) {
  2334       used += msp->used_words(mdtype);
  2337   return used * BytesPerWord;
  2340 size_t MetaspaceAux::free_in_bytes(Metaspace::MetadataType mdtype) {
  2341   size_t free = 0;
  2342   ClassLoaderDataGraphMetaspaceIterator iter;
  2343   while (iter.repeat()) {
  2344     Metaspace* msp = iter.get_next();
  2345     if (msp != NULL) {
  2346       free += msp->free_words(mdtype);
  2349   return free * BytesPerWord;
  2352 size_t MetaspaceAux::capacity_in_bytes(Metaspace::MetadataType mdtype) {
  2353   size_t capacity = free_chunks_total(mdtype);
  2354   ClassLoaderDataGraphMetaspaceIterator iter;
  2355   while (iter.repeat()) {
  2356     Metaspace* msp = iter.get_next();
  2357     if (msp != NULL) {
  2358       capacity += msp->capacity_words(mdtype);
  2361   return capacity * BytesPerWord;
  2364 size_t MetaspaceAux::reserved_in_bytes(Metaspace::MetadataType mdtype) {
  2365   size_t reserved = (mdtype == Metaspace::ClassType) ?
  2366                        Metaspace::class_space_list()->virtual_space_total() :
  2367                        Metaspace::space_list()->virtual_space_total();
  2368   return reserved * BytesPerWord;
  2371 size_t MetaspaceAux::min_chunk_size() { return Metaspace::first_chunk_word_size(); }
  2373 size_t MetaspaceAux::free_chunks_total(Metaspace::MetadataType mdtype) {
  2374   ChunkManager* chunk = (mdtype == Metaspace::ClassType) ?
  2375                             Metaspace::class_space_list()->chunk_manager() :
  2376                             Metaspace::space_list()->chunk_manager();
  2377   chunk->slow_verify();
  2378   return chunk->free_chunks_total();
  2381 size_t MetaspaceAux::free_chunks_total_in_bytes(Metaspace::MetadataType mdtype) {
  2382   return free_chunks_total(mdtype) * BytesPerWord;
  2385 void MetaspaceAux::print_metaspace_change(size_t prev_metadata_used) {
  2386   gclog_or_tty->print(", [Metaspace:");
  2387   if (PrintGCDetails && Verbose) {
  2388     gclog_or_tty->print(" "  SIZE_FORMAT
  2389                         "->" SIZE_FORMAT
  2390                         "("  SIZE_FORMAT "/" SIZE_FORMAT ")",
  2391                         prev_metadata_used,
  2392                         used_in_bytes(),
  2393                         capacity_in_bytes(),
  2394                         reserved_in_bytes());
  2395   } else {
  2396     gclog_or_tty->print(" "  SIZE_FORMAT "K"
  2397                         "->" SIZE_FORMAT "K"
  2398                         "("  SIZE_FORMAT "K/" SIZE_FORMAT "K)",
  2399                         prev_metadata_used / K,
  2400                         used_in_bytes()/ K,
  2401                         capacity_in_bytes()/K,
  2402                         reserved_in_bytes()/ K);
  2405   gclog_or_tty->print("]");
  2408 // This is printed when PrintGCDetails
  2409 void MetaspaceAux::print_on(outputStream* out) {
  2410   Metaspace::MetadataType ct = Metaspace::ClassType;
  2411   Metaspace::MetadataType nct = Metaspace::NonClassType;
  2413   out->print_cr(" Metaspace total "
  2414                 SIZE_FORMAT "K, used " SIZE_FORMAT "K,"
  2415                 " reserved " SIZE_FORMAT "K",
  2416                 capacity_in_bytes()/K, used_in_bytes()/K, reserved_in_bytes()/K);
  2417   out->print_cr("  data space     "
  2418                 SIZE_FORMAT "K, used " SIZE_FORMAT "K,"
  2419                 " reserved " SIZE_FORMAT "K",
  2420                 capacity_in_bytes(nct)/K, used_in_bytes(nct)/K, reserved_in_bytes(nct)/K);
  2421   out->print_cr("  class space    "
  2422                 SIZE_FORMAT "K, used " SIZE_FORMAT "K,"
  2423                 " reserved " SIZE_FORMAT "K",
  2424                 capacity_in_bytes(ct)/K, used_in_bytes(ct)/K, reserved_in_bytes(ct)/K);
  2427 // Print information for class space and data space separately.
  2428 // This is almost the same as above.
  2429 void MetaspaceAux::print_on(outputStream* out, Metaspace::MetadataType mdtype) {
  2430   size_t free_chunks_capacity_bytes = free_chunks_total_in_bytes(mdtype);
  2431   size_t capacity_bytes = capacity_in_bytes(mdtype);
  2432   size_t used_bytes = used_in_bytes(mdtype);
  2433   size_t free_bytes = free_in_bytes(mdtype);
  2434   size_t used_and_free = used_bytes + free_bytes +
  2435                            free_chunks_capacity_bytes;
  2436   out->print_cr("  Chunk accounting: used in chunks " SIZE_FORMAT
  2437              "K + unused in chunks " SIZE_FORMAT "K  + "
  2438              " capacity in free chunks " SIZE_FORMAT "K = " SIZE_FORMAT
  2439              "K  capacity in allocated chunks " SIZE_FORMAT "K",
  2440              used_bytes / K,
  2441              free_bytes / K,
  2442              free_chunks_capacity_bytes / K,
  2443              used_and_free / K,
  2444              capacity_bytes / K);
  2445   assert(used_and_free == capacity_bytes, "Accounting is wrong");
  2448 // Print total fragmentation for class and data metaspaces separately
  2449 void MetaspaceAux::print_waste(outputStream* out) {
  2451   size_t specialized_waste = 0, small_waste = 0, medium_waste = 0, large_waste = 0;
  2452   size_t specialized_count = 0, small_count = 0, medium_count = 0, large_count = 0;
  2453   size_t cls_specialized_waste = 0, cls_small_waste = 0, cls_medium_waste = 0, cls_large_waste = 0;
  2454   size_t cls_specialized_count = 0, cls_small_count = 0, cls_medium_count = 0, cls_large_count = 0;
  2456   ClassLoaderDataGraphMetaspaceIterator iter;
  2457   while (iter.repeat()) {
  2458     Metaspace* msp = iter.get_next();
  2459     if (msp != NULL) {
  2460       specialized_waste += msp->vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
  2461       specialized_count += msp->vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
  2462       small_waste += msp->vsm()->sum_waste_in_chunks_in_use(SmallIndex);
  2463       small_count += msp->vsm()->sum_count_in_chunks_in_use(SmallIndex);
  2464       medium_waste += msp->vsm()->sum_waste_in_chunks_in_use(MediumIndex);
  2465       medium_count += msp->vsm()->sum_count_in_chunks_in_use(MediumIndex);
  2466       large_waste += msp->vsm()->sum_waste_in_chunks_in_use(HumongousIndex);
  2467       large_count += msp->vsm()->sum_count_in_chunks_in_use(HumongousIndex);
  2469       cls_specialized_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
  2470       cls_specialized_count += msp->class_vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
  2471       cls_small_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SmallIndex);
  2472       cls_small_count += msp->class_vsm()->sum_count_in_chunks_in_use(SmallIndex);
  2473       cls_medium_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(MediumIndex);
  2474       cls_medium_count += msp->class_vsm()->sum_count_in_chunks_in_use(MediumIndex);
  2475       cls_large_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(HumongousIndex);
  2476       cls_large_count += msp->class_vsm()->sum_count_in_chunks_in_use(HumongousIndex);
  2479   out->print_cr("Total fragmentation waste (words) doesn't count free space");
  2480   out->print_cr("  data: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
  2481                         SIZE_FORMAT " small(s) " SIZE_FORMAT ", "
  2482                         SIZE_FORMAT " medium(s) " SIZE_FORMAT,
  2483              specialized_count, specialized_waste, small_count,
  2484              small_waste, medium_count, medium_waste);
  2485   out->print_cr(" class: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
  2486                            SIZE_FORMAT " small(s) " SIZE_FORMAT,
  2487              cls_specialized_count, cls_specialized_waste,
  2488              cls_small_count, cls_small_waste);
  2491 // Dump global metaspace things from the end of ClassLoaderDataGraph
  2492 void MetaspaceAux::dump(outputStream* out) {
  2493   out->print_cr("All Metaspace:");
  2494   out->print("data space: "); print_on(out, Metaspace::NonClassType);
  2495   out->print("class space: "); print_on(out, Metaspace::ClassType);
  2496   print_waste(out);
  2499 void MetaspaceAux::verify_free_chunks() {
  2500   Metaspace::space_list()->chunk_manager()->verify();
  2501   Metaspace::class_space_list()->chunk_manager()->verify();
  2504 // Metaspace methods
  2506 size_t Metaspace::_first_chunk_word_size = 0;
  2507 size_t Metaspace::_first_class_chunk_word_size = 0;
  2509 Metaspace::Metaspace(Mutex* lock, MetaspaceType type) {
  2510   initialize(lock, type);
  2513 Metaspace::~Metaspace() {
  2514   delete _vsm;
  2515   delete _class_vsm;
  2518 VirtualSpaceList* Metaspace::_space_list = NULL;
  2519 VirtualSpaceList* Metaspace::_class_space_list = NULL;
  2521 #define VIRTUALSPACEMULTIPLIER 2
  2523 void Metaspace::global_initialize() {
  2524   // Initialize the alignment for shared spaces.
  2525   int max_alignment = os::vm_page_size();
  2526   MetaspaceShared::set_max_alignment(max_alignment);
  2528   if (DumpSharedSpaces) {
  2529     SharedReadOnlySize = align_size_up(SharedReadOnlySize, max_alignment);
  2530     SharedReadWriteSize = align_size_up(SharedReadWriteSize, max_alignment);
  2531     SharedMiscDataSize  = align_size_up(SharedMiscDataSize, max_alignment);
  2532     SharedMiscCodeSize  = align_size_up(SharedMiscCodeSize, max_alignment);
  2534     // Initialize with the sum of the shared space sizes.  The read-only
  2535     // and read write metaspace chunks will be allocated out of this and the
  2536     // remainder is the misc code and data chunks.
  2537     size_t total = align_size_up(SharedReadOnlySize + SharedReadWriteSize +
  2538                                  SharedMiscDataSize + SharedMiscCodeSize,
  2539                                  os::vm_allocation_granularity());
  2540     size_t word_size = total/wordSize;
  2541     _space_list = new VirtualSpaceList(word_size);
  2542   } else {
  2543     // If using shared space, open the file that contains the shared space
  2544     // and map in the memory before initializing the rest of metaspace (so
  2545     // the addresses don't conflict)
  2546     if (UseSharedSpaces) {
  2547       FileMapInfo* mapinfo = new FileMapInfo();
  2548       memset(mapinfo, 0, sizeof(FileMapInfo));
  2550       // Open the shared archive file, read and validate the header. If
  2551       // initialization fails, shared spaces [UseSharedSpaces] are
  2552       // disabled and the file is closed.
  2553       // Map in spaces now also
  2554       if (mapinfo->initialize() && MetaspaceShared::map_shared_spaces(mapinfo)) {
  2555         FileMapInfo::set_current_info(mapinfo);
  2556       } else {
  2557         assert(!mapinfo->is_open() && !UseSharedSpaces,
  2558                "archive file not closed or shared spaces not disabled.");
  2562     // Initialize these before initializing the VirtualSpaceList
  2563     _first_chunk_word_size = InitialBootClassLoaderMetaspaceSize / BytesPerWord;
  2564     _first_chunk_word_size = align_word_size_up(_first_chunk_word_size);
  2565     // Make the first class chunk bigger than a medium chunk so it's not put
  2566     // on the medium chunk list.   The next chunk will be small and progress
  2567     // from there.  This size calculated by -version.
  2568     _first_class_chunk_word_size = MIN2((size_t)MediumChunk*6,
  2569                                        (ClassMetaspaceSize/BytesPerWord)*2);
  2570     _first_class_chunk_word_size = align_word_size_up(_first_class_chunk_word_size);
  2571     // Arbitrarily set the initial virtual space to a multiple
  2572     // of the boot class loader size.
  2573     size_t word_size = VIRTUALSPACEMULTIPLIER * first_chunk_word_size();
  2574     // Initialize the list of virtual spaces.
  2575     _space_list = new VirtualSpaceList(word_size);
  2579 // For UseCompressedKlassPointers the class space is reserved as a piece of the
  2580 // Java heap because the compression algorithm is the same for each.  The
  2581 // argument passed in is at the top of the compressed space
  2582 void Metaspace::initialize_class_space(ReservedSpace rs) {
  2583   // The reserved space size may be bigger because of alignment, esp with UseLargePages
  2584   assert(rs.size() >= ClassMetaspaceSize,
  2585          err_msg(SIZE_FORMAT " != " UINTX_FORMAT, rs.size(), ClassMetaspaceSize));
  2586   _class_space_list = new VirtualSpaceList(rs);
  2589 void Metaspace::initialize(Mutex* lock,
  2590                            MetaspaceType type) {
  2592   assert(space_list() != NULL,
  2593     "Metadata VirtualSpaceList has not been initialized");
  2595   _vsm = new SpaceManager(lock, space_list());
  2596   if (_vsm == NULL) {
  2597     return;
  2599   size_t word_size;
  2600   size_t class_word_size;
  2601   vsm()->get_initial_chunk_sizes(type,
  2602                                  &word_size,
  2603                                  &class_word_size);
  2605   assert(class_space_list() != NULL,
  2606     "Class VirtualSpaceList has not been initialized");
  2608   // Allocate SpaceManager for classes.
  2609   _class_vsm = new SpaceManager(lock, class_space_list());
  2610   if (_class_vsm == NULL) {
  2611     return;
  2614   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  2616   // Allocate chunk for metadata objects
  2617   Metachunk* new_chunk =
  2618      space_list()->get_initialization_chunk(word_size,
  2619                                             vsm()->medium_chunk_bunch());
  2620   assert(!DumpSharedSpaces || new_chunk != NULL, "should have enough space for both chunks");
  2621   if (new_chunk != NULL) {
  2622     // Add to this manager's list of chunks in use and current_chunk().
  2623     vsm()->add_chunk(new_chunk, true);
  2626   // Allocate chunk for class metadata objects
  2627   Metachunk* class_chunk =
  2628      class_space_list()->get_initialization_chunk(class_word_size,
  2629                                                   class_vsm()->medium_chunk_bunch());
  2630   if (class_chunk != NULL) {
  2631     class_vsm()->add_chunk(class_chunk, true);
  2635 size_t Metaspace::align_word_size_up(size_t word_size) {
  2636   size_t byte_size = word_size * wordSize;
  2637   return ReservedSpace::allocation_align_size_up(byte_size) / wordSize;
  2640 MetaWord* Metaspace::allocate(size_t word_size, MetadataType mdtype) {
  2641   // DumpSharedSpaces doesn't use class metadata area (yet)
  2642   if (mdtype == ClassType && !DumpSharedSpaces) {
  2643     return  class_vsm()->allocate(word_size);
  2644   } else {
  2645     return  vsm()->allocate(word_size);
  2649 MetaWord* Metaspace::expand_and_allocate(size_t word_size, MetadataType mdtype) {
  2650   MetaWord* result;
  2651   MetaspaceGC::set_expand_after_GC(true);
  2652   size_t before_inc = MetaspaceGC::capacity_until_GC();
  2653   size_t delta_words = MetaspaceGC::delta_capacity_until_GC(word_size);
  2654   MetaspaceGC::inc_capacity_until_GC(delta_words);
  2655   if (PrintGCDetails && Verbose) {
  2656     gclog_or_tty->print_cr("Increase capacity to GC from " SIZE_FORMAT
  2657       " to " SIZE_FORMAT, before_inc, MetaspaceGC::capacity_until_GC());
  2660   result = allocate(word_size, mdtype);
  2662   return result;
  2665 // Space allocated in the Metaspace.  This may
  2666 // be across several metadata virtual spaces.
  2667 char* Metaspace::bottom() const {
  2668   assert(DumpSharedSpaces, "only useful and valid for dumping shared spaces");
  2669   return (char*)vsm()->current_chunk()->bottom();
  2672 size_t Metaspace::used_words(MetadataType mdtype) const {
  2673   // return vsm()->allocation_total();
  2674   return mdtype == ClassType ? class_vsm()->sum_used_in_chunks_in_use() :
  2675                                vsm()->sum_used_in_chunks_in_use();  // includes overhead!
  2678 size_t Metaspace::free_words(MetadataType mdtype) const {
  2679   return mdtype == ClassType ? class_vsm()->sum_free_in_chunks_in_use() :
  2680                                vsm()->sum_free_in_chunks_in_use();
  2683 // Space capacity in the Metaspace.  It includes
  2684 // space in the list of chunks from which allocations
  2685 // have been made. Don't include space in the global freelist and
  2686 // in the space available in the dictionary which
  2687 // is already counted in some chunk.
  2688 size_t Metaspace::capacity_words(MetadataType mdtype) const {
  2689   return mdtype == ClassType ? class_vsm()->sum_capacity_in_chunks_in_use() :
  2690                                vsm()->sum_capacity_in_chunks_in_use();
  2693 void Metaspace::deallocate(MetaWord* ptr, size_t word_size, bool is_class) {
  2694   if (SafepointSynchronize::is_at_safepoint()) {
  2695     assert(Thread::current()->is_VM_thread(), "should be the VM thread");
  2696     // Don't take Heap_lock
  2697     MutexLocker ml(vsm()->lock());
  2698     if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
  2699       // Dark matter.  Too small for dictionary.
  2700 #ifdef ASSERT
  2701       Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
  2702 #endif
  2703       return;
  2705     if (is_class) {
  2706        class_vsm()->deallocate(ptr, word_size);
  2707     } else {
  2708       vsm()->deallocate(ptr, word_size);
  2710   } else {
  2711     MutexLocker ml(vsm()->lock());
  2713     if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
  2714       // Dark matter.  Too small for dictionary.
  2715 #ifdef ASSERT
  2716       Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
  2717 #endif
  2718       return;
  2720     if (is_class) {
  2721       class_vsm()->deallocate(ptr, word_size);
  2722     } else {
  2723       vsm()->deallocate(ptr, word_size);
  2728 Metablock* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size,
  2729                               bool read_only, MetadataType mdtype, TRAPS) {
  2730   if (HAS_PENDING_EXCEPTION) {
  2731     assert(false, "Should not allocate with exception pending");
  2732     return NULL;  // caller does a CHECK_NULL too
  2735   // SSS: Should we align the allocations and make sure the sizes are aligned.
  2736   MetaWord* result = NULL;
  2738   assert(loader_data != NULL, "Should never pass around a NULL loader_data. "
  2739         "ClassLoaderData::the_null_class_loader_data() should have been used.");
  2740   // Allocate in metaspaces without taking out a lock, because it deadlocks
  2741   // with the SymbolTable_lock.  Dumping is single threaded for now.  We'll have
  2742   // to revisit this for application class data sharing.
  2743   if (DumpSharedSpaces) {
  2744     if (read_only) {
  2745       result = loader_data->ro_metaspace()->allocate(word_size, NonClassType);
  2746     } else {
  2747       result = loader_data->rw_metaspace()->allocate(word_size, NonClassType);
  2749     if (result == NULL) {
  2750       report_out_of_shared_space(read_only ? SharedReadOnly : SharedReadWrite);
  2752     return Metablock::initialize(result, word_size);
  2755   result = loader_data->metaspace_non_null()->allocate(word_size, mdtype);
  2757   if (result == NULL) {
  2758     // Try to clean out some memory and retry.
  2759     result =
  2760       Universe::heap()->collector_policy()->satisfy_failed_metadata_allocation(
  2761         loader_data, word_size, mdtype);
  2763     // If result is still null, we are out of memory.
  2764     if (result == NULL) {
  2765       if (Verbose && TraceMetadataChunkAllocation) {
  2766         gclog_or_tty->print_cr("Metaspace allocation failed for size "
  2767           SIZE_FORMAT, word_size);
  2768         if (loader_data->metaspace_or_null() != NULL) loader_data->metaspace_or_null()->dump(gclog_or_tty);
  2769         MetaspaceAux::dump(gclog_or_tty);
  2771       // -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support
  2772       report_java_out_of_memory("Metadata space");
  2774       if (JvmtiExport::should_post_resource_exhausted()) {
  2775         JvmtiExport::post_resource_exhausted(
  2776             JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR,
  2777             "Metadata space");
  2779       THROW_OOP_0(Universe::out_of_memory_error_perm_gen());
  2782   return Metablock::initialize(result, word_size);
  2785 void Metaspace::print_on(outputStream* out) const {
  2786   // Print both class virtual space counts and metaspace.
  2787   if (Verbose) {
  2788       vsm()->print_on(out);
  2789       class_vsm()->print_on(out);
  2793 bool Metaspace::contains(const void * ptr) {
  2794   if (MetaspaceShared::is_in_shared_space(ptr)) {
  2795     return true;
  2797   // This is checked while unlocked.  As long as the virtualspaces are added
  2798   // at the end, the pointer will be in one of them.  The virtual spaces
  2799   // aren't deleted presently.  When they are, some sort of locking might
  2800   // be needed.  Note, locking this can cause inversion problems with the
  2801   // caller in MetaspaceObj::is_metadata() function.
  2802   return space_list()->contains(ptr) || class_space_list()->contains(ptr);
  2805 void Metaspace::verify() {
  2806   vsm()->verify();
  2807   class_vsm()->verify();
  2810 void Metaspace::dump(outputStream* const out) const {
  2811   if (UseMallocOnly) {
  2812     // Just print usage for now
  2813     out->print_cr("usage %d", used_words(Metaspace::NonClassType));
  2815   out->print_cr("\nVirtual space manager: " INTPTR_FORMAT, vsm());
  2816   vsm()->dump(out);
  2817   out->print_cr("\nClass space manager: " INTPTR_FORMAT, class_vsm());
  2818   class_vsm()->dump(out);

mercurial