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