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