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