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