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