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