1 /* 2 * Copyright (c) 2011, 2023, Oracle and/or its affiliates. All rights reserved. 3 * Copyright (c) 2017, 2021 SAP SE. All rights reserved. 4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 5 * 6 * This code is free software; you can redistribute it and/or modify it 7 * under the terms of the GNU General Public License version 2 only, as 8 * published by the Free Software Foundation. 9 * 10 * This code is distributed in the hope that it will be useful, but WITHOUT 11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 13 * version 2 for more details (a copy is included in the LICENSE file that 14 * accompanied this code). 15 * 16 * You should have received a copy of the GNU General Public License version 17 * 2 along with this work; if not, write to the Free Software Foundation, 18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 19 * 20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 21 * or visit www.oracle.com if you need additional information or have any 22 * questions. 23 * 24 */ 25 26 #include "precompiled.hpp" 27 #include "cds/metaspaceShared.hpp" 28 #include "classfile/classLoaderData.hpp" 29 #include "gc/shared/collectedHeap.hpp" 30 #include "logging/log.hpp" 31 #include "logging/logStream.hpp" 32 #include "memory/classLoaderMetaspace.hpp" 33 #include "memory/metaspace.hpp" 34 #include "memory/metaspaceCriticalAllocation.hpp" 35 #include "memory/metaspace/chunkHeaderPool.hpp" 36 #include "memory/metaspace/chunkManager.hpp" 37 #include "memory/metaspace/commitLimiter.hpp" 38 #include "memory/metaspace/internalStats.hpp" 39 #include "memory/metaspace/metaspaceCommon.hpp" 40 #include "memory/metaspace/metaspaceContext.hpp" 41 #include "memory/metaspace/metaspaceReporter.hpp" 42 #include "memory/metaspace/metaspaceSettings.hpp" 43 #include "memory/metaspace/runningCounters.hpp" 44 #include "memory/metaspace/virtualSpaceList.hpp" 45 #include "memory/metaspaceTracer.hpp" 46 #include "memory/metaspaceStats.hpp" 47 #include "memory/metaspaceUtils.hpp" 48 #include "memory/resourceArea.hpp" 49 #include "memory/universe.hpp" 50 #include "oops/compressedOops.hpp" 51 #include "prims/jvmtiExport.hpp" 52 #include "runtime/atomic.hpp" 53 #include "runtime/globals_extension.hpp" 54 #include "runtime/init.hpp" 55 #include "runtime/java.hpp" 56 #include "services/memTracker.hpp" 57 #include "utilities/copy.hpp" 58 #include "utilities/debug.hpp" 59 #include "utilities/formatBuffer.hpp" 60 #include "utilities/globalDefinitions.hpp" 61 62 using metaspace::ChunkManager; 63 using metaspace::CommitLimiter; 64 using metaspace::MetaspaceContext; 65 using metaspace::MetaspaceReporter; 66 using metaspace::RunningCounters; 67 using metaspace::VirtualSpaceList; 68 69 size_t MetaspaceUtils::used_words() { 70 return RunningCounters::used_words(); 71 } 72 73 size_t MetaspaceUtils::used_words(Metaspace::MetadataType mdtype) { 74 return mdtype == Metaspace::ClassType ? RunningCounters::used_words_class() : RunningCounters::used_words_nonclass(); 75 } 76 77 size_t MetaspaceUtils::reserved_words() { 78 return RunningCounters::reserved_words(); 79 } 80 81 size_t MetaspaceUtils::reserved_words(Metaspace::MetadataType mdtype) { 82 return mdtype == Metaspace::ClassType ? RunningCounters::reserved_words_class() : RunningCounters::reserved_words_nonclass(); 83 } 84 85 size_t MetaspaceUtils::committed_words() { 86 return RunningCounters::committed_words(); 87 } 88 89 size_t MetaspaceUtils::committed_words(Metaspace::MetadataType mdtype) { 90 return mdtype == Metaspace::ClassType ? RunningCounters::committed_words_class() : RunningCounters::committed_words_nonclass(); 91 } 92 93 // Helper for get_statistics() 94 static void get_values_for(Metaspace::MetadataType mdtype, size_t* reserved, size_t* committed, size_t* used) { 95 #define w2b(x) (x * sizeof(MetaWord)) 96 if (mdtype == Metaspace::ClassType) { 97 *reserved = w2b(RunningCounters::reserved_words_class()); 98 *committed = w2b(RunningCounters::committed_words_class()); 99 *used = w2b(RunningCounters::used_words_class()); 100 } else { 101 *reserved = w2b(RunningCounters::reserved_words_nonclass()); 102 *committed = w2b(RunningCounters::committed_words_nonclass()); 103 *used = w2b(RunningCounters::used_words_nonclass()); 104 } 105 #undef w2b 106 } 107 108 // Retrieve all statistics in one go; make sure the values are consistent. 109 MetaspaceStats MetaspaceUtils::get_statistics(Metaspace::MetadataType mdtype) { 110 111 // Consistency: 112 // This function reads three values (reserved, committed, used) from different counters. These counters 113 // may (very rarely) be out of sync. This has been a source for intermittent test errors in the past 114 // (see e.g. JDK-8237872, JDK-8151460). 115 // - reserved and committed counter are updated under protection of Metaspace_lock; an inconsistency 116 // between them can be the result of a dirty read. 117 // - used is an atomic counter updated outside any lock range; there is no way to guarantee 118 // a clean read wrt the other two values. 119 // Reading these values under lock protection would would only help for the first case. Therefore 120 // we don't bother and just re-read several times, then give up and correct the values. 121 122 size_t r = 0, c = 0, u = 0; // Note: byte values. 123 get_values_for(mdtype, &r, &c, &u); 124 int retries = 10; 125 // If the first retrieval resulted in inconsistent values, retry a bit... 126 while ((r < c || c < u) && --retries >= 0) { 127 get_values_for(mdtype, &r, &c, &u); 128 } 129 if (c < u || r < c) { // still inconsistent. 130 // ... but not endlessly. If we don't get consistent values, correct them on the fly. 131 // The logic here is that we trust the used counter - its an atomic counter and whatever we see 132 // must have been the truth once - and from that we reconstruct a likely set of committed/reserved 133 // values. 134 metaspace::InternalStats::inc_num_inconsistent_stats(); 135 if (c < u) { 136 c = align_up(u, Metaspace::commit_alignment()); 137 } 138 if (r < c) { 139 r = align_up(c, Metaspace::reserve_alignment()); 140 } 141 } 142 return MetaspaceStats(r, c, u); 143 } 144 145 MetaspaceCombinedStats MetaspaceUtils::get_combined_statistics() { 146 return MetaspaceCombinedStats(get_statistics(Metaspace::ClassType), get_statistics(Metaspace::NonClassType)); 147 } 148 149 void MetaspaceUtils::print_metaspace_change(const MetaspaceCombinedStats& pre_meta_values) { 150 // Get values now: 151 const MetaspaceCombinedStats meta_values = get_combined_statistics(); 152 153 // We print used and committed since these are the most useful at-a-glance vitals for Metaspace: 154 // - used tells you how much memory is actually used for metadata 155 // - committed tells you how much memory is committed for the purpose of metadata 156 // The difference between those two would be waste, which can have various forms (freelists, 157 // unused parts of committed chunks etc) 158 // 159 // Left out is reserved, since this is not as exciting as the first two values: for class space, 160 // it is a constant (to uninformed users, often confusingly large). For non-class space, it would 161 // be interesting since free chunks can be uncommitted, but for now it is left out. 162 163 if (Metaspace::using_class_space()) { 164 log_info(gc, metaspace)(HEAP_CHANGE_FORMAT" " 165 HEAP_CHANGE_FORMAT" " 166 HEAP_CHANGE_FORMAT, 167 HEAP_CHANGE_FORMAT_ARGS("Metaspace", 168 pre_meta_values.used(), 169 pre_meta_values.committed(), 170 meta_values.used(), 171 meta_values.committed()), 172 HEAP_CHANGE_FORMAT_ARGS("NonClass", 173 pre_meta_values.non_class_used(), 174 pre_meta_values.non_class_committed(), 175 meta_values.non_class_used(), 176 meta_values.non_class_committed()), 177 HEAP_CHANGE_FORMAT_ARGS("Class", 178 pre_meta_values.class_used(), 179 pre_meta_values.class_committed(), 180 meta_values.class_used(), 181 meta_values.class_committed())); 182 } else { 183 log_info(gc, metaspace)(HEAP_CHANGE_FORMAT, 184 HEAP_CHANGE_FORMAT_ARGS("Metaspace", 185 pre_meta_values.used(), 186 pre_meta_values.committed(), 187 meta_values.used(), 188 meta_values.committed())); 189 } 190 } 191 192 // This will print out a basic metaspace usage report but 193 // unlike print_report() is guaranteed not to lock or to walk the CLDG. 194 void MetaspaceUtils::print_basic_report(outputStream* out, size_t scale) { 195 MetaspaceReporter::print_basic_report(out, scale); 196 } 197 198 // Prints a report about the current metaspace state. 199 // Optional parts can be enabled via flags. 200 // Function will walk the CLDG and will lock the expand lock; if that is not 201 // convenient, use print_basic_report() instead. 202 void MetaspaceUtils::print_report(outputStream* out, size_t scale) { 203 const int flags = 204 (int)MetaspaceReporter::Option::ShowLoaders | 205 (int)MetaspaceReporter::Option::BreakDownByChunkType | 206 (int)MetaspaceReporter::Option::ShowClasses; 207 MetaspaceReporter::print_report(out, scale, flags); 208 } 209 210 void MetaspaceUtils::print_on(outputStream* out) { 211 212 // Used from all GCs. It first prints out totals, then, separately, the class space portion. 213 MetaspaceCombinedStats stats = get_combined_statistics(); 214 out->print_cr(" Metaspace " 215 "used " SIZE_FORMAT "K, " 216 "committed " SIZE_FORMAT "K, " 217 "reserved " SIZE_FORMAT "K", 218 stats.used()/K, 219 stats.committed()/K, 220 stats.reserved()/K); 221 222 if (Metaspace::using_class_space()) { 223 out->print_cr(" class space " 224 "used " SIZE_FORMAT "K, " 225 "committed " SIZE_FORMAT "K, " 226 "reserved " SIZE_FORMAT "K", 227 stats.class_space_stats().used()/K, 228 stats.class_space_stats().committed()/K, 229 stats.class_space_stats().reserved()/K); 230 } 231 } 232 233 #ifdef ASSERT 234 void MetaspaceUtils::verify() { 235 if (Metaspace::initialized()) { 236 237 // Verify non-class chunkmanager... 238 ChunkManager* cm = ChunkManager::chunkmanager_nonclass(); 239 cm->verify(); 240 241 // ... and space list. 242 VirtualSpaceList* vsl = VirtualSpaceList::vslist_nonclass(); 243 vsl->verify(); 244 245 if (Metaspace::using_class_space()) { 246 // If we use compressed class pointers, verify class chunkmanager... 247 cm = ChunkManager::chunkmanager_class(); 248 cm->verify(); 249 250 // ... and class spacelist. 251 vsl = VirtualSpaceList::vslist_class(); 252 vsl->verify(); 253 } 254 255 } 256 } 257 #endif 258 259 ////////////////////////////////7 260 // MetaspaceGC methods 261 262 volatile size_t MetaspaceGC::_capacity_until_GC = 0; 263 uint MetaspaceGC::_shrink_factor = 0; 264 265 // VM_CollectForMetadataAllocation is the vm operation used to GC. 266 // Within the VM operation after the GC the attempt to allocate the metadata 267 // should succeed. If the GC did not free enough space for the metaspace 268 // allocation, the HWM is increased so that another virtualspace will be 269 // allocated for the metadata. With perm gen the increase in the perm 270 // gen had bounds, MinMetaspaceExpansion and MaxMetaspaceExpansion. The 271 // metaspace policy uses those as the small and large steps for the HWM. 272 // 273 // After the GC the compute_new_size() for MetaspaceGC is called to 274 // resize the capacity of the metaspaces. The current implementation 275 // is based on the flags MinMetaspaceFreeRatio and MaxMetaspaceFreeRatio used 276 // to resize the Java heap by some GC's. New flags can be implemented 277 // if really needed. MinMetaspaceFreeRatio is used to calculate how much 278 // free space is desirable in the metaspace capacity to decide how much 279 // to increase the HWM. MaxMetaspaceFreeRatio is used to decide how much 280 // free space is desirable in the metaspace capacity before decreasing 281 // the HWM. 282 283 // Calculate the amount to increase the high water mark (HWM). 284 // Increase by a minimum amount (MinMetaspaceExpansion) so that 285 // another expansion is not requested too soon. If that is not 286 // enough to satisfy the allocation, increase by MaxMetaspaceExpansion. 287 // If that is still not enough, expand by the size of the allocation 288 // plus some. 289 size_t MetaspaceGC::delta_capacity_until_GC(size_t bytes) { 290 size_t min_delta = MinMetaspaceExpansion; 291 size_t max_delta = MaxMetaspaceExpansion; 292 size_t delta = align_up(bytes, Metaspace::commit_alignment()); 293 294 if (delta <= min_delta) { 295 delta = min_delta; 296 } else if (delta <= max_delta) { 297 // Don't want to hit the high water mark on the next 298 // allocation so make the delta greater than just enough 299 // for this allocation. 300 delta = max_delta; 301 } else { 302 // This allocation is large but the next ones are probably not 303 // so increase by the minimum. 304 delta = delta + min_delta; 305 } 306 307 assert_is_aligned(delta, Metaspace::commit_alignment()); 308 309 return delta; 310 } 311 312 size_t MetaspaceGC::capacity_until_GC() { 313 size_t value = Atomic::load_acquire(&_capacity_until_GC); 314 assert(value >= MetaspaceSize, "Not initialized properly?"); 315 return value; 316 } 317 318 // Try to increase the _capacity_until_GC limit counter by v bytes. 319 // Returns true if it succeeded. It may fail if either another thread 320 // concurrently increased the limit or the new limit would be larger 321 // than MaxMetaspaceSize. 322 // On success, optionally returns new and old metaspace capacity in 323 // new_cap_until_GC and old_cap_until_GC respectively. 324 // On error, optionally sets can_retry to indicate whether if there is 325 // actually enough space remaining to satisfy the request. 326 bool MetaspaceGC::inc_capacity_until_GC(size_t v, size_t* new_cap_until_GC, size_t* old_cap_until_GC, bool* can_retry) { 327 assert_is_aligned(v, Metaspace::commit_alignment()); 328 329 size_t old_capacity_until_GC = _capacity_until_GC; 330 size_t new_value = old_capacity_until_GC + v; 331 332 if (new_value < old_capacity_until_GC) { 333 // The addition wrapped around, set new_value to aligned max value. 334 new_value = align_down(max_uintx, Metaspace::reserve_alignment()); 335 } 336 337 if (new_value > MaxMetaspaceSize) { 338 if (can_retry != nullptr) { 339 *can_retry = false; 340 } 341 return false; 342 } 343 344 if (can_retry != nullptr) { 345 *can_retry = true; 346 } 347 size_t prev_value = Atomic::cmpxchg(&_capacity_until_GC, old_capacity_until_GC, new_value); 348 349 if (old_capacity_until_GC != prev_value) { 350 return false; 351 } 352 353 if (new_cap_until_GC != nullptr) { 354 *new_cap_until_GC = new_value; 355 } 356 if (old_cap_until_GC != nullptr) { 357 *old_cap_until_GC = old_capacity_until_GC; 358 } 359 return true; 360 } 361 362 size_t MetaspaceGC::dec_capacity_until_GC(size_t v) { 363 assert_is_aligned(v, Metaspace::commit_alignment()); 364 365 return Atomic::sub(&_capacity_until_GC, v); 366 } 367 368 void MetaspaceGC::initialize() { 369 // Set the high-water mark to MaxMetapaceSize during VM initializaton since 370 // we can't do a GC during initialization. 371 _capacity_until_GC = MaxMetaspaceSize; 372 } 373 374 void MetaspaceGC::post_initialize() { 375 // Reset the high-water mark once the VM initialization is done. 376 _capacity_until_GC = MAX2(MetaspaceUtils::committed_bytes(), MetaspaceSize); 377 } 378 379 bool MetaspaceGC::can_expand(size_t word_size, bool is_class) { 380 // Check if the compressed class space is full. 381 if (is_class && Metaspace::using_class_space()) { 382 size_t class_committed = MetaspaceUtils::committed_bytes(Metaspace::ClassType); 383 if (class_committed + word_size * BytesPerWord > CompressedClassSpaceSize) { 384 log_trace(gc, metaspace, freelist)("Cannot expand %s metaspace by " SIZE_FORMAT " words (CompressedClassSpaceSize = " SIZE_FORMAT " words)", 385 (is_class ? "class" : "non-class"), word_size, CompressedClassSpaceSize / sizeof(MetaWord)); 386 return false; 387 } 388 } 389 390 // Check if the user has imposed a limit on the metaspace memory. 391 size_t committed_bytes = MetaspaceUtils::committed_bytes(); 392 if (committed_bytes + word_size * BytesPerWord > MaxMetaspaceSize) { 393 log_trace(gc, metaspace, freelist)("Cannot expand %s metaspace by " SIZE_FORMAT " words (MaxMetaspaceSize = " SIZE_FORMAT " words)", 394 (is_class ? "class" : "non-class"), word_size, MaxMetaspaceSize / sizeof(MetaWord)); 395 return false; 396 } 397 398 return true; 399 } 400 401 size_t MetaspaceGC::allowed_expansion() { 402 size_t committed_bytes = MetaspaceUtils::committed_bytes(); 403 size_t capacity_until_gc = capacity_until_GC(); 404 405 assert(capacity_until_gc >= committed_bytes, 406 "capacity_until_gc: " SIZE_FORMAT " < committed_bytes: " SIZE_FORMAT, 407 capacity_until_gc, committed_bytes); 408 409 size_t left_until_max = MaxMetaspaceSize - committed_bytes; 410 size_t left_until_GC = capacity_until_gc - committed_bytes; 411 size_t left_to_commit = MIN2(left_until_GC, left_until_max); 412 log_trace(gc, metaspace, freelist)("allowed expansion words: " SIZE_FORMAT 413 " (left_until_max: " SIZE_FORMAT ", left_until_GC: " SIZE_FORMAT ".", 414 left_to_commit / BytesPerWord, left_until_max / BytesPerWord, left_until_GC / BytesPerWord); 415 416 return left_to_commit / BytesPerWord; 417 } 418 419 void MetaspaceGC::compute_new_size() { 420 assert(_shrink_factor <= 100, "invalid shrink factor"); 421 uint current_shrink_factor = _shrink_factor; 422 _shrink_factor = 0; 423 424 // Using committed_bytes() for used_after_gc is an overestimation, since the 425 // chunk free lists are included in committed_bytes() and the memory in an 426 // un-fragmented chunk free list is available for future allocations. 427 // However, if the chunk free lists becomes fragmented, then the memory may 428 // not be available for future allocations and the memory is therefore "in use". 429 // Including the chunk free lists in the definition of "in use" is therefore 430 // necessary. Not including the chunk free lists can cause capacity_until_GC to 431 // shrink below committed_bytes() and this has caused serious bugs in the past. 432 const size_t used_after_gc = MetaspaceUtils::committed_bytes(); 433 const size_t capacity_until_GC = MetaspaceGC::capacity_until_GC(); 434 435 const double minimum_free_percentage = MinMetaspaceFreeRatio / 100.0; 436 const double maximum_used_percentage = 1.0 - minimum_free_percentage; 437 438 const double min_tmp = used_after_gc / maximum_used_percentage; 439 size_t minimum_desired_capacity = 440 (size_t)MIN2(min_tmp, double(MaxMetaspaceSize)); 441 // Don't shrink less than the initial generation size 442 minimum_desired_capacity = MAX2(minimum_desired_capacity, 443 MetaspaceSize); 444 445 log_trace(gc, metaspace)("MetaspaceGC::compute_new_size: "); 446 log_trace(gc, metaspace)(" minimum_free_percentage: %6.2f maximum_used_percentage: %6.2f", 447 minimum_free_percentage, maximum_used_percentage); 448 log_trace(gc, metaspace)(" used_after_gc : %6.1fKB", used_after_gc / (double) K); 449 450 size_t shrink_bytes = 0; 451 if (capacity_until_GC < minimum_desired_capacity) { 452 // If we have less capacity below the metaspace HWM, then 453 // increment the HWM. 454 size_t expand_bytes = minimum_desired_capacity - capacity_until_GC; 455 expand_bytes = align_up(expand_bytes, Metaspace::commit_alignment()); 456 // Don't expand unless it's significant 457 if (expand_bytes >= MinMetaspaceExpansion) { 458 size_t new_capacity_until_GC = 0; 459 bool succeeded = MetaspaceGC::inc_capacity_until_GC(expand_bytes, &new_capacity_until_GC); 460 assert(succeeded, "Should always successfully increment HWM when at safepoint"); 461 462 Metaspace::tracer()->report_gc_threshold(capacity_until_GC, 463 new_capacity_until_GC, 464 MetaspaceGCThresholdUpdater::ComputeNewSize); 465 log_trace(gc, metaspace)(" expanding: minimum_desired_capacity: %6.1fKB expand_bytes: %6.1fKB MinMetaspaceExpansion: %6.1fKB new metaspace HWM: %6.1fKB", 466 minimum_desired_capacity / (double) K, 467 expand_bytes / (double) K, 468 MinMetaspaceExpansion / (double) K, 469 new_capacity_until_GC / (double) K); 470 } 471 return; 472 } 473 474 // No expansion, now see if we want to shrink 475 // We would never want to shrink more than this 476 assert(capacity_until_GC >= minimum_desired_capacity, 477 SIZE_FORMAT " >= " SIZE_FORMAT, 478 capacity_until_GC, minimum_desired_capacity); 479 size_t max_shrink_bytes = capacity_until_GC - minimum_desired_capacity; 480 481 // Should shrinking be considered? 482 if (MaxMetaspaceFreeRatio < 100) { 483 const double maximum_free_percentage = MaxMetaspaceFreeRatio / 100.0; 484 const double minimum_used_percentage = 1.0 - maximum_free_percentage; 485 const double max_tmp = used_after_gc / minimum_used_percentage; 486 size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(MaxMetaspaceSize)); 487 maximum_desired_capacity = MAX2(maximum_desired_capacity, 488 MetaspaceSize); 489 log_trace(gc, metaspace)(" maximum_free_percentage: %6.2f minimum_used_percentage: %6.2f", 490 maximum_free_percentage, minimum_used_percentage); 491 log_trace(gc, metaspace)(" minimum_desired_capacity: %6.1fKB maximum_desired_capacity: %6.1fKB", 492 minimum_desired_capacity / (double) K, maximum_desired_capacity / (double) K); 493 494 assert(minimum_desired_capacity <= maximum_desired_capacity, 495 "sanity check"); 496 497 if (capacity_until_GC > maximum_desired_capacity) { 498 // Capacity too large, compute shrinking size 499 shrink_bytes = capacity_until_GC - maximum_desired_capacity; 500 // We don't want shrink all the way back to initSize if people call 501 // System.gc(), because some programs do that between "phases" and then 502 // we'd just have to grow the heap up again for the next phase. So we 503 // damp the shrinking: 0% on the first call, 10% on the second call, 40% 504 // on the third call, and 100% by the fourth call. But if we recompute 505 // size without shrinking, it goes back to 0%. 506 shrink_bytes = shrink_bytes / 100 * current_shrink_factor; 507 508 shrink_bytes = align_down(shrink_bytes, Metaspace::commit_alignment()); 509 510 assert(shrink_bytes <= max_shrink_bytes, 511 "invalid shrink size " SIZE_FORMAT " not <= " SIZE_FORMAT, 512 shrink_bytes, max_shrink_bytes); 513 if (current_shrink_factor == 0) { 514 _shrink_factor = 10; 515 } else { 516 _shrink_factor = MIN2(current_shrink_factor * 4, (uint) 100); 517 } 518 log_trace(gc, metaspace)(" shrinking: initThreshold: %.1fK maximum_desired_capacity: %.1fK", 519 MetaspaceSize / (double) K, maximum_desired_capacity / (double) K); 520 log_trace(gc, metaspace)(" shrink_bytes: %.1fK current_shrink_factor: %d new shrink factor: %d MinMetaspaceExpansion: %.1fK", 521 shrink_bytes / (double) K, current_shrink_factor, _shrink_factor, MinMetaspaceExpansion / (double) K); 522 } 523 } 524 525 // Don't shrink unless it's significant 526 if (shrink_bytes >= MinMetaspaceExpansion && 527 ((capacity_until_GC - shrink_bytes) >= MetaspaceSize)) { 528 size_t new_capacity_until_GC = MetaspaceGC::dec_capacity_until_GC(shrink_bytes); 529 Metaspace::tracer()->report_gc_threshold(capacity_until_GC, 530 new_capacity_until_GC, 531 MetaspaceGCThresholdUpdater::ComputeNewSize); 532 } 533 } 534 535 ////// Metaspace methods ///// 536 537 const MetaspaceTracer* Metaspace::_tracer = nullptr; 538 539 bool Metaspace::initialized() { 540 return metaspace::MetaspaceContext::context_nonclass() != nullptr 541 LP64_ONLY(&& (using_class_space() ? Metaspace::class_space_is_initialized() : true)); 542 } 543 544 #ifdef _LP64 545 546 void Metaspace::print_compressed_class_space(outputStream* st) { 547 if (VirtualSpaceList::vslist_class() != nullptr) { 548 MetaWord* base = VirtualSpaceList::vslist_class()->base_of_first_node(); 549 size_t size = VirtualSpaceList::vslist_class()->word_size_of_first_node(); 550 MetaWord* top = base + size; 551 st->print("Compressed class space mapped at: " PTR_FORMAT "-" PTR_FORMAT ", reserved size: " SIZE_FORMAT, 552 p2i(base), p2i(top), (top - base) * BytesPerWord); 553 st->cr(); 554 } 555 } 556 557 // Given a prereserved space, use that to set up the compressed class space list. 558 void Metaspace::initialize_class_space(ReservedSpace rs) { 559 assert(rs.size() >= CompressedClassSpaceSize, 560 SIZE_FORMAT " != " SIZE_FORMAT, rs.size(), CompressedClassSpaceSize); 561 assert(using_class_space(), "Must be using class space"); 562 563 assert(rs.size() == CompressedClassSpaceSize, SIZE_FORMAT " != " SIZE_FORMAT, 564 rs.size(), CompressedClassSpaceSize); 565 assert(is_aligned(rs.base(), Metaspace::reserve_alignment()) && 566 is_aligned(rs.size(), Metaspace::reserve_alignment()), 567 "wrong alignment"); 568 569 MetaspaceContext::initialize_class_space_context(rs); 570 571 // This does currently not work because rs may be the result of a split 572 // operation and NMT seems not to be able to handle splits. 573 // Will be fixed with JDK-8243535. 574 // MemTracker::record_virtual_memory_type((address)rs.base(), mtClass); 575 576 } 577 578 // Returns true if class space has been setup (initialize_class_space). 579 bool Metaspace::class_space_is_initialized() { 580 return MetaspaceContext::context_class() != nullptr; 581 } 582 583 // Reserve a range of memory at an address suitable for en/decoding narrow 584 // Klass pointers (see: CompressedClassPointers::is_valid_base()). 585 // The returned address shall both be suitable as a compressed class pointers 586 // base, and aligned to Metaspace::reserve_alignment (which is equal to or a 587 // multiple of allocation granularity). 588 // On error, returns an unreserved space. 589 ReservedSpace Metaspace::reserve_address_space_for_compressed_classes(size_t size) { 590 591 #if defined(AARCH64) || defined(PPC64) 592 const size_t alignment = Metaspace::reserve_alignment(); 593 594 // AArch64: Try to align metaspace so that we can decode a compressed 595 // klass with a single MOVK instruction. We can do this iff the 596 // compressed class base is a multiple of 4G. 597 // Additionally, above 32G, ensure the lower LogKlassAlignmentInBytes bits 598 // of the upper 32-bits of the address are zero so we can handle a shift 599 // when decoding. 600 601 // PPC64: smaller heaps up to 2g will be mapped just below 4g. Then the 602 // attempt to place the compressed class space just after the heap fails on 603 // Linux 4.1.42 and higher because the launcher is loaded at 4g 604 // (ELF_ET_DYN_BASE). In that case we reach here and search the address space 605 // below 32g to get a zerobased CCS. For simplicity we reuse the search 606 // strategy for AARCH64. 607 608 static const struct { 609 address from; 610 address to; 611 size_t increment; 612 } search_ranges[] = { 613 { (address)(4*G), (address)(32*G), 4*G, }, 614 { (address)(32*G), (address)(1024*G), (4 << LogKlassAlignmentInBytes) * G }, 615 { nullptr, nullptr, 0 } 616 }; 617 618 for (int i = 0; search_ranges[i].from != nullptr; i ++) { 619 address a = search_ranges[i].from; 620 assert(CompressedKlassPointers::is_valid_base(a), "Sanity"); 621 while (a < search_ranges[i].to) { 622 ReservedSpace rs(size, Metaspace::reserve_alignment(), 623 os::vm_page_size(), (char*)a); 624 if (rs.is_reserved()) { 625 assert(a == (address)rs.base(), "Sanity"); 626 return rs; 627 } 628 a += search_ranges[i].increment; 629 } 630 } 631 #endif // defined(AARCH64) || defined(PPC64) 632 633 #ifdef AARCH64 634 // Note: on AARCH64, if the code above does not find any good placement, we 635 // have no recourse. We return an empty space and the VM will exit. 636 return ReservedSpace(); 637 #else 638 // Default implementation: Just reserve anywhere. 639 return ReservedSpace(size, Metaspace::reserve_alignment(), os::vm_page_size(), (char*)nullptr); 640 #endif // AARCH64 641 } 642 643 #endif // _LP64 644 645 size_t Metaspace::reserve_alignment_words() { 646 return metaspace::Settings::virtual_space_node_reserve_alignment_words(); 647 } 648 649 size_t Metaspace::commit_alignment_words() { 650 return metaspace::Settings::commit_granule_words(); 651 } 652 653 void Metaspace::ergo_initialize() { 654 655 // Must happen before using any setting from Settings::--- 656 metaspace::Settings::ergo_initialize(); 657 658 // MaxMetaspaceSize and CompressedClassSpaceSize: 659 // 660 // MaxMetaspaceSize is the maximum size, in bytes, of memory we are allowed 661 // to commit for the Metaspace. 662 // It is just a number; a limit we compare against before committing. It 663 // does not have to be aligned to anything. 664 // It gets used as compare value before attempting to increase the metaspace 665 // commit charge. It defaults to max_uintx (unlimited). 666 // 667 // CompressedClassSpaceSize is the size, in bytes, of the address range we 668 // pre-reserve for the compressed class space (if we use class space). 669 // This size has to be aligned to the metaspace reserve alignment (to the 670 // size of a root chunk). It gets aligned up from whatever value the caller 671 // gave us to the next multiple of root chunk size. 672 // 673 // Note: Strictly speaking MaxMetaspaceSize and CompressedClassSpaceSize have 674 // very little to do with each other. The notion often encountered: 675 // MaxMetaspaceSize = CompressedClassSpaceSize + <non-class metadata size> 676 // is subtly wrong: MaxMetaspaceSize can besmaller than CompressedClassSpaceSize, 677 // in which case we just would not be able to fully commit the class space range. 678 // 679 // We still adjust CompressedClassSpaceSize to reasonable limits, mainly to 680 // save on reserved space, and to make ergnonomics less confusing. 681 682 MaxMetaspaceSize = MAX2(MaxMetaspaceSize, commit_alignment()); 683 684 if (UseCompressedClassPointers) { 685 // Let CCS size not be larger than 80% of MaxMetaspaceSize. Note that is 686 // grossly over-dimensioned for most usage scenarios; typical ratio of 687 // class space : non class space usage is about 1:6. With many small classes, 688 // it can get as low as 1:2. It is not a big deal though since ccs is only 689 // reserved and will be committed on demand only. 690 size_t max_ccs_size = MaxMetaspaceSize * 0.8; 691 size_t adjusted_ccs_size = MIN2(CompressedClassSpaceSize, max_ccs_size); 692 693 // CCS must be aligned to root chunk size, and be at least the size of one 694 // root chunk. 695 adjusted_ccs_size = align_up(adjusted_ccs_size, reserve_alignment()); 696 adjusted_ccs_size = MAX2(adjusted_ccs_size, reserve_alignment()); 697 698 // Note: re-adjusting may have us left with a CompressedClassSpaceSize 699 // larger than MaxMetaspaceSize for very small values of MaxMetaspaceSize. 700 // Lets just live with that, its not a big deal. 701 702 if (adjusted_ccs_size != CompressedClassSpaceSize) { 703 FLAG_SET_ERGO(CompressedClassSpaceSize, adjusted_ccs_size); 704 log_info(metaspace)("Setting CompressedClassSpaceSize to " SIZE_FORMAT ".", 705 CompressedClassSpaceSize); 706 } 707 } 708 709 // Set MetaspaceSize, MinMetaspaceExpansion and MaxMetaspaceExpansion 710 if (MetaspaceSize > MaxMetaspaceSize) { 711 MetaspaceSize = MaxMetaspaceSize; 712 } 713 714 MetaspaceSize = align_down_bounded(MetaspaceSize, commit_alignment()); 715 716 assert(MetaspaceSize <= MaxMetaspaceSize, "MetaspaceSize should be limited by MaxMetaspaceSize"); 717 718 MinMetaspaceExpansion = align_down_bounded(MinMetaspaceExpansion, commit_alignment()); 719 MaxMetaspaceExpansion = align_down_bounded(MaxMetaspaceExpansion, commit_alignment()); 720 721 } 722 723 void Metaspace::global_initialize() { 724 MetaspaceGC::initialize(); // <- since we do not prealloc init chunks anymore is this still needed? 725 726 metaspace::ChunkHeaderPool::initialize(); 727 728 if (DumpSharedSpaces) { 729 assert(!UseSharedSpaces, "sanity"); 730 MetaspaceShared::initialize_for_static_dump(); 731 } 732 733 // If UseCompressedClassPointers=1, we have two cases: 734 // a) if CDS is active (runtime, Xshare=on), it will create the class space 735 // for us, initialize it and set up CompressedKlassPointers encoding. 736 // Class space will be reserved above the mapped archives. 737 // b) if CDS either deactivated (Xshare=off) or a static dump is to be done (Xshare:dump), 738 // we will create the class space on our own. It will be placed above the java heap, 739 // since we assume it has been placed in low 740 // address regions. We may rethink this (see JDK-8244943). Failing that, 741 // it will be placed anywhere. 742 743 #if INCLUDE_CDS 744 // case (a) 745 if (UseSharedSpaces) { 746 if (!FLAG_IS_DEFAULT(CompressedClassSpaceBaseAddress)) { 747 log_warning(metaspace)("CDS active - ignoring CompressedClassSpaceBaseAddress."); 748 } 749 MetaspaceShared::initialize_runtime_shared_and_meta_spaces(); 750 // If any of the archived space fails to map, UseSharedSpaces 751 // is reset to false. 752 } 753 #endif // INCLUDE_CDS 754 755 #ifdef _LP64 756 757 if (using_class_space() && !class_space_is_initialized()) { 758 assert(!UseSharedSpaces, "CDS archive is not mapped at this point"); 759 760 // case (b) (No CDS) 761 ReservedSpace rs; 762 const size_t size = align_up(CompressedClassSpaceSize, Metaspace::reserve_alignment()); 763 address base = nullptr; 764 765 // If CompressedClassSpaceBaseAddress is set, we attempt to force-map class space to 766 // the given address. This is a debug-only feature aiding tests. Due to the ASLR lottery 767 // this may fail, in which case the VM will exit after printing an appropriate message. 768 // Tests using this switch should cope with that. 769 if (CompressedClassSpaceBaseAddress != 0) { 770 base = (address)CompressedClassSpaceBaseAddress; 771 if (!is_aligned(base, Metaspace::reserve_alignment())) { 772 vm_exit_during_initialization( 773 err_msg("CompressedClassSpaceBaseAddress=" PTR_FORMAT " invalid " 774 "(must be aligned to " SIZE_FORMAT_X ").", 775 CompressedClassSpaceBaseAddress, Metaspace::reserve_alignment())); 776 } 777 rs = ReservedSpace(size, Metaspace::reserve_alignment(), 778 os::vm_page_size() /* large */, (char*)base); 779 if (rs.is_reserved()) { 780 log_info(metaspace)("Successfully forced class space address to " PTR_FORMAT, p2i(base)); 781 } else { 782 vm_exit_during_initialization( 783 err_msg("CompressedClassSpaceBaseAddress=" PTR_FORMAT " given, but reserving class space failed.", 784 CompressedClassSpaceBaseAddress)); 785 } 786 } 787 788 if (!rs.is_reserved()) { 789 // If UseCompressedOops=1 and the java heap has been placed in coops-friendly 790 // territory, i.e. its base is under 32G, then we attempt to place ccs 791 // right above the java heap. 792 // Otherwise the lower 32G are still free. We try to place ccs at the lowest 793 // allowed mapping address. 794 base = (UseCompressedOops && (uint64_t)CompressedOops::base() < OopEncodingHeapMax) ? 795 CompressedOops::end() : (address)HeapBaseMinAddress; 796 base = align_up(base, Metaspace::reserve_alignment()); 797 798 if (base != nullptr) { 799 if (CompressedKlassPointers::is_valid_base(base)) { 800 rs = ReservedSpace(size, Metaspace::reserve_alignment(), 801 os::vm_page_size(), (char*)base); 802 } 803 } 804 } 805 806 // ...failing that, reserve anywhere, but let platform do optimized placement: 807 if (!rs.is_reserved()) { 808 rs = Metaspace::reserve_address_space_for_compressed_classes(size); 809 } 810 811 // ...failing that, give up. 812 if (!rs.is_reserved()) { 813 vm_exit_during_initialization( 814 err_msg("Could not allocate compressed class space: " SIZE_FORMAT " bytes", 815 CompressedClassSpaceSize)); 816 } 817 818 // Initialize space 819 Metaspace::initialize_class_space(rs); 820 821 // Set up compressed class pointer encoding. 822 CompressedKlassPointers::initialize((address)rs.base(), rs.size()); 823 } 824 825 #endif 826 827 // Initialize non-class virtual space list, and its chunk manager: 828 MetaspaceContext::initialize_nonclass_space_context(); 829 830 _tracer = new MetaspaceTracer(); 831 832 // We must prevent the very first address of the ccs from being used to store 833 // metadata, since that address would translate to a narrow pointer of 0, and the 834 // VM does not distinguish between "narrow 0 as in null" and "narrow 0 as in start 835 // of ccs". 836 // Before Elastic Metaspace that did not happen due to the fact that every Metachunk 837 // had a header and therefore could not allocate anything at offset 0. 838 #ifdef _LP64 839 if (using_class_space()) { 840 // The simplest way to fix this is to allocate a tiny dummy chunk right at the 841 // start of ccs and do not use it for anything. 842 MetaspaceContext::context_class()->cm()->get_chunk(metaspace::chunklevel::HIGHEST_CHUNK_LEVEL); 843 } 844 #endif 845 846 #ifdef _LP64 847 if (UseCompressedClassPointers) { 848 // Note: "cds" would be a better fit but keep this for backward compatibility. 849 LogTarget(Info, gc, metaspace) lt; 850 if (lt.is_enabled()) { 851 ResourceMark rm; 852 LogStream ls(lt); 853 CDS_ONLY(MetaspaceShared::print_on(&ls);) 854 Metaspace::print_compressed_class_space(&ls); 855 CompressedKlassPointers::print_mode(&ls); 856 } 857 } 858 #endif 859 860 } 861 862 void Metaspace::post_initialize() { 863 MetaspaceGC::post_initialize(); 864 } 865 866 size_t Metaspace::max_allocation_word_size() { 867 return metaspace::chunklevel::MAX_CHUNK_WORD_SIZE; 868 } 869 870 // This version of Metaspace::allocate does not throw OOM but simply returns null, and 871 // is suitable for calling from non-Java threads. 872 // Callers are responsible for checking null. 873 MetaWord* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size, 874 MetaspaceObj::Type type) { 875 assert(word_size <= Metaspace::max_allocation_word_size(), 876 "allocation size too large (" SIZE_FORMAT ")", word_size); 877 878 assert(loader_data != nullptr, "Should never pass around a nullptr loader_data. " 879 "ClassLoaderData::the_null_class_loader_data() should have been used."); 880 881 // Deal with concurrent unloading failed allocation starvation 882 MetaspaceCriticalAllocation::block_if_concurrent_purge(); 883 884 MetadataType mdtype = (type == MetaspaceObj::ClassType) ? ClassType : NonClassType; 885 886 // Try to allocate metadata. 887 MetaWord* result = loader_data->metaspace_non_null()->allocate(word_size, mdtype); 888 889 if (result != nullptr) { 890 // Zero initialize. 891 Copy::fill_to_words((HeapWord*)result, word_size, 0); 892 893 log_trace(metaspace)("Metaspace::allocate: type %d return " PTR_FORMAT ".", (int)type, p2i(result)); 894 } 895 896 return result; 897 } 898 899 MetaWord* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size, 900 MetaspaceObj::Type type, TRAPS) { 901 902 if (HAS_PENDING_EXCEPTION) { 903 assert(false, "Should not allocate with exception pending"); 904 return nullptr; // caller does a CHECK_NULL too 905 } 906 907 MetaWord* result = allocate(loader_data, word_size, type); 908 909 if (result == nullptr) { 910 MetadataType mdtype = (type == MetaspaceObj::ClassType) ? ClassType : NonClassType; 911 tracer()->report_metaspace_allocation_failure(loader_data, word_size, type, mdtype); 912 913 // Allocation failed. 914 if (is_init_completed()) { 915 // Only start a GC if the bootstrapping has completed. 916 // Try to clean out some heap memory and retry. This can prevent premature 917 // expansion of the metaspace. 918 result = Universe::heap()->satisfy_failed_metadata_allocation(loader_data, word_size, mdtype); 919 } 920 921 if (result == nullptr) { 922 report_metadata_oome(loader_data, word_size, type, mdtype, THREAD); 923 assert(HAS_PENDING_EXCEPTION, "sanity"); 924 return nullptr; 925 } 926 927 // Zero initialize. 928 Copy::fill_to_words((HeapWord*)result, word_size, 0); 929 930 log_trace(metaspace)("Metaspace::allocate: type %d return " PTR_FORMAT ".", (int)type, p2i(result)); 931 } 932 933 return result; 934 } 935 936 void Metaspace::report_metadata_oome(ClassLoaderData* loader_data, size_t word_size, MetaspaceObj::Type type, MetadataType mdtype, TRAPS) { 937 tracer()->report_metadata_oom(loader_data, word_size, type, mdtype); 938 939 // If result is still null, we are out of memory. 940 Log(gc, metaspace, freelist, oom) log; 941 if (log.is_info()) { 942 log.info("Metaspace (%s) allocation failed for size " SIZE_FORMAT, 943 is_class_space_allocation(mdtype) ? "class" : "data", word_size); 944 ResourceMark rm; 945 if (log.is_debug()) { 946 if (loader_data->metaspace_or_null() != nullptr) { 947 LogStream ls(log.debug()); 948 loader_data->print_value_on(&ls); 949 } 950 } 951 LogStream ls(log.info()); 952 // In case of an OOM, log out a short but still useful report. 953 MetaspaceUtils::print_basic_report(&ls, 0); 954 } 955 956 bool out_of_compressed_class_space = false; 957 if (is_class_space_allocation(mdtype)) { 958 ClassLoaderMetaspace* metaspace = loader_data->metaspace_non_null(); 959 out_of_compressed_class_space = 960 MetaspaceUtils::committed_bytes(Metaspace::ClassType) + 961 align_up(word_size * BytesPerWord, 4 * M) > 962 CompressedClassSpaceSize; 963 } 964 965 // -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support 966 const char* space_string = out_of_compressed_class_space ? 967 "Compressed class space" : "Metaspace"; 968 969 report_java_out_of_memory(space_string); 970 971 if (JvmtiExport::should_post_resource_exhausted()) { 972 JvmtiExport::post_resource_exhausted( 973 JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR, 974 space_string); 975 } 976 977 if (!is_init_completed()) { 978 vm_exit_during_initialization("OutOfMemoryError", space_string); 979 } 980 981 if (out_of_compressed_class_space) { 982 THROW_OOP(Universe::out_of_memory_error_class_metaspace()); 983 } else { 984 THROW_OOP(Universe::out_of_memory_error_metaspace()); 985 } 986 } 987 988 const char* Metaspace::metadata_type_name(Metaspace::MetadataType mdtype) { 989 switch (mdtype) { 990 case Metaspace::ClassType: return "Class"; 991 case Metaspace::NonClassType: return "Metadata"; 992 default: 993 assert(false, "Got bad mdtype: %d", (int) mdtype); 994 return nullptr; 995 } 996 } 997 998 void Metaspace::purge(bool classes_unloaded) { 999 // The MetaspaceCritical_lock is used by a concurrent GC to block out concurrent metaspace 1000 // allocations, that would starve critical metaspace allocations, that are about to throw 1001 // OOM if they fail; they need precedence for correctness. 1002 MutexLocker ml(MetaspaceCritical_lock, Mutex::_no_safepoint_check_flag); 1003 if (classes_unloaded) { 1004 ChunkManager* cm = ChunkManager::chunkmanager_nonclass(); 1005 if (cm != nullptr) { 1006 cm->purge(); 1007 } 1008 if (using_class_space()) { 1009 cm = ChunkManager::chunkmanager_class(); 1010 if (cm != nullptr) { 1011 cm->purge(); 1012 } 1013 } 1014 } 1015 1016 // Try to satisfy queued metaspace allocation requests. 1017 // 1018 // It might seem unnecessary to try to process allocation requests if no 1019 // classes have been unloaded. However, this call is required for the code 1020 // in MetaspaceCriticalAllocation::try_allocate_critical to work. 1021 MetaspaceCriticalAllocation::process(); 1022 } 1023 1024 bool Metaspace::contains(const void* ptr) { 1025 if (MetaspaceShared::is_in_shared_metaspace(ptr)) { 1026 return true; 1027 } 1028 return contains_non_shared(ptr); 1029 } 1030 1031 bool Metaspace::contains_non_shared(const void* ptr) { 1032 if (using_class_space() && VirtualSpaceList::vslist_class()->contains((MetaWord*)ptr)) { 1033 return true; 1034 } 1035 1036 return VirtualSpaceList::vslist_nonclass()->contains((MetaWord*)ptr); 1037 }