Fri, 22 Mar 2013 10:32:21 +0100
Merge
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/binaryTreeDictionary.hpp"
27 #include "memory/freeList.hpp"
28 #include "memory/collectorPolicy.hpp"
29 #include "memory/filemap.hpp"
30 #include "memory/freeList.hpp"
31 #include "memory/metablock.hpp"
32 #include "memory/metachunk.hpp"
33 #include "memory/metaspace.hpp"
34 #include "memory/metaspaceShared.hpp"
35 #include "memory/resourceArea.hpp"
36 #include "memory/universe.hpp"
37 #include "runtime/globals.hpp"
38 #include "runtime/mutex.hpp"
39 #include "runtime/orderAccess.hpp"
40 #include "services/memTracker.hpp"
41 #include "utilities/copy.hpp"
42 #include "utilities/debug.hpp"
44 typedef BinaryTreeDictionary<Metablock, FreeList> BlockTreeDictionary;
45 typedef BinaryTreeDictionary<Metachunk, FreeList> ChunkTreeDictionary;
46 // Define this macro to enable slow integrity checking of
47 // the free chunk lists
48 const bool metaspace_slow_verify = false;
51 // Parameters for stress mode testing
52 const uint metadata_deallocate_a_lot_block = 10;
53 const uint metadata_deallocate_a_lock_chunk = 3;
54 size_t const allocation_from_dictionary_limit = 64 * K;
56 MetaWord* last_allocated = 0;
58 // Used in declarations in SpaceManager and ChunkManager
59 enum ChunkIndex {
60 ZeroIndex = 0,
61 SpecializedIndex = ZeroIndex,
62 SmallIndex = SpecializedIndex + 1,
63 MediumIndex = SmallIndex + 1,
64 HumongousIndex = MediumIndex + 1,
65 NumberOfFreeLists = 3,
66 NumberOfInUseLists = 4
67 };
69 enum ChunkSizes { // in words.
70 ClassSpecializedChunk = 128,
71 SpecializedChunk = 128,
72 ClassSmallChunk = 256,
73 SmallChunk = 512,
74 ClassMediumChunk = 1 * K,
75 MediumChunk = 8 * K,
76 HumongousChunkGranularity = 8
77 };
79 static ChunkIndex next_chunk_index(ChunkIndex i) {
80 assert(i < NumberOfInUseLists, "Out of bound");
81 return (ChunkIndex) (i+1);
82 }
84 // Originally _capacity_until_GC was set to MetaspaceSize here but
85 // the default MetaspaceSize before argument processing was being
86 // used which was not the desired value. See the code
87 // in should_expand() to see how the initialization is handled
88 // now.
89 size_t MetaspaceGC::_capacity_until_GC = 0;
90 bool MetaspaceGC::_expand_after_GC = false;
91 uint MetaspaceGC::_shrink_factor = 0;
92 bool MetaspaceGC::_should_concurrent_collect = false;
94 // Blocks of space for metadata are allocated out of Metachunks.
95 //
96 // Metachunk are allocated out of MetadataVirtualspaces and once
97 // allocated there is no explicit link between a Metachunk and
98 // the MetadataVirtualspaces from which it was allocated.
99 //
100 // Each SpaceManager maintains a
101 // list of the chunks it is using and the current chunk. The current
102 // chunk is the chunk from which allocations are done. Space freed in
103 // a chunk is placed on the free list of blocks (BlockFreelist) and
104 // reused from there.
106 // Pointer to list of Metachunks.
107 class ChunkList VALUE_OBJ_CLASS_SPEC {
108 // List of free chunks
109 Metachunk* _head;
111 public:
112 // Constructor
113 ChunkList() : _head(NULL) {}
115 // Accessors
116 Metachunk* head() { return _head; }
117 void set_head(Metachunk* v) { _head = v; }
119 // Link at head of the list
120 void add_at_head(Metachunk* head, Metachunk* tail);
121 void add_at_head(Metachunk* head);
123 size_t sum_list_size();
124 size_t sum_list_count();
125 size_t sum_list_capacity();
126 };
128 // Manages the global free lists of chunks.
129 // Has three lists of free chunks, and a total size and
130 // count that includes all three
132 class ChunkManager VALUE_OBJ_CLASS_SPEC {
134 // Free list of chunks of different sizes.
135 // SmallChunk
136 // MediumChunk
137 // HumongousChunk
138 ChunkList _free_chunks[NumberOfFreeLists];
141 // HumongousChunk
142 ChunkTreeDictionary _humongous_dictionary;
144 // ChunkManager in all lists of this type
145 size_t _free_chunks_total;
146 size_t _free_chunks_count;
148 void dec_free_chunks_total(size_t v) {
149 assert(_free_chunks_count > 0 &&
150 _free_chunks_total > 0,
151 "About to go negative");
152 Atomic::add_ptr(-1, &_free_chunks_count);
153 jlong minus_v = (jlong) - (jlong) v;
154 Atomic::add_ptr(minus_v, &_free_chunks_total);
155 }
157 // Debug support
159 size_t sum_free_chunks();
160 size_t sum_free_chunks_count();
162 void locked_verify_free_chunks_total();
163 void slow_locked_verify_free_chunks_total() {
164 if (metaspace_slow_verify) {
165 locked_verify_free_chunks_total();
166 }
167 }
168 void locked_verify_free_chunks_count();
169 void slow_locked_verify_free_chunks_count() {
170 if (metaspace_slow_verify) {
171 locked_verify_free_chunks_count();
172 }
173 }
174 void verify_free_chunks_count();
176 public:
178 ChunkManager() : _free_chunks_total(0), _free_chunks_count(0) {}
180 // add or delete (return) a chunk to the global freelist.
181 Metachunk* chunk_freelist_allocate(size_t word_size);
182 void chunk_freelist_deallocate(Metachunk* chunk);
184 // Map a size to a list index assuming that there are lists
185 // for special, small, medium, and humongous chunks.
186 static ChunkIndex list_index(size_t size);
188 // Total of the space in the free chunks list
189 size_t free_chunks_total();
190 size_t free_chunks_total_in_bytes();
192 // Number of chunks in the free chunks list
193 size_t free_chunks_count();
195 void inc_free_chunks_total(size_t v, size_t count = 1) {
196 Atomic::add_ptr(count, &_free_chunks_count);
197 Atomic::add_ptr(v, &_free_chunks_total);
198 }
199 ChunkTreeDictionary* humongous_dictionary() {
200 return &_humongous_dictionary;
201 }
203 ChunkList* free_chunks(ChunkIndex index);
205 // Returns the list for the given chunk word size.
206 ChunkList* find_free_chunks_list(size_t word_size);
208 // Add and remove from a list by size. Selects
209 // list based on size of chunk.
210 void free_chunks_put(Metachunk* chuck);
211 Metachunk* free_chunks_get(size_t chunk_word_size);
213 // Debug support
214 void verify();
215 void slow_verify() {
216 if (metaspace_slow_verify) {
217 verify();
218 }
219 }
220 void locked_verify();
221 void slow_locked_verify() {
222 if (metaspace_slow_verify) {
223 locked_verify();
224 }
225 }
226 void verify_free_chunks_total();
228 void locked_print_free_chunks(outputStream* st);
229 void locked_print_sum_free_chunks(outputStream* st);
231 void print_on(outputStream* st);
232 };
235 // Used to manage the free list of Metablocks (a block corresponds
236 // to the allocation of a quantum of metadata).
237 class BlockFreelist VALUE_OBJ_CLASS_SPEC {
238 BlockTreeDictionary* _dictionary;
239 static Metablock* initialize_free_chunk(MetaWord* p, size_t word_size);
241 // Accessors
242 BlockTreeDictionary* dictionary() const { return _dictionary; }
244 public:
245 BlockFreelist();
246 ~BlockFreelist();
248 // Get and return a block to the free list
249 MetaWord* get_block(size_t word_size);
250 void return_block(MetaWord* p, size_t word_size);
252 size_t total_size() {
253 if (dictionary() == NULL) {
254 return 0;
255 } else {
256 return dictionary()->total_size();
257 }
258 }
260 void print_on(outputStream* st) const;
261 };
263 class VirtualSpaceNode : public CHeapObj<mtClass> {
264 friend class VirtualSpaceList;
266 // Link to next VirtualSpaceNode
267 VirtualSpaceNode* _next;
269 // total in the VirtualSpace
270 MemRegion _reserved;
271 ReservedSpace _rs;
272 VirtualSpace _virtual_space;
273 MetaWord* _top;
275 // Convenience functions for logical bottom and end
276 MetaWord* bottom() const { return (MetaWord*) _virtual_space.low(); }
277 MetaWord* end() const { return (MetaWord*) _virtual_space.high(); }
279 // Convenience functions to access the _virtual_space
280 char* low() const { return virtual_space()->low(); }
281 char* high() const { return virtual_space()->high(); }
283 public:
285 VirtualSpaceNode(size_t byte_size);
286 VirtualSpaceNode(ReservedSpace rs) : _top(NULL), _next(NULL), _rs(rs) {}
287 ~VirtualSpaceNode();
289 // address of next available space in _virtual_space;
290 // Accessors
291 VirtualSpaceNode* next() { return _next; }
292 void set_next(VirtualSpaceNode* v) { _next = v; }
294 void set_reserved(MemRegion const v) { _reserved = v; }
295 void set_top(MetaWord* v) { _top = v; }
297 // Accessors
298 MemRegion* reserved() { return &_reserved; }
299 VirtualSpace* virtual_space() const { return (VirtualSpace*) &_virtual_space; }
301 // Returns true if "word_size" is available in the virtual space
302 bool is_available(size_t word_size) { return _top + word_size <= end(); }
304 MetaWord* top() const { return _top; }
305 void inc_top(size_t word_size) { _top += word_size; }
307 // used and capacity in this single entry in the list
308 size_t used_words_in_vs() const;
309 size_t capacity_words_in_vs() const;
311 bool initialize();
313 // get space from the virtual space
314 Metachunk* take_from_committed(size_t chunk_word_size);
316 // Allocate a chunk from the virtual space and return it.
317 Metachunk* get_chunk_vs(size_t chunk_word_size);
318 Metachunk* get_chunk_vs_with_expand(size_t chunk_word_size);
320 // Expands/shrinks the committed space in a virtual space. Delegates
321 // to Virtualspace
322 bool expand_by(size_t words, bool pre_touch = false);
323 bool shrink_by(size_t words);
325 #ifdef ASSERT
326 // Debug support
327 static void verify_virtual_space_total();
328 static void verify_virtual_space_count();
329 void mangle();
330 #endif
332 void print_on(outputStream* st) const;
333 };
335 // byte_size is the size of the associated virtualspace.
336 VirtualSpaceNode::VirtualSpaceNode(size_t byte_size) : _top(NULL), _next(NULL), _rs(0) {
337 // align up to vm allocation granularity
338 byte_size = align_size_up(byte_size, os::vm_allocation_granularity());
340 // This allocates memory with mmap. For DumpSharedspaces, allocate the
341 // space at low memory so that other shared images don't conflict.
342 // This is the same address as memory needed for UseCompressedOops but
343 // compressed oops don't work with CDS (offsets in metadata are wrong), so
344 // borrow the same address.
345 if (DumpSharedSpaces) {
346 char* shared_base = (char*)HeapBaseMinAddress;
347 _rs = ReservedSpace(byte_size, 0, false, shared_base, 0);
348 if (_rs.is_reserved()) {
349 assert(_rs.base() == shared_base, "should match");
350 } else {
351 // If we are dumping the heap, then allocate a wasted block of address
352 // space in order to push the heap to a lower address. This extra
353 // address range allows for other (or larger) libraries to be loaded
354 // without them occupying the space required for the shared spaces.
355 uintx reserved = 0;
356 uintx block_size = 64*1024*1024;
357 while (reserved < SharedDummyBlockSize) {
358 char* dummy = os::reserve_memory(block_size);
359 reserved += block_size;
360 }
361 _rs = ReservedSpace(byte_size);
362 }
363 MetaspaceShared::set_shared_rs(&_rs);
364 } else {
365 _rs = ReservedSpace(byte_size);
366 }
368 MemTracker::record_virtual_memory_type((address)_rs.base(), mtClass);
369 }
371 // List of VirtualSpaces for metadata allocation.
372 // It has a _next link for singly linked list and a MemRegion
373 // for total space in the VirtualSpace.
374 class VirtualSpaceList : public CHeapObj<mtClass> {
375 friend class VirtualSpaceNode;
377 enum VirtualSpaceSizes {
378 VirtualSpaceSize = 256 * K
379 };
381 // Global list of virtual spaces
382 // Head of the list
383 VirtualSpaceNode* _virtual_space_list;
384 // virtual space currently being used for allocations
385 VirtualSpaceNode* _current_virtual_space;
386 // Free chunk list for all other metadata
387 ChunkManager _chunk_manager;
389 // Can this virtual list allocate >1 spaces? Also, used to determine
390 // whether to allocate unlimited small chunks in this virtual space
391 bool _is_class;
392 bool can_grow() const { return !is_class() || !UseCompressedKlassPointers; }
394 // Sum of space in all virtual spaces and number of virtual spaces
395 size_t _virtual_space_total;
396 size_t _virtual_space_count;
398 ~VirtualSpaceList();
400 VirtualSpaceNode* virtual_space_list() const { return _virtual_space_list; }
402 void set_virtual_space_list(VirtualSpaceNode* v) {
403 _virtual_space_list = v;
404 }
405 void set_current_virtual_space(VirtualSpaceNode* v) {
406 _current_virtual_space = v;
407 }
409 void link_vs(VirtualSpaceNode* new_entry, size_t vs_word_size);
411 // Get another virtual space and add it to the list. This
412 // is typically prompted by a failed attempt to allocate a chunk
413 // and is typically followed by the allocation of a chunk.
414 bool grow_vs(size_t vs_word_size);
416 public:
417 VirtualSpaceList(size_t word_size);
418 VirtualSpaceList(ReservedSpace rs);
420 Metachunk* get_new_chunk(size_t word_size,
421 size_t grow_chunks_by_words,
422 size_t medium_chunk_bunch);
424 // Get the first chunk for a Metaspace. Used for
425 // special cases such as the boot class loader, reflection
426 // class loader and anonymous class loader.
427 Metachunk* get_initialization_chunk(size_t word_size, size_t chunk_bunch);
429 VirtualSpaceNode* current_virtual_space() {
430 return _current_virtual_space;
431 }
433 ChunkManager* chunk_manager() { return &_chunk_manager; }
434 bool is_class() const { return _is_class; }
436 // Allocate the first virtualspace.
437 void initialize(size_t word_size);
439 size_t virtual_space_total() { return _virtual_space_total; }
440 void inc_virtual_space_total(size_t v) {
441 Atomic::add_ptr(v, &_virtual_space_total);
442 }
444 size_t virtual_space_count() { return _virtual_space_count; }
445 void inc_virtual_space_count() {
446 Atomic::inc_ptr(&_virtual_space_count);
447 }
449 // Used and capacity in the entire list of virtual spaces.
450 // These are global values shared by all Metaspaces
451 size_t capacity_words_sum();
452 size_t capacity_bytes_sum() { return capacity_words_sum() * BytesPerWord; }
453 size_t used_words_sum();
454 size_t used_bytes_sum() { return used_words_sum() * BytesPerWord; }
456 bool contains(const void *ptr);
458 void print_on(outputStream* st) const;
460 class VirtualSpaceListIterator : public StackObj {
461 VirtualSpaceNode* _virtual_spaces;
462 public:
463 VirtualSpaceListIterator(VirtualSpaceNode* virtual_spaces) :
464 _virtual_spaces(virtual_spaces) {}
466 bool repeat() {
467 return _virtual_spaces != NULL;
468 }
470 VirtualSpaceNode* get_next() {
471 VirtualSpaceNode* result = _virtual_spaces;
472 if (_virtual_spaces != NULL) {
473 _virtual_spaces = _virtual_spaces->next();
474 }
475 return result;
476 }
477 };
478 };
480 class Metadebug : AllStatic {
481 // Debugging support for Metaspaces
482 static int _deallocate_block_a_lot_count;
483 static int _deallocate_chunk_a_lot_count;
484 static int _allocation_fail_alot_count;
486 public:
487 static int deallocate_block_a_lot_count() {
488 return _deallocate_block_a_lot_count;
489 }
490 static void set_deallocate_block_a_lot_count(int v) {
491 _deallocate_block_a_lot_count = v;
492 }
493 static void inc_deallocate_block_a_lot_count() {
494 _deallocate_block_a_lot_count++;
495 }
496 static int deallocate_chunk_a_lot_count() {
497 return _deallocate_chunk_a_lot_count;
498 }
499 static void reset_deallocate_chunk_a_lot_count() {
500 _deallocate_chunk_a_lot_count = 1;
501 }
502 static void inc_deallocate_chunk_a_lot_count() {
503 _deallocate_chunk_a_lot_count++;
504 }
506 static void init_allocation_fail_alot_count();
507 #ifdef ASSERT
508 static bool test_metadata_failure();
509 #endif
511 static void deallocate_chunk_a_lot(SpaceManager* sm,
512 size_t chunk_word_size);
513 static void deallocate_block_a_lot(SpaceManager* sm,
514 size_t chunk_word_size);
516 };
518 int Metadebug::_deallocate_block_a_lot_count = 0;
519 int Metadebug::_deallocate_chunk_a_lot_count = 0;
520 int Metadebug::_allocation_fail_alot_count = 0;
522 // SpaceManager - used by Metaspace to handle allocations
523 class SpaceManager : public CHeapObj<mtClass> {
524 friend class Metaspace;
525 friend class Metadebug;
527 private:
529 // protects allocations and contains.
530 Mutex* const _lock;
532 // Chunk related size
533 size_t _medium_chunk_bunch;
535 // List of chunks in use by this SpaceManager. Allocations
536 // are done from the current chunk. The list is used for deallocating
537 // chunks when the SpaceManager is freed.
538 Metachunk* _chunks_in_use[NumberOfInUseLists];
539 Metachunk* _current_chunk;
541 // Virtual space where allocation comes from.
542 VirtualSpaceList* _vs_list;
544 // Number of small chunks to allocate to a manager
545 // If class space manager, small chunks are unlimited
546 static uint const _small_chunk_limit;
547 bool has_small_chunk_limit() { return !vs_list()->is_class(); }
549 // Sum of all space in allocated chunks
550 size_t _allocation_total;
552 // Free lists of blocks are per SpaceManager since they
553 // are assumed to be in chunks in use by the SpaceManager
554 // and all chunks in use by a SpaceManager are freed when
555 // the class loader using the SpaceManager is collected.
556 BlockFreelist _block_freelists;
558 // protects virtualspace and chunk expansions
559 static const char* _expand_lock_name;
560 static const int _expand_lock_rank;
561 static Mutex* const _expand_lock;
563 private:
564 // Accessors
565 Metachunk* chunks_in_use(ChunkIndex index) const { return _chunks_in_use[index]; }
566 void set_chunks_in_use(ChunkIndex index, Metachunk* v) { _chunks_in_use[index] = v; }
568 BlockFreelist* block_freelists() const {
569 return (BlockFreelist*) &_block_freelists;
570 }
572 VirtualSpaceList* vs_list() const { return _vs_list; }
574 Metachunk* current_chunk() const { return _current_chunk; }
575 void set_current_chunk(Metachunk* v) {
576 _current_chunk = v;
577 }
579 Metachunk* find_current_chunk(size_t word_size);
581 // Add chunk to the list of chunks in use
582 void add_chunk(Metachunk* v, bool make_current);
584 Mutex* lock() const { return _lock; }
586 const char* chunk_size_name(ChunkIndex index) const;
588 protected:
589 void initialize();
591 public:
592 SpaceManager(Mutex* lock,
593 VirtualSpaceList* vs_list);
594 ~SpaceManager();
596 enum ChunkMultiples {
597 MediumChunkMultiple = 4
598 };
600 // Accessors
601 size_t specialized_chunk_size() { return SpecializedChunk; }
602 size_t small_chunk_size() { return (size_t) vs_list()->is_class() ? ClassSmallChunk : SmallChunk; }
603 size_t medium_chunk_size() { return (size_t) vs_list()->is_class() ? ClassMediumChunk : MediumChunk; }
604 size_t medium_chunk_bunch() { return medium_chunk_size() * MediumChunkMultiple; }
606 size_t allocation_total() const { return _allocation_total; }
607 void inc_allocation_total(size_t v) { Atomic::add_ptr(v, &_allocation_total); }
608 bool is_humongous(size_t word_size) { return word_size > medium_chunk_size(); }
610 static Mutex* expand_lock() { return _expand_lock; }
612 // Set the sizes for the initial chunks.
613 void get_initial_chunk_sizes(Metaspace::MetaspaceType type,
614 size_t* chunk_word_size,
615 size_t* class_chunk_word_size);
617 size_t sum_capacity_in_chunks_in_use() const;
618 size_t sum_used_in_chunks_in_use() const;
619 size_t sum_free_in_chunks_in_use() const;
620 size_t sum_waste_in_chunks_in_use() const;
621 size_t sum_waste_in_chunks_in_use(ChunkIndex index ) const;
623 size_t sum_count_in_chunks_in_use();
624 size_t sum_count_in_chunks_in_use(ChunkIndex i);
626 Metachunk* get_new_chunk(size_t word_size, size_t grow_chunks_by_words);
628 // Block allocation and deallocation.
629 // Allocates a block from the current chunk
630 MetaWord* allocate(size_t word_size);
632 // Helper for allocations
633 MetaWord* allocate_work(size_t word_size);
635 // Returns a block to the per manager freelist
636 void deallocate(MetaWord* p, size_t word_size);
638 // Based on the allocation size and a minimum chunk size,
639 // returned chunk size (for expanding space for chunk allocation).
640 size_t calc_chunk_size(size_t allocation_word_size);
642 // Called when an allocation from the current chunk fails.
643 // Gets a new chunk (may require getting a new virtual space),
644 // and allocates from that chunk.
645 MetaWord* grow_and_allocate(size_t word_size);
647 // debugging support.
649 void dump(outputStream* const out) const;
650 void print_on(outputStream* st) const;
651 void locked_print_chunks_in_use_on(outputStream* st) const;
653 void verify();
654 void verify_chunk_size(Metachunk* chunk);
655 NOT_PRODUCT(void mangle_freed_chunks();)
656 #ifdef ASSERT
657 void verify_allocation_total();
658 #endif
659 };
661 uint const SpaceManager::_small_chunk_limit = 4;
663 const char* SpaceManager::_expand_lock_name =
664 "SpaceManager chunk allocation lock";
665 const int SpaceManager::_expand_lock_rank = Monitor::leaf - 1;
666 Mutex* const SpaceManager::_expand_lock =
667 new Mutex(SpaceManager::_expand_lock_rank,
668 SpaceManager::_expand_lock_name,
669 Mutex::_allow_vm_block_flag);
671 // BlockFreelist methods
673 BlockFreelist::BlockFreelist() : _dictionary(NULL) {}
675 BlockFreelist::~BlockFreelist() {
676 if (_dictionary != NULL) {
677 if (Verbose && TraceMetadataChunkAllocation) {
678 _dictionary->print_free_lists(gclog_or_tty);
679 }
680 delete _dictionary;
681 }
682 }
684 Metablock* BlockFreelist::initialize_free_chunk(MetaWord* p, size_t word_size) {
685 Metablock* block = (Metablock*) p;
686 block->set_word_size(word_size);
687 block->set_prev(NULL);
688 block->set_next(NULL);
690 return block;
691 }
693 void BlockFreelist::return_block(MetaWord* p, size_t word_size) {
694 Metablock* free_chunk = initialize_free_chunk(p, word_size);
695 if (dictionary() == NULL) {
696 _dictionary = new BlockTreeDictionary();
697 }
698 dictionary()->return_chunk(free_chunk);
699 }
701 MetaWord* BlockFreelist::get_block(size_t word_size) {
702 if (dictionary() == NULL) {
703 return NULL;
704 }
706 if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
707 // Dark matter. Too small for dictionary.
708 return NULL;
709 }
711 Metablock* free_block =
712 dictionary()->get_chunk(word_size, FreeBlockDictionary<Metablock>::exactly);
713 if (free_block == NULL) {
714 return NULL;
715 }
717 return (MetaWord*) free_block;
718 }
720 void BlockFreelist::print_on(outputStream* st) const {
721 if (dictionary() == NULL) {
722 return;
723 }
724 dictionary()->print_free_lists(st);
725 }
727 // VirtualSpaceNode methods
729 VirtualSpaceNode::~VirtualSpaceNode() {
730 _rs.release();
731 }
733 size_t VirtualSpaceNode::used_words_in_vs() const {
734 return pointer_delta(top(), bottom(), sizeof(MetaWord));
735 }
737 // Space committed in the VirtualSpace
738 size_t VirtualSpaceNode::capacity_words_in_vs() const {
739 return pointer_delta(end(), bottom(), sizeof(MetaWord));
740 }
743 // Allocates the chunk from the virtual space only.
744 // This interface is also used internally for debugging. Not all
745 // chunks removed here are necessarily used for allocation.
746 Metachunk* VirtualSpaceNode::take_from_committed(size_t chunk_word_size) {
747 // Bottom of the new chunk
748 MetaWord* chunk_limit = top();
749 assert(chunk_limit != NULL, "Not safe to call this method");
751 if (!is_available(chunk_word_size)) {
752 if (TraceMetadataChunkAllocation) {
753 tty->print("VirtualSpaceNode::take_from_committed() not available %d words ", chunk_word_size);
754 // Dump some information about the virtual space that is nearly full
755 print_on(tty);
756 }
757 return NULL;
758 }
760 // Take the space (bump top on the current virtual space).
761 inc_top(chunk_word_size);
763 // Point the chunk at the space
764 Metachunk* result = Metachunk::initialize(chunk_limit, chunk_word_size);
765 return result;
766 }
769 // Expand the virtual space (commit more of the reserved space)
770 bool VirtualSpaceNode::expand_by(size_t words, bool pre_touch) {
771 size_t bytes = words * BytesPerWord;
772 bool result = virtual_space()->expand_by(bytes, pre_touch);
773 if (TraceMetavirtualspaceAllocation && !result) {
774 gclog_or_tty->print_cr("VirtualSpaceNode::expand_by() failed "
775 "for byte size " SIZE_FORMAT, bytes);
776 virtual_space()->print();
777 }
778 return result;
779 }
781 // Shrink the virtual space (commit more of the reserved space)
782 bool VirtualSpaceNode::shrink_by(size_t words) {
783 size_t bytes = words * BytesPerWord;
784 virtual_space()->shrink_by(bytes);
785 return true;
786 }
788 // Add another chunk to the chunk list.
790 Metachunk* VirtualSpaceNode::get_chunk_vs(size_t chunk_word_size) {
791 assert_lock_strong(SpaceManager::expand_lock());
792 Metachunk* result = NULL;
794 return take_from_committed(chunk_word_size);
795 }
797 Metachunk* VirtualSpaceNode::get_chunk_vs_with_expand(size_t chunk_word_size) {
798 assert_lock_strong(SpaceManager::expand_lock());
800 Metachunk* new_chunk = get_chunk_vs(chunk_word_size);
802 if (new_chunk == NULL) {
803 // Only a small part of the virtualspace is committed when first
804 // allocated so committing more here can be expected.
805 size_t page_size_words = os::vm_page_size() / BytesPerWord;
806 size_t aligned_expand_vs_by_words = align_size_up(chunk_word_size,
807 page_size_words);
808 expand_by(aligned_expand_vs_by_words, false);
809 new_chunk = get_chunk_vs(chunk_word_size);
810 }
811 return new_chunk;
812 }
814 bool VirtualSpaceNode::initialize() {
816 if (!_rs.is_reserved()) {
817 return false;
818 }
820 // An allocation out of this Virtualspace that is larger
821 // than an initial commit size can waste that initial committed
822 // space.
823 size_t committed_byte_size = 0;
824 bool result = virtual_space()->initialize(_rs, committed_byte_size);
825 if (result) {
826 set_top((MetaWord*)virtual_space()->low());
827 set_reserved(MemRegion((HeapWord*)_rs.base(),
828 (HeapWord*)(_rs.base() + _rs.size())));
830 assert(reserved()->start() == (HeapWord*) _rs.base(),
831 err_msg("Reserved start was not set properly " PTR_FORMAT
832 " != " PTR_FORMAT, reserved()->start(), _rs.base()));
833 assert(reserved()->word_size() == _rs.size() / BytesPerWord,
834 err_msg("Reserved size was not set properly " SIZE_FORMAT
835 " != " SIZE_FORMAT, reserved()->word_size(),
836 _rs.size() / BytesPerWord));
837 }
839 return result;
840 }
842 void VirtualSpaceNode::print_on(outputStream* st) const {
843 size_t used = used_words_in_vs();
844 size_t capacity = capacity_words_in_vs();
845 VirtualSpace* vs = virtual_space();
846 st->print_cr(" space @ " PTR_FORMAT " " SIZE_FORMAT "K, %3d%% used "
847 "[" PTR_FORMAT ", " PTR_FORMAT ", "
848 PTR_FORMAT ", " PTR_FORMAT ")",
849 vs, capacity / K,
850 capacity == 0 ? 0 : used * 100 / capacity,
851 bottom(), top(), end(),
852 vs->high_boundary());
853 }
855 #ifdef ASSERT
856 void VirtualSpaceNode::mangle() {
857 size_t word_size = capacity_words_in_vs();
858 Copy::fill_to_words((HeapWord*) low(), word_size, 0xf1f1f1f1);
859 }
860 #endif // ASSERT
862 // VirtualSpaceList methods
863 // Space allocated from the VirtualSpace
865 VirtualSpaceList::~VirtualSpaceList() {
866 VirtualSpaceListIterator iter(virtual_space_list());
867 while (iter.repeat()) {
868 VirtualSpaceNode* vsl = iter.get_next();
869 delete vsl;
870 }
871 }
873 size_t VirtualSpaceList::used_words_sum() {
874 size_t allocated_by_vs = 0;
875 VirtualSpaceListIterator iter(virtual_space_list());
876 while (iter.repeat()) {
877 VirtualSpaceNode* vsl = iter.get_next();
878 // Sum used region [bottom, top) in each virtualspace
879 allocated_by_vs += vsl->used_words_in_vs();
880 }
881 assert(allocated_by_vs >= chunk_manager()->free_chunks_total(),
882 err_msg("Total in free chunks " SIZE_FORMAT
883 " greater than total from virtual_spaces " SIZE_FORMAT,
884 allocated_by_vs, chunk_manager()->free_chunks_total()));
885 size_t used =
886 allocated_by_vs - chunk_manager()->free_chunks_total();
887 return used;
888 }
890 // Space available in all MetadataVirtualspaces allocated
891 // for metadata. This is the upper limit on the capacity
892 // of chunks allocated out of all the MetadataVirtualspaces.
893 size_t VirtualSpaceList::capacity_words_sum() {
894 size_t capacity = 0;
895 VirtualSpaceListIterator iter(virtual_space_list());
896 while (iter.repeat()) {
897 VirtualSpaceNode* vsl = iter.get_next();
898 capacity += vsl->capacity_words_in_vs();
899 }
900 return capacity;
901 }
903 VirtualSpaceList::VirtualSpaceList(size_t word_size ) :
904 _is_class(false),
905 _virtual_space_list(NULL),
906 _current_virtual_space(NULL),
907 _virtual_space_total(0),
908 _virtual_space_count(0) {
909 MutexLockerEx cl(SpaceManager::expand_lock(),
910 Mutex::_no_safepoint_check_flag);
911 bool initialization_succeeded = grow_vs(word_size);
913 assert(initialization_succeeded,
914 " VirtualSpaceList initialization should not fail");
915 }
917 VirtualSpaceList::VirtualSpaceList(ReservedSpace rs) :
918 _is_class(true),
919 _virtual_space_list(NULL),
920 _current_virtual_space(NULL),
921 _virtual_space_total(0),
922 _virtual_space_count(0) {
923 MutexLockerEx cl(SpaceManager::expand_lock(),
924 Mutex::_no_safepoint_check_flag);
925 VirtualSpaceNode* class_entry = new VirtualSpaceNode(rs);
926 bool succeeded = class_entry->initialize();
927 assert(succeeded, " VirtualSpaceList initialization should not fail");
928 link_vs(class_entry, rs.size()/BytesPerWord);
929 }
931 // Allocate another meta virtual space and add it to the list.
932 bool VirtualSpaceList::grow_vs(size_t vs_word_size) {
933 assert_lock_strong(SpaceManager::expand_lock());
934 if (vs_word_size == 0) {
935 return false;
936 }
937 // Reserve the space
938 size_t vs_byte_size = vs_word_size * BytesPerWord;
939 assert(vs_byte_size % os::vm_page_size() == 0, "Not aligned");
941 // Allocate the meta virtual space and initialize it.
942 VirtualSpaceNode* new_entry = new VirtualSpaceNode(vs_byte_size);
943 if (!new_entry->initialize()) {
944 delete new_entry;
945 return false;
946 } else {
947 // ensure lock-free iteration sees fully initialized node
948 OrderAccess::storestore();
949 link_vs(new_entry, vs_word_size);
950 return true;
951 }
952 }
954 void VirtualSpaceList::link_vs(VirtualSpaceNode* new_entry, size_t vs_word_size) {
955 if (virtual_space_list() == NULL) {
956 set_virtual_space_list(new_entry);
957 } else {
958 current_virtual_space()->set_next(new_entry);
959 }
960 set_current_virtual_space(new_entry);
961 inc_virtual_space_total(vs_word_size);
962 inc_virtual_space_count();
963 #ifdef ASSERT
964 new_entry->mangle();
965 #endif
966 if (TraceMetavirtualspaceAllocation && Verbose) {
967 VirtualSpaceNode* vsl = current_virtual_space();
968 vsl->print_on(tty);
969 }
970 }
972 Metachunk* VirtualSpaceList::get_new_chunk(size_t word_size,
973 size_t grow_chunks_by_words,
974 size_t medium_chunk_bunch) {
976 // Get a chunk from the chunk freelist
977 Metachunk* next = chunk_manager()->chunk_freelist_allocate(grow_chunks_by_words);
979 // Allocate a chunk out of the current virtual space.
980 if (next == NULL) {
981 next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
982 }
984 if (next == NULL) {
985 // Not enough room in current virtual space. Try to commit
986 // more space.
987 size_t expand_vs_by_words = MAX2(medium_chunk_bunch,
988 grow_chunks_by_words);
989 size_t page_size_words = os::vm_page_size() / BytesPerWord;
990 size_t aligned_expand_vs_by_words = align_size_up(expand_vs_by_words,
991 page_size_words);
992 bool vs_expanded =
993 current_virtual_space()->expand_by(aligned_expand_vs_by_words, false);
994 if (!vs_expanded) {
995 // Should the capacity of the metaspaces be expanded for
996 // this allocation? If it's the virtual space for classes and is
997 // being used for CompressedHeaders, don't allocate a new virtualspace.
998 if (can_grow() && MetaspaceGC::should_expand(this, word_size)) {
999 // Get another virtual space.
1000 size_t grow_vs_words =
1001 MAX2((size_t)VirtualSpaceSize, aligned_expand_vs_by_words);
1002 if (grow_vs(grow_vs_words)) {
1003 // Got it. It's on the list now. Get a chunk from it.
1004 next = current_virtual_space()->get_chunk_vs_with_expand(grow_chunks_by_words);
1005 }
1006 } else {
1007 // Allocation will fail and induce a GC
1008 if (TraceMetadataChunkAllocation && Verbose) {
1009 gclog_or_tty->print_cr("VirtualSpaceList::get_new_chunk():"
1010 " Fail instead of expand the metaspace");
1011 }
1012 }
1013 } else {
1014 // The virtual space expanded, get a new chunk
1015 next = current_virtual_space()->get_chunk_vs(grow_chunks_by_words);
1016 assert(next != NULL, "Just expanded, should succeed");
1017 }
1018 }
1020 assert(next == NULL || (next->next() == NULL && next->prev() == NULL),
1021 "New chunk is still on some list");
1022 return next;
1023 }
1025 Metachunk* VirtualSpaceList::get_initialization_chunk(size_t chunk_word_size,
1026 size_t chunk_bunch) {
1027 // Get a chunk from the chunk freelist
1028 Metachunk* new_chunk = get_new_chunk(chunk_word_size,
1029 chunk_word_size,
1030 chunk_bunch);
1031 return new_chunk;
1032 }
1034 void VirtualSpaceList::print_on(outputStream* st) const {
1035 if (TraceMetadataChunkAllocation && Verbose) {
1036 VirtualSpaceListIterator iter(virtual_space_list());
1037 while (iter.repeat()) {
1038 VirtualSpaceNode* node = iter.get_next();
1039 node->print_on(st);
1040 }
1041 }
1042 }
1044 bool VirtualSpaceList::contains(const void *ptr) {
1045 VirtualSpaceNode* list = virtual_space_list();
1046 VirtualSpaceListIterator iter(list);
1047 while (iter.repeat()) {
1048 VirtualSpaceNode* node = iter.get_next();
1049 if (node->reserved()->contains(ptr)) {
1050 return true;
1051 }
1052 }
1053 return false;
1054 }
1057 // MetaspaceGC methods
1059 // VM_CollectForMetadataAllocation is the vm operation used to GC.
1060 // Within the VM operation after the GC the attempt to allocate the metadata
1061 // should succeed. If the GC did not free enough space for the metaspace
1062 // allocation, the HWM is increased so that another virtualspace will be
1063 // allocated for the metadata. With perm gen the increase in the perm
1064 // gen had bounds, MinMetaspaceExpansion and MaxMetaspaceExpansion. The
1065 // metaspace policy uses those as the small and large steps for the HWM.
1066 //
1067 // After the GC the compute_new_size() for MetaspaceGC is called to
1068 // resize the capacity of the metaspaces. The current implementation
1069 // is based on the flags MinMetaspaceFreeRatio and MaxHeapFreeRatio used
1070 // to resize the Java heap by some GC's. New flags can be implemented
1071 // if really needed. MinHeapFreeRatio is used to calculate how much
1072 // free space is desirable in the metaspace capacity to decide how much
1073 // to increase the HWM. MaxMetaspaceFreeRatio is used to decide how much
1074 // free space is desirable in the metaspace capacity before decreasing
1075 // the HWM.
1077 // Calculate the amount to increase the high water mark (HWM).
1078 // Increase by a minimum amount (MinMetaspaceExpansion) so that
1079 // another expansion is not requested too soon. If that is not
1080 // enough to satisfy the allocation (i.e. big enough for a word_size
1081 // allocation), increase by MaxMetaspaceExpansion. If that is still
1082 // not enough, expand by the size of the allocation (word_size) plus
1083 // some.
1084 size_t MetaspaceGC::delta_capacity_until_GC(size_t word_size) {
1085 size_t before_inc = MetaspaceGC::capacity_until_GC();
1086 size_t min_delta_words = MinMetaspaceExpansion / BytesPerWord;
1087 size_t max_delta_words = MaxMetaspaceExpansion / BytesPerWord;
1088 size_t page_size_words = os::vm_page_size() / BytesPerWord;
1089 size_t size_delta_words = align_size_up(word_size, page_size_words);
1090 size_t delta_words = MAX2(size_delta_words, min_delta_words);
1091 if (delta_words > min_delta_words) {
1092 // Don't want to hit the high water mark on the next
1093 // allocation so make the delta greater than just enough
1094 // for this allocation.
1095 delta_words = MAX2(delta_words, max_delta_words);
1096 if (delta_words > max_delta_words) {
1097 // This allocation is large but the next ones are probably not
1098 // so increase by the minimum.
1099 delta_words = delta_words + min_delta_words;
1100 }
1101 }
1102 return delta_words;
1103 }
1105 bool MetaspaceGC::should_expand(VirtualSpaceList* vsl, size_t word_size) {
1106 // If the user wants a limit, impose one.
1107 if (!FLAG_IS_DEFAULT(MaxMetaspaceSize) &&
1108 MetaspaceAux::reserved_in_bytes() >= MaxMetaspaceSize) {
1109 return false;
1110 }
1112 // Class virtual space should always be expanded. Call GC for the other
1113 // metadata virtual space.
1114 if (vsl == Metaspace::class_space_list()) return true;
1116 // If this is part of an allocation after a GC, expand
1117 // unconditionally.
1118 if(MetaspaceGC::expand_after_GC()) {
1119 return true;
1120 }
1122 size_t metaspace_size_words = MetaspaceSize / BytesPerWord;
1124 // If the capacity is below the minimum capacity, allow the
1125 // expansion. Also set the high-water-mark (capacity_until_GC)
1126 // to that minimum capacity so that a GC will not be induced
1127 // until that minimum capacity is exceeded.
1128 if (vsl->capacity_words_sum() < metaspace_size_words ||
1129 capacity_until_GC() == 0) {
1130 set_capacity_until_GC(metaspace_size_words);
1131 return true;
1132 } else {
1133 if (vsl->capacity_words_sum() < capacity_until_GC()) {
1134 return true;
1135 } else {
1136 if (TraceMetadataChunkAllocation && Verbose) {
1137 gclog_or_tty->print_cr(" allocation request size " SIZE_FORMAT
1138 " capacity_until_GC " SIZE_FORMAT
1139 " capacity_words_sum " SIZE_FORMAT
1140 " used_words_sum " SIZE_FORMAT
1141 " free chunks " SIZE_FORMAT
1142 " free chunks count %d",
1143 word_size,
1144 capacity_until_GC(),
1145 vsl->capacity_words_sum(),
1146 vsl->used_words_sum(),
1147 vsl->chunk_manager()->free_chunks_total(),
1148 vsl->chunk_manager()->free_chunks_count());
1149 }
1150 return false;
1151 }
1152 }
1153 }
1155 // Variables are in bytes
1157 void MetaspaceGC::compute_new_size() {
1158 assert(_shrink_factor <= 100, "invalid shrink factor");
1159 uint current_shrink_factor = _shrink_factor;
1160 _shrink_factor = 0;
1162 VirtualSpaceList *vsl = Metaspace::space_list();
1164 size_t capacity_after_gc = vsl->capacity_bytes_sum();
1165 // Check to see if these two can be calculated without walking the CLDG
1166 size_t used_after_gc = vsl->used_bytes_sum();
1167 size_t capacity_until_GC = vsl->capacity_bytes_sum();
1168 size_t free_after_gc = capacity_until_GC - used_after_gc;
1170 const double minimum_free_percentage = MinMetaspaceFreeRatio / 100.0;
1171 const double maximum_used_percentage = 1.0 - minimum_free_percentage;
1173 const double min_tmp = used_after_gc / maximum_used_percentage;
1174 size_t minimum_desired_capacity =
1175 (size_t)MIN2(min_tmp, double(max_uintx));
1176 // Don't shrink less than the initial generation size
1177 minimum_desired_capacity = MAX2(minimum_desired_capacity,
1178 MetaspaceSize);
1180 if (PrintGCDetails && Verbose) {
1181 const double free_percentage = ((double)free_after_gc) / capacity_until_GC;
1182 gclog_or_tty->print_cr("\nMetaspaceGC::compute_new_size: ");
1183 gclog_or_tty->print_cr(" "
1184 " minimum_free_percentage: %6.2f"
1185 " maximum_used_percentage: %6.2f",
1186 minimum_free_percentage,
1187 maximum_used_percentage);
1188 double d_free_after_gc = free_after_gc / (double) K;
1189 gclog_or_tty->print_cr(" "
1190 " free_after_gc : %6.1fK"
1191 " used_after_gc : %6.1fK"
1192 " capacity_after_gc : %6.1fK"
1193 " metaspace HWM : %6.1fK",
1194 free_after_gc / (double) K,
1195 used_after_gc / (double) K,
1196 capacity_after_gc / (double) K,
1197 capacity_until_GC / (double) K);
1198 gclog_or_tty->print_cr(" "
1199 " free_percentage: %6.2f",
1200 free_percentage);
1201 }
1204 if (capacity_until_GC < minimum_desired_capacity) {
1205 // If we have less capacity below the metaspace HWM, then
1206 // increment the HWM.
1207 size_t expand_bytes = minimum_desired_capacity - capacity_until_GC;
1208 // Don't expand unless it's significant
1209 if (expand_bytes >= MinMetaspaceExpansion) {
1210 size_t expand_words = expand_bytes / BytesPerWord;
1211 MetaspaceGC::inc_capacity_until_GC(expand_words);
1212 }
1213 if (PrintGCDetails && Verbose) {
1214 size_t new_capacity_until_GC = MetaspaceGC::capacity_until_GC_in_bytes();
1215 gclog_or_tty->print_cr(" expanding:"
1216 " minimum_desired_capacity: %6.1fK"
1217 " expand_words: %6.1fK"
1218 " MinMetaspaceExpansion: %6.1fK"
1219 " new metaspace HWM: %6.1fK",
1220 minimum_desired_capacity / (double) K,
1221 expand_bytes / (double) K,
1222 MinMetaspaceExpansion / (double) K,
1223 new_capacity_until_GC / (double) K);
1224 }
1225 return;
1226 }
1228 // No expansion, now see if we want to shrink
1229 size_t shrink_words = 0;
1230 // We would never want to shrink more than this
1231 size_t max_shrink_words = capacity_until_GC - minimum_desired_capacity;
1232 assert(max_shrink_words >= 0, err_msg("max_shrink_words " SIZE_FORMAT,
1233 max_shrink_words));
1235 // Should shrinking be considered?
1236 if (MaxMetaspaceFreeRatio < 100) {
1237 const double maximum_free_percentage = MaxMetaspaceFreeRatio / 100.0;
1238 const double minimum_used_percentage = 1.0 - maximum_free_percentage;
1239 const double max_tmp = used_after_gc / minimum_used_percentage;
1240 size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(max_uintx));
1241 maximum_desired_capacity = MAX2(maximum_desired_capacity,
1242 MetaspaceSize);
1243 if (PrintGC && Verbose) {
1244 gclog_or_tty->print_cr(" "
1245 " maximum_free_percentage: %6.2f"
1246 " minimum_used_percentage: %6.2f",
1247 maximum_free_percentage,
1248 minimum_used_percentage);
1249 gclog_or_tty->print_cr(" "
1250 " capacity_until_GC: %6.1fK"
1251 " minimum_desired_capacity: %6.1fK"
1252 " maximum_desired_capacity: %6.1fK",
1253 capacity_until_GC / (double) K,
1254 minimum_desired_capacity / (double) K,
1255 maximum_desired_capacity / (double) K);
1256 }
1258 assert(minimum_desired_capacity <= maximum_desired_capacity,
1259 "sanity check");
1261 if (capacity_until_GC > maximum_desired_capacity) {
1262 // Capacity too large, compute shrinking size
1263 shrink_words = capacity_until_GC - maximum_desired_capacity;
1264 // We don't want shrink all the way back to initSize if people call
1265 // System.gc(), because some programs do that between "phases" and then
1266 // we'd just have to grow the heap up again for the next phase. So we
1267 // damp the shrinking: 0% on the first call, 10% on the second call, 40%
1268 // on the third call, and 100% by the fourth call. But if we recompute
1269 // size without shrinking, it goes back to 0%.
1270 shrink_words = shrink_words / 100 * current_shrink_factor;
1271 assert(shrink_words <= max_shrink_words,
1272 err_msg("invalid shrink size " SIZE_FORMAT " not <= " SIZE_FORMAT,
1273 shrink_words, max_shrink_words));
1274 if (current_shrink_factor == 0) {
1275 _shrink_factor = 10;
1276 } else {
1277 _shrink_factor = MIN2(current_shrink_factor * 4, (uint) 100);
1278 }
1279 if (PrintGCDetails && Verbose) {
1280 gclog_or_tty->print_cr(" "
1281 " shrinking:"
1282 " initSize: %.1fK"
1283 " maximum_desired_capacity: %.1fK",
1284 MetaspaceSize / (double) K,
1285 maximum_desired_capacity / (double) K);
1286 gclog_or_tty->print_cr(" "
1287 " shrink_words: %.1fK"
1288 " current_shrink_factor: %d"
1289 " new shrink factor: %d"
1290 " MinMetaspaceExpansion: %.1fK",
1291 shrink_words / (double) K,
1292 current_shrink_factor,
1293 _shrink_factor,
1294 MinMetaspaceExpansion / (double) K);
1295 }
1296 }
1297 }
1300 // Don't shrink unless it's significant
1301 if (shrink_words >= MinMetaspaceExpansion) {
1302 VirtualSpaceNode* csp = vsl->current_virtual_space();
1303 size_t available_to_shrink = csp->capacity_words_in_vs() -
1304 csp->used_words_in_vs();
1305 shrink_words = MIN2(shrink_words, available_to_shrink);
1306 csp->shrink_by(shrink_words);
1307 MetaspaceGC::dec_capacity_until_GC(shrink_words);
1308 if (PrintGCDetails && Verbose) {
1309 size_t new_capacity_until_GC = MetaspaceGC::capacity_until_GC_in_bytes();
1310 gclog_or_tty->print_cr(" metaspace HWM: %.1fK", new_capacity_until_GC / (double) K);
1311 }
1312 }
1313 assert(used_after_gc <= vsl->capacity_bytes_sum(),
1314 "sanity check");
1316 }
1318 // Metadebug methods
1320 void Metadebug::deallocate_chunk_a_lot(SpaceManager* sm,
1321 size_t chunk_word_size){
1322 #ifdef ASSERT
1323 VirtualSpaceList* vsl = sm->vs_list();
1324 if (MetaDataDeallocateALot &&
1325 Metadebug::deallocate_chunk_a_lot_count() % MetaDataDeallocateALotInterval == 0 ) {
1326 Metadebug::reset_deallocate_chunk_a_lot_count();
1327 for (uint i = 0; i < metadata_deallocate_a_lock_chunk; i++) {
1328 Metachunk* dummy_chunk = vsl->current_virtual_space()->take_from_committed(chunk_word_size);
1329 if (dummy_chunk == NULL) {
1330 break;
1331 }
1332 vsl->chunk_manager()->chunk_freelist_deallocate(dummy_chunk);
1334 if (TraceMetadataChunkAllocation && Verbose) {
1335 gclog_or_tty->print("Metadebug::deallocate_chunk_a_lot: %d) ",
1336 sm->sum_count_in_chunks_in_use());
1337 dummy_chunk->print_on(gclog_or_tty);
1338 gclog_or_tty->print_cr(" Free chunks total %d count %d",
1339 vsl->chunk_manager()->free_chunks_total(),
1340 vsl->chunk_manager()->free_chunks_count());
1341 }
1342 }
1343 } else {
1344 Metadebug::inc_deallocate_chunk_a_lot_count();
1345 }
1346 #endif
1347 }
1349 void Metadebug::deallocate_block_a_lot(SpaceManager* sm,
1350 size_t raw_word_size){
1351 #ifdef ASSERT
1352 if (MetaDataDeallocateALot &&
1353 Metadebug::deallocate_block_a_lot_count() % MetaDataDeallocateALotInterval == 0 ) {
1354 Metadebug::set_deallocate_block_a_lot_count(0);
1355 for (uint i = 0; i < metadata_deallocate_a_lot_block; i++) {
1356 MetaWord* dummy_block = sm->allocate_work(raw_word_size);
1357 if (dummy_block == 0) {
1358 break;
1359 }
1360 sm->deallocate(dummy_block, raw_word_size);
1361 }
1362 } else {
1363 Metadebug::inc_deallocate_block_a_lot_count();
1364 }
1365 #endif
1366 }
1368 void Metadebug::init_allocation_fail_alot_count() {
1369 if (MetadataAllocationFailALot) {
1370 _allocation_fail_alot_count =
1371 1+(long)((double)MetadataAllocationFailALotInterval*os::random()/(max_jint+1.0));
1372 }
1373 }
1375 #ifdef ASSERT
1376 bool Metadebug::test_metadata_failure() {
1377 if (MetadataAllocationFailALot &&
1378 Threads::is_vm_complete()) {
1379 if (_allocation_fail_alot_count > 0) {
1380 _allocation_fail_alot_count--;
1381 } else {
1382 if (TraceMetadataChunkAllocation && Verbose) {
1383 gclog_or_tty->print_cr("Metadata allocation failing for "
1384 "MetadataAllocationFailALot");
1385 }
1386 init_allocation_fail_alot_count();
1387 return true;
1388 }
1389 }
1390 return false;
1391 }
1392 #endif
1394 // ChunkList methods
1396 size_t ChunkList::sum_list_size() {
1397 size_t result = 0;
1398 Metachunk* cur = head();
1399 while (cur != NULL) {
1400 result += cur->word_size();
1401 cur = cur->next();
1402 }
1403 return result;
1404 }
1406 size_t ChunkList::sum_list_count() {
1407 size_t result = 0;
1408 Metachunk* cur = head();
1409 while (cur != NULL) {
1410 result++;
1411 cur = cur->next();
1412 }
1413 return result;
1414 }
1416 size_t ChunkList::sum_list_capacity() {
1417 size_t result = 0;
1418 Metachunk* cur = head();
1419 while (cur != NULL) {
1420 result += cur->capacity_word_size();
1421 cur = cur->next();
1422 }
1423 return result;
1424 }
1426 void ChunkList::add_at_head(Metachunk* head, Metachunk* tail) {
1427 assert_lock_strong(SpaceManager::expand_lock());
1428 assert(head == tail || tail->next() == NULL,
1429 "Not the tail or the head has already been added to a list");
1431 if (TraceMetadataChunkAllocation && Verbose) {
1432 gclog_or_tty->print("ChunkList::add_at_head(head, tail): ");
1433 Metachunk* cur = head;
1434 while (cur != NULL) {
1435 gclog_or_tty->print(PTR_FORMAT " (" SIZE_FORMAT ") ", cur, cur->word_size());
1436 cur = cur->next();
1437 }
1438 gclog_or_tty->print_cr("");
1439 }
1441 if (tail != NULL) {
1442 tail->set_next(_head);
1443 }
1444 set_head(head);
1445 }
1447 void ChunkList::add_at_head(Metachunk* list) {
1448 if (list == NULL) {
1449 // Nothing to add
1450 return;
1451 }
1452 assert_lock_strong(SpaceManager::expand_lock());
1453 Metachunk* head = list;
1454 Metachunk* tail = list;
1455 Metachunk* cur = head->next();
1456 // Search for the tail since it is not passed.
1457 while (cur != NULL) {
1458 tail = cur;
1459 cur = cur->next();
1460 }
1461 add_at_head(head, tail);
1462 }
1464 // ChunkManager methods
1466 // Verification of _free_chunks_total and _free_chunks_count does not
1467 // work with the CMS collector because its use of additional locks
1468 // complicate the mutex deadlock detection but it can still be useful
1469 // for detecting errors in the chunk accounting with other collectors.
1471 size_t ChunkManager::free_chunks_total() {
1472 #ifdef ASSERT
1473 if (!UseConcMarkSweepGC && !SpaceManager::expand_lock()->is_locked()) {
1474 MutexLockerEx cl(SpaceManager::expand_lock(),
1475 Mutex::_no_safepoint_check_flag);
1476 slow_locked_verify_free_chunks_total();
1477 }
1478 #endif
1479 return _free_chunks_total;
1480 }
1482 size_t ChunkManager::free_chunks_total_in_bytes() {
1483 return free_chunks_total() * BytesPerWord;
1484 }
1486 size_t ChunkManager::free_chunks_count() {
1487 #ifdef ASSERT
1488 if (!UseConcMarkSweepGC && !SpaceManager::expand_lock()->is_locked()) {
1489 MutexLockerEx cl(SpaceManager::expand_lock(),
1490 Mutex::_no_safepoint_check_flag);
1491 // This lock is only needed in debug because the verification
1492 // of the _free_chunks_totals walks the list of free chunks
1493 slow_locked_verify_free_chunks_count();
1494 }
1495 #endif
1496 return _free_chunks_count;
1497 }
1499 void ChunkManager::locked_verify_free_chunks_total() {
1500 assert_lock_strong(SpaceManager::expand_lock());
1501 assert(sum_free_chunks() == _free_chunks_total,
1502 err_msg("_free_chunks_total " SIZE_FORMAT " is not the"
1503 " same as sum " SIZE_FORMAT, _free_chunks_total,
1504 sum_free_chunks()));
1505 }
1507 void ChunkManager::verify_free_chunks_total() {
1508 MutexLockerEx cl(SpaceManager::expand_lock(),
1509 Mutex::_no_safepoint_check_flag);
1510 locked_verify_free_chunks_total();
1511 }
1513 void ChunkManager::locked_verify_free_chunks_count() {
1514 assert_lock_strong(SpaceManager::expand_lock());
1515 assert(sum_free_chunks_count() == _free_chunks_count,
1516 err_msg("_free_chunks_count " SIZE_FORMAT " is not the"
1517 " same as sum " SIZE_FORMAT, _free_chunks_count,
1518 sum_free_chunks_count()));
1519 }
1521 void ChunkManager::verify_free_chunks_count() {
1522 #ifdef ASSERT
1523 MutexLockerEx cl(SpaceManager::expand_lock(),
1524 Mutex::_no_safepoint_check_flag);
1525 locked_verify_free_chunks_count();
1526 #endif
1527 }
1529 void ChunkManager::verify() {
1530 MutexLockerEx cl(SpaceManager::expand_lock(),
1531 Mutex::_no_safepoint_check_flag);
1532 locked_verify();
1533 }
1535 void ChunkManager::locked_verify() {
1536 locked_verify_free_chunks_count();
1537 locked_verify_free_chunks_total();
1538 }
1540 void ChunkManager::locked_print_free_chunks(outputStream* st) {
1541 assert_lock_strong(SpaceManager::expand_lock());
1542 st->print_cr("Free chunk total " SIZE_FORMAT " count " SIZE_FORMAT,
1543 _free_chunks_total, _free_chunks_count);
1544 }
1546 void ChunkManager::locked_print_sum_free_chunks(outputStream* st) {
1547 assert_lock_strong(SpaceManager::expand_lock());
1548 st->print_cr("Sum free chunk total " SIZE_FORMAT " count " SIZE_FORMAT,
1549 sum_free_chunks(), sum_free_chunks_count());
1550 }
1551 ChunkList* ChunkManager::free_chunks(ChunkIndex index) {
1552 return &_free_chunks[index];
1553 }
1555 // These methods that sum the free chunk lists are used in printing
1556 // methods that are used in product builds.
1557 size_t ChunkManager::sum_free_chunks() {
1558 assert_lock_strong(SpaceManager::expand_lock());
1559 size_t result = 0;
1560 for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
1561 ChunkList* list = free_chunks(i);
1563 if (list == NULL) {
1564 continue;
1565 }
1567 result = result + list->sum_list_capacity();
1568 }
1569 result = result + humongous_dictionary()->total_size();
1570 return result;
1571 }
1573 size_t ChunkManager::sum_free_chunks_count() {
1574 assert_lock_strong(SpaceManager::expand_lock());
1575 size_t count = 0;
1576 for (ChunkIndex i = ZeroIndex; i < NumberOfFreeLists; i = next_chunk_index(i)) {
1577 ChunkList* list = free_chunks(i);
1578 if (list == NULL) {
1579 continue;
1580 }
1581 count = count + list->sum_list_count();
1582 }
1583 count = count + humongous_dictionary()->total_free_blocks();
1584 return count;
1585 }
1587 ChunkList* ChunkManager::find_free_chunks_list(size_t word_size) {
1588 ChunkIndex index = list_index(word_size);
1589 assert(index < HumongousIndex, "No humongous list");
1590 return free_chunks(index);
1591 }
1593 void ChunkManager::free_chunks_put(Metachunk* chunk) {
1594 assert_lock_strong(SpaceManager::expand_lock());
1595 ChunkList* free_list = find_free_chunks_list(chunk->word_size());
1596 chunk->set_next(free_list->head());
1597 free_list->set_head(chunk);
1598 // chunk is being returned to the chunk free list
1599 inc_free_chunks_total(chunk->capacity_word_size());
1600 slow_locked_verify();
1601 }
1603 void ChunkManager::chunk_freelist_deallocate(Metachunk* chunk) {
1604 // The deallocation of a chunk originates in the freelist
1605 // manangement code for a Metaspace and does not hold the
1606 // lock.
1607 assert(chunk != NULL, "Deallocating NULL");
1608 assert_lock_strong(SpaceManager::expand_lock());
1609 slow_locked_verify();
1610 if (TraceMetadataChunkAllocation) {
1611 tty->print_cr("ChunkManager::chunk_freelist_deallocate: chunk "
1612 PTR_FORMAT " size " SIZE_FORMAT,
1613 chunk, chunk->word_size());
1614 }
1615 free_chunks_put(chunk);
1616 }
1618 Metachunk* ChunkManager::free_chunks_get(size_t word_size) {
1619 assert_lock_strong(SpaceManager::expand_lock());
1621 slow_locked_verify();
1623 Metachunk* chunk = NULL;
1624 if (list_index(word_size) != HumongousIndex) {
1625 ChunkList* free_list = find_free_chunks_list(word_size);
1626 assert(free_list != NULL, "Sanity check");
1628 chunk = free_list->head();
1629 debug_only(Metachunk* debug_head = chunk;)
1631 if (chunk == NULL) {
1632 return NULL;
1633 }
1635 // Remove the chunk as the head of the list.
1636 free_list->set_head(chunk->next());
1638 // Chunk is being removed from the chunks free list.
1639 dec_free_chunks_total(chunk->capacity_word_size());
1641 if (TraceMetadataChunkAllocation && Verbose) {
1642 tty->print_cr("ChunkManager::free_chunks_get: free_list "
1643 PTR_FORMAT " head " PTR_FORMAT " size " SIZE_FORMAT,
1644 free_list, chunk, chunk->word_size());
1645 }
1646 } else {
1647 chunk = humongous_dictionary()->get_chunk(
1648 word_size,
1649 FreeBlockDictionary<Metachunk>::atLeast);
1651 if (chunk != NULL) {
1652 if (TraceMetadataHumongousAllocation) {
1653 size_t waste = chunk->word_size() - word_size;
1654 tty->print_cr("Free list allocate humongous chunk size " SIZE_FORMAT
1655 " for requested size " SIZE_FORMAT
1656 " waste " SIZE_FORMAT,
1657 chunk->word_size(), word_size, waste);
1658 }
1659 // Chunk is being removed from the chunks free list.
1660 dec_free_chunks_total(chunk->capacity_word_size());
1661 #ifdef ASSERT
1662 chunk->set_is_free(false);
1663 #endif
1664 } else {
1665 return NULL;
1666 }
1667 }
1669 // Remove it from the links to this freelist
1670 chunk->set_next(NULL);
1671 chunk->set_prev(NULL);
1672 slow_locked_verify();
1673 return chunk;
1674 }
1676 Metachunk* ChunkManager::chunk_freelist_allocate(size_t word_size) {
1677 assert_lock_strong(SpaceManager::expand_lock());
1678 slow_locked_verify();
1680 // Take from the beginning of the list
1681 Metachunk* chunk = free_chunks_get(word_size);
1682 if (chunk == NULL) {
1683 return NULL;
1684 }
1686 assert((word_size <= chunk->word_size()) ||
1687 list_index(chunk->word_size() == HumongousIndex),
1688 "Non-humongous variable sized chunk");
1689 if (TraceMetadataChunkAllocation) {
1690 size_t list_count;
1691 if (list_index(word_size) < HumongousIndex) {
1692 ChunkList* list = find_free_chunks_list(word_size);
1693 list_count = list->sum_list_count();
1694 } else {
1695 list_count = humongous_dictionary()->total_count();
1696 }
1697 tty->print("ChunkManager::chunk_freelist_allocate: " PTR_FORMAT " chunk "
1698 PTR_FORMAT " size " SIZE_FORMAT " count " SIZE_FORMAT " ",
1699 this, chunk, chunk->word_size(), list_count);
1700 locked_print_free_chunks(tty);
1701 }
1703 return chunk;
1704 }
1706 void ChunkManager::print_on(outputStream* out) {
1707 if (PrintFLSStatistics != 0) {
1708 humongous_dictionary()->report_statistics();
1709 }
1710 }
1712 // SpaceManager methods
1714 void SpaceManager::get_initial_chunk_sizes(Metaspace::MetaspaceType type,
1715 size_t* chunk_word_size,
1716 size_t* class_chunk_word_size) {
1717 switch (type) {
1718 case Metaspace::BootMetaspaceType:
1719 *chunk_word_size = Metaspace::first_chunk_word_size();
1720 *class_chunk_word_size = Metaspace::first_class_chunk_word_size();
1721 break;
1722 case Metaspace::ROMetaspaceType:
1723 *chunk_word_size = SharedReadOnlySize / wordSize;
1724 *class_chunk_word_size = ClassSpecializedChunk;
1725 break;
1726 case Metaspace::ReadWriteMetaspaceType:
1727 *chunk_word_size = SharedReadWriteSize / wordSize;
1728 *class_chunk_word_size = ClassSpecializedChunk;
1729 break;
1730 case Metaspace::AnonymousMetaspaceType:
1731 case Metaspace::ReflectionMetaspaceType:
1732 *chunk_word_size = SpecializedChunk;
1733 *class_chunk_word_size = ClassSpecializedChunk;
1734 break;
1735 default:
1736 *chunk_word_size = SmallChunk;
1737 *class_chunk_word_size = ClassSmallChunk;
1738 break;
1739 }
1740 assert(*chunk_word_size != 0 && *class_chunk_word_size != 0,
1741 err_msg("Initial chunks sizes bad: data " SIZE_FORMAT
1742 " class " SIZE_FORMAT,
1743 *chunk_word_size, *class_chunk_word_size));
1744 }
1746 size_t SpaceManager::sum_free_in_chunks_in_use() const {
1747 MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
1748 size_t free = 0;
1749 for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
1750 Metachunk* chunk = chunks_in_use(i);
1751 while (chunk != NULL) {
1752 free += chunk->free_word_size();
1753 chunk = chunk->next();
1754 }
1755 }
1756 return free;
1757 }
1759 size_t SpaceManager::sum_waste_in_chunks_in_use() const {
1760 MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
1761 size_t result = 0;
1762 for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
1763 result += sum_waste_in_chunks_in_use(i);
1764 }
1766 return result;
1767 }
1769 size_t SpaceManager::sum_waste_in_chunks_in_use(ChunkIndex index) const {
1770 size_t result = 0;
1771 Metachunk* chunk = chunks_in_use(index);
1772 // Count the free space in all the chunk but not the
1773 // current chunk from which allocations are still being done.
1774 if (chunk != NULL) {
1775 Metachunk* prev = chunk;
1776 while (chunk != NULL && chunk != current_chunk()) {
1777 result += chunk->free_word_size();
1778 prev = chunk;
1779 chunk = chunk->next();
1780 }
1781 }
1782 return result;
1783 }
1785 size_t SpaceManager::sum_capacity_in_chunks_in_use() const {
1786 MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
1787 size_t sum = 0;
1788 for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
1789 Metachunk* chunk = chunks_in_use(i);
1790 while (chunk != NULL) {
1791 // Just changed this sum += chunk->capacity_word_size();
1792 // sum += chunk->word_size() - Metachunk::overhead();
1793 sum += chunk->capacity_word_size();
1794 chunk = chunk->next();
1795 }
1796 }
1797 return sum;
1798 }
1800 size_t SpaceManager::sum_count_in_chunks_in_use() {
1801 size_t count = 0;
1802 for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
1803 count = count + sum_count_in_chunks_in_use(i);
1804 }
1806 return count;
1807 }
1809 size_t SpaceManager::sum_count_in_chunks_in_use(ChunkIndex i) {
1810 size_t count = 0;
1811 Metachunk* chunk = chunks_in_use(i);
1812 while (chunk != NULL) {
1813 count++;
1814 chunk = chunk->next();
1815 }
1816 return count;
1817 }
1820 size_t SpaceManager::sum_used_in_chunks_in_use() const {
1821 MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
1822 size_t used = 0;
1823 for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
1824 Metachunk* chunk = chunks_in_use(i);
1825 while (chunk != NULL) {
1826 used += chunk->used_word_size();
1827 chunk = chunk->next();
1828 }
1829 }
1830 return used;
1831 }
1833 void SpaceManager::locked_print_chunks_in_use_on(outputStream* st) const {
1835 for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
1836 Metachunk* chunk = chunks_in_use(i);
1837 st->print("SpaceManager: %s " PTR_FORMAT,
1838 chunk_size_name(i), chunk);
1839 if (chunk != NULL) {
1840 st->print_cr(" free " SIZE_FORMAT,
1841 chunk->free_word_size());
1842 } else {
1843 st->print_cr("");
1844 }
1845 }
1847 vs_list()->chunk_manager()->locked_print_free_chunks(st);
1848 vs_list()->chunk_manager()->locked_print_sum_free_chunks(st);
1849 }
1851 size_t SpaceManager::calc_chunk_size(size_t word_size) {
1853 // Decide between a small chunk and a medium chunk. Up to
1854 // _small_chunk_limit small chunks can be allocated but
1855 // once a medium chunk has been allocated, no more small
1856 // chunks will be allocated.
1857 size_t chunk_word_size;
1858 if (chunks_in_use(MediumIndex) == NULL &&
1859 (!has_small_chunk_limit() ||
1860 sum_count_in_chunks_in_use(SmallIndex) < _small_chunk_limit)) {
1861 chunk_word_size = (size_t) small_chunk_size();
1862 if (word_size + Metachunk::overhead() > small_chunk_size()) {
1863 chunk_word_size = medium_chunk_size();
1864 }
1865 } else {
1866 chunk_word_size = medium_chunk_size();
1867 }
1869 // Might still need a humongous chunk. Enforce an
1870 // eight word granularity to facilitate reuse (some
1871 // wastage but better chance of reuse).
1872 size_t if_humongous_sized_chunk =
1873 align_size_up(word_size + Metachunk::overhead(),
1874 HumongousChunkGranularity);
1875 chunk_word_size =
1876 MAX2((size_t) chunk_word_size, if_humongous_sized_chunk);
1878 assert(!SpaceManager::is_humongous(word_size) ||
1879 chunk_word_size == if_humongous_sized_chunk,
1880 err_msg("Size calculation is wrong, word_size " SIZE_FORMAT
1881 " chunk_word_size " SIZE_FORMAT,
1882 word_size, chunk_word_size));
1883 if (TraceMetadataHumongousAllocation &&
1884 SpaceManager::is_humongous(word_size)) {
1885 gclog_or_tty->print_cr("Metadata humongous allocation:");
1886 gclog_or_tty->print_cr(" word_size " PTR_FORMAT, word_size);
1887 gclog_or_tty->print_cr(" chunk_word_size " PTR_FORMAT,
1888 chunk_word_size);
1889 gclog_or_tty->print_cr(" chunk overhead " PTR_FORMAT,
1890 Metachunk::overhead());
1891 }
1892 return chunk_word_size;
1893 }
1895 MetaWord* SpaceManager::grow_and_allocate(size_t word_size) {
1896 assert(vs_list()->current_virtual_space() != NULL,
1897 "Should have been set");
1898 assert(current_chunk() == NULL ||
1899 current_chunk()->allocate(word_size) == NULL,
1900 "Don't need to expand");
1901 MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
1903 if (TraceMetadataChunkAllocation && Verbose) {
1904 size_t words_left = 0;
1905 size_t words_used = 0;
1906 if (current_chunk() != NULL) {
1907 words_left = current_chunk()->free_word_size();
1908 words_used = current_chunk()->used_word_size();
1909 }
1910 gclog_or_tty->print_cr("SpaceManager::grow_and_allocate for " SIZE_FORMAT
1911 " words " SIZE_FORMAT " words used " SIZE_FORMAT
1912 " words left",
1913 word_size, words_used, words_left);
1914 }
1916 // Get another chunk out of the virtual space
1917 size_t grow_chunks_by_words = calc_chunk_size(word_size);
1918 Metachunk* next = get_new_chunk(word_size, grow_chunks_by_words);
1920 // If a chunk was available, add it to the in-use chunk list
1921 // and do an allocation from it.
1922 if (next != NULL) {
1923 Metadebug::deallocate_chunk_a_lot(this, grow_chunks_by_words);
1924 // Add to this manager's list of chunks in use.
1925 add_chunk(next, false);
1926 return next->allocate(word_size);
1927 }
1928 return NULL;
1929 }
1931 void SpaceManager::print_on(outputStream* st) const {
1933 for (ChunkIndex i = ZeroIndex;
1934 i < NumberOfInUseLists ;
1935 i = next_chunk_index(i) ) {
1936 st->print_cr(" chunks_in_use " PTR_FORMAT " chunk size " PTR_FORMAT,
1937 chunks_in_use(i),
1938 chunks_in_use(i) == NULL ? 0 : chunks_in_use(i)->word_size());
1939 }
1940 st->print_cr(" waste: Small " SIZE_FORMAT " Medium " SIZE_FORMAT
1941 " Humongous " SIZE_FORMAT,
1942 sum_waste_in_chunks_in_use(SmallIndex),
1943 sum_waste_in_chunks_in_use(MediumIndex),
1944 sum_waste_in_chunks_in_use(HumongousIndex));
1945 // block free lists
1946 if (block_freelists() != NULL) {
1947 st->print_cr("total in block free lists " SIZE_FORMAT,
1948 block_freelists()->total_size());
1949 }
1950 }
1952 SpaceManager::SpaceManager(Mutex* lock,
1953 VirtualSpaceList* vs_list) :
1954 _vs_list(vs_list),
1955 _allocation_total(0),
1956 _lock(lock)
1957 {
1958 initialize();
1959 }
1961 void SpaceManager::initialize() {
1962 Metadebug::init_allocation_fail_alot_count();
1963 for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
1964 _chunks_in_use[i] = NULL;
1965 }
1966 _current_chunk = NULL;
1967 if (TraceMetadataChunkAllocation && Verbose) {
1968 gclog_or_tty->print_cr("SpaceManager(): " PTR_FORMAT, this);
1969 }
1970 }
1972 SpaceManager::~SpaceManager() {
1973 // This call this->_lock which can't be done while holding expand_lock()
1974 const size_t in_use_before = sum_capacity_in_chunks_in_use();
1976 MutexLockerEx fcl(SpaceManager::expand_lock(),
1977 Mutex::_no_safepoint_check_flag);
1979 ChunkManager* chunk_manager = vs_list()->chunk_manager();
1981 chunk_manager->slow_locked_verify();
1983 if (TraceMetadataChunkAllocation && Verbose) {
1984 gclog_or_tty->print_cr("~SpaceManager(): " PTR_FORMAT, this);
1985 locked_print_chunks_in_use_on(gclog_or_tty);
1986 }
1988 // Mangle freed memory.
1989 NOT_PRODUCT(mangle_freed_chunks();)
1991 // Have to update before the chunks_in_use lists are emptied
1992 // below.
1993 chunk_manager->inc_free_chunks_total(in_use_before,
1994 sum_count_in_chunks_in_use());
1996 // Add all the chunks in use by this space manager
1997 // to the global list of free chunks.
1999 // Follow each list of chunks-in-use and add them to the
2000 // free lists. Each list is NULL terminated.
2002 for (ChunkIndex i = ZeroIndex; i < HumongousIndex; i = next_chunk_index(i)) {
2003 if (TraceMetadataChunkAllocation && Verbose) {
2004 gclog_or_tty->print_cr("returned %d %s chunks to freelist",
2005 sum_count_in_chunks_in_use(i),
2006 chunk_size_name(i));
2007 }
2008 Metachunk* chunks = chunks_in_use(i);
2009 chunk_manager->free_chunks(i)->add_at_head(chunks);
2010 set_chunks_in_use(i, NULL);
2011 if (TraceMetadataChunkAllocation && Verbose) {
2012 gclog_or_tty->print_cr("updated freelist count %d %s",
2013 chunk_manager->free_chunks(i)->sum_list_count(),
2014 chunk_size_name(i));
2015 }
2016 assert(i != HumongousIndex, "Humongous chunks are handled explicitly later");
2017 }
2019 // The medium chunk case may be optimized by passing the head and
2020 // tail of the medium chunk list to add_at_head(). The tail is often
2021 // the current chunk but there are probably exceptions.
2023 // Humongous chunks
2024 if (TraceMetadataChunkAllocation && Verbose) {
2025 gclog_or_tty->print_cr("returned %d %s humongous chunks to dictionary",
2026 sum_count_in_chunks_in_use(HumongousIndex),
2027 chunk_size_name(HumongousIndex));
2028 gclog_or_tty->print("Humongous chunk dictionary: ");
2029 }
2030 // Humongous chunks are never the current chunk.
2031 Metachunk* humongous_chunks = chunks_in_use(HumongousIndex);
2033 while (humongous_chunks != NULL) {
2034 #ifdef ASSERT
2035 humongous_chunks->set_is_free(true);
2036 #endif
2037 if (TraceMetadataChunkAllocation && Verbose) {
2038 gclog_or_tty->print(PTR_FORMAT " (" SIZE_FORMAT ") ",
2039 humongous_chunks,
2040 humongous_chunks->word_size());
2041 }
2042 assert(humongous_chunks->word_size() == (size_t)
2043 align_size_up(humongous_chunks->word_size(),
2044 HumongousChunkGranularity),
2045 err_msg("Humongous chunk size is wrong: word size " SIZE_FORMAT
2046 " granularity %d",
2047 humongous_chunks->word_size(), HumongousChunkGranularity));
2048 Metachunk* next_humongous_chunks = humongous_chunks->next();
2049 chunk_manager->humongous_dictionary()->return_chunk(humongous_chunks);
2050 humongous_chunks = next_humongous_chunks;
2051 }
2052 if (TraceMetadataChunkAllocation && Verbose) {
2053 gclog_or_tty->print_cr("");
2054 gclog_or_tty->print_cr("updated dictionary count %d %s",
2055 chunk_manager->humongous_dictionary()->total_count(),
2056 chunk_size_name(HumongousIndex));
2057 }
2058 set_chunks_in_use(HumongousIndex, NULL);
2059 chunk_manager->slow_locked_verify();
2060 }
2062 const char* SpaceManager::chunk_size_name(ChunkIndex index) const {
2063 switch (index) {
2064 case SpecializedIndex:
2065 return "Specialized";
2066 case SmallIndex:
2067 return "Small";
2068 case MediumIndex:
2069 return "Medium";
2070 case HumongousIndex:
2071 return "Humongous";
2072 default:
2073 return NULL;
2074 }
2075 }
2077 ChunkIndex ChunkManager::list_index(size_t size) {
2078 switch (size) {
2079 case SpecializedChunk:
2080 assert(SpecializedChunk == ClassSpecializedChunk,
2081 "Need branch for ClassSpecializedChunk");
2082 return SpecializedIndex;
2083 case SmallChunk:
2084 case ClassSmallChunk:
2085 return SmallIndex;
2086 case MediumChunk:
2087 case ClassMediumChunk:
2088 return MediumIndex;
2089 default:
2090 assert(size > MediumChunk || size > ClassMediumChunk,
2091 "Not a humongous chunk");
2092 return HumongousIndex;
2093 }
2094 }
2096 void SpaceManager::deallocate(MetaWord* p, size_t word_size) {
2097 assert_lock_strong(_lock);
2098 size_t min_size = TreeChunk<Metablock, FreeList>::min_size();
2099 assert(word_size >= min_size,
2100 err_msg("Should not deallocate dark matter " SIZE_FORMAT, word_size));
2101 block_freelists()->return_block(p, word_size);
2102 }
2104 // Adds a chunk to the list of chunks in use.
2105 void SpaceManager::add_chunk(Metachunk* new_chunk, bool make_current) {
2107 assert(new_chunk != NULL, "Should not be NULL");
2108 assert(new_chunk->next() == NULL, "Should not be on a list");
2110 new_chunk->reset_empty();
2112 // Find the correct list and and set the current
2113 // chunk for that list.
2114 ChunkIndex index = ChunkManager::list_index(new_chunk->word_size());
2116 if (index != HumongousIndex) {
2117 set_current_chunk(new_chunk);
2118 new_chunk->set_next(chunks_in_use(index));
2119 set_chunks_in_use(index, new_chunk);
2120 } else {
2121 // For null class loader data and DumpSharedSpaces, the first chunk isn't
2122 // small, so small will be null. Link this first chunk as the current
2123 // chunk.
2124 if (make_current) {
2125 // Set as the current chunk but otherwise treat as a humongous chunk.
2126 set_current_chunk(new_chunk);
2127 }
2128 // Link at head. The _current_chunk only points to a humongous chunk for
2129 // the null class loader metaspace (class and data virtual space managers)
2130 // any humongous chunks so will not point to the tail
2131 // of the humongous chunks list.
2132 new_chunk->set_next(chunks_in_use(HumongousIndex));
2133 set_chunks_in_use(HumongousIndex, new_chunk);
2135 assert(new_chunk->word_size() > medium_chunk_size(), "List inconsistency");
2136 }
2138 assert(new_chunk->is_empty(), "Not ready for reuse");
2139 if (TraceMetadataChunkAllocation && Verbose) {
2140 gclog_or_tty->print("SpaceManager::add_chunk: %d) ",
2141 sum_count_in_chunks_in_use());
2142 new_chunk->print_on(gclog_or_tty);
2143 vs_list()->chunk_manager()->locked_print_free_chunks(tty);
2144 }
2145 }
2147 Metachunk* SpaceManager::get_new_chunk(size_t word_size,
2148 size_t grow_chunks_by_words) {
2150 Metachunk* next = vs_list()->get_new_chunk(word_size,
2151 grow_chunks_by_words,
2152 medium_chunk_bunch());
2154 if (TraceMetadataHumongousAllocation &&
2155 SpaceManager::is_humongous(next->word_size())) {
2156 gclog_or_tty->print_cr(" new humongous chunk word size " PTR_FORMAT,
2157 next->word_size());
2158 }
2160 return next;
2161 }
2163 MetaWord* SpaceManager::allocate(size_t word_size) {
2164 MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
2166 // If only the dictionary is going to be used (i.e., no
2167 // indexed free list), then there is a minimum size requirement.
2168 // MinChunkSize is a placeholder for the real minimum size JJJ
2169 size_t byte_size = word_size * BytesPerWord;
2171 size_t byte_size_with_overhead = byte_size + Metablock::overhead();
2173 size_t raw_bytes_size = MAX2(byte_size_with_overhead,
2174 Metablock::min_block_byte_size());
2175 raw_bytes_size = ARENA_ALIGN(raw_bytes_size);
2176 size_t raw_word_size = raw_bytes_size / BytesPerWord;
2177 assert(raw_word_size * BytesPerWord == raw_bytes_size, "Size problem");
2179 BlockFreelist* fl = block_freelists();
2180 MetaWord* p = NULL;
2181 // Allocation from the dictionary is expensive in the sense that
2182 // the dictionary has to be searched for a size. Don't allocate
2183 // from the dictionary until it starts to get fat. Is this
2184 // a reasonable policy? Maybe an skinny dictionary is fast enough
2185 // for allocations. Do some profiling. JJJ
2186 if (fl->total_size() > allocation_from_dictionary_limit) {
2187 p = fl->get_block(raw_word_size);
2188 }
2189 if (p == NULL) {
2190 p = allocate_work(raw_word_size);
2191 }
2192 Metadebug::deallocate_block_a_lot(this, raw_word_size);
2194 return p;
2195 }
2197 // Returns the address of spaced allocated for "word_size".
2198 // This methods does not know about blocks (Metablocks)
2199 MetaWord* SpaceManager::allocate_work(size_t word_size) {
2200 assert_lock_strong(_lock);
2201 #ifdef ASSERT
2202 if (Metadebug::test_metadata_failure()) {
2203 return NULL;
2204 }
2205 #endif
2206 // Is there space in the current chunk?
2207 MetaWord* result = NULL;
2209 // For DumpSharedSpaces, only allocate out of the current chunk which is
2210 // never null because we gave it the size we wanted. Caller reports out
2211 // of memory if this returns null.
2212 if (DumpSharedSpaces) {
2213 assert(current_chunk() != NULL, "should never happen");
2214 inc_allocation_total(word_size);
2215 return current_chunk()->allocate(word_size); // caller handles null result
2216 }
2217 if (current_chunk() != NULL) {
2218 result = current_chunk()->allocate(word_size);
2219 }
2221 if (result == NULL) {
2222 result = grow_and_allocate(word_size);
2223 }
2224 if (result > 0) {
2225 inc_allocation_total(word_size);
2226 assert(result != (MetaWord*) chunks_in_use(MediumIndex),
2227 "Head of the list is being allocated");
2228 }
2230 return result;
2231 }
2233 void SpaceManager::verify() {
2234 // If there are blocks in the dictionary, then
2235 // verfication of chunks does not work since
2236 // being in the dictionary alters a chunk.
2237 if (block_freelists()->total_size() == 0) {
2238 for (ChunkIndex i = ZeroIndex; i < NumberOfInUseLists; i = next_chunk_index(i)) {
2239 Metachunk* curr = chunks_in_use(i);
2240 while (curr != NULL) {
2241 curr->verify();
2242 verify_chunk_size(curr);
2243 curr = curr->next();
2244 }
2245 }
2246 }
2247 }
2249 void SpaceManager::verify_chunk_size(Metachunk* chunk) {
2250 assert(is_humongous(chunk->word_size()) ||
2251 chunk->word_size() == medium_chunk_size() ||
2252 chunk->word_size() == small_chunk_size() ||
2253 chunk->word_size() == specialized_chunk_size(),
2254 "Chunk size is wrong");
2255 return;
2256 }
2258 #ifdef ASSERT
2259 void SpaceManager::verify_allocation_total() {
2260 // Verification is only guaranteed at a safepoint.
2261 if (SafepointSynchronize::is_at_safepoint()) {
2262 gclog_or_tty->print_cr("Chunk " PTR_FORMAT " allocation_total " SIZE_FORMAT
2263 " sum_used_in_chunks_in_use " SIZE_FORMAT,
2264 this,
2265 allocation_total(),
2266 sum_used_in_chunks_in_use());
2267 }
2268 MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
2269 assert(allocation_total() == sum_used_in_chunks_in_use(),
2270 err_msg("allocation total is not consistent " SIZE_FORMAT
2271 " vs " SIZE_FORMAT,
2272 allocation_total(), sum_used_in_chunks_in_use()));
2273 }
2275 #endif
2277 void SpaceManager::dump(outputStream* const out) const {
2278 size_t curr_total = 0;
2279 size_t waste = 0;
2280 uint i = 0;
2281 size_t used = 0;
2282 size_t capacity = 0;
2284 // Add up statistics for all chunks in this SpaceManager.
2285 for (ChunkIndex index = ZeroIndex;
2286 index < NumberOfInUseLists;
2287 index = next_chunk_index(index)) {
2288 for (Metachunk* curr = chunks_in_use(index);
2289 curr != NULL;
2290 curr = curr->next()) {
2291 out->print("%d) ", i++);
2292 curr->print_on(out);
2293 if (TraceMetadataChunkAllocation && Verbose) {
2294 block_freelists()->print_on(out);
2295 }
2296 curr_total += curr->word_size();
2297 used += curr->used_word_size();
2298 capacity += curr->capacity_word_size();
2299 waste += curr->free_word_size() + curr->overhead();;
2300 }
2301 }
2303 size_t free = current_chunk() == NULL ? 0 : current_chunk()->free_word_size();
2304 // Free space isn't wasted.
2305 waste -= free;
2307 out->print_cr("total of all chunks " SIZE_FORMAT " used " SIZE_FORMAT
2308 " free " SIZE_FORMAT " capacity " SIZE_FORMAT
2309 " waste " SIZE_FORMAT, curr_total, used, free, capacity, waste);
2310 }
2312 #ifndef PRODUCT
2313 void SpaceManager::mangle_freed_chunks() {
2314 for (ChunkIndex index = ZeroIndex;
2315 index < NumberOfInUseLists;
2316 index = next_chunk_index(index)) {
2317 for (Metachunk* curr = chunks_in_use(index);
2318 curr != NULL;
2319 curr = curr->next()) {
2320 curr->mangle();
2321 }
2322 }
2323 }
2324 #endif // PRODUCT
2326 // MetaspaceAux
2328 size_t MetaspaceAux::used_in_bytes(Metaspace::MetadataType mdtype) {
2329 size_t used = 0;
2330 ClassLoaderDataGraphMetaspaceIterator iter;
2331 while (iter.repeat()) {
2332 Metaspace* msp = iter.get_next();
2333 // Sum allocation_total for each metaspace
2334 if (msp != NULL) {
2335 used += msp->used_words(mdtype);
2336 }
2337 }
2338 return used * BytesPerWord;
2339 }
2341 size_t MetaspaceAux::free_in_bytes(Metaspace::MetadataType mdtype) {
2342 size_t free = 0;
2343 ClassLoaderDataGraphMetaspaceIterator iter;
2344 while (iter.repeat()) {
2345 Metaspace* msp = iter.get_next();
2346 if (msp != NULL) {
2347 free += msp->free_words(mdtype);
2348 }
2349 }
2350 return free * BytesPerWord;
2351 }
2353 size_t MetaspaceAux::capacity_in_bytes(Metaspace::MetadataType mdtype) {
2354 size_t capacity = free_chunks_total(mdtype);
2355 ClassLoaderDataGraphMetaspaceIterator iter;
2356 while (iter.repeat()) {
2357 Metaspace* msp = iter.get_next();
2358 if (msp != NULL) {
2359 capacity += msp->capacity_words(mdtype);
2360 }
2361 }
2362 return capacity * BytesPerWord;
2363 }
2365 size_t MetaspaceAux::reserved_in_bytes(Metaspace::MetadataType mdtype) {
2366 size_t reserved = (mdtype == Metaspace::ClassType) ?
2367 Metaspace::class_space_list()->virtual_space_total() :
2368 Metaspace::space_list()->virtual_space_total();
2369 return reserved * BytesPerWord;
2370 }
2372 size_t MetaspaceAux::min_chunk_size() { return Metaspace::first_chunk_word_size(); }
2374 size_t MetaspaceAux::free_chunks_total(Metaspace::MetadataType mdtype) {
2375 ChunkManager* chunk = (mdtype == Metaspace::ClassType) ?
2376 Metaspace::class_space_list()->chunk_manager() :
2377 Metaspace::space_list()->chunk_manager();
2378 chunk->slow_verify();
2379 return chunk->free_chunks_total();
2380 }
2382 size_t MetaspaceAux::free_chunks_total_in_bytes(Metaspace::MetadataType mdtype) {
2383 return free_chunks_total(mdtype) * BytesPerWord;
2384 }
2386 void MetaspaceAux::print_metaspace_change(size_t prev_metadata_used) {
2387 gclog_or_tty->print(", [Metaspace:");
2388 if (PrintGCDetails && Verbose) {
2389 gclog_or_tty->print(" " SIZE_FORMAT
2390 "->" SIZE_FORMAT
2391 "(" SIZE_FORMAT "/" SIZE_FORMAT ")",
2392 prev_metadata_used,
2393 used_in_bytes(),
2394 capacity_in_bytes(),
2395 reserved_in_bytes());
2396 } else {
2397 gclog_or_tty->print(" " SIZE_FORMAT "K"
2398 "->" SIZE_FORMAT "K"
2399 "(" SIZE_FORMAT "K/" SIZE_FORMAT "K)",
2400 prev_metadata_used / K,
2401 used_in_bytes()/ K,
2402 capacity_in_bytes()/K,
2403 reserved_in_bytes()/ K);
2404 }
2406 gclog_or_tty->print("]");
2407 }
2409 // This is printed when PrintGCDetails
2410 void MetaspaceAux::print_on(outputStream* out) {
2411 Metaspace::MetadataType ct = Metaspace::ClassType;
2412 Metaspace::MetadataType nct = Metaspace::NonClassType;
2414 out->print_cr(" Metaspace total "
2415 SIZE_FORMAT "K, used " SIZE_FORMAT "K,"
2416 " reserved " SIZE_FORMAT "K",
2417 capacity_in_bytes()/K, used_in_bytes()/K, reserved_in_bytes()/K);
2418 out->print_cr(" data space "
2419 SIZE_FORMAT "K, used " SIZE_FORMAT "K,"
2420 " reserved " SIZE_FORMAT "K",
2421 capacity_in_bytes(nct)/K, used_in_bytes(nct)/K, reserved_in_bytes(nct)/K);
2422 out->print_cr(" class space "
2423 SIZE_FORMAT "K, used " SIZE_FORMAT "K,"
2424 " reserved " SIZE_FORMAT "K",
2425 capacity_in_bytes(ct)/K, used_in_bytes(ct)/K, reserved_in_bytes(ct)/K);
2426 }
2428 // Print information for class space and data space separately.
2429 // This is almost the same as above.
2430 void MetaspaceAux::print_on(outputStream* out, Metaspace::MetadataType mdtype) {
2431 size_t free_chunks_capacity_bytes = free_chunks_total_in_bytes(mdtype);
2432 size_t capacity_bytes = capacity_in_bytes(mdtype);
2433 size_t used_bytes = used_in_bytes(mdtype);
2434 size_t free_bytes = free_in_bytes(mdtype);
2435 size_t used_and_free = used_bytes + free_bytes +
2436 free_chunks_capacity_bytes;
2437 out->print_cr(" Chunk accounting: used in chunks " SIZE_FORMAT
2438 "K + unused in chunks " SIZE_FORMAT "K + "
2439 " capacity in free chunks " SIZE_FORMAT "K = " SIZE_FORMAT
2440 "K capacity in allocated chunks " SIZE_FORMAT "K",
2441 used_bytes / K,
2442 free_bytes / K,
2443 free_chunks_capacity_bytes / K,
2444 used_and_free / K,
2445 capacity_bytes / K);
2446 // Accounting can only be correct if we got the values during a safepoint
2447 assert(!SafepointSynchronize::is_at_safepoint() || used_and_free == capacity_bytes, "Accounting is wrong");
2448 }
2450 // Print total fragmentation for class and data metaspaces separately
2451 void MetaspaceAux::print_waste(outputStream* out) {
2453 size_t specialized_waste = 0, small_waste = 0, medium_waste = 0, large_waste = 0;
2454 size_t specialized_count = 0, small_count = 0, medium_count = 0, large_count = 0;
2455 size_t cls_specialized_waste = 0, cls_small_waste = 0, cls_medium_waste = 0, cls_large_waste = 0;
2456 size_t cls_specialized_count = 0, cls_small_count = 0, cls_medium_count = 0, cls_large_count = 0;
2458 ClassLoaderDataGraphMetaspaceIterator iter;
2459 while (iter.repeat()) {
2460 Metaspace* msp = iter.get_next();
2461 if (msp != NULL) {
2462 specialized_waste += msp->vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
2463 specialized_count += msp->vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
2464 small_waste += msp->vsm()->sum_waste_in_chunks_in_use(SmallIndex);
2465 small_count += msp->vsm()->sum_count_in_chunks_in_use(SmallIndex);
2466 medium_waste += msp->vsm()->sum_waste_in_chunks_in_use(MediumIndex);
2467 medium_count += msp->vsm()->sum_count_in_chunks_in_use(MediumIndex);
2468 large_waste += msp->vsm()->sum_waste_in_chunks_in_use(HumongousIndex);
2469 large_count += msp->vsm()->sum_count_in_chunks_in_use(HumongousIndex);
2471 cls_specialized_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SpecializedIndex);
2472 cls_specialized_count += msp->class_vsm()->sum_count_in_chunks_in_use(SpecializedIndex);
2473 cls_small_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SmallIndex);
2474 cls_small_count += msp->class_vsm()->sum_count_in_chunks_in_use(SmallIndex);
2475 cls_medium_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(MediumIndex);
2476 cls_medium_count += msp->class_vsm()->sum_count_in_chunks_in_use(MediumIndex);
2477 cls_large_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(HumongousIndex);
2478 cls_large_count += msp->class_vsm()->sum_count_in_chunks_in_use(HumongousIndex);
2479 }
2480 }
2481 out->print_cr("Total fragmentation waste (words) doesn't count free space");
2482 out->print_cr(" data: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
2483 SIZE_FORMAT " small(s) " SIZE_FORMAT ", "
2484 SIZE_FORMAT " medium(s) " SIZE_FORMAT,
2485 specialized_count, specialized_waste, small_count,
2486 small_waste, medium_count, medium_waste);
2487 out->print_cr(" class: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", "
2488 SIZE_FORMAT " small(s) " SIZE_FORMAT,
2489 cls_specialized_count, cls_specialized_waste,
2490 cls_small_count, cls_small_waste);
2491 }
2493 // Dump global metaspace things from the end of ClassLoaderDataGraph
2494 void MetaspaceAux::dump(outputStream* out) {
2495 out->print_cr("All Metaspace:");
2496 out->print("data space: "); print_on(out, Metaspace::NonClassType);
2497 out->print("class space: "); print_on(out, Metaspace::ClassType);
2498 print_waste(out);
2499 }
2501 void MetaspaceAux::verify_free_chunks() {
2502 Metaspace::space_list()->chunk_manager()->verify();
2503 Metaspace::class_space_list()->chunk_manager()->verify();
2504 }
2506 // Metaspace methods
2508 size_t Metaspace::_first_chunk_word_size = 0;
2509 size_t Metaspace::_first_class_chunk_word_size = 0;
2511 Metaspace::Metaspace(Mutex* lock, MetaspaceType type) {
2512 initialize(lock, type);
2513 }
2515 Metaspace::~Metaspace() {
2516 delete _vsm;
2517 delete _class_vsm;
2518 }
2520 VirtualSpaceList* Metaspace::_space_list = NULL;
2521 VirtualSpaceList* Metaspace::_class_space_list = NULL;
2523 #define VIRTUALSPACEMULTIPLIER 2
2525 void Metaspace::global_initialize() {
2526 // Initialize the alignment for shared spaces.
2527 int max_alignment = os::vm_page_size();
2528 MetaspaceShared::set_max_alignment(max_alignment);
2530 if (DumpSharedSpaces) {
2531 SharedReadOnlySize = align_size_up(SharedReadOnlySize, max_alignment);
2532 SharedReadWriteSize = align_size_up(SharedReadWriteSize, max_alignment);
2533 SharedMiscDataSize = align_size_up(SharedMiscDataSize, max_alignment);
2534 SharedMiscCodeSize = align_size_up(SharedMiscCodeSize, max_alignment);
2536 // Initialize with the sum of the shared space sizes. The read-only
2537 // and read write metaspace chunks will be allocated out of this and the
2538 // remainder is the misc code and data chunks.
2539 size_t total = align_size_up(SharedReadOnlySize + SharedReadWriteSize +
2540 SharedMiscDataSize + SharedMiscCodeSize,
2541 os::vm_allocation_granularity());
2542 size_t word_size = total/wordSize;
2543 _space_list = new VirtualSpaceList(word_size);
2544 } else {
2545 // If using shared space, open the file that contains the shared space
2546 // and map in the memory before initializing the rest of metaspace (so
2547 // the addresses don't conflict)
2548 if (UseSharedSpaces) {
2549 FileMapInfo* mapinfo = new FileMapInfo();
2550 memset(mapinfo, 0, sizeof(FileMapInfo));
2552 // Open the shared archive file, read and validate the header. If
2553 // initialization fails, shared spaces [UseSharedSpaces] are
2554 // disabled and the file is closed.
2555 // Map in spaces now also
2556 if (mapinfo->initialize() && MetaspaceShared::map_shared_spaces(mapinfo)) {
2557 FileMapInfo::set_current_info(mapinfo);
2558 } else {
2559 assert(!mapinfo->is_open() && !UseSharedSpaces,
2560 "archive file not closed or shared spaces not disabled.");
2561 }
2562 }
2564 // Initialize these before initializing the VirtualSpaceList
2565 _first_chunk_word_size = InitialBootClassLoaderMetaspaceSize / BytesPerWord;
2566 _first_chunk_word_size = align_word_size_up(_first_chunk_word_size);
2567 // Make the first class chunk bigger than a medium chunk so it's not put
2568 // on the medium chunk list. The next chunk will be small and progress
2569 // from there. This size calculated by -version.
2570 _first_class_chunk_word_size = MIN2((size_t)MediumChunk*6,
2571 (ClassMetaspaceSize/BytesPerWord)*2);
2572 _first_class_chunk_word_size = align_word_size_up(_first_class_chunk_word_size);
2573 // Arbitrarily set the initial virtual space to a multiple
2574 // of the boot class loader size.
2575 size_t word_size = VIRTUALSPACEMULTIPLIER * first_chunk_word_size();
2576 // Initialize the list of virtual spaces.
2577 _space_list = new VirtualSpaceList(word_size);
2578 }
2579 }
2581 // For UseCompressedKlassPointers the class space is reserved as a piece of the
2582 // Java heap because the compression algorithm is the same for each. The
2583 // argument passed in is at the top of the compressed space
2584 void Metaspace::initialize_class_space(ReservedSpace rs) {
2585 // The reserved space size may be bigger because of alignment, esp with UseLargePages
2586 assert(rs.size() >= ClassMetaspaceSize,
2587 err_msg(SIZE_FORMAT " != " UINTX_FORMAT, rs.size(), ClassMetaspaceSize));
2588 _class_space_list = new VirtualSpaceList(rs);
2589 }
2591 void Metaspace::initialize(Mutex* lock,
2592 MetaspaceType type) {
2594 assert(space_list() != NULL,
2595 "Metadata VirtualSpaceList has not been initialized");
2597 _vsm = new SpaceManager(lock, space_list());
2598 if (_vsm == NULL) {
2599 return;
2600 }
2601 size_t word_size;
2602 size_t class_word_size;
2603 vsm()->get_initial_chunk_sizes(type,
2604 &word_size,
2605 &class_word_size);
2607 assert(class_space_list() != NULL,
2608 "Class VirtualSpaceList has not been initialized");
2610 // Allocate SpaceManager for classes.
2611 _class_vsm = new SpaceManager(lock, class_space_list());
2612 if (_class_vsm == NULL) {
2613 return;
2614 }
2616 MutexLockerEx cl(SpaceManager::expand_lock(), Mutex::_no_safepoint_check_flag);
2618 // Allocate chunk for metadata objects
2619 Metachunk* new_chunk =
2620 space_list()->get_initialization_chunk(word_size,
2621 vsm()->medium_chunk_bunch());
2622 assert(!DumpSharedSpaces || new_chunk != NULL, "should have enough space for both chunks");
2623 if (new_chunk != NULL) {
2624 // Add to this manager's list of chunks in use and current_chunk().
2625 vsm()->add_chunk(new_chunk, true);
2626 }
2628 // Allocate chunk for class metadata objects
2629 Metachunk* class_chunk =
2630 class_space_list()->get_initialization_chunk(class_word_size,
2631 class_vsm()->medium_chunk_bunch());
2632 if (class_chunk != NULL) {
2633 class_vsm()->add_chunk(class_chunk, true);
2634 }
2635 }
2637 size_t Metaspace::align_word_size_up(size_t word_size) {
2638 size_t byte_size = word_size * wordSize;
2639 return ReservedSpace::allocation_align_size_up(byte_size) / wordSize;
2640 }
2642 MetaWord* Metaspace::allocate(size_t word_size, MetadataType mdtype) {
2643 // DumpSharedSpaces doesn't use class metadata area (yet)
2644 if (mdtype == ClassType && !DumpSharedSpaces) {
2645 return class_vsm()->allocate(word_size);
2646 } else {
2647 return vsm()->allocate(word_size);
2648 }
2649 }
2651 MetaWord* Metaspace::expand_and_allocate(size_t word_size, MetadataType mdtype) {
2652 MetaWord* result;
2653 MetaspaceGC::set_expand_after_GC(true);
2654 size_t before_inc = MetaspaceGC::capacity_until_GC();
2655 size_t delta_words = MetaspaceGC::delta_capacity_until_GC(word_size);
2656 MetaspaceGC::inc_capacity_until_GC(delta_words);
2657 if (PrintGCDetails && Verbose) {
2658 gclog_or_tty->print_cr("Increase capacity to GC from " SIZE_FORMAT
2659 " to " SIZE_FORMAT, before_inc, MetaspaceGC::capacity_until_GC());
2660 }
2662 result = allocate(word_size, mdtype);
2664 return result;
2665 }
2667 // Space allocated in the Metaspace. This may
2668 // be across several metadata virtual spaces.
2669 char* Metaspace::bottom() const {
2670 assert(DumpSharedSpaces, "only useful and valid for dumping shared spaces");
2671 return (char*)vsm()->current_chunk()->bottom();
2672 }
2674 size_t Metaspace::used_words(MetadataType mdtype) const {
2675 // return vsm()->allocation_total();
2676 return mdtype == ClassType ? class_vsm()->sum_used_in_chunks_in_use() :
2677 vsm()->sum_used_in_chunks_in_use(); // includes overhead!
2678 }
2680 size_t Metaspace::free_words(MetadataType mdtype) const {
2681 return mdtype == ClassType ? class_vsm()->sum_free_in_chunks_in_use() :
2682 vsm()->sum_free_in_chunks_in_use();
2683 }
2685 // Space capacity in the Metaspace. It includes
2686 // space in the list of chunks from which allocations
2687 // have been made. Don't include space in the global freelist and
2688 // in the space available in the dictionary which
2689 // is already counted in some chunk.
2690 size_t Metaspace::capacity_words(MetadataType mdtype) const {
2691 return mdtype == ClassType ? class_vsm()->sum_capacity_in_chunks_in_use() :
2692 vsm()->sum_capacity_in_chunks_in_use();
2693 }
2695 void Metaspace::deallocate(MetaWord* ptr, size_t word_size, bool is_class) {
2696 if (SafepointSynchronize::is_at_safepoint()) {
2697 assert(Thread::current()->is_VM_thread(), "should be the VM thread");
2698 // Don't take Heap_lock
2699 MutexLocker ml(vsm()->lock());
2700 if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
2701 // Dark matter. Too small for dictionary.
2702 #ifdef ASSERT
2703 Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
2704 #endif
2705 return;
2706 }
2707 if (is_class) {
2708 class_vsm()->deallocate(ptr, word_size);
2709 } else {
2710 vsm()->deallocate(ptr, word_size);
2711 }
2712 } else {
2713 MutexLocker ml(vsm()->lock());
2715 if (word_size < TreeChunk<Metablock, FreeList>::min_size()) {
2716 // Dark matter. Too small for dictionary.
2717 #ifdef ASSERT
2718 Copy::fill_to_words((HeapWord*)ptr, word_size, 0xf5f5f5f5);
2719 #endif
2720 return;
2721 }
2722 if (is_class) {
2723 class_vsm()->deallocate(ptr, word_size);
2724 } else {
2725 vsm()->deallocate(ptr, word_size);
2726 }
2727 }
2728 }
2730 Metablock* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size,
2731 bool read_only, MetadataType mdtype, TRAPS) {
2732 if (HAS_PENDING_EXCEPTION) {
2733 assert(false, "Should not allocate with exception pending");
2734 return NULL; // caller does a CHECK_NULL too
2735 }
2737 // SSS: Should we align the allocations and make sure the sizes are aligned.
2738 MetaWord* result = NULL;
2740 assert(loader_data != NULL, "Should never pass around a NULL loader_data. "
2741 "ClassLoaderData::the_null_class_loader_data() should have been used.");
2742 // Allocate in metaspaces without taking out a lock, because it deadlocks
2743 // with the SymbolTable_lock. Dumping is single threaded for now. We'll have
2744 // to revisit this for application class data sharing.
2745 if (DumpSharedSpaces) {
2746 if (read_only) {
2747 result = loader_data->ro_metaspace()->allocate(word_size, NonClassType);
2748 } else {
2749 result = loader_data->rw_metaspace()->allocate(word_size, NonClassType);
2750 }
2751 if (result == NULL) {
2752 report_out_of_shared_space(read_only ? SharedReadOnly : SharedReadWrite);
2753 }
2754 return Metablock::initialize(result, word_size);
2755 }
2757 result = loader_data->metaspace_non_null()->allocate(word_size, mdtype);
2759 if (result == NULL) {
2760 // Try to clean out some memory and retry.
2761 result =
2762 Universe::heap()->collector_policy()->satisfy_failed_metadata_allocation(
2763 loader_data, word_size, mdtype);
2765 // If result is still null, we are out of memory.
2766 if (result == NULL) {
2767 if (Verbose && TraceMetadataChunkAllocation) {
2768 gclog_or_tty->print_cr("Metaspace allocation failed for size "
2769 SIZE_FORMAT, word_size);
2770 if (loader_data->metaspace_or_null() != NULL) loader_data->metaspace_or_null()->dump(gclog_or_tty);
2771 MetaspaceAux::dump(gclog_or_tty);
2772 }
2773 // -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support
2774 report_java_out_of_memory("Metadata space");
2776 if (JvmtiExport::should_post_resource_exhausted()) {
2777 JvmtiExport::post_resource_exhausted(
2778 JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR,
2779 "Metadata space");
2780 }
2781 THROW_OOP_0(Universe::out_of_memory_error_perm_gen());
2782 }
2783 }
2784 return Metablock::initialize(result, word_size);
2785 }
2787 void Metaspace::print_on(outputStream* out) const {
2788 // Print both class virtual space counts and metaspace.
2789 if (Verbose) {
2790 vsm()->print_on(out);
2791 class_vsm()->print_on(out);
2792 }
2793 }
2795 bool Metaspace::contains(const void * ptr) {
2796 if (MetaspaceShared::is_in_shared_space(ptr)) {
2797 return true;
2798 }
2799 // This is checked while unlocked. As long as the virtualspaces are added
2800 // at the end, the pointer will be in one of them. The virtual spaces
2801 // aren't deleted presently. When they are, some sort of locking might
2802 // be needed. Note, locking this can cause inversion problems with the
2803 // caller in MetaspaceObj::is_metadata() function.
2804 return space_list()->contains(ptr) || class_space_list()->contains(ptr);
2805 }
2807 void Metaspace::verify() {
2808 vsm()->verify();
2809 class_vsm()->verify();
2810 }
2812 void Metaspace::dump(outputStream* const out) const {
2813 if (UseMallocOnly) {
2814 // Just print usage for now
2815 out->print_cr("usage %d", used_words(Metaspace::NonClassType));
2816 }
2817 out->print_cr("\nVirtual space manager: " INTPTR_FORMAT, vsm());
2818 vsm()->dump(out);
2819 out->print_cr("\nClass space manager: " INTPTR_FORMAT, class_vsm());
2820 class_vsm()->dump(out);
2821 }