1 /*
   2  * Copyright (c) 2011, 2018, 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 "aot/aotLoader.hpp"
  26 #include "gc/shared/collectedHeap.hpp"
  27 #include "gc/shared/collectorPolicy.hpp"
  28 #include "gc/shared/gcLocker.hpp"
  29 #include "logging/log.hpp"
  30 #include "logging/logStream.hpp"
  31 #include "memory/allocation.hpp"
  32 #include "memory/binaryTreeDictionary.hpp"
  33 #include "memory/filemap.hpp"
  34 #include "memory/freeList.hpp"
  35 #include "memory/metachunk.hpp"
  36 #include "memory/metaspace.hpp"
  37 #include "memory/metaspaceGCThresholdUpdater.hpp"
  38 #include "memory/metaspaceShared.hpp"
  39 #include "memory/metaspaceTracer.hpp"
  40 #include "memory/resourceArea.hpp"
  41 #include "memory/universe.hpp"
  42 #include "runtime/atomic.hpp"
  43 #include "runtime/globals.hpp"
  44 #include "runtime/init.hpp"
  45 #include "runtime/java.hpp"
  46 #include "runtime/mutex.hpp"
  47 #include "runtime/orderAccess.inline.hpp"
  48 #include "services/memTracker.hpp"
  49 #include "services/memoryService.hpp"
  50 #include "utilities/align.hpp"
  51 #include "utilities/copy.hpp"
  52 #include "utilities/debug.hpp"
  53 #include "utilities/macros.hpp"
  54 
  55 typedef BinaryTreeDictionary<Metablock, FreeList<Metablock> > BlockTreeDictionary;
  56 typedef BinaryTreeDictionary<Metachunk, FreeList<Metachunk> > ChunkTreeDictionary;
  57 
  58 // Set this constant to enable slow integrity checking of the free chunk lists
  59 const bool metaspace_slow_verify = false;
  60 
  61 size_t const allocation_from_dictionary_limit = 4 * K;
  62 
  63 MetaWord* last_allocated = 0;
  64 
  65 size_t Metaspace::_compressed_class_space_size;
  66 const MetaspaceTracer* Metaspace::_tracer = NULL;
  67 
  68 DEBUG_ONLY(bool Metaspace::_frozen = false;)
  69 
  70 // Used in declarations in SpaceManager and ChunkManager
  71 enum ChunkIndex {
  72   ZeroIndex = 0,
  73   SpecializedIndex = ZeroIndex,
  74   SmallIndex = SpecializedIndex + 1,
  75   MediumIndex = SmallIndex + 1,
  76   HumongousIndex = MediumIndex + 1,
  77   NumberOfFreeLists = 3,
  78   NumberOfInUseLists = 4
  79 };
  80 
  81 // Helper, returns a descriptive name for the given index.
  82 static const char* chunk_size_name(ChunkIndex index) {
  83   switch (index) {
  84     case SpecializedIndex:
  85       return "specialized";
  86     case SmallIndex:
  87       return "small";
  88     case MediumIndex:
  89       return "medium";
  90     case HumongousIndex:
  91       return "humongous";
  92     default:
  93       return "Invalid index";
  94   }
  95 }
  96 
  97 enum ChunkSizes {    // in words.
  98   ClassSpecializedChunk = 128,
  99   SpecializedChunk = 128,
 100   ClassSmallChunk = 256,
 101   SmallChunk = 512,
 102   ClassMediumChunk = 4 * K,
 103   MediumChunk = 8 * K
 104 };
 105 
 106 static ChunkIndex next_chunk_index(ChunkIndex i) {
 107   assert(i < NumberOfInUseLists, "Out of bound");
 108   return (ChunkIndex) (i+1);
 109 }
 110 
 111 static const char* scale_unit(size_t scale) {
 112   switch(scale) {
 113     case 1: return "BYTES";
 114     case K: return "KB";
 115     case M: return "MB";
 116     case G: return "GB";
 117     default:
 118       ShouldNotReachHere();
 119       return NULL;
 120   }
 121 }
 122 
 123 volatile intptr_t MetaspaceGC::_capacity_until_GC = 0;
 124 uint MetaspaceGC::_shrink_factor = 0;
 125 bool MetaspaceGC::_should_concurrent_collect = false;
 126 
 127 typedef class FreeList<Metachunk> ChunkList;
 128 
 129 // Manages the global free lists of chunks.
 130 class ChunkManager : public CHeapObj<mtInternal> {
 131   friend class TestVirtualSpaceNodeTest;
 132 
 133   // Free list of chunks of different sizes.
 134   //   SpecializedChunk
 135   //   SmallChunk
 136   //   MediumChunk
 137   ChunkList _free_chunks[NumberOfFreeLists];
 138 
 139   // Return non-humongous chunk list by its index.
 140   ChunkList* free_chunks(ChunkIndex index);
 141 
 142   // Returns non-humongous chunk list for the given chunk word size.
 143   ChunkList* find_free_chunks_list(size_t word_size);
 144 
 145   //   HumongousChunk
 146   ChunkTreeDictionary _humongous_dictionary;
 147 
 148   // Returns the humongous chunk dictionary.
 149   ChunkTreeDictionary* humongous_dictionary() {
 150     return &_humongous_dictionary;
 151   }
 152 
 153   // Size, in metaspace words, of all chunks managed by this ChunkManager
 154   size_t _free_chunks_total;
 155   // Number of chunks in this ChunkManager
 156   size_t _free_chunks_count;
 157 
 158   // Update counters after a chunk was added or removed removed.
 159   void account_for_added_chunk(const Metachunk* c);
 160   void account_for_removed_chunk(const Metachunk* c);
 161 
 162   // Debug support
 163 
 164   size_t sum_free_chunks();
 165   size_t sum_free_chunks_count();
 166 
 167   void locked_verify_free_chunks_total();
 168   void slow_locked_verify_free_chunks_total() {
 169     if (metaspace_slow_verify) {
 170       locked_verify_free_chunks_total();
 171     }
 172   }
 173   void locked_verify_free_chunks_count();
 174   void slow_locked_verify_free_chunks_count() {
 175     if (metaspace_slow_verify) {
 176       locked_verify_free_chunks_count();
 177     }
 178   }
 179   void verify_free_chunks_count();
 180 
 181   struct ChunkManagerStatistics {
 182     size_t num_by_type[NumberOfFreeLists];
 183     size_t single_size_by_type[NumberOfFreeLists];
 184     size_t total_size_by_type[NumberOfFreeLists];
 185     size_t num_humongous_chunks;
 186     size_t total_size_humongous_chunks;
 187   };
 188 
 189   void locked_get_statistics(ChunkManagerStatistics* stat) const;
 190   void get_statistics(ChunkManagerStatistics* stat) const;
 191   static void print_statistics(const ChunkManagerStatistics* stat, outputStream* out, size_t scale);
 192 
 193  public:
 194 
 195   ChunkManager(size_t specialized_size, size_t small_size, size_t medium_size)
 196       : _free_chunks_total(0), _free_chunks_count(0) {
 197     _free_chunks[SpecializedIndex].set_size(specialized_size);
 198     _free_chunks[SmallIndex].set_size(small_size);
 199     _free_chunks[MediumIndex].set_size(medium_size);
 200   }
 201 
 202   // add or delete (return) a chunk to the global freelist.
 203   Metachunk* chunk_freelist_allocate(size_t word_size);
 204 
 205   // Map a size to a list index assuming that there are lists
 206   // for special, small, medium, and humongous chunks.
 207   ChunkIndex list_index(size_t size);
 208 
 209   // Map a given index to the chunk size.
 210   size_t size_by_index(ChunkIndex index) const;
 211 
 212   // Take a chunk from the ChunkManager. The chunk is expected to be in
 213   // the chunk manager (the freelist if non-humongous, the dictionary if
 214   // humongous).
 215   void remove_chunk(Metachunk* chunk);
 216 
 217   // Return a single chunk of type index to the ChunkManager.
 218   void return_single_chunk(ChunkIndex index, Metachunk* chunk);
 219 
 220   // Add the simple linked list of chunks to the freelist of chunks
 221   // of type index.
 222   void return_chunk_list(ChunkIndex index, Metachunk* chunk);
 223 
 224   // Total of the space in the free chunks list
 225   size_t free_chunks_total_words();
 226   size_t free_chunks_total_bytes();
 227 
 228   // Number of chunks in the free chunks list
 229   size_t free_chunks_count();
 230 
 231   // Remove from a list by size.  Selects list based on size of chunk.
 232   Metachunk* free_chunks_get(size_t chunk_word_size);
 233 
 234 #define index_bounds_check(index)                                         \
 235   assert(index == SpecializedIndex ||                                     \
 236          index == SmallIndex ||                                           \
 237          index == MediumIndex ||                                          \
 238          index == HumongousIndex, "Bad index: %d", (int) index)
 239 
 240   size_t num_free_chunks(ChunkIndex index) const {
 241     index_bounds_check(index);
 242 
 243     if (index == HumongousIndex) {
 244       return _humongous_dictionary.total_free_blocks();
 245     }
 246 
 247     ssize_t count = _free_chunks[index].count();
 248     return count == -1 ? 0 : (size_t) count;
 249   }
 250 
 251   size_t size_free_chunks_in_bytes(ChunkIndex index) const {
 252     index_bounds_check(index);
 253 
 254     size_t word_size = 0;
 255     if (index == HumongousIndex) {
 256       word_size = _humongous_dictionary.total_size();
 257     } else {
 258       const size_t size_per_chunk_in_words = _free_chunks[index].size();
 259       word_size = size_per_chunk_in_words * num_free_chunks(index);
 260     }
 261 
 262     return word_size * BytesPerWord;
 263   }
 264 
 265   MetaspaceChunkFreeListSummary chunk_free_list_summary() const {
 266     return MetaspaceChunkFreeListSummary(num_free_chunks(SpecializedIndex),
 267                                          num_free_chunks(SmallIndex),
 268                                          num_free_chunks(MediumIndex),
 269                                          num_free_chunks(HumongousIndex),
 270                                          size_free_chunks_in_bytes(SpecializedIndex),
 271                                          size_free_chunks_in_bytes(SmallIndex),
 272                                          size_free_chunks_in_bytes(MediumIndex),
 273                                          size_free_chunks_in_bytes(HumongousIndex));
 274   }
 275 
 276   // Debug support
 277   void verify();
 278   void slow_verify() {
 279     if (metaspace_slow_verify) {
 280       verify();
 281     }
 282   }
 283   void locked_verify();
 284   void slow_locked_verify() {
 285     if (metaspace_slow_verify) {
 286       locked_verify();
 287     }
 288   }
 289   void verify_free_chunks_total();
 290 
 291   void locked_print_free_chunks(outputStream* st);
 292   void locked_print_sum_free_chunks(outputStream* st);
 293 
 294   void print_on(outputStream* st) const;
 295 
 296   // Prints composition for both non-class and (if available)
 297   // class chunk manager.
 298   static void print_all_chunkmanagers(outputStream* out, size_t scale = 1);
 299 };
 300 
 301 class SmallBlocks : public CHeapObj<mtClass> {
 302   const static uint _small_block_max_size = sizeof(TreeChunk<Metablock,  FreeList<Metablock> >)/HeapWordSize;
 303   const static uint _small_block_min_size = sizeof(Metablock)/HeapWordSize;
 304 
 305  private:
 306   FreeList<Metablock> _small_lists[_small_block_max_size - _small_block_min_size];
 307 
 308   FreeList<Metablock>& list_at(size_t word_size) {
 309     assert(word_size >= _small_block_min_size, "There are no metaspace objects less than %u words", _small_block_min_size);
 310     return _small_lists[word_size - _small_block_min_size];
 311   }
 312 
 313  public:
 314   SmallBlocks() {
 315     for (uint i = _small_block_min_size; i < _small_block_max_size; i++) {
 316       uint k = i - _small_block_min_size;
 317       _small_lists[k].set_size(i);
 318     }
 319   }
 320 
 321   size_t total_size() const {
 322     size_t result = 0;
 323     for (uint i = _small_block_min_size; i < _small_block_max_size; i++) {
 324       uint k = i - _small_block_min_size;
 325       result = result + _small_lists[k].count() * _small_lists[k].size();
 326     }
 327     return result;
 328   }
 329 
 330   static uint small_block_max_size() { return _small_block_max_size; }
 331   static uint small_block_min_size() { return _small_block_min_size; }
 332 
 333   MetaWord* get_block(size_t word_size) {
 334     if (list_at(word_size).count() > 0) {
 335       MetaWord* new_block = (MetaWord*) list_at(word_size).get_chunk_at_head();
 336       return new_block;
 337     } else {
 338       return NULL;
 339     }
 340   }
 341   void return_block(Metablock* free_chunk, size_t word_size) {
 342     list_at(word_size).return_chunk_at_head(free_chunk, false);
 343     assert(list_at(word_size).count() > 0, "Should have a chunk");
 344   }
 345 
 346   void print_on(outputStream* st) const {
 347     st->print_cr("SmallBlocks:");
 348     for (uint i = _small_block_min_size; i < _small_block_max_size; i++) {
 349       uint k = i - _small_block_min_size;
 350       st->print_cr("small_lists size " SIZE_FORMAT " count " SIZE_FORMAT, _small_lists[k].size(), _small_lists[k].count());
 351     }
 352   }
 353 };
 354 
 355 // Used to manage the free list of Metablocks (a block corresponds
 356 // to the allocation of a quantum of metadata).
 357 class BlockFreelist : public CHeapObj<mtClass> {
 358   BlockTreeDictionary* const _dictionary;
 359   SmallBlocks* _small_blocks;
 360 
 361   // Only allocate and split from freelist if the size of the allocation
 362   // is at least 1/4th the size of the available block.
 363   const static int WasteMultiplier = 4;
 364 
 365   // Accessors
 366   BlockTreeDictionary* dictionary() const { return _dictionary; }
 367   SmallBlocks* small_blocks() {
 368     if (_small_blocks == NULL) {
 369       _small_blocks = new SmallBlocks();
 370     }
 371     return _small_blocks;
 372   }
 373 
 374  public:
 375   BlockFreelist();
 376   ~BlockFreelist();
 377 
 378   // Get and return a block to the free list
 379   MetaWord* get_block(size_t word_size);
 380   void return_block(MetaWord* p, size_t word_size);
 381 
 382   size_t total_size() const  {
 383     size_t result = dictionary()->total_size();
 384     if (_small_blocks != NULL) {
 385       result = result + _small_blocks->total_size();
 386     }
 387     return result;
 388   }
 389 
 390   static size_t min_dictionary_size()   { return TreeChunk<Metablock, FreeList<Metablock> >::min_size(); }
 391   void print_on(outputStream* st) const;
 392 };
 393 
 394 // A VirtualSpaceList node.
 395 class VirtualSpaceNode : public CHeapObj<mtClass> {
 396   friend class VirtualSpaceList;
 397 
 398   // Link to next VirtualSpaceNode
 399   VirtualSpaceNode* _next;
 400 
 401   // total in the VirtualSpace
 402   MemRegion _reserved;
 403   ReservedSpace _rs;
 404   VirtualSpace _virtual_space;
 405   MetaWord* _top;
 406   // count of chunks contained in this VirtualSpace
 407   uintx _container_count;
 408 
 409   // Convenience functions to access the _virtual_space
 410   char* low()  const { return virtual_space()->low(); }
 411   char* high() const { return virtual_space()->high(); }
 412 
 413   // The first Metachunk will be allocated at the bottom of the
 414   // VirtualSpace
 415   Metachunk* first_chunk() { return (Metachunk*) bottom(); }
 416 
 417   // Committed but unused space in the virtual space
 418   size_t free_words_in_vs() const;
 419  public:
 420 
 421   VirtualSpaceNode(size_t byte_size);
 422   VirtualSpaceNode(ReservedSpace rs) : _top(NULL), _next(NULL), _rs(rs), _container_count(0) {}
 423   ~VirtualSpaceNode();
 424 
 425   // Convenience functions for logical bottom and end
 426   MetaWord* bottom() const { return (MetaWord*) _virtual_space.low(); }
 427   MetaWord* end() const { return (MetaWord*) _virtual_space.high(); }
 428 
 429   bool contains(const void* ptr) { return ptr >= low() && ptr < high(); }
 430 
 431   size_t reserved_words() const  { return _virtual_space.reserved_size() / BytesPerWord; }
 432   size_t committed_words() const { return _virtual_space.actual_committed_size() / BytesPerWord; }
 433 
 434   bool is_pre_committed() const { return _virtual_space.special(); }
 435 
 436   // address of next available space in _virtual_space;
 437   // Accessors
 438   VirtualSpaceNode* next() { return _next; }
 439   void set_next(VirtualSpaceNode* v) { _next = v; }
 440 
 441   void set_reserved(MemRegion const v) { _reserved = v; }
 442   void set_top(MetaWord* v) { _top = v; }
 443 
 444   // Accessors
 445   MemRegion* reserved() { return &_reserved; }
 446   VirtualSpace* virtual_space() const { return (VirtualSpace*) &_virtual_space; }
 447 
 448   // Returns true if "word_size" is available in the VirtualSpace
 449   bool is_available(size_t word_size) { return word_size <= pointer_delta(end(), _top, sizeof(MetaWord)); }
 450 
 451   MetaWord* top() const { return _top; }
 452   void inc_top(size_t word_size) { _top += word_size; }
 453 
 454   uintx container_count() { return _container_count; }
 455   void inc_container_count();
 456   void dec_container_count();
 457 #ifdef ASSERT
 458   uintx container_count_slow();
 459   void verify_container_count();
 460 #endif
 461 
 462   // used and capacity in this single entry in the list
 463   size_t used_words_in_vs() const;
 464   size_t capacity_words_in_vs() const;
 465 
 466   bool initialize();
 467 
 468   // get space from the virtual space
 469   Metachunk* take_from_committed(size_t chunk_word_size);
 470 
 471   // Allocate a chunk from the virtual space and return it.
 472   Metachunk* get_chunk_vs(size_t chunk_word_size);
 473 
 474   // Expands/shrinks the committed space in a virtual space.  Delegates
 475   // to Virtualspace
 476   bool expand_by(size_t min_words, size_t preferred_words);
 477 
 478   // In preparation for deleting this node, remove all the chunks
 479   // in the node from any freelist.
 480   void purge(ChunkManager* chunk_manager);
 481 
 482   // If an allocation doesn't fit in the current node a new node is created.
 483   // Allocate chunks out of the remaining committed space in this node
 484   // to avoid wasting that memory.
 485   // This always adds up because all the chunk sizes are multiples of
 486   // the smallest chunk size.
 487   void retire(ChunkManager* chunk_manager);
 488 
 489 #ifdef ASSERT
 490   // Debug support
 491   void mangle();
 492 #endif
 493 
 494   void print_on(outputStream* st) const;
 495   void print_map(outputStream* st, bool is_class) const;
 496 };
 497 
 498 #define assert_is_aligned(value, alignment)                  \
 499   assert(is_aligned((value), (alignment)),                   \
 500          SIZE_FORMAT_HEX " is not aligned to "               \
 501          SIZE_FORMAT, (size_t)(uintptr_t)value, (alignment))
 502 
 503 // Decide if large pages should be committed when the memory is reserved.
 504 static bool should_commit_large_pages_when_reserving(size_t bytes) {
 505   if (UseLargePages && UseLargePagesInMetaspace && !os::can_commit_large_page_memory()) {
 506     size_t words = bytes / BytesPerWord;
 507     bool is_class = false; // We never reserve large pages for the class space.
 508     if (MetaspaceGC::can_expand(words, is_class) &&
 509         MetaspaceGC::allowed_expansion() >= words) {
 510       return true;
 511     }
 512   }
 513 
 514   return false;
 515 }
 516 
 517   // byte_size is the size of the associated virtualspace.
 518 VirtualSpaceNode::VirtualSpaceNode(size_t bytes) : _top(NULL), _next(NULL), _rs(), _container_count(0) {
 519   assert_is_aligned(bytes, Metaspace::reserve_alignment());
 520   bool large_pages = should_commit_large_pages_when_reserving(bytes);
 521   _rs = ReservedSpace(bytes, Metaspace::reserve_alignment(), large_pages);
 522 
 523   if (_rs.is_reserved()) {
 524     assert(_rs.base() != NULL, "Catch if we get a NULL address");
 525     assert(_rs.size() != 0, "Catch if we get a 0 size");
 526     assert_is_aligned(_rs.base(), Metaspace::reserve_alignment());
 527     assert_is_aligned(_rs.size(), Metaspace::reserve_alignment());
 528 
 529     MemTracker::record_virtual_memory_type((address)_rs.base(), mtClass);
 530   }
 531 }
 532 
 533 void VirtualSpaceNode::purge(ChunkManager* chunk_manager) {
 534   Metachunk* chunk = first_chunk();
 535   Metachunk* invalid_chunk = (Metachunk*) top();
 536   while (chunk < invalid_chunk ) {
 537     assert(chunk->is_tagged_free(), "Should be tagged free");
 538     MetaWord* next = ((MetaWord*)chunk) + chunk->word_size();
 539     chunk_manager->remove_chunk(chunk);
 540     assert(chunk->next() == NULL &&
 541            chunk->prev() == NULL,
 542            "Was not removed from its list");
 543     chunk = (Metachunk*) next;
 544   }
 545 }
 546 
 547 void VirtualSpaceNode::print_map(outputStream* st, bool is_class) const {
 548 
 549   // Format:
 550   // <ptr>
 551   // <ptr>  . .. .               .  ..
 552   //        SSxSSMMMMMMMMMMMMMMMMsssXX
 553   //        112114444444444444444
 554   // <ptr>  . .. .               .  ..
 555   //        SSxSSMMMMMMMMMMMMMMMMsssXX
 556   //        112114444444444444444
 557 
 558   if (bottom() == top()) {
 559     return;
 560   }
 561 
 562   // First line: dividers for every med-chunk-sized interval
 563   // Second line: a dot for the start of a chunk
 564   // Third line: a letter per chunk type (x,s,m,h), uppercase if in use.
 565 
 566   const size_t spec_chunk_size = is_class ? ClassSpecializedChunk : SpecializedChunk;
 567   const size_t small_chunk_size = is_class ? ClassSmallChunk : SmallChunk;
 568   const size_t med_chunk_size = is_class ? ClassMediumChunk : MediumChunk;
 569 
 570   int line_len = 100;
 571   const size_t section_len = align_up(spec_chunk_size * line_len, med_chunk_size);
 572   line_len = (int)(section_len / spec_chunk_size);
 573 
 574   char* line1 = (char*)os::malloc(line_len, mtInternal);
 575   char* line2 = (char*)os::malloc(line_len, mtInternal);
 576   char* line3 = (char*)os::malloc(line_len, mtInternal);
 577   int pos = 0;
 578   const MetaWord* p = bottom();
 579   const Metachunk* chunk = (const Metachunk*)p;
 580   const MetaWord* chunk_end = p + chunk->word_size();
 581   while (p < top()) {
 582     if (pos == line_len) {
 583       pos = 0;
 584       st->fill_to(22);
 585       st->print_raw(line1, line_len);
 586       st->cr();
 587       st->fill_to(22);
 588       st->print_raw(line2, line_len);
 589       st->cr();
 590     }
 591     if (pos == 0) {
 592       st->print(PTR_FORMAT ":", p2i(p));
 593     }
 594     if (p == chunk_end) {
 595       chunk = (Metachunk*)p;
 596       chunk_end = p + chunk->word_size();
 597     }
 598     if (p == (const MetaWord*)chunk) {
 599       // chunk starts.
 600       line1[pos] = '.';
 601     } else {
 602       line1[pos] = ' ';
 603     }
 604     // Line 2: chunk type (x=spec, s=small, m=medium, h=humongous), uppercase if
 605     // chunk is in use.
 606     const bool chunk_is_free = ((Metachunk*)chunk)->is_tagged_free();
 607     if (chunk->word_size() == spec_chunk_size) {
 608       line2[pos] = chunk_is_free ? 'x' : 'X';
 609     } else if (chunk->word_size() == small_chunk_size) {
 610       line2[pos] = chunk_is_free ? 's' : 'S';
 611     } else if (chunk->word_size() == med_chunk_size) {
 612       line2[pos] = chunk_is_free ? 'm' : 'M';
 613    } else if (chunk->word_size() > med_chunk_size) {
 614       line2[pos] = chunk_is_free ? 'h' : 'H';
 615     } else {
 616       ShouldNotReachHere();
 617     }
 618     p += spec_chunk_size;
 619     pos ++;
 620   }
 621   if (pos > 0) {
 622     st->fill_to(22);
 623     st->print_raw(line1, pos);
 624     st->cr();
 625     st->fill_to(22);
 626     st->print_raw(line2, pos);
 627     st->cr();
 628   }
 629   os::free(line1);
 630   os::free(line2);
 631   os::free(line3);
 632 }
 633 
 634 
 635 #ifdef ASSERT
 636 uintx VirtualSpaceNode::container_count_slow() {
 637   uintx count = 0;
 638   Metachunk* chunk = first_chunk();
 639   Metachunk* invalid_chunk = (Metachunk*) top();
 640   while (chunk < invalid_chunk ) {
 641     MetaWord* next = ((MetaWord*)chunk) + chunk->word_size();
 642     // Don't count the chunks on the free lists.  Those are
 643     // still part of the VirtualSpaceNode but not currently
 644     // counted.
 645     if (!chunk->is_tagged_free()) {
 646       count++;
 647     }
 648     chunk = (Metachunk*) next;
 649   }
 650   return count;
 651 }
 652 #endif
 653 
 654 // List of VirtualSpaces for metadata allocation.
 655 class VirtualSpaceList : public CHeapObj<mtClass> {
 656   friend class VirtualSpaceNode;
 657 
 658   enum VirtualSpaceSizes {
 659     VirtualSpaceSize = 256 * K
 660   };
 661 
 662   // Head of the list
 663   VirtualSpaceNode* _virtual_space_list;
 664   // virtual space currently being used for allocations
 665   VirtualSpaceNode* _current_virtual_space;
 666 
 667   // Is this VirtualSpaceList used for the compressed class space
 668   bool _is_class;
 669 
 670   // Sum of reserved and committed memory in the virtual spaces
 671   size_t _reserved_words;
 672   size_t _committed_words;
 673 
 674   // Number of virtual spaces
 675   size_t _virtual_space_count;
 676 
 677   ~VirtualSpaceList();
 678 
 679   VirtualSpaceNode* virtual_space_list() const { return _virtual_space_list; }
 680 
 681   void set_virtual_space_list(VirtualSpaceNode* v) {
 682     _virtual_space_list = v;
 683   }
 684   void set_current_virtual_space(VirtualSpaceNode* v) {
 685     _current_virtual_space = v;
 686   }
 687 
 688   void link_vs(VirtualSpaceNode* new_entry);
 689 
 690   // Get another virtual space and add it to the list.  This
 691   // is typically prompted by a failed attempt to allocate a chunk
 692   // and is typically followed by the allocation of a chunk.
 693   bool create_new_virtual_space(size_t vs_word_size);
 694 
 695   // Chunk up the unused committed space in the current
 696   // virtual space and add the chunks to the free list.
 697   void retire_current_virtual_space();
 698 
 699  public:
 700   VirtualSpaceList(size_t word_size);
 701   VirtualSpaceList(ReservedSpace rs);
 702 
 703   size_t free_bytes();
 704 
 705   Metachunk* get_new_chunk(size_t chunk_word_size,
 706                            size_t suggested_commit_granularity);
 707 
 708   bool expand_node_by(VirtualSpaceNode* node,
 709                       size_t min_words,
 710                       size_t preferred_words);
 711 
 712   bool expand_by(size_t min_words,
 713                  size_t preferred_words);
 714 
 715   VirtualSpaceNode* current_virtual_space() {
 716     return _current_virtual_space;
 717   }
 718 
 719   bool is_class() const { return _is_class; }
 720 
 721   bool initialization_succeeded() { return _virtual_space_list != NULL; }
 722 
 723   size_t reserved_words()  { return _reserved_words; }
 724   size_t reserved_bytes()  { return reserved_words() * BytesPerWord; }
 725   size_t committed_words() { return _committed_words; }
 726   size_t committed_bytes() { return committed_words() * BytesPerWord; }
 727 
 728   void inc_reserved_words(size_t v);
 729   void dec_reserved_words(size_t v);
 730   void inc_committed_words(size_t v);
 731   void dec_committed_words(size_t v);
 732   void inc_virtual_space_count();
 733   void dec_virtual_space_count();
 734 
 735   bool contains(const void* ptr);
 736 
 737   // Unlink empty VirtualSpaceNodes and free it.
 738   void purge(ChunkManager* chunk_manager);
 739 
 740   void print_on(outputStream* st) const;
 741   void print_map(outputStream* st) const;
 742 
 743   class VirtualSpaceListIterator : public StackObj {
 744     VirtualSpaceNode* _virtual_spaces;
 745    public:
 746     VirtualSpaceListIterator(VirtualSpaceNode* virtual_spaces) :
 747       _virtual_spaces(virtual_spaces) {}
 748 
 749     bool repeat() {
 750       return _virtual_spaces != NULL;
 751     }
 752 
 753     VirtualSpaceNode* get_next() {
 754       VirtualSpaceNode* result = _virtual_spaces;
 755       if (_virtual_spaces != NULL) {
 756         _virtual_spaces = _virtual_spaces->next();
 757       }
 758       return result;
 759     }
 760   };
 761 };
 762 
 763 class Metadebug : AllStatic {
 764   // Debugging support for Metaspaces
 765   static int _allocation_fail_alot_count;
 766 
 767  public:
 768 
 769   static void init_allocation_fail_alot_count();
 770 #ifdef ASSERT
 771   static bool test_metadata_failure();
 772 #endif
 773 };
 774 
 775 int Metadebug::_allocation_fail_alot_count = 0;
 776 
 777 //  SpaceManager - used by Metaspace to handle allocations
 778 class SpaceManager : public CHeapObj<mtClass> {
 779   friend class Metaspace;
 780   friend class Metadebug;
 781 
 782  private:
 783 
 784   // protects allocations
 785   Mutex* const _lock;
 786 
 787   // Type of metadata allocated.
 788   const Metaspace::MetadataType   _mdtype;
 789 
 790   // Type of metaspace
 791   const Metaspace::MetaspaceType  _space_type;
 792 
 793   // List of chunks in use by this SpaceManager.  Allocations
 794   // are done from the current chunk.  The list is used for deallocating
 795   // chunks when the SpaceManager is freed.
 796   Metachunk* _chunks_in_use[NumberOfInUseLists];
 797   Metachunk* _current_chunk;
 798 
 799   // Maximum number of small chunks to allocate to a SpaceManager
 800   static uint const _small_chunk_limit;
 801 
 802   // Maximum number of specialize chunks to allocate for anonymous
 803   // metadata space to a SpaceManager
 804   static uint const _anon_metadata_specialize_chunk_limit;
 805 
 806   // Sum of all space in allocated chunks
 807   size_t _allocated_blocks_words;
 808 
 809   // Sum of all allocated chunks
 810   size_t _allocated_chunks_words;
 811   size_t _allocated_chunks_count;
 812 
 813   // Free lists of blocks are per SpaceManager since they
 814   // are assumed to be in chunks in use by the SpaceManager
 815   // and all chunks in use by a SpaceManager are freed when
 816   // the class loader using the SpaceManager is collected.
 817   BlockFreelist* _block_freelists;
 818 
 819   // protects virtualspace and chunk expansions
 820   static const char*  _expand_lock_name;
 821   static const int    _expand_lock_rank;
 822   static Mutex* const _expand_lock;
 823 
 824  private:
 825   // Accessors
 826   Metachunk* chunks_in_use(ChunkIndex index) const { return _chunks_in_use[index]; }
 827   void set_chunks_in_use(ChunkIndex index, Metachunk* v) {
 828     _chunks_in_use[index] = v;
 829   }
 830 
 831   BlockFreelist* block_freelists() const { return _block_freelists; }
 832 
 833   Metaspace::MetadataType mdtype() { return _mdtype; }
 834 
 835   VirtualSpaceList* vs_list()   const { return Metaspace::get_space_list(_mdtype); }
 836   ChunkManager* chunk_manager() const { return Metaspace::get_chunk_manager(_mdtype); }
 837 
 838   Metachunk* current_chunk() const { return _current_chunk; }
 839   void set_current_chunk(Metachunk* v) {
 840     _current_chunk = v;
 841   }
 842 
 843   Metachunk* find_current_chunk(size_t word_size);
 844 
 845   // Add chunk to the list of chunks in use
 846   void add_chunk(Metachunk* v, bool make_current);
 847   void retire_current_chunk();
 848 
 849   Mutex* lock() const { return _lock; }
 850 
 851  protected:
 852   void initialize();
 853 
 854  public:
 855   SpaceManager(Metaspace::MetadataType mdtype,
 856                Metaspace::MetaspaceType space_type,
 857                Mutex* lock);
 858   ~SpaceManager();
 859 
 860   enum ChunkMultiples {
 861     MediumChunkMultiple = 4
 862   };
 863 
 864   static size_t specialized_chunk_size(bool is_class) { return is_class ? ClassSpecializedChunk : SpecializedChunk; }
 865   static size_t small_chunk_size(bool is_class)       { return is_class ? ClassSmallChunk : SmallChunk; }
 866   static size_t medium_chunk_size(bool is_class)      { return is_class ? ClassMediumChunk : MediumChunk; }
 867 
 868   static size_t smallest_chunk_size(bool is_class)    { return specialized_chunk_size(is_class); }
 869 
 870   // Accessors
 871   bool is_class() const { return _mdtype == Metaspace::ClassType; }
 872 
 873   size_t specialized_chunk_size() const { return specialized_chunk_size(is_class()); }
 874   size_t small_chunk_size()       const { return small_chunk_size(is_class()); }
 875   size_t medium_chunk_size()      const { return medium_chunk_size(is_class()); }
 876 
 877   size_t smallest_chunk_size()    const { return smallest_chunk_size(is_class()); }
 878 
 879   size_t medium_chunk_bunch()     const { return medium_chunk_size() * MediumChunkMultiple; }
 880 
 881   size_t allocated_blocks_words() const { return _allocated_blocks_words; }
 882   size_t allocated_blocks_bytes() const { return _allocated_blocks_words * BytesPerWord; }
 883   size_t allocated_chunks_words() const { return _allocated_chunks_words; }
 884   size_t allocated_chunks_bytes() const { return _allocated_chunks_words * BytesPerWord; }
 885   size_t allocated_chunks_count() const { return _allocated_chunks_count; }
 886 
 887   bool is_humongous(size_t word_size) { return word_size > medium_chunk_size(); }
 888 
 889   static Mutex* expand_lock() { return _expand_lock; }
 890 
 891   // Increment the per Metaspace and global running sums for Metachunks
 892   // by the given size.  This is used when a Metachunk to added to
 893   // the in-use list.
 894   void inc_size_metrics(size_t words);
 895   // Increment the per Metaspace and global running sums Metablocks by the given
 896   // size.  This is used when a Metablock is allocated.
 897   void inc_used_metrics(size_t words);
 898   // Delete the portion of the running sums for this SpaceManager. That is,
 899   // the globals running sums for the Metachunks and Metablocks are
 900   // decremented for all the Metachunks in-use by this SpaceManager.
 901   void dec_total_from_size_metrics();
 902 
 903   // Adjust the initial chunk size to match one of the fixed chunk list sizes,
 904   // or return the unadjusted size if the requested size is humongous.
 905   static size_t adjust_initial_chunk_size(size_t requested, bool is_class_space);
 906   size_t adjust_initial_chunk_size(size_t requested) const;
 907 
 908   // Get the initial chunks size for this metaspace type.
 909   size_t get_initial_chunk_size(Metaspace::MetaspaceType type) const;
 910 
 911   size_t sum_capacity_in_chunks_in_use() const;
 912   size_t sum_used_in_chunks_in_use() const;
 913   size_t sum_free_in_chunks_in_use() const;
 914   size_t sum_waste_in_chunks_in_use() const;
 915   size_t sum_waste_in_chunks_in_use(ChunkIndex index ) const;
 916 
 917   size_t sum_count_in_chunks_in_use();
 918   size_t sum_count_in_chunks_in_use(ChunkIndex i);
 919 
 920   Metachunk* get_new_chunk(size_t chunk_word_size);
 921 
 922   // Block allocation and deallocation.
 923   // Allocates a block from the current chunk
 924   MetaWord* allocate(size_t word_size);
 925   // Allocates a block from a small chunk
 926   MetaWord* get_small_chunk_and_allocate(size_t word_size);
 927 
 928   // Helper for allocations
 929   MetaWord* allocate_work(size_t word_size);
 930 
 931   // Returns a block to the per manager freelist
 932   void deallocate(MetaWord* p, size_t word_size);
 933 
 934   // Based on the allocation size and a minimum chunk size,
 935   // returned chunk size (for expanding space for chunk allocation).
 936   size_t calc_chunk_size(size_t allocation_word_size);
 937 
 938   // Called when an allocation from the current chunk fails.
 939   // Gets a new chunk (may require getting a new virtual space),
 940   // and allocates from that chunk.
 941   MetaWord* grow_and_allocate(size_t word_size);
 942 
 943   // Notify memory usage to MemoryService.
 944   void track_metaspace_memory_usage();
 945 
 946   // debugging support.
 947 
 948   void dump(outputStream* const out) const;
 949   void print_on(outputStream* st) const;
 950   void locked_print_chunks_in_use_on(outputStream* st) const;
 951 
 952   void verify();
 953   void verify_chunk_size(Metachunk* chunk);
 954 #ifdef ASSERT
 955   void verify_allocated_blocks_words();
 956 #endif
 957 
 958   // This adjusts the size given to be greater than the minimum allocation size in
 959   // words for data in metaspace.  Esentially the minimum size is currently 3 words.
 960   size_t get_allocation_word_size(size_t word_size) {
 961     size_t byte_size = word_size * BytesPerWord;
 962 
 963     size_t raw_bytes_size = MAX2(byte_size, sizeof(Metablock));
 964     raw_bytes_size = align_up(raw_bytes_size, Metachunk::object_alignment());
 965 
 966     size_t raw_word_size = raw_bytes_size / BytesPerWord;
 967     assert(raw_word_size * BytesPerWord == raw_bytes_size, "Size problem");
 968 
 969     return raw_word_size;
 970   }
 971 };
 972 
 973 uint const SpaceManager::_small_chunk_limit = 4;
 974 uint const SpaceManager::_anon_metadata_specialize_chunk_limit = 4;
 975 
 976 const char* SpaceManager::_expand_lock_name =
 977   "SpaceManager chunk allocation lock";
 978 const int SpaceManager::_expand_lock_rank = Monitor::leaf - 1;
 979 Mutex* const SpaceManager::_expand_lock =
 980   new Mutex(SpaceManager::_expand_lock_rank,
 981             SpaceManager::_expand_lock_name,
 982             Mutex::_allow_vm_block_flag,
 983             Monitor::_safepoint_check_never);
 984 
 985 void VirtualSpaceNode::inc_container_count() {
 986   assert_lock_strong(SpaceManager::expand_lock());
 987   _container_count++;
 988 }
 989 
 990 void VirtualSpaceNode::dec_container_count() {
 991   assert_lock_strong(SpaceManager::expand_lock());
 992   _container_count--;
 993 }
 994 
 995 #ifdef ASSERT
 996 void VirtualSpaceNode::verify_container_count() {
 997   assert(_container_count == container_count_slow(),
 998          "Inconsistency in container_count _container_count " UINTX_FORMAT
 999          " container_count_slow() " UINTX_FORMAT, _container_count, container_count_slow());
1000 }
1001 #endif
1002 
1003 // BlockFreelist methods
1004 
1005 BlockFreelist::BlockFreelist() : _dictionary(new BlockTreeDictionary()), _small_blocks(NULL) {}
1006 
1007 BlockFreelist::~BlockFreelist() {
1008   delete _dictionary;
1009   if (_small_blocks != NULL) {
1010     delete _small_blocks;
1011   }
1012 }
1013 
1014 void BlockFreelist::return_block(MetaWord* p, size_t word_size) {
1015   assert(word_size >= SmallBlocks::small_block_min_size(), "never return dark matter");
1016 
1017   Metablock* free_chunk = ::new (p) Metablock(word_size);
1018   if (word_size < SmallBlocks::small_block_max_size()) {
1019     small_blocks()->return_block(free_chunk, word_size);
1020   } else {
1021   dictionary()->return_chunk(free_chunk);
1022 }
1023   log_trace(gc, metaspace, freelist, blocks)("returning block at " INTPTR_FORMAT " size = "
1024             SIZE_FORMAT, p2i(free_chunk), word_size);
1025 }
1026 
1027 MetaWord* BlockFreelist::get_block(size_t word_size) {
1028   assert(word_size >= SmallBlocks::small_block_min_size(), "never get dark matter");
1029 
1030   // Try small_blocks first.
1031   if (word_size < SmallBlocks::small_block_max_size()) {
1032     // Don't create small_blocks() until needed.  small_blocks() allocates the small block list for
1033     // this space manager.
1034     MetaWord* new_block = (MetaWord*) small_blocks()->get_block(word_size);
1035     if (new_block != NULL) {
1036       log_trace(gc, metaspace, freelist, blocks)("getting block at " INTPTR_FORMAT " size = " SIZE_FORMAT,
1037               p2i(new_block), word_size);
1038       return new_block;
1039     }
1040   }
1041 
1042   if (word_size < BlockFreelist::min_dictionary_size()) {
1043     // If allocation in small blocks fails, this is Dark Matter.  Too small for dictionary.
1044     return NULL;
1045   }
1046 
1047   Metablock* free_block = dictionary()->get_chunk(word_size);
1048   if (free_block == NULL) {
1049     return NULL;
1050   }
1051 
1052   const size_t block_size = free_block->size();
1053   if (block_size > WasteMultiplier * word_size) {
1054     return_block((MetaWord*)free_block, block_size);
1055     return NULL;
1056   }
1057 
1058   MetaWord* new_block = (MetaWord*)free_block;
1059   assert(block_size >= word_size, "Incorrect size of block from freelist");
1060   const size_t unused = block_size - word_size;
1061   if (unused >= SmallBlocks::small_block_min_size()) {
1062     return_block(new_block + word_size, unused);
1063   }
1064 
1065   log_trace(gc, metaspace, freelist, blocks)("getting block at " INTPTR_FORMAT " size = " SIZE_FORMAT,
1066             p2i(new_block), word_size);
1067   return new_block;
1068 }
1069 
1070 void BlockFreelist::print_on(outputStream* st) const {
1071   dictionary()->print_free_lists(st);
1072   if (_small_blocks != NULL) {
1073     _small_blocks->print_on(st);
1074   }
1075 }
1076 
1077 // VirtualSpaceNode methods
1078 
1079 VirtualSpaceNode::~VirtualSpaceNode() {
1080   _rs.release();
1081 #ifdef ASSERT
1082   size_t word_size = sizeof(*this) / BytesPerWord;
1083   Copy::fill_to_words((HeapWord*) this, word_size, 0xf1f1f1f1);
1084 #endif
1085 }
1086 
1087 size_t VirtualSpaceNode::used_words_in_vs() const {
1088   return pointer_delta(top(), bottom(), sizeof(MetaWord));
1089 }
1090 
1091 // Space committed in the VirtualSpace
1092 size_t VirtualSpaceNode::capacity_words_in_vs() const {
1093   return pointer_delta(end(), bottom(), sizeof(MetaWord));
1094 }
1095 
1096 size_t VirtualSpaceNode::free_words_in_vs() const {
1097   return pointer_delta(end(), top(), sizeof(MetaWord));
1098 }
1099 
1100 // Allocates the chunk from the virtual space only.
1101 // This interface is also used internally for debugging.  Not all
1102 // chunks removed here are necessarily used for allocation.
1103 Metachunk* VirtualSpaceNode::take_from_committed(size_t chunk_word_size) {
1104   // Bottom of the new chunk
1105   MetaWord* chunk_limit = top();
1106   assert(chunk_limit != NULL, "Not safe to call this method");
1107 
1108   // The virtual spaces are always expanded by the
1109   // commit granularity to enforce the following condition.
1110   // Without this the is_available check will not work correctly.
1111   assert(_virtual_space.committed_size() == _virtual_space.actual_committed_size(),
1112       "The committed memory doesn't match the expanded memory.");
1113 
1114   if (!is_available(chunk_word_size)) {
1115     LogTarget(Debug, gc, metaspace, freelist) lt;
1116     if (lt.is_enabled()) {
1117       LogStream ls(lt);
1118       ls.print("VirtualSpaceNode::take_from_committed() not available " SIZE_FORMAT " words ", chunk_word_size);
1119       // Dump some information about the virtual space that is nearly full
1120       print_on(&ls);
1121     }
1122     return NULL;
1123   }
1124 
1125   // Take the space  (bump top on the current virtual space).
1126   inc_top(chunk_word_size);
1127 
1128   // Initialize the chunk
1129   Metachunk* result = ::new (chunk_limit) Metachunk(chunk_word_size, this);
1130   return result;
1131 }
1132 
1133 
1134 // Expand the virtual space (commit more of the reserved space)
1135 bool VirtualSpaceNode::expand_by(size_t min_words, size_t preferred_words) {
1136   size_t min_bytes = min_words * BytesPerWord;
1137   size_t preferred_bytes = preferred_words * BytesPerWord;
1138 
1139   size_t uncommitted = virtual_space()->reserved_size() - virtual_space()->actual_committed_size();
1140 
1141   if (uncommitted < min_bytes) {
1142     return false;
1143   }
1144 
1145   size_t commit = MIN2(preferred_bytes, uncommitted);
1146   bool result = virtual_space()->expand_by(commit, false);
1147 
1148   assert(result, "Failed to commit memory");
1149 
1150   return result;
1151 }
1152 
1153 Metachunk* VirtualSpaceNode::get_chunk_vs(size_t chunk_word_size) {
1154   assert_lock_strong(SpaceManager::expand_lock());
1155   Metachunk* result = take_from_committed(chunk_word_size);
1156   if (result != NULL) {
1157     inc_container_count();
1158   }
1159   return result;
1160 }
1161 
1162 bool VirtualSpaceNode::initialize() {
1163 
1164   if (!_rs.is_reserved()) {
1165     return false;
1166   }
1167 
1168   // These are necessary restriction to make sure that the virtual space always
1169   // grows in steps of Metaspace::commit_alignment(). If both base and size are
1170   // aligned only the middle alignment of the VirtualSpace is used.
1171   assert_is_aligned(_rs.base(), Metaspace::commit_alignment());
1172   assert_is_aligned(_rs.size(), Metaspace::commit_alignment());
1173 
1174   // ReservedSpaces marked as special will have the entire memory
1175   // pre-committed. Setting a committed size will make sure that
1176   // committed_size and actual_committed_size agrees.
1177   size_t pre_committed_size = _rs.special() ? _rs.size() : 0;
1178 
1179   bool result = virtual_space()->initialize_with_granularity(_rs, pre_committed_size,
1180                                             Metaspace::commit_alignment());
1181   if (result) {
1182     assert(virtual_space()->committed_size() == virtual_space()->actual_committed_size(),
1183         "Checking that the pre-committed memory was registered by the VirtualSpace");
1184 
1185     set_top((MetaWord*)virtual_space()->low());
1186     set_reserved(MemRegion((HeapWord*)_rs.base(),
1187                  (HeapWord*)(_rs.base() + _rs.size())));
1188 
1189     assert(reserved()->start() == (HeapWord*) _rs.base(),
1190            "Reserved start was not set properly " PTR_FORMAT
1191            " != " PTR_FORMAT, p2i(reserved()->start()), p2i(_rs.base()));
1192     assert(reserved()->word_size() == _rs.size() / BytesPerWord,
1193            "Reserved size was not set properly " SIZE_FORMAT
1194            " != " SIZE_FORMAT, reserved()->word_size(),
1195            _rs.size() / BytesPerWord);
1196   }
1197 
1198   return result;
1199 }
1200 
1201 void VirtualSpaceNode::print_on(outputStream* st) const {
1202   size_t used = used_words_in_vs();
1203   size_t capacity = capacity_words_in_vs();
1204   VirtualSpace* vs = virtual_space();
1205   st->print_cr("   space @ " PTR_FORMAT " " SIZE_FORMAT "K, " SIZE_FORMAT_W(3) "%% used "
1206            "[" PTR_FORMAT ", " PTR_FORMAT ", "
1207            PTR_FORMAT ", " PTR_FORMAT ")",
1208            p2i(vs), capacity / K,
1209            capacity == 0 ? 0 : used * 100 / capacity,
1210            p2i(bottom()), p2i(top()), p2i(end()),
1211            p2i(vs->high_boundary()));
1212 }
1213 
1214 #ifdef ASSERT
1215 void VirtualSpaceNode::mangle() {
1216   size_t word_size = capacity_words_in_vs();
1217   Copy::fill_to_words((HeapWord*) low(), word_size, 0xf1f1f1f1);
1218 }
1219 #endif // ASSERT
1220 
1221 // VirtualSpaceList methods
1222 // Space allocated from the VirtualSpace
1223 
1224 VirtualSpaceList::~VirtualSpaceList() {
1225   VirtualSpaceListIterator iter(virtual_space_list());
1226   while (iter.repeat()) {
1227     VirtualSpaceNode* vsl = iter.get_next();
1228     delete vsl;
1229   }
1230 }
1231 
1232 void VirtualSpaceList::inc_reserved_words(size_t v) {
1233   assert_lock_strong(SpaceManager::expand_lock());
1234   _reserved_words = _reserved_words + v;
1235 }
1236 void VirtualSpaceList::dec_reserved_words(size_t v) {
1237   assert_lock_strong(SpaceManager::expand_lock());
1238   _reserved_words = _reserved_words - v;
1239 }
1240 
1241 #define assert_committed_below_limit()                        \
1242   assert(MetaspaceAux::committed_bytes() <= MaxMetaspaceSize, \
1243          "Too much committed memory. Committed: " SIZE_FORMAT \
1244          " limit (MaxMetaspaceSize): " SIZE_FORMAT,           \
1245          MetaspaceAux::committed_bytes(), MaxMetaspaceSize);
1246 
1247 void VirtualSpaceList::inc_committed_words(size_t v) {
1248   assert_lock_strong(SpaceManager::expand_lock());
1249   _committed_words = _committed_words + v;
1250 
1251   assert_committed_below_limit();
1252 }
1253 void VirtualSpaceList::dec_committed_words(size_t v) {
1254   assert_lock_strong(SpaceManager::expand_lock());
1255   _committed_words = _committed_words - v;
1256 
1257   assert_committed_below_limit();
1258 }
1259 
1260 void VirtualSpaceList::inc_virtual_space_count() {
1261   assert_lock_strong(SpaceManager::expand_lock());
1262   _virtual_space_count++;
1263 }
1264 void VirtualSpaceList::dec_virtual_space_count() {
1265   assert_lock_strong(SpaceManager::expand_lock());
1266   _virtual_space_count--;
1267 }
1268 
1269 void ChunkManager::remove_chunk(Metachunk* chunk) {
1270   size_t word_size = chunk->word_size();
1271   ChunkIndex index = list_index(word_size);
1272   if (index != HumongousIndex) {
1273     free_chunks(index)->remove_chunk(chunk);
1274   } else {
1275     humongous_dictionary()->remove_chunk(chunk);
1276   }
1277 
1278   // Chunk has been removed from the chunks free list, update counters.
1279   account_for_removed_chunk(chunk);
1280 }
1281 
1282 // Walk the list of VirtualSpaceNodes and delete
1283 // nodes with a 0 container_count.  Remove Metachunks in
1284 // the node from their respective freelists.
1285 void VirtualSpaceList::purge(ChunkManager* chunk_manager) {
1286   assert(SafepointSynchronize::is_at_safepoint(), "must be called at safepoint for contains to work");
1287   assert_lock_strong(SpaceManager::expand_lock());
1288   // Don't use a VirtualSpaceListIterator because this
1289   // list is being changed and a straightforward use of an iterator is not safe.
1290   VirtualSpaceNode* purged_vsl = NULL;
1291   VirtualSpaceNode* prev_vsl = virtual_space_list();
1292   VirtualSpaceNode* next_vsl = prev_vsl;
1293   while (next_vsl != NULL) {
1294     VirtualSpaceNode* vsl = next_vsl;
1295     DEBUG_ONLY(vsl->verify_container_count();)
1296     next_vsl = vsl->next();
1297     // Don't free the current virtual space since it will likely
1298     // be needed soon.
1299     if (vsl->container_count() == 0 && vsl != current_virtual_space()) {
1300       // Unlink it from the list
1301       if (prev_vsl == vsl) {
1302         // This is the case of the current node being the first node.
1303         assert(vsl == virtual_space_list(), "Expected to be the first node");
1304         set_virtual_space_list(vsl->next());
1305       } else {
1306         prev_vsl->set_next(vsl->next());
1307       }
1308 
1309       vsl->purge(chunk_manager);
1310       dec_reserved_words(vsl->reserved_words());
1311       dec_committed_words(vsl->committed_words());
1312       dec_virtual_space_count();
1313       purged_vsl = vsl;
1314       delete vsl;
1315     } else {
1316       prev_vsl = vsl;
1317     }
1318   }
1319 #ifdef ASSERT
1320   if (purged_vsl != NULL) {
1321     // List should be stable enough to use an iterator here.
1322     VirtualSpaceListIterator iter(virtual_space_list());
1323     while (iter.repeat()) {
1324       VirtualSpaceNode* vsl = iter.get_next();
1325       assert(vsl != purged_vsl, "Purge of vsl failed");
1326     }
1327   }
1328 #endif
1329 }
1330 
1331 
1332 // This function looks at the mmap regions in the metaspace without locking.
1333 // The chunks are added with store ordering and not deleted except for at
1334 // unloading time during a safepoint.
1335 bool VirtualSpaceList::contains(const void* ptr) {
1336   // List should be stable enough to use an iterator here because removing virtual
1337   // space nodes is only allowed at a safepoint.
1338   VirtualSpaceListIterator iter(virtual_space_list());
1339   while (iter.repeat()) {
1340     VirtualSpaceNode* vsn = iter.get_next();
1341     if (vsn->contains(ptr)) {
1342       return true;
1343     }
1344   }
1345   return false;
1346 }
1347 
1348 void VirtualSpaceList::retire_current_virtual_space() {
1349   assert_lock_strong(SpaceManager::expand_lock());
1350 
1351   VirtualSpaceNode* vsn = current_virtual_space();
1352 
1353   ChunkManager* cm = is_class() ? Metaspace::chunk_manager_class() :
1354                                   Metaspace::chunk_manager_metadata();
1355 
1356   vsn->retire(cm);
1357 }
1358 
1359 void VirtualSpaceNode::retire(ChunkManager* chunk_manager) {
1360   DEBUG_ONLY(verify_container_count();)
1361   for (int i = (int)MediumIndex; i >= (int)ZeroIndex; --i) {
1362     ChunkIndex index = (ChunkIndex)i;
1363     size_t chunk_size = chunk_manager->size_by_index(index);
1364 
1365     while (free_words_in_vs() >= chunk_size) {
1366       Metachunk* chunk = get_chunk_vs(chunk_size);
1367       assert(chunk != NULL, "allocation should have been successful");
1368 
1369       chunk_manager->return_single_chunk(index, chunk);
1370     }
1371     DEBUG_ONLY(verify_container_count();)
1372   }
1373   assert(free_words_in_vs() == 0, "should be empty now");
1374 }
1375 
1376 VirtualSpaceList::VirtualSpaceList(size_t word_size) :
1377                                    _is_class(false),
1378                                    _virtual_space_list(NULL),
1379                                    _current_virtual_space(NULL),
1380                                    _reserved_words(0),
1381                                    _committed_words(0),
1382                                    _virtual_space_count(0) {
1383   MutexLockerEx cl(SpaceManager::expand_lock(),
1384                    Mutex::_no_safepoint_check_flag);
1385   create_new_virtual_space(word_size);
1386 }
1387 
1388 VirtualSpaceList::VirtualSpaceList(ReservedSpace rs) :
1389                                    _is_class(true),
1390                                    _virtual_space_list(NULL),
1391                                    _current_virtual_space(NULL),
1392                                    _reserved_words(0),
1393                                    _committed_words(0),
1394                                    _virtual_space_count(0) {
1395   MutexLockerEx cl(SpaceManager::expand_lock(),
1396                    Mutex::_no_safepoint_check_flag);
1397   VirtualSpaceNode* class_entry = new VirtualSpaceNode(rs);
1398   bool succeeded = class_entry->initialize();
1399   if (succeeded) {
1400     link_vs(class_entry);
1401   }
1402 }
1403 
1404 size_t VirtualSpaceList::free_bytes() {
1405   return current_virtual_space()->free_words_in_vs() * BytesPerWord;
1406 }
1407 
1408 // Allocate another meta virtual space and add it to the list.
1409 bool VirtualSpaceList::create_new_virtual_space(size_t vs_word_size) {
1410   assert_lock_strong(SpaceManager::expand_lock());
1411 
1412   if (is_class()) {
1413     assert(false, "We currently don't support more than one VirtualSpace for"
1414                   " the compressed class space. The initialization of the"
1415                   " CCS uses another code path and should not hit this path.");
1416     return false;
1417   }
1418 
1419   if (vs_word_size == 0) {
1420     assert(false, "vs_word_size should always be at least _reserve_alignment large.");
1421     return false;
1422   }
1423 
1424   // Reserve the space
1425   size_t vs_byte_size = vs_word_size * BytesPerWord;
1426   assert_is_aligned(vs_byte_size, Metaspace::reserve_alignment());
1427 
1428   // Allocate the meta virtual space and initialize it.
1429   VirtualSpaceNode* new_entry = new VirtualSpaceNode(vs_byte_size);
1430   if (!new_entry->initialize()) {
1431     delete new_entry;
1432     return false;
1433   } else {
1434     assert(new_entry->reserved_words() == vs_word_size,
1435         "Reserved memory size differs from requested memory size");
1436     // ensure lock-free iteration sees fully initialized node
1437     OrderAccess::storestore();
1438     link_vs(new_entry);
1439     return true;
1440   }
1441 }
1442 
1443 void VirtualSpaceList::link_vs(VirtualSpaceNode* new_entry) {
1444   if (virtual_space_list() == NULL) {
1445       set_virtual_space_list(new_entry);
1446   } else {
1447     current_virtual_space()->set_next(new_entry);
1448   }
1449   set_current_virtual_space(new_entry);
1450   inc_reserved_words(new_entry->reserved_words());
1451   inc_committed_words(new_entry->committed_words());
1452   inc_virtual_space_count();
1453 #ifdef ASSERT
1454   new_entry->mangle();
1455 #endif
1456   LogTarget(Trace, gc, metaspace) lt;
1457   if (lt.is_enabled()) {
1458     LogStream ls(lt);
1459     VirtualSpaceNode* vsl = current_virtual_space();
1460     ResourceMark rm;
1461     vsl->print_on(&ls);
1462   }
1463 }
1464 
1465 bool VirtualSpaceList::expand_node_by(VirtualSpaceNode* node,
1466                                       size_t min_words,
1467                                       size_t preferred_words) {
1468   size_t before = node->committed_words();
1469 
1470   bool result = node->expand_by(min_words, preferred_words);
1471 
1472   size_t after = node->committed_words();
1473 
1474   // after and before can be the same if the memory was pre-committed.
1475   assert(after >= before, "Inconsistency");
1476   inc_committed_words(after - before);
1477 
1478   return result;
1479 }
1480 
1481 bool VirtualSpaceList::expand_by(size_t min_words, size_t preferred_words) {
1482   assert_is_aligned(min_words,       Metaspace::commit_alignment_words());
1483   assert_is_aligned(preferred_words, Metaspace::commit_alignment_words());
1484   assert(min_words <= preferred_words, "Invalid arguments");
1485 
1486   if (!MetaspaceGC::can_expand(min_words, this->is_class())) {
1487     return  false;
1488   }
1489 
1490   size_t allowed_expansion_words = MetaspaceGC::allowed_expansion();
1491   if (allowed_expansion_words < min_words) {
1492     return false;
1493   }
1494 
1495   size_t max_expansion_words = MIN2(preferred_words, allowed_expansion_words);
1496 
1497   // Commit more memory from the the current virtual space.
1498   bool vs_expanded = expand_node_by(current_virtual_space(),
1499                                     min_words,
1500                                     max_expansion_words);
1501   if (vs_expanded) {
1502     return true;
1503   }
1504   retire_current_virtual_space();
1505 
1506   // Get another virtual space.
1507   size_t grow_vs_words = MAX2((size_t)VirtualSpaceSize, preferred_words);
1508   grow_vs_words = align_up(grow_vs_words, Metaspace::reserve_alignment_words());
1509 
1510   if (create_new_virtual_space(grow_vs_words)) {
1511     if (current_virtual_space()->is_pre_committed()) {
1512       // The memory was pre-committed, so we are done here.
1513       assert(min_words <= current_virtual_space()->committed_words(),
1514           "The new VirtualSpace was pre-committed, so it"
1515           "should be large enough to fit the alloc request.");
1516       return true;
1517     }
1518 
1519     return expand_node_by(current_virtual_space(),
1520                           min_words,
1521                           max_expansion_words);
1522   }
1523 
1524   return false;
1525 }
1526 
1527 Metachunk* VirtualSpaceList::get_new_chunk(size_t chunk_word_size, size_t suggested_commit_granularity) {
1528 
1529   // Allocate a chunk out of the current virtual space.
1530   Metachunk* next = current_virtual_space()->get_chunk_vs(chunk_word_size);
1531 
1532   if (next != NULL) {
1533     return next;
1534   }
1535 
1536   // The expand amount is currently only determined by the requested sizes
1537   // and not how much committed memory is left in the current virtual space.
1538 
1539   size_t min_word_size       = align_up(chunk_word_size,              Metaspace::commit_alignment_words());
1540   size_t preferred_word_size = align_up(suggested_commit_granularity, Metaspace::commit_alignment_words());
1541   if (min_word_size >= preferred_word_size) {
1542     // Can happen when humongous chunks are allocated.
1543     preferred_word_size = min_word_size;
1544   }
1545 
1546   bool expanded = expand_by(min_word_size, preferred_word_size);
1547   if (expanded) {
1548     next = current_virtual_space()->get_chunk_vs(chunk_word_size);
1549     assert(next != NULL, "The allocation was expected to succeed after the expansion");
1550   }
1551 
1552    return next;
1553 }
1554 
1555 void VirtualSpaceList::print_on(outputStream* st) const {
1556   VirtualSpaceListIterator iter(virtual_space_list());
1557   while (iter.repeat()) {
1558     VirtualSpaceNode* node = iter.get_next();
1559     node->print_on(st);
1560   }
1561 }
1562 
1563 void VirtualSpaceList::print_map(outputStream* st) const {
1564   VirtualSpaceNode* list = virtual_space_list();
1565   VirtualSpaceListIterator iter(list);
1566   unsigned i = 0;
1567   while (iter.repeat()) {
1568     st->print_cr("Node %u:", i);
1569     VirtualSpaceNode* node = iter.get_next();
1570     node->print_map(st, this->is_class());
1571     i ++;
1572   }
1573 }
1574 
1575 // MetaspaceGC methods
1576 
1577 // VM_CollectForMetadataAllocation is the vm operation used to GC.
1578 // Within the VM operation after the GC the attempt to allocate the metadata
1579 // should succeed.  If the GC did not free enough space for the metaspace
1580 // allocation, the HWM is increased so that another virtualspace will be
1581 // allocated for the metadata.  With perm gen the increase in the perm
1582 // gen had bounds, MinMetaspaceExpansion and MaxMetaspaceExpansion.  The
1583 // metaspace policy uses those as the small and large steps for the HWM.
1584 //
1585 // After the GC the compute_new_size() for MetaspaceGC is called to
1586 // resize the capacity of the metaspaces.  The current implementation
1587 // is based on the flags MinMetaspaceFreeRatio and MaxMetaspaceFreeRatio used
1588 // to resize the Java heap by some GC's.  New flags can be implemented
1589 // if really needed.  MinMetaspaceFreeRatio is used to calculate how much
1590 // free space is desirable in the metaspace capacity to decide how much
1591 // to increase the HWM.  MaxMetaspaceFreeRatio is used to decide how much
1592 // free space is desirable in the metaspace capacity before decreasing
1593 // the HWM.
1594 
1595 // Calculate the amount to increase the high water mark (HWM).
1596 // Increase by a minimum amount (MinMetaspaceExpansion) so that
1597 // another expansion is not requested too soon.  If that is not
1598 // enough to satisfy the allocation, increase by MaxMetaspaceExpansion.
1599 // If that is still not enough, expand by the size of the allocation
1600 // plus some.
1601 size_t MetaspaceGC::delta_capacity_until_GC(size_t bytes) {
1602   size_t min_delta = MinMetaspaceExpansion;
1603   size_t max_delta = MaxMetaspaceExpansion;
1604   size_t delta = align_up(bytes, Metaspace::commit_alignment());
1605 
1606   if (delta <= min_delta) {
1607     delta = min_delta;
1608   } else if (delta <= max_delta) {
1609     // Don't want to hit the high water mark on the next
1610     // allocation so make the delta greater than just enough
1611     // for this allocation.
1612     delta = max_delta;
1613   } else {
1614     // This allocation is large but the next ones are probably not
1615     // so increase by the minimum.
1616     delta = delta + min_delta;
1617   }
1618 
1619   assert_is_aligned(delta, Metaspace::commit_alignment());
1620 
1621   return delta;
1622 }
1623 
1624 size_t MetaspaceGC::capacity_until_GC() {
1625   size_t value = OrderAccess::load_acquire(&_capacity_until_GC);
1626   assert(value >= MetaspaceSize, "Not initialized properly?");
1627   return value;
1628 }
1629 
1630 bool MetaspaceGC::inc_capacity_until_GC(size_t v, size_t* new_cap_until_GC, size_t* old_cap_until_GC) {
1631   assert_is_aligned(v, Metaspace::commit_alignment());
1632 
1633   intptr_t capacity_until_GC = _capacity_until_GC;
1634   intptr_t new_value = capacity_until_GC + v;
1635 
1636   if (new_value < capacity_until_GC) {
1637     // The addition wrapped around, set new_value to aligned max value.
1638     new_value = align_down(max_uintx, Metaspace::commit_alignment());
1639   }
1640 
1641   intptr_t expected = _capacity_until_GC;
1642   intptr_t actual = Atomic::cmpxchg(new_value, &_capacity_until_GC, expected);
1643 
1644   if (expected != actual) {
1645     return false;
1646   }
1647 
1648   if (new_cap_until_GC != NULL) {
1649     *new_cap_until_GC = new_value;
1650   }
1651   if (old_cap_until_GC != NULL) {
1652     *old_cap_until_GC = capacity_until_GC;
1653   }
1654   return true;
1655 }
1656 
1657 size_t MetaspaceGC::dec_capacity_until_GC(size_t v) {
1658   assert_is_aligned(v, Metaspace::commit_alignment());
1659 
1660   return (size_t)Atomic::sub((intptr_t)v, &_capacity_until_GC);
1661 }
1662 
1663 void MetaspaceGC::initialize() {
1664   // Set the high-water mark to MaxMetapaceSize during VM initializaton since
1665   // we can't do a GC during initialization.
1666   _capacity_until_GC = MaxMetaspaceSize;
1667 }
1668 
1669 void MetaspaceGC::post_initialize() {
1670   // Reset the high-water mark once the VM initialization is done.
1671   _capacity_until_GC = MAX2(MetaspaceAux::committed_bytes(), MetaspaceSize);
1672 }
1673 
1674 bool MetaspaceGC::can_expand(size_t word_size, bool is_class) {
1675   // Check if the compressed class space is full.
1676   if (is_class && Metaspace::using_class_space()) {
1677     size_t class_committed = MetaspaceAux::committed_bytes(Metaspace::ClassType);
1678     if (class_committed + word_size * BytesPerWord > CompressedClassSpaceSize) {
1679       return false;
1680     }
1681   }
1682 
1683   // Check if the user has imposed a limit on the metaspace memory.
1684   size_t committed_bytes = MetaspaceAux::committed_bytes();
1685   if (committed_bytes + word_size * BytesPerWord > MaxMetaspaceSize) {
1686     return false;
1687   }
1688 
1689   return true;
1690 }
1691 
1692 size_t MetaspaceGC::allowed_expansion() {
1693   size_t committed_bytes = MetaspaceAux::committed_bytes();
1694   size_t capacity_until_gc = capacity_until_GC();
1695 
1696   assert(capacity_until_gc >= committed_bytes,
1697          "capacity_until_gc: " SIZE_FORMAT " < committed_bytes: " SIZE_FORMAT,
1698          capacity_until_gc, committed_bytes);
1699 
1700   size_t left_until_max  = MaxMetaspaceSize - committed_bytes;
1701   size_t left_until_GC = capacity_until_gc - committed_bytes;
1702   size_t left_to_commit = MIN2(left_until_GC, left_until_max);
1703 
1704   return left_to_commit / BytesPerWord;
1705 }
1706 
1707 void MetaspaceGC::compute_new_size() {
1708   assert(_shrink_factor <= 100, "invalid shrink factor");
1709   uint current_shrink_factor = _shrink_factor;
1710   _shrink_factor = 0;
1711 
1712   // Using committed_bytes() for used_after_gc is an overestimation, since the
1713   // chunk free lists are included in committed_bytes() and the memory in an
1714   // un-fragmented chunk free list is available for future allocations.
1715   // However, if the chunk free lists becomes fragmented, then the memory may
1716   // not be available for future allocations and the memory is therefore "in use".
1717   // Including the chunk free lists in the definition of "in use" is therefore
1718   // necessary. Not including the chunk free lists can cause capacity_until_GC to
1719   // shrink below committed_bytes() and this has caused serious bugs in the past.
1720   const size_t used_after_gc = MetaspaceAux::committed_bytes();
1721   const size_t capacity_until_GC = MetaspaceGC::capacity_until_GC();
1722 
1723   const double minimum_free_percentage = MinMetaspaceFreeRatio / 100.0;
1724   const double maximum_used_percentage = 1.0 - minimum_free_percentage;
1725 
1726   const double min_tmp = used_after_gc / maximum_used_percentage;
1727   size_t minimum_desired_capacity =
1728     (size_t)MIN2(min_tmp, double(max_uintx));
1729   // Don't shrink less than the initial generation size
1730   minimum_desired_capacity = MAX2(minimum_desired_capacity,
1731                                   MetaspaceSize);
1732 
1733   log_trace(gc, metaspace)("MetaspaceGC::compute_new_size: ");
1734   log_trace(gc, metaspace)("    minimum_free_percentage: %6.2f  maximum_used_percentage: %6.2f",
1735                            minimum_free_percentage, maximum_used_percentage);
1736   log_trace(gc, metaspace)("     used_after_gc       : %6.1fKB", used_after_gc / (double) K);
1737 
1738 
1739   size_t shrink_bytes = 0;
1740   if (capacity_until_GC < minimum_desired_capacity) {
1741     // If we have less capacity below the metaspace HWM, then
1742     // increment the HWM.
1743     size_t expand_bytes = minimum_desired_capacity - capacity_until_GC;
1744     expand_bytes = align_up(expand_bytes, Metaspace::commit_alignment());
1745     // Don't expand unless it's significant
1746     if (expand_bytes >= MinMetaspaceExpansion) {
1747       size_t new_capacity_until_GC = 0;
1748       bool succeeded = MetaspaceGC::inc_capacity_until_GC(expand_bytes, &new_capacity_until_GC);
1749       assert(succeeded, "Should always succesfully increment HWM when at safepoint");
1750 
1751       Metaspace::tracer()->report_gc_threshold(capacity_until_GC,
1752                                                new_capacity_until_GC,
1753                                                MetaspaceGCThresholdUpdater::ComputeNewSize);
1754       log_trace(gc, metaspace)("    expanding:  minimum_desired_capacity: %6.1fKB  expand_bytes: %6.1fKB  MinMetaspaceExpansion: %6.1fKB  new metaspace HWM:  %6.1fKB",
1755                                minimum_desired_capacity / (double) K,
1756                                expand_bytes / (double) K,
1757                                MinMetaspaceExpansion / (double) K,
1758                                new_capacity_until_GC / (double) K);
1759     }
1760     return;
1761   }
1762 
1763   // No expansion, now see if we want to shrink
1764   // We would never want to shrink more than this
1765   assert(capacity_until_GC >= minimum_desired_capacity,
1766          SIZE_FORMAT " >= " SIZE_FORMAT,
1767          capacity_until_GC, minimum_desired_capacity);
1768   size_t max_shrink_bytes = capacity_until_GC - minimum_desired_capacity;
1769 
1770   // Should shrinking be considered?
1771   if (MaxMetaspaceFreeRatio < 100) {
1772     const double maximum_free_percentage = MaxMetaspaceFreeRatio / 100.0;
1773     const double minimum_used_percentage = 1.0 - maximum_free_percentage;
1774     const double max_tmp = used_after_gc / minimum_used_percentage;
1775     size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(max_uintx));
1776     maximum_desired_capacity = MAX2(maximum_desired_capacity,
1777                                     MetaspaceSize);
1778     log_trace(gc, metaspace)("    maximum_free_percentage: %6.2f  minimum_used_percentage: %6.2f",
1779                              maximum_free_percentage, minimum_used_percentage);
1780     log_trace(gc, metaspace)("    minimum_desired_capacity: %6.1fKB  maximum_desired_capacity: %6.1fKB",
1781                              minimum_desired_capacity / (double) K, maximum_desired_capacity / (double) K);
1782 
1783     assert(minimum_desired_capacity <= maximum_desired_capacity,
1784            "sanity check");
1785 
1786     if (capacity_until_GC > maximum_desired_capacity) {
1787       // Capacity too large, compute shrinking size
1788       shrink_bytes = capacity_until_GC - maximum_desired_capacity;
1789       // We don't want shrink all the way back to initSize if people call
1790       // System.gc(), because some programs do that between "phases" and then
1791       // we'd just have to grow the heap up again for the next phase.  So we
1792       // damp the shrinking: 0% on the first call, 10% on the second call, 40%
1793       // on the third call, and 100% by the fourth call.  But if we recompute
1794       // size without shrinking, it goes back to 0%.
1795       shrink_bytes = shrink_bytes / 100 * current_shrink_factor;
1796 
1797       shrink_bytes = align_down(shrink_bytes, Metaspace::commit_alignment());
1798 
1799       assert(shrink_bytes <= max_shrink_bytes,
1800              "invalid shrink size " SIZE_FORMAT " not <= " SIZE_FORMAT,
1801              shrink_bytes, max_shrink_bytes);
1802       if (current_shrink_factor == 0) {
1803         _shrink_factor = 10;
1804       } else {
1805         _shrink_factor = MIN2(current_shrink_factor * 4, (uint) 100);
1806       }
1807       log_trace(gc, metaspace)("    shrinking:  initThreshold: %.1fK  maximum_desired_capacity: %.1fK",
1808                                MetaspaceSize / (double) K, maximum_desired_capacity / (double) K);
1809       log_trace(gc, metaspace)("    shrink_bytes: %.1fK  current_shrink_factor: %d  new shrink factor: %d  MinMetaspaceExpansion: %.1fK",
1810                                shrink_bytes / (double) K, current_shrink_factor, _shrink_factor, MinMetaspaceExpansion / (double) K);
1811     }
1812   }
1813 
1814   // Don't shrink unless it's significant
1815   if (shrink_bytes >= MinMetaspaceExpansion &&
1816       ((capacity_until_GC - shrink_bytes) >= MetaspaceSize)) {
1817     size_t new_capacity_until_GC = MetaspaceGC::dec_capacity_until_GC(shrink_bytes);
1818     Metaspace::tracer()->report_gc_threshold(capacity_until_GC,
1819                                              new_capacity_until_GC,
1820                                              MetaspaceGCThresholdUpdater::ComputeNewSize);
1821   }
1822 }
1823 
1824 // Metadebug methods
1825 
1826 void Metadebug::init_allocation_fail_alot_count() {
1827   if (MetadataAllocationFailALot) {
1828     _allocation_fail_alot_count =
1829       1+(long)((double)MetadataAllocationFailALotInterval*os::random()/(max_jint+1.0));
1830   }
1831 }
1832 
1833 #ifdef ASSERT
1834 bool Metadebug::test_metadata_failure() {
1835   if (MetadataAllocationFailALot &&
1836       Threads::is_vm_complete()) {
1837     if (_allocation_fail_alot_count > 0) {
1838       _allocation_fail_alot_count--;
1839     } else {
1840       log_trace(gc, metaspace, freelist)("Metadata allocation failing for MetadataAllocationFailALot");
1841       init_allocation_fail_alot_count();
1842       return true;
1843     }
1844   }
1845   return false;
1846 }
1847 #endif
1848 
1849 // ChunkManager methods
1850 size_t ChunkManager::free_chunks_total_words() {
1851   return _free_chunks_total;
1852 }
1853 
1854 size_t ChunkManager::free_chunks_total_bytes() {
1855   return free_chunks_total_words() * BytesPerWord;
1856 }
1857 
1858 // Update internal accounting after a chunk was added
1859 void ChunkManager::account_for_added_chunk(const Metachunk* c) {
1860   assert_lock_strong(SpaceManager::expand_lock());
1861   _free_chunks_count ++;
1862   _free_chunks_total += c->word_size();
1863 }
1864 
1865 // Update internal accounting after a chunk was removed
1866 void ChunkManager::account_for_removed_chunk(const Metachunk* c) {
1867   assert_lock_strong(SpaceManager::expand_lock());
1868   assert(_free_chunks_count >= 1,
1869     "ChunkManager::_free_chunks_count: about to go negative (" SIZE_FORMAT ").", _free_chunks_count);
1870   assert(_free_chunks_total >= c->word_size(),
1871     "ChunkManager::_free_chunks_total: about to go negative"
1872      "(now: " SIZE_FORMAT ", decrement value: " SIZE_FORMAT ").", _free_chunks_total, c->word_size());
1873   _free_chunks_count --;
1874   _free_chunks_total -= c->word_size();
1875 }
1876 
1877 size_t ChunkManager::free_chunks_count() {
1878 #ifdef ASSERT
1879   if (!UseConcMarkSweepGC && !SpaceManager::expand_lock()->is_locked()) {
1880     MutexLockerEx cl(SpaceManager::expand_lock(),
1881                      Mutex::_no_safepoint_check_flag);
1882     // This lock is only needed in debug because the verification
1883     // of the _free_chunks_totals walks the list of free chunks
1884     slow_locked_verify_free_chunks_count();
1885   }
1886 #endif
1887   return _free_chunks_count;
1888 }
1889 
1890 ChunkIndex ChunkManager::list_index(size_t size) {
1891   if (size_by_index(SpecializedIndex) == size) {
1892     return SpecializedIndex;
1893   }
1894   if (size_by_index(SmallIndex) == size) {
1895     return SmallIndex;
1896   }
1897   const size_t med_size = size_by_index(MediumIndex);
1898   if (med_size == size) {
1899     return MediumIndex;
1900   }
1901 
1902   assert(size > med_size, "Not a humongous chunk");
1903   return HumongousIndex;
1904 }
1905 
1906 size_t ChunkManager::size_by_index(ChunkIndex index) const {
1907   index_bounds_check(index);
1908   assert(index != HumongousIndex, "Do not call for humongous chunks.");
1909   return _free_chunks[index].size();
1910 }
1911 
1912 void ChunkManager::locked_verify_free_chunks_total() {
1913   assert_lock_strong(SpaceManager::expand_lock());
1914   assert(sum_free_chunks() == _free_chunks_total,
1915          "_free_chunks_total " SIZE_FORMAT " is not the"
1916          " same as sum " SIZE_FORMAT, _free_chunks_total,
1917          sum_free_chunks());
1918 }
1919 
1920 void ChunkManager::verify_free_chunks_total() {
1921   MutexLockerEx cl(SpaceManager::expand_lock(),
1922                      Mutex::_no_safepoint_check_flag);
1923   locked_verify_free_chunks_total();
1924 }
1925 
1926 void ChunkManager::locked_verify_free_chunks_count() {
1927   assert_lock_strong(SpaceManager::expand_lock());
1928   assert(sum_free_chunks_count() == _free_chunks_count,
1929          "_free_chunks_count " SIZE_FORMAT " is not the"
1930          " same as sum " SIZE_FORMAT, _free_chunks_count,
1931          sum_free_chunks_count());
1932 }
1933 
1934 void ChunkManager::verify_free_chunks_count() {
1935 #ifdef ASSERT
1936   MutexLockerEx cl(SpaceManager::expand_lock(),
1937                      Mutex::_no_safepoint_check_flag);
1938   locked_verify_free_chunks_count();
1939 #endif
1940 }
1941 
1942 void ChunkManager::verify() {
1943   MutexLockerEx cl(SpaceManager::expand_lock(),
1944                      Mutex::_no_safepoint_check_flag);
1945   locked_verify();
1946 }
1947 
1948 void ChunkManager::locked_verify() {
1949   locked_verify_free_chunks_count();
1950   locked_verify_free_chunks_total();
1951 }
1952 
1953 void ChunkManager::locked_print_free_chunks(outputStream* st) {
1954   assert_lock_strong(SpaceManager::expand_lock());
1955   st->print_cr("Free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
1956                 _free_chunks_total, _free_chunks_count);
1957 }
1958 
1959 void ChunkManager::locked_print_sum_free_chunks(outputStream* st) {
1960   assert_lock_strong(SpaceManager::expand_lock());
1961   st->print_cr("Sum free chunk total " SIZE_FORMAT "  count " SIZE_FORMAT,
1962                 sum_free_chunks(), sum_free_chunks_count());
1963 }
1964 
1965 ChunkList* ChunkManager::free_chunks(ChunkIndex index) {
1966   assert(index == SpecializedIndex || index == SmallIndex || index == MediumIndex,
1967          "Bad index: %d", (int)index);
1968 
1969   return &_free_chunks[index];
1970 }
1971 
1972 // These methods that sum the free chunk lists are used in printing
1973 // methods that are used in product builds.
1974 size_t ChunkManager::sum_free_chunks() {
1975   assert_lock_strong(SpaceManager::expand_lock());
1976   size_t result = 0;
1977   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
1978     ChunkList* list = free_chunks(i);
1979 
1980     if (list == NULL) {
1981       continue;
1982     }
1983 
1984     result = result + list->count() * list->size();
1985   }
1986   result = result + humongous_dictionary()->total_size();
1987   return result;
1988 }
1989 
1990 size_t ChunkManager::sum_free_chunks_count() {
1991   assert_lock_strong(SpaceManager::expand_lock());
1992   size_t count = 0;
1993   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
1994     ChunkList* list = free_chunks(i);
1995     if (list == NULL) {
1996       continue;
1997     }
1998     count = count + list->count();
1999   }
2000   count = count + humongous_dictionary()->total_free_blocks();
2001   return count;
2002 }
2003 
2004 ChunkList* ChunkManager::find_free_chunks_list(size_t word_size) {
2005   ChunkIndex index = list_index(word_size);
2006   assert(index < HumongousIndex, "No humongous list");
2007   return free_chunks(index);
2008 }
2009 
2010 Metachunk* ChunkManager::free_chunks_get(size_t word_size) {
2011   assert_lock_strong(SpaceManager::expand_lock());
2012 
2013   slow_locked_verify();
2014 
2015   Metachunk* chunk = NULL;
2016   if (list_index(word_size) != HumongousIndex) {
2017     ChunkList* free_list = find_free_chunks_list(word_size);
2018     assert(free_list != NULL, "Sanity check");
2019 
2020     chunk = free_list->head();
2021 
2022     if (chunk == NULL) {
2023       return NULL;
2024     }
2025 
2026     // Remove the chunk as the head of the list.
2027     free_list->remove_chunk(chunk);
2028 
2029     log_trace(gc, metaspace, freelist)("ChunkManager::free_chunks_get: free_list " PTR_FORMAT " head " PTR_FORMAT " size " SIZE_FORMAT,
2030                                        p2i(free_list), p2i(chunk), chunk->word_size());
2031   } else {
2032     chunk = humongous_dictionary()->get_chunk(word_size);
2033 
2034     if (chunk == NULL) {
2035       return NULL;
2036     }
2037 
2038     log_debug(gc, metaspace, alloc)("Free list allocate humongous chunk size " SIZE_FORMAT " for requested size " SIZE_FORMAT " waste " SIZE_FORMAT,
2039                                     chunk->word_size(), word_size, chunk->word_size() - word_size);
2040   }
2041 
2042   // Chunk has been removed from the chunk manager; update counters.
2043   account_for_removed_chunk(chunk);
2044 
2045   // Remove it from the links to this freelist
2046   chunk->set_next(NULL);
2047   chunk->set_prev(NULL);
2048 
2049   // Chunk is no longer on any freelist. Setting to false make container_count_slow()
2050   // work.
2051   chunk->set_is_tagged_free(false);
2052   chunk->container()->inc_container_count();
2053 
2054   slow_locked_verify();
2055   return chunk;
2056 }
2057 
2058 Metachunk* ChunkManager::chunk_freelist_allocate(size_t word_size) {
2059   assert_lock_strong(SpaceManager::expand_lock());
2060   slow_locked_verify();
2061 
2062   // Take from the beginning of the list
2063   Metachunk* chunk = free_chunks_get(word_size);
2064   if (chunk == NULL) {
2065     return NULL;
2066   }
2067 
2068   assert((word_size <= chunk->word_size()) ||
2069          (list_index(chunk->word_size()) == HumongousIndex),
2070          "Non-humongous variable sized chunk");
2071   LogTarget(Debug, gc, metaspace, freelist) lt;
2072   if (lt.is_enabled()) {
2073     size_t list_count;
2074     if (list_index(word_size) < HumongousIndex) {
2075       ChunkList* list = find_free_chunks_list(word_size);
2076       list_count = list->count();
2077     } else {
2078       list_count = humongous_dictionary()->total_count();
2079     }
2080     LogStream ls(lt);
2081     ls.print("ChunkManager::chunk_freelist_allocate: " PTR_FORMAT " chunk " PTR_FORMAT "  size " SIZE_FORMAT " count " SIZE_FORMAT " ",
2082              p2i(this), p2i(chunk), chunk->word_size(), list_count);
2083     ResourceMark rm;
2084     locked_print_free_chunks(&ls);
2085   }
2086 
2087   return chunk;
2088 }
2089 
2090 void ChunkManager::return_single_chunk(ChunkIndex index, Metachunk* chunk) {
2091   assert_lock_strong(SpaceManager::expand_lock());
2092   assert(chunk != NULL, "Expected chunk.");
2093   assert(chunk->container() != NULL, "Container should have been set.");
2094   assert(chunk->is_tagged_free() == false, "Chunk should be in use.");
2095   index_bounds_check(index);
2096 
2097   // Note: mangle *before* returning the chunk to the freelist or dictionary. It does not
2098   // matter for the freelist (non-humongous chunks), but the humongous chunk dictionary
2099   // keeps tree node pointers in the chunk payload area which mangle will overwrite.
2100   NOT_PRODUCT(chunk->mangle(badMetaWordVal);)
2101 
2102   if (index != HumongousIndex) {
2103     // Return non-humongous chunk to freelist.
2104     ChunkList* list = free_chunks(index);
2105     assert(list->size() == chunk->word_size(), "Wrong chunk type.");
2106     list->return_chunk_at_head(chunk);
2107     log_trace(gc, metaspace, freelist)("returned one %s chunk at " PTR_FORMAT " to freelist.",
2108         chunk_size_name(index), p2i(chunk));
2109   } else {
2110     // Return humongous chunk to dictionary.
2111     assert(chunk->word_size() > free_chunks(MediumIndex)->size(), "Wrong chunk type.");
2112     assert(chunk->word_size() % free_chunks(SpecializedIndex)->size() == 0,
2113            "Humongous chunk has wrong alignment.");
2114     _humongous_dictionary.return_chunk(chunk);
2115     log_trace(gc, metaspace, freelist)("returned one %s chunk at " PTR_FORMAT " (word size " SIZE_FORMAT ") to freelist.",
2116         chunk_size_name(index), p2i(chunk), chunk->word_size());
2117   }
2118   chunk->container()->dec_container_count();
2119   chunk->set_is_tagged_free(true);
2120 
2121   // Chunk has been added; update counters.
2122   account_for_added_chunk(chunk);
2123 
2124 }
2125 
2126 void ChunkManager::return_chunk_list(ChunkIndex index, Metachunk* chunks) {
2127   index_bounds_check(index);
2128   if (chunks == NULL) {
2129     return;
2130   }
2131   LogTarget(Trace, gc, metaspace, freelist) log;
2132   if (log.is_enabled()) { // tracing
2133     log.print("returning list of %s chunks...", chunk_size_name(index));
2134   }
2135   unsigned num_chunks_returned = 0;
2136   size_t size_chunks_returned = 0;
2137   Metachunk* cur = chunks;
2138   while (cur != NULL) {
2139     // Capture the next link before it is changed
2140     // by the call to return_chunk_at_head();
2141     Metachunk* next = cur->next();
2142     if (log.is_enabled()) { // tracing
2143       num_chunks_returned ++;
2144       size_chunks_returned += cur->word_size();
2145     }
2146     return_single_chunk(index, cur);
2147     cur = next;
2148   }
2149   if (log.is_enabled()) { // tracing
2150     log.print("returned %u %s chunks to freelist, total word size " SIZE_FORMAT ".",
2151         num_chunks_returned, chunk_size_name(index), size_chunks_returned);
2152     if (index != HumongousIndex) {
2153       log.print("updated freelist count: " SIZE_FORMAT ".", free_chunks(index)->size());
2154     } else {
2155       log.print("updated dictionary count " SIZE_FORMAT ".", _humongous_dictionary.total_count());
2156     }
2157   }
2158 }
2159 
2160 void ChunkManager::print_on(outputStream* out) const {
2161   _humongous_dictionary.report_statistics(out);
2162 }
2163 
2164 void ChunkManager::locked_get_statistics(ChunkManagerStatistics* stat) const {
2165   assert_lock_strong(SpaceManager::expand_lock());
2166   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
2167     stat->num_by_type[i] = num_free_chunks(i);
2168     stat->single_size_by_type[i] = size_by_index(i);
2169     stat->total_size_by_type[i] = size_free_chunks_in_bytes(i);
2170   }
2171   stat->num_humongous_chunks = num_free_chunks(HumongousIndex);
2172   stat->total_size_humongous_chunks = size_free_chunks_in_bytes(HumongousIndex);
2173 }
2174 
2175 void ChunkManager::get_statistics(ChunkManagerStatistics* stat) const {
2176   MutexLockerEx cl(SpaceManager::expand_lock(),
2177                    Mutex::_no_safepoint_check_flag);
2178   locked_get_statistics(stat);
2179 }
2180 
2181 void ChunkManager::print_statistics(const ChunkManagerStatistics* stat, outputStream* out, size_t scale) {
2182   size_t total = 0;
2183   assert(scale == 1 || scale == K || scale == M || scale == G, "Invalid scale");
2184 
2185   const char* unit = scale_unit(scale);
2186   for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
2187     out->print("  " SIZE_FORMAT " %s (" SIZE_FORMAT " bytes) chunks, total ",
2188                    stat->num_by_type[i], chunk_size_name(i),
2189                    stat->single_size_by_type[i]);
2190     if (scale == 1) {
2191       out->print_cr(SIZE_FORMAT " bytes", stat->total_size_by_type[i]);
2192     } else {
2193       out->print_cr("%.2f%s", (float)stat->total_size_by_type[i] / scale, unit);
2194     }
2195 
2196     total += stat->total_size_by_type[i];
2197   }
2198 
2199 
2200   total += stat->total_size_humongous_chunks;
2201 
2202   if (scale == 1) {
2203     out->print_cr("  " SIZE_FORMAT " humongous chunks, total " SIZE_FORMAT " bytes",
2204     stat->num_humongous_chunks, stat->total_size_humongous_chunks);
2205 
2206     out->print_cr("  total size: " SIZE_FORMAT " bytes.", total);
2207   } else {
2208     out->print_cr("  " SIZE_FORMAT " humongous chunks, total %.2f%s",
2209     stat->num_humongous_chunks,
2210     (float)stat->total_size_humongous_chunks / scale, unit);
2211 
2212     out->print_cr("  total size: %.2f%s.", (float)total / scale, unit);
2213   }
2214 
2215 }
2216 
2217 void ChunkManager::print_all_chunkmanagers(outputStream* out, size_t scale) {
2218   assert(scale == 1 || scale == K || scale == M || scale == G, "Invalid scale");
2219 
2220   // Note: keep lock protection only to retrieving statistics; keep printing
2221   // out of lock protection
2222   ChunkManagerStatistics stat;
2223   out->print_cr("Chunkmanager (non-class):");
2224   const ChunkManager* const non_class_cm = Metaspace::chunk_manager_metadata();
2225   if (non_class_cm != NULL) {
2226     non_class_cm->get_statistics(&stat);
2227     ChunkManager::print_statistics(&stat, out, scale);
2228   } else {
2229     out->print_cr("unavailable.");
2230   }
2231   out->print_cr("Chunkmanager (class):");
2232   const ChunkManager* const class_cm = Metaspace::chunk_manager_class();
2233   if (class_cm != NULL) {
2234     class_cm->get_statistics(&stat);
2235     ChunkManager::print_statistics(&stat, out, scale);
2236   } else {
2237     out->print_cr("unavailable.");
2238   }
2239 }
2240 
2241 // SpaceManager methods
2242 
2243 size_t SpaceManager::adjust_initial_chunk_size(size_t requested, bool is_class_space) {
2244   size_t chunk_sizes[] = {
2245       specialized_chunk_size(is_class_space),
2246       small_chunk_size(is_class_space),
2247       medium_chunk_size(is_class_space)
2248   };
2249 
2250   // Adjust up to one of the fixed chunk sizes ...
2251   for (size_t i = 0; i < ARRAY_SIZE(chunk_sizes); i++) {
2252     if (requested <= chunk_sizes[i]) {
2253       return chunk_sizes[i];
2254     }
2255   }
2256 
2257   // ... or return the size as a humongous chunk.
2258   return requested;
2259 }
2260 
2261 size_t SpaceManager::adjust_initial_chunk_size(size_t requested) const {
2262   return adjust_initial_chunk_size(requested, is_class());
2263 }
2264 
2265 size_t SpaceManager::get_initial_chunk_size(Metaspace::MetaspaceType type) const {
2266   size_t requested;
2267 
2268   if (is_class()) {
2269     switch (type) {
2270     case Metaspace::BootMetaspaceType:       requested = Metaspace::first_class_chunk_word_size(); break;
2271     case Metaspace::AnonymousMetaspaceType:  requested = ClassSpecializedChunk; break;
2272     case Metaspace::ReflectionMetaspaceType: requested = ClassSpecializedChunk; break;
2273     default:                                 requested = ClassSmallChunk; break;
2274     }
2275   } else {
2276     switch (type) {
2277     case Metaspace::BootMetaspaceType:       requested = Metaspace::first_chunk_word_size(); break;
2278     case Metaspace::AnonymousMetaspaceType:  requested = SpecializedChunk; break;
2279     case Metaspace::ReflectionMetaspaceType: requested = SpecializedChunk; break;
2280     default:                                 requested = SmallChunk; break;
2281     }
2282   }
2283 
2284   // Adjust to one of the fixed chunk sizes (unless humongous)
2285   const size_t adjusted = adjust_initial_chunk_size(requested);
2286 
2287   assert(adjusted != 0, "Incorrect initial chunk size. Requested: "
2288          SIZE_FORMAT " adjusted: " SIZE_FORMAT, requested, adjusted);
2289 
2290   return adjusted;
2291 }
2292 
2293 size_t SpaceManager::sum_free_in_chunks_in_use() const {
2294   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
2295   size_t free = 0;
2296   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
2297     Metachunk* chunk = chunks_in_use(i);
2298     while (chunk != NULL) {
2299       free += chunk->free_word_size();
2300       chunk = chunk->next();
2301     }
2302   }
2303   return free;
2304 }
2305 
2306 size_t SpaceManager::sum_waste_in_chunks_in_use() const {
2307   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
2308   size_t result = 0;
2309   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
2310    result += sum_waste_in_chunks_in_use(i);
2311   }
2312 
2313   return result;
2314 }
2315 
2316 size_t SpaceManager::sum_waste_in_chunks_in_use(ChunkIndex index) const {
2317   size_t result = 0;
2318   Metachunk* chunk = chunks_in_use(index);
2319   // Count the free space in all the chunk but not the
2320   // current chunk from which allocations are still being done.
2321   while (chunk != NULL) {
2322     if (chunk != current_chunk()) {
2323       result += chunk->free_word_size();
2324     }
2325     chunk = chunk->next();
2326   }
2327   return result;
2328 }
2329 
2330 size_t SpaceManager::sum_capacity_in_chunks_in_use() const {
2331   // For CMS use "allocated_chunks_words()" which does not need the
2332   // Metaspace lock.  For the other collectors sum over the
2333   // lists.  Use both methods as a check that "allocated_chunks_words()"
2334   // is correct.  That is, sum_capacity_in_chunks() is too expensive
2335   // to use in the product and allocated_chunks_words() should be used
2336   // but allow for  checking that allocated_chunks_words() returns the same
2337   // value as sum_capacity_in_chunks_in_use() which is the definitive
2338   // answer.
2339   if (UseConcMarkSweepGC) {
2340     return allocated_chunks_words();
2341   } else {
2342     MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
2343     size_t sum = 0;
2344     for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
2345       Metachunk* chunk = chunks_in_use(i);
2346       while (chunk != NULL) {
2347         sum += chunk->word_size();
2348         chunk = chunk->next();
2349       }
2350     }
2351   return sum;
2352   }
2353 }
2354 
2355 size_t SpaceManager::sum_count_in_chunks_in_use() {
2356   size_t count = 0;
2357   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
2358     count = count + sum_count_in_chunks_in_use(i);
2359   }
2360 
2361   return count;
2362 }
2363 
2364 size_t SpaceManager::sum_count_in_chunks_in_use(ChunkIndex i) {
2365   size_t count = 0;
2366   Metachunk* chunk = chunks_in_use(i);
2367   while (chunk != NULL) {
2368     count++;
2369     chunk = chunk->next();
2370   }
2371   return count;
2372 }
2373 
2374 
2375 size_t SpaceManager::sum_used_in_chunks_in_use() const {
2376   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
2377   size_t used = 0;
2378   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
2379     Metachunk* chunk = chunks_in_use(i);
2380     while (chunk != NULL) {
2381       used += chunk->used_word_size();
2382       chunk = chunk->next();
2383     }
2384   }
2385   return used;
2386 }
2387 
2388 void SpaceManager::locked_print_chunks_in_use_on(outputStream* st) const {
2389 
2390   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
2391     Metachunk* chunk = chunks_in_use(i);
2392     st->print("SpaceManager: %s " PTR_FORMAT,
2393                  chunk_size_name(i), p2i(chunk));
2394     if (chunk != NULL) {
2395       st->print_cr(" free " SIZE_FORMAT,
2396                    chunk->free_word_size());
2397     } else {
2398       st->cr();
2399     }
2400   }
2401 
2402   chunk_manager()->locked_print_free_chunks(st);
2403   chunk_manager()->locked_print_sum_free_chunks(st);
2404 }
2405 
2406 size_t SpaceManager::calc_chunk_size(size_t word_size) {
2407 
2408   // Decide between a small chunk and a medium chunk.  Up to
2409   // _small_chunk_limit small chunks can be allocated.
2410   // After that a medium chunk is preferred.
2411   size_t chunk_word_size;
2412 
2413   // Special case for anonymous metadata space.
2414   // Anonymous metadata space is usually small, with majority within 1K - 2K range and
2415   // rarely about 4K (64-bits JVM).
2416   // Instead of jumping to SmallChunk after initial chunk exhausted, keeping allocation
2417   // from SpecializeChunk up to _anon_metadata_specialize_chunk_limit (4) reduces space waste
2418   // from 60+% to around 30%.
2419   if (_space_type == Metaspace::AnonymousMetaspaceType &&
2420       _mdtype == Metaspace::NonClassType &&
2421       sum_count_in_chunks_in_use(SpecializedIndex) < _anon_metadata_specialize_chunk_limit &&
2422       word_size + Metachunk::overhead() <= SpecializedChunk) {
2423     return SpecializedChunk;
2424   }
2425 
2426   if (chunks_in_use(MediumIndex) == NULL &&
2427       sum_count_in_chunks_in_use(SmallIndex) < _small_chunk_limit) {
2428     chunk_word_size = (size_t) small_chunk_size();
2429     if (word_size + Metachunk::overhead() > small_chunk_size()) {
2430       chunk_word_size = medium_chunk_size();
2431     }
2432   } else {
2433     chunk_word_size = medium_chunk_size();
2434   }
2435 
2436   // Might still need a humongous chunk.  Enforce
2437   // humongous allocations sizes to be aligned up to
2438   // the smallest chunk size.
2439   size_t if_humongous_sized_chunk =
2440     align_up(word_size + Metachunk::overhead(),
2441                   smallest_chunk_size());
2442   chunk_word_size =
2443     MAX2((size_t) chunk_word_size, if_humongous_sized_chunk);
2444 
2445   assert(!SpaceManager::is_humongous(word_size) ||
2446          chunk_word_size == if_humongous_sized_chunk,
2447          "Size calculation is wrong, word_size " SIZE_FORMAT
2448          " chunk_word_size " SIZE_FORMAT,
2449          word_size, chunk_word_size);
2450   Log(gc, metaspace, alloc) log;
2451   if (log.is_debug() && SpaceManager::is_humongous(word_size)) {
2452     log.debug("Metadata humongous allocation:");
2453     log.debug("  word_size " PTR_FORMAT, word_size);
2454     log.debug("  chunk_word_size " PTR_FORMAT, chunk_word_size);
2455     log.debug("    chunk overhead " PTR_FORMAT, Metachunk::overhead());
2456   }
2457   return chunk_word_size;
2458 }
2459 
2460 void SpaceManager::track_metaspace_memory_usage() {
2461   if (is_init_completed()) {
2462     if (is_class()) {
2463       MemoryService::track_compressed_class_memory_usage();
2464     }
2465     MemoryService::track_metaspace_memory_usage();
2466   }
2467 }
2468 
2469 MetaWord* SpaceManager::grow_and_allocate(size_t word_size) {
2470   assert(vs_list()->current_virtual_space() != NULL,
2471          "Should have been set");
2472   assert(current_chunk() == NULL ||
2473          current_chunk()->allocate(word_size) == NULL,
2474          "Don't need to expand");
2475   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
2476 
2477   if (log_is_enabled(Trace, gc, metaspace, freelist)) {
2478     size_t words_left = 0;
2479     size_t words_used = 0;
2480     if (current_chunk() != NULL) {
2481       words_left = current_chunk()->free_word_size();
2482       words_used = current_chunk()->used_word_size();
2483     }
2484     log_trace(gc, metaspace, freelist)("SpaceManager::grow_and_allocate for " SIZE_FORMAT " words " SIZE_FORMAT " words used " SIZE_FORMAT " words left",
2485                                        word_size, words_used, words_left);
2486   }
2487 
2488   // Get another chunk
2489   size_t chunk_word_size = calc_chunk_size(word_size);
2490   Metachunk* next = get_new_chunk(chunk_word_size);
2491 
2492   MetaWord* mem = NULL;
2493 
2494   // If a chunk was available, add it to the in-use chunk list
2495   // and do an allocation from it.
2496   if (next != NULL) {
2497     // Add to this manager's list of chunks in use.
2498     add_chunk(next, false);
2499     mem = next->allocate(word_size);
2500   }
2501 
2502   // Track metaspace memory usage statistic.
2503   track_metaspace_memory_usage();
2504 
2505   return mem;
2506 }
2507 
2508 void SpaceManager::print_on(outputStream* st) const {
2509 
2510   for (ChunkIndex i = ZeroIndex;
2511        i < NumberOfInUseLists ;
2512        i = next_chunk_index(i) ) {
2513     st->print_cr("  chunks_in_use " PTR_FORMAT " chunk size " SIZE_FORMAT,
2514                  p2i(chunks_in_use(i)),
2515                  chunks_in_use(i) == NULL ? 0 : chunks_in_use(i)->word_size());
2516   }
2517   st->print_cr("    waste:  Small " SIZE_FORMAT " Medium " SIZE_FORMAT
2518                " Humongous " SIZE_FORMAT,
2519                sum_waste_in_chunks_in_use(SmallIndex),
2520                sum_waste_in_chunks_in_use(MediumIndex),
2521                sum_waste_in_chunks_in_use(HumongousIndex));
2522   // block free lists
2523   if (block_freelists() != NULL) {
2524     st->print_cr("total in block free lists " SIZE_FORMAT,
2525       block_freelists()->total_size());
2526   }
2527 }
2528 
2529 SpaceManager::SpaceManager(Metaspace::MetadataType mdtype,
2530                            Metaspace::MetaspaceType space_type,
2531                            Mutex* lock) :
2532   _mdtype(mdtype),
2533   _space_type(space_type),
2534   _allocated_blocks_words(0),
2535   _allocated_chunks_words(0),
2536   _allocated_chunks_count(0),
2537   _block_freelists(NULL),
2538   _lock(lock)
2539 {
2540   initialize();
2541 }
2542 
2543 void SpaceManager::inc_size_metrics(size_t words) {
2544   assert_lock_strong(SpaceManager::expand_lock());
2545   // Total of allocated Metachunks and allocated Metachunks count
2546   // for each SpaceManager
2547   _allocated_chunks_words = _allocated_chunks_words + words;
2548   _allocated_chunks_count++;
2549   // Global total of capacity in allocated Metachunks
2550   MetaspaceAux::inc_capacity(mdtype(), words);
2551   // Global total of allocated Metablocks.
2552   // used_words_slow() includes the overhead in each
2553   // Metachunk so include it in the used when the
2554   // Metachunk is first added (so only added once per
2555   // Metachunk).
2556   MetaspaceAux::inc_used(mdtype(), Metachunk::overhead());
2557 }
2558 
2559 void SpaceManager::inc_used_metrics(size_t words) {
2560   // Add to the per SpaceManager total
2561   Atomic::add(words, &_allocated_blocks_words);
2562   // Add to the global total
2563   MetaspaceAux::inc_used(mdtype(), words);
2564 }
2565 
2566 void SpaceManager::dec_total_from_size_metrics() {
2567   MetaspaceAux::dec_capacity(mdtype(), allocated_chunks_words());
2568   MetaspaceAux::dec_used(mdtype(), allocated_blocks_words());
2569   // Also deduct the overhead per Metachunk
2570   MetaspaceAux::dec_used(mdtype(), allocated_chunks_count() * Metachunk::overhead());
2571 }
2572 
2573 void SpaceManager::initialize() {
2574   Metadebug::init_allocation_fail_alot_count();
2575   for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
2576     _chunks_in_use[i] = NULL;
2577   }
2578   _current_chunk = NULL;
2579   log_trace(gc, metaspace, freelist)("SpaceManager(): " PTR_FORMAT, p2i(this));
2580 }
2581 
2582 SpaceManager::~SpaceManager() {
2583   // This call this->_lock which can't be done while holding expand_lock()
2584   assert(sum_capacity_in_chunks_in_use() == allocated_chunks_words(),
2585          "sum_capacity_in_chunks_in_use() " SIZE_FORMAT
2586          " allocated_chunks_words() " SIZE_FORMAT,
2587          sum_capacity_in_chunks_in_use(), allocated_chunks_words());
2588 
2589   MutexLockerEx fcl(SpaceManager::expand_lock(),
2590                     Mutex::_no_safepoint_check_flag);
2591 
2592   chunk_manager()->slow_locked_verify();
2593 
2594   dec_total_from_size_metrics();
2595 
2596   Log(gc, metaspace, freelist) log;
2597   if (log.is_trace()) {
2598     log.trace("~SpaceManager(): " PTR_FORMAT, p2i(this));
2599     ResourceMark rm;
2600     LogStream ls(log.trace());
2601     locked_print_chunks_in_use_on(&ls);
2602     if (block_freelists() != NULL) {
2603       block_freelists()->print_on(&ls);
2604     }
2605   }
2606 
2607   // Add all the chunks in use by this space manager
2608   // to the global list of free chunks.
2609 
2610   // Follow each list of chunks-in-use and add them to the
2611   // free lists.  Each list is NULL terminated.
2612 
2613   for (ChunkIndex i = ZeroIndex; i <= HumongousIndex; i = next_chunk_index(i)) {
2614     Metachunk* chunks = chunks_in_use(i);
2615     chunk_manager()->return_chunk_list(i, chunks);
2616     set_chunks_in_use(i, NULL);
2617   }
2618 
2619   chunk_manager()->slow_locked_verify();
2620 
2621   if (_block_freelists != NULL) {
2622     delete _block_freelists;
2623   }
2624 }
2625 
2626 void SpaceManager::deallocate(MetaWord* p, size_t word_size) {
2627   assert_lock_strong(_lock);
2628   // Allocations and deallocations are in raw_word_size
2629   size_t raw_word_size = get_allocation_word_size(word_size);
2630   // Lazily create a block_freelist
2631   if (block_freelists() == NULL) {
2632     _block_freelists = new BlockFreelist();
2633   }
2634   block_freelists()->return_block(p, raw_word_size);
2635 }
2636 
2637 // Adds a chunk to the list of chunks in use.
2638 void SpaceManager::add_chunk(Metachunk* new_chunk, bool make_current) {
2639 
2640   assert(new_chunk != NULL, "Should not be NULL");
2641   assert(new_chunk->next() == NULL, "Should not be on a list");
2642 
2643   new_chunk->reset_empty();
2644 
2645   // Find the correct list and and set the current
2646   // chunk for that list.
2647   ChunkIndex index = chunk_manager()->list_index(new_chunk->word_size());
2648 
2649   if (index != HumongousIndex) {
2650     retire_current_chunk();
2651     set_current_chunk(new_chunk);
2652     new_chunk->set_next(chunks_in_use(index));
2653     set_chunks_in_use(index, new_chunk);
2654   } else {
2655     // For null class loader data and DumpSharedSpaces, the first chunk isn't
2656     // small, so small will be null.  Link this first chunk as the current
2657     // chunk.
2658     if (make_current) {
2659       // Set as the current chunk but otherwise treat as a humongous chunk.
2660       set_current_chunk(new_chunk);
2661     }
2662     // Link at head.  The _current_chunk only points to a humongous chunk for
2663     // the null class loader metaspace (class and data virtual space managers)
2664     // any humongous chunks so will not point to the tail
2665     // of the humongous chunks list.
2666     new_chunk->set_next(chunks_in_use(HumongousIndex));
2667     set_chunks_in_use(HumongousIndex, new_chunk);
2668 
2669     assert(new_chunk->word_size() > medium_chunk_size(), "List inconsistency");
2670   }
2671 
2672   // Add to the running sum of capacity
2673   inc_size_metrics(new_chunk->word_size());
2674 
2675   assert(new_chunk->is_empty(), "Not ready for reuse");
2676   Log(gc, metaspace, freelist) log;
2677   if (log.is_trace()) {
2678     log.trace("SpaceManager::add_chunk: " SIZE_FORMAT ") ", sum_count_in_chunks_in_use());
2679     ResourceMark rm;
2680     LogStream ls(log.trace());
2681     new_chunk->print_on(&ls);
2682     chunk_manager()->locked_print_free_chunks(&ls);
2683   }
2684 }
2685 
2686 void SpaceManager::retire_current_chunk() {
2687   if (current_chunk() != NULL) {
2688     size_t remaining_words = current_chunk()->free_word_size();
2689     if (remaining_words >= BlockFreelist::min_dictionary_size()) {
2690       MetaWord* ptr = current_chunk()->allocate(remaining_words);
2691       deallocate(ptr, remaining_words);
2692       inc_used_metrics(remaining_words);
2693     }
2694   }
2695 }
2696 
2697 Metachunk* SpaceManager::get_new_chunk(size_t chunk_word_size) {
2698   // Get a chunk from the chunk freelist
2699   Metachunk* next = chunk_manager()->chunk_freelist_allocate(chunk_word_size);
2700 
2701   if (next == NULL) {
2702     next = vs_list()->get_new_chunk(chunk_word_size,
2703                                     medium_chunk_bunch());
2704   }
2705 
2706   Log(gc, metaspace, alloc) log;
2707   if (log.is_debug() && next != NULL &&
2708       SpaceManager::is_humongous(next->word_size())) {
2709     log.debug("  new humongous chunk word size " PTR_FORMAT, next->word_size());
2710   }
2711 
2712   return next;
2713 }
2714 
2715 /*
2716  * The policy is to allocate up to _small_chunk_limit small chunks
2717  * after which only medium chunks are allocated.  This is done to
2718  * reduce fragmentation.  In some cases, this can result in a lot
2719  * of small chunks being allocated to the point where it's not
2720  * possible to expand.  If this happens, there may be no medium chunks
2721  * available and OOME would be thrown.  Instead of doing that,
2722  * if the allocation request size fits in a small chunk, an attempt
2723  * will be made to allocate a small chunk.
2724  */
2725 MetaWord* SpaceManager::get_small_chunk_and_allocate(size_t word_size) {
2726   size_t raw_word_size = get_allocation_word_size(word_size);
2727 
2728   if (raw_word_size + Metachunk::overhead() > small_chunk_size()) {
2729     return NULL;
2730   }
2731 
2732   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
2733   MutexLockerEx cl1(expand_lock(), Mutex::_no_safepoint_check_flag);
2734 
2735   Metachunk* chunk = chunk_manager()->chunk_freelist_allocate(small_chunk_size());
2736 
2737   MetaWord* mem = NULL;
2738 
2739   if (chunk != NULL) {
2740     // Add chunk to the in-use chunk list and do an allocation from it.
2741     // Add to this manager's list of chunks in use.
2742     add_chunk(chunk, false);
2743     mem = chunk->allocate(raw_word_size);
2744 
2745     inc_used_metrics(raw_word_size);
2746 
2747     // Track metaspace memory usage statistic.
2748     track_metaspace_memory_usage();
2749   }
2750 
2751   return mem;
2752 }
2753 
2754 MetaWord* SpaceManager::allocate(size_t word_size) {
2755   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
2756   size_t raw_word_size = get_allocation_word_size(word_size);
2757   BlockFreelist* fl =  block_freelists();
2758   MetaWord* p = NULL;
2759   // Allocation from the dictionary is expensive in the sense that
2760   // the dictionary has to be searched for a size.  Don't allocate
2761   // from the dictionary until it starts to get fat.  Is this
2762   // a reasonable policy?  Maybe an skinny dictionary is fast enough
2763   // for allocations.  Do some profiling.  JJJ
2764   if (fl != NULL && fl->total_size() > allocation_from_dictionary_limit) {
2765     p = fl->get_block(raw_word_size);
2766   }
2767   if (p == NULL) {
2768     p = allocate_work(raw_word_size);
2769   }
2770 
2771   return p;
2772 }
2773 
2774 // Returns the address of spaced allocated for "word_size".
2775 // This methods does not know about blocks (Metablocks)
2776 MetaWord* SpaceManager::allocate_work(size_t word_size) {
2777   assert_lock_strong(_lock);
2778 #ifdef ASSERT
2779   if (Metadebug::test_metadata_failure()) {
2780     return NULL;
2781   }
2782 #endif
2783   // Is there space in the current chunk?
2784   MetaWord* result = NULL;
2785 
2786   if (current_chunk() != NULL) {
2787     result = current_chunk()->allocate(word_size);
2788   }
2789 
2790   if (result == NULL) {
2791     result = grow_and_allocate(word_size);
2792   }
2793 
2794   if (result != NULL) {
2795     inc_used_metrics(word_size);
2796     assert(result != (MetaWord*) chunks_in_use(MediumIndex),
2797            "Head of the list is being allocated");
2798   }
2799 
2800   return result;
2801 }
2802 
2803 void SpaceManager::verify() {
2804   // If there are blocks in the dictionary, then
2805   // verification of chunks does not work since
2806   // being in the dictionary alters a chunk.
2807   if (block_freelists() != NULL && block_freelists()->total_size() == 0) {
2808     for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
2809       Metachunk* curr = chunks_in_use(i);
2810       while (curr != NULL) {
2811         curr->verify();
2812         verify_chunk_size(curr);
2813         curr = curr->next();
2814       }
2815     }
2816   }
2817 }
2818 
2819 void SpaceManager::verify_chunk_size(Metachunk* chunk) {
2820   assert(is_humongous(chunk->word_size()) ||
2821          chunk->word_size() == medium_chunk_size() ||
2822          chunk->word_size() == small_chunk_size() ||
2823          chunk->word_size() == specialized_chunk_size(),
2824          "Chunk size is wrong");
2825   return;
2826 }
2827 
2828 #ifdef ASSERT
2829 void SpaceManager::verify_allocated_blocks_words() {
2830   // Verification is only guaranteed at a safepoint.
2831   assert(SafepointSynchronize::is_at_safepoint() || !Universe::is_fully_initialized(),
2832     "Verification can fail if the applications is running");
2833   assert(allocated_blocks_words() == sum_used_in_chunks_in_use(),
2834          "allocation total is not consistent " SIZE_FORMAT
2835          " vs " SIZE_FORMAT,
2836          allocated_blocks_words(), sum_used_in_chunks_in_use());
2837 }
2838 
2839 #endif
2840 
2841 void SpaceManager::dump(outputStream* const out) const {
2842   size_t curr_total = 0;
2843   size_t waste = 0;
2844   uint i = 0;
2845   size_t used = 0;
2846   size_t capacity = 0;
2847 
2848   // Add up statistics for all chunks in this SpaceManager.
2849   for (ChunkIndex index = ZeroIndex;
2850        index < NumberOfInUseLists;
2851        index = next_chunk_index(index)) {
2852     for (Metachunk* curr = chunks_in_use(index);
2853          curr != NULL;
2854          curr = curr->next()) {
2855       out->print("%d) ", i++);
2856       curr->print_on(out);
2857       curr_total += curr->word_size();
2858       used += curr->used_word_size();
2859       capacity += curr->word_size();
2860       waste += curr->free_word_size() + curr->overhead();;
2861     }
2862   }
2863 
2864   if (log_is_enabled(Trace, gc, metaspace, freelist)) {
2865     if (block_freelists() != NULL) block_freelists()->print_on(out);
2866   }
2867 
2868   size_t free = current_chunk() == NULL ? 0 : current_chunk()->free_word_size();
2869   // Free space isn't wasted.
2870   waste -= free;
2871 
2872   out->print_cr("total of all chunks "  SIZE_FORMAT " used " SIZE_FORMAT
2873                 " free " SIZE_FORMAT " capacity " SIZE_FORMAT
2874                 " waste " SIZE_FORMAT, curr_total, used, free, capacity, waste);
2875 }
2876 
2877 // MetaspaceAux
2878 
2879 
2880 size_t MetaspaceAux::_capacity_words[] = {0, 0};
2881 volatile size_t MetaspaceAux::_used_words[] = {0, 0};
2882 
2883 size_t MetaspaceAux::free_bytes(Metaspace::MetadataType mdtype) {
2884   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
2885   return list == NULL ? 0 : list->free_bytes();
2886 }
2887 
2888 size_t MetaspaceAux::free_bytes() {
2889   return free_bytes(Metaspace::ClassType) + free_bytes(Metaspace::NonClassType);
2890 }
2891 
2892 void MetaspaceAux::dec_capacity(Metaspace::MetadataType mdtype, size_t words) {
2893   assert_lock_strong(SpaceManager::expand_lock());
2894   assert(words <= capacity_words(mdtype),
2895          "About to decrement below 0: words " SIZE_FORMAT
2896          " is greater than _capacity_words[%u] " SIZE_FORMAT,
2897          words, mdtype, capacity_words(mdtype));
2898   _capacity_words[mdtype] -= words;
2899 }
2900 
2901 void MetaspaceAux::inc_capacity(Metaspace::MetadataType mdtype, size_t words) {
2902   assert_lock_strong(SpaceManager::expand_lock());
2903   // Needs to be atomic
2904   _capacity_words[mdtype] += words;
2905 }
2906 
2907 void MetaspaceAux::dec_used(Metaspace::MetadataType mdtype, size_t words) {
2908   assert(words <= used_words(mdtype),
2909          "About to decrement below 0: words " SIZE_FORMAT
2910          " is greater than _used_words[%u] " SIZE_FORMAT,
2911          words, mdtype, used_words(mdtype));
2912   // For CMS deallocation of the Metaspaces occurs during the
2913   // sweep which is a concurrent phase.  Protection by the expand_lock()
2914   // is not enough since allocation is on a per Metaspace basis
2915   // and protected by the Metaspace lock.
2916   Atomic::sub(words, &_used_words[mdtype]);
2917 }
2918 
2919 void MetaspaceAux::inc_used(Metaspace::MetadataType mdtype, size_t words) {
2920   // _used_words tracks allocations for
2921   // each piece of metadata.  Those allocations are
2922   // generally done concurrently by different application
2923   // threads so must be done atomically.
2924   Atomic::add(words, &_used_words[mdtype]);
2925 }
2926 
2927 size_t MetaspaceAux::used_bytes_slow(Metaspace::MetadataType mdtype) {
2928   size_t used = 0;
2929   ClassLoaderDataGraphMetaspaceIterator iter;
2930   while (iter.repeat()) {
2931     Metaspace* msp = iter.get_next();
2932     // Sum allocated_blocks_words for each metaspace
2933     if (msp != NULL) {
2934       used += msp->used_words_slow(mdtype);
2935     }
2936   }
2937   return used * BytesPerWord;
2938 }
2939 
2940 size_t MetaspaceAux::free_bytes_slow(Metaspace::MetadataType mdtype) {
2941   size_t free = 0;
2942   ClassLoaderDataGraphMetaspaceIterator iter;
2943   while (iter.repeat()) {
2944     Metaspace* msp = iter.get_next();
2945     if (msp != NULL) {
2946       free += msp->free_words_slow(mdtype);
2947     }
2948   }
2949   return free * BytesPerWord;
2950 }
2951 
2952 size_t MetaspaceAux::capacity_bytes_slow(Metaspace::MetadataType mdtype) {
2953   if ((mdtype == Metaspace::ClassType) && !Metaspace::using_class_space()) {
2954     return 0;
2955   }
2956   // Don't count the space in the freelists.  That space will be
2957   // added to the capacity calculation as needed.
2958   size_t capacity = 0;
2959   ClassLoaderDataGraphMetaspaceIterator iter;
2960   while (iter.repeat()) {
2961     Metaspace* msp = iter.get_next();
2962     if (msp != NULL) {
2963       capacity += msp->capacity_words_slow(mdtype);
2964     }
2965   }
2966   return capacity * BytesPerWord;
2967 }
2968 
2969 size_t MetaspaceAux::capacity_bytes_slow() {
2970 #ifdef PRODUCT
2971   // Use capacity_bytes() in PRODUCT instead of this function.
2972   guarantee(false, "Should not call capacity_bytes_slow() in the PRODUCT");
2973 #endif
2974   size_t class_capacity = capacity_bytes_slow(Metaspace::ClassType);
2975   size_t non_class_capacity = capacity_bytes_slow(Metaspace::NonClassType);
2976   assert(capacity_bytes() == class_capacity + non_class_capacity,
2977          "bad accounting: capacity_bytes() " SIZE_FORMAT
2978          " class_capacity + non_class_capacity " SIZE_FORMAT
2979          " class_capacity " SIZE_FORMAT " non_class_capacity " SIZE_FORMAT,
2980          capacity_bytes(), class_capacity + non_class_capacity,
2981          class_capacity, non_class_capacity);
2982 
2983   return class_capacity + non_class_capacity;
2984 }
2985 
2986 size_t MetaspaceAux::reserved_bytes(Metaspace::MetadataType mdtype) {
2987   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
2988   return list == NULL ? 0 : list->reserved_bytes();
2989 }
2990 
2991 size_t MetaspaceAux::committed_bytes(Metaspace::MetadataType mdtype) {
2992   VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
2993   return list == NULL ? 0 : list->committed_bytes();
2994 }
2995 
2996 size_t MetaspaceAux::min_chunk_size_words() { return Metaspace::first_chunk_word_size(); }
2997 
2998 size_t MetaspaceAux::free_chunks_total_words(Metaspace::MetadataType mdtype) {
2999   ChunkManager* chunk_manager = Metaspace::get_chunk_manager(mdtype);
3000   if (chunk_manager == NULL) {
3001     return 0;
3002   }
3003   chunk_manager->slow_verify();
3004   return chunk_manager->free_chunks_total_words();
3005 }
3006 
3007 size_t MetaspaceAux::free_chunks_total_bytes(Metaspace::MetadataType mdtype) {
3008   return free_chunks_total_words(mdtype) * BytesPerWord;
3009 }
3010 
3011 size_t MetaspaceAux::free_chunks_total_words() {
3012   return free_chunks_total_words(Metaspace::ClassType) +
3013          free_chunks_total_words(Metaspace::NonClassType);
3014 }
3015 
3016 size_t MetaspaceAux::free_chunks_total_bytes() {
3017   return free_chunks_total_words() * BytesPerWord;
3018 }
3019 
3020 bool MetaspaceAux::has_chunk_free_list(Metaspace::MetadataType mdtype) {
3021   return Metaspace::get_chunk_manager(mdtype) != NULL;
3022 }
3023 
3024 MetaspaceChunkFreeListSummary MetaspaceAux::chunk_free_list_summary(Metaspace::MetadataType mdtype) {
3025   if (!has_chunk_free_list(mdtype)) {
3026     return MetaspaceChunkFreeListSummary();
3027   }
3028 
3029   const ChunkManager* cm = Metaspace::get_chunk_manager(mdtype);
3030   return cm->chunk_free_list_summary();
3031 }
3032 
3033 void MetaspaceAux::print_metaspace_change(size_t prev_metadata_used) {
3034   log_info(gc, metaspace)("Metaspace: "  SIZE_FORMAT "K->" SIZE_FORMAT "K("  SIZE_FORMAT "K)",
3035                           prev_metadata_used/K, used_bytes()/K, reserved_bytes()/K);
3036 }
3037 
3038 void MetaspaceAux::print_on(outputStream* out) {
3039   Metaspace::MetadataType nct = Metaspace::NonClassType;
3040 
3041   out->print_cr(" Metaspace       "
3042                 "used "      SIZE_FORMAT "K, "
3043                 "capacity "  SIZE_FORMAT "K, "
3044                 "committed " SIZE_FORMAT "K, "
3045                 "reserved "  SIZE_FORMAT "K",
3046                 used_bytes()/K,
3047                 capacity_bytes()/K,
3048                 committed_bytes()/K,
3049                 reserved_bytes()/K);
3050 
3051   if (Metaspace::using_class_space()) {
3052     Metaspace::MetadataType ct = Metaspace::ClassType;
3053     out->print_cr("  class space    "
3054                   "used "      SIZE_FORMAT "K, "
3055                   "capacity "  SIZE_FORMAT "K, "
3056                   "committed " SIZE_FORMAT "K, "
3057                   "reserved "  SIZE_FORMAT "K",
3058                   used_bytes(ct)/K,
3059                   capacity_bytes(ct)/K,
3060                   committed_bytes(ct)/K,
3061                   reserved_bytes(ct)/K);
3062   }
3063 }
3064 
3065 // Print information for class space and data space separately.
3066 // This is almost the same as above.
3067 void MetaspaceAux::print_on(outputStream* out, Metaspace::MetadataType mdtype) {
3068   size_t free_chunks_capacity_bytes = free_chunks_total_bytes(mdtype);
3069   size_t capacity_bytes = capacity_bytes_slow(mdtype);
3070   size_t used_bytes = used_bytes_slow(mdtype);
3071   size_t free_bytes = free_bytes_slow(mdtype);
3072   size_t used_and_free = used_bytes + free_bytes +
3073                            free_chunks_capacity_bytes;
3074   out->print_cr("  Chunk accounting: (used in chunks " SIZE_FORMAT
3075              "K + unused in chunks " SIZE_FORMAT "K  + "
3076              " capacity in free chunks " SIZE_FORMAT "K) = " SIZE_FORMAT
3077              "K  capacity in allocated chunks " SIZE_FORMAT "K",
3078              used_bytes / K,
3079              free_bytes / K,
3080              free_chunks_capacity_bytes / K,
3081              used_and_free / K,
3082              capacity_bytes / K);
3083   // Accounting can only be correct if we got the values during a safepoint
3084   assert(!SafepointSynchronize::is_at_safepoint() || used_and_free == capacity_bytes, "Accounting is wrong");
3085 }
3086 
3087 // Print total fragmentation for class metaspaces
3088 void MetaspaceAux::print_class_waste(outputStream* out) {
3089   assert(Metaspace::using_class_space(), "class metaspace not used");
3090   size_t cls_specialized_waste = 0, cls_small_waste = 0, cls_medium_waste = 0;
3091   size_t cls_specialized_count = 0, cls_small_count = 0, cls_medium_count = 0, cls_humongous_count = 0;
3092   ClassLoaderDataGraphMetaspaceIterator iter;
3093   while (iter.repeat()) {
3094     Metaspace* msp = iter.get_next();
3095     if (msp != NULL) {
3096       cls_specialized_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
3097       cls_specialized_count += msp->class_vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
3098       cls_small_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SmallIndex);
3099       cls_small_count += msp->class_vsm()->sum_count_in_chunks_in_use(SmallIndex);
3100       cls_medium_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(MediumIndex);
3101       cls_medium_count += msp->class_vsm()->sum_count_in_chunks_in_use(MediumIndex);
3102       cls_humongous_count += msp->class_vsm()->sum_count_in_chunks_in_use(HumongousIndex);
3103     }
3104   }
3105   out->print_cr(" class: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
3106                 SIZE_FORMAT " small(s) " SIZE_FORMAT ", "
3107                 SIZE_FORMAT " medium(s) " SIZE_FORMAT ", "
3108                 "large count " SIZE_FORMAT,
3109                 cls_specialized_count, cls_specialized_waste,
3110                 cls_small_count, cls_small_waste,
3111                 cls_medium_count, cls_medium_waste, cls_humongous_count);
3112 }
3113 
3114 // Print total fragmentation for data and class metaspaces separately
3115 void MetaspaceAux::print_waste(outputStream* out) {
3116   size_t specialized_waste = 0, small_waste = 0, medium_waste = 0;
3117   size_t specialized_count = 0, small_count = 0, medium_count = 0, humongous_count = 0;
3118 
3119   ClassLoaderDataGraphMetaspaceIterator iter;
3120   while (iter.repeat()) {
3121     Metaspace* msp = iter.get_next();
3122     if (msp != NULL) {
3123       specialized_waste += msp->vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
3124       specialized_count += msp->vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
3125       small_waste += msp->vsm()->sum_waste_in_chunks_in_use(SmallIndex);
3126       small_count += msp->vsm()->sum_count_in_chunks_in_use(SmallIndex);
3127       medium_waste += msp->vsm()->sum_waste_in_chunks_in_use(MediumIndex);
3128       medium_count += msp->vsm()->sum_count_in_chunks_in_use(MediumIndex);
3129       humongous_count += msp->vsm()->sum_count_in_chunks_in_use(HumongousIndex);
3130     }
3131   }
3132   out->print_cr("Total fragmentation waste (words) doesn't count free space");
3133   out->print_cr("  data: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
3134                         SIZE_FORMAT " small(s) " SIZE_FORMAT ", "
3135                         SIZE_FORMAT " medium(s) " SIZE_FORMAT ", "
3136                         "large count " SIZE_FORMAT,
3137              specialized_count, specialized_waste, small_count,
3138              small_waste, medium_count, medium_waste, humongous_count);
3139   if (Metaspace::using_class_space()) {
3140     print_class_waste(out);
3141   }
3142 }
3143 
3144 class MetadataStats VALUE_OBJ_CLASS_SPEC {
3145 private:
3146   size_t _capacity;
3147   size_t _used;
3148   size_t _free;
3149   size_t _waste;
3150 
3151 public:
3152   MetadataStats() : _capacity(0), _used(0), _free(0), _waste(0) { }
3153   MetadataStats(size_t capacity, size_t used, size_t free, size_t waste)
3154   : _capacity(capacity), _used(used), _free(free), _waste(waste) { }
3155 
3156   void add(const MetadataStats& stats) {
3157     _capacity += stats.capacity();
3158     _used += stats.used();
3159     _free += stats.free();
3160     _waste += stats.waste();
3161   }
3162 
3163   size_t capacity() const { return _capacity; }
3164   size_t used() const     { return _used; }
3165   size_t free() const     { return _free; }
3166   size_t waste() const    { return _waste; }
3167 
3168   void print_on(outputStream* out, size_t scale) const;
3169 };
3170 
3171 
3172 void MetadataStats::print_on(outputStream* out, size_t scale) const {
3173   const char* unit = scale_unit(scale);
3174   out->print_cr("capacity=%10.2f%s used=%10.2f%s free=%10.2f%s waste=%10.2f%s",
3175     (float)capacity() / scale, unit,
3176     (float)used() / scale, unit,
3177     (float)free() / scale, unit,
3178     (float)waste() / scale, unit);
3179 }
3180 
3181 class PrintCLDMetaspaceInfoClosure : public CLDClosure {
3182 private:
3183   outputStream*  _out;
3184   size_t         _scale;
3185 
3186   size_t         _total_count;
3187   MetadataStats  _total_metadata;
3188   MetadataStats  _total_class;
3189 
3190   size_t         _total_anon_count;
3191   MetadataStats  _total_anon_metadata;
3192   MetadataStats  _total_anon_class;
3193 
3194 public:
3195   PrintCLDMetaspaceInfoClosure(outputStream* out, size_t scale = K)
3196   : _out(out), _scale(scale), _total_count(0), _total_anon_count(0) { }
3197 
3198   ~PrintCLDMetaspaceInfoClosure() {
3199     print_summary();
3200   }
3201 
3202   void do_cld(ClassLoaderData* cld) {
3203     assert(SafepointSynchronize::is_at_safepoint(), "Must be at a safepoint");
3204 
3205     if (cld->is_unloading()) return;
3206     Metaspace* msp = cld->metaspace_or_null();
3207     if (msp == NULL) {
3208       return;
3209     }
3210 
3211     bool anonymous = false;
3212     if (cld->is_anonymous()) {
3213       _out->print_cr("ClassLoader: for anonymous class");
3214       anonymous = true;
3215     } else {
3216       ResourceMark rm;
3217       _out->print_cr("ClassLoader: %s", cld->loader_name());
3218     }
3219 
3220     print_metaspace(msp, anonymous);
3221     _out->cr();
3222   }
3223 
3224 private:
3225   void print_metaspace(Metaspace* msp, bool anonymous);
3226   void print_summary() const;
3227 };
3228 
3229 void PrintCLDMetaspaceInfoClosure::print_metaspace(Metaspace* msp, bool anonymous){
3230   assert(msp != NULL, "Sanity");
3231   SpaceManager* vsm = msp->vsm();
3232   const char* unit = scale_unit(_scale);
3233 
3234   size_t capacity = vsm->sum_capacity_in_chunks_in_use() * BytesPerWord;
3235   size_t used = vsm->sum_used_in_chunks_in_use() * BytesPerWord;
3236   size_t free = vsm->sum_free_in_chunks_in_use() * BytesPerWord;
3237   size_t waste = vsm->sum_waste_in_chunks_in_use() * BytesPerWord;
3238 
3239   _total_count ++;
3240   MetadataStats metadata_stats(capacity, used, free, waste);
3241   _total_metadata.add(metadata_stats);
3242 
3243   if (anonymous) {
3244     _total_anon_count ++;
3245     _total_anon_metadata.add(metadata_stats);
3246   }
3247 
3248   _out->print("  Metadata   ");
3249   metadata_stats.print_on(_out, _scale);
3250 
3251   if (Metaspace::using_class_space()) {
3252     vsm = msp->class_vsm();
3253 
3254     capacity = vsm->sum_capacity_in_chunks_in_use() * BytesPerWord;
3255     used = vsm->sum_used_in_chunks_in_use() * BytesPerWord;
3256     free = vsm->sum_free_in_chunks_in_use() * BytesPerWord;
3257     waste = vsm->sum_waste_in_chunks_in_use() * BytesPerWord;
3258 
3259     MetadataStats class_stats(capacity, used, free, waste);
3260     _total_class.add(class_stats);
3261 
3262     if (anonymous) {
3263       _total_anon_class.add(class_stats);
3264     }
3265 
3266     _out->print("  Class data ");
3267     class_stats.print_on(_out, _scale);
3268   }
3269 }
3270 
3271 void PrintCLDMetaspaceInfoClosure::print_summary() const {
3272   const char* unit = scale_unit(_scale);
3273   _out->cr();
3274   _out->print_cr("Summary:");
3275 
3276   MetadataStats total;
3277   total.add(_total_metadata);
3278   total.add(_total_class);
3279 
3280   _out->print("  Total class loaders=" SIZE_FORMAT_W(6) " ", _total_count);
3281   total.print_on(_out, _scale);
3282 
3283   _out->print("                    Metadata ");
3284   _total_metadata.print_on(_out, _scale);
3285 
3286   if (Metaspace::using_class_space()) {
3287     _out->print("                  Class data ");
3288     _total_class.print_on(_out, _scale);
3289   }
3290   _out->cr();
3291 
3292   MetadataStats total_anon;
3293   total_anon.add(_total_anon_metadata);
3294   total_anon.add(_total_anon_class);
3295 
3296   _out->print("For anonymous classes=" SIZE_FORMAT_W(6) " ", _total_anon_count);
3297   total_anon.print_on(_out, _scale);
3298 
3299   _out->print("                    Metadata ");
3300   _total_anon_metadata.print_on(_out, _scale);
3301 
3302   if (Metaspace::using_class_space()) {
3303     _out->print("                  Class data ");
3304     _total_anon_class.print_on(_out, _scale);
3305   }
3306 }
3307 
3308 void MetaspaceAux::print_metadata_for_nmt(outputStream* out, size_t scale) {
3309   const char* unit = scale_unit(scale);
3310   out->print_cr("Metaspaces:");
3311   out->print_cr("  Metadata space: reserved=" SIZE_FORMAT_W(10) "%s committed=" SIZE_FORMAT_W(10) "%s",
3312     reserved_bytes(Metaspace::NonClassType) / scale, unit,
3313     committed_bytes(Metaspace::NonClassType) / scale, unit);
3314   if (Metaspace::using_class_space()) {
3315     out->print_cr("  Class    space: reserved=" SIZE_FORMAT_W(10) "%s committed=" SIZE_FORMAT_W(10) "%s",
3316     reserved_bytes(Metaspace::ClassType) / scale, unit,
3317     committed_bytes(Metaspace::ClassType) / scale, unit);
3318   }
3319 
3320   out->cr();
3321   ChunkManager::print_all_chunkmanagers(out, scale);
3322 
3323   out->cr();
3324   out->print_cr("Per-classloader metadata:");
3325   out->cr();
3326 
3327   PrintCLDMetaspaceInfoClosure cl(out, scale);
3328   ClassLoaderDataGraph::cld_do(&cl);
3329 }
3330 
3331 
3332 // Dump global metaspace things from the end of ClassLoaderDataGraph
3333 void MetaspaceAux::dump(outputStream* out) {
3334   out->print_cr("All Metaspace:");
3335   out->print("data space: "); print_on(out, Metaspace::NonClassType);
3336   out->print("class space: "); print_on(out, Metaspace::ClassType);
3337   print_waste(out);
3338 }
3339 
3340 // Prints an ASCII representation of the given space.
3341 void MetaspaceAux::print_metaspace_map(outputStream* out, Metaspace::MetadataType mdtype) {
3342   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
3343   const bool for_class = mdtype == Metaspace::ClassType ? true : false;
3344   VirtualSpaceList* const vsl = for_class ? Metaspace::class_space_list() : Metaspace::space_list();
3345   if (vsl != NULL) {
3346     if (for_class) {
3347       if (!Metaspace::using_class_space()) {
3348         out->print_cr("No Class Space.");
3349         return;
3350       }
3351       out->print_raw("---- Metaspace Map (Class Space) ----");
3352     } else {
3353       out->print_raw("---- Metaspace Map (Non-Class Space) ----");
3354     }
3355     // Print legend:
3356     out->cr();
3357     out->print_cr("Chunk Types (uppercase chunks are in use): x-specialized, s-small, m-medium, h-humongous.");
3358     out->cr();
3359     VirtualSpaceList* const vsl = for_class ? Metaspace::class_space_list() : Metaspace::space_list();
3360     vsl->print_map(out);
3361     out->cr();
3362   }
3363 }
3364 
3365 void MetaspaceAux::verify_free_chunks() {
3366   Metaspace::chunk_manager_metadata()->verify();
3367   if (Metaspace::using_class_space()) {
3368     Metaspace::chunk_manager_class()->verify();
3369   }
3370 }
3371 
3372 void MetaspaceAux::verify_capacity() {
3373 #ifdef ASSERT
3374   size_t running_sum_capacity_bytes = capacity_bytes();
3375   // For purposes of the running sum of capacity, verify against capacity
3376   size_t capacity_in_use_bytes = capacity_bytes_slow();
3377   assert(running_sum_capacity_bytes == capacity_in_use_bytes,
3378          "capacity_words() * BytesPerWord " SIZE_FORMAT
3379          " capacity_bytes_slow()" SIZE_FORMAT,
3380          running_sum_capacity_bytes, capacity_in_use_bytes);
3381   for (Metaspace::MetadataType i = Metaspace::ClassType;
3382        i < Metaspace:: MetadataTypeCount;
3383        i = (Metaspace::MetadataType)(i + 1)) {
3384     size_t capacity_in_use_bytes = capacity_bytes_slow(i);
3385     assert(capacity_bytes(i) == capacity_in_use_bytes,
3386            "capacity_bytes(%u) " SIZE_FORMAT
3387            " capacity_bytes_slow(%u)" SIZE_FORMAT,
3388            i, capacity_bytes(i), i, capacity_in_use_bytes);
3389   }
3390 #endif
3391 }
3392 
3393 void MetaspaceAux::verify_used() {
3394 #ifdef ASSERT
3395   size_t running_sum_used_bytes = used_bytes();
3396   // For purposes of the running sum of used, verify against used
3397   size_t used_in_use_bytes = used_bytes_slow();
3398   assert(used_bytes() == used_in_use_bytes,
3399          "used_bytes() " SIZE_FORMAT
3400          " used_bytes_slow()" SIZE_FORMAT,
3401          used_bytes(), used_in_use_bytes);
3402   for (Metaspace::MetadataType i = Metaspace::ClassType;
3403        i < Metaspace:: MetadataTypeCount;
3404        i = (Metaspace::MetadataType)(i + 1)) {
3405     size_t used_in_use_bytes = used_bytes_slow(i);
3406     assert(used_bytes(i) == used_in_use_bytes,
3407            "used_bytes(%u) " SIZE_FORMAT
3408            " used_bytes_slow(%u)" SIZE_FORMAT,
3409            i, used_bytes(i), i, used_in_use_bytes);
3410   }
3411 #endif
3412 }
3413 
3414 void MetaspaceAux::verify_metrics() {
3415   verify_capacity();
3416   verify_used();
3417 }
3418 
3419 
3420 // Metaspace methods
3421 
3422 size_t Metaspace::_first_chunk_word_size = 0;
3423 size_t Metaspace::_first_class_chunk_word_size = 0;
3424 
3425 size_t Metaspace::_commit_alignment = 0;
3426 size_t Metaspace::_reserve_alignment = 0;
3427 
3428 Metaspace::Metaspace(Mutex* lock, MetaspaceType type) {
3429   initialize(lock, type);
3430 }
3431 
3432 Metaspace::~Metaspace() {
3433   delete _vsm;
3434   if (using_class_space()) {
3435     delete _class_vsm;
3436   }
3437 }
3438 
3439 VirtualSpaceList* Metaspace::_space_list = NULL;
3440 VirtualSpaceList* Metaspace::_class_space_list = NULL;
3441 
3442 ChunkManager* Metaspace::_chunk_manager_metadata = NULL;
3443 ChunkManager* Metaspace::_chunk_manager_class = NULL;
3444 
3445 #define VIRTUALSPACEMULTIPLIER 2
3446 
3447 #ifdef _LP64
3448 static const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
3449 
3450 void Metaspace::set_narrow_klass_base_and_shift(address metaspace_base, address cds_base) {
3451   assert(!DumpSharedSpaces, "narrow_klass is set by MetaspaceShared class.");
3452   // Figure out the narrow_klass_base and the narrow_klass_shift.  The
3453   // narrow_klass_base is the lower of the metaspace base and the cds base
3454   // (if cds is enabled).  The narrow_klass_shift depends on the distance
3455   // between the lower base and higher address.
3456   address lower_base;
3457   address higher_address;
3458 #if INCLUDE_CDS
3459   if (UseSharedSpaces) {
3460     higher_address = MAX2((address)(cds_base + MetaspaceShared::core_spaces_size()),
3461                           (address)(metaspace_base + compressed_class_space_size()));
3462     lower_base = MIN2(metaspace_base, cds_base);
3463   } else
3464 #endif
3465   {
3466     higher_address = metaspace_base + compressed_class_space_size();
3467     lower_base = metaspace_base;
3468 
3469     uint64_t klass_encoding_max = UnscaledClassSpaceMax << LogKlassAlignmentInBytes;
3470     // If compressed class space fits in lower 32G, we don't need a base.
3471     if (higher_address <= (address)klass_encoding_max) {
3472       lower_base = 0; // Effectively lower base is zero.
3473     }
3474   }
3475 
3476   Universe::set_narrow_klass_base(lower_base);
3477 
3478   // CDS uses LogKlassAlignmentInBytes for narrow_klass_shift. See
3479   // MetaspaceShared::initialize_dumptime_shared_and_meta_spaces() for
3480   // how dump time narrow_klass_shift is set. Although, CDS can work
3481   // with zero-shift mode also, to be consistent with AOT it uses
3482   // LogKlassAlignmentInBytes for klass shift so archived java heap objects
3483   // can be used at same time as AOT code.
3484   if (!UseSharedSpaces
3485       && (uint64_t)(higher_address - lower_base) <= UnscaledClassSpaceMax) {
3486     Universe::set_narrow_klass_shift(0);
3487   } else {
3488     Universe::set_narrow_klass_shift(LogKlassAlignmentInBytes);
3489   }
3490   AOTLoader::set_narrow_klass_shift();
3491 }
3492 
3493 #if INCLUDE_CDS
3494 // Return TRUE if the specified metaspace_base and cds_base are close enough
3495 // to work with compressed klass pointers.
3496 bool Metaspace::can_use_cds_with_metaspace_addr(char* metaspace_base, address cds_base) {
3497   assert(cds_base != 0 && UseSharedSpaces, "Only use with CDS");
3498   assert(UseCompressedClassPointers, "Only use with CompressedKlassPtrs");
3499   address lower_base = MIN2((address)metaspace_base, cds_base);
3500   address higher_address = MAX2((address)(cds_base + MetaspaceShared::core_spaces_size()),
3501                                 (address)(metaspace_base + compressed_class_space_size()));
3502   return ((uint64_t)(higher_address - lower_base) <= UnscaledClassSpaceMax);
3503 }
3504 #endif
3505 
3506 // Try to allocate the metaspace at the requested addr.
3507 void Metaspace::allocate_metaspace_compressed_klass_ptrs(char* requested_addr, address cds_base) {
3508   assert(!DumpSharedSpaces, "compress klass space is allocated by MetaspaceShared class.");
3509   assert(using_class_space(), "called improperly");
3510   assert(UseCompressedClassPointers, "Only use with CompressedKlassPtrs");
3511   assert(compressed_class_space_size() < KlassEncodingMetaspaceMax,
3512          "Metaspace size is too big");
3513   assert_is_aligned(requested_addr, _reserve_alignment);
3514   assert_is_aligned(cds_base, _reserve_alignment);
3515   assert_is_aligned(compressed_class_space_size(), _reserve_alignment);
3516 
3517   // Don't use large pages for the class space.
3518   bool large_pages = false;
3519 
3520 #if !(defined(AARCH64) || defined(AIX))
3521   ReservedSpace metaspace_rs = ReservedSpace(compressed_class_space_size(),
3522                                              _reserve_alignment,
3523                                              large_pages,
3524                                              requested_addr);
3525 #else // AARCH64
3526   ReservedSpace metaspace_rs;
3527 
3528   // Our compressed klass pointers may fit nicely into the lower 32
3529   // bits.
3530   if ((uint64_t)requested_addr + compressed_class_space_size() < 4*G) {
3531     metaspace_rs = ReservedSpace(compressed_class_space_size(),
3532                                  _reserve_alignment,
3533                                  large_pages,
3534                                  requested_addr);
3535   }
3536 
3537   if (! metaspace_rs.is_reserved()) {
3538     // Aarch64: Try to align metaspace so that we can decode a compressed
3539     // klass with a single MOVK instruction.  We can do this iff the
3540     // compressed class base is a multiple of 4G.
3541     // Aix: Search for a place where we can find memory. If we need to load
3542     // the base, 4G alignment is helpful, too.
3543     size_t increment = AARCH64_ONLY(4*)G;
3544     for (char *a = align_up(requested_addr, increment);
3545          a < (char*)(1024*G);
3546          a += increment) {
3547       if (a == (char *)(32*G)) {
3548         // Go faster from here on. Zero-based is no longer possible.
3549         increment = 4*G;
3550       }
3551 
3552 #if INCLUDE_CDS
3553       if (UseSharedSpaces
3554           && ! can_use_cds_with_metaspace_addr(a, cds_base)) {
3555         // We failed to find an aligned base that will reach.  Fall
3556         // back to using our requested addr.
3557         metaspace_rs = ReservedSpace(compressed_class_space_size(),
3558                                      _reserve_alignment,
3559                                      large_pages,
3560                                      requested_addr);
3561         break;
3562       }
3563 #endif
3564 
3565       metaspace_rs = ReservedSpace(compressed_class_space_size(),
3566                                    _reserve_alignment,
3567                                    large_pages,
3568                                    a);
3569       if (metaspace_rs.is_reserved())
3570         break;
3571     }
3572   }
3573 
3574 #endif // AARCH64
3575 
3576   if (!metaspace_rs.is_reserved()) {
3577 #if INCLUDE_CDS
3578     if (UseSharedSpaces) {
3579       size_t increment = align_up(1*G, _reserve_alignment);
3580 
3581       // Keep trying to allocate the metaspace, increasing the requested_addr
3582       // by 1GB each time, until we reach an address that will no longer allow
3583       // use of CDS with compressed klass pointers.
3584       char *addr = requested_addr;
3585       while (!metaspace_rs.is_reserved() && (addr + increment > addr) &&
3586              can_use_cds_with_metaspace_addr(addr + increment, cds_base)) {
3587         addr = addr + increment;
3588         metaspace_rs = ReservedSpace(compressed_class_space_size(),
3589                                      _reserve_alignment, large_pages, addr);
3590       }
3591     }
3592 #endif
3593     // If no successful allocation then try to allocate the space anywhere.  If
3594     // that fails then OOM doom.  At this point we cannot try allocating the
3595     // metaspace as if UseCompressedClassPointers is off because too much
3596     // initialization has happened that depends on UseCompressedClassPointers.
3597     // So, UseCompressedClassPointers cannot be turned off at this point.
3598     if (!metaspace_rs.is_reserved()) {
3599       metaspace_rs = ReservedSpace(compressed_class_space_size(),
3600                                    _reserve_alignment, large_pages);
3601       if (!metaspace_rs.is_reserved()) {
3602         vm_exit_during_initialization(err_msg("Could not allocate metaspace: " SIZE_FORMAT " bytes",
3603                                               compressed_class_space_size()));
3604       }
3605     }
3606   }
3607 
3608   // If we got here then the metaspace got allocated.
3609   MemTracker::record_virtual_memory_type((address)metaspace_rs.base(), mtClass);
3610 
3611 #if INCLUDE_CDS
3612   // Verify that we can use shared spaces.  Otherwise, turn off CDS.
3613   if (UseSharedSpaces && !can_use_cds_with_metaspace_addr(metaspace_rs.base(), cds_base)) {
3614     FileMapInfo::stop_sharing_and_unmap(
3615         "Could not allocate metaspace at a compatible address");
3616   }
3617 #endif
3618   set_narrow_klass_base_and_shift((address)metaspace_rs.base(),
3619                                   UseSharedSpaces ? (address)cds_base : 0);
3620 
3621   initialize_class_space(metaspace_rs);
3622 
3623   LogTarget(Trace, gc, metaspace) lt;
3624   if (lt.is_enabled()) {
3625     ResourceMark rm;
3626     LogStream ls(lt);
3627     print_compressed_class_space(&ls, requested_addr);
3628   }
3629 }
3630 
3631 void Metaspace::print_compressed_class_space(outputStream* st, const char* requested_addr) {
3632   st->print_cr("Narrow klass base: " PTR_FORMAT ", Narrow klass shift: %d",
3633                p2i(Universe::narrow_klass_base()), Universe::narrow_klass_shift());
3634   if (_class_space_list != NULL) {
3635     address base = (address)_class_space_list->current_virtual_space()->bottom();
3636     st->print("Compressed class space size: " SIZE_FORMAT " Address: " PTR_FORMAT,
3637                  compressed_class_space_size(), p2i(base));
3638     if (requested_addr != 0) {
3639       st->print(" Req Addr: " PTR_FORMAT, p2i(requested_addr));
3640     }
3641     st->cr();
3642   }
3643 }
3644 
3645 // For UseCompressedClassPointers the class space is reserved above the top of
3646 // the Java heap.  The argument passed in is at the base of the compressed space.
3647 void Metaspace::initialize_class_space(ReservedSpace rs) {
3648   // The reserved space size may be bigger because of alignment, esp with UseLargePages
3649   assert(rs.size() >= CompressedClassSpaceSize,
3650          SIZE_FORMAT " != " SIZE_FORMAT, rs.size(), CompressedClassSpaceSize);
3651   assert(using_class_space(), "Must be using class space");
3652   _class_space_list = new VirtualSpaceList(rs);
3653   _chunk_manager_class = new ChunkManager(ClassSpecializedChunk, ClassSmallChunk, ClassMediumChunk);
3654 
3655   if (!_class_space_list->initialization_succeeded()) {
3656     vm_exit_during_initialization("Failed to setup compressed class space virtual space list.");
3657   }
3658 }
3659 
3660 #endif
3661 
3662 void Metaspace::ergo_initialize() {
3663   if (DumpSharedSpaces) {
3664     // Using large pages when dumping the shared archive is currently not implemented.
3665     FLAG_SET_ERGO(bool, UseLargePagesInMetaspace, false);
3666   }
3667 
3668   size_t page_size = os::vm_page_size();
3669   if (UseLargePages && UseLargePagesInMetaspace) {
3670     page_size = os::large_page_size();
3671   }
3672 
3673   _commit_alignment  = page_size;
3674   _reserve_alignment = MAX2(page_size, (size_t)os::vm_allocation_granularity());
3675 
3676   // Do not use FLAG_SET_ERGO to update MaxMetaspaceSize, since this will
3677   // override if MaxMetaspaceSize was set on the command line or not.
3678   // This information is needed later to conform to the specification of the
3679   // java.lang.management.MemoryUsage API.
3680   //
3681   // Ideally, we would be able to set the default value of MaxMetaspaceSize in
3682   // globals.hpp to the aligned value, but this is not possible, since the
3683   // alignment depends on other flags being parsed.
3684   MaxMetaspaceSize = align_down_bounded(MaxMetaspaceSize, _reserve_alignment);
3685 
3686   if (MetaspaceSize > MaxMetaspaceSize) {
3687     MetaspaceSize = MaxMetaspaceSize;
3688   }
3689 
3690   MetaspaceSize = align_down_bounded(MetaspaceSize, _commit_alignment);
3691 
3692   assert(MetaspaceSize <= MaxMetaspaceSize, "MetaspaceSize should be limited by MaxMetaspaceSize");
3693 
3694   MinMetaspaceExpansion = align_down_bounded(MinMetaspaceExpansion, _commit_alignment);
3695   MaxMetaspaceExpansion = align_down_bounded(MaxMetaspaceExpansion, _commit_alignment);
3696 
3697   CompressedClassSpaceSize = align_down_bounded(CompressedClassSpaceSize, _reserve_alignment);
3698 
3699   // Initial virtual space size will be calculated at global_initialize()
3700   size_t min_metaspace_sz =
3701       VIRTUALSPACEMULTIPLIER * InitialBootClassLoaderMetaspaceSize;
3702   if (UseCompressedClassPointers) {
3703     if ((min_metaspace_sz + CompressedClassSpaceSize) >  MaxMetaspaceSize) {
3704       if (min_metaspace_sz >= MaxMetaspaceSize) {
3705         vm_exit_during_initialization("MaxMetaspaceSize is too small.");
3706       } else {
3707         FLAG_SET_ERGO(size_t, CompressedClassSpaceSize,
3708                       MaxMetaspaceSize - min_metaspace_sz);
3709       }
3710     }
3711   } else if (min_metaspace_sz >= MaxMetaspaceSize) {
3712     FLAG_SET_ERGO(size_t, InitialBootClassLoaderMetaspaceSize,
3713                   min_metaspace_sz);
3714   }
3715 
3716   set_compressed_class_space_size(CompressedClassSpaceSize);
3717 }
3718 
3719 void Metaspace::global_initialize() {
3720   MetaspaceGC::initialize();
3721 
3722 #if INCLUDE_CDS
3723   if (DumpSharedSpaces) {
3724     MetaspaceShared::initialize_dumptime_shared_and_meta_spaces();
3725   } else if (UseSharedSpaces) {
3726     // If any of the archived space fails to map, UseSharedSpaces
3727     // is reset to false. Fall through to the
3728     // (!DumpSharedSpaces && !UseSharedSpaces) case to set up class
3729     // metaspace.
3730     MetaspaceShared::initialize_runtime_shared_and_meta_spaces();
3731   }
3732 
3733   if (!DumpSharedSpaces && !UseSharedSpaces)
3734 #endif // INCLUDE_CDS
3735   {
3736 #ifdef _LP64
3737     if (using_class_space()) {
3738       char* base = (char*)align_up(Universe::heap()->reserved_region().end(), _reserve_alignment);
3739       allocate_metaspace_compressed_klass_ptrs(base, 0);
3740     }
3741 #endif // _LP64
3742   }
3743 
3744   // Initialize these before initializing the VirtualSpaceList
3745   _first_chunk_word_size = InitialBootClassLoaderMetaspaceSize / BytesPerWord;
3746   _first_chunk_word_size = align_word_size_up(_first_chunk_word_size);
3747   // Make the first class chunk bigger than a medium chunk so it's not put
3748   // on the medium chunk list.   The next chunk will be small and progress
3749   // from there.  This size calculated by -version.
3750   _first_class_chunk_word_size = MIN2((size_t)MediumChunk*6,
3751                                      (CompressedClassSpaceSize/BytesPerWord)*2);
3752   _first_class_chunk_word_size = align_word_size_up(_first_class_chunk_word_size);
3753   // Arbitrarily set the initial virtual space to a multiple
3754   // of the boot class loader size.
3755   size_t word_size = VIRTUALSPACEMULTIPLIER * _first_chunk_word_size;
3756   word_size = align_up(word_size, Metaspace::reserve_alignment_words());
3757 
3758   // Initialize the list of virtual spaces.
3759   _space_list = new VirtualSpaceList(word_size);
3760   _chunk_manager_metadata = new ChunkManager(SpecializedChunk, SmallChunk, MediumChunk);
3761 
3762   if (!_space_list->initialization_succeeded()) {
3763     vm_exit_during_initialization("Unable to setup metadata virtual space list.", NULL);
3764   }
3765 
3766   _tracer = new MetaspaceTracer();
3767 }
3768 
3769 void Metaspace::post_initialize() {
3770   MetaspaceGC::post_initialize();
3771 }
3772 
3773 void Metaspace::initialize_first_chunk(MetaspaceType type, MetadataType mdtype) {
3774   Metachunk* chunk = get_initialization_chunk(type, mdtype);
3775   if (chunk != NULL) {
3776     // Add to this manager's list of chunks in use and current_chunk().
3777     get_space_manager(mdtype)->add_chunk(chunk, true);
3778   }
3779 }
3780 
3781 Metachunk* Metaspace::get_initialization_chunk(MetaspaceType type, MetadataType mdtype) {
3782   size_t chunk_word_size = get_space_manager(mdtype)->get_initial_chunk_size(type);
3783 
3784   // Get a chunk from the chunk freelist
3785   Metachunk* chunk = get_chunk_manager(mdtype)->chunk_freelist_allocate(chunk_word_size);
3786 
3787   if (chunk == NULL) {
3788     chunk = get_space_list(mdtype)->get_new_chunk(chunk_word_size,
3789                                                   get_space_manager(mdtype)->medium_chunk_bunch());
3790   }
3791 
3792   return chunk;
3793 }
3794 
3795 void Metaspace::verify_global_initialization() {
3796   assert(space_list() != NULL, "Metadata VirtualSpaceList has not been initialized");
3797   assert(chunk_manager_metadata() != NULL, "Metadata ChunkManager has not been initialized");
3798 
3799   if (using_class_space()) {
3800     assert(class_space_list() != NULL, "Class VirtualSpaceList has not been initialized");
3801     assert(chunk_manager_class() != NULL, "Class ChunkManager has not been initialized");
3802   }
3803 }
3804 
3805 void Metaspace::initialize(Mutex* lock, MetaspaceType type) {
3806   verify_global_initialization();
3807 
3808   // Allocate SpaceManager for metadata objects.
3809   _vsm = new SpaceManager(NonClassType, type, lock);
3810 
3811   if (using_class_space()) {
3812     // Allocate SpaceManager for classes.
3813     _class_vsm = new SpaceManager(ClassType, type, lock);
3814   }
3815 
3816   MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
3817 
3818   // Allocate chunk for metadata objects
3819   initialize_first_chunk(type, NonClassType);
3820 
3821   // Allocate chunk for class metadata objects
3822   if (using_class_space()) {
3823     initialize_first_chunk(type, ClassType);
3824   }
3825 }
3826 
3827 size_t Metaspace::align_word_size_up(size_t word_size) {
3828   size_t byte_size = word_size * wordSize;
3829   return ReservedSpace::allocation_align_size_up(byte_size) / wordSize;
3830 }
3831 
3832 MetaWord* Metaspace::allocate(size_t word_size, MetadataType mdtype) {
3833   assert(!_frozen, "sanity");
3834   // Don't use class_vsm() unless UseCompressedClassPointers is true.
3835   if (is_class_space_allocation(mdtype)) {
3836     return  class_vsm()->allocate(word_size);
3837   } else {
3838     return  vsm()->allocate(word_size);
3839   }
3840 }
3841 
3842 MetaWord* Metaspace::expand_and_allocate(size_t word_size, MetadataType mdtype) {
3843   assert(!_frozen, "sanity");
3844   size_t delta_bytes = MetaspaceGC::delta_capacity_until_GC(word_size * BytesPerWord);
3845   assert(delta_bytes > 0, "Must be");
3846 
3847   size_t before = 0;
3848   size_t after = 0;
3849   MetaWord* res;
3850   bool incremented;
3851 
3852   // Each thread increments the HWM at most once. Even if the thread fails to increment
3853   // the HWM, an allocation is still attempted. This is because another thread must then
3854   // have incremented the HWM and therefore the allocation might still succeed.
3855   do {
3856     incremented = MetaspaceGC::inc_capacity_until_GC(delta_bytes, &after, &before);
3857     res = allocate(word_size, mdtype);
3858   } while (!incremented && res == NULL);
3859 
3860   if (incremented) {
3861     tracer()->report_gc_threshold(before, after,
3862                                   MetaspaceGCThresholdUpdater::ExpandAndAllocate);
3863     log_trace(gc, metaspace)("Increase capacity to GC from " SIZE_FORMAT " to " SIZE_FORMAT, before, after);
3864   }
3865 
3866   return res;
3867 }
3868 
3869 size_t Metaspace::used_words_slow(MetadataType mdtype) const {
3870   if (mdtype == ClassType) {
3871     return using_class_space() ? class_vsm()->sum_used_in_chunks_in_use() : 0;
3872   } else {
3873     return vsm()->sum_used_in_chunks_in_use();  // includes overhead!
3874   }
3875 }
3876 
3877 size_t Metaspace::free_words_slow(MetadataType mdtype) const {
3878   assert(!_frozen, "sanity");
3879   if (mdtype == ClassType) {
3880     return using_class_space() ? class_vsm()->sum_free_in_chunks_in_use() : 0;
3881   } else {
3882     return vsm()->sum_free_in_chunks_in_use();
3883   }
3884 }
3885 
3886 // Space capacity in the Metaspace.  It includes
3887 // space in the list of chunks from which allocations
3888 // have been made. Don't include space in the global freelist and
3889 // in the space available in the dictionary which
3890 // is already counted in some chunk.
3891 size_t Metaspace::capacity_words_slow(MetadataType mdtype) const {
3892   if (mdtype == ClassType) {
3893     return using_class_space() ? class_vsm()->sum_capacity_in_chunks_in_use() : 0;
3894   } else {
3895     return vsm()->sum_capacity_in_chunks_in_use();
3896   }
3897 }
3898 
3899 size_t Metaspace::used_bytes_slow(MetadataType mdtype) const {
3900   return used_words_slow(mdtype) * BytesPerWord;
3901 }
3902 
3903 size_t Metaspace::capacity_bytes_slow(MetadataType mdtype) const {
3904   return capacity_words_slow(mdtype) * BytesPerWord;
3905 }
3906 
3907 size_t Metaspace::allocated_blocks_bytes() const {
3908   return vsm()->allocated_blocks_bytes() +
3909       (using_class_space() ? class_vsm()->allocated_blocks_bytes() : 0);
3910 }
3911 
3912 size_t Metaspace::allocated_chunks_bytes() const {
3913   return vsm()->allocated_chunks_bytes() +
3914       (using_class_space() ? class_vsm()->allocated_chunks_bytes() : 0);
3915 }
3916 
3917 void Metaspace::deallocate(MetaWord* ptr, size_t word_size, bool is_class) {
3918   assert(!_frozen, "sanity");
3919   assert(!SafepointSynchronize::is_at_safepoint()
3920          || Thread::current()->is_VM_thread(), "should be the VM thread");
3921 
3922   MutexLockerEx ml(vsm()->lock(), Mutex::_no_safepoint_check_flag);
3923 
3924   if (is_class && using_class_space()) {
3925     class_vsm()->deallocate(ptr, word_size);
3926   } else {
3927     vsm()->deallocate(ptr, word_size);
3928   }
3929 }
3930 
3931 MetaWord* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size,
3932                               MetaspaceObj::Type type, TRAPS) {
3933   assert(!_frozen, "sanity");
3934   if (HAS_PENDING_EXCEPTION) {
3935     assert(false, "Should not allocate with exception pending");
3936     return NULL;  // caller does a CHECK_NULL too
3937   }
3938 
3939   assert(loader_data != NULL, "Should never pass around a NULL loader_data. "
3940         "ClassLoaderData::the_null_class_loader_data() should have been used.");
3941 
3942   MetadataType mdtype = (type == MetaspaceObj::ClassType) ? ClassType : NonClassType;
3943 
3944   // Try to allocate metadata.
3945   MetaWord* result = loader_data->metaspace_non_null()->allocate(word_size, mdtype);
3946 
3947   if (result == NULL) {
3948     tracer()->report_metaspace_allocation_failure(loader_data, word_size, type, mdtype);
3949 
3950     // Allocation failed.
3951     if (is_init_completed()) {
3952       // Only start a GC if the bootstrapping has completed.
3953 
3954       // Try to clean out some memory and retry.
3955       result = Universe::heap()->satisfy_failed_metadata_allocation(loader_data, word_size, mdtype);
3956     }
3957   }
3958 
3959   if (result == NULL) {
3960     SpaceManager* sm;
3961     if (is_class_space_allocation(mdtype)) {
3962       sm = loader_data->metaspace_non_null()->class_vsm();
3963     } else {
3964       sm = loader_data->metaspace_non_null()->vsm();
3965     }
3966 
3967     result = sm->get_small_chunk_and_allocate(word_size);
3968 
3969     if (result == NULL) {
3970       report_metadata_oome(loader_data, word_size, type, mdtype, CHECK_NULL);
3971     }
3972   }
3973 
3974   // Zero initialize.
3975   Copy::fill_to_words((HeapWord*)result, word_size, 0);
3976 
3977   return result;
3978 }
3979 
3980 size_t Metaspace::class_chunk_size(size_t word_size) {
3981   assert(using_class_space(), "Has to use class space");
3982   return class_vsm()->calc_chunk_size(word_size);
3983 }
3984 
3985 void Metaspace::report_metadata_oome(ClassLoaderData* loader_data, size_t word_size, MetaspaceObj::Type type, MetadataType mdtype, TRAPS) {
3986   tracer()->report_metadata_oom(loader_data, word_size, type, mdtype);
3987 
3988   // If result is still null, we are out of memory.
3989   Log(gc, metaspace, freelist) log;
3990   if (log.is_info()) {
3991     log.info("Metaspace (%s) allocation failed for size " SIZE_FORMAT,
3992              is_class_space_allocation(mdtype) ? "class" : "data", word_size);
3993     ResourceMark rm;
3994     if (log.is_debug()) {
3995       if (loader_data->metaspace_or_null() != NULL) {
3996         LogStream ls(log.debug());
3997         loader_data->dump(&ls);
3998       }
3999     }
4000     LogStream ls(log.info());
4001     MetaspaceAux::dump(&ls);
4002     MetaspaceAux::print_metaspace_map(&ls, mdtype);
4003     ChunkManager::print_all_chunkmanagers(&ls);
4004   }
4005 
4006   bool out_of_compressed_class_space = false;
4007   if (is_class_space_allocation(mdtype)) {
4008     Metaspace* metaspace = loader_data->metaspace_non_null();
4009     out_of_compressed_class_space =
4010       MetaspaceAux::committed_bytes(Metaspace::ClassType) +
4011       (metaspace->class_chunk_size(word_size) * BytesPerWord) >
4012       CompressedClassSpaceSize;
4013   }
4014 
4015   // -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support
4016   const char* space_string = out_of_compressed_class_space ?
4017     "Compressed class space" : "Metaspace";
4018 
4019   report_java_out_of_memory(space_string);
4020 
4021   if (JvmtiExport::should_post_resource_exhausted()) {
4022     JvmtiExport::post_resource_exhausted(
4023         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR,
4024         space_string);
4025   }
4026 
4027   if (!is_init_completed()) {
4028     vm_exit_during_initialization("OutOfMemoryError", space_string);
4029   }
4030 
4031   if (out_of_compressed_class_space) {
4032     THROW_OOP(Universe::out_of_memory_error_class_metaspace());
4033   } else {
4034     THROW_OOP(Universe::out_of_memory_error_metaspace());
4035   }
4036 }
4037 
4038 const char* Metaspace::metadata_type_name(Metaspace::MetadataType mdtype) {
4039   switch (mdtype) {
4040     case Metaspace::ClassType: return "Class";
4041     case Metaspace::NonClassType: return "Metadata";
4042     default:
4043       assert(false, "Got bad mdtype: %d", (int) mdtype);
4044       return NULL;
4045   }
4046 }
4047 
4048 void Metaspace::purge(MetadataType mdtype) {
4049   get_space_list(mdtype)->purge(get_chunk_manager(mdtype));
4050 }
4051 
4052 void Metaspace::purge() {
4053   MutexLockerEx cl(SpaceManager::expand_lock(),
4054                    Mutex::_no_safepoint_check_flag);
4055   purge(NonClassType);
4056   if (using_class_space()) {
4057     purge(ClassType);
4058   }
4059 }
4060 
4061 void Metaspace::print_on(outputStream* out) const {
4062   // Print both class virtual space counts and metaspace.
4063   if (Verbose) {
4064     vsm()->print_on(out);
4065     if (using_class_space()) {
4066       class_vsm()->print_on(out);
4067     }
4068   }
4069 }
4070 
4071 bool Metaspace::contains(const void* ptr) {
4072   if (MetaspaceShared::is_in_shared_metaspace(ptr)) {
4073     return true;
4074   }
4075   return contains_non_shared(ptr);
4076 }
4077 
4078 bool Metaspace::contains_non_shared(const void* ptr) {
4079   if (using_class_space() && get_space_list(ClassType)->contains(ptr)) {
4080      return true;
4081   }
4082 
4083   return get_space_list(NonClassType)->contains(ptr);
4084 }
4085 
4086 void Metaspace::verify() {
4087   vsm()->verify();
4088   if (using_class_space()) {
4089     class_vsm()->verify();
4090   }
4091 }
4092 
4093 void Metaspace::dump(outputStream* const out) const {
4094   out->print_cr("\nVirtual space manager: " INTPTR_FORMAT, p2i(vsm()));
4095   vsm()->dump(out);
4096   if (using_class_space()) {
4097     out->print_cr("\nClass space manager: " INTPTR_FORMAT, p2i(class_vsm()));
4098     class_vsm()->dump(out);
4099   }
4100 }
4101 
4102 /////////////// Unit tests ///////////////
4103 
4104 #ifndef PRODUCT
4105 
4106 class TestMetaspaceAuxTest : AllStatic {
4107  public:
4108   static void test_reserved() {
4109     size_t reserved = MetaspaceAux::reserved_bytes();
4110 
4111     assert(reserved > 0, "assert");
4112 
4113     size_t committed  = MetaspaceAux::committed_bytes();
4114     assert(committed <= reserved, "assert");
4115 
4116     size_t reserved_metadata = MetaspaceAux::reserved_bytes(Metaspace::NonClassType);
4117     assert(reserved_metadata > 0, "assert");
4118     assert(reserved_metadata <= reserved, "assert");
4119 
4120     if (UseCompressedClassPointers) {
4121       size_t reserved_class    = MetaspaceAux::reserved_bytes(Metaspace::ClassType);
4122       assert(reserved_class > 0, "assert");
4123       assert(reserved_class < reserved, "assert");
4124     }
4125   }
4126 
4127   static void test_committed() {
4128     size_t committed = MetaspaceAux::committed_bytes();
4129 
4130     assert(committed > 0, "assert");
4131 
4132     size_t reserved  = MetaspaceAux::reserved_bytes();
4133     assert(committed <= reserved, "assert");
4134 
4135     size_t committed_metadata = MetaspaceAux::committed_bytes(Metaspace::NonClassType);
4136     assert(committed_metadata > 0, "assert");
4137     assert(committed_metadata <= committed, "assert");
4138 
4139     if (UseCompressedClassPointers) {
4140       size_t committed_class    = MetaspaceAux::committed_bytes(Metaspace::ClassType);
4141       assert(committed_class > 0, "assert");
4142       assert(committed_class < committed, "assert");
4143     }
4144   }
4145 
4146   static void test_virtual_space_list_large_chunk() {
4147     VirtualSpaceList* vs_list = new VirtualSpaceList(os::vm_allocation_granularity());
4148     MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
4149     // A size larger than VirtualSpaceSize (256k) and add one page to make it _not_ be
4150     // vm_allocation_granularity aligned on Windows.
4151     size_t large_size = (size_t)(2*256*K + (os::vm_page_size()/BytesPerWord));
4152     large_size += (os::vm_page_size()/BytesPerWord);
4153     vs_list->get_new_chunk(large_size, 0);
4154   }
4155 
4156   static void test() {
4157     test_reserved();
4158     test_committed();
4159     test_virtual_space_list_large_chunk();
4160   }
4161 };
4162 
4163 void TestMetaspaceAux_test() {
4164   TestMetaspaceAuxTest::test();
4165 }
4166 
4167 class TestVirtualSpaceNodeTest {
4168   static void chunk_up(size_t words_left, size_t& num_medium_chunks,
4169                                           size_t& num_small_chunks,
4170                                           size_t& num_specialized_chunks) {
4171     num_medium_chunks = words_left / MediumChunk;
4172     words_left = words_left % MediumChunk;
4173 
4174     num_small_chunks = words_left / SmallChunk;
4175     words_left = words_left % SmallChunk;
4176     // how many specialized chunks can we get?
4177     num_specialized_chunks = words_left / SpecializedChunk;
4178     assert(words_left % SpecializedChunk == 0, "should be nothing left");
4179   }
4180 
4181  public:
4182   static void test() {
4183     MutexLockerEx ml(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
4184     const size_t vsn_test_size_words = MediumChunk  * 4;
4185     const size_t vsn_test_size_bytes = vsn_test_size_words * BytesPerWord;
4186 
4187     // The chunk sizes must be multiples of eachother, or this will fail
4188     STATIC_ASSERT(MediumChunk % SmallChunk == 0);
4189     STATIC_ASSERT(SmallChunk % SpecializedChunk == 0);
4190 
4191     { // No committed memory in VSN
4192       ChunkManager cm(SpecializedChunk, SmallChunk, MediumChunk);
4193       VirtualSpaceNode vsn(vsn_test_size_bytes);
4194       vsn.initialize();
4195       vsn.retire(&cm);
4196       assert(cm.sum_free_chunks_count() == 0, "did not commit any memory in the VSN");
4197     }
4198 
4199     { // All of VSN is committed, half is used by chunks
4200       ChunkManager cm(SpecializedChunk, SmallChunk, MediumChunk);
4201       VirtualSpaceNode vsn(vsn_test_size_bytes);
4202       vsn.initialize();
4203       vsn.expand_by(vsn_test_size_words, vsn_test_size_words);
4204       vsn.get_chunk_vs(MediumChunk);
4205       vsn.get_chunk_vs(MediumChunk);
4206       vsn.retire(&cm);
4207       assert(cm.sum_free_chunks_count() == 2, "should have been memory left for 2 medium chunks");
4208       assert(cm.sum_free_chunks() == 2*MediumChunk, "sizes should add up");
4209     }
4210 
4211     const size_t page_chunks = 4 * (size_t)os::vm_page_size() / BytesPerWord;
4212     // This doesn't work for systems with vm_page_size >= 16K.
4213     if (page_chunks < MediumChunk) {
4214       // 4 pages of VSN is committed, some is used by chunks
4215       ChunkManager cm(SpecializedChunk, SmallChunk, MediumChunk);
4216       VirtualSpaceNode vsn(vsn_test_size_bytes);
4217 
4218       vsn.initialize();
4219       vsn.expand_by(page_chunks, page_chunks);
4220       vsn.get_chunk_vs(SmallChunk);
4221       vsn.get_chunk_vs(SpecializedChunk);
4222       vsn.retire(&cm);
4223 
4224       // committed - used = words left to retire
4225       const size_t words_left = page_chunks - SmallChunk - SpecializedChunk;
4226 
4227       size_t num_medium_chunks, num_small_chunks, num_spec_chunks;
4228       chunk_up(words_left, num_medium_chunks, num_small_chunks, num_spec_chunks);
4229 
4230       assert(num_medium_chunks == 0, "should not get any medium chunks");
4231       assert(cm.sum_free_chunks_count() == (num_small_chunks + num_spec_chunks), "should be space for 3 chunks");
4232       assert(cm.sum_free_chunks() == words_left, "sizes should add up");
4233     }
4234 
4235     { // Half of VSN is committed, a humongous chunk is used
4236       ChunkManager cm(SpecializedChunk, SmallChunk, MediumChunk);
4237       VirtualSpaceNode vsn(vsn_test_size_bytes);
4238       vsn.initialize();
4239       vsn.expand_by(MediumChunk * 2, MediumChunk * 2);
4240       vsn.get_chunk_vs(MediumChunk + SpecializedChunk); // Humongous chunks will be aligned up to MediumChunk + SpecializedChunk
4241       vsn.retire(&cm);
4242 
4243       const size_t words_left = MediumChunk * 2 - (MediumChunk + SpecializedChunk);
4244       size_t num_medium_chunks, num_small_chunks, num_spec_chunks;
4245       chunk_up(words_left, num_medium_chunks, num_small_chunks, num_spec_chunks);
4246 
4247       assert(num_medium_chunks == 0, "should not get any medium chunks");
4248       assert(cm.sum_free_chunks_count() == (num_small_chunks + num_spec_chunks), "should be space for 3 chunks");
4249       assert(cm.sum_free_chunks() == words_left, "sizes should add up");
4250     }
4251 
4252   }
4253 
4254 #define assert_is_available_positive(word_size) \
4255   assert(vsn.is_available(word_size), \
4256          #word_size ": " PTR_FORMAT " bytes were not available in " \
4257          "VirtualSpaceNode [" PTR_FORMAT ", " PTR_FORMAT ")", \
4258          (uintptr_t)(word_size * BytesPerWord), p2i(vsn.bottom()), p2i(vsn.end()));
4259 
4260 #define assert_is_available_negative(word_size) \
4261   assert(!vsn.is_available(word_size), \
4262          #word_size ": " PTR_FORMAT " bytes should not be available in " \
4263          "VirtualSpaceNode [" PTR_FORMAT ", " PTR_FORMAT ")", \
4264          (uintptr_t)(word_size * BytesPerWord), p2i(vsn.bottom()), p2i(vsn.end()));
4265 
4266   static void test_is_available_positive() {
4267     // Reserve some memory.
4268     VirtualSpaceNode vsn(os::vm_allocation_granularity());
4269     assert(vsn.initialize(), "Failed to setup VirtualSpaceNode");
4270 
4271     // Commit some memory.
4272     size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord;
4273     bool expanded = vsn.expand_by(commit_word_size, commit_word_size);
4274     assert(expanded, "Failed to commit");
4275 
4276     // Check that is_available accepts the committed size.
4277     assert_is_available_positive(commit_word_size);
4278 
4279     // Check that is_available accepts half the committed size.
4280     size_t expand_word_size = commit_word_size / 2;
4281     assert_is_available_positive(expand_word_size);
4282   }
4283 
4284   static void test_is_available_negative() {
4285     // Reserve some memory.
4286     VirtualSpaceNode vsn(os::vm_allocation_granularity());
4287     assert(vsn.initialize(), "Failed to setup VirtualSpaceNode");
4288 
4289     // Commit some memory.
4290     size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord;
4291     bool expanded = vsn.expand_by(commit_word_size, commit_word_size);
4292     assert(expanded, "Failed to commit");
4293 
4294     // Check that is_available doesn't accept a too large size.
4295     size_t two_times_commit_word_size = commit_word_size * 2;
4296     assert_is_available_negative(two_times_commit_word_size);
4297   }
4298 
4299   static void test_is_available_overflow() {
4300     // Reserve some memory.
4301     VirtualSpaceNode vsn(os::vm_allocation_granularity());
4302     assert(vsn.initialize(), "Failed to setup VirtualSpaceNode");
4303 
4304     // Commit some memory.
4305     size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord;
4306     bool expanded = vsn.expand_by(commit_word_size, commit_word_size);
4307     assert(expanded, "Failed to commit");
4308 
4309     // Calculate a size that will overflow the virtual space size.
4310     void* virtual_space_max = (void*)(uintptr_t)-1;
4311     size_t bottom_to_max = pointer_delta(virtual_space_max, vsn.bottom(), 1);
4312     size_t overflow_size = bottom_to_max + BytesPerWord;
4313     size_t overflow_word_size = overflow_size / BytesPerWord;
4314 
4315     // Check that is_available can handle the overflow.
4316     assert_is_available_negative(overflow_word_size);
4317   }
4318 
4319   static void test_is_available() {
4320     TestVirtualSpaceNodeTest::test_is_available_positive();
4321     TestVirtualSpaceNodeTest::test_is_available_negative();
4322     TestVirtualSpaceNodeTest::test_is_available_overflow();
4323   }
4324 };
4325 
4326 void TestVirtualSpaceNode_test() {
4327   TestVirtualSpaceNodeTest::test();
4328   TestVirtualSpaceNodeTest::test_is_available();
4329 }
4330 
4331 // The following test is placed here instead of a gtest / unittest file
4332 // because the ChunkManager class is only available in this file.
4333 void ChunkManager_test_list_index() {
4334   ChunkManager manager(ClassSpecializedChunk, ClassSmallChunk, ClassMediumChunk);
4335 
4336   // Test previous bug where a query for a humongous class metachunk,
4337   // incorrectly matched the non-class medium metachunk size.
4338   {
4339     assert(MediumChunk > ClassMediumChunk, "Precondition for test");
4340 
4341     ChunkIndex index = manager.list_index(MediumChunk);
4342 
4343     assert(index == HumongousIndex,
4344            "Requested size is larger than ClassMediumChunk,"
4345            " so should return HumongousIndex. Got index: %d", (int)index);
4346   }
4347 
4348   // Check the specified sizes as well.
4349   {
4350     ChunkIndex index = manager.list_index(ClassSpecializedChunk);
4351     assert(index == SpecializedIndex, "Wrong index returned. Got index: %d", (int)index);
4352   }
4353   {
4354     ChunkIndex index = manager.list_index(ClassSmallChunk);
4355     assert(index == SmallIndex, "Wrong index returned. Got index: %d", (int)index);
4356   }
4357   {
4358     ChunkIndex index = manager.list_index(ClassMediumChunk);
4359     assert(index == MediumIndex, "Wrong index returned. Got index: %d", (int)index);
4360   }
4361   {
4362     ChunkIndex index = manager.list_index(ClassMediumChunk + 1);
4363     assert(index == HumongousIndex, "Wrong index returned. Got index: %d", (int)index);
4364   }
4365 }
4366 
4367 #endif // !PRODUCT
4368 
4369 #ifdef ASSERT
4370 
4371 // ChunkManagerReturnTest stresses taking/returning chunks from the ChunkManager. It takes and
4372 // returns chunks from/to the ChunkManager while keeping track of the expected ChunkManager
4373 // content.
4374 class ChunkManagerReturnTestImpl : public CHeapObj<mtClass> {
4375 
4376   VirtualSpaceNode _vsn;
4377   ChunkManager _cm;
4378 
4379   // The expected content of the chunk manager.
4380   unsigned _chunks_in_chunkmanager;
4381   size_t _words_in_chunkmanager;
4382 
4383   // A fixed size pool of chunks. Chunks may be in the chunk manager (free) or not (in use).
4384   static const int num_chunks = 256;
4385   Metachunk* _pool[num_chunks];
4386 
4387   // Helper, return a random position into the chunk pool.
4388   static int get_random_position() {
4389     return os::random() % num_chunks;
4390   }
4391 
4392   // Asserts that ChunkManager counters match expectations.
4393   void assert_counters() {
4394     assert(_vsn.container_count() == num_chunks - _chunks_in_chunkmanager, "vsn counter mismatch.");
4395     assert(_cm.free_chunks_count() == _chunks_in_chunkmanager, "cm counter mismatch.");
4396     assert(_cm.free_chunks_total_words() == _words_in_chunkmanager, "cm counter mismatch.");
4397   }
4398 
4399   // Get a random chunk size. Equal chance to get spec/med/small chunk size or
4400   // a humongous chunk size. The latter itself is random in the range of [med+spec..4*med).
4401   size_t get_random_chunk_size() {
4402     const size_t sizes [] = { SpecializedChunk, SmallChunk, MediumChunk };
4403     const int rand = os::random() % 4;
4404     if (rand < 3) {
4405       return sizes[rand];
4406     } else {
4407       // Note: this affects the max. size of space (see _vsn initialization in ctor).
4408       return align_up(MediumChunk + 1 + (os::random() % (MediumChunk * 4)), SpecializedChunk);
4409     }
4410   }
4411 
4412   // Starting at pool index <start>+1, find the next chunk tagged as either free or in use, depending
4413   // on <is_free>. Search wraps. Returns its position, or -1 if no matching chunk was found.
4414   int next_matching_chunk(int start, bool is_free) const {
4415     assert(start >= 0 && start < num_chunks, "invalid parameter");
4416     int pos = start;
4417     do {
4418       if (++pos == num_chunks) {
4419         pos = 0;
4420       }
4421       if (_pool[pos]->is_tagged_free() == is_free) {
4422         return pos;
4423       }
4424     } while (pos != start);
4425     return -1;
4426   }
4427 
4428   // A structure to keep information about a chunk list including which
4429   // chunks are part of this list. This is needed to keep information about a chunk list
4430   // we will to return to the ChunkManager, because the original list will be destroyed.
4431   struct AChunkList {
4432     Metachunk* head;
4433     Metachunk* all[num_chunks];
4434     size_t size;
4435     int num;
4436     ChunkIndex index;
4437   };
4438 
4439   // Assemble, from the in-use chunks (not in the chunk manager) in the pool,
4440   // a random chunk list of max. length <list_size> of chunks with the same
4441   // ChunkIndex (chunk size).
4442   // Returns false if list cannot be assembled. List is returned in the <out>
4443   // structure. Returned list may be smaller than <list_size>.
4444   bool assemble_random_chunklist(AChunkList* out, int list_size) {
4445     // Choose a random in-use chunk from the pool...
4446     const int headpos = next_matching_chunk(get_random_position(), false);
4447     if (headpos == -1) {
4448       return false;
4449     }
4450     Metachunk* const head = _pool[headpos];
4451     out->all[0] = head;
4452     assert(head->is_tagged_free() == false, "Chunk state mismatch");
4453     // ..then go from there, chain it up with up to list_size - 1 number of other
4454     // in-use chunks of the same index.
4455     const ChunkIndex index = _cm.list_index(head->word_size());
4456     int num_added = 1;
4457     size_t size_added = head->word_size();
4458     int pos = headpos;
4459     Metachunk* tail = head;
4460     do {
4461       pos = next_matching_chunk(pos, false);
4462       if (pos != headpos) {
4463         Metachunk* c = _pool[pos];
4464         assert(c->is_tagged_free() == false, "Chunk state mismatch");
4465         if (index == _cm.list_index(c->word_size())) {
4466           tail->set_next(c);
4467           c->set_prev(tail);
4468           tail = c;
4469           out->all[num_added] = c;
4470           num_added ++;
4471           size_added += c->word_size();
4472         }
4473       }
4474     } while (num_added < list_size && pos != headpos);
4475     out->head = head;
4476     out->index = index;
4477     out->size = size_added;
4478     out->num = num_added;
4479     return true;
4480   }
4481 
4482   // Take a single random chunk from the ChunkManager.
4483   bool take_single_random_chunk_from_chunkmanager() {
4484     assert_counters();
4485     _cm.locked_verify();
4486     int pos = next_matching_chunk(get_random_position(), true);
4487     if (pos == -1) {
4488       return false;
4489     }
4490     Metachunk* c = _pool[pos];
4491     assert(c->is_tagged_free(), "Chunk state mismatch");
4492     // Note: instead of using ChunkManager::remove_chunk on this one chunk, we call
4493     // ChunkManager::free_chunks_get() with this chunk's word size. We really want
4494     // to exercise ChunkManager::free_chunks_get() because that one gets called for
4495     // normal chunk allocation.
4496     Metachunk* c2 = _cm.free_chunks_get(c->word_size());
4497     assert(c2 != NULL, "Unexpected.");
4498     assert(!c2->is_tagged_free(), "Chunk state mismatch");
4499     assert(c2->next() == NULL && c2->prev() == NULL, "Chunk should be outside of a list.");
4500     _chunks_in_chunkmanager --;
4501     _words_in_chunkmanager -= c->word_size();
4502     assert_counters();
4503     _cm.locked_verify();
4504     return true;
4505   }
4506 
4507   // Returns a single random chunk to the chunk manager. Returns false if that
4508   // was not possible (all chunks are already in the chunk manager).
4509   bool return_single_random_chunk_to_chunkmanager() {
4510     assert_counters();
4511     _cm.locked_verify();
4512     int pos = next_matching_chunk(get_random_position(), false);
4513     if (pos == -1) {
4514       return false;
4515     }
4516     Metachunk* c = _pool[pos];
4517     assert(c->is_tagged_free() == false, "wrong chunk information");
4518     _cm.return_single_chunk(_cm.list_index(c->word_size()), c);
4519     _chunks_in_chunkmanager ++;
4520     _words_in_chunkmanager += c->word_size();
4521     assert(c->is_tagged_free() == true, "wrong chunk information");
4522     assert_counters();
4523     _cm.locked_verify();
4524     return true;
4525   }
4526 
4527   // Return a random chunk list to the chunk manager. Returns the length of the
4528   // returned list.
4529   int return_random_chunk_list_to_chunkmanager(int list_size) {
4530     assert_counters();
4531     _cm.locked_verify();
4532     AChunkList aChunkList;
4533     if (!assemble_random_chunklist(&aChunkList, list_size)) {
4534       return 0;
4535     }
4536     // Before returning chunks are returned, they should be tagged in use.
4537     for (int i = 0; i < aChunkList.num; i ++) {
4538       assert(!aChunkList.all[i]->is_tagged_free(), "chunk state mismatch.");
4539     }
4540     _cm.return_chunk_list(aChunkList.index, aChunkList.head);
4541     _chunks_in_chunkmanager += aChunkList.num;
4542     _words_in_chunkmanager += aChunkList.size;
4543     // After all chunks are returned, check that they are now tagged free.
4544     for (int i = 0; i < aChunkList.num; i ++) {
4545       assert(aChunkList.all[i]->is_tagged_free(), "chunk state mismatch.");
4546     }
4547     assert_counters();
4548     _cm.locked_verify();
4549     return aChunkList.num;
4550   }
4551 
4552 public:
4553 
4554   ChunkManagerReturnTestImpl()
4555     : _vsn(align_up(MediumChunk * num_chunks * 5 * sizeof(MetaWord), Metaspace::reserve_alignment()))
4556     , _cm(SpecializedChunk, SmallChunk, MediumChunk)
4557     , _chunks_in_chunkmanager(0)
4558     , _words_in_chunkmanager(0)
4559   {
4560     MutexLockerEx ml(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
4561     // Allocate virtual space and allocate random chunks. Keep these chunks in the _pool. These chunks are
4562     // "in use", because not yet added to any chunk manager.
4563     _vsn.initialize();
4564     _vsn.expand_by(_vsn.reserved_words(), _vsn.reserved_words());
4565     for (int i = 0; i < num_chunks; i ++) {
4566       const size_t size = get_random_chunk_size();
4567       _pool[i] = _vsn.get_chunk_vs(size);
4568       assert(_pool[i] != NULL, "allocation failed");
4569     }
4570     assert_counters();
4571     _cm.locked_verify();
4572   }
4573 
4574   // Test entry point.
4575   // Return some chunks to the chunk manager (return phase). Take some chunks out (take phase). Repeat.
4576   // Chunks are choosen randomly. Number of chunks to return or taken are choosen randomly, but affected
4577   // by the <phase_length_factor> argument: a factor of 0.0 will cause the test to quickly alternate between
4578   // returning and taking, whereas a factor of 1.0 will take/return all chunks from/to the
4579   // chunks manager, thereby emptying or filling it completely.
4580   void do_test(float phase_length_factor) {
4581     MutexLockerEx ml(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
4582     assert_counters();
4583     // Execute n operations, and operation being the move of a single chunk to/from the chunk manager.
4584     const int num_max_ops = num_chunks * 100;
4585     int num_ops = num_max_ops;
4586     const int average_phase_length = (int)(phase_length_factor * num_chunks);
4587     int num_ops_until_switch = MAX2(1, (average_phase_length + os::random() % 8 - 4));
4588     bool return_phase = true;
4589     while (num_ops > 0) {
4590       int chunks_moved = 0;
4591       if (return_phase) {
4592         // Randomly switch between returning a single chunk or a random length chunk list.
4593         if (os::random() % 2 == 0) {
4594           if (return_single_random_chunk_to_chunkmanager()) {
4595             chunks_moved = 1;
4596           }
4597         } else {
4598           const int list_length = MAX2(1, (os::random() % num_ops_until_switch));
4599           chunks_moved = return_random_chunk_list_to_chunkmanager(list_length);
4600         }
4601       } else {
4602         // Breath out.
4603         if (take_single_random_chunk_from_chunkmanager()) {
4604           chunks_moved = 1;
4605         }
4606       }
4607       num_ops -= chunks_moved;
4608       num_ops_until_switch -= chunks_moved;
4609       if (chunks_moved == 0 || num_ops_until_switch <= 0) {
4610         return_phase = !return_phase;
4611         num_ops_until_switch = MAX2(1, (average_phase_length + os::random() % 8 - 4));
4612       }
4613     }
4614   }
4615 };
4616 
4617 void* setup_chunkmanager_returntests() {
4618   ChunkManagerReturnTestImpl* p = new ChunkManagerReturnTestImpl();
4619   return p;
4620 }
4621 
4622 void teardown_chunkmanager_returntests(void* p) {
4623   delete (ChunkManagerReturnTestImpl*) p;
4624 }
4625 
4626 void run_chunkmanager_returntests(void* p, float phase_length) {
4627   ChunkManagerReturnTestImpl* test = (ChunkManagerReturnTestImpl*) p;
4628   test->do_test(phase_length);
4629 }
4630 
4631 // The following test is placed here instead of a gtest / unittest file
4632 // because the ChunkManager class is only available in this file.
4633 class SpaceManagerTest : AllStatic {
4634   friend void SpaceManager_test_adjust_initial_chunk_size();
4635 
4636   static void test_adjust_initial_chunk_size(bool is_class) {
4637     const size_t smallest = SpaceManager::smallest_chunk_size(is_class);
4638     const size_t normal   = SpaceManager::small_chunk_size(is_class);
4639     const size_t medium   = SpaceManager::medium_chunk_size(is_class);
4640 
4641 #define test_adjust_initial_chunk_size(value, expected, is_class_value)          \
4642     do {                                                                         \
4643       size_t v = value;                                                          \
4644       size_t e = expected;                                                       \
4645       assert(SpaceManager::adjust_initial_chunk_size(v, (is_class_value)) == e,  \
4646              "Expected: " SIZE_FORMAT " got: " SIZE_FORMAT, e, v);               \
4647     } while (0)
4648 
4649     // Smallest (specialized)
4650     test_adjust_initial_chunk_size(1,            smallest, is_class);
4651     test_adjust_initial_chunk_size(smallest - 1, smallest, is_class);
4652     test_adjust_initial_chunk_size(smallest,     smallest, is_class);
4653 
4654     // Small
4655     test_adjust_initial_chunk_size(smallest + 1, normal, is_class);
4656     test_adjust_initial_chunk_size(normal - 1,   normal, is_class);
4657     test_adjust_initial_chunk_size(normal,       normal, is_class);
4658 
4659     // Medium
4660     test_adjust_initial_chunk_size(normal + 1, medium, is_class);
4661     test_adjust_initial_chunk_size(medium - 1, medium, is_class);
4662     test_adjust_initial_chunk_size(medium,     medium, is_class);
4663 
4664     // Humongous
4665     test_adjust_initial_chunk_size(medium + 1, medium + 1, is_class);
4666 
4667 #undef test_adjust_initial_chunk_size
4668   }
4669 
4670   static void test_adjust_initial_chunk_size() {
4671     test_adjust_initial_chunk_size(false);
4672     test_adjust_initial_chunk_size(true);
4673   }
4674 };
4675 
4676 void SpaceManager_test_adjust_initial_chunk_size() {
4677   SpaceManagerTest::test_adjust_initial_chunk_size();
4678 }
4679 
4680 #endif // ASSERT