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