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