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