src/share/vm/memory/metaspace.cpp

Tue, 18 Dec 2012 10:40:51 +0100

author
stefank
date
Tue, 18 Dec 2012 10:40:51 +0100
changeset 4371
c71879335291
parent 4327
eade6b2e4782
child 4382
e51c9860cf66
permissions
-rw-r--r--

8005108: NPG: MetaspaceAux::used_in_bytes(), capacity_in_bytes() and reserved_in_bytes() return inconsistent numbers
Summary: Reverted the changes to these functions from JDK-8000662
Reviewed-by: brutisso, jmasa

     1 /*
     2  * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  *
    23  */
    24 #include "precompiled.hpp"
    25 #include "gc_interface/collectedHeap.hpp"
    26 #include "memory/binaryTreeDictionary.hpp"
    27 #include "memory/freeList.hpp"
    28 #include "memory/collectorPolicy.hpp"
    29 #include "memory/filemap.hpp"
    30 #include "memory/freeList.hpp"
    31 #include "memory/metablock.hpp"
    32 #include "memory/metachunk.hpp"
    33 #include "memory/metaspace.hpp"
    34 #include "memory/metaspaceShared.hpp"
    35 #include "memory/resourceArea.hpp"
    36 #include "memory/universe.hpp"
    37 #include "runtime/globals.hpp"
    38 #include "runtime/mutex.hpp"
    39 #include "runtime/orderAccess.hpp"
    40 #include "services/memTracker.hpp"
    41 #include "utilities/copy.hpp"
    42 #include "utilities/debug.hpp"
    44 typedef BinaryTreeDictionary<Metablock, FreeList> BlockTreeDictionary;
    45 typedef BinaryTreeDictionary<Metachunk, FreeList> ChunkTreeDictionary;
    46 // Define this macro to enable slow integrity checking of
    47 // the free chunk lists
    48 const bool metaspace_slow_verify = false;
    51 // Parameters for stress mode testing
    52 const uint metadata_deallocate_a_lot_block = 10;
    53 const uint metadata_deallocate_a_lock_chunk = 3;
    54 size_t const allocation_from_dictionary_limit = 64 * K;
    55 const size_t metadata_deallocate = 0xf5f5f5f5;
    57 MetaWord* last_allocated = 0;
    59 // Used in declarations in SpaceManager and ChunkManager
    60 enum ChunkIndex {
    61   SmallIndex = 0,
    62   MediumIndex = 1,
    63   HumongousIndex = 2,
    64   NumberOfFreeLists = 2,
    65   NumberOfInUseLists = 3
    66 };
    68 static ChunkIndex next_chunk_index(ChunkIndex i) {
    69   assert(i < NumberOfInUseLists, "Out of bound");
    70   return (ChunkIndex) (i+1);
    71 }
    73 // Originally _capacity_until_GC was set to MetaspaceSize here but
    74 // the default MetaspaceSize before argument processing was being
    75 // used which was not the desired value.  See the code
    76 // in should_expand() to see how the initialization is handled
    77 // now.
    78 size_t MetaspaceGC::_capacity_until_GC = 0;
    79 bool MetaspaceGC::_expand_after_GC = false;
    80 uint MetaspaceGC::_shrink_factor = 0;
    81 bool MetaspaceGC::_should_concurrent_collect = false;
    83 // Blocks of space for metadata are allocated out of Metachunks.
    84 //
    85 // Metachunk are allocated out of MetadataVirtualspaces and once
    86 // allocated there is no explicit link between a Metachunk and
    87 // the MetadataVirtualspaces from which it was allocated.
    88 //
    89 // Each SpaceManager maintains a
    90 // list of the chunks it is using and the current chunk.  The current
    91 // chunk is the chunk from which allocations are done.  Space freed in
    92 // a chunk is placed on the free list of blocks (BlockFreelist) and
    93 // reused from there.
    95 // Pointer to list of Metachunks.
    96 class ChunkList VALUE_OBJ_CLASS_SPEC {
    97   // List of free chunks
    98   Metachunk* _head;
   100  public:
   101   // Constructor
   102   ChunkList() : _head(NULL) {}
   104   // Accessors
   105   Metachunk* head() { return _head; }
   106   void set_head(Metachunk* v) { _head = v; }
   108   // Link at head of the list
   109   void add_at_head(Metachunk* head, Metachunk* tail);
   110   void add_at_head(Metachunk* head);
   112   size_t sum_list_size();
   113   size_t sum_list_count();
   114   size_t sum_list_capacity();
   115 };
   117 // Manages the global free lists of chunks.
   118 // Has three lists of free chunks, and a total size and
   119 // count that includes all three
   121 class ChunkManager VALUE_OBJ_CLASS_SPEC {
   123   // Free list of chunks of different sizes.
   124   //   SmallChunk
   125   //   MediumChunk
   126   //   HumongousChunk
   127   ChunkList _free_chunks[NumberOfFreeLists];
   129   //   HumongousChunk
   130   ChunkTreeDictionary _humongous_dictionary;
   132   // ChunkManager in all lists of this type
   133   size_t _free_chunks_total;
   134   size_t _free_chunks_count;
   136   void dec_free_chunks_total(size_t v) {
   137     assert(_free_chunks_count > 0 &&
   138              _free_chunks_total > 0,
   139              "About to go negative");
   140     Atomic::add_ptr(-1, &_free_chunks_count);
   141     jlong minus_v = (jlong) - (jlong) v;
   142     Atomic::add_ptr(minus_v, &_free_chunks_total);
   143   }
   145   // Debug support
   147   size_t sum_free_chunks();
   148   size_t sum_free_chunks_count();
   150   void locked_verify_free_chunks_total();
   151   void slow_locked_verify_free_chunks_total() {
   152     if (metaspace_slow_verify) {
   153       locked_verify_free_chunks_total();
   154     }
   155   }
   156   void locked_verify_free_chunks_count();
   157   void slow_locked_verify_free_chunks_count() {
   158     if (metaspace_slow_verify) {
   159       locked_verify_free_chunks_count();
   160     }
   161   }
   162   void verify_free_chunks_count();
   164  public:
   166   ChunkManager() : _free_chunks_total(0), _free_chunks_count(0) {}
   168   // add or delete (return) a chunk to the global freelist.
   169   Metachunk* chunk_freelist_allocate(size_t word_size);
   170   void chunk_freelist_deallocate(Metachunk* chunk);
   172   // Total of the space in the free chunks list
   173   size_t free_chunks_total();
   174   size_t free_chunks_total_in_bytes();
   176   // Number of chunks in the free chunks list
   177   size_t free_chunks_count();
   179   void inc_free_chunks_total(size_t v, size_t count = 1) {
   180     Atomic::add_ptr(count, &_free_chunks_count);
   181     Atomic::add_ptr(v, &_free_chunks_total);
   182   }
   183   ChunkList* free_medium_chunks() { return &_free_chunks[1]; }
   184   ChunkList* free_small_chunks() { return &_free_chunks[0]; }
   185   ChunkTreeDictionary* humongous_dictionary() {
   186     return &_humongous_dictionary;
   187   }
   189   ChunkList* free_chunks(ChunkIndex index);
   191   // Returns the list for the given chunk word size.
   192   ChunkList* find_free_chunks_list(size_t word_size);
   194   // Add and remove from a list by size.  Selects
   195   // list based on size of chunk.
   196   void free_chunks_put(Metachunk* chuck);
   197   Metachunk* free_chunks_get(size_t chunk_word_size);
   199   // Debug support
   200   void verify();
   201   void slow_verify() {
   202     if (metaspace_slow_verify) {
   203       verify();
   204     }
   205   }
   206   void locked_verify();
   207   void slow_locked_verify() {
   208     if (metaspace_slow_verify) {
   209       locked_verify();
   210     }
   211   }
   212   void verify_free_chunks_total();
   214   void locked_print_free_chunks(outputStream* st);
   215   void locked_print_sum_free_chunks(outputStream* st);
   217   void print_on(outputStream* st);
   218 };
   221 // Used to manage the free list of Metablocks (a block corresponds
   222 // to the allocation of a quantum of metadata).
   223 class BlockFreelist VALUE_OBJ_CLASS_SPEC {
   224   BlockTreeDictionary* _dictionary;
   225   static Metablock* initialize_free_chunk(MetaWord* p, size_t word_size);
   227   // Accessors
   228   BlockTreeDictionary* dictionary() const { return _dictionary; }
   230  public:
   231   BlockFreelist();
   232   ~BlockFreelist();
   234   // Get and return a block to the free list
   235   MetaWord* get_block(size_t word_size);
   236   void return_block(MetaWord* p, size_t word_size);
   238   size_t total_size() {
   239   if (dictionary() == NULL) {
   240     return 0;
   241   } else {
   242     return dictionary()->total_size();
   243   }
   244 }
   246   void print_on(outputStream* st) const;
   247 };
   249 class VirtualSpaceNode : public CHeapObj<mtClass> {
   250   friend class VirtualSpaceList;
   252   // Link to next VirtualSpaceNode
   253   VirtualSpaceNode* _next;
   255   // total in the VirtualSpace
   256   MemRegion _reserved;
   257   ReservedSpace _rs;
   258   VirtualSpace _virtual_space;
   259   MetaWord* _top;
   261   // Convenience functions for logical bottom and end
   262   MetaWord* bottom() const { return (MetaWord*) _virtual_space.low(); }
   263   MetaWord* end() const { return (MetaWord*) _virtual_space.high(); }
   265   // Convenience functions to access the _virtual_space
   266   char* low()  const { return virtual_space()->low(); }
   267   char* high() const { return virtual_space()->high(); }
   269  public:
   271   VirtualSpaceNode(size_t byte_size);
   272   VirtualSpaceNode(ReservedSpace rs) : _top(NULL), _next(NULL), _rs(rs) {}
   273   ~VirtualSpaceNode();
   275   // address of next available space in _virtual_space;
   276   // Accessors
   277   VirtualSpaceNode* next() { return _next; }
   278   void set_next(VirtualSpaceNode* v) { _next = v; }
   280   void set_reserved(MemRegion const v) { _reserved = v; }
   281   void set_top(MetaWord* v) { _top = v; }
   283   // Accessors
   284   MemRegion* reserved() { return &_reserved; }
   285   VirtualSpace* virtual_space() const { return (VirtualSpace*) &_virtual_space; }
   287   // Returns true if "word_size" is available in the virtual space
   288   bool is_available(size_t word_size) { return _top + word_size <= end(); }
   290   MetaWord* top() const { return _top; }
   291   void inc_top(size_t word_size) { _top += word_size; }
   293   // used and capacity in this single entry in the list
   294   size_t used_words_in_vs() const;
   295   size_t capacity_words_in_vs() const;
   297   bool initialize();
   299   // get space from the virtual space
   300   Metachunk* take_from_committed(size_t chunk_word_size);
   302   // Allocate a chunk from the virtual space and return it.
   303   Metachunk* get_chunk_vs(size_t chunk_word_size);
   304   Metachunk* get_chunk_vs_with_expand(size_t chunk_word_size);
   306   // Expands/shrinks the committed space in a virtual space.  Delegates
   307   // to Virtualspace
   308   bool expand_by(size_t words, bool pre_touch = false);
   309   bool shrink_by(size_t words);
   311 #ifdef ASSERT
   312   // Debug support
   313   static void verify_virtual_space_total();
   314   static void verify_virtual_space_count();
   315   void mangle();
   316 #endif
   318   void print_on(outputStream* st) const;
   319 };
   321   // byte_size is the size of the associated virtualspace.
   322 VirtualSpaceNode::VirtualSpaceNode(size_t byte_size) : _top(NULL), _next(NULL), _rs(0) {
   323   // This allocates memory with mmap.  For DumpSharedspaces, allocate the
   324   // space at low memory so that other shared images don't conflict.
   325   // This is the same address as memory needed for UseCompressedOops but
   326   // compressed oops don't work with CDS (offsets in metadata are wrong), so
   327   // borrow the same address.
   328   if (DumpSharedSpaces) {
   329     char* shared_base = (char*)HeapBaseMinAddress;
   330     _rs = ReservedSpace(byte_size, 0, false, shared_base, 0);
   331     if (_rs.is_reserved()) {
   332       assert(_rs.base() == shared_base, "should match");
   333     } else {
   334       // If we are dumping the heap, then allocate a wasted block of address
   335       // space in order to push the heap to a lower address.  This extra
   336       // address range allows for other (or larger) libraries to be loaded
   337       // without them occupying the space required for the shared spaces.
   338       uintx reserved = 0;
   339       uintx block_size = 64*1024*1024;
   340       while (reserved < SharedDummyBlockSize) {
   341         char* dummy = os::reserve_memory(block_size);
   342         reserved += block_size;
   343       }
   344       _rs = ReservedSpace(byte_size);
   345     }
   346     MetaspaceShared::set_shared_rs(&_rs);
   347   } else {
   348     _rs = ReservedSpace(byte_size);
   349   }
   351   MemTracker::record_virtual_memory_type((address)_rs.base(), mtClass);
   352 }
   354 // List of VirtualSpaces for metadata allocation.
   355 // It has a  _next link for singly linked list and a MemRegion
   356 // for total space in the VirtualSpace.
   357 class VirtualSpaceList : public CHeapObj<mtClass> {
   358   friend class VirtualSpaceNode;
   360   enum VirtualSpaceSizes {
   361     VirtualSpaceSize = 256 * K
   362   };
   364   // Global list of virtual spaces
   365   // Head of the list
   366   VirtualSpaceNode* _virtual_space_list;
   367   // virtual space currently being used for allocations
   368   VirtualSpaceNode* _current_virtual_space;
   369   // Free chunk list for all other metadata
   370   ChunkManager      _chunk_manager;
   372   // Can this virtual list allocate >1 spaces?  Also, used to determine
   373   // whether to allocate unlimited small chunks in this virtual space
   374   bool _is_class;
   375   bool can_grow() const { return !is_class() || !UseCompressedKlassPointers; }
   377   // Sum of space in all virtual spaces and number of virtual spaces
   378   size_t _virtual_space_total;
   379   size_t _virtual_space_count;
   381   ~VirtualSpaceList();
   383   VirtualSpaceNode* virtual_space_list() const { return _virtual_space_list; }
   385   void set_virtual_space_list(VirtualSpaceNode* v) {
   386     _virtual_space_list = v;
   387   }
   388   void set_current_virtual_space(VirtualSpaceNode* v) {
   389     _current_virtual_space = v;
   390   }
   392   void link_vs(VirtualSpaceNode* new_entry, size_t vs_word_size);
   394   // Get another virtual space and add it to the list.  This
   395   // is typically prompted by a failed attempt to allocate a chunk
   396   // and is typically followed by the allocation of a chunk.
   397   bool grow_vs(size_t vs_word_size);
   399  public:
   400   VirtualSpaceList(size_t word_size);
   401   VirtualSpaceList(ReservedSpace rs);
   403   Metachunk* get_new_chunk(size_t word_size, size_t grow_chunks_by_words);
   405   VirtualSpaceNode* current_virtual_space() {
   406     return _current_virtual_space;
   407   }
   409   ChunkManager* chunk_manager() { return &_chunk_manager; }
   410   bool is_class() const { return _is_class; }
   412   // Allocate the first virtualspace.
   413   void initialize(size_t word_size);
   415   size_t virtual_space_total() { return _virtual_space_total; }
   416   void inc_virtual_space_total(size_t v) {
   417     Atomic::add_ptr(v, &_virtual_space_total);
   418   }
   420   size_t virtual_space_count() { return _virtual_space_count; }
   421   void inc_virtual_space_count() {
   422     Atomic::inc_ptr(&_virtual_space_count);
   423   }
   425   // Used and capacity in the entire list of virtual spaces.
   426   // These are global values shared by all Metaspaces
   427   size_t capacity_words_sum();
   428   size_t capacity_bytes_sum() { return capacity_words_sum() * BytesPerWord; }
   429   size_t used_words_sum();
   430   size_t used_bytes_sum() { return used_words_sum() * BytesPerWord; }
   432   bool contains(const void *ptr);
   434   void print_on(outputStream* st) const;
   436   class VirtualSpaceListIterator : public StackObj {
   437     VirtualSpaceNode* _virtual_spaces;
   438    public:
   439     VirtualSpaceListIterator(VirtualSpaceNode* virtual_spaces) :
   440       _virtual_spaces(virtual_spaces) {}
   442     bool repeat() {
   443       return _virtual_spaces != NULL;
   444     }
   446     VirtualSpaceNode* get_next() {
   447       VirtualSpaceNode* result = _virtual_spaces;
   448       if (_virtual_spaces != NULL) {
   449         _virtual_spaces = _virtual_spaces->next();
   450       }
   451       return result;
   452     }
   453   };
   454 };
   456 class Metadebug : AllStatic {
   457   // Debugging support for Metaspaces
   458   static int _deallocate_block_a_lot_count;
   459   static int _deallocate_chunk_a_lot_count;
   460   static int _allocation_fail_alot_count;
   462  public:
   463   static int deallocate_block_a_lot_count() {
   464     return _deallocate_block_a_lot_count;
   465   }
   466   static void set_deallocate_block_a_lot_count(int v) {
   467     _deallocate_block_a_lot_count = v;
   468   }
   469   static void inc_deallocate_block_a_lot_count() {
   470     _deallocate_block_a_lot_count++;
   471   }
   472   static int deallocate_chunk_a_lot_count() {
   473     return _deallocate_chunk_a_lot_count;
   474   }
   475   static void reset_deallocate_chunk_a_lot_count() {
   476     _deallocate_chunk_a_lot_count = 1;
   477   }
   478   static void inc_deallocate_chunk_a_lot_count() {
   479     _deallocate_chunk_a_lot_count++;
   480   }
   482   static void init_allocation_fail_alot_count();
   483 #ifdef ASSERT
   484   static bool test_metadata_failure();
   485 #endif
   487   static void deallocate_chunk_a_lot(SpaceManager* sm,
   488                                      size_t chunk_word_size);
   489   static void deallocate_block_a_lot(SpaceManager* sm,
   490                                      size_t chunk_word_size);
   492 };
   494 int Metadebug::_deallocate_block_a_lot_count = 0;
   495 int Metadebug::_deallocate_chunk_a_lot_count = 0;
   496 int Metadebug::_allocation_fail_alot_count = 0;
   498 //  SpaceManager - used by Metaspace to handle allocations
   499 class SpaceManager : public CHeapObj<mtClass> {
   500   friend class Metaspace;
   501   friend class Metadebug;
   503  private:
   504   // protects allocations and contains.
   505   Mutex* const _lock;
   507   // List of chunks in use by this SpaceManager.  Allocations
   508   // are done from the current chunk.  The list is used for deallocating
   509   // chunks when the SpaceManager is freed.
   510   Metachunk* _chunks_in_use[NumberOfInUseLists];
   511   Metachunk* _current_chunk;
   513   // Virtual space where allocation comes from.
   514   VirtualSpaceList* _vs_list;
   516   // Number of small chunks to allocate to a manager
   517   // If class space manager, small chunks are unlimited
   518   static uint const _small_chunk_limit;
   519   bool has_small_chunk_limit() { return !vs_list()->is_class(); }
   521   // Sum of all space in allocated chunks
   522   size_t _allocation_total;
   524   // Free lists of blocks are per SpaceManager since they
   525   // are assumed to be in chunks in use by the SpaceManager
   526   // and all chunks in use by a SpaceManager are freed when
   527   // the class loader using the SpaceManager is collected.
   528   BlockFreelist _block_freelists;
   530   // protects virtualspace and chunk expansions
   531   static const char*  _expand_lock_name;
   532   static const int    _expand_lock_rank;
   533   static Mutex* const _expand_lock;
   535   // Accessors
   536   Metachunk* chunks_in_use(ChunkIndex index) const { return _chunks_in_use[index]; }
   537   void set_chunks_in_use(ChunkIndex index, Metachunk* v) { _chunks_in_use[index] = v; }
   539   BlockFreelist* block_freelists() const {
   540     return (BlockFreelist*) &_block_freelists;
   541   }
   543   VirtualSpaceList* vs_list() const    { return _vs_list; }
   545   Metachunk* current_chunk() const { return _current_chunk; }
   546   void set_current_chunk(Metachunk* v) {
   547     _current_chunk = v;
   548   }
   550   Metachunk* find_current_chunk(size_t word_size);
   552   // Add chunk to the list of chunks in use
   553   void add_chunk(Metachunk* v, bool make_current);
   555   Mutex* lock() const { return _lock; }
   557  public:
   558   SpaceManager(Mutex* lock, VirtualSpaceList* vs_list);
   559   ~SpaceManager();
   561   enum ChunkSizes {    // in words.
   562     SmallChunk = 512,
   563     MediumChunk = 8 * K,
   564     MediumChunkBunch = 4 * MediumChunk
   565   };
   567   // Accessors
   568   size_t allocation_total() const { return _allocation_total; }
   569   void inc_allocation_total(size_t v) { Atomic::add_ptr(v, &_allocation_total); }
   570   static bool is_humongous(size_t word_size) { return word_size > MediumChunk; }
   572   static Mutex* expand_lock() { return _expand_lock; }
   574   size_t sum_capacity_in_chunks_in_use() const;
   575   size_t sum_used_in_chunks_in_use() const;
   576   size_t sum_free_in_chunks_in_use() const;
   577   size_t sum_waste_in_chunks_in_use() const;
   578   size_t sum_waste_in_chunks_in_use(ChunkIndex index ) const;
   580   size_t sum_count_in_chunks_in_use();
   581   size_t sum_count_in_chunks_in_use(ChunkIndex i);
   583   // Block allocation and deallocation.
   584   // Allocates a block from the current chunk
   585   MetaWord* allocate(size_t word_size);
   587   // Helper for allocations
   588   MetaWord* allocate_work(size_t word_size);
   590   // Returns a block to the per manager freelist
   591   void deallocate(MetaWord* p, size_t word_size);
   593   // Based on the allocation size and a minimum chunk size,
   594   // returned chunk size (for expanding space for chunk allocation).
   595   size_t calc_chunk_size(size_t allocation_word_size);
   597   // Called when an allocation from the current chunk fails.
   598   // Gets a new chunk (may require getting a new virtual space),
   599   // and allocates from that chunk.
   600   MetaWord* grow_and_allocate(size_t word_size);
   602   // debugging support.
   604   void dump(outputStream* const out) const;
   605   void print_on(outputStream* st) const;
   606   void locked_print_chunks_in_use_on(outputStream* st) const;
   608   void verify();
   609   void verify_chunk_size(Metachunk* chunk);
   610   NOT_PRODUCT(void mangle_freed_chunks();)
   611 #ifdef ASSERT
   612   void verify_allocation_total();
   613 #endif
   614 };
   616 uint const SpaceManager::_small_chunk_limit = 4;
   618 const char* SpaceManager::_expand_lock_name =
   619   "SpaceManager chunk allocation lock";
   620 const int SpaceManager::_expand_lock_rank = Monitor::leaf - 1;
   621 Mutex* const SpaceManager::_expand_lock =
   622   new Mutex(SpaceManager::_expand_lock_rank,
   623             SpaceManager::_expand_lock_name,
   624             Mutex::_allow_vm_block_flag);
   626 // BlockFreelist methods
   628 BlockFreelist::BlockFreelist() : _dictionary(NULL) {}
   630 BlockFreelist::~BlockFreelist() {
   631   if (_dictionary != NULL) {
   632     if (Verbose && TraceMetadataChunkAllocation) {
   633       _dictionary->print_free_lists(gclog_or_tty);
   634     }
   635     delete _dictionary;
   636   }
   637 }
   639 Metablock* BlockFreelist::initialize_free_chunk(MetaWord* p, size_t word_size) {
   640   Metablock* block = (Metablock*) p;
   641   block->set_word_size(word_size);
   642   block->set_prev(NULL);
   643   block->set_next(NULL);
   645   return block;
   646 }
   648 void BlockFreelist::return_block(MetaWord* p, size_t word_size) {
   649   Metablock* free_chunk = initialize_free_chunk(p, word_size);
   650   if (dictionary() == NULL) {
   651    _dictionary = new BlockTreeDictionary();
   652   }
   653   dictionary()->return_chunk(free_chunk);
   654 }
   656 MetaWord* BlockFreelist::get_block(size_t word_size) {
   657   if (dictionary() == NULL) {
   658     return NULL;
   659   }
   661   if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
   662     // Dark matter.  Too small for dictionary.
   663     return NULL;
   664   }
   666   Metablock* free_block =
   667     dictionary()->get_chunk(word_size, FreeBlockDictionary<Metablock>::exactly);
   668   if (free_block == NULL) {
   669     return NULL;
   670   }
   672   return (MetaWord*) free_block;
   673 }
   675 void BlockFreelist::print_on(outputStream* st) const {
   676   if (dictionary() == NULL) {
   677     return;
   678   }
   679   dictionary()->print_free_lists(st);
   680 }
   682 // VirtualSpaceNode methods
   684 VirtualSpaceNode::~VirtualSpaceNode() {
   685   _rs.release();
   686 }
   688 size_t VirtualSpaceNode::used_words_in_vs() const {
   689   return pointer_delta(top(), bottom(), sizeof(MetaWord));
   690 }
   692 // Space committed in the VirtualSpace
   693 size_t VirtualSpaceNode::capacity_words_in_vs() const {
   694   return pointer_delta(end(), bottom(), sizeof(MetaWord));
   695 }
   698 // Allocates the chunk from the virtual space only.
   699 // This interface is also used internally for debugging.  Not all
   700 // chunks removed here are necessarily used for allocation.
   701 Metachunk* VirtualSpaceNode::take_from_committed(size_t chunk_word_size) {
   702   // Bottom of the new chunk
   703   MetaWord* chunk_limit = top();
   704   assert(chunk_limit != NULL, "Not safe to call this method");
   706   if (!is_available(chunk_word_size)) {
   707     if (TraceMetadataChunkAllocation) {
   708       tty->print("VirtualSpaceNode::take_from_committed() not available %d words ", chunk_word_size);
   709       // Dump some information about the virtual space that is nearly full
   710       print_on(tty);
   711     }
   712     return NULL;
   713   }
   715   // Take the space  (bump top on the current virtual space).
   716   inc_top(chunk_word_size);
   718   // Point the chunk at the space
   719   Metachunk* result = Metachunk::initialize(chunk_limit, chunk_word_size);
   720   return result;
   721 }
   724 // Expand the virtual space (commit more of the reserved space)
   725 bool VirtualSpaceNode::expand_by(size_t words, bool pre_touch) {
   726   size_t bytes = words * BytesPerWord;
   727   bool result =  virtual_space()->expand_by(bytes, pre_touch);
   728   if (TraceMetavirtualspaceAllocation && !result) {
   729     gclog_or_tty->print_cr("VirtualSpaceNode::expand_by() failed "
   730                            "for byte size " SIZE_FORMAT, bytes);
   731     virtual_space()->print();
   732   }
   733   return result;
   734 }
   736 // Shrink the virtual space (commit more of the reserved space)
   737 bool VirtualSpaceNode::shrink_by(size_t words) {
   738   size_t bytes = words * BytesPerWord;
   739   virtual_space()->shrink_by(bytes);
   740   return true;
   741 }
   743 // Add another chunk to the chunk list.
   745 Metachunk* VirtualSpaceNode::get_chunk_vs(size_t chunk_word_size) {
   746   assert_lock_strong(SpaceManager::expand_lock());
   747   Metachunk* result = NULL;
   749   return take_from_committed(chunk_word_size);
   750 }
   752 Metachunk* VirtualSpaceNode::get_chunk_vs_with_expand(size_t chunk_word_size) {
   753   assert_lock_strong(SpaceManager::expand_lock());
   755   Metachunk* new_chunk = get_chunk_vs(chunk_word_size);
   757   if (new_chunk == NULL) {
   758     // Only a small part of the virtualspace is committed when first
   759     // allocated so committing more here can be expected.
   760     size_t page_size_words = os::vm_page_size() / BytesPerWord;
   761     size_t aligned_expand_vs_by_words = align_size_up(chunk_word_size,
   762                                                     page_size_words);
   763     expand_by(aligned_expand_vs_by_words, false);
   764     new_chunk = get_chunk_vs(chunk_word_size);
   765   }
   766   return new_chunk;
   767 }
   769 bool VirtualSpaceNode::initialize() {
   771   if (!_rs.is_reserved()) {
   772     return false;
   773   }
   775   // Commit only 1 page instead of the whole reserved space _rs.size()
   776   size_t committed_byte_size = os::vm_page_size();
   777   bool result = virtual_space()->initialize(_rs, committed_byte_size);
   778   if (result) {
   779     set_top((MetaWord*)virtual_space()->low());
   780     set_reserved(MemRegion((HeapWord*)_rs.base(),
   781                  (HeapWord*)(_rs.base() + _rs.size())));
   783     assert(reserved()->start() == (HeapWord*) _rs.base(),
   784       err_msg("Reserved start was not set properly " PTR_FORMAT
   785         " != " PTR_FORMAT, reserved()->start(), _rs.base()));
   786     assert(reserved()->word_size() == _rs.size() / BytesPerWord,
   787       err_msg("Reserved size was not set properly " SIZE_FORMAT
   788         " != " SIZE_FORMAT, reserved()->word_size(),
   789         _rs.size() / BytesPerWord));
   790   }
   792   return result;
   793 }
   795 void VirtualSpaceNode::print_on(outputStream* st) const {
   796   size_t used = used_words_in_vs();
   797   size_t capacity = capacity_words_in_vs();
   798   VirtualSpace* vs = virtual_space();
   799   st->print_cr("   space @ " PTR_FORMAT " " SIZE_FORMAT "K, %3d%% used "
   800            "[" PTR_FORMAT ", " PTR_FORMAT ", "
   801            PTR_FORMAT ", " PTR_FORMAT ")",
   802            vs, capacity / K, used * 100 / capacity,
   803            bottom(), top(), end(),
   804            vs->high_boundary());
   805 }
   807 #ifdef ASSERT
   808 void VirtualSpaceNode::mangle() {
   809   size_t word_size = capacity_words_in_vs();
   810   Copy::fill_to_words((HeapWord*) low(), word_size, 0xf1f1f1f1);
   811 }
   812 #endif // ASSERT
   814 // VirtualSpaceList methods
   815 // Space allocated from the VirtualSpace
   817 VirtualSpaceList::~VirtualSpaceList() {
   818   VirtualSpaceListIterator iter(virtual_space_list());
   819   while (iter.repeat()) {
   820     VirtualSpaceNode* vsl = iter.get_next();
   821     delete vsl;
   822   }
   823 }
   825 size_t VirtualSpaceList::used_words_sum() {
   826   size_t allocated_by_vs = 0;
   827   VirtualSpaceListIterator iter(virtual_space_list());
   828   while (iter.repeat()) {
   829     VirtualSpaceNode* vsl = iter.get_next();
   830     // Sum used region [bottom, top) in each virtualspace
   831     allocated_by_vs += vsl->used_words_in_vs();
   832   }
   833   assert(allocated_by_vs >= chunk_manager()->free_chunks_total(),
   834     err_msg("Total in free chunks " SIZE_FORMAT
   835             " greater than total from virtual_spaces " SIZE_FORMAT,
   836             allocated_by_vs, chunk_manager()->free_chunks_total()));
   837   size_t used =
   838     allocated_by_vs - chunk_manager()->free_chunks_total();
   839   return used;
   840 }
   842 // Space available in all MetadataVirtualspaces allocated
   843 // for metadata.  This is the upper limit on the capacity
   844 // of chunks allocated out of all the MetadataVirtualspaces.
   845 size_t VirtualSpaceList::capacity_words_sum() {
   846   size_t capacity = 0;
   847   VirtualSpaceListIterator iter(virtual_space_list());
   848   while (iter.repeat()) {
   849     VirtualSpaceNode* vsl = iter.get_next();
   850     capacity += vsl->capacity_words_in_vs();
   851   }
   852   return capacity;
   853 }
   855 VirtualSpaceList::VirtualSpaceList(size_t word_size ) :
   856                                    _is_class(false),
   857                                    _virtual_space_list(NULL),
   858                                    _current_virtual_space(NULL),
   859                                    _virtual_space_total(0),
   860                                    _virtual_space_count(0) {
   861   MutexLockerEx cl(SpaceManager::expand_lock(),
   862                    Mutex::_no_safepoint_check_flag);
   863   bool initialization_succeeded = grow_vs(word_size);
   865   assert(initialization_succeeded,
   866     " VirtualSpaceList initialization should not fail");
   867 }
   869 VirtualSpaceList::VirtualSpaceList(ReservedSpace rs) :
   870                                    _is_class(true),
   871                                    _virtual_space_list(NULL),
   872                                    _current_virtual_space(NULL),
   873                                    _virtual_space_total(0),
   874                                    _virtual_space_count(0) {
   875   MutexLockerEx cl(SpaceManager::expand_lock(),
   876                    Mutex::_no_safepoint_check_flag);
   877   VirtualSpaceNode* class_entry = new VirtualSpaceNode(rs);
   878   bool succeeded = class_entry->initialize();
   879   assert(succeeded, " VirtualSpaceList initialization should not fail");
   880   link_vs(class_entry, rs.size()/BytesPerWord);
   881 }
   883 // Allocate another meta virtual space and add it to the list.
   884 bool VirtualSpaceList::grow_vs(size_t vs_word_size) {
   885   assert_lock_strong(SpaceManager::expand_lock());
   886   if (vs_word_size == 0) {
   887     return false;
   888   }
   889   // Reserve the space
   890   size_t vs_byte_size = vs_word_size * BytesPerWord;
   891   assert(vs_byte_size % os::vm_page_size() == 0, "Not aligned");
   893   // Allocate the meta virtual space and initialize it.
   894   VirtualSpaceNode* new_entry = new VirtualSpaceNode(vs_byte_size);
   895   if (!new_entry->initialize()) {
   896     delete new_entry;
   897     return false;
   898   } else {
   899     // ensure lock-free iteration sees fully initialized node
   900     OrderAccess::storestore();
   901     link_vs(new_entry, vs_word_size);
   902     return true;
   903   }
   904 }
   906 void VirtualSpaceList::link_vs(VirtualSpaceNode* new_entry, size_t vs_word_size) {
   907   if (virtual_space_list() == NULL) {
   908       set_virtual_space_list(new_entry);
   909   } else {
   910     current_virtual_space()->set_next(new_entry);
   911   }
   912   set_current_virtual_space(new_entry);
   913   inc_virtual_space_total(vs_word_size);
   914   inc_virtual_space_count();
   915 #ifdef ASSERT
   916   new_entry->mangle();
   917 #endif
   918   if (TraceMetavirtualspaceAllocation && Verbose) {
   919     VirtualSpaceNode* vsl = current_virtual_space();
   920     vsl->print_on(tty);
   921   }
   922 }
   924 Metachunk* VirtualSpaceList::get_new_chunk(size_t word_size,
   925                                            size_t grow_chunks_by_words) {
   927   // Get a chunk from the chunk freelist
   928   Metachunk* next = chunk_manager()->chunk_freelist_allocate(grow_chunks_by_words);
   930   // Allocate a chunk out of the current virtual space.
   931   if (next == NULL) {
   932     next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
   933   }
   935   if (next == NULL) {
   936     // Not enough room in current virtual space.  Try to commit
   937     // more space.
   938     size_t expand_vs_by_words = MAX2((size_t)SpaceManager::MediumChunkBunch,
   939                                        grow_chunks_by_words);
   940     size_t page_size_words = os::vm_page_size() / BytesPerWord;
   941     size_t aligned_expand_vs_by_words = align_size_up(expand_vs_by_words,
   942                                                         page_size_words);
   943     bool vs_expanded =
   944       current_virtual_space()->expand_by(aligned_expand_vs_by_words, false);
   945     if (!vs_expanded) {
   946       // Should the capacity of the metaspaces be expanded for
   947       // this allocation?  If it's the virtual space for classes and is
   948       // being used for CompressedHeaders, don't allocate a new virtualspace.
   949       if (can_grow() && MetaspaceGC::should_expand(this, word_size)) {
   950         // Get another virtual space.
   951           size_t grow_vs_words =
   952             MAX2((size_t)VirtualSpaceSize, aligned_expand_vs_by_words);
   953         if (grow_vs(grow_vs_words)) {
   954           // Got it.  It's on the list now.  Get a chunk from it.
   955           next = current_virtual_space()->get_chunk_vs_with_expand(grow_chunks_by_words);
   956         }
   957         if (TraceMetadataHumongousAllocation && SpaceManager::is_humongous(word_size)) {
   958           gclog_or_tty->print_cr("  aligned_expand_vs_by_words " PTR_FORMAT,
   959                                  aligned_expand_vs_by_words);
   960           gclog_or_tty->print_cr("  grow_vs_words " PTR_FORMAT,
   961                                  grow_vs_words);
   962         }
   963       } else {
   964         // Allocation will fail and induce a GC
   965         if (TraceMetadataChunkAllocation && Verbose) {
   966           gclog_or_tty->print_cr("VirtualSpaceList::get_new_chunk():"
   967             " Fail instead of expand the metaspace");
   968         }
   969       }
   970     } else {
   971       // The virtual space expanded, get a new chunk
   972       next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
   973       assert(next != NULL, "Just expanded, should succeed");
   974     }
   975   }
   977   return next;
   978 }
   980 void VirtualSpaceList::print_on(outputStream* st) const {
   981   if (TraceMetadataChunkAllocation && Verbose) {
   982     VirtualSpaceListIterator iter(virtual_space_list());
   983     while (iter.repeat()) {
   984       VirtualSpaceNode* node = iter.get_next();
   985       node->print_on(st);
   986     }
   987   }
   988 }
   990 bool VirtualSpaceList::contains(const void *ptr) {
   991   VirtualSpaceNode* list = virtual_space_list();
   992   VirtualSpaceListIterator iter(list);
   993   while (iter.repeat()) {
   994     VirtualSpaceNode* node = iter.get_next();
   995     if (node->reserved()->contains(ptr)) {
   996       return true;
   997     }
   998   }
   999   return false;
  1003 // MetaspaceGC methods
  1005 // VM_CollectForMetadataAllocation is the vm operation used to GC.
  1006 // Within the VM operation after the GC the attempt to allocate the metadata
  1007 // should succeed.  If the GC did not free enough space for the metaspace
  1008 // allocation, the HWM is increased so that another virtualspace will be
  1009 // allocated for the metadata.  With perm gen the increase in the perm
  1010 // gen had bounds, MinMetaspaceExpansion and MaxMetaspaceExpansion.  The
  1011 // metaspace policy uses those as the small and large steps for the HWM.
  1012 //
  1013 // After the GC the compute_new_size() for MetaspaceGC is called to
  1014 // resize the capacity of the metaspaces.  The current implementation
  1015 // is based on the flags MinHeapFreeRatio and MaxHeapFreeRatio used
  1016 // to resize the Java heap by some GC's.  New flags can be implemented
  1017 // if really needed.  MinHeapFreeRatio is used to calculate how much
  1018 // free space is desirable in the metaspace capacity to decide how much
  1019 // to increase the HWM.  MaxHeapFreeRatio is used to decide how much
  1020 // free space is desirable in the metaspace capacity before decreasing
  1021 // the HWM.
  1023 // Calculate the amount to increase the high water mark (HWM).
  1024 // Increase by a minimum amount (MinMetaspaceExpansion) so that
  1025 // another expansion is not requested too soon.  If that is not
  1026 // enough to satisfy the allocation (i.e. big enough for a word_size
  1027 // allocation), increase by MaxMetaspaceExpansion.  If that is still
  1028 // not enough, expand by the size of the allocation (word_size) plus
  1029 // some.
  1030 size_t MetaspaceGC::delta_capacity_until_GC(size_t word_size) {
  1031   size_t before_inc = MetaspaceGC::capacity_until_GC();
  1032   size_t min_delta_words = MinMetaspaceExpansion / BytesPerWord;
  1033   size_t max_delta_words = MaxMetaspaceExpansion / BytesPerWord;
  1034   size_t page_size_words = os::vm_page_size() / BytesPerWord;
  1035   size_t size_delta_words = align_size_up(word_size, page_size_words);
  1036   size_t delta_words = MAX2(size_delta_words, min_delta_words);
  1037   if (delta_words > min_delta_words) {
  1038     // Don't want to hit the high water mark on the next
  1039     // allocation so make the delta greater than just enough
  1040     // for this allocation.
  1041     delta_words = MAX2(delta_words, max_delta_words);
  1042     if (delta_words > max_delta_words) {
  1043       // This allocation is large but the next ones are probably not
  1044       // so increase by the minimum.
  1045       delta_words = delta_words + min_delta_words;
  1048   return delta_words;
  1051 bool MetaspaceGC::should_expand(VirtualSpaceList* vsl, size_t word_size) {
  1053   // Class virtual space should always be expanded.  Call GC for the other
  1054   // metadata virtual space.
  1055   if (vsl == Metaspace::class_space_list()) return true;
  1057   // If the user wants a limit, impose one.
  1058   size_t max_metaspace_size_words = MaxMetaspaceSize / BytesPerWord;
  1059   size_t metaspace_size_words = MetaspaceSize / BytesPerWord;
  1060   if (!FLAG_IS_DEFAULT(MaxMetaspaceSize) &&
  1061       vsl->capacity_words_sum() >= max_metaspace_size_words) {
  1062     return false;
  1065   // If this is part of an allocation after a GC, expand
  1066   // unconditionally.
  1067   if(MetaspaceGC::expand_after_GC()) {
  1068     return true;
  1071   // If the capacity is below the minimum capacity, allow the
  1072   // expansion.  Also set the high-water-mark (capacity_until_GC)
  1073   // to that minimum capacity so that a GC will not be induced
  1074   // until that minimum capacity is exceeded.
  1075   if (vsl->capacity_words_sum() < metaspace_size_words ||
  1076       capacity_until_GC() == 0) {
  1077     set_capacity_until_GC(metaspace_size_words);
  1078     return true;
  1079   } else {
  1080     if (vsl->capacity_words_sum() < capacity_until_GC()) {
  1081       return true;
  1082     } else {
  1083       if (TraceMetadataChunkAllocation && Verbose) {
  1084         gclog_or_tty->print_cr("  allocation request size " SIZE_FORMAT
  1085                         "  capacity_until_GC " SIZE_FORMAT
  1086                         "  capacity_words_sum " SIZE_FORMAT
  1087                         "  used_words_sum " SIZE_FORMAT
  1088                         "  free chunks " SIZE_FORMAT
  1089                         "  free chunks count %d",
  1090                         word_size,
  1091                         capacity_until_GC(),
  1092                         vsl->capacity_words_sum(),
  1093                         vsl->used_words_sum(),
  1094                         vsl->chunk_manager()->free_chunks_total(),
  1095                         vsl->chunk_manager()->free_chunks_count());
  1097       return false;
  1102 // Variables are in bytes
  1104 void MetaspaceGC::compute_new_size() {
  1105   assert(_shrink_factor <= 100, "invalid shrink factor");
  1106   uint current_shrink_factor = _shrink_factor;
  1107   _shrink_factor = 0;
  1109   VirtualSpaceList *vsl = Metaspace::space_list();
  1111   size_t capacity_after_gc = vsl->capacity_bytes_sum();
  1112   // Check to see if these two can be calculated without walking the CLDG
  1113   size_t used_after_gc = vsl->used_bytes_sum();
  1114   size_t capacity_until_GC = vsl->capacity_bytes_sum();
  1115   size_t free_after_gc = capacity_until_GC - used_after_gc;
  1117   const double minimum_free_percentage = MinHeapFreeRatio / 100.0;
  1118   const double maximum_used_percentage = 1.0 - minimum_free_percentage;
  1120   const double min_tmp = used_after_gc / maximum_used_percentage;
  1121   size_t minimum_desired_capacity =
  1122     (size_t)MIN2(min_tmp, double(max_uintx));
  1123   // Don't shrink less than the initial generation size
  1124   minimum_desired_capacity = MAX2(minimum_desired_capacity,
  1125                                   MetaspaceSize);
  1127   if (PrintGCDetails && Verbose) {
  1128     const double free_percentage = ((double)free_after_gc) / capacity_until_GC;
  1129     gclog_or_tty->print_cr("\nMetaspaceGC::compute_new_size: ");
  1130     gclog_or_tty->print_cr("  "
  1131                   "  minimum_free_percentage: %6.2f"
  1132                   "  maximum_used_percentage: %6.2f",
  1133                   minimum_free_percentage,
  1134                   maximum_used_percentage);
  1135     double d_free_after_gc = free_after_gc / (double) K;
  1136     gclog_or_tty->print_cr("  "
  1137                   "   free_after_gc       : %6.1fK"
  1138                   "   used_after_gc       : %6.1fK"
  1139                   "   capacity_after_gc   : %6.1fK"
  1140                   "   metaspace HWM     : %6.1fK",
  1141                   free_after_gc / (double) K,
  1142                   used_after_gc / (double) K,
  1143                   capacity_after_gc / (double) K,
  1144                   capacity_until_GC / (double) K);
  1145     gclog_or_tty->print_cr("  "
  1146                   "   free_percentage: %6.2f",
  1147                   free_percentage);
  1151   if (capacity_until_GC < minimum_desired_capacity) {
  1152     // If we have less capacity below the metaspace HWM, then
  1153     // increment the HWM.
  1154     size_t expand_bytes = minimum_desired_capacity - capacity_until_GC;
  1155     // Don't expand unless it's significant
  1156     if (expand_bytes >= MinMetaspaceExpansion) {
  1157       size_t expand_words = expand_bytes / BytesPerWord;
  1158       MetaspaceGC::inc_capacity_until_GC(expand_words);
  1160     if (PrintGCDetails && Verbose) {
  1161       size_t new_capacity_until_GC = MetaspaceGC::capacity_until_GC_in_bytes();
  1162       gclog_or_tty->print_cr("    expanding:"
  1163                     "  minimum_desired_capacity: %6.1fK"
  1164                     "  expand_words: %6.1fK"
  1165                     "  MinMetaspaceExpansion: %6.1fK"
  1166                     "  new metaspace HWM:  %6.1fK",
  1167                     minimum_desired_capacity / (double) K,
  1168                     expand_bytes / (double) K,
  1169                     MinMetaspaceExpansion / (double) K,
  1170                     new_capacity_until_GC / (double) K);
  1172     return;
  1175   // No expansion, now see if we want to shrink
  1176   size_t shrink_words = 0;
  1177   // We would never want to shrink more than this
  1178   size_t max_shrink_words = capacity_until_GC - minimum_desired_capacity;
  1179   assert(max_shrink_words >= 0, err_msg("max_shrink_words " SIZE_FORMAT,
  1180     max_shrink_words));
  1182   // Should shrinking be considered?
  1183   if (MaxHeapFreeRatio < 100) {
  1184     const double maximum_free_percentage = MaxHeapFreeRatio / 100.0;
  1185     const double minimum_used_percentage = 1.0 - maximum_free_percentage;
  1186     const double max_tmp = used_after_gc / minimum_used_percentage;
  1187     size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(max_uintx));
  1188     maximum_desired_capacity = MAX2(maximum_desired_capacity,
  1189                                     MetaspaceSize);
  1190     if (PrintGC && Verbose) {
  1191       gclog_or_tty->print_cr("  "
  1192                              "  maximum_free_percentage: %6.2f"
  1193                              "  minimum_used_percentage: %6.2f",
  1194                              maximum_free_percentage,
  1195                              minimum_used_percentage);
  1196       gclog_or_tty->print_cr("  "
  1197                              "  capacity_until_GC: %6.1fK"
  1198                              "  minimum_desired_capacity: %6.1fK"
  1199                              "  maximum_desired_capacity: %6.1fK",
  1200                              capacity_until_GC / (double) K,
  1201                              minimum_desired_capacity / (double) K,
  1202                              maximum_desired_capacity / (double) K);
  1205     assert(minimum_desired_capacity <= maximum_desired_capacity,
  1206            "sanity check");
  1208     if (capacity_until_GC > maximum_desired_capacity) {
  1209       // Capacity too large, compute shrinking size
  1210       shrink_words = capacity_until_GC - maximum_desired_capacity;
  1211       // We don't want shrink all the way back to initSize if people call
  1212       // System.gc(), because some programs do that between "phases" and then
  1213       // we'd just have to grow the heap up again for the next phase.  So we
  1214       // damp the shrinking: 0% on the first call, 10% on the second call, 40%
  1215       // on the third call, and 100% by the fourth call.  But if we recompute
  1216       // size without shrinking, it goes back to 0%.
  1217       shrink_words = shrink_words / 100 * current_shrink_factor;
  1218       assert(shrink_words <= max_shrink_words,
  1219         err_msg("invalid shrink size " SIZE_FORMAT " not <= " SIZE_FORMAT,
  1220           shrink_words, max_shrink_words));
  1221       if (current_shrink_factor == 0) {
  1222         _shrink_factor = 10;
  1223       } else {
  1224         _shrink_factor = MIN2(current_shrink_factor * 4, (uint) 100);
  1226       if (PrintGCDetails && Verbose) {
  1227         gclog_or_tty->print_cr("  "
  1228                       "  shrinking:"
  1229                       "  initSize: %.1fK"
  1230                       "  maximum_desired_capacity: %.1fK",
  1231                       MetaspaceSize / (double) K,
  1232                       maximum_desired_capacity / (double) K);
  1233         gclog_or_tty->print_cr("  "
  1234                       "  shrink_words: %.1fK"
  1235                       "  current_shrink_factor: %d"
  1236                       "  new shrink factor: %d"
  1237                       "  MinMetaspaceExpansion: %.1fK",
  1238                       shrink_words / (double) K,
  1239                       current_shrink_factor,
  1240                       _shrink_factor,
  1241                       MinMetaspaceExpansion / (double) K);
  1247   // Don't shrink unless it's significant
  1248   if (shrink_words >= MinMetaspaceExpansion) {
  1249     VirtualSpaceNode* csp = vsl->current_virtual_space();
  1250     size_t available_to_shrink = csp->capacity_words_in_vs() -
  1251       csp->used_words_in_vs();
  1252     shrink_words = MIN2(shrink_words, available_to_shrink);
  1253     csp->shrink_by(shrink_words);
  1254     MetaspaceGC::dec_capacity_until_GC(shrink_words);
  1255     if (PrintGCDetails && Verbose) {
  1256       size_t new_capacity_until_GC = MetaspaceGC::capacity_until_GC_in_bytes();
  1257       gclog_or_tty->print_cr("  metaspace HWM: %.1fK", new_capacity_until_GC / (double) K);
  1260   assert(vsl->used_bytes_sum() == used_after_gc &&
  1261          used_after_gc <= vsl->capacity_bytes_sum(),
  1262          "sanity check");
  1266 // Metadebug methods
  1268 void Metadebug::deallocate_chunk_a_lot(SpaceManager* sm,
  1269                                        size_t chunk_word_size){
  1270 #ifdef ASSERT
  1271   VirtualSpaceList* vsl = sm->vs_list();
  1272   if (MetaDataDeallocateALot &&
  1273       Metadebug::deallocate_chunk_a_lot_count() % MetaDataDeallocateALotInterval == 0 ) {
  1274     Metadebug::reset_deallocate_chunk_a_lot_count();
  1275     for (uint i = 0; i < metadata_deallocate_a_lock_chunk; i++) {
  1276       Metachunk* dummy_chunk = vsl->current_virtual_space()->take_from_committed(chunk_word_size);
  1277       if (dummy_chunk == NULL) {
  1278         break;
  1280       vsl->chunk_manager()->chunk_freelist_deallocate(dummy_chunk);
  1282       if (TraceMetadataChunkAllocation && Verbose) {
  1283         gclog_or_tty->print("Metadebug::deallocate_chunk_a_lot: %d) ",
  1284                                sm->sum_count_in_chunks_in_use());
  1285         dummy_chunk->print_on(gclog_or_tty);
  1286         gclog_or_tty->print_cr("  Free chunks total %d  count %d",
  1287                                vsl->chunk_manager()->free_chunks_total(),
  1288                                vsl->chunk_manager()->free_chunks_count());
  1291   } else {
  1292     Metadebug::inc_deallocate_chunk_a_lot_count();
  1294 #endif
  1297 void Metadebug::deallocate_block_a_lot(SpaceManager* sm,
  1298                                        size_t raw_word_size){
  1299 #ifdef ASSERT
  1300   if (MetaDataDeallocateALot &&
  1301         Metadebug::deallocate_block_a_lot_count() % MetaDataDeallocateALotInterval == 0 ) {
  1302     Metadebug::set_deallocate_block_a_lot_count(0);
  1303     for (uint i = 0; i < metadata_deallocate_a_lot_block; i++) {
  1304       MetaWord* dummy_block = sm->allocate_work(raw_word_size);
  1305       if (dummy_block == 0) {
  1306         break;
  1308       sm->deallocate(dummy_block, raw_word_size);
  1310   } else {
  1311     Metadebug::inc_deallocate_block_a_lot_count();
  1313 #endif
  1316 void Metadebug::init_allocation_fail_alot_count() {
  1317   if (MetadataAllocationFailALot) {
  1318     _allocation_fail_alot_count =
  1319       1+(long)((double)MetadataAllocationFailALotInterval*os::random()/(max_jint+1.0));
  1323 #ifdef ASSERT
  1324 bool Metadebug::test_metadata_failure() {
  1325   if (MetadataAllocationFailALot &&
  1326       Threads::is_vm_complete()) {
  1327     if (_allocation_fail_alot_count > 0) {
  1328       _allocation_fail_alot_count--;
  1329     } else {
  1330       if (TraceMetadataChunkAllocation && Verbose) {
  1331         gclog_or_tty->print_cr("Metadata allocation failing for "
  1332                                "MetadataAllocationFailALot");
  1334       init_allocation_fail_alot_count();
  1335       return true;
  1338   return false;
  1340 #endif
  1342 // ChunkList methods
  1344 size_t ChunkList::sum_list_size() {
  1345   size_t result = 0;
  1346   Metachunk* cur = head();
  1347   while (cur != NULL) {
  1348     result += cur->word_size();
  1349     cur = cur->next();
  1351   return result;
  1354 size_t ChunkList::sum_list_count() {
  1355   size_t result = 0;
  1356   Metachunk* cur = head();
  1357   while (cur != NULL) {
  1358     result++;
  1359     cur = cur->next();
  1361   return result;
  1364 size_t ChunkList::sum_list_capacity() {
  1365   size_t result = 0;
  1366   Metachunk* cur = head();
  1367   while (cur != NULL) {
  1368     result += cur->capacity_word_size();
  1369     cur = cur->next();
  1371   return result;
  1374 void ChunkList::add_at_head(Metachunk* head, Metachunk* tail) {
  1375   assert_lock_strong(SpaceManager::expand_lock());
  1376   assert(tail->next() == NULL, "Not the tail");
  1378   if (TraceMetadataChunkAllocation && Verbose) {
  1379     tty->print("ChunkList::add_at_head: ");
  1380     Metachunk* cur = head;
  1381     while (cur != NULL) {
  1382     tty->print(PTR_FORMAT " (" SIZE_FORMAT ") ", cur, cur->word_size());
  1383       cur = cur->next();
  1385     tty->print_cr("");
  1388   if (tail != NULL) {
  1389     tail->set_next(_head);
  1391   set_head(head);
  1394 void ChunkList::add_at_head(Metachunk* list) {
  1395   if (list == NULL) {
  1396     // Nothing to add
  1397     return;
  1399   assert_lock_strong(SpaceManager::expand_lock());
  1400   Metachunk* head = list;
  1401   Metachunk* tail = list;
  1402   Metachunk* cur = head->next();
  1403   // Search for the tail since it is not passed.
  1404   while (cur != NULL) {
  1405     tail = cur;
  1406     cur = cur->next();
  1408   add_at_head(head, tail);
  1411 // ChunkManager methods
  1413 // Verification of _free_chunks_total and _free_chunks_count does not
  1414 // work with the CMS collector because its use of additional locks
  1415 // complicate the mutex deadlock detection but it can still be useful
  1416 // for detecting errors in the chunk accounting with other collectors.
  1418 size_t ChunkManager::free_chunks_total() {
  1419 #ifdef ASSERT
  1420   if (!UseConcMarkSweepGC && !SpaceManager::expand_lock()->is_locked()) {
  1421     MutexLockerEx cl(SpaceManager::expand_lock(),
  1422                      Mutex::_no_safepoint_check_flag);
  1423     slow_locked_verify_free_chunks_total();
  1425 #endif
  1426   return _free_chunks_total;
  1429 size_t ChunkManager::free_chunks_total_in_bytes() {
  1430   return free_chunks_total() * BytesPerWord;
  1433 size_t ChunkManager::free_chunks_count() {
  1434 #ifdef ASSERT
  1435   if (!UseConcMarkSweepGC && !SpaceManager::expand_lock()->is_locked()) {
  1436     MutexLockerEx cl(SpaceManager::expand_lock(),
  1437                      Mutex::_no_safepoint_check_flag);
  1438     // This lock is only needed in debug because the verification
  1439     // of the _free_chunks_totals walks the list of free chunks
  1440     slow_locked_verify_free_chunks_count();
  1442 #endif
  1443   return _free_chunks_count;
  1446 void ChunkManager::locked_verify_free_chunks_total() {
  1447   assert_lock_strong(SpaceManager::expand_lock());
  1448   assert(sum_free_chunks() == _free_chunks_total,
  1449     err_msg("_free_chunks_total " SIZE_FORMAT " is not the"
  1450            " same as sum " SIZE_FORMAT, _free_chunks_total,
  1451            sum_free_chunks()));
  1454 void ChunkManager::verify_free_chunks_total() {
  1455   MutexLockerEx cl(SpaceManager::expand_lock(),
  1456                      Mutex::_no_safepoint_check_flag);
  1457   locked_verify_free_chunks_total();
  1460 void ChunkManager::locked_verify_free_chunks_count() {
  1461   assert_lock_strong(SpaceManager::expand_lock());
  1462   assert(sum_free_chunks_count() == _free_chunks_count,
  1463     err_msg("_free_chunks_count " SIZE_FORMAT " is not the"
  1464            " same as sum " SIZE_FORMAT, _free_chunks_count,
  1465            sum_free_chunks_count()));
  1468 void ChunkManager::verify_free_chunks_count() {
  1469 #ifdef ASSERT
  1470   MutexLockerEx cl(SpaceManager::expand_lock(),
  1471                      Mutex::_no_safepoint_check_flag);
  1472   locked_verify_free_chunks_count();
  1473 #endif
  1476 void ChunkManager::verify() {
  1477   MutexLockerEx cl(SpaceManager::expand_lock(),
  1478                      Mutex::_no_safepoint_check_flag);
  1479   locked_verify();
  1482 void ChunkManager::locked_verify() {
  1483   locked_verify_free_chunks_count();
  1484   locked_verify_free_chunks_total();
  1487 void ChunkManager::locked_print_free_chunks(outputStream* st) {
  1488   assert_lock_strong(SpaceManager::expand_lock());
  1489   st->print_cr("Free chunk total 0x%x  count 0x%x",
  1490                 _free_chunks_total, _free_chunks_count);
  1493 void ChunkManager::locked_print_sum_free_chunks(outputStream* st) {
  1494   assert_lock_strong(SpaceManager::expand_lock());
  1495   st->print_cr("Sum free chunk total 0x%x  count 0x%x",
  1496                 sum_free_chunks(), sum_free_chunks_count());
  1498 ChunkList* ChunkManager::free_chunks(ChunkIndex index) {
  1499   return &_free_chunks[index];
  1502 // These methods that sum the free chunk lists are used in printing
  1503 // methods that are used in product builds.
  1504 size_t ChunkManager::sum_free_chunks() {
  1505   assert_lock_strong(SpaceManager::expand_lock());
  1506   size_t result = 0;
  1507   for (ChunkIndex i = SmallIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
  1508     ChunkList* list = free_chunks(i);
  1510     if (list == NULL) {
  1511       continue;
  1514     result = result + list->sum_list_capacity();
  1516   result = result + humongous_dictionary()->total_size();
  1517   return result;
  1520 size_t ChunkManager::sum_free_chunks_count() {
  1521   assert_lock_strong(SpaceManager::expand_lock());
  1522   size_t count = 0;
  1523   for (ChunkIndex i = SmallIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
  1524     ChunkList* list = free_chunks(i);
  1525     if (list == NULL) {
  1526       continue;
  1528     count = count + list->sum_list_count();
  1530   count = count + humongous_dictionary()->total_free_blocks();
  1531   return count;
  1534 ChunkList* ChunkManager::find_free_chunks_list(size_t word_size) {
  1535   switch (word_size) {
  1536   case SpaceManager::SmallChunk :
  1537       return &_free_chunks[0];
  1538   case SpaceManager::MediumChunk :
  1539       return &_free_chunks[1];
  1540   default:
  1541     assert(word_size > SpaceManager::MediumChunk, "List inconsistency");
  1542     return &_free_chunks[2];
  1546 void ChunkManager::free_chunks_put(Metachunk* chunk) {
  1547   assert_lock_strong(SpaceManager::expand_lock());
  1548   ChunkList* free_list = find_free_chunks_list(chunk->word_size());
  1549   chunk->set_next(free_list->head());
  1550   free_list->set_head(chunk);
  1551   // chunk is being returned to the chunk free list
  1552   inc_free_chunks_total(chunk->capacity_word_size());
  1553   slow_locked_verify();
  1556 void ChunkManager::chunk_freelist_deallocate(Metachunk* chunk) {
  1557   // The deallocation of a chunk originates in the freelist
  1558   // manangement code for a Metaspace and does not hold the
  1559   // lock.
  1560   assert(chunk != NULL, "Deallocating NULL");
  1561   assert_lock_strong(SpaceManager::expand_lock());
  1562   slow_locked_verify();
  1563   if (TraceMetadataChunkAllocation) {
  1564     tty->print_cr("ChunkManager::chunk_freelist_deallocate: chunk "
  1565                   PTR_FORMAT "  size " SIZE_FORMAT,
  1566                   chunk, chunk->word_size());
  1568   free_chunks_put(chunk);
  1571 Metachunk* ChunkManager::free_chunks_get(size_t word_size) {
  1572   assert_lock_strong(SpaceManager::expand_lock());
  1574   slow_locked_verify();
  1576   Metachunk* chunk = NULL;
  1577   if (!SpaceManager::is_humongous(word_size)) {
  1578     ChunkList* free_list = find_free_chunks_list(word_size);
  1579     assert(free_list != NULL, "Sanity check");
  1581     chunk = free_list->head();
  1582     debug_only(Metachunk* debug_head = chunk;)
  1584     if (chunk == NULL) {
  1585       return NULL;
  1588     // Remove the chunk as the head of the list.
  1589     free_list->set_head(chunk->next());
  1590     chunk->set_next(NULL);
  1591     // Chunk has been removed from the chunks free list.
  1592     dec_free_chunks_total(chunk->capacity_word_size());
  1594     if (TraceMetadataChunkAllocation && Verbose) {
  1595       tty->print_cr("ChunkManager::free_chunks_get: free_list "
  1596                     PTR_FORMAT " head " PTR_FORMAT " size " SIZE_FORMAT,
  1597                     free_list, chunk, chunk->word_size());
  1599   } else {
  1600     chunk = humongous_dictionary()->get_chunk(
  1601       word_size,
  1602       FreeBlockDictionary<Metachunk>::atLeast);
  1604     if (chunk != NULL) {
  1605       if (TraceMetadataHumongousAllocation) {
  1606         size_t waste = chunk->word_size() - word_size;
  1607         tty->print_cr("Free list allocate humongous chunk size " SIZE_FORMAT
  1608                       " for requested size " SIZE_FORMAT
  1609                       " waste " SIZE_FORMAT,
  1610                       chunk->word_size(), word_size, waste);
  1612       // Chunk is being removed from the chunks free list.
  1613       dec_free_chunks_total(chunk->capacity_word_size());
  1614 #ifdef ASSERT
  1615       chunk->set_is_free(false);
  1616 #endif
  1619   slow_locked_verify();
  1620   return chunk;
  1623 Metachunk* ChunkManager::chunk_freelist_allocate(size_t word_size) {
  1624   assert_lock_strong(SpaceManager::expand_lock());
  1625   slow_locked_verify();
  1627   // Take from the beginning of the list
  1628   Metachunk* chunk = free_chunks_get(word_size);
  1629   if (chunk == NULL) {
  1630     return NULL;
  1633   assert(word_size <= chunk->word_size() ||
  1634            SpaceManager::is_humongous(chunk->word_size()),
  1635            "Non-humongous variable sized chunk");
  1636   if (TraceMetadataChunkAllocation) {
  1637     tty->print("ChunkManager::chunk_freelist_allocate: chunk "
  1638                PTR_FORMAT "  size " SIZE_FORMAT " ",
  1639                chunk, chunk->word_size());
  1640     locked_print_free_chunks(tty);
  1643   return chunk;
  1646 void ChunkManager::print_on(outputStream* out) {
  1647   if (PrintFLSStatistics != 0) {
  1648     humongous_dictionary()->report_statistics();
  1652 // SpaceManager methods
  1654 size_t SpaceManager::sum_free_in_chunks_in_use() const {
  1655   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1656   size_t free = 0;
  1657   for (ChunkIndex i = SmallIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1658     Metachunk* chunk = chunks_in_use(i);
  1659     while (chunk != NULL) {
  1660       free += chunk->free_word_size();
  1661       chunk = chunk->next();
  1664   return free;
  1667 size_t SpaceManager::sum_waste_in_chunks_in_use() const {
  1668   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1669   size_t result = 0;
  1670   for (ChunkIndex i = SmallIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1673    result += sum_waste_in_chunks_in_use(i);
  1676   return result;
  1679 size_t SpaceManager::sum_waste_in_chunks_in_use(ChunkIndex index) const {
  1680   size_t result = 0;
  1681   size_t count = 0;
  1682   Metachunk* chunk = chunks_in_use(index);
  1683   // Count the free space in all the chunk but not the
  1684   // current chunk from which allocations are still being done.
  1685   if (chunk != NULL) {
  1686     Metachunk* prev = chunk;
  1687     while (chunk != NULL && chunk != current_chunk()) {
  1688       result += chunk->free_word_size();
  1689       prev = chunk;
  1690       chunk = chunk->next();
  1691       count++;
  1694   return result;
  1697 size_t SpaceManager::sum_capacity_in_chunks_in_use() const {
  1698   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1699   size_t sum = 0;
  1700   for (ChunkIndex i = SmallIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1701     Metachunk* chunk = chunks_in_use(i);
  1702     while (chunk != NULL) {
  1703       // Just changed this sum += chunk->capacity_word_size();
  1704       // sum += chunk->word_size() - Metachunk::overhead();
  1705       sum += chunk->capacity_word_size();
  1706       chunk = chunk->next();
  1709   return sum;
  1712 size_t SpaceManager::sum_count_in_chunks_in_use() {
  1713   size_t count = 0;
  1714   for (ChunkIndex i = SmallIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1715     count = count + sum_count_in_chunks_in_use(i);
  1718   return count;
  1721 size_t SpaceManager::sum_count_in_chunks_in_use(ChunkIndex i) {
  1722   size_t count = 0;
  1723   Metachunk* chunk = chunks_in_use(i);
  1724   while (chunk != NULL) {
  1725     count++;
  1726     chunk = chunk->next();
  1728   return count;
  1732 size_t SpaceManager::sum_used_in_chunks_in_use() const {
  1733   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  1734   size_t used = 0;
  1735   for (ChunkIndex i = SmallIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1736     Metachunk* chunk = chunks_in_use(i);
  1737     while (chunk != NULL) {
  1738       used += chunk->used_word_size();
  1739       chunk = chunk->next();
  1742   return used;
  1745 void SpaceManager::locked_print_chunks_in_use_on(outputStream* st) const {
  1747   Metachunk* small_chunk = chunks_in_use(SmallIndex);
  1748   st->print_cr("SpaceManager: small chunk " PTR_FORMAT
  1749                " free " SIZE_FORMAT,
  1750                small_chunk,
  1751                small_chunk->free_word_size());
  1753   Metachunk* medium_chunk = chunks_in_use(MediumIndex);
  1754   st->print("medium chunk " PTR_FORMAT, medium_chunk);
  1755   Metachunk* tail = current_chunk();
  1756   st->print_cr(" current chunk " PTR_FORMAT, tail);
  1758   Metachunk* head = chunks_in_use(HumongousIndex);
  1759   st->print_cr("humongous chunk " PTR_FORMAT, head);
  1761   vs_list()->chunk_manager()->locked_print_free_chunks(st);
  1762   vs_list()->chunk_manager()->locked_print_sum_free_chunks(st);
  1765 size_t SpaceManager::calc_chunk_size(size_t word_size) {
  1767   // Decide between a small chunk and a medium chunk.  Up to
  1768   // _small_chunk_limit small chunks can be allocated but
  1769   // once a medium chunk has been allocated, no more small
  1770   // chunks will be allocated.
  1771   size_t chunk_word_size;
  1772   if (chunks_in_use(MediumIndex) == NULL &&
  1773       (!has_small_chunk_limit() ||
  1774        sum_count_in_chunks_in_use(SmallIndex) < _small_chunk_limit)) {
  1775     chunk_word_size = (size_t) SpaceManager::SmallChunk;
  1776     if (word_size + Metachunk::overhead() > SpaceManager::SmallChunk) {
  1777       chunk_word_size = MediumChunk;
  1779   } else {
  1780     chunk_word_size = MediumChunk;
  1783   // Might still need a humongous chunk
  1784   chunk_word_size =
  1785     MAX2((size_t) chunk_word_size, word_size + Metachunk::overhead());
  1787   if (TraceMetadataHumongousAllocation &&
  1788       SpaceManager::is_humongous(word_size)) {
  1789     gclog_or_tty->print_cr("Metadata humongous allocation:");
  1790     gclog_or_tty->print_cr("  word_size " PTR_FORMAT, word_size);
  1791     gclog_or_tty->print_cr("  chunk_word_size " PTR_FORMAT,
  1792                            chunk_word_size);
  1793     gclog_or_tty->print_cr("    chunk overhead " PTR_FORMAT,
  1794                            Metachunk::overhead());
  1796   return chunk_word_size;
  1799 MetaWord* SpaceManager::grow_and_allocate(size_t word_size) {
  1800   assert(vs_list()->current_virtual_space() != NULL,
  1801          "Should have been set");
  1802   assert(current_chunk() == NULL ||
  1803          current_chunk()->allocate(word_size) == NULL,
  1804          "Don't need to expand");
  1805   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  1807   if (TraceMetadataChunkAllocation && Verbose) {
  1808     gclog_or_tty->print_cr("SpaceManager::grow_and_allocate for " SIZE_FORMAT
  1809                            " words " SIZE_FORMAT " space left",
  1810                             word_size, current_chunk() != NULL ?
  1811                               current_chunk()->free_word_size() : 0);
  1814   // Get another chunk out of the virtual space
  1815   size_t grow_chunks_by_words = calc_chunk_size(word_size);
  1816   Metachunk* next = vs_list()->get_new_chunk(word_size, grow_chunks_by_words);
  1818   // If a chunk was available, add it to the in-use chunk list
  1819   // and do an allocation from it.
  1820   if (next != NULL) {
  1821     Metadebug::deallocate_chunk_a_lot(this, grow_chunks_by_words);
  1822     // Add to this manager's list of chunks in use.
  1823     add_chunk(next, false);
  1824     return next->allocate(word_size);
  1826   return NULL;
  1829 void SpaceManager::print_on(outputStream* st) const {
  1831   for (ChunkIndex i = SmallIndex;
  1832        i < NumberOfInUseLists ;
  1833        i = next_chunk_index(i) ) {
  1834     st->print_cr("  chunks_in_use " PTR_FORMAT " chunk size " PTR_FORMAT,
  1835                  chunks_in_use(i),
  1836                  chunks_in_use(i) == NULL ? 0 : chunks_in_use(i)->word_size());
  1838   st->print_cr("    waste:  Small " SIZE_FORMAT " Medium " SIZE_FORMAT
  1839                " Humongous " SIZE_FORMAT,
  1840                sum_waste_in_chunks_in_use(SmallIndex),
  1841                sum_waste_in_chunks_in_use(MediumIndex),
  1842                sum_waste_in_chunks_in_use(HumongousIndex));
  1843   // block free lists
  1844   if (block_freelists() != NULL) {
  1845     st->print_cr("total in block free lists " SIZE_FORMAT,
  1846       block_freelists()->total_size());
  1850 SpaceManager::SpaceManager(Mutex* lock, VirtualSpaceList* vs_list) :
  1851   _vs_list(vs_list),
  1852   _allocation_total(0),
  1853   _lock(lock) {
  1854   Metadebug::init_allocation_fail_alot_count();
  1855   for (ChunkIndex i = SmallIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  1856     _chunks_in_use[i] = NULL;
  1858   _current_chunk = NULL;
  1859   if (TraceMetadataChunkAllocation && Verbose) {
  1860     gclog_or_tty->print_cr("SpaceManager(): " PTR_FORMAT, this);
  1864 SpaceManager::~SpaceManager() {
  1865   MutexLockerEx fcl(SpaceManager::expand_lock(),
  1866                     Mutex::_no_safepoint_check_flag);
  1868   ChunkManager* chunk_manager = vs_list()->chunk_manager();
  1870   chunk_manager->slow_locked_verify();
  1872   if (TraceMetadataChunkAllocation && Verbose) {
  1873     gclog_or_tty->print_cr("~SpaceManager(): " PTR_FORMAT, this);
  1874     locked_print_chunks_in_use_on(gclog_or_tty);
  1877   // Mangle freed memory.
  1878   NOT_PRODUCT(mangle_freed_chunks();)
  1880   // Have to update before the chunks_in_use lists are emptied
  1881   // below.
  1882   chunk_manager->inc_free_chunks_total(sum_capacity_in_chunks_in_use(),
  1883                                        sum_count_in_chunks_in_use());
  1885   // Add all the chunks in use by this space manager
  1886   // to the global list of free chunks.
  1888   // Small chunks.  There is one _current_chunk for each
  1889   // Metaspace.  It could point to a small or medium chunk.
  1890   // Rather than determine which it is, follow the list of
  1891   // small chunks to add them to the free list
  1892   Metachunk* small_chunk = chunks_in_use(SmallIndex);
  1893   chunk_manager->free_small_chunks()->add_at_head(small_chunk);
  1894   set_chunks_in_use(SmallIndex, NULL);
  1896   // After the small chunk are the medium chunks
  1897   Metachunk* medium_chunk = chunks_in_use(MediumIndex);
  1898   assert(medium_chunk == NULL ||
  1899          medium_chunk->word_size() == MediumChunk,
  1900          "Chunk is on the wrong list");
  1902   if (medium_chunk != NULL) {
  1903     Metachunk* head = medium_chunk;
  1904     // If there is a medium chunk then the _current_chunk can only
  1905     // point to the last medium chunk.
  1906     Metachunk* tail = current_chunk();
  1907     chunk_manager->free_medium_chunks()->add_at_head(head, tail);
  1908     set_chunks_in_use(MediumIndex, NULL);
  1911   // Humongous chunks
  1912   // Humongous chunks are never the current chunk.
  1913   Metachunk* humongous_chunks = chunks_in_use(HumongousIndex);
  1915   while (humongous_chunks != NULL) {
  1916 #ifdef ASSERT
  1917     humongous_chunks->set_is_free(true);
  1918 #endif
  1919     Metachunk* next_humongous_chunks = humongous_chunks->next();
  1920     chunk_manager->humongous_dictionary()->return_chunk(humongous_chunks);
  1921     humongous_chunks = next_humongous_chunks;
  1923   set_chunks_in_use(HumongousIndex, NULL);
  1924   chunk_manager->slow_locked_verify();
  1927 void SpaceManager::deallocate(MetaWord* p, size_t word_size) {
  1928   assert_lock_strong(_lock);
  1929   size_t min_size = TreeChunk<Metablock, FreeList>::min_size();
  1930   assert(word_size >= min_size,
  1931     err_msg("Should not deallocate dark matter " SIZE_FORMAT, word_size));
  1932   block_freelists()->return_block(p, word_size);
  1935 // Adds a chunk to the list of chunks in use.
  1936 void SpaceManager::add_chunk(Metachunk* new_chunk, bool make_current) {
  1938   assert(new_chunk != NULL, "Should not be NULL");
  1939   assert(new_chunk->next() == NULL, "Should not be on a list");
  1941   new_chunk->reset_empty();
  1943   // Find the correct list and and set the current
  1944   // chunk for that list.
  1945   switch (new_chunk->word_size()) {
  1946   case SpaceManager::SmallChunk :
  1947     if (chunks_in_use(SmallIndex) == NULL) {
  1948       // First chunk to add to the list
  1949       set_chunks_in_use(SmallIndex, new_chunk);
  1950     } else {
  1951       assert(current_chunk()->word_size() == SpaceManager::SmallChunk,
  1952         err_msg( "Incorrect mix of sizes in chunk list "
  1953         SIZE_FORMAT " new chunk " SIZE_FORMAT,
  1954         current_chunk()->word_size(), new_chunk->word_size()));
  1955       current_chunk()->set_next(new_chunk);
  1957     // Make current chunk
  1958     set_current_chunk(new_chunk);
  1959     break;
  1960   case SpaceManager::MediumChunk :
  1961     if (chunks_in_use(MediumIndex) == NULL) {
  1962       // About to add the first medium chunk so teminate the
  1963       // small chunk list.  In general once medium chunks are
  1964       // being added, we're past the need for small chunks.
  1965       if (current_chunk() != NULL) {
  1966         // Only a small chunk or the initial chunk could be
  1967         // the current chunk if this is the first medium chunk.
  1968         assert(current_chunk()->word_size() == SpaceManager::SmallChunk ||
  1969           chunks_in_use(SmallIndex) == NULL,
  1970           err_msg("Should be a small chunk or initial chunk, current chunk "
  1971           SIZE_FORMAT " new chunk " SIZE_FORMAT,
  1972           current_chunk()->word_size(), new_chunk->word_size()));
  1973         current_chunk()->set_next(NULL);
  1975       // First chunk to add to the list
  1976       set_chunks_in_use(MediumIndex, new_chunk);
  1978     } else {
  1979       // As a minimum the first medium chunk added would
  1980       // have become the _current_chunk
  1981       // so the _current_chunk has to be non-NULL here
  1982       // (although not necessarily still the first medium chunk).
  1983       assert(current_chunk()->word_size() == SpaceManager::MediumChunk,
  1984              "A medium chunk should the current chunk");
  1985       current_chunk()->set_next(new_chunk);
  1987     // Make current chunk
  1988     set_current_chunk(new_chunk);
  1989     break;
  1990   default: {
  1991     // For null class loader data and DumpSharedSpaces, the first chunk isn't
  1992     // small, so small will be null.  Link this first chunk as the current
  1993     // chunk.
  1994     if (make_current) {
  1995       // Set as the current chunk but otherwise treat as a humongous chunk.
  1996       set_current_chunk(new_chunk);
  1998     // Link at head.  The _current_chunk only points to a humongous chunk for
  1999     // the null class loader metaspace (class and data virtual space managers)
  2000     // any humongous chunks so will not point to the tail
  2001     // of the humongous chunks list.
  2002     new_chunk->set_next(chunks_in_use(HumongousIndex));
  2003     set_chunks_in_use(HumongousIndex, new_chunk);
  2005     assert(new_chunk->word_size() > MediumChunk, "List inconsistency");
  2009   assert(new_chunk->is_empty(), "Not ready for reuse");
  2010   if (TraceMetadataChunkAllocation && Verbose) {
  2011     gclog_or_tty->print("SpaceManager::add_chunk: %d) ",
  2012                         sum_count_in_chunks_in_use());
  2013     new_chunk->print_on(gclog_or_tty);
  2014     vs_list()->chunk_manager()->locked_print_free_chunks(tty);
  2018 MetaWord* SpaceManager::allocate(size_t word_size) {
  2019   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  2021   // If only the dictionary is going to be used (i.e., no
  2022   // indexed free list), then there is a minimum size requirement.
  2023   // MinChunkSize is a placeholder for the real minimum size JJJ
  2024   size_t byte_size = word_size * BytesPerWord;
  2026   size_t byte_size_with_overhead = byte_size + Metablock::overhead();
  2028   size_t raw_bytes_size = MAX2(byte_size_with_overhead,
  2029                                Metablock::min_block_byte_size());
  2030   raw_bytes_size = ARENA_ALIGN(raw_bytes_size);
  2031   size_t raw_word_size = raw_bytes_size / BytesPerWord;
  2032   assert(raw_word_size * BytesPerWord == raw_bytes_size, "Size problem");
  2034   BlockFreelist* fl =  block_freelists();
  2035   MetaWord* p = NULL;
  2036   // Allocation from the dictionary is expensive in the sense that
  2037   // the dictionary has to be searched for a size.  Don't allocate
  2038   // from the dictionary until it starts to get fat.  Is this
  2039   // a reasonable policy?  Maybe an skinny dictionary is fast enough
  2040   // for allocations.  Do some profiling.  JJJ
  2041   if (fl->total_size() > allocation_from_dictionary_limit) {
  2042     p = fl->get_block(raw_word_size);
  2044   if (p == NULL) {
  2045     p = allocate_work(raw_word_size);
  2047   Metadebug::deallocate_block_a_lot(this, raw_word_size);
  2049   return p;
  2052 // Returns the address of spaced allocated for "word_size".
  2053 // This methods does not know about blocks (Metablocks)
  2054 MetaWord* SpaceManager::allocate_work(size_t word_size) {
  2055   assert_lock_strong(_lock);
  2056 #ifdef ASSERT
  2057   if (Metadebug::test_metadata_failure()) {
  2058     return NULL;
  2060 #endif
  2061   // Is there space in the current chunk?
  2062   MetaWord* result = NULL;
  2064   // For DumpSharedSpaces, only allocate out of the current chunk which is
  2065   // never null because we gave it the size we wanted.   Caller reports out
  2066   // of memory if this returns null.
  2067   if (DumpSharedSpaces) {
  2068     assert(current_chunk() != NULL, "should never happen");
  2069     inc_allocation_total(word_size);
  2070     return current_chunk()->allocate(word_size); // caller handles null result
  2072   if (current_chunk() != NULL) {
  2073     result = current_chunk()->allocate(word_size);
  2076   if (result == NULL) {
  2077     result = grow_and_allocate(word_size);
  2079   if (result > 0) {
  2080     inc_allocation_total(word_size);
  2081     assert(result != (MetaWord*) chunks_in_use(MediumIndex),
  2082            "Head of the list is being allocated");
  2085   return result;
  2088 void SpaceManager::verify() {
  2089   // If there are blocks in the dictionary, then
  2090   // verfication of chunks does not work since
  2091   // being in the dictionary alters a chunk.
  2092   if (block_freelists()->total_size() == 0) {
  2093     // Skip the small chunks because their next link points to
  2094     // medium chunks.  This is because the small chunk is the
  2095     // current chunk (for allocations) until it is full and the
  2096     // the addition of the next chunk does not NULL the next
  2097     // like of the small chunk.
  2098     for (ChunkIndex i = MediumIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
  2099       Metachunk* curr = chunks_in_use(i);
  2100       while (curr != NULL) {
  2101         curr->verify();
  2102         verify_chunk_size(curr);
  2103         curr = curr->next();
  2109 void SpaceManager::verify_chunk_size(Metachunk* chunk) {
  2110   assert(is_humongous(chunk->word_size()) ||
  2111          chunk->word_size() == MediumChunk ||
  2112          chunk->word_size() == SmallChunk,
  2113          "Chunk size is wrong");
  2114   return;
  2117 #ifdef ASSERT
  2118 void SpaceManager::verify_allocation_total() {
  2119 #if 0
  2120   // Verification is only guaranteed at a safepoint.
  2121   if (SafepointSynchronize::is_at_safepoint()) {
  2122     gclog_or_tty->print_cr("Chunk " PTR_FORMAT " allocation_total " SIZE_FORMAT
  2123                            " sum_used_in_chunks_in_use " SIZE_FORMAT,
  2124                            this,
  2125                            allocation_total(),
  2126                            sum_used_in_chunks_in_use());
  2128   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
  2129   assert(allocation_total() == sum_used_in_chunks_in_use(),
  2130     err_msg("allocation total is not consistent %d vs %d",
  2131             allocation_total(), sum_used_in_chunks_in_use()));
  2132 #endif
  2135 #endif
  2137 void SpaceManager::dump(outputStream* const out) const {
  2138   size_t curr_total = 0;
  2139   size_t waste = 0;
  2140   uint i = 0;
  2141   size_t used = 0;
  2142   size_t capacity = 0;
  2144   // Add up statistics for all chunks in this SpaceManager.
  2145   for (ChunkIndex index = SmallIndex;
  2146        index < NumberOfInUseLists;
  2147        index = next_chunk_index(index)) {
  2148     for (Metachunk* curr = chunks_in_use(index);
  2149          curr != NULL;
  2150          curr = curr->next()) {
  2151       out->print("%d) ", i++);
  2152       curr->print_on(out);
  2153       if (TraceMetadataChunkAllocation && Verbose) {
  2154         block_freelists()->print_on(out);
  2156       curr_total += curr->word_size();
  2157       used += curr->used_word_size();
  2158       capacity += curr->capacity_word_size();
  2159       waste += curr->free_word_size() + curr->overhead();;
  2163   size_t free = current_chunk()->free_word_size();
  2164   // Free space isn't wasted.
  2165   waste -= free;
  2167   out->print_cr("total of all chunks "  SIZE_FORMAT " used " SIZE_FORMAT
  2168                 " free " SIZE_FORMAT " capacity " SIZE_FORMAT
  2169                 " waste " SIZE_FORMAT, curr_total, used, free, capacity, waste);
  2172 #ifndef PRODUCT
  2173 void SpaceManager::mangle_freed_chunks() {
  2174   for (ChunkIndex index = SmallIndex;
  2175        index < NumberOfInUseLists;
  2176        index = next_chunk_index(index)) {
  2177     for (Metachunk* curr = chunks_in_use(index);
  2178          curr != NULL;
  2179          curr = curr->next()) {
  2180       // Try to detect incorrectly terminated small chunk
  2181       // list.
  2182       assert(index == MediumIndex || curr != chunks_in_use(MediumIndex),
  2183              err_msg("Mangling medium chunks in small chunks? "
  2184                      "curr " PTR_FORMAT " medium list " PTR_FORMAT,
  2185                      curr, chunks_in_use(MediumIndex)));
  2186       curr->mangle();
  2190 #endif // PRODUCT
  2193 // MetaspaceAux
  2195 size_t MetaspaceAux::used_in_bytes(Metaspace::MetadataType mdtype) {
  2196   size_t used = 0;
  2197   ClassLoaderDataGraphMetaspaceIterator iter;
  2198   while (iter.repeat()) {
  2199     Metaspace* msp = iter.get_next();
  2200     // Sum allocation_total for each metaspace
  2201     if (msp != NULL) {
  2202       used += msp->used_words(mdtype);
  2205   return used * BytesPerWord;
  2208 size_t MetaspaceAux::free_in_bytes(Metaspace::MetadataType mdtype) {
  2209   size_t free = 0;
  2210   ClassLoaderDataGraphMetaspaceIterator iter;
  2211   while (iter.repeat()) {
  2212     Metaspace* msp = iter.get_next();
  2213     if (msp != NULL) {
  2214       free += msp->free_words(mdtype);
  2217   return free * BytesPerWord;
  2220 size_t MetaspaceAux::capacity_in_bytes(Metaspace::MetadataType mdtype) {
  2221   size_t capacity = free_chunks_total(mdtype);
  2222   ClassLoaderDataGraphMetaspaceIterator iter;
  2223   while (iter.repeat()) {
  2224     Metaspace* msp = iter.get_next();
  2225     if (msp != NULL) {
  2226       capacity += msp->capacity_words(mdtype);
  2229   return capacity * BytesPerWord;
  2232 size_t MetaspaceAux::reserved_in_bytes(Metaspace::MetadataType mdtype) {
  2233   size_t reserved = (mdtype == Metaspace::ClassType) ?
  2234                        Metaspace::class_space_list()->virtual_space_total() :
  2235                        Metaspace::space_list()->virtual_space_total();
  2236   return reserved * BytesPerWord;
  2239 size_t MetaspaceAux::min_chunk_size() { return SpaceManager::MediumChunk; }
  2241 size_t MetaspaceAux::free_chunks_total(Metaspace::MetadataType mdtype) {
  2242   ChunkManager* chunk = (mdtype == Metaspace::ClassType) ?
  2243                             Metaspace::class_space_list()->chunk_manager() :
  2244                             Metaspace::space_list()->chunk_manager();
  2245   chunk->slow_verify();
  2246   return chunk->free_chunks_total();
  2249 size_t MetaspaceAux::free_chunks_total_in_bytes(Metaspace::MetadataType mdtype) {
  2250   return free_chunks_total(mdtype) * BytesPerWord;
  2253 void MetaspaceAux::print_metaspace_change(size_t prev_metadata_used) {
  2254   gclog_or_tty->print(", [Metaspace:");
  2255   if (PrintGCDetails && Verbose) {
  2256     gclog_or_tty->print(" "  SIZE_FORMAT
  2257                         "->" SIZE_FORMAT
  2258                         "("  SIZE_FORMAT "/" SIZE_FORMAT ")",
  2259                         prev_metadata_used,
  2260                         used_in_bytes(),
  2261                         capacity_in_bytes(),
  2262                         reserved_in_bytes());
  2263   } else {
  2264     gclog_or_tty->print(" "  SIZE_FORMAT "K"
  2265                         "->" SIZE_FORMAT "K"
  2266                         "("  SIZE_FORMAT "K/" SIZE_FORMAT "K)",
  2267                         prev_metadata_used / K,
  2268                         used_in_bytes()/ K,
  2269                         capacity_in_bytes()/K,
  2270                         reserved_in_bytes()/ K);
  2273   gclog_or_tty->print("]");
  2276 // This is printed when PrintGCDetails
  2277 void MetaspaceAux::print_on(outputStream* out) {
  2278   Metaspace::MetadataType ct = Metaspace::ClassType;
  2279   Metaspace::MetadataType nct = Metaspace::NonClassType;
  2281   out->print_cr(" Metaspace total "
  2282                 SIZE_FORMAT "K, used " SIZE_FORMAT "K,"
  2283                 " reserved " SIZE_FORMAT "K",
  2284                 capacity_in_bytes()/K, used_in_bytes()/K, reserved_in_bytes()/K);
  2285   out->print_cr("  data space     "
  2286                 SIZE_FORMAT "K, used " SIZE_FORMAT "K,"
  2287                 " reserved " SIZE_FORMAT "K",
  2288                 capacity_in_bytes(nct)/K, used_in_bytes(nct)/K, reserved_in_bytes(nct)/K);
  2289   out->print_cr("  class space    "
  2290                 SIZE_FORMAT "K, used " SIZE_FORMAT "K,"
  2291                 " reserved " SIZE_FORMAT "K",
  2292                 capacity_in_bytes(ct)/K, used_in_bytes(ct)/K, reserved_in_bytes(ct)/K);
  2295 // Print information for class space and data space separately.
  2296 // This is almost the same as above.
  2297 void MetaspaceAux::print_on(outputStream* out, Metaspace::MetadataType mdtype) {
  2298   size_t free_chunks_capacity_bytes = free_chunks_total_in_bytes(mdtype);
  2299   size_t capacity_bytes = capacity_in_bytes(mdtype);
  2300   size_t used_bytes = used_in_bytes(mdtype);
  2301   size_t free_bytes = free_in_bytes(mdtype);
  2302   size_t used_and_free = used_bytes + free_bytes +
  2303                            free_chunks_capacity_bytes;
  2304   out->print_cr("  Chunk accounting: used in chunks " SIZE_FORMAT
  2305              "K + unused in chunks " SIZE_FORMAT "K  + "
  2306              " capacity in free chunks " SIZE_FORMAT "K = " SIZE_FORMAT
  2307              "K  capacity in allocated chunks " SIZE_FORMAT "K",
  2308              used_bytes / K,
  2309              free_bytes / K,
  2310              free_chunks_capacity_bytes / K,
  2311              used_and_free / K,
  2312              capacity_bytes / K);
  2313   assert(used_and_free == capacity_bytes, "Accounting is wrong");
  2316 // Print total fragmentation for class and data metaspaces separately
  2317 void MetaspaceAux::print_waste(outputStream* out) {
  2319   size_t small_waste = 0, medium_waste = 0, large_waste = 0;
  2320   size_t cls_small_waste = 0, cls_medium_waste = 0, cls_large_waste = 0;
  2322   ClassLoaderDataGraphMetaspaceIterator iter;
  2323   while (iter.repeat()) {
  2324     Metaspace* msp = iter.get_next();
  2325     if (msp != NULL) {
  2326       small_waste += msp->vsm()->sum_waste_in_chunks_in_use(SmallIndex);
  2327       medium_waste += msp->vsm()->sum_waste_in_chunks_in_use(MediumIndex);
  2328       large_waste += msp->vsm()->sum_waste_in_chunks_in_use(HumongousIndex);
  2330       cls_small_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SmallIndex);
  2331       cls_medium_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(MediumIndex);
  2332       cls_large_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(HumongousIndex);
  2335   out->print_cr("Total fragmentation waste (words) doesn't count free space");
  2336   out->print("  data: small " SIZE_FORMAT " medium " SIZE_FORMAT,
  2337              small_waste, medium_waste);
  2338   out->print_cr(" class: small " SIZE_FORMAT, cls_small_waste);
  2341 // Dump global metaspace things from the end of ClassLoaderDataGraph
  2342 void MetaspaceAux::dump(outputStream* out) {
  2343   out->print_cr("All Metaspace:");
  2344   out->print("data space: "); print_on(out, Metaspace::NonClassType);
  2345   out->print("class space: "); print_on(out, Metaspace::ClassType);
  2346   print_waste(out);
  2349 void MetaspaceAux::verify_free_chunks() {
  2350   Metaspace::space_list()->chunk_manager()->verify();
  2351   Metaspace::class_space_list()->chunk_manager()->verify();
  2354 // Metaspace methods
  2356 size_t Metaspace::_first_chunk_word_size = 0;
  2358 Metaspace::Metaspace(Mutex* lock, size_t word_size) {
  2359   initialize(lock, word_size);
  2362 Metaspace::Metaspace(Mutex* lock) {
  2363   initialize(lock);
  2366 Metaspace::~Metaspace() {
  2367   delete _vsm;
  2368   delete _class_vsm;
  2371 VirtualSpaceList* Metaspace::_space_list = NULL;
  2372 VirtualSpaceList* Metaspace::_class_space_list = NULL;
  2374 #define VIRTUALSPACEMULTIPLIER 2
  2376 void Metaspace::global_initialize() {
  2377   // Initialize the alignment for shared spaces.
  2378   int max_alignment = os::vm_page_size();
  2379   MetaspaceShared::set_max_alignment(max_alignment);
  2381   if (DumpSharedSpaces) {
  2382     SharedReadOnlySize = align_size_up(SharedReadOnlySize, max_alignment);
  2383     SharedReadWriteSize = align_size_up(SharedReadWriteSize, max_alignment);
  2384     SharedMiscDataSize  = align_size_up(SharedMiscDataSize, max_alignment);
  2385     SharedMiscCodeSize  = align_size_up(SharedMiscCodeSize, max_alignment);
  2387     // Initialize with the sum of the shared space sizes.  The read-only
  2388     // and read write metaspace chunks will be allocated out of this and the
  2389     // remainder is the misc code and data chunks.
  2390     size_t total = align_size_up(SharedReadOnlySize + SharedReadWriteSize +
  2391                                  SharedMiscDataSize + SharedMiscCodeSize,
  2392                                  os::vm_allocation_granularity());
  2393     size_t word_size = total/wordSize;
  2394     _space_list = new VirtualSpaceList(word_size);
  2395   } else {
  2396     // If using shared space, open the file that contains the shared space
  2397     // and map in the memory before initializing the rest of metaspace (so
  2398     // the addresses don't conflict)
  2399     if (UseSharedSpaces) {
  2400       FileMapInfo* mapinfo = new FileMapInfo();
  2401       memset(mapinfo, 0, sizeof(FileMapInfo));
  2403       // Open the shared archive file, read and validate the header. If
  2404       // initialization fails, shared spaces [UseSharedSpaces] are
  2405       // disabled and the file is closed.
  2406       // Map in spaces now also
  2407       if (mapinfo->initialize() && MetaspaceShared::map_shared_spaces(mapinfo)) {
  2408         FileMapInfo::set_current_info(mapinfo);
  2409       } else {
  2410         assert(!mapinfo->is_open() && !UseSharedSpaces,
  2411                "archive file not closed or shared spaces not disabled.");
  2415     // Initialize this before initializing the VirtualSpaceList
  2416     _first_chunk_word_size = InitialBootClassLoaderMetaspaceSize / BytesPerWord;
  2417     // Arbitrarily set the initial virtual space to a multiple
  2418     // of the boot class loader size.
  2419     size_t word_size = VIRTUALSPACEMULTIPLIER * Metaspace::first_chunk_word_size();
  2420     // Initialize the list of virtual spaces.
  2421     _space_list = new VirtualSpaceList(word_size);
  2425 // For UseCompressedKlassPointers the class space is reserved as a piece of the
  2426 // Java heap because the compression algorithm is the same for each.  The
  2427 // argument passed in is at the top of the compressed space
  2428 void Metaspace::initialize_class_space(ReservedSpace rs) {
  2429   // The reserved space size may be bigger because of alignment, esp with UseLargePages
  2430   assert(rs.size() >= ClassMetaspaceSize, err_msg("%d != %d", rs.size(), ClassMetaspaceSize));
  2431   _class_space_list = new VirtualSpaceList(rs);
  2435 void Metaspace::initialize(Mutex* lock, size_t initial_size) {
  2436   // Use SmallChunk size if not specified.   If specified, use this size for
  2437   // the data metaspace.
  2438   size_t word_size;
  2439   size_t class_word_size;
  2440   if (initial_size == 0) {
  2441     word_size = (size_t) SpaceManager::SmallChunk;
  2442     class_word_size = (size_t) SpaceManager::SmallChunk;
  2443   } else {
  2444     word_size = initial_size;
  2445     // Make the first class chunk bigger than a medium chunk so it's not put
  2446     // on the medium chunk list.   The next chunk will be small and progress
  2447     // from there.  This size calculated by -version.
  2448     class_word_size = MIN2((size_t)SpaceManager::MediumChunk*5,
  2449                            (ClassMetaspaceSize/BytesPerWord)*2);
  2452   assert(space_list() != NULL,
  2453     "Metadata VirtualSpaceList has not been initialized");
  2455   _vsm = new SpaceManager(lock, space_list());
  2456   if (_vsm == NULL) {
  2457     return;
  2460   assert(class_space_list() != NULL,
  2461     "Class VirtualSpaceList has not been initialized");
  2463   // Allocate SpaceManager for classes.
  2464   _class_vsm = new SpaceManager(lock, class_space_list());
  2465   if (_class_vsm == NULL) {
  2466     return;
  2469   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
  2471   // Allocate chunk for metadata objects
  2472   Metachunk* new_chunk =
  2473      space_list()->current_virtual_space()->get_chunk_vs_with_expand(word_size);
  2474   assert(!DumpSharedSpaces || new_chunk != NULL, "should have enough space for both chunks");
  2475   if (new_chunk != NULL) {
  2476     // Add to this manager's list of chunks in use and current_chunk().
  2477     vsm()->add_chunk(new_chunk, true);
  2480   // Allocate chunk for class metadata objects
  2481   Metachunk* class_chunk =
  2482      class_space_list()->current_virtual_space()->get_chunk_vs_with_expand(class_word_size);
  2483   if (class_chunk != NULL) {
  2484     class_vsm()->add_chunk(class_chunk, true);
  2488 MetaWord* Metaspace::allocate(size_t word_size, MetadataType mdtype) {
  2489   // DumpSharedSpaces doesn't use class metadata area (yet)
  2490   if (mdtype == ClassType && !DumpSharedSpaces) {
  2491     return  class_vsm()->allocate(word_size);
  2492   } else {
  2493     return  vsm()->allocate(word_size);
  2497 MetaWord* Metaspace::expand_and_allocate(size_t word_size, MetadataType mdtype) {
  2498   MetaWord* result;
  2499   MetaspaceGC::set_expand_after_GC(true);
  2500   size_t before_inc = MetaspaceGC::capacity_until_GC();
  2501   size_t delta_words = MetaspaceGC::delta_capacity_until_GC(word_size);
  2502   MetaspaceGC::inc_capacity_until_GC(delta_words);
  2503   if (PrintGCDetails && Verbose) {
  2504     gclog_or_tty->print_cr("Increase capacity to GC from " SIZE_FORMAT
  2505       " to " SIZE_FORMAT, before_inc, MetaspaceGC::capacity_until_GC());
  2508   result = allocate(word_size, mdtype);
  2510   return result;
  2513 // Space allocated in the Metaspace.  This may
  2514 // be across several metadata virtual spaces.
  2515 char* Metaspace::bottom() const {
  2516   assert(DumpSharedSpaces, "only useful and valid for dumping shared spaces");
  2517   return (char*)vsm()->current_chunk()->bottom();
  2520 size_t Metaspace::used_words(MetadataType mdtype) const {
  2521   // return vsm()->allocation_total();
  2522   return mdtype == ClassType ? class_vsm()->sum_used_in_chunks_in_use() :
  2523                                vsm()->sum_used_in_chunks_in_use();  // includes overhead!
  2526 size_t Metaspace::free_words(MetadataType mdtype) const {
  2527   return mdtype == ClassType ? class_vsm()->sum_free_in_chunks_in_use() :
  2528                                vsm()->sum_free_in_chunks_in_use();
  2531 // Space capacity in the Metaspace.  It includes
  2532 // space in the list of chunks from which allocations
  2533 // have been made. Don't include space in the global freelist and
  2534 // in the space available in the dictionary which
  2535 // is already counted in some chunk.
  2536 size_t Metaspace::capacity_words(MetadataType mdtype) const {
  2537   return mdtype == ClassType ? class_vsm()->sum_capacity_in_chunks_in_use() :
  2538                                vsm()->sum_capacity_in_chunks_in_use();
  2541 void Metaspace::deallocate(MetaWord* ptr, size_t word_size, bool is_class) {
  2542   if (SafepointSynchronize::is_at_safepoint()) {
  2543     assert(Thread::current()->is_VM_thread(), "should be the VM thread");
  2544     // Don't take Heap_lock
  2545     MutexLocker ml(vsm()->lock());
  2546     if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
  2547       // Dark matter.  Too small for dictionary.
  2548 #ifdef ASSERT
  2549       Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
  2550 #endif
  2551       return;
  2553     if (is_class) {
  2554        class_vsm()->deallocate(ptr, word_size);
  2555     } else {
  2556       vsm()->deallocate(ptr, word_size);
  2558   } else {
  2559     MutexLocker ml(vsm()->lock());
  2561     if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
  2562       // Dark matter.  Too small for dictionary.
  2563 #ifdef ASSERT
  2564       Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
  2565 #endif
  2566       return;
  2568     if (is_class) {
  2569       class_vsm()->deallocate(ptr, word_size);
  2570     } else {
  2571       vsm()->deallocate(ptr, word_size);
  2576 Metablock* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size,
  2577                               bool read_only, MetadataType mdtype, TRAPS) {
  2578   if (HAS_PENDING_EXCEPTION) {
  2579     assert(false, "Should not allocate with exception pending");
  2580     return NULL;  // caller does a CHECK_NULL too
  2583   // SSS: Should we align the allocations and make sure the sizes are aligned.
  2584   MetaWord* result = NULL;
  2586   assert(loader_data != NULL, "Should never pass around a NULL loader_data. "
  2587         "ClassLoaderData::the_null_class_loader_data() should have been used.");
  2588   // Allocate in metaspaces without taking out a lock, because it deadlocks
  2589   // with the SymbolTable_lock.  Dumping is single threaded for now.  We'll have
  2590   // to revisit this for application class data sharing.
  2591   if (DumpSharedSpaces) {
  2592     if (read_only) {
  2593       result = loader_data->ro_metaspace()->allocate(word_size, NonClassType);
  2594     } else {
  2595       result = loader_data->rw_metaspace()->allocate(word_size, NonClassType);
  2597     if (result == NULL) {
  2598       report_out_of_shared_space(read_only ? SharedReadOnly : SharedReadWrite);
  2600     return Metablock::initialize(result, word_size);
  2603   result = loader_data->metaspace_non_null()->allocate(word_size, mdtype);
  2605   if (result == NULL) {
  2606     // Try to clean out some memory and retry.
  2607     result =
  2608       Universe::heap()->collector_policy()->satisfy_failed_metadata_allocation(
  2609         loader_data, word_size, mdtype);
  2611     // If result is still null, we are out of memory.
  2612     if (result == NULL) {
  2613       // -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support
  2614       report_java_out_of_memory("Metadata space");
  2616       if (JvmtiExport::should_post_resource_exhausted()) {
  2617         JvmtiExport::post_resource_exhausted(
  2618             JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR,
  2619             "Metadata space");
  2621       THROW_OOP_0(Universe::out_of_memory_error_perm_gen());
  2624   return Metablock::initialize(result, word_size);
  2627 void Metaspace::print_on(outputStream* out) const {
  2628   // Print both class virtual space counts and metaspace.
  2629   if (Verbose) {
  2630       vsm()->print_on(out);
  2631       class_vsm()->print_on(out);
  2635 bool Metaspace::contains(const void * ptr) {
  2636   if (MetaspaceShared::is_in_shared_space(ptr)) {
  2637     return true;
  2639   // This is checked while unlocked.  As long as the virtualspaces are added
  2640   // at the end, the pointer will be in one of them.  The virtual spaces
  2641   // aren't deleted presently.  When they are, some sort of locking might
  2642   // be needed.  Note, locking this can cause inversion problems with the
  2643   // caller in MetaspaceObj::is_metadata() function.
  2644   return space_list()->contains(ptr) || class_space_list()->contains(ptr);
  2647 void Metaspace::verify() {
  2648   vsm()->verify();
  2649   class_vsm()->verify();
  2652 void Metaspace::dump(outputStream* const out) const {
  2653   if (UseMallocOnly) {
  2654     // Just print usage for now
  2655     out->print_cr("usage %d", used_words(Metaspace::NonClassType));
  2657   out->print_cr("\nVirtual space manager: " INTPTR_FORMAT, vsm());
  2658   vsm()->dump(out);
  2659   out->print_cr("\nClass space manager: " INTPTR_FORMAT, class_vsm());
  2660   class_vsm()->dump(out);

mercurial