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