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