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