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