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