1 /*
2 * Copyright (c) 2011, 2018, 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
25 #include "precompiled.hpp"
26
27 #include "aot/aotLoader.hpp"
28 #include "gc/shared/collectedHeap.hpp"
29 #include "logging/log.hpp"
30 #include "logging/logStream.hpp"
31 #include "memory/filemap.hpp"
32 #include "memory/metaspace.hpp"
33 #include "memory/metaspace/chunkManager.hpp"
34 #include "memory/metaspace/metachunk.hpp"
35 #include "memory/metaspace/metaspaceCommon.hpp"
36 #include "memory/metaspace/printCLDMetaspaceInfoClosure.hpp"
37 #include "memory/metaspace/spaceManager.hpp"
38 #include "memory/metaspace/virtualSpaceList.hpp"
39 #include "memory/metaspaceShared.hpp"
40 #include "memory/metaspaceTracer.hpp"
41 #include "memory/universe.hpp"
42 #include "runtime/init.hpp"
43 #include "runtime/orderAccess.hpp"
44 #include "services/memTracker.hpp"
45 #include "utilities/copy.hpp"
46 #include "utilities/debug.hpp"
47 #include "utilities/formatBuffer.hpp"
48 #include "utilities/globalDefinitions.hpp"
49
50
51 using namespace metaspace;
52
53 MetaWord* last_allocated = 0;
54
55 size_t Metaspace::_compressed_class_space_size;
56 const MetaspaceTracer* Metaspace::_tracer = NULL;
57
DEBUG_ONLY(bool Metaspace::_frozen=false;) const58 DEBUG_ONLY(bool Metaspace::_frozen = false;)
59
60 static const char* space_type_name(Metaspace::MetaspaceType t) {
61 const char* s = NULL;
62 switch (t) {
63 case Metaspace::StandardMetaspaceType: s = "Standard"; break;
64 case Metaspace::BootMetaspaceType: s = "Boot"; break;
65 case Metaspace::AnonymousMetaspaceType: s = "Anonymous"; break;
66 case Metaspace::ReflectionMetaspaceType: s = "Reflection"; break;
67 default: ShouldNotReachHere();
68 }
69 return s;
70 }
71
72 volatile size_t MetaspaceGC::_capacity_until_GC = 0;
73 uint MetaspaceGC::_shrink_factor = 0;
74 bool MetaspaceGC::_should_concurrent_collect = false;
75
76 // BlockFreelist methods
77
78 // VirtualSpaceNode methods
79
80 // MetaspaceGC methods
81
82 // VM_CollectForMetadataAllocation is the vm operation used to GC.
83 // Within the VM operation after the GC the attempt to allocate the metadata
84 // should succeed. If the GC did not free enough space for the metaspace
85 // allocation, the HWM is increased so that another virtualspace will be
86 // allocated for the metadata. With perm gen the increase in the perm
87 // gen had bounds, MinMetaspaceExpansion and MaxMetaspaceExpansion. The
88 // metaspace policy uses those as the small and large steps for the HWM.
89 //
90 // After the GC the compute_new_size() for MetaspaceGC is called to
91 // resize the capacity of the metaspaces. The current implementation
92 // is based on the flags MinMetaspaceFreeRatio and MaxMetaspaceFreeRatio used
93 // to resize the Java heap by some GC's. New flags can be implemented
94 // if really needed. MinMetaspaceFreeRatio is used to calculate how much
95 // free space is desirable in the metaspace capacity to decide how much
96 // to increase the HWM. MaxMetaspaceFreeRatio is used to decide how much
97 // free space is desirable in the metaspace capacity before decreasing
98 // the HWM.
99
100 // Calculate the amount to increase the high water mark (HWM).
101 // Increase by a minimum amount (MinMetaspaceExpansion) so that
102 // another expansion is not requested too soon. If that is not
103 // enough to satisfy the allocation, increase by MaxMetaspaceExpansion.
104 // If that is still not enough, expand by the size of the allocation
105 // plus some.
delta_capacity_until_GC(size_t bytes)106 size_t MetaspaceGC::delta_capacity_until_GC(size_t bytes) {
107 size_t min_delta = MinMetaspaceExpansion;
108 size_t max_delta = MaxMetaspaceExpansion;
109 size_t delta = align_up(bytes, Metaspace::commit_alignment());
110
111 if (delta <= min_delta) {
112 delta = min_delta;
113 } else if (delta <= max_delta) {
114 // Don't want to hit the high water mark on the next
115 // allocation so make the delta greater than just enough
116 // for this allocation.
117 delta = max_delta;
118 } else {
119 // This allocation is large but the next ones are probably not
120 // so increase by the minimum.
121 delta = delta + min_delta;
122 }
123
124 assert_is_aligned(delta, Metaspace::commit_alignment());
125
126 return delta;
127 }
128
capacity_until_GC()129 size_t MetaspaceGC::capacity_until_GC() {
130 size_t value = OrderAccess::load_acquire(&_capacity_until_GC);
131 assert(value >= MetaspaceSize, "Not initialized properly?");
132 return value;
133 }
134
135 // Try to increase the _capacity_until_GC limit counter by v bytes.
136 // Returns true if it succeeded. It may fail if either another thread
137 // concurrently increased the limit or the new limit would be larger
138 // than MaxMetaspaceSize.
139 // On success, optionally returns new and old metaspace capacity in
140 // new_cap_until_GC and old_cap_until_GC respectively.
141 // On error, optionally sets can_retry to indicate whether if there is
142 // actually enough space remaining to satisfy the request.
inc_capacity_until_GC(size_t v,size_t * new_cap_until_GC,size_t * old_cap_until_GC,bool * can_retry)143 bool MetaspaceGC::inc_capacity_until_GC(size_t v, size_t* new_cap_until_GC, size_t* old_cap_until_GC, bool* can_retry) {
144 assert_is_aligned(v, Metaspace::commit_alignment());
145
146 size_t old_capacity_until_GC = _capacity_until_GC;
147 size_t new_value = old_capacity_until_GC + v;
148
149 if (new_value < old_capacity_until_GC) {
150 // The addition wrapped around, set new_value to aligned max value.
151 new_value = align_down(max_uintx, Metaspace::commit_alignment());
152 }
153
154 if (new_value > MaxMetaspaceSize) {
155 if (can_retry != NULL) {
156 *can_retry = false;
157 }
158 return false;
159 }
160
161 if (can_retry != NULL) {
162 *can_retry = true;
163 }
164 size_t prev_value = Atomic::cmpxchg(new_value, &_capacity_until_GC, old_capacity_until_GC);
165
166 if (old_capacity_until_GC != prev_value) {
167 return false;
168 }
169
170 if (new_cap_until_GC != NULL) {
171 *new_cap_until_GC = new_value;
172 }
173 if (old_cap_until_GC != NULL) {
174 *old_cap_until_GC = old_capacity_until_GC;
175 }
176 return true;
177 }
178
dec_capacity_until_GC(size_t v)179 size_t MetaspaceGC::dec_capacity_until_GC(size_t v) {
180 assert_is_aligned(v, Metaspace::commit_alignment());
181
182 return Atomic::sub(v, &_capacity_until_GC);
183 }
184
initialize()185 void MetaspaceGC::initialize() {
186 // Set the high-water mark to MaxMetapaceSize during VM initializaton since
187 // we can't do a GC during initialization.
188 _capacity_until_GC = MaxMetaspaceSize;
189 }
190
post_initialize()191 void MetaspaceGC::post_initialize() {
192 // Reset the high-water mark once the VM initialization is done.
193 _capacity_until_GC = MAX2(MetaspaceUtils::committed_bytes(), MetaspaceSize);
194 }
195
can_expand(size_t word_size,bool is_class)196 bool MetaspaceGC::can_expand(size_t word_size, bool is_class) {
197 // Check if the compressed class space is full.
198 if (is_class && Metaspace::using_class_space()) {
199 size_t class_committed = MetaspaceUtils::committed_bytes(Metaspace::ClassType);
200 if (class_committed + word_size * BytesPerWord > CompressedClassSpaceSize) {
201 log_trace(gc, metaspace, freelist)("Cannot expand %s metaspace by " SIZE_FORMAT " words (CompressedClassSpaceSize = " SIZE_FORMAT " words)",
202 (is_class ? "class" : "non-class"), word_size, CompressedClassSpaceSize / sizeof(MetaWord));
203 return false;
204 }
205 }
206
207 // Check if the user has imposed a limit on the metaspace memory.
208 size_t committed_bytes = MetaspaceUtils::committed_bytes();
209 if (committed_bytes + word_size * BytesPerWord > MaxMetaspaceSize) {
210 log_trace(gc, metaspace, freelist)("Cannot expand %s metaspace by " SIZE_FORMAT " words (MaxMetaspaceSize = " SIZE_FORMAT " words)",
211 (is_class ? "class" : "non-class"), word_size, MaxMetaspaceSize / sizeof(MetaWord));
212 return false;
213 }
214
215 return true;
216 }
217
allowed_expansion()218 size_t MetaspaceGC::allowed_expansion() {
219 size_t committed_bytes = MetaspaceUtils::committed_bytes();
220 size_t capacity_until_gc = capacity_until_GC();
221
222 assert(capacity_until_gc >= committed_bytes,
223 "capacity_until_gc: " SIZE_FORMAT " < committed_bytes: " SIZE_FORMAT,
224 capacity_until_gc, committed_bytes);
225
226 size_t left_until_max = MaxMetaspaceSize - committed_bytes;
227 size_t left_until_GC = capacity_until_gc - committed_bytes;
228 size_t left_to_commit = MIN2(left_until_GC, left_until_max);
229 log_trace(gc, metaspace, freelist)("allowed expansion words: " SIZE_FORMAT
230 " (left_until_max: " SIZE_FORMAT ", left_until_GC: " SIZE_FORMAT ".",
231 left_to_commit / BytesPerWord, left_until_max / BytesPerWord, left_until_GC / BytesPerWord);
232
233 return left_to_commit / BytesPerWord;
234 }
235
compute_new_size()236 void MetaspaceGC::compute_new_size() {
237 assert(_shrink_factor <= 100, "invalid shrink factor");
238 uint current_shrink_factor = _shrink_factor;
239 _shrink_factor = 0;
240
241 // Using committed_bytes() for used_after_gc is an overestimation, since the
242 // chunk free lists are included in committed_bytes() and the memory in an
243 // un-fragmented chunk free list is available for future allocations.
244 // However, if the chunk free lists becomes fragmented, then the memory may
245 // not be available for future allocations and the memory is therefore "in use".
246 // Including the chunk free lists in the definition of "in use" is therefore
247 // necessary. Not including the chunk free lists can cause capacity_until_GC to
248 // shrink below committed_bytes() and this has caused serious bugs in the past.
249 const size_t used_after_gc = MetaspaceUtils::committed_bytes();
250 const size_t capacity_until_GC = MetaspaceGC::capacity_until_GC();
251
252 const double minimum_free_percentage = MinMetaspaceFreeRatio / 100.0;
253 const double maximum_used_percentage = 1.0 - minimum_free_percentage;
254
255 const double min_tmp = used_after_gc / maximum_used_percentage;
256 size_t minimum_desired_capacity =
257 (size_t)MIN2(min_tmp, double(MaxMetaspaceSize));
258 // Don't shrink less than the initial generation size
259 minimum_desired_capacity = MAX2(minimum_desired_capacity,
260 MetaspaceSize);
261
262 log_trace(gc, metaspace)("MetaspaceGC::compute_new_size: ");
263 log_trace(gc, metaspace)(" minimum_free_percentage: %6.2f maximum_used_percentage: %6.2f",
264 minimum_free_percentage, maximum_used_percentage);
265 log_trace(gc, metaspace)(" used_after_gc : %6.1fKB", used_after_gc / (double) K);
266
267
268 size_t shrink_bytes = 0;
269 if (capacity_until_GC < minimum_desired_capacity) {
270 // If we have less capacity below the metaspace HWM, then
271 // increment the HWM.
272 size_t expand_bytes = minimum_desired_capacity - capacity_until_GC;
273 expand_bytes = align_up(expand_bytes, Metaspace::commit_alignment());
274 // Don't expand unless it's significant
275 if (expand_bytes >= MinMetaspaceExpansion) {
276 size_t new_capacity_until_GC = 0;
277 bool succeeded = MetaspaceGC::inc_capacity_until_GC(expand_bytes, &new_capacity_until_GC);
278 assert(succeeded, "Should always succesfully increment HWM when at safepoint");
279
280 Metaspace::tracer()->report_gc_threshold(capacity_until_GC,
281 new_capacity_until_GC,
282 MetaspaceGCThresholdUpdater::ComputeNewSize);
283 log_trace(gc, metaspace)(" expanding: minimum_desired_capacity: %6.1fKB expand_bytes: %6.1fKB MinMetaspaceExpansion: %6.1fKB new metaspace HWM: %6.1fKB",
284 minimum_desired_capacity / (double) K,
285 expand_bytes / (double) K,
286 MinMetaspaceExpansion / (double) K,
287 new_capacity_until_GC / (double) K);
288 }
289 return;
290 }
291
292 // No expansion, now see if we want to shrink
293 // We would never want to shrink more than this
294 assert(capacity_until_GC >= minimum_desired_capacity,
295 SIZE_FORMAT " >= " SIZE_FORMAT,
296 capacity_until_GC, minimum_desired_capacity);
297 size_t max_shrink_bytes = capacity_until_GC - minimum_desired_capacity;
298
299 // Should shrinking be considered?
300 if (MaxMetaspaceFreeRatio < 100) {
301 const double maximum_free_percentage = MaxMetaspaceFreeRatio / 100.0;
302 const double minimum_used_percentage = 1.0 - maximum_free_percentage;
303 const double max_tmp = used_after_gc / minimum_used_percentage;
304 size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(MaxMetaspaceSize));
305 maximum_desired_capacity = MAX2(maximum_desired_capacity,
306 MetaspaceSize);
307 log_trace(gc, metaspace)(" maximum_free_percentage: %6.2f minimum_used_percentage: %6.2f",
308 maximum_free_percentage, minimum_used_percentage);
309 log_trace(gc, metaspace)(" minimum_desired_capacity: %6.1fKB maximum_desired_capacity: %6.1fKB",
310 minimum_desired_capacity / (double) K, maximum_desired_capacity / (double) K);
311
312 assert(minimum_desired_capacity <= maximum_desired_capacity,
313 "sanity check");
314
315 if (capacity_until_GC > maximum_desired_capacity) {
316 // Capacity too large, compute shrinking size
317 shrink_bytes = capacity_until_GC - maximum_desired_capacity;
318 // We don't want shrink all the way back to initSize if people call
319 // System.gc(), because some programs do that between "phases" and then
320 // we'd just have to grow the heap up again for the next phase. So we
321 // damp the shrinking: 0% on the first call, 10% on the second call, 40%
322 // on the third call, and 100% by the fourth call. But if we recompute
323 // size without shrinking, it goes back to 0%.
324 shrink_bytes = shrink_bytes / 100 * current_shrink_factor;
325
326 shrink_bytes = align_down(shrink_bytes, Metaspace::commit_alignment());
327
328 assert(shrink_bytes <= max_shrink_bytes,
329 "invalid shrink size " SIZE_FORMAT " not <= " SIZE_FORMAT,
330 shrink_bytes, max_shrink_bytes);
331 if (current_shrink_factor == 0) {
332 _shrink_factor = 10;
333 } else {
334 _shrink_factor = MIN2(current_shrink_factor * 4, (uint) 100);
335 }
336 log_trace(gc, metaspace)(" shrinking: initThreshold: %.1fK maximum_desired_capacity: %.1fK",
337 MetaspaceSize / (double) K, maximum_desired_capacity / (double) K);
338 log_trace(gc, metaspace)(" shrink_bytes: %.1fK current_shrink_factor: %d new shrink factor: %d MinMetaspaceExpansion: %.1fK",
339 shrink_bytes / (double) K, current_shrink_factor, _shrink_factor, MinMetaspaceExpansion / (double) K);
340 }
341 }
342
343 // Don't shrink unless it's significant
344 if (shrink_bytes >= MinMetaspaceExpansion &&
345 ((capacity_until_GC - shrink_bytes) >= MetaspaceSize)) {
346 size_t new_capacity_until_GC = MetaspaceGC::dec_capacity_until_GC(shrink_bytes);
347 Metaspace::tracer()->report_gc_threshold(capacity_until_GC,
348 new_capacity_until_GC,
349 MetaspaceGCThresholdUpdater::ComputeNewSize);
350 }
351 }
352
353 // MetaspaceUtils
354 size_t MetaspaceUtils::_capacity_words [Metaspace:: MetadataTypeCount] = {0, 0};
355 size_t MetaspaceUtils::_overhead_words [Metaspace:: MetadataTypeCount] = {0, 0};
356 volatile size_t MetaspaceUtils::_used_words [Metaspace:: MetadataTypeCount] = {0, 0};
357
358 // Collect used metaspace statistics. This involves walking the CLDG. The resulting
359 // output will be the accumulated values for all live metaspaces.
360 // Note: method does not do any locking.
collect_statistics(ClassLoaderMetaspaceStatistics * out)361 void MetaspaceUtils::collect_statistics(ClassLoaderMetaspaceStatistics* out) {
362 out->reset();
363 ClassLoaderDataGraphMetaspaceIterator iter;
364 while (iter.repeat()) {
365 ClassLoaderMetaspace* msp = iter.get_next();
366 if (msp != NULL) {
367 msp->add_to_statistics(out);
368 }
369 }
370 }
371
free_in_vs_bytes(Metaspace::MetadataType mdtype)372 size_t MetaspaceUtils::free_in_vs_bytes(Metaspace::MetadataType mdtype) {
373 VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
374 return list == NULL ? 0 : list->free_bytes();
375 }
376
free_in_vs_bytes()377 size_t MetaspaceUtils::free_in_vs_bytes() {
378 return free_in_vs_bytes(Metaspace::ClassType) + free_in_vs_bytes(Metaspace::NonClassType);
379 }
380
inc_stat_nonatomically(size_t * pstat,size_t words)381 static void inc_stat_nonatomically(size_t* pstat, size_t words) {
382 assert_lock_strong(MetaspaceExpand_lock);
383 (*pstat) += words;
384 }
385
dec_stat_nonatomically(size_t * pstat,size_t words)386 static void dec_stat_nonatomically(size_t* pstat, size_t words) {
387 assert_lock_strong(MetaspaceExpand_lock);
388 const size_t size_now = *pstat;
389 assert(size_now >= words, "About to decrement counter below zero "
390 "(current value: " SIZE_FORMAT ", decrement value: " SIZE_FORMAT ".",
391 size_now, words);
392 *pstat = size_now - words;
393 }
394
inc_stat_atomically(volatile size_t * pstat,size_t words)395 static void inc_stat_atomically(volatile size_t* pstat, size_t words) {
396 Atomic::add(words, pstat);
397 }
398
dec_stat_atomically(volatile size_t * pstat,size_t words)399 static void dec_stat_atomically(volatile size_t* pstat, size_t words) {
400 const size_t size_now = *pstat;
401 assert(size_now >= words, "About to decrement counter below zero "
402 "(current value: " SIZE_FORMAT ", decrement value: " SIZE_FORMAT ".",
403 size_now, words);
404 Atomic::sub(words, pstat);
405 }
406
dec_capacity(Metaspace::MetadataType mdtype,size_t words)407 void MetaspaceUtils::dec_capacity(Metaspace::MetadataType mdtype, size_t words) {
408 dec_stat_nonatomically(&_capacity_words[mdtype], words);
409 }
inc_capacity(Metaspace::MetadataType mdtype,size_t words)410 void MetaspaceUtils::inc_capacity(Metaspace::MetadataType mdtype, size_t words) {
411 inc_stat_nonatomically(&_capacity_words[mdtype], words);
412 }
dec_used(Metaspace::MetadataType mdtype,size_t words)413 void MetaspaceUtils::dec_used(Metaspace::MetadataType mdtype, size_t words) {
414 dec_stat_atomically(&_used_words[mdtype], words);
415 }
inc_used(Metaspace::MetadataType mdtype,size_t words)416 void MetaspaceUtils::inc_used(Metaspace::MetadataType mdtype, size_t words) {
417 inc_stat_atomically(&_used_words[mdtype], words);
418 }
dec_overhead(Metaspace::MetadataType mdtype,size_t words)419 void MetaspaceUtils::dec_overhead(Metaspace::MetadataType mdtype, size_t words) {
420 dec_stat_nonatomically(&_overhead_words[mdtype], words);
421 }
inc_overhead(Metaspace::MetadataType mdtype,size_t words)422 void MetaspaceUtils::inc_overhead(Metaspace::MetadataType mdtype, size_t words) {
423 inc_stat_nonatomically(&_overhead_words[mdtype], words);
424 }
425
reserved_bytes(Metaspace::MetadataType mdtype)426 size_t MetaspaceUtils::reserved_bytes(Metaspace::MetadataType mdtype) {
427 VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
428 return list == NULL ? 0 : list->reserved_bytes();
429 }
430
committed_bytes(Metaspace::MetadataType mdtype)431 size_t MetaspaceUtils::committed_bytes(Metaspace::MetadataType mdtype) {
432 VirtualSpaceList* list = Metaspace::get_space_list(mdtype);
433 return list == NULL ? 0 : list->committed_bytes();
434 }
435
min_chunk_size_words()436 size_t MetaspaceUtils::min_chunk_size_words() { return Metaspace::first_chunk_word_size(); }
437
free_chunks_total_words(Metaspace::MetadataType mdtype)438 size_t MetaspaceUtils::free_chunks_total_words(Metaspace::MetadataType mdtype) {
439 ChunkManager* chunk_manager = Metaspace::get_chunk_manager(mdtype);
440 if (chunk_manager == NULL) {
441 return 0;
442 }
443 chunk_manager->slow_verify();
444 return chunk_manager->free_chunks_total_words();
445 }
446
free_chunks_total_bytes(Metaspace::MetadataType mdtype)447 size_t MetaspaceUtils::free_chunks_total_bytes(Metaspace::MetadataType mdtype) {
448 return free_chunks_total_words(mdtype) * BytesPerWord;
449 }
450
free_chunks_total_words()451 size_t MetaspaceUtils::free_chunks_total_words() {
452 return free_chunks_total_words(Metaspace::ClassType) +
453 free_chunks_total_words(Metaspace::NonClassType);
454 }
455
free_chunks_total_bytes()456 size_t MetaspaceUtils::free_chunks_total_bytes() {
457 return free_chunks_total_words() * BytesPerWord;
458 }
459
has_chunk_free_list(Metaspace::MetadataType mdtype)460 bool MetaspaceUtils::has_chunk_free_list(Metaspace::MetadataType mdtype) {
461 return Metaspace::get_chunk_manager(mdtype) != NULL;
462 }
463
chunk_free_list_summary(Metaspace::MetadataType mdtype)464 MetaspaceChunkFreeListSummary MetaspaceUtils::chunk_free_list_summary(Metaspace::MetadataType mdtype) {
465 if (!has_chunk_free_list(mdtype)) {
466 return MetaspaceChunkFreeListSummary();
467 }
468
469 const ChunkManager* cm = Metaspace::get_chunk_manager(mdtype);
470 return cm->chunk_free_list_summary();
471 }
472
print_metaspace_change(size_t prev_metadata_used)473 void MetaspaceUtils::print_metaspace_change(size_t prev_metadata_used) {
474 log_info(gc, metaspace)("Metaspace: " SIZE_FORMAT "K->" SIZE_FORMAT "K(" SIZE_FORMAT "K)",
475 prev_metadata_used/K, used_bytes()/K, reserved_bytes()/K);
476 }
477
print_on(outputStream * out)478 void MetaspaceUtils::print_on(outputStream* out) {
479 Metaspace::MetadataType nct = Metaspace::NonClassType;
480
481 out->print_cr(" Metaspace "
482 "used " SIZE_FORMAT "K, "
483 "capacity " SIZE_FORMAT "K, "
484 "committed " SIZE_FORMAT "K, "
485 "reserved " SIZE_FORMAT "K",
486 used_bytes()/K,
487 capacity_bytes()/K,
488 committed_bytes()/K,
489 reserved_bytes()/K);
490
491 if (Metaspace::using_class_space()) {
492 Metaspace::MetadataType ct = Metaspace::ClassType;
493 out->print_cr(" class space "
494 "used " SIZE_FORMAT "K, "
495 "capacity " SIZE_FORMAT "K, "
496 "committed " SIZE_FORMAT "K, "
497 "reserved " SIZE_FORMAT "K",
498 used_bytes(ct)/K,
499 capacity_bytes(ct)/K,
500 committed_bytes(ct)/K,
501 reserved_bytes(ct)/K);
502 }
503 }
504
505
print_vs(outputStream * out,size_t scale)506 void MetaspaceUtils::print_vs(outputStream* out, size_t scale) {
507 const size_t reserved_nonclass_words = reserved_bytes(Metaspace::NonClassType) / sizeof(MetaWord);
508 const size_t committed_nonclass_words = committed_bytes(Metaspace::NonClassType) / sizeof(MetaWord);
509 {
510 if (Metaspace::using_class_space()) {
511 out->print(" Non-class space: ");
512 }
513 print_scaled_words(out, reserved_nonclass_words, scale, 7);
514 out->print(" reserved, ");
515 print_scaled_words_and_percentage(out, committed_nonclass_words, reserved_nonclass_words, scale, 7);
516 out->print_cr(" committed ");
517
518 if (Metaspace::using_class_space()) {
519 const size_t reserved_class_words = reserved_bytes(Metaspace::ClassType) / sizeof(MetaWord);
520 const size_t committed_class_words = committed_bytes(Metaspace::ClassType) / sizeof(MetaWord);
521 out->print(" Class space: ");
522 print_scaled_words(out, reserved_class_words, scale, 7);
523 out->print(" reserved, ");
524 print_scaled_words_and_percentage(out, committed_class_words, reserved_class_words, scale, 7);
525 out->print_cr(" committed ");
526
527 const size_t reserved_words = reserved_nonclass_words + reserved_class_words;
528 const size_t committed_words = committed_nonclass_words + committed_class_words;
529 out->print(" Both: ");
530 print_scaled_words(out, reserved_words, scale, 7);
531 out->print(" reserved, ");
532 print_scaled_words_and_percentage(out, committed_words, reserved_words, scale, 7);
533 out->print_cr(" committed ");
534 }
535 }
536 }
537
print_basic_switches(outputStream * out,size_t scale)538 static void print_basic_switches(outputStream* out, size_t scale) {
539 out->print("MaxMetaspaceSize: ");
540 if (MaxMetaspaceSize >= (max_uintx) - (2 * os::vm_page_size())) {
541 // aka "very big". Default is max_uintx, but due to rounding in arg parsing the real
542 // value is smaller.
543 out->print("unlimited");
544 } else {
545 print_human_readable_size(out, MaxMetaspaceSize, scale);
546 }
547 out->cr();
548 if (Metaspace::using_class_space()) {
549 out->print("CompressedClassSpaceSize: ");
550 print_human_readable_size(out, CompressedClassSpaceSize, scale);
551 } else {
552 out->print("No class space");
553 }
554 out->cr();
555 out->print("Initial GC threshold: ");
556 print_human_readable_size(out, MetaspaceSize, scale);
557 out->cr();
558 out->print("Current GC threshold: ");
559 print_human_readable_size(out, MetaspaceGC::capacity_until_GC(), scale);
560 out->cr();
561 out->print_cr("CDS: %s", (UseSharedSpaces ? "on" : (DumpSharedSpaces ? "dump" : "off")));
562 }
563
564 // This will print out a basic metaspace usage report but
565 // unlike print_report() is guaranteed not to lock or to walk the CLDG.
print_basic_report(outputStream * out,size_t scale)566 void MetaspaceUtils::print_basic_report(outputStream* out, size_t scale) {
567
568 if (!Metaspace::initialized()) {
569 out->print_cr("Metaspace not yet initialized.");
570 return;
571 }
572
573 out->cr();
574 out->print_cr("Usage:");
575
576 if (Metaspace::using_class_space()) {
577 out->print(" Non-class: ");
578 }
579
580 // In its most basic form, we do not require walking the CLDG. Instead, just print the running totals from
581 // MetaspaceUtils.
582 const size_t cap_nc = MetaspaceUtils::capacity_words(Metaspace::NonClassType);
583 const size_t overhead_nc = MetaspaceUtils::overhead_words(Metaspace::NonClassType);
584 const size_t used_nc = MetaspaceUtils::used_words(Metaspace::NonClassType);
585 const size_t free_and_waste_nc = cap_nc - overhead_nc - used_nc;
586
587 print_scaled_words(out, cap_nc, scale, 5);
588 out->print(" capacity, ");
589 print_scaled_words_and_percentage(out, used_nc, cap_nc, scale, 5);
590 out->print(" used, ");
591 print_scaled_words_and_percentage(out, free_and_waste_nc, cap_nc, scale, 5);
592 out->print(" free+waste, ");
593 print_scaled_words_and_percentage(out, overhead_nc, cap_nc, scale, 5);
594 out->print(" overhead. ");
595 out->cr();
596
597 if (Metaspace::using_class_space()) {
598 const size_t cap_c = MetaspaceUtils::capacity_words(Metaspace::ClassType);
599 const size_t overhead_c = MetaspaceUtils::overhead_words(Metaspace::ClassType);
600 const size_t used_c = MetaspaceUtils::used_words(Metaspace::ClassType);
601 const size_t free_and_waste_c = cap_c - overhead_c - used_c;
602 out->print(" Class: ");
603 print_scaled_words(out, cap_c, scale, 5);
604 out->print(" capacity, ");
605 print_scaled_words_and_percentage(out, used_c, cap_c, scale, 5);
606 out->print(" used, ");
607 print_scaled_words_and_percentage(out, free_and_waste_c, cap_c, scale, 5);
608 out->print(" free+waste, ");
609 print_scaled_words_and_percentage(out, overhead_c, cap_c, scale, 5);
610 out->print(" overhead. ");
611 out->cr();
612
613 out->print(" Both: ");
614 const size_t cap = cap_nc + cap_c;
615
616 print_scaled_words(out, cap, scale, 5);
617 out->print(" capacity, ");
618 print_scaled_words_and_percentage(out, used_nc + used_c, cap, scale, 5);
619 out->print(" used, ");
620 print_scaled_words_and_percentage(out, free_and_waste_nc + free_and_waste_c, cap, scale, 5);
621 out->print(" free+waste, ");
622 print_scaled_words_and_percentage(out, overhead_nc + overhead_c, cap, scale, 5);
623 out->print(" overhead. ");
624 out->cr();
625 }
626
627 out->cr();
628 out->print_cr("Virtual space:");
629
630 print_vs(out, scale);
631
632 out->cr();
633 out->print_cr("Chunk freelists:");
634
635 if (Metaspace::using_class_space()) {
636 out->print(" Non-Class: ");
637 }
638 print_human_readable_size(out, Metaspace::chunk_manager_metadata()->free_chunks_total_bytes(), scale);
639 out->cr();
640 if (Metaspace::using_class_space()) {
641 out->print(" Class: ");
642 print_human_readable_size(out, Metaspace::chunk_manager_class()->free_chunks_total_bytes(), scale);
643 out->cr();
644 out->print(" Both: ");
645 print_human_readable_size(out, Metaspace::chunk_manager_class()->free_chunks_total_bytes() +
646 Metaspace::chunk_manager_metadata()->free_chunks_total_bytes(), scale);
647 out->cr();
648 }
649
650 out->cr();
651
652 // Print basic settings
653 print_basic_switches(out, scale);
654
655 out->cr();
656
657 }
658
print_report(outputStream * out,size_t scale,int flags)659 void MetaspaceUtils::print_report(outputStream* out, size_t scale, int flags) {
660
661 if (!Metaspace::initialized()) {
662 out->print_cr("Metaspace not yet initialized.");
663 return;
664 }
665
666 const bool print_loaders = (flags & rf_show_loaders) > 0;
667 const bool print_classes = (flags & rf_show_classes) > 0;
668 const bool print_by_chunktype = (flags & rf_break_down_by_chunktype) > 0;
669 const bool print_by_spacetype = (flags & rf_break_down_by_spacetype) > 0;
670
671 // Some report options require walking the class loader data graph.
672 PrintCLDMetaspaceInfoClosure cl(out, scale, print_loaders, print_classes, print_by_chunktype);
673 if (print_loaders) {
674 out->cr();
675 out->print_cr("Usage per loader:");
676 out->cr();
677 }
678
679 ClassLoaderDataGraph::cld_do(&cl); // collect data and optionally print
680
681 // Print totals, broken up by space type.
682 if (print_by_spacetype) {
683 out->cr();
684 out->print_cr("Usage per space type:");
685 out->cr();
686 for (int space_type = (int)Metaspace::ZeroMetaspaceType;
687 space_type < (int)Metaspace::MetaspaceTypeCount; space_type ++)
688 {
689 uintx num_loaders = cl._num_loaders_by_spacetype[space_type];
690 uintx num_classes = cl._num_classes_by_spacetype[space_type];
691 out->print("%s - " UINTX_FORMAT " %s",
692 space_type_name((Metaspace::MetaspaceType)space_type),
693 num_loaders, loaders_plural(num_loaders));
694 if (num_classes > 0) {
695 out->print(", ");
696 print_number_of_classes(out, num_classes, cl._num_classes_shared_by_spacetype[space_type]);
697 out->print(":");
698 cl._stats_by_spacetype[space_type].print_on(out, scale, print_by_chunktype);
699 } else {
700 out->print(".");
701 out->cr();
702 }
703 out->cr();
704 }
705 }
706
707 // Print totals for in-use data:
708 out->cr();
709 {
710 uintx num_loaders = cl._num_loaders;
711 out->print("Total Usage - " UINTX_FORMAT " %s, ",
712 num_loaders, loaders_plural(num_loaders));
713 print_number_of_classes(out, cl._num_classes, cl._num_classes_shared);
714 out->print(":");
715 cl._stats_total.print_on(out, scale, print_by_chunktype);
716 out->cr();
717 }
718
719 // -- Print Virtual space.
720 out->cr();
721 out->print_cr("Virtual space:");
722
723 print_vs(out, scale);
724
725 // -- Print VirtualSpaceList details.
726 if ((flags & rf_show_vslist) > 0) {
727 out->cr();
728 out->print_cr("Virtual space list%s:", Metaspace::using_class_space() ? "s" : "");
729
730 if (Metaspace::using_class_space()) {
731 out->print_cr(" Non-Class:");
732 }
733 Metaspace::space_list()->print_on(out, scale);
734 if (Metaspace::using_class_space()) {
735 out->print_cr(" Class:");
736 Metaspace::class_space_list()->print_on(out, scale);
737 }
738 }
739 out->cr();
740
741 // -- Print VirtualSpaceList map.
742 if ((flags & rf_show_vsmap) > 0) {
743 out->cr();
744 out->print_cr("Virtual space map:");
745
746 if (Metaspace::using_class_space()) {
747 out->print_cr(" Non-Class:");
748 }
749 Metaspace::space_list()->print_map(out);
750 if (Metaspace::using_class_space()) {
751 out->print_cr(" Class:");
752 Metaspace::class_space_list()->print_map(out);
753 }
754 }
755 out->cr();
756
757 // -- Print Freelists (ChunkManager) details
758 out->cr();
759 out->print_cr("Chunk freelist%s:", Metaspace::using_class_space() ? "s" : "");
760
761 ChunkManagerStatistics non_class_cm_stat;
762 Metaspace::chunk_manager_metadata()->collect_statistics(&non_class_cm_stat);
763
764 if (Metaspace::using_class_space()) {
765 out->print_cr(" Non-Class:");
766 }
767 non_class_cm_stat.print_on(out, scale);
768
769 if (Metaspace::using_class_space()) {
770 ChunkManagerStatistics class_cm_stat;
771 Metaspace::chunk_manager_class()->collect_statistics(&class_cm_stat);
772 out->print_cr(" Class:");
773 class_cm_stat.print_on(out, scale);
774 }
775
776 // As a convenience, print a summary of common waste.
777 out->cr();
778 out->print("Waste ");
779 // For all wastages, print percentages from total. As total use the total size of memory committed for metaspace.
780 const size_t committed_words = committed_bytes() / BytesPerWord;
781
782 out->print("(percentages refer to total committed size ");
783 print_scaled_words(out, committed_words, scale);
784 out->print_cr("):");
785
786 // Print space committed but not yet used by any class loader
787 const size_t unused_words_in_vs = MetaspaceUtils::free_in_vs_bytes() / BytesPerWord;
788 out->print(" Committed unused: ");
789 print_scaled_words_and_percentage(out, unused_words_in_vs, committed_words, scale, 6);
790 out->cr();
791
792 // Print waste for in-use chunks.
793 UsedChunksStatistics ucs_nonclass = cl._stats_total.nonclass_sm_stats().totals();
794 UsedChunksStatistics ucs_class = cl._stats_total.class_sm_stats().totals();
795 UsedChunksStatistics ucs_all;
796 ucs_all.add(ucs_nonclass);
797 ucs_all.add(ucs_class);
798
799 out->print(" Waste in chunks in use: ");
800 print_scaled_words_and_percentage(out, ucs_all.waste(), committed_words, scale, 6);
801 out->cr();
802 out->print(" Free in chunks in use: ");
803 print_scaled_words_and_percentage(out, ucs_all.free(), committed_words, scale, 6);
804 out->cr();
805 out->print(" Overhead in chunks in use: ");
806 print_scaled_words_and_percentage(out, ucs_all.overhead(), committed_words, scale, 6);
807 out->cr();
808
809 // Print waste in free chunks.
810 const size_t total_capacity_in_free_chunks =
811 Metaspace::chunk_manager_metadata()->free_chunks_total_words() +
812 (Metaspace::using_class_space() ? Metaspace::chunk_manager_class()->free_chunks_total_words() : 0);
813 out->print(" In free chunks: ");
814 print_scaled_words_and_percentage(out, total_capacity_in_free_chunks, committed_words, scale, 6);
815 out->cr();
816
817 // Print waste in deallocated blocks.
818 const uintx free_blocks_num =
819 cl._stats_total.nonclass_sm_stats().free_blocks_num() +
820 cl._stats_total.class_sm_stats().free_blocks_num();
821 const size_t free_blocks_cap_words =
822 cl._stats_total.nonclass_sm_stats().free_blocks_cap_words() +
823 cl._stats_total.class_sm_stats().free_blocks_cap_words();
824 out->print("Deallocated from chunks in use: ");
825 print_scaled_words_and_percentage(out, free_blocks_cap_words, committed_words, scale, 6);
826 out->print(" (" UINTX_FORMAT " blocks)", free_blocks_num);
827 out->cr();
828
829 // Print total waste.
830 const size_t total_waste = ucs_all.waste() + ucs_all.free() + ucs_all.overhead() + total_capacity_in_free_chunks
831 + free_blocks_cap_words + unused_words_in_vs;
832 out->print(" -total-: ");
833 print_scaled_words_and_percentage(out, total_waste, committed_words, scale, 6);
834 out->cr();
835
836 // Print internal statistics
837 #ifdef ASSERT
838 out->cr();
839 out->cr();
840 out->print_cr("Internal statistics:");
841 out->cr();
842 out->print_cr("Number of allocations: " UINTX_FORMAT ".", g_internal_statistics.num_allocs);
843 out->print_cr("Number of space births: " UINTX_FORMAT ".", g_internal_statistics.num_metaspace_births);
844 out->print_cr("Number of space deaths: " UINTX_FORMAT ".", g_internal_statistics.num_metaspace_deaths);
845 out->print_cr("Number of virtual space node births: " UINTX_FORMAT ".", g_internal_statistics.num_vsnodes_created);
846 out->print_cr("Number of virtual space node deaths: " UINTX_FORMAT ".", g_internal_statistics.num_vsnodes_purged);
847 out->print_cr("Number of times virtual space nodes were expanded: " UINTX_FORMAT ".", g_internal_statistics.num_committed_space_expanded);
848 out->print_cr("Number of deallocations: " UINTX_FORMAT " (" UINTX_FORMAT " external).", g_internal_statistics.num_deallocs, g_internal_statistics.num_external_deallocs);
849 out->print_cr("Allocations from deallocated blocks: " UINTX_FORMAT ".", g_internal_statistics.num_allocs_from_deallocated_blocks);
850 out->cr();
851 #endif
852
853 // Print some interesting settings
854 out->cr();
855 out->cr();
856 print_basic_switches(out, scale);
857
858 out->cr();
859 out->print("InitialBootClassLoaderMetaspaceSize: ");
860 print_human_readable_size(out, InitialBootClassLoaderMetaspaceSize, scale);
861
862 out->cr();
863 out->cr();
864
865 } // MetaspaceUtils::print_report()
866
867 // Prints an ASCII representation of the given space.
print_metaspace_map(outputStream * out,Metaspace::MetadataType mdtype)868 void MetaspaceUtils::print_metaspace_map(outputStream* out, Metaspace::MetadataType mdtype) {
869 MutexLockerEx cl(MetaspaceExpand_lock, Mutex::_no_safepoint_check_flag);
870 const bool for_class = mdtype == Metaspace::ClassType ? true : false;
871 VirtualSpaceList* const vsl = for_class ? Metaspace::class_space_list() : Metaspace::space_list();
872 if (vsl != NULL) {
873 if (for_class) {
874 if (!Metaspace::using_class_space()) {
875 out->print_cr("No Class Space.");
876 return;
877 }
878 out->print_raw("---- Metaspace Map (Class Space) ----");
879 } else {
880 out->print_raw("---- Metaspace Map (Non-Class Space) ----");
881 }
882 // Print legend:
883 out->cr();
884 out->print_cr("Chunk Types (uppercase chunks are in use): x-specialized, s-small, m-medium, h-humongous.");
885 out->cr();
886 VirtualSpaceList* const vsl = for_class ? Metaspace::class_space_list() : Metaspace::space_list();
887 vsl->print_map(out);
888 out->cr();
889 }
890 }
891
verify_free_chunks()892 void MetaspaceUtils::verify_free_chunks() {
893 Metaspace::chunk_manager_metadata()->verify();
894 if (Metaspace::using_class_space()) {
895 Metaspace::chunk_manager_class()->verify();
896 }
897 }
898
verify_metrics()899 void MetaspaceUtils::verify_metrics() {
900 #ifdef ASSERT
901 // Please note: there are time windows where the internal counters are out of sync with
902 // reality. For example, when a newly created ClassLoaderMetaspace creates its first chunk -
903 // the ClassLoaderMetaspace is not yet attached to its ClassLoaderData object and hence will
904 // not be counted when iterating the CLDG. So be careful when you call this method.
905 ClassLoaderMetaspaceStatistics total_stat;
906 collect_statistics(&total_stat);
907 UsedChunksStatistics nonclass_chunk_stat = total_stat.nonclass_sm_stats().totals();
908 UsedChunksStatistics class_chunk_stat = total_stat.class_sm_stats().totals();
909
910 bool mismatch = false;
911 for (int i = 0; i < Metaspace::MetadataTypeCount; i ++) {
912 Metaspace::MetadataType mdtype = (Metaspace::MetadataType)i;
913 UsedChunksStatistics chunk_stat = total_stat.sm_stats(mdtype).totals();
914 if (capacity_words(mdtype) != chunk_stat.cap() ||
915 used_words(mdtype) != chunk_stat.used() ||
916 overhead_words(mdtype) != chunk_stat.overhead()) {
917 mismatch = true;
918 tty->print_cr("MetaspaceUtils::verify_metrics: counter mismatch for mdtype=%u:", mdtype);
919 tty->print_cr("Expected cap " SIZE_FORMAT ", used " SIZE_FORMAT ", overhead " SIZE_FORMAT ".",
920 capacity_words(mdtype), used_words(mdtype), overhead_words(mdtype));
921 tty->print_cr("Got cap " SIZE_FORMAT ", used " SIZE_FORMAT ", overhead " SIZE_FORMAT ".",
922 chunk_stat.cap(), chunk_stat.used(), chunk_stat.overhead());
923 tty->flush();
924 }
925 }
926 assert(mismatch == false, "MetaspaceUtils::verify_metrics: counter mismatch.");
927 #endif
928 }
929
930 // Utils to check if a pointer or range is part of a committed metaspace region.
find_enclosing_virtual_space(const void * p)931 metaspace::VirtualSpaceNode* MetaspaceUtils::find_enclosing_virtual_space(const void* p) {
932 VirtualSpaceNode* vsn = Metaspace::space_list()->find_enclosing_space(p);
933 if (Metaspace::using_class_space() && vsn == NULL) {
934 vsn = Metaspace::class_space_list()->find_enclosing_space(p);
935 }
936 return vsn;
937 }
938
is_in_committed(const void * p)939 bool MetaspaceUtils::is_in_committed(const void* p) {
940 #if INCLUDE_CDS
941 if (UseSharedSpaces) {
942 for (int idx = MetaspaceShared::ro; idx <= MetaspaceShared::mc; idx++) {
943 if (FileMapInfo::current_info()->is_in_shared_region(p, idx)) {
944 return true;
945 }
946 }
947 }
948 #endif
949 return find_enclosing_virtual_space(p) != NULL;
950 }
951
is_range_in_committed(const void * from,const void * to)952 bool MetaspaceUtils::is_range_in_committed(const void* from, const void* to) {
953 #if INCLUDE_CDS
954 if (UseSharedSpaces) {
955 for (int idx = MetaspaceShared::ro; idx <= MetaspaceShared::mc; idx++) {
956 if (FileMapInfo::current_info()->is_in_shared_region(from, idx)) {
957 return FileMapInfo::current_info()->is_in_shared_region(to, idx);
958 }
959 }
960 }
961 #endif
962 VirtualSpaceNode* vsn = find_enclosing_virtual_space(from);
963 return (vsn != NULL) && vsn->contains(to);
964 }
965
966
967 // Metaspace methods
968
969 size_t Metaspace::_first_chunk_word_size = 0;
970 size_t Metaspace::_first_class_chunk_word_size = 0;
971
972 size_t Metaspace::_commit_alignment = 0;
973 size_t Metaspace::_reserve_alignment = 0;
974
975 VirtualSpaceList* Metaspace::_space_list = NULL;
976 VirtualSpaceList* Metaspace::_class_space_list = NULL;
977
978 ChunkManager* Metaspace::_chunk_manager_metadata = NULL;
979 ChunkManager* Metaspace::_chunk_manager_class = NULL;
980
981 bool Metaspace::_initialized = false;
982
983 #define VIRTUALSPACEMULTIPLIER 2
984
985 #ifdef _LP64
986 static const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
987
set_narrow_klass_base_and_shift(address metaspace_base,address cds_base)988 void Metaspace::set_narrow_klass_base_and_shift(address metaspace_base, address cds_base) {
989 assert(!DumpSharedSpaces, "narrow_klass is set by MetaspaceShared class.");
990 // Figure out the narrow_klass_base and the narrow_klass_shift. The
991 // narrow_klass_base is the lower of the metaspace base and the cds base
992 // (if cds is enabled). The narrow_klass_shift depends on the distance
993 // between the lower base and higher address.
994 address lower_base;
995 address higher_address;
996 #if INCLUDE_CDS
997 if (UseSharedSpaces) {
998 higher_address = MAX2((address)(cds_base + MetaspaceShared::core_spaces_size()),
999 (address)(metaspace_base + compressed_class_space_size()));
1000 lower_base = MIN2(metaspace_base, cds_base);
1001 } else
1002 #endif
1003 {
1004 higher_address = metaspace_base + compressed_class_space_size();
1005 lower_base = metaspace_base;
1006
1007 uint64_t klass_encoding_max = UnscaledClassSpaceMax << LogKlassAlignmentInBytes;
1008 // If compressed class space fits in lower 32G, we don't need a base.
1009 if (higher_address <= (address)klass_encoding_max) {
1010 lower_base = 0; // Effectively lower base is zero.
1011 }
1012 }
1013
1014 Universe::set_narrow_klass_base(lower_base);
1015
1016 // CDS uses LogKlassAlignmentInBytes for narrow_klass_shift. See
1017 // MetaspaceShared::initialize_dumptime_shared_and_meta_spaces() for
1018 // how dump time narrow_klass_shift is set. Although, CDS can work
1019 // with zero-shift mode also, to be consistent with AOT it uses
1020 // LogKlassAlignmentInBytes for klass shift so archived java heap objects
1021 // can be used at same time as AOT code.
1022 if (!UseSharedSpaces
1023 && (uint64_t)(higher_address - lower_base) <= UnscaledClassSpaceMax) {
1024 Universe::set_narrow_klass_shift(0);
1025 } else {
1026 Universe::set_narrow_klass_shift(LogKlassAlignmentInBytes);
1027 }
1028 AOTLoader::set_narrow_klass_shift();
1029 }
1030
1031 #if INCLUDE_CDS
1032 // Return TRUE if the specified metaspace_base and cds_base are close enough
1033 // to work with compressed klass pointers.
can_use_cds_with_metaspace_addr(char * metaspace_base,address cds_base)1034 bool Metaspace::can_use_cds_with_metaspace_addr(char* metaspace_base, address cds_base) {
1035 assert(cds_base != 0 && UseSharedSpaces, "Only use with CDS");
1036 assert(UseCompressedClassPointers, "Only use with CompressedKlassPtrs");
1037 address lower_base = MIN2((address)metaspace_base, cds_base);
1038 address higher_address = MAX2((address)(cds_base + MetaspaceShared::core_spaces_size()),
1039 (address)(metaspace_base + compressed_class_space_size()));
1040 return ((uint64_t)(higher_address - lower_base) <= UnscaledClassSpaceMax);
1041 }
1042 #endif
1043
1044 // Try to allocate the metaspace at the requested addr.
allocate_metaspace_compressed_klass_ptrs(char * requested_addr,address cds_base)1045 void Metaspace::allocate_metaspace_compressed_klass_ptrs(char* requested_addr, address cds_base) {
1046 assert(!DumpSharedSpaces, "compress klass space is allocated by MetaspaceShared class.");
1047 assert(using_class_space(), "called improperly");
1048 assert(UseCompressedClassPointers, "Only use with CompressedKlassPtrs");
1049 assert(compressed_class_space_size() < KlassEncodingMetaspaceMax,
1050 "Metaspace size is too big");
1051 assert_is_aligned(requested_addr, _reserve_alignment);
1052 assert_is_aligned(cds_base, _reserve_alignment);
1053 assert_is_aligned(compressed_class_space_size(), _reserve_alignment);
1054
1055 // Don't use large pages for the class space.
1056 bool large_pages = false;
1057
1058 #if !(defined(AARCH64) || defined(PPC64))
1059 ReservedSpace metaspace_rs = ReservedSpace(compressed_class_space_size(),
1060 _reserve_alignment,
1061 large_pages,
1062 requested_addr);
1063 #else // AARCH64 || PPC64
1064
1065 ReservedSpace metaspace_rs;
1066
1067 // Our compressed klass pointers may fit nicely into the lower 32
1068 // bits.
1069 if ((uint64_t)requested_addr + compressed_class_space_size() < 4*G) {
1070 metaspace_rs = ReservedSpace(compressed_class_space_size(),
1071 _reserve_alignment,
1072 large_pages,
1073 requested_addr);
1074 }
1075
1076 if (! metaspace_rs.is_reserved()) {
1077 // Aarch64: Try to align metaspace so that we can decode a compressed
1078 // klass with a single MOVK instruction. We can do this iff the
1079 // compressed class base is a multiple of 4G.
1080 // Aix: Search for a place where we can find memory. If we need to load
1081 // the base, 4G alignment is helpful, too.
1082 // PPC64: smaller heaps up to 2g will be mapped just below 4g. Then the
1083 // attempt to place the compressed class space just after the heap fails on
1084 // Linux 4.1.42 and higher because the launcher is loaded at 4g
1085 // (ELF_ET_DYN_BASE). In that case we reach here and search the address space
1086 // below 32g to get a zerobased CCS. For simplicity we reuse the search
1087 // strategy for AARCH64.
1088
1089 size_t increment = AARCH64_ONLY(4*)G;
1090 for (char *a = align_up(requested_addr, increment);
1091 a < (char*)(1024*G);
1092 a += increment) {
1093 if (a == (char *)(32*G)) {
1094 // Go faster from here on. Zero-based is no longer possible.
1095 increment = 4*G;
1096 }
1097
1098 #if INCLUDE_CDS
1099 if (UseSharedSpaces
1100 && ! can_use_cds_with_metaspace_addr(a, cds_base)) {
1101 // We failed to find an aligned base that will reach. Fall
1102 // back to using our requested addr.
1103 metaspace_rs = ReservedSpace(compressed_class_space_size(),
1104 _reserve_alignment,
1105 large_pages,
1106 requested_addr);
1107 break;
1108 }
1109 #endif
1110
1111 metaspace_rs = ReservedSpace(compressed_class_space_size(),
1112 _reserve_alignment,
1113 large_pages,
1114 a);
1115 if (metaspace_rs.is_reserved())
1116 break;
1117 }
1118 }
1119
1120 #endif // AARCH64 || PPC64
1121
1122 if (!metaspace_rs.is_reserved()) {
1123 #if INCLUDE_CDS
1124 if (UseSharedSpaces) {
1125 size_t increment = align_up(1*G, _reserve_alignment);
1126
1127 // Keep trying to allocate the metaspace, increasing the requested_addr
1128 // by 1GB each time, until we reach an address that will no longer allow
1129 // use of CDS with compressed klass pointers.
1130 char *addr = requested_addr;
1131 while (!metaspace_rs.is_reserved() && (addr + increment > addr) &&
1132 can_use_cds_with_metaspace_addr(addr + increment, cds_base)) {
1133 addr = addr + increment;
1134 metaspace_rs = ReservedSpace(compressed_class_space_size(),
1135 _reserve_alignment, large_pages, addr);
1136 }
1137 }
1138 #endif
1139 // If no successful allocation then try to allocate the space anywhere. If
1140 // that fails then OOM doom. At this point we cannot try allocating the
1141 // metaspace as if UseCompressedClassPointers is off because too much
1142 // initialization has happened that depends on UseCompressedClassPointers.
1143 // So, UseCompressedClassPointers cannot be turned off at this point.
1144 if (!metaspace_rs.is_reserved()) {
1145 metaspace_rs = ReservedSpace(compressed_class_space_size(),
1146 _reserve_alignment, large_pages);
1147 if (!metaspace_rs.is_reserved()) {
1148 vm_exit_during_initialization(err_msg("Could not allocate metaspace: " SIZE_FORMAT " bytes",
1149 compressed_class_space_size()));
1150 }
1151 }
1152 }
1153
1154 // If we got here then the metaspace got allocated.
1155 MemTracker::record_virtual_memory_type((address)metaspace_rs.base(), mtClass);
1156
1157 #if INCLUDE_CDS
1158 // Verify that we can use shared spaces. Otherwise, turn off CDS.
1159 if (UseSharedSpaces && !can_use_cds_with_metaspace_addr(metaspace_rs.base(), cds_base)) {
1160 FileMapInfo::stop_sharing_and_unmap(
1161 "Could not allocate metaspace at a compatible address");
1162 }
1163 #endif
1164 set_narrow_klass_base_and_shift((address)metaspace_rs.base(),
1165 UseSharedSpaces ? (address)cds_base : 0);
1166
1167 initialize_class_space(metaspace_rs);
1168
1169 LogTarget(Trace, gc, metaspace) lt;
1170 if (lt.is_enabled()) {
1171 ResourceMark rm;
1172 LogStream ls(lt);
1173 print_compressed_class_space(&ls, requested_addr);
1174 }
1175 }
1176
print_compressed_class_space(outputStream * st,const char * requested_addr)1177 void Metaspace::print_compressed_class_space(outputStream* st, const char* requested_addr) {
1178 st->print_cr("Narrow klass base: " PTR_FORMAT ", Narrow klass shift: %d",
1179 p2i(Universe::narrow_klass_base()), Universe::narrow_klass_shift());
1180 if (_class_space_list != NULL) {
1181 address base = (address)_class_space_list->current_virtual_space()->bottom();
1182 st->print("Compressed class space size: " SIZE_FORMAT " Address: " PTR_FORMAT,
1183 compressed_class_space_size(), p2i(base));
1184 if (requested_addr != 0) {
1185 st->print(" Req Addr: " PTR_FORMAT, p2i(requested_addr));
1186 }
1187 st->cr();
1188 }
1189 }
1190
1191 // For UseCompressedClassPointers the class space is reserved above the top of
1192 // the Java heap. The argument passed in is at the base of the compressed space.
initialize_class_space(ReservedSpace rs)1193 void Metaspace::initialize_class_space(ReservedSpace rs) {
1194 // The reserved space size may be bigger because of alignment, esp with UseLargePages
1195 assert(rs.size() >= CompressedClassSpaceSize,
1196 SIZE_FORMAT " != " SIZE_FORMAT, rs.size(), CompressedClassSpaceSize);
1197 assert(using_class_space(), "Must be using class space");
1198 _class_space_list = new VirtualSpaceList(rs);
1199 _chunk_manager_class = new ChunkManager(true/*is_class*/);
1200
1201 if (!_class_space_list->initialization_succeeded()) {
1202 vm_exit_during_initialization("Failed to setup compressed class space virtual space list.");
1203 }
1204 }
1205
1206 #endif
1207
ergo_initialize()1208 void Metaspace::ergo_initialize() {
1209 if (DumpSharedSpaces) {
1210 // Using large pages when dumping the shared archive is currently not implemented.
1211 FLAG_SET_ERGO(bool, UseLargePagesInMetaspace, false);
1212 }
1213
1214 size_t page_size = os::vm_page_size();
1215 if (UseLargePages && UseLargePagesInMetaspace) {
1216 page_size = os::large_page_size();
1217 }
1218
1219 _commit_alignment = page_size;
1220 _reserve_alignment = MAX2(page_size, (size_t)os::vm_allocation_granularity());
1221
1222 // Do not use FLAG_SET_ERGO to update MaxMetaspaceSize, since this will
1223 // override if MaxMetaspaceSize was set on the command line or not.
1224 // This information is needed later to conform to the specification of the
1225 // java.lang.management.MemoryUsage API.
1226 //
1227 // Ideally, we would be able to set the default value of MaxMetaspaceSize in
1228 // globals.hpp to the aligned value, but this is not possible, since the
1229 // alignment depends on other flags being parsed.
1230 MaxMetaspaceSize = align_down_bounded(MaxMetaspaceSize, _reserve_alignment);
1231
1232 if (MetaspaceSize > MaxMetaspaceSize) {
1233 MetaspaceSize = MaxMetaspaceSize;
1234 }
1235
1236 MetaspaceSize = align_down_bounded(MetaspaceSize, _commit_alignment);
1237
1238 assert(MetaspaceSize <= MaxMetaspaceSize, "MetaspaceSize should be limited by MaxMetaspaceSize");
1239
1240 MinMetaspaceExpansion = align_down_bounded(MinMetaspaceExpansion, _commit_alignment);
1241 MaxMetaspaceExpansion = align_down_bounded(MaxMetaspaceExpansion, _commit_alignment);
1242
1243 CompressedClassSpaceSize = align_down_bounded(CompressedClassSpaceSize, _reserve_alignment);
1244
1245 // Initial virtual space size will be calculated at global_initialize()
1246 size_t min_metaspace_sz =
1247 VIRTUALSPACEMULTIPLIER * InitialBootClassLoaderMetaspaceSize;
1248 if (UseCompressedClassPointers) {
1249 if ((min_metaspace_sz + CompressedClassSpaceSize) > MaxMetaspaceSize) {
1250 if (min_metaspace_sz >= MaxMetaspaceSize) {
1251 vm_exit_during_initialization("MaxMetaspaceSize is too small.");
1252 } else {
1253 FLAG_SET_ERGO(size_t, CompressedClassSpaceSize,
1254 MaxMetaspaceSize - min_metaspace_sz);
1255 }
1256 }
1257 } else if (min_metaspace_sz >= MaxMetaspaceSize) {
1258 FLAG_SET_ERGO(size_t, InitialBootClassLoaderMetaspaceSize,
1259 min_metaspace_sz);
1260 }
1261
1262 set_compressed_class_space_size(CompressedClassSpaceSize);
1263 }
1264
global_initialize()1265 void Metaspace::global_initialize() {
1266 MetaspaceGC::initialize();
1267
1268 #if INCLUDE_CDS
1269 if (DumpSharedSpaces) {
1270 MetaspaceShared::initialize_dumptime_shared_and_meta_spaces();
1271 } else if (UseSharedSpaces) {
1272 // If any of the archived space fails to map, UseSharedSpaces
1273 // is reset to false. Fall through to the
1274 // (!DumpSharedSpaces && !UseSharedSpaces) case to set up class
1275 // metaspace.
1276 MetaspaceShared::initialize_runtime_shared_and_meta_spaces();
1277 }
1278
1279 if (!DumpSharedSpaces && !UseSharedSpaces)
1280 #endif // INCLUDE_CDS
1281 {
1282 #ifdef _LP64
1283 if (using_class_space()) {
1284 char* base = (char*)align_up(Universe::heap()->reserved_region().end(), _reserve_alignment);
1285 allocate_metaspace_compressed_klass_ptrs(base, 0);
1286 }
1287 #endif // _LP64
1288 }
1289
1290 // Initialize these before initializing the VirtualSpaceList
1291 _first_chunk_word_size = InitialBootClassLoaderMetaspaceSize / BytesPerWord;
1292 _first_chunk_word_size = align_word_size_up(_first_chunk_word_size);
1293 // Make the first class chunk bigger than a medium chunk so it's not put
1294 // on the medium chunk list. The next chunk will be small and progress
1295 // from there. This size calculated by -version.
1296 _first_class_chunk_word_size = MIN2((size_t)MediumChunk*6,
1297 (CompressedClassSpaceSize/BytesPerWord)*2);
1298 _first_class_chunk_word_size = align_word_size_up(_first_class_chunk_word_size);
1299 // Arbitrarily set the initial virtual space to a multiple
1300 // of the boot class loader size.
1301 size_t word_size = VIRTUALSPACEMULTIPLIER * _first_chunk_word_size;
1302 word_size = align_up(word_size, Metaspace::reserve_alignment_words());
1303
1304 // Initialize the list of virtual spaces.
1305 _space_list = new VirtualSpaceList(word_size);
1306 _chunk_manager_metadata = new ChunkManager(false/*metaspace*/);
1307
1308 if (!_space_list->initialization_succeeded()) {
1309 vm_exit_during_initialization("Unable to setup metadata virtual space list.", NULL);
1310 }
1311
1312 _tracer = new MetaspaceTracer();
1313
1314 _initialized = true;
1315
1316 }
1317
post_initialize()1318 void Metaspace::post_initialize() {
1319 MetaspaceGC::post_initialize();
1320 }
1321
verify_global_initialization()1322 void Metaspace::verify_global_initialization() {
1323 assert(space_list() != NULL, "Metadata VirtualSpaceList has not been initialized");
1324 assert(chunk_manager_metadata() != NULL, "Metadata ChunkManager has not been initialized");
1325
1326 if (using_class_space()) {
1327 assert(class_space_list() != NULL, "Class VirtualSpaceList has not been initialized");
1328 assert(chunk_manager_class() != NULL, "Class ChunkManager has not been initialized");
1329 }
1330 }
1331
align_word_size_up(size_t word_size)1332 size_t Metaspace::align_word_size_up(size_t word_size) {
1333 size_t byte_size = word_size * wordSize;
1334 return ReservedSpace::allocation_align_size_up(byte_size) / wordSize;
1335 }
1336
allocate(ClassLoaderData * loader_data,size_t word_size,MetaspaceObj::Type type,TRAPS)1337 MetaWord* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size,
1338 MetaspaceObj::Type type, TRAPS) {
1339 assert(!_frozen, "sanity");
1340 assert(!(DumpSharedSpaces && THREAD->is_VM_thread()), "sanity");
1341
1342 if (HAS_PENDING_EXCEPTION) {
1343 assert(false, "Should not allocate with exception pending");
1344 return NULL; // caller does a CHECK_NULL too
1345 }
1346
1347 assert(loader_data != NULL, "Should never pass around a NULL loader_data. "
1348 "ClassLoaderData::the_null_class_loader_data() should have been used.");
1349
1350 MetadataType mdtype = (type == MetaspaceObj::ClassType) ? ClassType : NonClassType;
1351
1352 // Try to allocate metadata.
1353 MetaWord* result = loader_data->metaspace_non_null()->allocate(word_size, mdtype);
1354
1355 if (result == NULL) {
1356 tracer()->report_metaspace_allocation_failure(loader_data, word_size, type, mdtype);
1357
1358 // Allocation failed.
1359 if (is_init_completed()) {
1360 // Only start a GC if the bootstrapping has completed.
1361 // Try to clean out some heap memory and retry. This can prevent premature
1362 // expansion of the metaspace.
1363 result = Universe::heap()->satisfy_failed_metadata_allocation(loader_data, word_size, mdtype);
1364 }
1365 }
1366
1367 if (result == NULL) {
1368 if (DumpSharedSpaces) {
1369 // CDS dumping keeps loading classes, so if we hit an OOM we probably will keep hitting OOM.
1370 // We should abort to avoid generating a potentially bad archive.
1371 tty->print_cr("Failed allocating metaspace object type %s of size " SIZE_FORMAT ". CDS dump aborted.",
1372 MetaspaceObj::type_name(type), word_size * BytesPerWord);
1373 tty->print_cr("Please increase MaxMetaspaceSize (currently " SIZE_FORMAT " bytes).", MaxMetaspaceSize);
1374 vm_exit(1);
1375 }
1376 report_metadata_oome(loader_data, word_size, type, mdtype, THREAD);
1377 assert(HAS_PENDING_EXCEPTION, "sanity");
1378 return NULL;
1379 }
1380
1381 // Zero initialize.
1382 Copy::fill_to_words((HeapWord*)result, word_size, 0);
1383
1384 return result;
1385 }
1386
report_metadata_oome(ClassLoaderData * loader_data,size_t word_size,MetaspaceObj::Type type,MetadataType mdtype,TRAPS)1387 void Metaspace::report_metadata_oome(ClassLoaderData* loader_data, size_t word_size, MetaspaceObj::Type type, MetadataType mdtype, TRAPS) {
1388 tracer()->report_metadata_oom(loader_data, word_size, type, mdtype);
1389
1390 // If result is still null, we are out of memory.
1391 Log(gc, metaspace, freelist, oom) log;
1392 if (log.is_info()) {
1393 log.info("Metaspace (%s) allocation failed for size " SIZE_FORMAT,
1394 is_class_space_allocation(mdtype) ? "class" : "data", word_size);
1395 ResourceMark rm;
1396 if (log.is_debug()) {
1397 if (loader_data->metaspace_or_null() != NULL) {
1398 LogStream ls(log.debug());
1399 loader_data->print_value_on(&ls);
1400 }
1401 }
1402 LogStream ls(log.info());
1403 // In case of an OOM, log out a short but still useful report.
1404 MetaspaceUtils::print_basic_report(&ls, 0);
1405 }
1406
1407 bool out_of_compressed_class_space = false;
1408 if (is_class_space_allocation(mdtype)) {
1409 ClassLoaderMetaspace* metaspace = loader_data->metaspace_non_null();
1410 out_of_compressed_class_space =
1411 MetaspaceUtils::committed_bytes(Metaspace::ClassType) +
1412 (metaspace->class_chunk_size(word_size) * BytesPerWord) >
1413 CompressedClassSpaceSize;
1414 }
1415
1416 // -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support
1417 const char* space_string = out_of_compressed_class_space ?
1418 "Compressed class space" : "Metaspace";
1419
1420 report_java_out_of_memory(space_string);
1421
1422 if (JvmtiExport::should_post_resource_exhausted()) {
1423 JvmtiExport::post_resource_exhausted(
1424 JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR,
1425 space_string);
1426 }
1427
1428 if (!is_init_completed()) {
1429 vm_exit_during_initialization("OutOfMemoryError", space_string);
1430 }
1431
1432 if (out_of_compressed_class_space) {
1433 THROW_OOP(Universe::out_of_memory_error_class_metaspace());
1434 } else {
1435 THROW_OOP(Universe::out_of_memory_error_metaspace());
1436 }
1437 }
1438
metadata_type_name(Metaspace::MetadataType mdtype)1439 const char* Metaspace::metadata_type_name(Metaspace::MetadataType mdtype) {
1440 switch (mdtype) {
1441 case Metaspace::ClassType: return "Class";
1442 case Metaspace::NonClassType: return "Metadata";
1443 default:
1444 assert(false, "Got bad mdtype: %d", (int) mdtype);
1445 return NULL;
1446 }
1447 }
1448
purge(MetadataType mdtype)1449 void Metaspace::purge(MetadataType mdtype) {
1450 get_space_list(mdtype)->purge(get_chunk_manager(mdtype));
1451 }
1452
purge()1453 void Metaspace::purge() {
1454 MutexLockerEx cl(MetaspaceExpand_lock,
1455 Mutex::_no_safepoint_check_flag);
1456 purge(NonClassType);
1457 if (using_class_space()) {
1458 purge(ClassType);
1459 }
1460 }
1461
contains(const void * ptr)1462 bool Metaspace::contains(const void* ptr) {
1463 if (MetaspaceShared::is_in_shared_metaspace(ptr)) {
1464 return true;
1465 }
1466 return contains_non_shared(ptr);
1467 }
1468
contains_non_shared(const void * ptr)1469 bool Metaspace::contains_non_shared(const void* ptr) {
1470 if (using_class_space() && get_space_list(ClassType)->contains(ptr)) {
1471 return true;
1472 }
1473
1474 return get_space_list(NonClassType)->contains(ptr);
1475 }
1476
1477 // ClassLoaderMetaspace
1478
ClassLoaderMetaspace(Mutex * lock,Metaspace::MetaspaceType type)1479 ClassLoaderMetaspace::ClassLoaderMetaspace(Mutex* lock, Metaspace::MetaspaceType type)
1480 : _lock(lock)
1481 , _space_type(type)
1482 , _vsm(NULL)
1483 , _class_vsm(NULL)
1484 {
1485 initialize(lock, type);
1486 }
1487
~ClassLoaderMetaspace()1488 ClassLoaderMetaspace::~ClassLoaderMetaspace() {
1489 Metaspace::assert_not_frozen();
1490 DEBUG_ONLY(Atomic::inc(&g_internal_statistics.num_metaspace_deaths));
1491 delete _vsm;
1492 if (Metaspace::using_class_space()) {
1493 delete _class_vsm;
1494 }
1495 }
1496
initialize_first_chunk(Metaspace::MetaspaceType type,Metaspace::MetadataType mdtype)1497 void ClassLoaderMetaspace::initialize_first_chunk(Metaspace::MetaspaceType type, Metaspace::MetadataType mdtype) {
1498 Metachunk* chunk = get_initialization_chunk(type, mdtype);
1499 if (chunk != NULL) {
1500 // Add to this manager's list of chunks in use and make it the current_chunk().
1501 get_space_manager(mdtype)->add_chunk(chunk, true);
1502 }
1503 }
1504
get_initialization_chunk(Metaspace::MetaspaceType type,Metaspace::MetadataType mdtype)1505 Metachunk* ClassLoaderMetaspace::get_initialization_chunk(Metaspace::MetaspaceType type, Metaspace::MetadataType mdtype) {
1506 size_t chunk_word_size = get_space_manager(mdtype)->get_initial_chunk_size(type);
1507
1508 // Get a chunk from the chunk freelist
1509 Metachunk* chunk = Metaspace::get_chunk_manager(mdtype)->chunk_freelist_allocate(chunk_word_size);
1510
1511 if (chunk == NULL) {
1512 chunk = Metaspace::get_space_list(mdtype)->get_new_chunk(chunk_word_size,
1513 get_space_manager(mdtype)->medium_chunk_bunch());
1514 }
1515
1516 return chunk;
1517 }
1518
initialize(Mutex * lock,Metaspace::MetaspaceType type)1519 void ClassLoaderMetaspace::initialize(Mutex* lock, Metaspace::MetaspaceType type) {
1520 Metaspace::verify_global_initialization();
1521
1522 DEBUG_ONLY(Atomic::inc(&g_internal_statistics.num_metaspace_births));
1523
1524 // Allocate SpaceManager for metadata objects.
1525 _vsm = new SpaceManager(Metaspace::NonClassType, type, lock);
1526
1527 if (Metaspace::using_class_space()) {
1528 // Allocate SpaceManager for classes.
1529 _class_vsm = new SpaceManager(Metaspace::ClassType, type, lock);
1530 }
1531
1532 MutexLockerEx cl(MetaspaceExpand_lock, Mutex::_no_safepoint_check_flag);
1533
1534 // Allocate chunk for metadata objects
1535 initialize_first_chunk(type, Metaspace::NonClassType);
1536
1537 // Allocate chunk for class metadata objects
1538 if (Metaspace::using_class_space()) {
1539 initialize_first_chunk(type, Metaspace::ClassType);
1540 }
1541 }
1542
allocate(size_t word_size,Metaspace::MetadataType mdtype)1543 MetaWord* ClassLoaderMetaspace::allocate(size_t word_size, Metaspace::MetadataType mdtype) {
1544 Metaspace::assert_not_frozen();
1545
1546 DEBUG_ONLY(Atomic::inc(&g_internal_statistics.num_allocs));
1547
1548 // Don't use class_vsm() unless UseCompressedClassPointers is true.
1549 if (Metaspace::is_class_space_allocation(mdtype)) {
1550 return class_vsm()->allocate(word_size);
1551 } else {
1552 return vsm()->allocate(word_size);
1553 }
1554 }
1555
expand_and_allocate(size_t word_size,Metaspace::MetadataType mdtype)1556 MetaWord* ClassLoaderMetaspace::expand_and_allocate(size_t word_size, Metaspace::MetadataType mdtype) {
1557 Metaspace::assert_not_frozen();
1558 size_t delta_bytes = MetaspaceGC::delta_capacity_until_GC(word_size * BytesPerWord);
1559 assert(delta_bytes > 0, "Must be");
1560
1561 size_t before = 0;
1562 size_t after = 0;
1563 bool can_retry = true;
1564 MetaWord* res;
1565 bool incremented;
1566
1567 // Each thread increments the HWM at most once. Even if the thread fails to increment
1568 // the HWM, an allocation is still attempted. This is because another thread must then
1569 // have incremented the HWM and therefore the allocation might still succeed.
1570 do {
1571 incremented = MetaspaceGC::inc_capacity_until_GC(delta_bytes, &after, &before, &can_retry);
1572 res = allocate(word_size, mdtype);
1573 } while (!incremented && res == NULL && can_retry);
1574
1575 if (incremented) {
1576 Metaspace::tracer()->report_gc_threshold(before, after,
1577 MetaspaceGCThresholdUpdater::ExpandAndAllocate);
1578 log_trace(gc, metaspace)("Increase capacity to GC from " SIZE_FORMAT " to " SIZE_FORMAT, before, after);
1579 }
1580
1581 return res;
1582 }
1583
allocated_blocks_bytes() const1584 size_t ClassLoaderMetaspace::allocated_blocks_bytes() const {
1585 return (vsm()->used_words() +
1586 (Metaspace::using_class_space() ? class_vsm()->used_words() : 0)) * BytesPerWord;
1587 }
1588
allocated_chunks_bytes() const1589 size_t ClassLoaderMetaspace::allocated_chunks_bytes() const {
1590 return (vsm()->capacity_words() +
1591 (Metaspace::using_class_space() ? class_vsm()->capacity_words() : 0)) * BytesPerWord;
1592 }
1593
deallocate(MetaWord * ptr,size_t word_size,bool is_class)1594 void ClassLoaderMetaspace::deallocate(MetaWord* ptr, size_t word_size, bool is_class) {
1595 Metaspace::assert_not_frozen();
1596 assert(!SafepointSynchronize::is_at_safepoint()
1597 || Thread::current()->is_VM_thread(), "should be the VM thread");
1598
1599 DEBUG_ONLY(Atomic::inc(&g_internal_statistics.num_external_deallocs));
1600
1601 MutexLockerEx ml(vsm()->lock(), Mutex::_no_safepoint_check_flag);
1602
1603 if (is_class && Metaspace::using_class_space()) {
1604 class_vsm()->deallocate(ptr, word_size);
1605 } else {
1606 vsm()->deallocate(ptr, word_size);
1607 }
1608 }
1609
class_chunk_size(size_t word_size)1610 size_t ClassLoaderMetaspace::class_chunk_size(size_t word_size) {
1611 assert(Metaspace::using_class_space(), "Has to use class space");
1612 return class_vsm()->calc_chunk_size(word_size);
1613 }
1614
print_on(outputStream * out) const1615 void ClassLoaderMetaspace::print_on(outputStream* out) const {
1616 // Print both class virtual space counts and metaspace.
1617 if (Verbose) {
1618 vsm()->print_on(out);
1619 if (Metaspace::using_class_space()) {
1620 class_vsm()->print_on(out);
1621 }
1622 }
1623 }
1624
verify()1625 void ClassLoaderMetaspace::verify() {
1626 vsm()->verify();
1627 if (Metaspace::using_class_space()) {
1628 class_vsm()->verify();
1629 }
1630 }
1631
add_to_statistics_locked(ClassLoaderMetaspaceStatistics * out) const1632 void ClassLoaderMetaspace::add_to_statistics_locked(ClassLoaderMetaspaceStatistics* out) const {
1633 assert_lock_strong(lock());
1634 vsm()->add_to_statistics_locked(&out->nonclass_sm_stats());
1635 if (Metaspace::using_class_space()) {
1636 class_vsm()->add_to_statistics_locked(&out->class_sm_stats());
1637 }
1638 }
1639
add_to_statistics(ClassLoaderMetaspaceStatistics * out) const1640 void ClassLoaderMetaspace::add_to_statistics(ClassLoaderMetaspaceStatistics* out) const {
1641 MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
1642 add_to_statistics_locked(out);
1643 }
1644
1645 /////////////// Unit tests ///////////////
1646
1647 #ifndef PRODUCT
1648
1649 class TestVirtualSpaceNodeTest {
chunk_up(size_t words_left,size_t & num_medium_chunks,size_t & num_small_chunks,size_t & num_specialized_chunks)1650 static void chunk_up(size_t words_left, size_t& num_medium_chunks,
1651 size_t& num_small_chunks,
1652 size_t& num_specialized_chunks) {
1653 num_medium_chunks = words_left / MediumChunk;
1654 words_left = words_left % MediumChunk;
1655
1656 num_small_chunks = words_left / SmallChunk;
1657 words_left = words_left % SmallChunk;
1658 // how many specialized chunks can we get?
1659 num_specialized_chunks = words_left / SpecializedChunk;
1660 assert(words_left % SpecializedChunk == 0, "should be nothing left");
1661 }
1662
1663 public:
test()1664 static void test() {
1665 MutexLockerEx ml(MetaspaceExpand_lock, Mutex::_no_safepoint_check_flag);
1666 const size_t vsn_test_size_words = MediumChunk * 4;
1667 const size_t vsn_test_size_bytes = vsn_test_size_words * BytesPerWord;
1668
1669 // The chunk sizes must be multiples of eachother, or this will fail
1670 STATIC_ASSERT(MediumChunk % SmallChunk == 0);
1671 STATIC_ASSERT(SmallChunk % SpecializedChunk == 0);
1672
1673 { // No committed memory in VSN
1674 ChunkManager cm(false);
1675 VirtualSpaceNode vsn(false, vsn_test_size_bytes);
1676 vsn.initialize();
1677 vsn.retire(&cm);
1678 assert(cm.sum_free_chunks_count() == 0, "did not commit any memory in the VSN");
1679 }
1680
1681 { // All of VSN is committed, half is used by chunks
1682 ChunkManager cm(false);
1683 VirtualSpaceNode vsn(false, vsn_test_size_bytes);
1684 vsn.initialize();
1685 vsn.expand_by(vsn_test_size_words, vsn_test_size_words);
1686 vsn.get_chunk_vs(MediumChunk);
1687 vsn.get_chunk_vs(MediumChunk);
1688 vsn.retire(&cm);
1689 assert(cm.sum_free_chunks_count() == 2, "should have been memory left for 2 medium chunks");
1690 assert(cm.sum_free_chunks() == 2*MediumChunk, "sizes should add up");
1691 }
1692
1693 const size_t page_chunks = 4 * (size_t)os::vm_page_size() / BytesPerWord;
1694 // This doesn't work for systems with vm_page_size >= 16K.
1695 if (page_chunks < MediumChunk) {
1696 // 4 pages of VSN is committed, some is used by chunks
1697 ChunkManager cm(false);
1698 VirtualSpaceNode vsn(false, vsn_test_size_bytes);
1699
1700 vsn.initialize();
1701 vsn.expand_by(page_chunks, page_chunks);
1702 vsn.get_chunk_vs(SmallChunk);
1703 vsn.get_chunk_vs(SpecializedChunk);
1704 vsn.retire(&cm);
1705
1706 // committed - used = words left to retire
1707 const size_t words_left = page_chunks - SmallChunk - SpecializedChunk;
1708
1709 size_t num_medium_chunks, num_small_chunks, num_spec_chunks;
1710 chunk_up(words_left, num_medium_chunks, num_small_chunks, num_spec_chunks);
1711
1712 assert(num_medium_chunks == 0, "should not get any medium chunks");
1713 assert(cm.sum_free_chunks_count() == (num_small_chunks + num_spec_chunks), "should be space for 3 chunks");
1714 assert(cm.sum_free_chunks() == words_left, "sizes should add up");
1715 }
1716
1717 { // Half of VSN is committed, a humongous chunk is used
1718 ChunkManager cm(false);
1719 VirtualSpaceNode vsn(false, vsn_test_size_bytes);
1720 vsn.initialize();
1721 vsn.expand_by(MediumChunk * 2, MediumChunk * 2);
1722 vsn.get_chunk_vs(MediumChunk + SpecializedChunk); // Humongous chunks will be aligned up to MediumChunk + SpecializedChunk
1723 vsn.retire(&cm);
1724
1725 const size_t words_left = MediumChunk * 2 - (MediumChunk + SpecializedChunk);
1726 size_t num_medium_chunks, num_small_chunks, num_spec_chunks;
1727 chunk_up(words_left, num_medium_chunks, num_small_chunks, num_spec_chunks);
1728
1729 assert(num_medium_chunks == 0, "should not get any medium chunks");
1730 assert(cm.sum_free_chunks_count() == (num_small_chunks + num_spec_chunks), "should be space for 3 chunks");
1731 assert(cm.sum_free_chunks() == words_left, "sizes should add up");
1732 }
1733
1734 }
1735
1736 #define assert_is_available_positive(word_size) \
1737 assert(vsn.is_available(word_size), \
1738 #word_size ": " PTR_FORMAT " bytes were not available in " \
1739 "VirtualSpaceNode [" PTR_FORMAT ", " PTR_FORMAT ")", \
1740 (uintptr_t)(word_size * BytesPerWord), p2i(vsn.bottom()), p2i(vsn.end()));
1741
1742 #define assert_is_available_negative(word_size) \
1743 assert(!vsn.is_available(word_size), \
1744 #word_size ": " PTR_FORMAT " bytes should not be available in " \
1745 "VirtualSpaceNode [" PTR_FORMAT ", " PTR_FORMAT ")", \
1746 (uintptr_t)(word_size * BytesPerWord), p2i(vsn.bottom()), p2i(vsn.end()));
1747
test_is_available_positive()1748 static void test_is_available_positive() {
1749 // Reserve some memory.
1750 VirtualSpaceNode vsn(false, os::vm_allocation_granularity());
1751 assert(vsn.initialize(), "Failed to setup VirtualSpaceNode");
1752
1753 // Commit some memory.
1754 size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord;
1755 bool expanded = vsn.expand_by(commit_word_size, commit_word_size);
1756 assert(expanded, "Failed to commit");
1757
1758 // Check that is_available accepts the committed size.
1759 assert_is_available_positive(commit_word_size);
1760
1761 // Check that is_available accepts half the committed size.
1762 size_t expand_word_size = commit_word_size / 2;
1763 assert_is_available_positive(expand_word_size);
1764 }
1765
test_is_available_negative()1766 static void test_is_available_negative() {
1767 // Reserve some memory.
1768 VirtualSpaceNode vsn(false, os::vm_allocation_granularity());
1769 assert(vsn.initialize(), "Failed to setup VirtualSpaceNode");
1770
1771 // Commit some memory.
1772 size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord;
1773 bool expanded = vsn.expand_by(commit_word_size, commit_word_size);
1774 assert(expanded, "Failed to commit");
1775
1776 // Check that is_available doesn't accept a too large size.
1777 size_t two_times_commit_word_size = commit_word_size * 2;
1778 assert_is_available_negative(two_times_commit_word_size);
1779 }
1780
test_is_available_overflow()1781 static void test_is_available_overflow() {
1782 // Reserve some memory.
1783 VirtualSpaceNode vsn(false, os::vm_allocation_granularity());
1784 assert(vsn.initialize(), "Failed to setup VirtualSpaceNode");
1785
1786 // Commit some memory.
1787 size_t commit_word_size = os::vm_allocation_granularity() / BytesPerWord;
1788 bool expanded = vsn.expand_by(commit_word_size, commit_word_size);
1789 assert(expanded, "Failed to commit");
1790
1791 // Calculate a size that will overflow the virtual space size.
1792 void* virtual_space_max = (void*)(uintptr_t)-1;
1793 size_t bottom_to_max = pointer_delta(virtual_space_max, vsn.bottom(), 1);
1794 size_t overflow_size = bottom_to_max + BytesPerWord;
1795 size_t overflow_word_size = overflow_size / BytesPerWord;
1796
1797 // Check that is_available can handle the overflow.
1798 assert_is_available_negative(overflow_word_size);
1799 }
1800
test_is_available()1801 static void test_is_available() {
1802 TestVirtualSpaceNodeTest::test_is_available_positive();
1803 TestVirtualSpaceNodeTest::test_is_available_negative();
1804 TestVirtualSpaceNodeTest::test_is_available_overflow();
1805 }
1806 };
1807
1808 #endif // !PRODUCT
1809
1810 struct chunkmanager_statistics_t {
1811 int num_specialized_chunks;
1812 int num_small_chunks;
1813 int num_medium_chunks;
1814 int num_humongous_chunks;
1815 };
1816
test_metaspace_retrieve_chunkmanager_statistics(Metaspace::MetadataType mdType,chunkmanager_statistics_t * out)1817 extern void test_metaspace_retrieve_chunkmanager_statistics(Metaspace::MetadataType mdType, chunkmanager_statistics_t* out) {
1818 ChunkManager* const chunk_manager = Metaspace::get_chunk_manager(mdType);
1819 ChunkManagerStatistics stat;
1820 chunk_manager->collect_statistics(&stat);
1821 out->num_specialized_chunks = (int)stat.chunk_stats(SpecializedIndex).num();
1822 out->num_small_chunks = (int)stat.chunk_stats(SmallIndex).num();
1823 out->num_medium_chunks = (int)stat.chunk_stats(MediumIndex).num();
1824 out->num_humongous_chunks = (int)stat.chunk_stats(HumongousIndex).num();
1825 }
1826
1827 struct chunk_geometry_t {
1828 size_t specialized_chunk_word_size;
1829 size_t small_chunk_word_size;
1830 size_t medium_chunk_word_size;
1831 };
1832
test_metaspace_retrieve_chunk_geometry(Metaspace::MetadataType mdType,chunk_geometry_t * out)1833 extern void test_metaspace_retrieve_chunk_geometry(Metaspace::MetadataType mdType, chunk_geometry_t* out) {
1834 if (mdType == Metaspace::NonClassType) {
1835 out->specialized_chunk_word_size = SpecializedChunk;
1836 out->small_chunk_word_size = SmallChunk;
1837 out->medium_chunk_word_size = MediumChunk;
1838 } else {
1839 out->specialized_chunk_word_size = ClassSpecializedChunk;
1840 out->small_chunk_word_size = ClassSmallChunk;
1841 out->medium_chunk_word_size = ClassMediumChunk;
1842 }
1843 }
1844