src/share/vm/memory/metaspace.cpp

Wed, 11 Sep 2013 09:37:14 +0200

author
mgerdin
date
Wed, 11 Sep 2013 09:37:14 +0200
changeset 5699
24e87613ee58
parent 5694
7944aba7ba41
child 5703
d6c266999345
permissions
-rw-r--r--

8009561: NPG: Metaspace fragmentation when retiring a Metachunk
Summary: Use best-fit block-splitting freelist allocation from the block freelist.
Reviewed-by: jmasa, stefank

     1 /*
     2  * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    24 #include "precompiled.hpp"
    25 #include "gc_interface/collectedHeap.hpp"
    26 #include "memory/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/java.hpp"
    39 #include "runtime/mutex.hpp"
    40 #include "runtime/orderAccess.hpp"
    41 #include "services/memTracker.hpp"
    42 #include "utilities/copy.hpp"
    43 #include "utilities/debug.hpp"
    45 typedef BinaryTreeDictionary<Metablock, FreeList> BlockTreeDictionary;
    46 typedef BinaryTreeDictionary<Metachunk, FreeList> ChunkTreeDictionary;
    47 // Define this macro to enable slow integrity checking of
    48 // the free chunk lists
    49 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 = 4 * K;
    56 MetaWord* last_allocated = 0;
    58 size_t Metaspace::_class_metaspace_size;
    60 // Used in declarations in SpaceManager and ChunkManager
    61 enum ChunkIndex {
    62   ZeroIndex = 0,
    63   SpecializedIndex = ZeroIndex,
    64   SmallIndex = SpecializedIndex + 1,
    65   MediumIndex = SmallIndex + 1,
    66   HumongousIndex = MediumIndex + 1,
    67   NumberOfFreeLists = 3,
    68   NumberOfInUseLists = 4
    69 };
    71 enum ChunkSizes {    // in words.
    72   ClassSpecializedChunk = 128,
    73   SpecializedChunk = 128,
    74   ClassSmallChunk = 256,
    75   SmallChunk = 512,
    76   ClassMediumChunk = 4 * K,
    77   MediumChunk = 8 * K,
    78   HumongousChunkGranularity = 8
    79 };
    81 static ChunkIndex next_chunk_index(ChunkIndex i) {
    82   assert(i < NumberOfInUseLists, "Out of bound");
    83   return (ChunkIndex) (i+1);
    84 }
    86 // Originally _capacity_until_GC was set to MetaspaceSize here but
    87 // the default MetaspaceSize before argument processing was being
    88 // used which was not the desired value.  See the code
    89 // in should_expand() to see how the initialization is handled
    90 // now.
    91 size_t MetaspaceGC::_capacity_until_GC = 0;
    92 bool MetaspaceGC::_expand_after_GC = false;
    93 uint MetaspaceGC::_shrink_factor = 0;
    94 bool MetaspaceGC::_should_concurrent_collect = false;
    96 // Blocks of space for metadata are allocated out of Metachunks.
    97 //
    98 // Metachunk are allocated out of MetadataVirtualspaces and once
    99 // allocated there is no explicit link between a Metachunk and
   100 // the MetadataVirtualspaces from which it was allocated.
   101 //
   102 // Each SpaceManager maintains a
   103 // list of the chunks it is using and the current chunk.  The current
   104 // chunk is the chunk from which allocations are done.  Space freed in
   105 // a chunk is placed on the free list of blocks (BlockFreelist) and
   106 // reused from there.
   108 typedef class FreeList<Metachunk> ChunkList;
   110 // Manages the global free lists of chunks.
   111 // Has three lists of free chunks, and a total size and
   112 // count that includes all three
   114 class ChunkManager VALUE_OBJ_CLASS_SPEC {
   116   // Free list of chunks of different sizes.
   117   //   SpecializedChunk
   118   //   SmallChunk
   119   //   MediumChunk
   120   //   HumongousChunk
   121   ChunkList _free_chunks[NumberOfFreeLists];
   124   //   HumongousChunk
   125   ChunkTreeDictionary _humongous_dictionary;
   127   // ChunkManager in all lists of this type
   128   size_t _free_chunks_total;
   129   size_t _free_chunks_count;
   131   void dec_free_chunks_total(size_t v) {
   132     assert(_free_chunks_count > 0 &&
   133              _free_chunks_total > 0,
   134              "About to go negative");
   135     Atomic::add_ptr(-1, &_free_chunks_count);
   136     jlong minus_v = (jlong) - (jlong) v;
   137     Atomic::add_ptr(minus_v, &_free_chunks_total);
   138   }
   140   // Debug support
   142   size_t sum_free_chunks();
   143   size_t sum_free_chunks_count();
   145   void locked_verify_free_chunks_total();
   146   void slow_locked_verify_free_chunks_total() {
   147     if (metaspace_slow_verify) {
   148       locked_verify_free_chunks_total();
   149     }
   150   }
   151   void locked_verify_free_chunks_count();
   152   void slow_locked_verify_free_chunks_count() {
   153     if (metaspace_slow_verify) {
   154       locked_verify_free_chunks_count();
   155     }
   156   }
   157   void verify_free_chunks_count();
   159  public:
   161   ChunkManager() : _free_chunks_total(0), _free_chunks_count(0) {}
   163   // add or delete (return) a chunk to the global freelist.
   164   Metachunk* chunk_freelist_allocate(size_t word_size);
   165   void chunk_freelist_deallocate(Metachunk* chunk);
   167   // Map a size to a list index assuming that there are lists
   168   // for special, small, medium, and humongous chunks.
   169   static ChunkIndex list_index(size_t size);
   171   // Remove the chunk from its freelist.  It is
   172   // expected to be on one of the _free_chunks[] lists.
   173   void remove_chunk(Metachunk* chunk);
   175   // Add the simple linked list of chunks to the freelist of chunks
   176   // of type index.
   177   void return_chunks(ChunkIndex index, Metachunk* chunks);
   179   // Total of the space in the free chunks list
   180   size_t free_chunks_total();
   181   size_t free_chunks_total_in_bytes();
   183   // Number of chunks in the free chunks list
   184   size_t free_chunks_count();
   186   void inc_free_chunks_total(size_t v, size_t count = 1) {
   187     Atomic::add_ptr(count, &_free_chunks_count);
   188     Atomic::add_ptr(v, &_free_chunks_total);
   189   }
   190   ChunkTreeDictionary* humongous_dictionary() {
   191     return &_humongous_dictionary;
   192   }
   194   ChunkList* free_chunks(ChunkIndex index);
   196   // Returns the list for the given chunk word size.
   197   ChunkList* find_free_chunks_list(size_t word_size);
   199   // Add and remove from a list by size.  Selects
   200   // list based on size of chunk.
   201   void free_chunks_put(Metachunk* chuck);
   202   Metachunk* free_chunks_get(size_t chunk_word_size);
   204   // Debug support
   205   void verify();
   206   void slow_verify() {
   207     if (metaspace_slow_verify) {
   208       verify();
   209     }
   210   }
   211   void locked_verify();
   212   void slow_locked_verify() {
   213     if (metaspace_slow_verify) {
   214       locked_verify();
   215     }
   216   }
   217   void verify_free_chunks_total();
   219   void locked_print_free_chunks(outputStream* st);
   220   void locked_print_sum_free_chunks(outputStream* st);
   222   void print_on(outputStream* st);
   223 };
   225 // Used to manage the free list of Metablocks (a block corresponds
   226 // to the allocation of a quantum of metadata).
   227 class BlockFreelist VALUE_OBJ_CLASS_SPEC {
   228   BlockTreeDictionary* _dictionary;
   229   static Metablock* initialize_free_chunk(MetaWord* p, size_t word_size);
   231   // Only allocate and split from freelist if the size of the allocation
   232   // is at least 1/4th the size of the available block.
   233   const static int WasteMultiplier = 4;
   235   // Accessors
   236   BlockTreeDictionary* dictionary() const { return _dictionary; }
   238  public:
   239   BlockFreelist();
   240   ~BlockFreelist();
   242   // Get and return a block to the free list
   243   MetaWord* get_block(size_t word_size);
   244   void return_block(MetaWord* p, size_t word_size);
   246   size_t total_size() {
   247   if (dictionary() == NULL) {
   248     return 0;
   249   } else {
   250     return dictionary()->total_size();
   251   }
   252 }
   254   void print_on(outputStream* st) const;
   255 };
   257 class VirtualSpaceNode : public CHeapObj<mtClass> {
   258   friend class VirtualSpaceList;
   260   // Link to next VirtualSpaceNode
   261   VirtualSpaceNode* _next;
   263   // total in the VirtualSpace
   264   MemRegion _reserved;
   265   ReservedSpace _rs;
   266   VirtualSpace _virtual_space;
   267   MetaWord* _top;
   268   // count of chunks contained in this VirtualSpace
   269   uintx _container_count;
   271   // Convenience functions to access the _virtual_space
   272   char* low()  const { return virtual_space()->low(); }
   273   char* high() const { return virtual_space()->high(); }
   275   // The first Metachunk will be allocated at the bottom of the
   276   // VirtualSpace
   277   Metachunk* first_chunk() { return (Metachunk*) bottom(); }
   279   void inc_container_count();
   280 #ifdef ASSERT
   281   uint container_count_slow();
   282 #endif
   284  public:
   286   VirtualSpaceNode(size_t byte_size);
   287   VirtualSpaceNode(ReservedSpace rs) : _top(NULL), _next(NULL), _rs(rs), _container_count(0) {}
   288   ~VirtualSpaceNode();
   290   // Convenience functions for logical bottom and end
   291   MetaWord* bottom() const { return (MetaWord*) _virtual_space.low(); }
   292   MetaWord* end() const { return (MetaWord*) _virtual_space.high(); }
   294   // address of next available space in _virtual_space;
   295   // Accessors
   296   VirtualSpaceNode* next() { return _next; }
   297   void set_next(VirtualSpaceNode* v) { _next = v; }
   299   void set_reserved(MemRegion const v) { _reserved = v; }
   300   void set_top(MetaWord* v) { _top = v; }
   302   // Accessors
   303   MemRegion* reserved() { return &_reserved; }
   304   VirtualSpace* virtual_space() const { return (VirtualSpace*) &_virtual_space; }
   306   // Returns true if "word_size" is available in the VirtualSpace
   307   bool is_available(size_t word_size) { return _top + word_size <= end(); }
   309   MetaWord* top() const { return _top; }
   310   void inc_top(size_t word_size) { _top += word_size; }
   312   uintx container_count() { return _container_count; }
   313   void dec_container_count();
   314 #ifdef ASSERT
   315   void verify_container_count();
   316 #endif
   318   // used and capacity in this single entry in the list
   319   size_t used_words_in_vs() const;
   320   size_t capacity_words_in_vs() const;
   321   size_t free_words_in_vs() const;
   323   bool initialize();
   325   // get space from the virtual space
   326   Metachunk* take_from_committed(size_t chunk_word_size);
   328   // Allocate a chunk from the virtual space and return it.
   329   Metachunk* get_chunk_vs(size_t chunk_word_size);
   330   Metachunk* get_chunk_vs_with_expand(size_t chunk_word_size);
   332   // Expands/shrinks the committed space in a virtual space.  Delegates
   333   // to Virtualspace
   334   bool expand_by(size_t words, bool pre_touch = false);
   335   bool shrink_by(size_t words);
   337   // In preparation for deleting this node, remove all the chunks
   338   // in the node from any freelist.
   339   void purge(ChunkManager* chunk_manager);
   341 #ifdef ASSERT
   342   // Debug support
   343   static void verify_virtual_space_total();
   344   static void verify_virtual_space_count();
   345   void mangle();
   346 #endif
   348   void print_on(outputStream* st) const;
   349 };
   351   // byte_size is the size of the associated virtualspace.
   352 VirtualSpaceNode::VirtualSpaceNode(size_t byte_size) : _top(NULL), _next(NULL), _rs(), _container_count(0) {
   353   // align up to vm allocation granularity
   354   byte_size = align_size_up(byte_size, os::vm_allocation_granularity());
   356   // This allocates memory with mmap.  For DumpSharedspaces, try to reserve
   357   // configurable address, generally at the top of the Java heap so other
   358   // memory addresses don't conflict.
   359   if (DumpSharedSpaces) {
   360     char* shared_base = (char*)SharedBaseAddress;
   361     _rs = ReservedSpace(byte_size, 0, false, shared_base, 0);
   362     if (_rs.is_reserved()) {
   363       assert(shared_base == 0 || _rs.base() == shared_base, "should match");
   364     } else {
   365       // Get a mmap region anywhere if the SharedBaseAddress fails.
   366       _rs = ReservedSpace(byte_size);
   367     }
   368     MetaspaceShared::set_shared_rs(&_rs);
   369   } else {
   370     _rs = ReservedSpace(byte_size);
   371   }
   373   MemTracker::record_virtual_memory_type((address)_rs.base(), mtClass);
   374 }
   376 void VirtualSpaceNode::purge(ChunkManager* chunk_manager) {
   377   Metachunk* chunk = first_chunk();
   378   Metachunk* invalid_chunk = (Metachunk*) top();
   379   while (chunk < invalid_chunk ) {
   380     assert(chunk->is_free(), "Should be marked free");
   381       MetaWord* next = ((MetaWord*)chunk) + chunk->word_size();
   382       chunk_manager->remove_chunk(chunk);
   383       assert(chunk->next() == NULL &&
   384              chunk->prev() == NULL,
   385              "Was not removed from its list");
   386       chunk = (Metachunk*) next;
   387   }
   388 }
   390 #ifdef ASSERT
   391 uint VirtualSpaceNode::container_count_slow() {
   392   uint count = 0;
   393   Metachunk* chunk = first_chunk();
   394   Metachunk* invalid_chunk = (Metachunk*) top();
   395   while (chunk < invalid_chunk ) {
   396     MetaWord* next = ((MetaWord*)chunk) + chunk->word_size();
   397     // Don't count the chunks on the free lists.  Those are
   398     // still part of the VirtualSpaceNode but not currently
   399     // counted.
   400     if (!chunk->is_free()) {
   401       count++;
   402     }
   403     chunk = (Metachunk*) next;
   404   }
   405   return count;
   406 }
   407 #endif
   409 // List of VirtualSpaces for metadata allocation.
   410 // It has a  _next link for singly linked list and a MemRegion
   411 // for total space in the VirtualSpace.
   412 class VirtualSpaceList : public CHeapObj<mtClass> {
   413   friend class VirtualSpaceNode;
   415   enum VirtualSpaceSizes {
   416     VirtualSpaceSize = 256 * K
   417   };
   419   // Global list of virtual spaces
   420   // Head of the list
   421   VirtualSpaceNode* _virtual_space_list;
   422   // virtual space currently being used for allocations
   423   VirtualSpaceNode* _current_virtual_space;
   424   // Free chunk list for all other metadata
   425   ChunkManager      _chunk_manager;
   427   // Can this virtual list allocate >1 spaces?  Also, used to determine
   428   // whether to allocate unlimited small chunks in this virtual space
   429   bool _is_class;
   430   bool can_grow() const { return !is_class() || !UseCompressedClassPointers; }
   432   // Sum of space in all virtual spaces and number of virtual spaces
   433   size_t _virtual_space_total;
   434   size_t _virtual_space_count;
   436   ~VirtualSpaceList();
   438   VirtualSpaceNode* virtual_space_list() const { return _virtual_space_list; }
   440   void set_virtual_space_list(VirtualSpaceNode* v) {
   441     _virtual_space_list = v;
   442   }
   443   void set_current_virtual_space(VirtualSpaceNode* v) {
   444     _current_virtual_space = v;
   445   }
   447   void link_vs(VirtualSpaceNode* new_entry, size_t vs_word_size);
   449   // Get another virtual space and add it to the list.  This
   450   // is typically prompted by a failed attempt to allocate a chunk
   451   // and is typically followed by the allocation of a chunk.
   452   bool grow_vs(size_t vs_word_size);
   454  public:
   455   VirtualSpaceList(size_t word_size);
   456   VirtualSpaceList(ReservedSpace rs);
   458   size_t free_bytes();
   460   Metachunk* get_new_chunk(size_t word_size,
   461                            size_t grow_chunks_by_words,
   462                            size_t medium_chunk_bunch);
   464   // Get the first chunk for a Metaspace.  Used for
   465   // special cases such as the boot class loader, reflection
   466   // class loader and anonymous class loader.
   467   Metachunk* get_initialization_chunk(size_t word_size, size_t chunk_bunch);
   469   VirtualSpaceNode* current_virtual_space() {
   470     return _current_virtual_space;
   471   }
   473   ChunkManager* chunk_manager() { return &_chunk_manager; }
   474   bool is_class() const { return _is_class; }
   476   // Allocate the first virtualspace.
   477   void initialize(size_t word_size);
   479   size_t virtual_space_total() { return _virtual_space_total; }
   481   void inc_virtual_space_total(size_t v);
   482   void dec_virtual_space_total(size_t v);
   483   void inc_virtual_space_count();
   484   void dec_virtual_space_count();
   486   // Unlink empty VirtualSpaceNodes and free it.
   487   void purge();
   489   // Used and capacity in the entire list of virtual spaces.
   490   // These are global values shared by all Metaspaces
   491   size_t capacity_words_sum();
   492   size_t capacity_bytes_sum() { return capacity_words_sum() * BytesPerWord; }
   493   size_t used_words_sum();
   494   size_t used_bytes_sum() { return used_words_sum() * BytesPerWord; }
   496   bool contains(const void *ptr);
   498   void print_on(outputStream* st) const;
   500   class VirtualSpaceListIterator : public StackObj {
   501     VirtualSpaceNode* _virtual_spaces;
   502    public:
   503     VirtualSpaceListIterator(VirtualSpaceNode* virtual_spaces) :
   504       _virtual_spaces(virtual_spaces) {}
   506     bool repeat() {
   507       return _virtual_spaces != NULL;
   508     }
   510     VirtualSpaceNode* get_next() {
   511       VirtualSpaceNode* result = _virtual_spaces;
   512       if (_virtual_spaces != NULL) {
   513         _virtual_spaces = _virtual_spaces->next();
   514       }
   515       return result;
   516     }
   517   };
   518 };
   520 class Metadebug : AllStatic {
   521   // Debugging support for Metaspaces
   522   static int _deallocate_block_a_lot_count;
   523   static int _deallocate_chunk_a_lot_count;
   524   static int _allocation_fail_alot_count;
   526  public:
   527   static int deallocate_block_a_lot_count() {
   528     return _deallocate_block_a_lot_count;
   529   }
   530   static void set_deallocate_block_a_lot_count(int v) {
   531     _deallocate_block_a_lot_count = v;
   532   }
   533   static void inc_deallocate_block_a_lot_count() {
   534     _deallocate_block_a_lot_count++;
   535   }
   536   static int deallocate_chunk_a_lot_count() {
   537     return _deallocate_chunk_a_lot_count;
   538   }
   539   static void reset_deallocate_chunk_a_lot_count() {
   540     _deallocate_chunk_a_lot_count = 1;
   541   }
   542   static void inc_deallocate_chunk_a_lot_count() {
   543     _deallocate_chunk_a_lot_count++;
   544   }
   546   static void init_allocation_fail_alot_count();
   547 #ifdef ASSERT
   548   static bool test_metadata_failure();
   549 #endif
   551   static void deallocate_chunk_a_lot(SpaceManager* sm,
   552                                      size_t chunk_word_size);
   553   static void deallocate_block_a_lot(SpaceManager* sm,
   554                                      size_t chunk_word_size);
   556 };
   558 int Metadebug::_deallocate_block_a_lot_count = 0;
   559 int Metadebug::_deallocate_chunk_a_lot_count = 0;
   560 int Metadebug::_allocation_fail_alot_count = 0;
   562 //  SpaceManager - used by Metaspace to handle allocations
   563 class SpaceManager : public CHeapObj<mtClass> {
   564   friend class Metaspace;
   565   friend class Metadebug;
   567  private:
   569   // protects allocations and contains.
   570   Mutex* const _lock;
   572   // Type of metadata allocated.
   573   Metaspace::MetadataType _mdtype;
   575   // Chunk related size
   576   size_t _medium_chunk_bunch;
   578   // List of chunks in use by this SpaceManager.  Allocations
   579   // are done from the current chunk.  The list is used for deallocating
   580   // chunks when the SpaceManager is freed.
   581   Metachunk* _chunks_in_use[NumberOfInUseLists];
   582   Metachunk* _current_chunk;
   584   // Virtual space where allocation comes from.
   585   VirtualSpaceList* _vs_list;
   587   // Number of small chunks to allocate to a manager
   588   // If class space manager, small chunks are unlimited
   589   static uint const _small_chunk_limit;
   591   // Sum of all space in allocated chunks
   592   size_t _allocated_blocks_words;
   594   // Sum of all allocated chunks
   595   size_t _allocated_chunks_words;
   596   size_t _allocated_chunks_count;
   598   // Free lists of blocks are per SpaceManager since they
   599   // are assumed to be in chunks in use by the SpaceManager
   600   // and all chunks in use by a SpaceManager are freed when
   601   // the class loader using the SpaceManager is collected.
   602   BlockFreelist _block_freelists;
   604   // protects virtualspace and chunk expansions
   605   static const char*  _expand_lock_name;
   606   static const int    _expand_lock_rank;
   607   static Mutex* const _expand_lock;
   609  private:
   610   // Accessors
   611   Metachunk* chunks_in_use(ChunkIndex index) const { return _chunks_in_use[index]; }
   612   void set_chunks_in_use(ChunkIndex index, Metachunk* v) { _chunks_in_use[index] = v; }
   614   BlockFreelist* block_freelists() const {
   615     return (BlockFreelist*) &_block_freelists;
   616   }
   618   Metaspace::MetadataType mdtype() { return _mdtype; }
   619   VirtualSpaceList* vs_list() const    { return _vs_list; }
   621   Metachunk* current_chunk() const { return _current_chunk; }
   622   void set_current_chunk(Metachunk* v) {
   623     _current_chunk = v;
   624   }
   626   Metachunk* find_current_chunk(size_t word_size);
   628   // Add chunk to the list of chunks in use
   629   void add_chunk(Metachunk* v, bool make_current);
   630   void retire_current_chunk();
   632   Mutex* lock() const { return _lock; }
   634   const char* chunk_size_name(ChunkIndex index) const;
   636  protected:
   637   void initialize();
   639  public:
   640   SpaceManager(Metaspace::MetadataType mdtype,
   641                Mutex* lock,
   642                VirtualSpaceList* vs_list);
   643   ~SpaceManager();
   645   enum ChunkMultiples {
   646     MediumChunkMultiple = 4
   647   };
   649   // Accessors
   650   size_t specialized_chunk_size() { return SpecializedChunk; }
   651   size_t small_chunk_size() { return (size_t) vs_list()->is_class() ? ClassSmallChunk : SmallChunk; }
   652   size_t medium_chunk_size() { return (size_t) vs_list()->is_class() ? ClassMediumChunk : MediumChunk; }
   653   size_t medium_chunk_bunch() { return medium_chunk_size() * MediumChunkMultiple; }
   655   size_t allocated_blocks_words() const { return _allocated_blocks_words; }
   656   size_t allocated_blocks_bytes() const { return _allocated_blocks_words * BytesPerWord; }
   657   size_t allocated_chunks_words() const { return _allocated_chunks_words; }
   658   size_t allocated_chunks_count() const { return _allocated_chunks_count; }
   660   bool is_humongous(size_t word_size) { return word_size > medium_chunk_size(); }
   662   static Mutex* expand_lock() { return _expand_lock; }
   664   // Increment the per Metaspace and global running sums for Metachunks
   665   // by the given size.  This is used when a Metachunk to added to
   666   // the in-use list.
   667   void inc_size_metrics(size_t words);
   668   // Increment the per Metaspace and global running sums Metablocks by the given
   669   // size.  This is used when a Metablock is allocated.
   670   void inc_used_metrics(size_t words);
   671   // Delete the portion of the running sums for this SpaceManager. That is,
   672   // the globals running sums for the Metachunks and Metablocks are
   673   // decremented for all the Metachunks in-use by this SpaceManager.
   674   void dec_total_from_size_metrics();
   676   // Set the sizes for the initial chunks.
   677   void get_initial_chunk_sizes(Metaspace::MetaspaceType type,
   678                                size_t* chunk_word_size,
   679                                size_t* class_chunk_word_size);
   681   size_t sum_capacity_in_chunks_in_use() const;
   682   size_t sum_used_in_chunks_in_use() const;
   683   size_t sum_free_in_chunks_in_use() const;
   684   size_t sum_waste_in_chunks_in_use() const;
   685   size_t sum_waste_in_chunks_in_use(ChunkIndex index ) const;
   687   size_t sum_count_in_chunks_in_use();
   688   size_t sum_count_in_chunks_in_use(ChunkIndex i);
   690   Metachunk* get_new_chunk(size_t word_size, size_t grow_chunks_by_words);
   692   // Block allocation and deallocation.
   693   // Allocates a block from the current chunk
   694   MetaWord* allocate(size_t word_size);
   696   // Helper for allocations
   697   MetaWord* allocate_work(size_t word_size);
   699   // Returns a block to the per manager freelist
   700   void deallocate(MetaWord* p, size_t word_size);
   702   // Based on the allocation size and a minimum chunk size,
   703   // returned chunk size (for expanding space for chunk allocation).
   704   size_t calc_chunk_size(size_t allocation_word_size);
   706   // Called when an allocation from the current chunk fails.
   707   // Gets a new chunk (may require getting a new virtual space),
   708   // and allocates from that chunk.
   709   MetaWord* grow_and_allocate(size_t word_size);
   711   // debugging support.
   713   void dump(outputStream* const out) const;
   714   void print_on(outputStream* st) const;
   715   void locked_print_chunks_in_use_on(outputStream* st) const;
   717   void verify();
   718   void verify_chunk_size(Metachunk* chunk);
   719   NOT_PRODUCT(void mangle_freed_chunks();)
   720 #ifdef ASSERT
   721   void verify_allocated_blocks_words();
   722 #endif
   724   size_t get_raw_word_size(size_t word_size) {
   725     // If only the dictionary is going to be used (i.e., no
   726     // indexed free list), then there is a minimum size requirement.
   727     // MinChunkSize is a placeholder for the real minimum size JJJ
   728     size_t byte_size = word_size * BytesPerWord;
   730     size_t byte_size_with_overhead = byte_size + Metablock::overhead();
   732     size_t raw_bytes_size = MAX2(byte_size_with_overhead,
   733                                  Metablock::min_block_byte_size());
   734     raw_bytes_size = ARENA_ALIGN(raw_bytes_size);
   735     size_t raw_word_size = raw_bytes_size / BytesPerWord;
   736     assert(raw_word_size * BytesPerWord == raw_bytes_size, "Size problem");
   738     return raw_word_size;
   739   }
   740 };
   742 uint const SpaceManager::_small_chunk_limit = 4;
   744 const char* SpaceManager::_expand_lock_name =
   745   "SpaceManager chunk allocation lock";
   746 const int SpaceManager::_expand_lock_rank = Monitor::leaf - 1;
   747 Mutex* const SpaceManager::_expand_lock =
   748   new Mutex(SpaceManager::_expand_lock_rank,
   749             SpaceManager::_expand_lock_name,
   750             Mutex::_allow_vm_block_flag);
   752 void VirtualSpaceNode::inc_container_count() {
   753   assert_lock_strong(SpaceManager::expand_lock());
   754   _container_count++;
   755   assert(_container_count == container_count_slow(),
   756          err_msg("Inconsistency in countainer_count _container_count " SIZE_FORMAT
   757                  "container_count_slow() " SIZE_FORMAT,
   758                  _container_count, container_count_slow()));
   759 }
   761 void VirtualSpaceNode::dec_container_count() {
   762   assert_lock_strong(SpaceManager::expand_lock());
   763   _container_count--;
   764 }
   766 #ifdef ASSERT
   767 void VirtualSpaceNode::verify_container_count() {
   768   assert(_container_count == container_count_slow(),
   769     err_msg("Inconsistency in countainer_count _container_count " SIZE_FORMAT
   770             "container_count_slow() " SIZE_FORMAT, _container_count, container_count_slow()));
   771 }
   772 #endif
   774 // BlockFreelist methods
   776 BlockFreelist::BlockFreelist() : _dictionary(NULL) {}
   778 BlockFreelist::~BlockFreelist() {
   779   if (_dictionary != NULL) {
   780     if (Verbose && TraceMetadataChunkAllocation) {
   781       _dictionary->print_free_lists(gclog_or_tty);
   782     }
   783     delete _dictionary;
   784   }
   785 }
   787 Metablock* BlockFreelist::initialize_free_chunk(MetaWord* p, size_t word_size) {
   788   Metablock* block = (Metablock*) p;
   789   block->set_word_size(word_size);
   790   block->set_prev(NULL);
   791   block->set_next(NULL);
   793   return block;
   794 }
   796 void BlockFreelist::return_block(MetaWord* p, size_t word_size) {
   797   Metablock* free_chunk = initialize_free_chunk(p, word_size);
   798   if (dictionary() == NULL) {
   799    _dictionary = new BlockTreeDictionary();
   800   }
   801   dictionary()->return_chunk(free_chunk);
   802 }
   804 MetaWord* BlockFreelist::get_block(size_t word_size) {
   805   if (dictionary() == NULL) {
   806     return NULL;
   807   }
   809   if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
   810     // Dark matter.  Too small for dictionary.
   811     return NULL;
   812   }
   814   Metablock* free_block =
   815     dictionary()->get_chunk(word_size, FreeBlockDictionary<Metablock>::atLeast);
   816   if (free_block == NULL) {
   817     return NULL;
   818   }
   820   const size_t block_size = free_block->size();
   821   if (block_size > WasteMultiplier * word_size) {
   822     return_block((MetaWord*)free_block, block_size);
   823     return NULL;
   824   }
   826   MetaWord* new_block = (MetaWord*)free_block;
   827   assert(block_size >= word_size, "Incorrect size of block from freelist");
   828   const size_t unused = block_size - word_size;
   829   if (unused >= TreeChunk<Metablock, FreeList>::min_size()) {
   830     return_block(new_block + word_size, unused);
   831   }
   833   return new_block;
   834 }
   836 void BlockFreelist::print_on(outputStream* st) const {
   837   if (dictionary() == NULL) {
   838     return;
   839   }
   840   dictionary()->print_free_lists(st);
   841 }
   843 // VirtualSpaceNode methods
   845 VirtualSpaceNode::~VirtualSpaceNode() {
   846   _rs.release();
   847 #ifdef ASSERT
   848   size_t word_size = sizeof(*this) / BytesPerWord;
   849   Copy::fill_to_words((HeapWord*) this, word_size, 0xf1f1f1f1);
   850 #endif
   851 }
   853 size_t VirtualSpaceNode::used_words_in_vs() const {
   854   return pointer_delta(top(), bottom(), sizeof(MetaWord));
   855 }
   857 // Space committed in the VirtualSpace
   858 size_t VirtualSpaceNode::capacity_words_in_vs() const {
   859   return pointer_delta(end(), bottom(), sizeof(MetaWord));
   860 }
   862 size_t VirtualSpaceNode::free_words_in_vs() const {
   863   return pointer_delta(end(), top(), sizeof(MetaWord));
   864 }
   866 // Allocates the chunk from the virtual space only.
   867 // This interface is also used internally for debugging.  Not all
   868 // chunks removed here are necessarily used for allocation.
   869 Metachunk* VirtualSpaceNode::take_from_committed(size_t chunk_word_size) {
   870   // Bottom of the new chunk
   871   MetaWord* chunk_limit = top();
   872   assert(chunk_limit != NULL, "Not safe to call this method");
   874   if (!is_available(chunk_word_size)) {
   875     if (TraceMetadataChunkAllocation) {
   876       tty->print("VirtualSpaceNode::take_from_committed() not available %d words ", chunk_word_size);
   877       // Dump some information about the virtual space that is nearly full
   878       print_on(tty);
   879     }
   880     return NULL;
   881   }
   883   // Take the space  (bump top on the current virtual space).
   884   inc_top(chunk_word_size);
   886   // Initialize the chunk
   887   Metachunk* result = ::new (chunk_limit) Metachunk(chunk_word_size, this);
   888   return result;
   889 }
   892 // Expand the virtual space (commit more of the reserved space)
   893 bool VirtualSpaceNode::expand_by(size_t words, bool pre_touch) {
   894   size_t bytes = words * BytesPerWord;
   895   bool result =  virtual_space()->expand_by(bytes, pre_touch);
   896   if (TraceMetavirtualspaceAllocation && !result) {
   897     gclog_or_tty->print_cr("VirtualSpaceNode::expand_by() failed "
   898                            "for byte size " SIZE_FORMAT, bytes);
   899     virtual_space()->print();
   900   }
   901   return result;
   902 }
   904 // Shrink the virtual space (commit more of the reserved space)
   905 bool VirtualSpaceNode::shrink_by(size_t words) {
   906   size_t bytes = words * BytesPerWord;
   907   virtual_space()->shrink_by(bytes);
   908   return true;
   909 }
   911 // Add another chunk to the chunk list.
   913 Metachunk* VirtualSpaceNode::get_chunk_vs(size_t chunk_word_size) {
   914   assert_lock_strong(SpaceManager::expand_lock());
   915   Metachunk* result = take_from_committed(chunk_word_size);
   916   if (result != NULL) {
   917     inc_container_count();
   918   }
   919   return result;
   920 }
   922 Metachunk* VirtualSpaceNode::get_chunk_vs_with_expand(size_t chunk_word_size) {
   923   assert_lock_strong(SpaceManager::expand_lock());
   925   Metachunk* new_chunk = get_chunk_vs(chunk_word_size);
   927   if (new_chunk == NULL) {
   928     // Only a small part of the virtualspace is committed when first
   929     // allocated so committing more here can be expected.
   930     size_t page_size_words = os::vm_page_size() / BytesPerWord;
   931     size_t aligned_expand_vs_by_words = align_size_up(chunk_word_size,
   932                                                     page_size_words);
   933     expand_by(aligned_expand_vs_by_words, false);
   934     new_chunk = get_chunk_vs(chunk_word_size);
   935   }
   936   return new_chunk;
   937 }
   939 bool VirtualSpaceNode::initialize() {
   941   if (!_rs.is_reserved()) {
   942     return false;
   943   }
   945   // An allocation out of this Virtualspace that is larger
   946   // than an initial commit size can waste that initial committed
   947   // space.
   948   size_t committed_byte_size = 0;
   949   bool result = virtual_space()->initialize(_rs, committed_byte_size);
   950   if (result) {
   951     set_top((MetaWord*)virtual_space()->low());
   952     set_reserved(MemRegion((HeapWord*)_rs.base(),
   953                  (HeapWord*)(_rs.base() + _rs.size())));
   955     assert(reserved()->start() == (HeapWord*) _rs.base(),
   956       err_msg("Reserved start was not set properly " PTR_FORMAT
   957         " != " PTR_FORMAT, reserved()->start(), _rs.base()));
   958     assert(reserved()->word_size() == _rs.size() / BytesPerWord,
   959       err_msg("Reserved size was not set properly " SIZE_FORMAT
   960         " != " SIZE_FORMAT, reserved()->word_size(),
   961         _rs.size() / BytesPerWord));
   962   }
   964   return result;
   965 }
   967 void VirtualSpaceNode::print_on(outputStream* st) const {
   968   size_t used = used_words_in_vs();
   969   size_t capacity = capacity_words_in_vs();
   970   VirtualSpace* vs = virtual_space();
   971   st->print_cr("   space @ " PTR_FORMAT " " SIZE_FORMAT "K, %3d%% used "
   972            "[" PTR_FORMAT ", " PTR_FORMAT ", "
   973            PTR_FORMAT ", " PTR_FORMAT ")",
   974            vs, capacity / K,
   975            capacity == 0 ? 0 : used * 100 / capacity,
   976            bottom(), top(), end(),
   977            vs->high_boundary());
   978 }
   980 #ifdef ASSERT
   981 void VirtualSpaceNode::mangle() {
   982   size_t word_size = capacity_words_in_vs();
   983   Copy::fill_to_words((HeapWord*) low(), word_size, 0xf1f1f1f1);
   984 }
   985 #endif // ASSERT
   987 // VirtualSpaceList methods
   988 // Space allocated from the VirtualSpace
   990 VirtualSpaceList::~VirtualSpaceList() {
   991   VirtualSpaceListIterator iter(virtual_space_list());
   992   while (iter.repeat()) {
   993     VirtualSpaceNode* vsl = iter.get_next();
   994     delete vsl;
   995   }
   996 }
   998 void VirtualSpaceList::inc_virtual_space_total(size_t v) {
   999   assert_lock_strong(SpaceManager::expand_lock());
  1000   _virtual_space_total = _virtual_space_total + v;
  1002 void VirtualSpaceList::dec_virtual_space_total(size_t v) {
  1003   assert_lock_strong(SpaceManager::expand_lock());
  1004   _virtual_space_total = _virtual_space_total - v;
  1007 void VirtualSpaceList::inc_virtual_space_count() {
  1008   assert_lock_strong(SpaceManager::expand_lock());
  1009   _virtual_space_count++;
  1011 void VirtualSpaceList::dec_virtual_space_count() {
  1012   assert_lock_strong(SpaceManager::expand_lock());
  1013   _virtual_space_count--;
  1016 void ChunkManager::remove_chunk(Metachunk* chunk) {
  1017   size_t word_size = chunk->word_size();
  1018   ChunkIndex index = list_index(word_size);
  1019   if (index != HumongousIndex) {
  1020     free_chunks(index)->remove_chunk(chunk);
  1021   } else {
  1022     humongous_dictionary()->remove_chunk(chunk);
  1025   // Chunk is being removed from the chunks free list.
  1026   dec_free_chunks_total(chunk->capacity_word_size());
  1029 // Walk the list of VirtualSpaceNodes and delete
  1030 // nodes with a 0 container_count.  Remove Metachunks in
  1031 // the node from their respective freelists.
  1032 void VirtualSpaceList::purge() {
  1033   assert_lock_strong(SpaceManager::expand_lock());
  1034   // Don't use a VirtualSpaceListIterator because this
  1035   // list is being changed and a straightforward use of an iterator is not safe.
  1036   VirtualSpaceNode* purged_vsl = NULL;
  1037   VirtualSpaceNode* prev_vsl = virtual_space_list();
  1038   VirtualSpaceNode* next_vsl = prev_vsl;
  1039   while (next_vsl != NULL) {
  1040     VirtualSpaceNode* vsl = next_vsl;
  1041     next_vsl = vsl->next();
  1042     // Don't free the current virtual space since it will likely
  1043     // be needed soon.
  1044     if (vsl->container_count() == 0 && vsl != current_virtual_space()) {
  1045       // Unlink it from the list
  1046       if (prev_vsl == vsl) {
  1047         // This is the case of the current note being the first note.
  1048         assert(vsl == virtual_space_list(), "Expected to be the first note");
  1049         set_virtual_space_list(vsl->next());
  1050       } else {
  1051         prev_vsl->set_next(vsl->next());
  1054       vsl->purge(chunk_manager());
  1055       dec_virtual_space_total(vsl->reserved()->word_size());
  1056       dec_virtual_space_count();
  1057       purged_vsl = vsl;
  1058       delete vsl;
  1059     } else {
  1060       prev_vsl = vsl;
  1063 #ifdef ASSERT
  1064   if (purged_vsl != NULL) {
  1065   // List should be stable enough to use an iterator here.
  1066   VirtualSpaceListIterator iter(virtual_space_list());
  1067     while (iter.repeat()) {
  1068       VirtualSpaceNode* vsl = iter.get_next();
  1069       assert(vsl != purged_vsl, "Purge of vsl failed");
  1072 #endif
  1075 size_t VirtualSpaceList::used_words_sum() {
  1076   size_t allocated_by_vs = 0;
  1077   VirtualSpaceListIterator iter(virtual_space_list());
  1078   while (iter.repeat()) {
  1079     VirtualSpaceNode* vsl = iter.get_next();
  1080     // Sum used region [bottom, top) in each virtualspace
  1081     allocated_by_vs += vsl->used_words_in_vs();
  1083   assert(allocated_by_vs >= chunk_manager()->free_chunks_total(),
  1084     err_msg("Total in free chunks " SIZE_FORMAT
  1085             " greater than total from virtual_spaces " SIZE_FORMAT,
  1086             allocated_by_vs, chunk_manager()->free_chunks_total()));
  1087   size_t used =
  1088     allocated_by_vs - chunk_manager()->free_chunks_total();
  1089   return used;
  1092 // Space available in all MetadataVirtualspaces allocated
  1093 // for metadata.  This is the upper limit on the capacity
  1094 // of chunks allocated out of all the MetadataVirtualspaces.
  1095 size_t VirtualSpaceList::capacity_words_sum() {
  1096   size_t capacity = 0;
  1097   VirtualSpaceListIterator iter(virtual_space_list());
  1098   while (iter.repeat()) {
  1099     VirtualSpaceNode* vsl = iter.get_next();
  1100     capacity += vsl->capacity_words_in_vs();
  1102   return capacity;
  1105 VirtualSpaceList::VirtualSpaceList(size_t word_size ) :
  1106                                    _is_class(false),
  1107                                    _virtual_space_list(NULL),
  1108                                    _current_virtual_space(NULL),
  1109                                    _virtual_space_total(0),
  1110                                    _virtual_space_count(0) {
  1111   MutexLockerEx cl(SpaceManager::expand_lock(),
  1112                    Mutex::_no_safepoint_check_flag);
  1113   bool initialization_succeeded = grow_vs(word_size);
  1115   _chunk_manager.free_chunks(SpecializedIndex)->set_size(SpecializedChunk);
  1116   _chunk_manager.free_chunks(SmallIndex)->set_size(SmallChunk);
  1117   _chunk_manager.free_chunks(MediumIndex)->set_size(MediumChunk);
  1118   assert(initialization_succeeded,
  1119     " VirtualSpaceList initialization should not fail");
  1122 VirtualSpaceList::VirtualSpaceList(ReservedSpace rs) :
  1123                                    _is_class(true),
  1124                                    _virtual_space_list(NULL),
  1125                                    _current_virtual_space(NULL),
  1126                                    _virtual_space_total(0),
  1127                                    _virtual_space_count(0) {
  1128   MutexLockerEx cl(SpaceManager::expand_lock(),
  1129                    Mutex::_no_safepoint_check_flag);
  1130   VirtualSpaceNode* class_entry = new VirtualSpaceNode(rs);
  1131   bool succeeded = class_entry->initialize();
  1132   _chunk_manager.free_chunks(SpecializedIndex)->set_size(SpecializedChunk);
  1133   _chunk_manager.free_chunks(SmallIndex)->set_size(ClassSmallChunk);
  1134   _chunk_manager.free_chunks(MediumIndex)->set_size(ClassMediumChunk);
  1135   assert(succeeded, " VirtualSpaceList initialization should not fail");
  1136   link_vs(class_entry, rs.size()/BytesPerWord);
  1139 size_t VirtualSpaceList::free_bytes() {
  1140   return virtual_space_list()->free_words_in_vs() * BytesPerWord;
  1143 // Allocate another meta virtual space and add it to the list.
  1144 bool VirtualSpaceList::grow_vs(size_t vs_word_size) {
  1145   assert_lock_strong(SpaceManager::expand_lock());
  1146   if (vs_word_size == 0) {
  1147     return false;
  1149   // Reserve the space
  1150   size_t vs_byte_size = vs_word_size * BytesPerWord;
  1151   assert(vs_byte_size % os::vm_page_size() == 0, "Not aligned");
  1153   // Allocate the meta virtual space and initialize it.
  1154   VirtualSpaceNode* new_entry = new VirtualSpaceNode(vs_byte_size);
  1155   if (!new_entry->initialize()) {
  1156     delete new_entry;
  1157     return false;
  1158   } else {
  1159     // ensure lock-free iteration sees fully initialized node
  1160     OrderAccess::storestore();
  1161     link_vs(new_entry, vs_word_size);
  1162     return true;
  1166 void VirtualSpaceList::link_vs(VirtualSpaceNode* new_entry, size_t vs_word_size) {
  1167   if (virtual_space_list() == NULL) {
  1168       set_virtual_space_list(new_entry);
  1169   } else {
  1170     current_virtual_space()->set_next(new_entry);
  1172   set_current_virtual_space(new_entry);
  1173   inc_virtual_space_total(vs_word_size);
  1174   inc_virtual_space_count();
  1175 #ifdef ASSERT
  1176   new_entry->mangle();
  1177 #endif
  1178   if (TraceMetavirtualspaceAllocation && Verbose) {
  1179     VirtualSpaceNode* vsl = current_virtual_space();
  1180     vsl->print_on(tty);
  1184 Metachunk* VirtualSpaceList::get_new_chunk(size_t word_size,
  1185                                            size_t grow_chunks_by_words,
  1186                                            size_t medium_chunk_bunch) {
  1188   // Get a chunk from the chunk freelist
  1189   Metachunk* next = chunk_manager()->chunk_freelist_allocate(grow_chunks_by_words);
  1191   if (next != NULL) {
  1192     next->container()->inc_container_count();
  1193   } else {
  1194     // Allocate a chunk out of the current virtual space.
  1195     next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
  1198   if (next == NULL) {
  1199     // Not enough room in current virtual space.  Try to commit
  1200     // more space.
  1201     size_t expand_vs_by_words = MAX2(medium_chunk_bunch,
  1202                                      grow_chunks_by_words);
  1203     size_t page_size_words = os::vm_page_size() / BytesPerWord;
  1204     size_t aligned_expand_vs_by_words = align_size_up(expand_vs_by_words,
  1205                                                         page_size_words);
  1206     bool vs_expanded =
  1207       current_virtual_space()->expand_by(aligned_expand_vs_by_words, false);
  1208     if (!vs_expanded) {
  1209       // Should the capacity of the metaspaces be expanded for
  1210       // this allocation?  If it's the virtual space for classes and is
  1211       // being used for CompressedHeaders, don't allocate a new virtualspace.
  1212       if (can_grow() && MetaspaceGC::should_expand(this, word_size)) {
  1213         // Get another virtual space.
  1214           size_t grow_vs_words =
  1215             MAX2((size_t)VirtualSpaceSize, aligned_expand_vs_by_words);
  1216         if (grow_vs(grow_vs_words)) {
  1217           // Got it.  It's on the list now.  Get a chunk from it.
  1218           next = current_virtual_space()->get_chunk_vs_with_expand(grow_chunks_by_words);
  1220       } else {
  1221         // Allocation will fail and induce a GC
  1222         if (TraceMetadataChunkAllocation && Verbose) {
  1223           gclog_or_tty->print_cr("VirtualSpaceList::get_new_chunk():"
  1224             " Fail instead of expand the metaspace");
  1227     } else {
  1228       // The virtual space expanded, get a new chunk
  1229       next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
  1230       assert(next != NULL, "Just expanded, should succeed");
  1234   assert(next == NULL || (next->next() == NULL && next->prev() == NULL),
  1235          "New chunk is still on some list");
  1236   return next;
  1239 Metachunk* VirtualSpaceList::get_initialization_chunk(size_t chunk_word_size,
  1240                                                       size_t chunk_bunch) {
  1241   // Get a chunk from the chunk freelist
  1242   Metachunk* new_chunk = get_new_chunk(chunk_word_size,
  1243                                        chunk_word_size,
  1244                                        chunk_bunch);
  1245   return new_chunk;
  1248 void VirtualSpaceList::print_on(outputStream* st) const {
  1249   if (TraceMetadataChunkAllocation && Verbose) {
  1250     VirtualSpaceListIterator iter(virtual_space_list());
  1251     while (iter.repeat()) {
  1252       VirtualSpaceNode* node = iter.get_next();
  1253       node->print_on(st);
  1258 bool VirtualSpaceList::contains(const void *ptr) {
  1259   VirtualSpaceNode* list = virtual_space_list();
  1260   VirtualSpaceListIterator iter(list);
  1261   while (iter.repeat()) {
  1262     VirtualSpaceNode* node = iter.get_next();
  1263     if (node->reserved()->contains(ptr)) {
  1264       return true;
  1267   return false;
  1271 // MetaspaceGC methods
  1273 // VM_CollectForMetadataAllocation is the vm operation used to GC.
  1274 // Within the VM operation after the GC the attempt to allocate the metadata
  1275 // should succeed.  If the GC did not free enough space for the metaspace
  1276 // allocation, the HWM is increased so that another virtualspace will be
  1277 // allocated for the metadata.  With perm gen the increase in the perm
  1278 // gen had bounds, MinMetaspaceExpansion and MaxMetaspaceExpansion.  The
  1279 // metaspace policy uses those as the small and large steps for the HWM.
  1280 //
  1281 // After the GC the compute_new_size() for MetaspaceGC is called to
  1282 // resize the capacity of the metaspaces.  The current implementation
  1283 // is based on the flags MinMetaspaceFreeRatio and MaxMetaspaceFreeRatio used
  1284 // to resize the Java heap by some GC's.  New flags can be implemented
  1285 // if really needed.  MinMetaspaceFreeRatio is used to calculate how much
  1286 // free space is desirable in the metaspace capacity to decide how much
  1287 // to increase the HWM.  MaxMetaspaceFreeRatio is used to decide how much
  1288 // free space is desirable in the metaspace capacity before decreasing
  1289 // the HWM.
  1291 // Calculate the amount to increase the high water mark (HWM).
  1292 // Increase by a minimum amount (MinMetaspaceExpansion) so that
  1293 // another expansion is not requested too soon.  If that is not
  1294 // enough to satisfy the allocation (i.e. big enough for a word_size
  1295 // allocation), increase by MaxMetaspaceExpansion.  If that is still
  1296 // not enough, expand by the size of the allocation (word_size) plus
  1297 // some.
  1298 size_t MetaspaceGC::delta_capacity_until_GC(size_t word_size) {
  1299   size_t before_inc = MetaspaceGC::capacity_until_GC();
  1300   size_t min_delta_words = MinMetaspaceExpansion / BytesPerWord;
  1301   size_t max_delta_words = MaxMetaspaceExpansion / BytesPerWord;
  1302   size_t page_size_words = os::vm_page_size() / BytesPerWord;
  1303   size_t size_delta_words = align_size_up(word_size, page_size_words);
  1304   size_t delta_words = MAX2(size_delta_words, min_delta_words);
  1305   if (delta_words > min_delta_words) {
  1306     // Don't want to hit the high water mark on the next
  1307     // allocation so make the delta greater than just enough
  1308     // for this allocation.
  1309     delta_words = MAX2(delta_words, max_delta_words);
  1310     if (delta_words > max_delta_words) {
  1311       // This allocation is large but the next ones are probably not
  1312       // so increase by the minimum.
  1313       delta_words = delta_words + min_delta_words;
  1316   return delta_words;
  1319 bool MetaspaceGC::should_expand(VirtualSpaceList* vsl, size_t word_size) {
  1321   // If the user wants a limit, impose one.
  1322   // The reason for someone using this flag is to limit reserved space.  So
  1323   // for non-class virtual space, compare against virtual spaces that are reserved.
  1324   // For class virtual space, we only compare against the committed space, not
  1325   // reserved space, because this is a larger space prereserved for compressed
  1326   // class pointers.
  1327   if (!FLAG_IS_DEFAULT(MaxMetaspaceSize)) {
  1328     size_t real_allocated = Metaspace::space_list()->virtual_space_total() +
  1329               MetaspaceAux::allocated_capacity_bytes(Metaspace::ClassType);
  1330     if (real_allocated >= MaxMetaspaceSize) {
  1331       return false;
  1335   // Class virtual space should always be expanded.  Call GC for the other
  1336   // metadata virtual space.
  1337   if (Metaspace::using_class_space() &&
  1338       (vsl == Metaspace::class_space_list())) return true;
  1340   // If this is part of an allocation after a GC, expand
  1341   // unconditionally.
  1342   if (MetaspaceGC::expand_after_GC()) {
  1343     return true;
  1347   // If the capacity is below the minimum capacity, allow the
  1348   // expansion.  Also set the high-water-mark (capacity_until_GC)
  1349   // to that minimum capacity so that a GC will not be induced
  1350   // until that minimum capacity is exceeded.
  1351   size_t committed_capacity_bytes = MetaspaceAux::allocated_capacity_bytes();
  1352   size_t metaspace_size_bytes = MetaspaceSize;
  1353   if (committed_capacity_bytes < metaspace_size_bytes ||
  1354       capacity_until_GC() == 0) {
  1355     set_capacity_until_GC(metaspace_size_bytes);
  1356     return true;
  1357   } else {
  1358     if (committed_capacity_bytes < capacity_until_GC()) {
  1359       return true;
  1360     } else {
  1361       if (TraceMetadataChunkAllocation && Verbose) {
  1362         gclog_or_tty->print_cr("  allocation request size " SIZE_FORMAT
  1363                         "  capacity_until_GC " SIZE_FORMAT
  1364                         "  allocated_capacity_bytes " SIZE_FORMAT,
  1365                         word_size,
  1366                         capacity_until_GC(),
  1367                         MetaspaceAux::allocated_capacity_bytes());
  1369       return false;
  1376 void MetaspaceGC::compute_new_size() {
  1377   assert(_shrink_factor <= 100, "invalid shrink factor");
  1378   uint current_shrink_factor = _shrink_factor;
  1379   _shrink_factor = 0;
  1381   // Until a faster way of calculating the "used" quantity is implemented,
  1382   // use "capacity".
  1383   const size_t used_after_gc = MetaspaceAux::allocated_capacity_bytes();
  1384   const size_t capacity_until_GC = MetaspaceGC::capacity_until_GC();
  1386   const double minimum_free_percentage = MinMetaspaceFreeRatio / 100.0;
  1387   const double maximum_used_percentage = 1.0 - minimum_free_percentage;
  1389   const double min_tmp = used_after_gc / maximum_used_percentage;
  1390   size_t minimum_desired_capacity =
  1391     (size_t)MIN2(min_tmp, double(max_uintx));
  1392   // Don't shrink less than the initial generation size
  1393   minimum_desired_capacity = MAX2(minimum_desired_capacity,
  1394                                   MetaspaceSize);
  1396   if (PrintGCDetails && Verbose) {
  1397     gclog_or_tty->print_cr("\nMetaspaceGC::compute_new_size: ");
  1398     gclog_or_tty->print_cr("  "
  1399                   "  minimum_free_percentage: %6.2f"
  1400                   "  maximum_used_percentage: %6.2f",
  1401                   minimum_free_percentage,
  1402                   maximum_used_percentage);
  1403     gclog_or_tty->print_cr("  "
  1404                   "   used_after_gc       : %6.1fKB",
  1405                   used_after_gc / (double) K);
  1409   size_t shrink_bytes = 0;
  1410   if (capacity_until_GC < minimum_desired_capacity) {
  1411     // If we have less capacity below the metaspace HWM, then
  1412     // increment the HWM.
  1413     size_t expand_bytes = minimum_desired_capacity - capacity_until_GC;
  1414     // Don't expand unless it's significant
  1415     if (expand_bytes >= MinMetaspaceExpansion) {
  1416       MetaspaceGC::set_capacity_until_GC(capacity_until_GC + expand_bytes);
  1418     if (PrintGCDetails && Verbose) {
  1419       size_t new_capacity_until_GC = capacity_until_GC;
  1420       gclog_or_tty->print_cr("    expanding:"
  1421                     "  minimum_desired_capacity: %6.1fKB"
  1422                     "  expand_bytes: %6.1fKB"
  1423                     "  MinMetaspaceExpansion: %6.1fKB"
  1424                     "  new metaspace HWM:  %6.1fKB",
  1425                     minimum_desired_capacity / (double) K,
  1426                     expand_bytes / (double) K,
  1427                     MinMetaspaceExpansion / (double) K,
  1428                     new_capacity_until_GC / (double) K);
  1430     return;
  1433   // No expansion, now see if we want to shrink
  1434   // We would never want to shrink more than this
  1435   size_t max_shrink_bytes = capacity_until_GC - minimum_desired_capacity;
  1436   assert(max_shrink_bytes >= 0, err_msg("max_shrink_bytes " SIZE_FORMAT,
  1437     max_shrink_bytes));
  1439   // Should shrinking be considered?
  1440   if (MaxMetaspaceFreeRatio < 100) {
  1441     const double maximum_free_percentage = MaxMetaspaceFreeRatio / 100.0;
  1442     const double minimum_used_percentage = 1.0 - maximum_free_percentage;
  1443     const double max_tmp = used_after_gc / minimum_used_percentage;
  1444     size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(max_uintx));
  1445     maximum_desired_capacity = MAX2(maximum_desired_capacity,
  1446                                     MetaspaceSize);
  1447     if (PrintGCDetails && Verbose) {
  1448       gclog_or_tty->print_cr("  "
  1449                              "  maximum_free_percentage: %6.2f"
  1450                              "  minimum_used_percentage: %6.2f",
  1451                              maximum_free_percentage,
  1452                              minimum_used_percentage);
  1453       gclog_or_tty->print_cr("  "
  1454                              "  minimum_desired_capacity: %6.1fKB"
  1455                              "  maximum_desired_capacity: %6.1fKB",
  1456                              minimum_desired_capacity / (double) K,
  1457                              maximum_desired_capacity / (double) K);
  1460     assert(minimum_desired_capacity <= maximum_desired_capacity,
  1461            "sanity check");
  1463     if (capacity_until_GC > maximum_desired_capacity) {
  1464       // Capacity too large, compute shrinking size
  1465       shrink_bytes = capacity_until_GC - maximum_desired_capacity;
  1466       // We don't want shrink all the way back to initSize if people call
  1467       // System.gc(), because some programs do that between "phases" and then
  1468       // we'd just have to grow the heap up again for the next phase.  So we
  1469       // damp the shrinking: 0% on the first call, 10% on the second call, 40%
  1470       // on the third call, and 100% by the fourth call.  But if we recompute
  1471       // size without shrinking, it goes back to 0%.
  1472       shrink_bytes = shrink_bytes / 100 * current_shrink_factor;
  1473       assert(shrink_bytes <= max_shrink_bytes,
  1474         err_msg("invalid shrink size " SIZE_FORMAT " not <= " SIZE_FORMAT,
  1475           shrink_bytes, max_shrink_bytes));
  1476       if (current_shrink_factor == 0) {
  1477         _shrink_factor = 10;
  1478       } else {
  1479         _shrink_factor = MIN2(current_shrink_factor * 4, (uint) 100);
  1481       if (PrintGCDetails && Verbose) {
  1482         gclog_or_tty->print_cr("  "
  1483                       "  shrinking:"
  1484                       "  initSize: %.1fK"
  1485                       "  maximum_desired_capacity: %.1fK",
  1486                       MetaspaceSize / (double) K,
  1487                       maximum_desired_capacity / (double) K);
  1488         gclog_or_tty->print_cr("  "
  1489                       "  shrink_bytes: %.1fK"
  1490                       "  current_shrink_factor: %d"
  1491                       "  new shrink factor: %d"
  1492                       "  MinMetaspaceExpansion: %.1fK",
  1493                       shrink_bytes / (double) K,
  1494                       current_shrink_factor,
  1495                       _shrink_factor,
  1496                       MinMetaspaceExpansion / (double) K);
  1501   // Don't shrink unless it's significant
  1502   if (shrink_bytes >= MinMetaspaceExpansion &&
  1503       ((capacity_until_GC - shrink_bytes) >= MetaspaceSize)) {
  1504     MetaspaceGC::set_capacity_until_GC(capacity_until_GC - shrink_bytes);
  1508 // Metadebug methods
  1510 void Metadebug::deallocate_chunk_a_lot(SpaceManager* sm,
  1511                                        size_t chunk_word_size){
  1512 #ifdef ASSERT
  1513   VirtualSpaceList* vsl = sm->vs_list();
  1514   if (MetaDataDeallocateALot &&
  1515       Metadebug::deallocate_chunk_a_lot_count() % MetaDataDeallocateALotInterval == 0 ) {
  1516     Metadebug::reset_deallocate_chunk_a_lot_count();
  1517     for (uint i = 0; i < metadata_deallocate_a_lock_chunk; i++) {
  1518       Metachunk* dummy_chunk = vsl->current_virtual_space()->take_from_committed(chunk_word_size);
  1519       if (dummy_chunk == NULL) {
  1520         break;
  1522       vsl->chunk_manager()->chunk_freelist_deallocate(dummy_chunk);
  1524       if (TraceMetadataChunkAllocation && Verbose) {
  1525         gclog_or_tty->print("Metadebug::deallocate_chunk_a_lot: %d) ",
  1526                                sm->sum_count_in_chunks_in_use());
  1527         dummy_chunk->print_on(gclog_or_tty);
  1528         gclog_or_tty->print_cr("  Free chunks total %d  count %d",
  1529                                vsl->chunk_manager()->free_chunks_total(),
  1530                                vsl->chunk_manager()->free_chunks_count());
  1533   } else {
  1534     Metadebug::inc_deallocate_chunk_a_lot_count();
  1536 #endif
  1539 void Metadebug::deallocate_block_a_lot(SpaceManager* sm,
  1540                                        size_t raw_word_size){
  1541 #ifdef ASSERT
  1542   if (MetaDataDeallocateALot &&
  1543         Metadebug::deallocate_block_a_lot_count() % MetaDataDeallocateALotInterval == 0 ) {
  1544     Metadebug::set_deallocate_block_a_lot_count(0);
  1545     for (uint i = 0; i < metadata_deallocate_a_lot_block; i++) {
  1546       MetaWord* dummy_block = sm->allocate_work(raw_word_size);
  1547       if (dummy_block == 0) {
  1548         break;
  1550       sm->deallocate(dummy_block, raw_word_size);
  1552   } else {
  1553     Metadebug::inc_deallocate_block_a_lot_count();
  1555 #endif
  1558 void Metadebug::init_allocation_fail_alot_count() {
  1559   if (MetadataAllocationFailALot) {
  1560     _allocation_fail_alot_count =
  1561       1+(long)((double)MetadataAllocationFailALotInterval*os::random()/(max_jint+1.0));
  1565 #ifdef ASSERT
  1566 bool Metadebug::test_metadata_failure() {
  1567   if (MetadataAllocationFailALot &&
  1568       Threads::is_vm_complete()) {
  1569     if (_allocation_fail_alot_count > 0) {
  1570       _allocation_fail_alot_count--;
  1571     } else {
  1572       if (TraceMetadataChunkAllocation && Verbose) {
  1573         gclog_or_tty->print_cr("Metadata allocation failing for "
  1574                                "MetadataAllocationFailALot");
  1576       init_allocation_fail_alot_count();
  1577       return true;
  1580   return false;
  1582 #endif
  1584 // ChunkManager methods
  1586 size_t ChunkManager::free_chunks_total() {
  1587   return _free_chunks_total;
  1590 size_t ChunkManager::free_chunks_total_in_bytes() {
  1591   return free_chunks_total() * BytesPerWord;
  1594 size_t ChunkManager::free_chunks_count() {
  1595 #ifdef ASSERT
  1596   if (!UseConcMarkSweepGC && !SpaceManager::expand_lock()->is_locked()) {
  1597     MutexLockerEx cl(SpaceManager::expand_lock(),
  1598                      Mutex::_no_safepoint_check_flag);
  1599     // This lock is only needed in debug because the verification
  1600     // of the _free_chunks_totals walks the list of free chunks
  1601     slow_locked_verify_free_chunks_count();
  1603 #endif
  1604   return _free_chunks_count;
  1607 void ChunkManager::locked_verify_free_chunks_total() {
  1608   assert_lock_strong(SpaceManager::expand_lock());
  1609   assert(sum_free_chunks() == _free_chunks_total,
  1610     err_msg("_free_chunks_total " SIZE_FORMAT " is not the"
  1611            " same as sum " SIZE_FORMAT, _free_chunks_total,
  1612            sum_free_chunks()));
  1615 void ChunkManager::verify_free_chunks_total() {
  1616   MutexLockerEx cl(SpaceManager::expand_lock(),
  1617                      Mutex::_no_safepoint_check_flag);
  1618   locked_verify_free_chunks_total();
  1621 void ChunkManager::locked_verify_free_chunks_count() {
  1622   assert_lock_strong(SpaceManager::expand_lock());
  1623   assert(sum_free_chunks_count() == _free_chunks_count,
  1624     err_msg("_free_chunks_count " SIZE_FORMAT " is not the"
  1625            " same as sum " SIZE_FORMAT, _free_chunks_count,
  1626            sum_free_chunks_count()));
  1629 void ChunkManager::verify_free_chunks_count() {
  1630 #ifdef ASSERT
  1631   MutexLockerEx cl(SpaceManager::expand_lock(),
  1632                      Mutex::_no_safepoint_check_flag);
  1633   locked_verify_free_chunks_count();
  1634 #endif
  1637 void ChunkManager::verify() {
  1638   MutexLockerEx cl(SpaceManager::expand_lock(),
  1639                      Mutex::_no_safepoint_check_flag);
  1640   locked_verify();
  1643 void ChunkManager::locked_verify() {
  1644   locked_verify_free_chunks_count();
  1645   locked_verify_free_chunks_total();
  1648 void ChunkManager::locked_print_free_chunks(outputStream* st) {
  1649   assert_lock_strong(SpaceManager::expand_lock());
  1650   st->print_cr("Free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
  1651                 _free_chunks_total, _free_chunks_count);
  1654 void ChunkManager::locked_print_sum_free_chunks(outputStream* st) {
  1655   assert_lock_strong(SpaceManager::expand_lock());
  1656   st->print_cr("Sum free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
  1657                 sum_free_chunks(), sum_free_chunks_count());
  1659 ChunkList* ChunkManager::free_chunks(ChunkIndex index) {
  1660   return &_free_chunks[index];
  1663 // These methods that sum the free chunk lists are used in printing
  1664 // methods that are used in product builds.
  1665 size_t ChunkManager::sum_free_chunks() {
  1666   assert_lock_strong(SpaceManager::expand_lock());
  1667   size_t result = 0;
  1668   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
  1669     ChunkList* list = free_chunks(i);
  1671     if (list == NULL) {
  1672       continue;
  1675     result = result + list->count() * list->size();
  1677   result = result + humongous_dictionary()->total_size();
  1678   return result;
  1681 size_t ChunkManager::sum_free_chunks_count() {
  1682   assert_lock_strong(SpaceManager::expand_lock());
  1683   size_t count = 0;
  1684   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
  1685     ChunkList* list = free_chunks(i);
  1686     if (list == NULL) {
  1687       continue;
  1689     count = count + list->count();
  1691   count = count + humongous_dictionary()->total_free_blocks();
  1692   return count;
  1695 ChunkList* ChunkManager::find_free_chunks_list(size_t word_size) {
  1696   ChunkIndex index = list_index(word_size);
  1697   assert(index < HumongousIndex, "No humongous list");
  1698   return free_chunks(index);
  1701 void ChunkManager::free_chunks_put(Metachunk* chunk) {
  1702   assert_lock_strong(SpaceManager::expand_lock());
  1703   ChunkList* free_list = find_free_chunks_list(chunk->word_size());
  1704   chunk->set_next(free_list->head());
  1705   free_list->set_head(chunk);
  1706   // chunk is being returned to the chunk free list
  1707   inc_free_chunks_total(chunk->capacity_word_size());
  1708   slow_locked_verify();
  1711 void ChunkManager::chunk_freelist_deallocate(Metachunk* chunk) {
  1712   // The deallocation of a chunk originates in the freelist
  1713   // manangement code for a Metaspace and does not hold the
  1714   // lock.
  1715   assert(chunk != NULL, "Deallocating NULL");
  1716   assert_lock_strong(SpaceManager::expand_lock());
  1717   slow_locked_verify();
  1718   if (TraceMetadataChunkAllocation) {
  1719     tty->print_cr("ChunkManager::chunk_freelist_deallocate: chunk "
  1720                   PTR_FORMAT "  size " SIZE_FORMAT,
  1721                   chunk, chunk->word_size());
  1723   free_chunks_put(chunk);
  1726 Metachunk* ChunkManager::free_chunks_get(size_t word_size) {
  1727   assert_lock_strong(SpaceManager::expand_lock());
  1729   slow_locked_verify();
  1731   Metachunk* chunk = NULL;
  1732   if (list_index(word_size) != HumongousIndex) {
  1733     ChunkList* free_list = find_free_chunks_list(word_size);
  1734     assert(free_list != NULL, "Sanity check");
  1736     chunk = free_list->head();
  1737     debug_only(Metachunk* debug_head = chunk;)
  1739     if (chunk == NULL) {
  1740       return NULL;
  1743     // Remove the chunk as the head of the list.
  1744     free_list->remove_chunk(chunk);
  1746     // Chunk is being removed from the chunks free list.
  1747     dec_free_chunks_total(chunk->capacity_word_size());
  1749     if (TraceMetadataChunkAllocation && Verbose) {
  1750       tty->print_cr("ChunkManager::free_chunks_get: free_list "
  1751                     PTR_FORMAT " head " PTR_FORMAT " size " SIZE_FORMAT,
  1752                     free_list, chunk, chunk->word_size());
  1754   } else {
  1755     chunk = humongous_dictionary()->get_chunk(
  1756       word_size,
  1757       FreeBlockDictionary<Metachunk>::atLeast);
  1759     if (chunk != NULL) {
  1760       if (TraceMetadataHumongousAllocation) {
  1761         size_t waste = chunk->word_size() - word_size;
  1762         tty->print_cr("Free list allocate humongous chunk size " SIZE_FORMAT
  1763                       " for requested size " SIZE_FORMAT
  1764                       " waste " SIZE_FORMAT,
  1765                       chunk->word_size(), word_size, waste);
  1767       // Chunk is being removed from the chunks free list.
  1768       dec_free_chunks_total(chunk->capacity_word_size());
  1769     } else {
  1770       return NULL;
  1774   // Remove it from the links to this freelist
  1775   chunk->set_next(NULL);
  1776   chunk->set_prev(NULL);
  1777 #ifdef ASSERT
  1778   // Chunk is no longer on any freelist. Setting to false make container_count_slow()
  1779   // work.
  1780   chunk->set_is_free(false);
  1781 #endif
  1782   slow_locked_verify();
  1783   return chunk;
  1786 Metachunk* ChunkManager::chunk_freelist_allocate(size_t word_size) {
  1787   assert_lock_strong(SpaceManager::expand_lock());
  1788   slow_locked_verify();
  1790   // Take from the beginning of the list
  1791   Metachunk* chunk = free_chunks_get(word_size);
  1792   if (chunk == NULL) {
  1793     return NULL;
  1796   assert((word_size <= chunk->word_size()) ||
  1797          list_index(chunk->word_size() == HumongousIndex),
  1798          "Non-humongous variable sized chunk");
  1799   if (TraceMetadataChunkAllocation) {
  1800     size_t list_count;
  1801     if (list_index(word_size) < HumongousIndex) {
  1802       ChunkList* list = find_free_chunks_list(word_size);
  1803       list_count = list->count();
  1804     } else {
  1805       list_count = humongous_dictionary()->total_count();
  1807     tty->print("ChunkManager::chunk_freelist_allocate: " PTR_FORMAT " chunk "
  1808                PTR_FORMAT "  size " SIZE_FORMAT " count " SIZE_FORMAT " ",
  1809                this, chunk, chunk->word_size(), list_count);
  1810     locked_print_free_chunks(tty);
  1813   return chunk;
  1816 void ChunkManager::print_on(outputStream* out) {
  1817   if (PrintFLSStatistics != 0) {
  1818     humongous_dictionary()->report_statistics();
  1822 // SpaceManager methods
  1824 void SpaceManager::get_initial_chunk_sizes(Metaspace::MetaspaceType type,
  1825                                            size_t* chunk_word_size,
  1826                                            size_t* class_chunk_word_size) {
  1827   switch (type) {
  1828   case Metaspace::BootMetaspaceType:
  1829     *chunk_word_size = Metaspace::first_chunk_word_size();
  1830     *class_chunk_word_size = Metaspace::first_class_chunk_word_size();
  1831     break;
  1832   case Metaspace::ROMetaspaceType:
  1833     *chunk_word_size = SharedReadOnlySize / wordSize;
  1834     *class_chunk_word_size = ClassSpecializedChunk;
  1835     break;
  1836   case Metaspace::ReadWriteMetaspaceType:
  1837     *chunk_word_size = SharedReadWriteSize / wordSize;
  1838     *class_chunk_word_size = ClassSpecializedChunk;
  1839     break;
  1840   case Metaspace::AnonymousMetaspaceType:
  1841   case Metaspace::ReflectionMetaspaceType:
  1842     *chunk_word_size = SpecializedChunk;
  1843     *class_chunk_word_size = ClassSpecializedChunk;
  1844     break;
  1845   default:
  1846     *chunk_word_size = SmallChunk;
  1847     *class_chunk_word_size = ClassSmallChunk;
  1848     break;
  1850   assert(*chunk_word_size != 0 && *class_chunk_word_size != 0,
  1851     err_msg("Initial chunks sizes bad: data  " SIZE_FORMAT
  1852             " class " SIZE_FORMAT,
  1853             *chunk_word_size, *class_chunk_word_size));
  1856 size_t SpaceManager::sum_free_in_chunks_in_use() const {
  1857   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1858   size_t free = 0;
  1859   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1860     Metachunk* chunk = chunks_in_use(i);
  1861     while (chunk != NULL) {
  1862       free += chunk->free_word_size();
  1863       chunk = chunk->next();
  1866   return free;
  1869 size_t SpaceManager::sum_waste_in_chunks_in_use() const {
  1870   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1871   size_t result = 0;
  1872   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1873    result += sum_waste_in_chunks_in_use(i);
  1876   return result;
  1879 size_t SpaceManager::sum_waste_in_chunks_in_use(ChunkIndex index) const {
  1880   size_t result = 0;
  1881   Metachunk* chunk = chunks_in_use(index);
  1882   // Count the free space in all the chunk but not the
  1883   // current chunk from which allocations are still being done.
  1884   while (chunk != NULL) {
  1885     if (chunk != current_chunk()) {
  1886       result += chunk->free_word_size();
  1888     chunk = chunk->next();
  1890   return result;
  1893 size_t SpaceManager::sum_capacity_in_chunks_in_use() const {
  1894   // For CMS use "allocated_chunks_words()" which does not need the
  1895   // Metaspace lock.  For the other collectors sum over the
  1896   // lists.  Use both methods as a check that "allocated_chunks_words()"
  1897   // is correct.  That is, sum_capacity_in_chunks() is too expensive
  1898   // to use in the product and allocated_chunks_words() should be used
  1899   // but allow for  checking that allocated_chunks_words() returns the same
  1900   // value as sum_capacity_in_chunks_in_use() which is the definitive
  1901   // answer.
  1902   if (UseConcMarkSweepGC) {
  1903     return allocated_chunks_words();
  1904   } else {
  1905     MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1906     size_t sum = 0;
  1907     for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1908       Metachunk* chunk = chunks_in_use(i);
  1909       while (chunk != NULL) {
  1910         sum += chunk->capacity_word_size();
  1911         chunk = chunk->next();
  1914   return sum;
  1918 size_t SpaceManager::sum_count_in_chunks_in_use() {
  1919   size_t count = 0;
  1920   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1921     count = count + sum_count_in_chunks_in_use(i);
  1924   return count;
  1927 size_t SpaceManager::sum_count_in_chunks_in_use(ChunkIndex i) {
  1928   size_t count = 0;
  1929   Metachunk* chunk = chunks_in_use(i);
  1930   while (chunk != NULL) {
  1931     count++;
  1932     chunk = chunk->next();
  1934   return count;
  1938 size_t SpaceManager::sum_used_in_chunks_in_use() const {
  1939   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1940   size_t used = 0;
  1941   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1942     Metachunk* chunk = chunks_in_use(i);
  1943     while (chunk != NULL) {
  1944       used += chunk->used_word_size();
  1945       chunk = chunk->next();
  1948   return used;
  1951 void SpaceManager::locked_print_chunks_in_use_on(outputStream* st) const {
  1953   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1954     Metachunk* chunk = chunks_in_use(i);
  1955     st->print("SpaceManager: %s " PTR_FORMAT,
  1956                  chunk_size_name(i), chunk);
  1957     if (chunk != NULL) {
  1958       st->print_cr(" free " SIZE_FORMAT,
  1959                    chunk->free_word_size());
  1960     } else {
  1961       st->print_cr("");
  1965   vs_list()->chunk_manager()->locked_print_free_chunks(st);
  1966   vs_list()->chunk_manager()->locked_print_sum_free_chunks(st);
  1969 size_t SpaceManager::calc_chunk_size(size_t word_size) {
  1971   // Decide between a small chunk and a medium chunk.  Up to
  1972   // _small_chunk_limit small chunks can be allocated but
  1973   // once a medium chunk has been allocated, no more small
  1974   // chunks will be allocated.
  1975   size_t chunk_word_size;
  1976   if (chunks_in_use(MediumIndex) == NULL &&
  1977       sum_count_in_chunks_in_use(SmallIndex) < _small_chunk_limit) {
  1978     chunk_word_size = (size_t) small_chunk_size();
  1979     if (word_size + Metachunk::overhead() > small_chunk_size()) {
  1980       chunk_word_size = medium_chunk_size();
  1982   } else {
  1983     chunk_word_size = medium_chunk_size();
  1986   // Might still need a humongous chunk.  Enforce an
  1987   // eight word granularity to facilitate reuse (some
  1988   // wastage but better chance of reuse).
  1989   size_t if_humongous_sized_chunk =
  1990     align_size_up(word_size + Metachunk::overhead(),
  1991                   HumongousChunkGranularity);
  1992   chunk_word_size =
  1993     MAX2((size_t) chunk_word_size, if_humongous_sized_chunk);
  1995   assert(!SpaceManager::is_humongous(word_size) ||
  1996          chunk_word_size == if_humongous_sized_chunk,
  1997          err_msg("Size calculation is wrong, word_size " SIZE_FORMAT
  1998                  " chunk_word_size " SIZE_FORMAT,
  1999                  word_size, chunk_word_size));
  2000   if (TraceMetadataHumongousAllocation &&
  2001       SpaceManager::is_humongous(word_size)) {
  2002     gclog_or_tty->print_cr("Metadata humongous allocation:");
  2003     gclog_or_tty->print_cr("  word_size " PTR_FORMAT, word_size);
  2004     gclog_or_tty->print_cr("  chunk_word_size " PTR_FORMAT,
  2005                            chunk_word_size);
  2006     gclog_or_tty->print_cr("    chunk overhead " PTR_FORMAT,
  2007                            Metachunk::overhead());
  2009   return chunk_word_size;
  2012 MetaWord* SpaceManager::grow_and_allocate(size_t word_size) {
  2013   assert(vs_list()->current_virtual_space() != NULL,
  2014          "Should have been set");
  2015   assert(current_chunk() == NULL ||
  2016          current_chunk()->allocate(word_size) == NULL,
  2017          "Don't need to expand");
  2018   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  2020   if (TraceMetadataChunkAllocation && Verbose) {
  2021     size_t words_left = 0;
  2022     size_t words_used = 0;
  2023     if (current_chunk() != NULL) {
  2024       words_left = current_chunk()->free_word_size();
  2025       words_used = current_chunk()->used_word_size();
  2027     gclog_or_tty->print_cr("SpaceManager::grow_and_allocate for " SIZE_FORMAT
  2028                            " words " SIZE_FORMAT " words used " SIZE_FORMAT
  2029                            " words left",
  2030                             word_size, words_used, words_left);
  2033   // Get another chunk out of the virtual space
  2034   size_t grow_chunks_by_words = calc_chunk_size(word_size);
  2035   Metachunk* next = get_new_chunk(word_size, grow_chunks_by_words);
  2037   // If a chunk was available, add it to the in-use chunk list
  2038   // and do an allocation from it.
  2039   if (next != NULL) {
  2040     Metadebug::deallocate_chunk_a_lot(this, grow_chunks_by_words);
  2041     // Add to this manager's list of chunks in use.
  2042     add_chunk(next, false);
  2043     return next->allocate(word_size);
  2045   return NULL;
  2048 void SpaceManager::print_on(outputStream* st) const {
  2050   for (ChunkIndex i = ZeroIndex;
  2051        i < NumberOfInUseLists ;
  2052        i = next_chunk_index(i) ) {
  2053     st->print_cr("  chunks_in_use " PTR_FORMAT " chunk size " PTR_FORMAT,
  2054                  chunks_in_use(i),
  2055                  chunks_in_use(i) == NULL ? 0 : chunks_in_use(i)->word_size());
  2057   st->print_cr("    waste:  Small " SIZE_FORMAT " Medium " SIZE_FORMAT
  2058                " Humongous " SIZE_FORMAT,
  2059                sum_waste_in_chunks_in_use(SmallIndex),
  2060                sum_waste_in_chunks_in_use(MediumIndex),
  2061                sum_waste_in_chunks_in_use(HumongousIndex));
  2062   // block free lists
  2063   if (block_freelists() != NULL) {
  2064     st->print_cr("total in block free lists " SIZE_FORMAT,
  2065       block_freelists()->total_size());
  2069 SpaceManager::SpaceManager(Metaspace::MetadataType mdtype,
  2070                            Mutex* lock,
  2071                            VirtualSpaceList* vs_list) :
  2072   _vs_list(vs_list),
  2073   _mdtype(mdtype),
  2074   _allocated_blocks_words(0),
  2075   _allocated_chunks_words(0),
  2076   _allocated_chunks_count(0),
  2077   _lock(lock)
  2079   initialize();
  2082 void SpaceManager::inc_size_metrics(size_t words) {
  2083   assert_lock_strong(SpaceManager::expand_lock());
  2084   // Total of allocated Metachunks and allocated Metachunks count
  2085   // for each SpaceManager
  2086   _allocated_chunks_words = _allocated_chunks_words + words;
  2087   _allocated_chunks_count++;
  2088   // Global total of capacity in allocated Metachunks
  2089   MetaspaceAux::inc_capacity(mdtype(), words);
  2090   // Global total of allocated Metablocks.
  2091   // used_words_slow() includes the overhead in each
  2092   // Metachunk so include it in the used when the
  2093   // Metachunk is first added (so only added once per
  2094   // Metachunk).
  2095   MetaspaceAux::inc_used(mdtype(), Metachunk::overhead());
  2098 void SpaceManager::inc_used_metrics(size_t words) {
  2099   // Add to the per SpaceManager total
  2100   Atomic::add_ptr(words, &_allocated_blocks_words);
  2101   // Add to the global total
  2102   MetaspaceAux::inc_used(mdtype(), words);
  2105 void SpaceManager::dec_total_from_size_metrics() {
  2106   MetaspaceAux::dec_capacity(mdtype(), allocated_chunks_words());
  2107   MetaspaceAux::dec_used(mdtype(), allocated_blocks_words());
  2108   // Also deduct the overhead per Metachunk
  2109   MetaspaceAux::dec_used(mdtype(), allocated_chunks_count() * Metachunk::overhead());
  2112 void SpaceManager::initialize() {
  2113   Metadebug::init_allocation_fail_alot_count();
  2114   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2115     _chunks_in_use[i] = NULL;
  2117   _current_chunk = NULL;
  2118   if (TraceMetadataChunkAllocation && Verbose) {
  2119     gclog_or_tty->print_cr("SpaceManager(): " PTR_FORMAT, this);
  2123 void ChunkManager::return_chunks(ChunkIndex index, Metachunk* chunks) {
  2124   if (chunks == NULL) {
  2125     return;
  2127   ChunkList* list = free_chunks(index);
  2128   assert(list->size() == chunks->word_size(), "Mismatch in chunk sizes");
  2129   assert_lock_strong(SpaceManager::expand_lock());
  2130   Metachunk* cur = chunks;
  2132   // This returns chunks one at a time.  If a new
  2133   // class List can be created that is a base class
  2134   // of FreeList then something like FreeList::prepend()
  2135   // can be used in place of this loop
  2136   while (cur != NULL) {
  2137     assert(cur->container() != NULL, "Container should have been set");
  2138     cur->container()->dec_container_count();
  2139     // Capture the next link before it is changed
  2140     // by the call to return_chunk_at_head();
  2141     Metachunk* next = cur->next();
  2142     cur->set_is_free(true);
  2143     list->return_chunk_at_head(cur);
  2144     cur = next;
  2148 SpaceManager::~SpaceManager() {
  2149   // This call this->_lock which can't be done while holding expand_lock()
  2150   assert(sum_capacity_in_chunks_in_use() == allocated_chunks_words(),
  2151     err_msg("sum_capacity_in_chunks_in_use() " SIZE_FORMAT
  2152             " allocated_chunks_words() " SIZE_FORMAT,
  2153             sum_capacity_in_chunks_in_use(), allocated_chunks_words()));
  2155   MutexLockerEx fcl(SpaceManager::expand_lock(),
  2156                     Mutex::_no_safepoint_check_flag);
  2158   ChunkManager* chunk_manager = vs_list()->chunk_manager();
  2160   chunk_manager->slow_locked_verify();
  2162   dec_total_from_size_metrics();
  2164   if (TraceMetadataChunkAllocation && Verbose) {
  2165     gclog_or_tty->print_cr("~SpaceManager(): " PTR_FORMAT, this);
  2166     locked_print_chunks_in_use_on(gclog_or_tty);
  2169   // Do not mangle freed Metachunks.  The chunk size inside Metachunks
  2170   // is during the freeing of a VirtualSpaceNodes.
  2172   // Have to update before the chunks_in_use lists are emptied
  2173   // below.
  2174   chunk_manager->inc_free_chunks_total(allocated_chunks_words(),
  2175                                        sum_count_in_chunks_in_use());
  2177   // Add all the chunks in use by this space manager
  2178   // to the global list of free chunks.
  2180   // Follow each list of chunks-in-use and add them to the
  2181   // free lists.  Each list is NULL terminated.
  2183   for (ChunkIndex i = ZeroIndex; i < HumongousIndex; i = next_chunk_index(i)) {
  2184     if (TraceMetadataChunkAllocation && Verbose) {
  2185       gclog_or_tty->print_cr("returned %d %s chunks to freelist",
  2186                              sum_count_in_chunks_in_use(i),
  2187                              chunk_size_name(i));
  2189     Metachunk* chunks = chunks_in_use(i);
  2190     chunk_manager->return_chunks(i, chunks);
  2191     set_chunks_in_use(i, NULL);
  2192     if (TraceMetadataChunkAllocation && Verbose) {
  2193       gclog_or_tty->print_cr("updated freelist count %d %s",
  2194                              chunk_manager->free_chunks(i)->count(),
  2195                              chunk_size_name(i));
  2197     assert(i != HumongousIndex, "Humongous chunks are handled explicitly later");
  2200   // The medium chunk case may be optimized by passing the head and
  2201   // tail of the medium chunk list to add_at_head().  The tail is often
  2202   // the current chunk but there are probably exceptions.
  2204   // Humongous chunks
  2205   if (TraceMetadataChunkAllocation && Verbose) {
  2206     gclog_or_tty->print_cr("returned %d %s humongous chunks to dictionary",
  2207                             sum_count_in_chunks_in_use(HumongousIndex),
  2208                             chunk_size_name(HumongousIndex));
  2209     gclog_or_tty->print("Humongous chunk dictionary: ");
  2211   // Humongous chunks are never the current chunk.
  2212   Metachunk* humongous_chunks = chunks_in_use(HumongousIndex);
  2214   while (humongous_chunks != NULL) {
  2215 #ifdef ASSERT
  2216     humongous_chunks->set_is_free(true);
  2217 #endif
  2218     if (TraceMetadataChunkAllocation && Verbose) {
  2219       gclog_or_tty->print(PTR_FORMAT " (" SIZE_FORMAT ") ",
  2220                           humongous_chunks,
  2221                           humongous_chunks->word_size());
  2223     assert(humongous_chunks->word_size() == (size_t)
  2224            align_size_up(humongous_chunks->word_size(),
  2225                              HumongousChunkGranularity),
  2226            err_msg("Humongous chunk size is wrong: word size " SIZE_FORMAT
  2227                    " granularity %d",
  2228                    humongous_chunks->word_size(), HumongousChunkGranularity));
  2229     Metachunk* next_humongous_chunks = humongous_chunks->next();
  2230     humongous_chunks->container()->dec_container_count();
  2231     chunk_manager->humongous_dictionary()->return_chunk(humongous_chunks);
  2232     humongous_chunks = next_humongous_chunks;
  2234   if (TraceMetadataChunkAllocation && Verbose) {
  2235     gclog_or_tty->print_cr("");
  2236     gclog_or_tty->print_cr("updated dictionary count %d %s",
  2237                      chunk_manager->humongous_dictionary()->total_count(),
  2238                      chunk_size_name(HumongousIndex));
  2240   chunk_manager->slow_locked_verify();
  2243 const char* SpaceManager::chunk_size_name(ChunkIndex index) const {
  2244   switch (index) {
  2245     case SpecializedIndex:
  2246       return "Specialized";
  2247     case SmallIndex:
  2248       return "Small";
  2249     case MediumIndex:
  2250       return "Medium";
  2251     case HumongousIndex:
  2252       return "Humongous";
  2253     default:
  2254       return NULL;
  2258 ChunkIndex ChunkManager::list_index(size_t size) {
  2259   switch (size) {
  2260     case SpecializedChunk:
  2261       assert(SpecializedChunk == ClassSpecializedChunk,
  2262              "Need branch for ClassSpecializedChunk");
  2263       return SpecializedIndex;
  2264     case SmallChunk:
  2265     case ClassSmallChunk:
  2266       return SmallIndex;
  2267     case MediumChunk:
  2268     case ClassMediumChunk:
  2269       return MediumIndex;
  2270     default:
  2271       assert(size > MediumChunk || size > ClassMediumChunk,
  2272              "Not a humongous chunk");
  2273       return HumongousIndex;
  2277 void SpaceManager::deallocate(MetaWord* p, size_t word_size) {
  2278   assert_lock_strong(_lock);
  2279   size_t raw_word_size = get_raw_word_size(word_size);
  2280   size_t min_size = TreeChunk<Metablock, FreeList>::min_size();
  2281   assert(raw_word_size >= min_size,
  2282          err_msg("Should not deallocate dark matter " SIZE_FORMAT "<" SIZE_FORMAT, word_size, min_size));
  2283   block_freelists()->return_block(p, raw_word_size);
  2286 // Adds a chunk to the list of chunks in use.
  2287 void SpaceManager::add_chunk(Metachunk* new_chunk, bool make_current) {
  2289   assert(new_chunk != NULL, "Should not be NULL");
  2290   assert(new_chunk->next() == NULL, "Should not be on a list");
  2292   new_chunk->reset_empty();
  2294   // Find the correct list and and set the current
  2295   // chunk for that list.
  2296   ChunkIndex index = ChunkManager::list_index(new_chunk->word_size());
  2298   if (index != HumongousIndex) {
  2299     retire_current_chunk();
  2300     set_current_chunk(new_chunk);
  2301     new_chunk->set_next(chunks_in_use(index));
  2302     set_chunks_in_use(index, new_chunk);
  2303   } else {
  2304     // For null class loader data and DumpSharedSpaces, the first chunk isn't
  2305     // small, so small will be null.  Link this first chunk as the current
  2306     // chunk.
  2307     if (make_current) {
  2308       // Set as the current chunk but otherwise treat as a humongous chunk.
  2309       set_current_chunk(new_chunk);
  2311     // Link at head.  The _current_chunk only points to a humongous chunk for
  2312     // the null class loader metaspace (class and data virtual space managers)
  2313     // any humongous chunks so will not point to the tail
  2314     // of the humongous chunks list.
  2315     new_chunk->set_next(chunks_in_use(HumongousIndex));
  2316     set_chunks_in_use(HumongousIndex, new_chunk);
  2318     assert(new_chunk->word_size() > medium_chunk_size(), "List inconsistency");
  2321   // Add to the running sum of capacity
  2322   inc_size_metrics(new_chunk->word_size());
  2324   assert(new_chunk->is_empty(), "Not ready for reuse");
  2325   if (TraceMetadataChunkAllocation && Verbose) {
  2326     gclog_or_tty->print("SpaceManager::add_chunk: %d) ",
  2327                         sum_count_in_chunks_in_use());
  2328     new_chunk->print_on(gclog_or_tty);
  2329     if (vs_list() != NULL) {
  2330       vs_list()->chunk_manager()->locked_print_free_chunks(tty);
  2335 void SpaceManager::retire_current_chunk() {
  2336   if (current_chunk() != NULL) {
  2337     size_t remaining_words = current_chunk()->free_word_size();
  2338     if (remaining_words >= TreeChunk<Metablock, FreeList>::min_size()) {
  2339       block_freelists()->return_block(current_chunk()->allocate(remaining_words), remaining_words);
  2340       inc_used_metrics(remaining_words);
  2345 Metachunk* SpaceManager::get_new_chunk(size_t word_size,
  2346                                        size_t grow_chunks_by_words) {
  2348   Metachunk* next = vs_list()->get_new_chunk(word_size,
  2349                                              grow_chunks_by_words,
  2350                                              medium_chunk_bunch());
  2352   if (TraceMetadataHumongousAllocation &&
  2353       SpaceManager::is_humongous(next->word_size())) {
  2354     gclog_or_tty->print_cr("  new humongous chunk word size " PTR_FORMAT,
  2355                            next->word_size());
  2358   return next;
  2361 MetaWord* SpaceManager::allocate(size_t word_size) {
  2362   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  2364   size_t raw_word_size = get_raw_word_size(word_size);
  2365   BlockFreelist* fl =  block_freelists();
  2366   MetaWord* p = NULL;
  2367   // Allocation from the dictionary is expensive in the sense that
  2368   // the dictionary has to be searched for a size.  Don't allocate
  2369   // from the dictionary until it starts to get fat.  Is this
  2370   // a reasonable policy?  Maybe an skinny dictionary is fast enough
  2371   // for allocations.  Do some profiling.  JJJ
  2372   if (fl->total_size() > allocation_from_dictionary_limit) {
  2373     p = fl->get_block(raw_word_size);
  2375   if (p == NULL) {
  2376     p = allocate_work(raw_word_size);
  2378   Metadebug::deallocate_block_a_lot(this, raw_word_size);
  2380   return p;
  2383 // Returns the address of spaced allocated for "word_size".
  2384 // This methods does not know about blocks (Metablocks)
  2385 MetaWord* SpaceManager::allocate_work(size_t word_size) {
  2386   assert_lock_strong(_lock);
  2387 #ifdef ASSERT
  2388   if (Metadebug::test_metadata_failure()) {
  2389     return NULL;
  2391 #endif
  2392   // Is there space in the current chunk?
  2393   MetaWord* result = NULL;
  2395   // For DumpSharedSpaces, only allocate out of the current chunk which is
  2396   // never null because we gave it the size we wanted.   Caller reports out
  2397   // of memory if this returns null.
  2398   if (DumpSharedSpaces) {
  2399     assert(current_chunk() != NULL, "should never happen");
  2400     inc_used_metrics(word_size);
  2401     return current_chunk()->allocate(word_size); // caller handles null result
  2403   if (current_chunk() != NULL) {
  2404     result = current_chunk()->allocate(word_size);
  2407   if (result == NULL) {
  2408     result = grow_and_allocate(word_size);
  2410   if (result != 0) {
  2411     inc_used_metrics(word_size);
  2412     assert(result != (MetaWord*) chunks_in_use(MediumIndex),
  2413            "Head of the list is being allocated");
  2416   return result;
  2419 void SpaceManager::verify() {
  2420   // If there are blocks in the dictionary, then
  2421   // verfication of chunks does not work since
  2422   // being in the dictionary alters a chunk.
  2423   if (block_freelists()->total_size() == 0) {
  2424     for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2425       Metachunk* curr = chunks_in_use(i);
  2426       while (curr != NULL) {
  2427         curr->verify();
  2428         verify_chunk_size(curr);
  2429         curr = curr->next();
  2435 void SpaceManager::verify_chunk_size(Metachunk* chunk) {
  2436   assert(is_humongous(chunk->word_size()) ||
  2437          chunk->word_size() == medium_chunk_size() ||
  2438          chunk->word_size() == small_chunk_size() ||
  2439          chunk->word_size() == specialized_chunk_size(),
  2440          "Chunk size is wrong");
  2441   return;
  2444 #ifdef ASSERT
  2445 void SpaceManager::verify_allocated_blocks_words() {
  2446   // Verification is only guaranteed at a safepoint.
  2447   assert(SafepointSynchronize::is_at_safepoint() || !Universe::is_fully_initialized(),
  2448     "Verification can fail if the applications is running");
  2449   assert(allocated_blocks_words() == sum_used_in_chunks_in_use(),
  2450     err_msg("allocation total is not consistent " SIZE_FORMAT
  2451             " vs " SIZE_FORMAT,
  2452             allocated_blocks_words(), sum_used_in_chunks_in_use()));
  2455 #endif
  2457 void SpaceManager::dump(outputStream* const out) const {
  2458   size_t curr_total = 0;
  2459   size_t waste = 0;
  2460   uint i = 0;
  2461   size_t used = 0;
  2462   size_t capacity = 0;
  2464   // Add up statistics for all chunks in this SpaceManager.
  2465   for (ChunkIndex index = ZeroIndex;
  2466        index < NumberOfInUseLists;
  2467        index = next_chunk_index(index)) {
  2468     for (Metachunk* curr = chunks_in_use(index);
  2469          curr != NULL;
  2470          curr = curr->next()) {
  2471       out->print("%d) ", i++);
  2472       curr->print_on(out);
  2473       if (TraceMetadataChunkAllocation && Verbose) {
  2474         block_freelists()->print_on(out);
  2476       curr_total += curr->word_size();
  2477       used += curr->used_word_size();
  2478       capacity += curr->capacity_word_size();
  2479       waste += curr->free_word_size() + curr->overhead();;
  2483   size_t free = current_chunk() == NULL ? 0 : current_chunk()->free_word_size();
  2484   // Free space isn't wasted.
  2485   waste -= free;
  2487   out->print_cr("total of all chunks "  SIZE_FORMAT " used " SIZE_FORMAT
  2488                 " free " SIZE_FORMAT " capacity " SIZE_FORMAT
  2489                 " waste " SIZE_FORMAT, curr_total, used, free, capacity, waste);
  2492 #ifndef PRODUCT
  2493 void SpaceManager::mangle_freed_chunks() {
  2494   for (ChunkIndex index = ZeroIndex;
  2495        index < NumberOfInUseLists;
  2496        index = next_chunk_index(index)) {
  2497     for (Metachunk* curr = chunks_in_use(index);
  2498          curr != NULL;
  2499          curr = curr->next()) {
  2500       curr->mangle();
  2504 #endif // PRODUCT
  2506 // MetaspaceAux
  2509 size_t MetaspaceAux::_allocated_capacity_words[] = {0, 0};
  2510 size_t MetaspaceAux::_allocated_used_words[] = {0, 0};
  2512 size_t MetaspaceAux::free_bytes(Metaspace::MetadataType mdtype) {
  2513   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
  2514   return list == NULL ? 0 : list->free_bytes();
  2517 size_t MetaspaceAux::free_bytes() {
  2518   return free_bytes(Metaspace::ClassType) + free_bytes(Metaspace::NonClassType);
  2521 void MetaspaceAux::dec_capacity(Metaspace::MetadataType mdtype, size_t words) {
  2522   assert_lock_strong(SpaceManager::expand_lock());
  2523   assert(words <= allocated_capacity_words(mdtype),
  2524     err_msg("About to decrement below 0: words " SIZE_FORMAT
  2525             " is greater than _allocated_capacity_words[%u] " SIZE_FORMAT,
  2526             words, mdtype, allocated_capacity_words(mdtype)));
  2527   _allocated_capacity_words[mdtype] -= words;
  2530 void MetaspaceAux::inc_capacity(Metaspace::MetadataType mdtype, size_t words) {
  2531   assert_lock_strong(SpaceManager::expand_lock());
  2532   // Needs to be atomic
  2533   _allocated_capacity_words[mdtype] += words;
  2536 void MetaspaceAux::dec_used(Metaspace::MetadataType mdtype, size_t words) {
  2537   assert(words <= allocated_used_words(mdtype),
  2538     err_msg("About to decrement below 0: words " SIZE_FORMAT
  2539             " is greater than _allocated_used_words[%u] " SIZE_FORMAT,
  2540             words, mdtype, allocated_used_words(mdtype)));
  2541   // For CMS deallocation of the Metaspaces occurs during the
  2542   // sweep which is a concurrent phase.  Protection by the expand_lock()
  2543   // is not enough since allocation is on a per Metaspace basis
  2544   // and protected by the Metaspace lock.
  2545   jlong minus_words = (jlong) - (jlong) words;
  2546   Atomic::add_ptr(minus_words, &_allocated_used_words[mdtype]);
  2549 void MetaspaceAux::inc_used(Metaspace::MetadataType mdtype, size_t words) {
  2550   // _allocated_used_words tracks allocations for
  2551   // each piece of metadata.  Those allocations are
  2552   // generally done concurrently by different application
  2553   // threads so must be done atomically.
  2554   Atomic::add_ptr(words, &_allocated_used_words[mdtype]);
  2557 size_t MetaspaceAux::used_bytes_slow(Metaspace::MetadataType mdtype) {
  2558   size_t used = 0;
  2559   ClassLoaderDataGraphMetaspaceIterator iter;
  2560   while (iter.repeat()) {
  2561     Metaspace* msp = iter.get_next();
  2562     // Sum allocated_blocks_words for each metaspace
  2563     if (msp != NULL) {
  2564       used += msp->used_words_slow(mdtype);
  2567   return used * BytesPerWord;
  2570 size_t MetaspaceAux::free_in_bytes(Metaspace::MetadataType mdtype) {
  2571   size_t free = 0;
  2572   ClassLoaderDataGraphMetaspaceIterator iter;
  2573   while (iter.repeat()) {
  2574     Metaspace* msp = iter.get_next();
  2575     if (msp != NULL) {
  2576       free += msp->free_words(mdtype);
  2579   return free * BytesPerWord;
  2582 size_t MetaspaceAux::capacity_bytes_slow(Metaspace::MetadataType mdtype) {
  2583   if ((mdtype == Metaspace::ClassType) && !Metaspace::using_class_space()) {
  2584     return 0;
  2586   // Don't count the space in the freelists.  That space will be
  2587   // added to the capacity calculation as needed.
  2588   size_t capacity = 0;
  2589   ClassLoaderDataGraphMetaspaceIterator iter;
  2590   while (iter.repeat()) {
  2591     Metaspace* msp = iter.get_next();
  2592     if (msp != NULL) {
  2593       capacity += msp->capacity_words_slow(mdtype);
  2596   return capacity * BytesPerWord;
  2599 size_t MetaspaceAux::reserved_in_bytes(Metaspace::MetadataType mdtype) {
  2600   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
  2601   return list == NULL ? 0 : list->virtual_space_total();
  2604 size_t MetaspaceAux::min_chunk_size() { return Metaspace::first_chunk_word_size(); }
  2606 size_t MetaspaceAux::free_chunks_total(Metaspace::MetadataType mdtype) {
  2607   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
  2608   if (list == NULL) {
  2609     return 0;
  2611   ChunkManager* chunk = list->chunk_manager();
  2612   chunk->slow_verify();
  2613   return chunk->free_chunks_total();
  2616 size_t MetaspaceAux::free_chunks_total_in_bytes(Metaspace::MetadataType mdtype) {
  2617   return free_chunks_total(mdtype) * BytesPerWord;
  2620 size_t MetaspaceAux::free_chunks_total() {
  2621   return free_chunks_total(Metaspace::ClassType) +
  2622          free_chunks_total(Metaspace::NonClassType);
  2625 size_t MetaspaceAux::free_chunks_total_in_bytes() {
  2626   return free_chunks_total() * BytesPerWord;
  2629 void MetaspaceAux::print_metaspace_change(size_t prev_metadata_used) {
  2630   gclog_or_tty->print(", [Metaspace:");
  2631   if (PrintGCDetails && Verbose) {
  2632     gclog_or_tty->print(" "  SIZE_FORMAT
  2633                         "->" SIZE_FORMAT
  2634                         "("  SIZE_FORMAT ")",
  2635                         prev_metadata_used,
  2636                         allocated_used_bytes(),
  2637                         reserved_in_bytes());
  2638   } else {
  2639     gclog_or_tty->print(" "  SIZE_FORMAT "K"
  2640                         "->" SIZE_FORMAT "K"
  2641                         "("  SIZE_FORMAT "K)",
  2642                         prev_metadata_used / K,
  2643                         allocated_used_bytes() / K,
  2644                         reserved_in_bytes()/ K);
  2647   gclog_or_tty->print("]");
  2650 // This is printed when PrintGCDetails
  2651 void MetaspaceAux::print_on(outputStream* out) {
  2652   Metaspace::MetadataType nct = Metaspace::NonClassType;
  2654   out->print_cr(" Metaspace total "
  2655                 SIZE_FORMAT "K, used " SIZE_FORMAT "K,"
  2656                 " reserved " SIZE_FORMAT "K",
  2657                 allocated_capacity_bytes()/K, allocated_used_bytes()/K, reserved_in_bytes()/K);
  2659   out->print_cr("  data space     "
  2660                 SIZE_FORMAT "K, used " SIZE_FORMAT "K,"
  2661                 " reserved " SIZE_FORMAT "K",
  2662                 allocated_capacity_bytes(nct)/K,
  2663                 allocated_used_bytes(nct)/K,
  2664                 reserved_in_bytes(nct)/K);
  2665   if (Metaspace::using_class_space()) {
  2666     Metaspace::MetadataType ct = Metaspace::ClassType;
  2667     out->print_cr("  class space    "
  2668                   SIZE_FORMAT "K, used " SIZE_FORMAT "K,"
  2669                   " reserved " SIZE_FORMAT "K",
  2670                   allocated_capacity_bytes(ct)/K,
  2671                   allocated_used_bytes(ct)/K,
  2672                   reserved_in_bytes(ct)/K);
  2676 // Print information for class space and data space separately.
  2677 // This is almost the same as above.
  2678 void MetaspaceAux::print_on(outputStream* out, Metaspace::MetadataType mdtype) {
  2679   size_t free_chunks_capacity_bytes = free_chunks_total_in_bytes(mdtype);
  2680   size_t capacity_bytes = capacity_bytes_slow(mdtype);
  2681   size_t used_bytes = used_bytes_slow(mdtype);
  2682   size_t free_bytes = free_in_bytes(mdtype);
  2683   size_t used_and_free = used_bytes + free_bytes +
  2684                            free_chunks_capacity_bytes;
  2685   out->print_cr("  Chunk accounting: used in chunks " SIZE_FORMAT
  2686              "K + unused in chunks " SIZE_FORMAT "K  + "
  2687              " capacity in free chunks " SIZE_FORMAT "K = " SIZE_FORMAT
  2688              "K  capacity in allocated chunks " SIZE_FORMAT "K",
  2689              used_bytes / K,
  2690              free_bytes / K,
  2691              free_chunks_capacity_bytes / K,
  2692              used_and_free / K,
  2693              capacity_bytes / K);
  2694   // Accounting can only be correct if we got the values during a safepoint
  2695   assert(!SafepointSynchronize::is_at_safepoint() || used_and_free == capacity_bytes, "Accounting is wrong");
  2698 // Print total fragmentation for class metaspaces
  2699 void MetaspaceAux::print_class_waste(outputStream* out) {
  2700   assert(Metaspace::using_class_space(), "class metaspace not used");
  2701   size_t cls_specialized_waste = 0, cls_small_waste = 0, cls_medium_waste = 0;
  2702   size_t cls_specialized_count = 0, cls_small_count = 0, cls_medium_count = 0, cls_humongous_count = 0;
  2703   ClassLoaderDataGraphMetaspaceIterator iter;
  2704   while (iter.repeat()) {
  2705     Metaspace* msp = iter.get_next();
  2706     if (msp != NULL) {
  2707       cls_specialized_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
  2708       cls_specialized_count += msp->class_vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
  2709       cls_small_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SmallIndex);
  2710       cls_small_count += msp->class_vsm()->sum_count_in_chunks_in_use(SmallIndex);
  2711       cls_medium_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(MediumIndex);
  2712       cls_medium_count += msp->class_vsm()->sum_count_in_chunks_in_use(MediumIndex);
  2713       cls_humongous_count += msp->class_vsm()->sum_count_in_chunks_in_use(HumongousIndex);
  2716   out->print_cr(" class: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
  2717                 SIZE_FORMAT " small(s) " SIZE_FORMAT ", "
  2718                 SIZE_FORMAT " medium(s) " SIZE_FORMAT ", "
  2719                 "large count " SIZE_FORMAT,
  2720                 cls_specialized_count, cls_specialized_waste,
  2721                 cls_small_count, cls_small_waste,
  2722                 cls_medium_count, cls_medium_waste, cls_humongous_count);
  2725 // Print total fragmentation for data and class metaspaces separately
  2726 void MetaspaceAux::print_waste(outputStream* out) {
  2727   size_t specialized_waste = 0, small_waste = 0, medium_waste = 0;
  2728   size_t specialized_count = 0, small_count = 0, medium_count = 0, humongous_count = 0;
  2730   ClassLoaderDataGraphMetaspaceIterator iter;
  2731   while (iter.repeat()) {
  2732     Metaspace* msp = iter.get_next();
  2733     if (msp != NULL) {
  2734       specialized_waste += msp->vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
  2735       specialized_count += msp->vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
  2736       small_waste += msp->vsm()->sum_waste_in_chunks_in_use(SmallIndex);
  2737       small_count += msp->vsm()->sum_count_in_chunks_in_use(SmallIndex);
  2738       medium_waste += msp->vsm()->sum_waste_in_chunks_in_use(MediumIndex);
  2739       medium_count += msp->vsm()->sum_count_in_chunks_in_use(MediumIndex);
  2740       humongous_count += msp->vsm()->sum_count_in_chunks_in_use(HumongousIndex);
  2743   out->print_cr("Total fragmentation waste (words) doesn't count free space");
  2744   out->print_cr("  data: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
  2745                         SIZE_FORMAT " small(s) " SIZE_FORMAT ", "
  2746                         SIZE_FORMAT " medium(s) " SIZE_FORMAT ", "
  2747                         "large count " SIZE_FORMAT,
  2748              specialized_count, specialized_waste, small_count,
  2749              small_waste, medium_count, medium_waste, humongous_count);
  2750   if (Metaspace::using_class_space()) {
  2751     print_class_waste(out);
  2755 // Dump global metaspace things from the end of ClassLoaderDataGraph
  2756 void MetaspaceAux::dump(outputStream* out) {
  2757   out->print_cr("All Metaspace:");
  2758   out->print("data space: "); print_on(out, Metaspace::NonClassType);
  2759   out->print("class space: "); print_on(out, Metaspace::ClassType);
  2760   print_waste(out);
  2763 void MetaspaceAux::verify_free_chunks() {
  2764   Metaspace::space_list()->chunk_manager()->verify();
  2765   if (Metaspace::using_class_space()) {
  2766     Metaspace::class_space_list()->chunk_manager()->verify();
  2770 void MetaspaceAux::verify_capacity() {
  2771 #ifdef ASSERT
  2772   size_t running_sum_capacity_bytes = allocated_capacity_bytes();
  2773   // For purposes of the running sum of capacity, verify against capacity
  2774   size_t capacity_in_use_bytes = capacity_bytes_slow();
  2775   assert(running_sum_capacity_bytes == capacity_in_use_bytes,
  2776     err_msg("allocated_capacity_words() * BytesPerWord " SIZE_FORMAT
  2777             " capacity_bytes_slow()" SIZE_FORMAT,
  2778             running_sum_capacity_bytes, capacity_in_use_bytes));
  2779   for (Metaspace::MetadataType i = Metaspace::ClassType;
  2780        i < Metaspace:: MetadataTypeCount;
  2781        i = (Metaspace::MetadataType)(i + 1)) {
  2782     size_t capacity_in_use_bytes = capacity_bytes_slow(i);
  2783     assert(allocated_capacity_bytes(i) == capacity_in_use_bytes,
  2784       err_msg("allocated_capacity_bytes(%u) " SIZE_FORMAT
  2785               " capacity_bytes_slow(%u)" SIZE_FORMAT,
  2786               i, allocated_capacity_bytes(i), i, capacity_in_use_bytes));
  2788 #endif
  2791 void MetaspaceAux::verify_used() {
  2792 #ifdef ASSERT
  2793   size_t running_sum_used_bytes = allocated_used_bytes();
  2794   // For purposes of the running sum of used, verify against used
  2795   size_t used_in_use_bytes = used_bytes_slow();
  2796   assert(allocated_used_bytes() == used_in_use_bytes,
  2797     err_msg("allocated_used_bytes() " SIZE_FORMAT
  2798             " used_bytes_slow()" SIZE_FORMAT,
  2799             allocated_used_bytes(), used_in_use_bytes));
  2800   for (Metaspace::MetadataType i = Metaspace::ClassType;
  2801        i < Metaspace:: MetadataTypeCount;
  2802        i = (Metaspace::MetadataType)(i + 1)) {
  2803     size_t used_in_use_bytes = used_bytes_slow(i);
  2804     assert(allocated_used_bytes(i) == used_in_use_bytes,
  2805       err_msg("allocated_used_bytes(%u) " SIZE_FORMAT
  2806               " used_bytes_slow(%u)" SIZE_FORMAT,
  2807               i, allocated_used_bytes(i), i, used_in_use_bytes));
  2809 #endif
  2812 void MetaspaceAux::verify_metrics() {
  2813   verify_capacity();
  2814   verify_used();
  2818 // Metaspace methods
  2820 size_t Metaspace::_first_chunk_word_size = 0;
  2821 size_t Metaspace::_first_class_chunk_word_size = 0;
  2823 Metaspace::Metaspace(Mutex* lock, MetaspaceType type) {
  2824   initialize(lock, type);
  2827 Metaspace::~Metaspace() {
  2828   delete _vsm;
  2829   if (using_class_space()) {
  2830     delete _class_vsm;
  2834 VirtualSpaceList* Metaspace::_space_list = NULL;
  2835 VirtualSpaceList* Metaspace::_class_space_list = NULL;
  2837 #define VIRTUALSPACEMULTIPLIER 2
  2839 #ifdef _LP64
  2840 void Metaspace::set_narrow_klass_base_and_shift(address metaspace_base, address cds_base) {
  2841   // Figure out the narrow_klass_base and the narrow_klass_shift.  The
  2842   // narrow_klass_base is the lower of the metaspace base and the cds base
  2843   // (if cds is enabled).  The narrow_klass_shift depends on the distance
  2844   // between the lower base and higher address.
  2845   address lower_base;
  2846   address higher_address;
  2847   if (UseSharedSpaces) {
  2848     higher_address = MAX2((address)(cds_base + FileMapInfo::shared_spaces_size()),
  2849                           (address)(metaspace_base + class_metaspace_size()));
  2850     lower_base = MIN2(metaspace_base, cds_base);
  2851   } else {
  2852     higher_address = metaspace_base + class_metaspace_size();
  2853     lower_base = metaspace_base;
  2855   Universe::set_narrow_klass_base(lower_base);
  2856   if ((uint64_t)(higher_address - lower_base) < (uint64_t)max_juint) {
  2857     Universe::set_narrow_klass_shift(0);
  2858   } else {
  2859     assert(!UseSharedSpaces, "Cannot shift with UseSharedSpaces");
  2860     Universe::set_narrow_klass_shift(LogKlassAlignmentInBytes);
  2864 // Return TRUE if the specified metaspace_base and cds_base are close enough
  2865 // to work with compressed klass pointers.
  2866 bool Metaspace::can_use_cds_with_metaspace_addr(char* metaspace_base, address cds_base) {
  2867   assert(cds_base != 0 && UseSharedSpaces, "Only use with CDS");
  2868   assert(UseCompressedClassPointers, "Only use with CompressedKlassPtrs");
  2869   address lower_base = MIN2((address)metaspace_base, cds_base);
  2870   address higher_address = MAX2((address)(cds_base + FileMapInfo::shared_spaces_size()),
  2871                                 (address)(metaspace_base + class_metaspace_size()));
  2872   return ((uint64_t)(higher_address - lower_base) < (uint64_t)max_juint);
  2875 // Try to allocate the metaspace at the requested addr.
  2876 void Metaspace::allocate_metaspace_compressed_klass_ptrs(char* requested_addr, address cds_base) {
  2877   assert(using_class_space(), "called improperly");
  2878   assert(UseCompressedClassPointers, "Only use with CompressedKlassPtrs");
  2879   assert(class_metaspace_size() < KlassEncodingMetaspaceMax,
  2880          "Metaspace size is too big");
  2882   ReservedSpace metaspace_rs = ReservedSpace(class_metaspace_size(),
  2883                                              os::vm_allocation_granularity(),
  2884                                              false, requested_addr, 0);
  2885   if (!metaspace_rs.is_reserved()) {
  2886     if (UseSharedSpaces) {
  2887       // Keep trying to allocate the metaspace, increasing the requested_addr
  2888       // by 1GB each time, until we reach an address that will no longer allow
  2889       // use of CDS with compressed klass pointers.
  2890       char *addr = requested_addr;
  2891       while (!metaspace_rs.is_reserved() && (addr + 1*G > addr) &&
  2892              can_use_cds_with_metaspace_addr(addr + 1*G, cds_base)) {
  2893         addr = addr + 1*G;
  2894         metaspace_rs = ReservedSpace(class_metaspace_size(),
  2895                                      os::vm_allocation_granularity(), false, addr, 0);
  2899     // If no successful allocation then try to allocate the space anywhere.  If
  2900     // that fails then OOM doom.  At this point we cannot try allocating the
  2901     // metaspace as if UseCompressedClassPointers is off because too much
  2902     // initialization has happened that depends on UseCompressedClassPointers.
  2903     // So, UseCompressedClassPointers cannot be turned off at this point.
  2904     if (!metaspace_rs.is_reserved()) {
  2905       metaspace_rs = ReservedSpace(class_metaspace_size(),
  2906                                    os::vm_allocation_granularity(), false);
  2907       if (!metaspace_rs.is_reserved()) {
  2908         vm_exit_during_initialization(err_msg("Could not allocate metaspace: %d bytes",
  2909                                               class_metaspace_size()));
  2914   // If we got here then the metaspace got allocated.
  2915   MemTracker::record_virtual_memory_type((address)metaspace_rs.base(), mtClass);
  2917   // Verify that we can use shared spaces.  Otherwise, turn off CDS.
  2918   if (UseSharedSpaces && !can_use_cds_with_metaspace_addr(metaspace_rs.base(), cds_base)) {
  2919     FileMapInfo::stop_sharing_and_unmap(
  2920         "Could not allocate metaspace at a compatible address");
  2923   set_narrow_klass_base_and_shift((address)metaspace_rs.base(),
  2924                                   UseSharedSpaces ? (address)cds_base : 0);
  2926   initialize_class_space(metaspace_rs);
  2928   if (PrintCompressedOopsMode || (PrintMiscellaneous && Verbose)) {
  2929     gclog_or_tty->print_cr("Narrow klass base: " PTR_FORMAT ", Narrow klass shift: " SIZE_FORMAT,
  2930                             Universe::narrow_klass_base(), Universe::narrow_klass_shift());
  2931     gclog_or_tty->print_cr("Metaspace Size: " SIZE_FORMAT " Address: " PTR_FORMAT " Req Addr: " PTR_FORMAT,
  2932                            class_metaspace_size(), metaspace_rs.base(), requested_addr);
  2936 // For UseCompressedClassPointers the class space is reserved above the top of
  2937 // the Java heap.  The argument passed in is at the base of the compressed space.
  2938 void Metaspace::initialize_class_space(ReservedSpace rs) {
  2939   // The reserved space size may be bigger because of alignment, esp with UseLargePages
  2940   assert(rs.size() >= CompressedClassSpaceSize,
  2941          err_msg(SIZE_FORMAT " != " UINTX_FORMAT, rs.size(), CompressedClassSpaceSize));
  2942   assert(using_class_space(), "Must be using class space");
  2943   _class_space_list = new VirtualSpaceList(rs);
  2946 #endif
  2948 void Metaspace::global_initialize() {
  2949   // Initialize the alignment for shared spaces.
  2950   int max_alignment = os::vm_page_size();
  2951   size_t cds_total = 0;
  2953   set_class_metaspace_size(align_size_up(CompressedClassSpaceSize,
  2954                                          os::vm_allocation_granularity()));
  2956   MetaspaceShared::set_max_alignment(max_alignment);
  2958   if (DumpSharedSpaces) {
  2959     SharedReadOnlySize = align_size_up(SharedReadOnlySize, max_alignment);
  2960     SharedReadWriteSize = align_size_up(SharedReadWriteSize, max_alignment);
  2961     SharedMiscDataSize  = align_size_up(SharedMiscDataSize, max_alignment);
  2962     SharedMiscCodeSize  = align_size_up(SharedMiscCodeSize, max_alignment);
  2964     // Initialize with the sum of the shared space sizes.  The read-only
  2965     // and read write metaspace chunks will be allocated out of this and the
  2966     // remainder is the misc code and data chunks.
  2967     cds_total = FileMapInfo::shared_spaces_size();
  2968     _space_list = new VirtualSpaceList(cds_total/wordSize);
  2970 #ifdef _LP64
  2971     // Set the compressed klass pointer base so that decoding of these pointers works
  2972     // properly when creating the shared archive.
  2973     assert(UseCompressedOops && UseCompressedClassPointers,
  2974       "UseCompressedOops and UseCompressedClassPointers must be set");
  2975     Universe::set_narrow_klass_base((address)_space_list->current_virtual_space()->bottom());
  2976     if (TraceMetavirtualspaceAllocation && Verbose) {
  2977       gclog_or_tty->print_cr("Setting_narrow_klass_base to Address: " PTR_FORMAT,
  2978                              _space_list->current_virtual_space()->bottom());
  2981     // Set the shift to zero.
  2982     assert(class_metaspace_size() < (uint64_t)(max_juint) - cds_total,
  2983            "CDS region is too large");
  2984     Universe::set_narrow_klass_shift(0);
  2985 #endif
  2987   } else {
  2988     // If using shared space, open the file that contains the shared space
  2989     // and map in the memory before initializing the rest of metaspace (so
  2990     // the addresses don't conflict)
  2991     address cds_address = NULL;
  2992     if (UseSharedSpaces) {
  2993       FileMapInfo* mapinfo = new FileMapInfo();
  2994       memset(mapinfo, 0, sizeof(FileMapInfo));
  2996       // Open the shared archive file, read and validate the header. If
  2997       // initialization fails, shared spaces [UseSharedSpaces] are
  2998       // disabled and the file is closed.
  2999       // Map in spaces now also
  3000       if (mapinfo->initialize() && MetaspaceShared::map_shared_spaces(mapinfo)) {
  3001         FileMapInfo::set_current_info(mapinfo);
  3002       } else {
  3003         assert(!mapinfo->is_open() && !UseSharedSpaces,
  3004                "archive file not closed or shared spaces not disabled.");
  3006       cds_total = FileMapInfo::shared_spaces_size();
  3007       cds_address = (address)mapinfo->region_base(0);
  3010 #ifdef _LP64
  3011     // If UseCompressedClassPointers is set then allocate the metaspace area
  3012     // above the heap and above the CDS area (if it exists).
  3013     if (using_class_space()) {
  3014       if (UseSharedSpaces) {
  3015         allocate_metaspace_compressed_klass_ptrs((char *)(cds_address + cds_total), cds_address);
  3016       } else {
  3017         allocate_metaspace_compressed_klass_ptrs((char *)CompressedKlassPointersBase, 0);
  3020 #endif
  3022     // Initialize these before initializing the VirtualSpaceList
  3023     _first_chunk_word_size = InitialBootClassLoaderMetaspaceSize / BytesPerWord;
  3024     _first_chunk_word_size = align_word_size_up(_first_chunk_word_size);
  3025     // Make the first class chunk bigger than a medium chunk so it's not put
  3026     // on the medium chunk list.   The next chunk will be small and progress
  3027     // from there.  This size calculated by -version.
  3028     _first_class_chunk_word_size = MIN2((size_t)MediumChunk*6,
  3029                                        (CompressedClassSpaceSize/BytesPerWord)*2);
  3030     _first_class_chunk_word_size = align_word_size_up(_first_class_chunk_word_size);
  3031     // Arbitrarily set the initial virtual space to a multiple
  3032     // of the boot class loader size.
  3033     size_t word_size = VIRTUALSPACEMULTIPLIER * first_chunk_word_size();
  3034     // Initialize the list of virtual spaces.
  3035     _space_list = new VirtualSpaceList(word_size);
  3039 void Metaspace::initialize(Mutex* lock, MetaspaceType type) {
  3041   assert(space_list() != NULL,
  3042     "Metadata VirtualSpaceList has not been initialized");
  3044   _vsm = new SpaceManager(NonClassType, lock, space_list());
  3045   if (_vsm == NULL) {
  3046     return;
  3048   size_t word_size;
  3049   size_t class_word_size;
  3050   vsm()->get_initial_chunk_sizes(type, &word_size, &class_word_size);
  3052   if (using_class_space()) {
  3053     assert(class_space_list() != NULL,
  3054       "Class VirtualSpaceList has not been initialized");
  3056     // Allocate SpaceManager for classes.
  3057     _class_vsm = new SpaceManager(ClassType, lock, class_space_list());
  3058     if (_class_vsm == NULL) {
  3059       return;
  3063   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  3065   // Allocate chunk for metadata objects
  3066   Metachunk* new_chunk =
  3067      space_list()->get_initialization_chunk(word_size,
  3068                                             vsm()->medium_chunk_bunch());
  3069   assert(!DumpSharedSpaces || new_chunk != NULL, "should have enough space for both chunks");
  3070   if (new_chunk != NULL) {
  3071     // Add to this manager's list of chunks in use and current_chunk().
  3072     vsm()->add_chunk(new_chunk, true);
  3075   // Allocate chunk for class metadata objects
  3076   if (using_class_space()) {
  3077     Metachunk* class_chunk =
  3078        class_space_list()->get_initialization_chunk(class_word_size,
  3079                                                     class_vsm()->medium_chunk_bunch());
  3080     if (class_chunk != NULL) {
  3081       class_vsm()->add_chunk(class_chunk, true);
  3085   _alloc_record_head = NULL;
  3086   _alloc_record_tail = NULL;
  3089 size_t Metaspace::align_word_size_up(size_t word_size) {
  3090   size_t byte_size = word_size * wordSize;
  3091   return ReservedSpace::allocation_align_size_up(byte_size) / wordSize;
  3094 MetaWord* Metaspace::allocate(size_t word_size, MetadataType mdtype) {
  3095   // DumpSharedSpaces doesn't use class metadata area (yet)
  3096   // Also, don't use class_vsm() unless UseCompressedClassPointers is true.
  3097   if (mdtype == ClassType && using_class_space()) {
  3098     return  class_vsm()->allocate(word_size);
  3099   } else {
  3100     return  vsm()->allocate(word_size);
  3104 MetaWord* Metaspace::expand_and_allocate(size_t word_size, MetadataType mdtype) {
  3105   MetaWord* result;
  3106   MetaspaceGC::set_expand_after_GC(true);
  3107   size_t before_inc = MetaspaceGC::capacity_until_GC();
  3108   size_t delta_bytes = MetaspaceGC::delta_capacity_until_GC(word_size) * BytesPerWord;
  3109   MetaspaceGC::inc_capacity_until_GC(delta_bytes);
  3110   if (PrintGCDetails && Verbose) {
  3111     gclog_or_tty->print_cr("Increase capacity to GC from " SIZE_FORMAT
  3112       " to " SIZE_FORMAT, before_inc, MetaspaceGC::capacity_until_GC());
  3115   result = allocate(word_size, mdtype);
  3117   return result;
  3120 // Space allocated in the Metaspace.  This may
  3121 // be across several metadata virtual spaces.
  3122 char* Metaspace::bottom() const {
  3123   assert(DumpSharedSpaces, "only useful and valid for dumping shared spaces");
  3124   return (char*)vsm()->current_chunk()->bottom();
  3127 size_t Metaspace::used_words_slow(MetadataType mdtype) const {
  3128   if (mdtype == ClassType) {
  3129     return using_class_space() ? class_vsm()->sum_used_in_chunks_in_use() : 0;
  3130   } else {
  3131     return vsm()->sum_used_in_chunks_in_use();  // includes overhead!
  3135 size_t Metaspace::free_words(MetadataType mdtype) const {
  3136   if (mdtype == ClassType) {
  3137     return using_class_space() ? class_vsm()->sum_free_in_chunks_in_use() : 0;
  3138   } else {
  3139     return vsm()->sum_free_in_chunks_in_use();
  3143 // Space capacity in the Metaspace.  It includes
  3144 // space in the list of chunks from which allocations
  3145 // have been made. Don't include space in the global freelist and
  3146 // in the space available in the dictionary which
  3147 // is already counted in some chunk.
  3148 size_t Metaspace::capacity_words_slow(MetadataType mdtype) const {
  3149   if (mdtype == ClassType) {
  3150     return using_class_space() ? class_vsm()->sum_capacity_in_chunks_in_use() : 0;
  3151   } else {
  3152     return vsm()->sum_capacity_in_chunks_in_use();
  3156 size_t Metaspace::used_bytes_slow(MetadataType mdtype) const {
  3157   return used_words_slow(mdtype) * BytesPerWord;
  3160 size_t Metaspace::capacity_bytes_slow(MetadataType mdtype) const {
  3161   return capacity_words_slow(mdtype) * BytesPerWord;
  3164 void Metaspace::deallocate(MetaWord* ptr, size_t word_size, bool is_class) {
  3165   if (SafepointSynchronize::is_at_safepoint()) {
  3166     assert(Thread::current()->is_VM_thread(), "should be the VM thread");
  3167     // Don't take Heap_lock
  3168     MutexLockerEx ml(vsm()->lock(), Mutex::_no_safepoint_check_flag);
  3169     if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
  3170       // Dark matter.  Too small for dictionary.
  3171 #ifdef ASSERT
  3172       Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
  3173 #endif
  3174       return;
  3176     if (is_class && using_class_space()) {
  3177       class_vsm()->deallocate(ptr, word_size);
  3178     } else {
  3179       vsm()->deallocate(ptr, word_size);
  3181   } else {
  3182     MutexLockerEx ml(vsm()->lock(), Mutex::_no_safepoint_check_flag);
  3184     if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
  3185       // Dark matter.  Too small for dictionary.
  3186 #ifdef ASSERT
  3187       Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
  3188 #endif
  3189       return;
  3191     if (is_class && using_class_space()) {
  3192       class_vsm()->deallocate(ptr, word_size);
  3193     } else {
  3194       vsm()->deallocate(ptr, word_size);
  3199 Metablock* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size,
  3200                               bool read_only, MetaspaceObj::Type type, TRAPS) {
  3201   if (HAS_PENDING_EXCEPTION) {
  3202     assert(false, "Should not allocate with exception pending");
  3203     return NULL;  // caller does a CHECK_NULL too
  3206   MetadataType mdtype = (type == MetaspaceObj::ClassType) ? ClassType : NonClassType;
  3208   // SSS: Should we align the allocations and make sure the sizes are aligned.
  3209   MetaWord* result = NULL;
  3211   assert(loader_data != NULL, "Should never pass around a NULL loader_data. "
  3212         "ClassLoaderData::the_null_class_loader_data() should have been used.");
  3213   // Allocate in metaspaces without taking out a lock, because it deadlocks
  3214   // with the SymbolTable_lock.  Dumping is single threaded for now.  We'll have
  3215   // to revisit this for application class data sharing.
  3216   if (DumpSharedSpaces) {
  3217     assert(type > MetaspaceObj::UnknownType && type < MetaspaceObj::_number_of_types, "sanity");
  3218     Metaspace* space = read_only ? loader_data->ro_metaspace() : loader_data->rw_metaspace();
  3219     result = space->allocate(word_size, NonClassType);
  3220     if (result == NULL) {
  3221       report_out_of_shared_space(read_only ? SharedReadOnly : SharedReadWrite);
  3222     } else {
  3223       space->record_allocation(result, type, space->vsm()->get_raw_word_size(word_size));
  3225     return Metablock::initialize(result, word_size);
  3228   result = loader_data->metaspace_non_null()->allocate(word_size, mdtype);
  3230   if (result == NULL) {
  3231     // Try to clean out some memory and retry.
  3232     result =
  3233       Universe::heap()->collector_policy()->satisfy_failed_metadata_allocation(
  3234         loader_data, word_size, mdtype);
  3236     // If result is still null, we are out of memory.
  3237     if (result == NULL) {
  3238       if (Verbose && TraceMetadataChunkAllocation) {
  3239         gclog_or_tty->print_cr("Metaspace allocation failed for size "
  3240           SIZE_FORMAT, word_size);
  3241         if (loader_data->metaspace_or_null() != NULL) loader_data->dump(gclog_or_tty);
  3242         MetaspaceAux::dump(gclog_or_tty);
  3244       // -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support
  3245       const char* space_string = (mdtype == ClassType) ? "Compressed class space" :
  3246                                                          "Metadata space";
  3247       report_java_out_of_memory(space_string);
  3249       if (JvmtiExport::should_post_resource_exhausted()) {
  3250         JvmtiExport::post_resource_exhausted(
  3251             JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR,
  3252             space_string);
  3254       if (mdtype == ClassType) {
  3255         THROW_OOP_0(Universe::out_of_memory_error_class_metaspace());
  3256       } else {
  3257         THROW_OOP_0(Universe::out_of_memory_error_metaspace());
  3261   return Metablock::initialize(result, word_size);
  3264 void Metaspace::record_allocation(void* ptr, MetaspaceObj::Type type, size_t word_size) {
  3265   assert(DumpSharedSpaces, "sanity");
  3267   AllocRecord *rec = new AllocRecord((address)ptr, type, (int)word_size * HeapWordSize);
  3268   if (_alloc_record_head == NULL) {
  3269     _alloc_record_head = _alloc_record_tail = rec;
  3270   } else {
  3271     _alloc_record_tail->_next = rec;
  3272     _alloc_record_tail = rec;
  3276 void Metaspace::iterate(Metaspace::AllocRecordClosure *closure) {
  3277   assert(DumpSharedSpaces, "unimplemented for !DumpSharedSpaces");
  3279   address last_addr = (address)bottom();
  3281   for (AllocRecord *rec = _alloc_record_head; rec; rec = rec->_next) {
  3282     address ptr = rec->_ptr;
  3283     if (last_addr < ptr) {
  3284       closure->doit(last_addr, MetaspaceObj::UnknownType, ptr - last_addr);
  3286     closure->doit(ptr, rec->_type, rec->_byte_size);
  3287     last_addr = ptr + rec->_byte_size;
  3290   address top = ((address)bottom()) + used_bytes_slow(Metaspace::NonClassType);
  3291   if (last_addr < top) {
  3292     closure->doit(last_addr, MetaspaceObj::UnknownType, top - last_addr);
  3296 void Metaspace::purge() {
  3297   MutexLockerEx cl(SpaceManager::expand_lock(),
  3298                    Mutex::_no_safepoint_check_flag);
  3299   space_list()->purge();
  3300   if (using_class_space()) {
  3301     class_space_list()->purge();
  3305 void Metaspace::print_on(outputStream* out) const {
  3306   // Print both class virtual space counts and metaspace.
  3307   if (Verbose) {
  3308     vsm()->print_on(out);
  3309     if (using_class_space()) {
  3310       class_vsm()->print_on(out);
  3315 bool Metaspace::contains(const void * ptr) {
  3316   if (MetaspaceShared::is_in_shared_space(ptr)) {
  3317     return true;
  3319   // This is checked while unlocked.  As long as the virtualspaces are added
  3320   // at the end, the pointer will be in one of them.  The virtual spaces
  3321   // aren't deleted presently.  When they are, some sort of locking might
  3322   // be needed.  Note, locking this can cause inversion problems with the
  3323   // caller in MetaspaceObj::is_metadata() function.
  3324   return space_list()->contains(ptr) ||
  3325          (using_class_space() && class_space_list()->contains(ptr));
  3328 void Metaspace::verify() {
  3329   vsm()->verify();
  3330   if (using_class_space()) {
  3331     class_vsm()->verify();
  3335 void Metaspace::dump(outputStream* const out) const {
  3336   out->print_cr("\nVirtual space manager: " INTPTR_FORMAT, vsm());
  3337   vsm()->dump(out);
  3338   if (using_class_space()) {
  3339     out->print_cr("\nClass space manager: " INTPTR_FORMAT, class_vsm());
  3340     class_vsm()->dump(out);

mercurial