1 /*
   2  * Copyright (c) 2011, 2019, 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 #include "aot/aotLoader.hpp"
  27 #include "classfile/classLoaderDataGraph.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 
  58 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::UnsafeAnonymousMetaspaceType: s = "UnsafeAnonymous"; 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.
 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 
 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.
 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 
 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 
 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 
 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 
 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 
 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 
 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.
 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 
 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 
 377 size_t MetaspaceUtils::free_in_vs_bytes() {
 378   return free_in_vs_bytes(Metaspace::ClassType) + free_in_vs_bytes(Metaspace::NonClassType);
 379 }
 380 
 381 static void inc_stat_nonatomically(size_t* pstat, size_t words) {
 382   assert_lock_strong(MetaspaceExpand_lock);
 383   (*pstat) += words;
 384 }
 385 
 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 
 395 static void inc_stat_atomically(volatile size_t* pstat, size_t words) {
 396   Atomic::add(words, pstat);
 397 }
 398 
 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 
 407 void MetaspaceUtils::dec_capacity(Metaspace::MetadataType mdtype, size_t words) {
 408   dec_stat_nonatomically(&_capacity_words[mdtype], words);
 409 }
 410 void MetaspaceUtils::inc_capacity(Metaspace::MetadataType mdtype, size_t words) {
 411   inc_stat_nonatomically(&_capacity_words[mdtype], words);
 412 }
 413 void MetaspaceUtils::dec_used(Metaspace::MetadataType mdtype, size_t words) {
 414   dec_stat_atomically(&_used_words[mdtype], words);
 415 }
 416 void MetaspaceUtils::inc_used(Metaspace::MetadataType mdtype, size_t words) {
 417   inc_stat_atomically(&_used_words[mdtype], words);
 418 }
 419 void MetaspaceUtils::dec_overhead(Metaspace::MetadataType mdtype, size_t words) {
 420   dec_stat_nonatomically(&_overhead_words[mdtype], words);
 421 }
 422 void MetaspaceUtils::inc_overhead(Metaspace::MetadataType mdtype, size_t words) {
 423   inc_stat_nonatomically(&_overhead_words[mdtype], words);
 424 }
 425 
 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 
 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 
 436 size_t MetaspaceUtils::min_chunk_size_words() { return Metaspace::first_chunk_word_size(); }
 437 
 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   return chunk_manager->free_chunks_total_words();
 444 }
 445 
 446 size_t MetaspaceUtils::free_chunks_total_bytes(Metaspace::MetadataType mdtype) {
 447   return free_chunks_total_words(mdtype) * BytesPerWord;
 448 }
 449 
 450 size_t MetaspaceUtils::free_chunks_total_words() {
 451   return free_chunks_total_words(Metaspace::ClassType) +
 452          free_chunks_total_words(Metaspace::NonClassType);
 453 }
 454 
 455 size_t MetaspaceUtils::free_chunks_total_bytes() {
 456   return free_chunks_total_words() * BytesPerWord;
 457 }
 458 
 459 bool MetaspaceUtils::has_chunk_free_list(Metaspace::MetadataType mdtype) {
 460   return Metaspace::get_chunk_manager(mdtype) != NULL;
 461 }
 462 
 463 MetaspaceChunkFreeListSummary MetaspaceUtils::chunk_free_list_summary(Metaspace::MetadataType mdtype) {
 464   if (!has_chunk_free_list(mdtype)) {
 465     return MetaspaceChunkFreeListSummary();
 466   }
 467 
 468   const ChunkManager* cm = Metaspace::get_chunk_manager(mdtype);
 469   return cm->chunk_free_list_summary();
 470 }
 471 
 472 void MetaspaceUtils::print_metaspace_change(size_t prev_metadata_used) {
 473   log_info(gc, metaspace)("Metaspace: "  SIZE_FORMAT "K->" SIZE_FORMAT "K("  SIZE_FORMAT "K)",
 474                           prev_metadata_used/K, used_bytes()/K, reserved_bytes()/K);
 475 }
 476 
 477 void MetaspaceUtils::print_on(outputStream* out) {
 478   Metaspace::MetadataType nct = Metaspace::NonClassType;
 479 
 480   out->print_cr(" Metaspace       "
 481                 "used "      SIZE_FORMAT "K, "
 482                 "capacity "  SIZE_FORMAT "K, "
 483                 "committed " SIZE_FORMAT "K, "
 484                 "reserved "  SIZE_FORMAT "K",
 485                 used_bytes()/K,
 486                 capacity_bytes()/K,
 487                 committed_bytes()/K,
 488                 reserved_bytes()/K);
 489 
 490   if (Metaspace::using_class_space()) {
 491     Metaspace::MetadataType ct = Metaspace::ClassType;
 492     out->print_cr("  class space    "
 493                   "used "      SIZE_FORMAT "K, "
 494                   "capacity "  SIZE_FORMAT "K, "
 495                   "committed " SIZE_FORMAT "K, "
 496                   "reserved "  SIZE_FORMAT "K",
 497                   used_bytes(ct)/K,
 498                   capacity_bytes(ct)/K,
 499                   committed_bytes(ct)/K,
 500                   reserved_bytes(ct)/K);
 501   }
 502 }
 503 
 504 
 505 void MetaspaceUtils::print_vs(outputStream* out, size_t scale) {
 506   const size_t reserved_nonclass_words = reserved_bytes(Metaspace::NonClassType) / sizeof(MetaWord);
 507   const size_t committed_nonclass_words = committed_bytes(Metaspace::NonClassType) / sizeof(MetaWord);
 508   {
 509     if (Metaspace::using_class_space()) {
 510       out->print("  Non-class space:  ");
 511     }
 512     print_scaled_words(out, reserved_nonclass_words, scale, 7);
 513     out->print(" reserved, ");
 514     print_scaled_words_and_percentage(out, committed_nonclass_words, reserved_nonclass_words, scale, 7);
 515     out->print_cr(" committed ");
 516 
 517     if (Metaspace::using_class_space()) {
 518       const size_t reserved_class_words = reserved_bytes(Metaspace::ClassType) / sizeof(MetaWord);
 519       const size_t committed_class_words = committed_bytes(Metaspace::ClassType) / sizeof(MetaWord);
 520       out->print("      Class space:  ");
 521       print_scaled_words(out, reserved_class_words, scale, 7);
 522       out->print(" reserved, ");
 523       print_scaled_words_and_percentage(out, committed_class_words, reserved_class_words, scale, 7);
 524       out->print_cr(" committed ");
 525 
 526       const size_t reserved_words = reserved_nonclass_words + reserved_class_words;
 527       const size_t committed_words = committed_nonclass_words + committed_class_words;
 528       out->print("             Both:  ");
 529       print_scaled_words(out, reserved_words, scale, 7);
 530       out->print(" reserved, ");
 531       print_scaled_words_and_percentage(out, committed_words, reserved_words, scale, 7);
 532       out->print_cr(" committed ");
 533     }
 534   }
 535 }
 536 
 537 // This will print out a basic metaspace usage report but
 538 // unlike print_report() is guaranteed not to lock or to walk the CLDG.
 539 void MetaspaceUtils::print_basic_report(outputStream* out, size_t scale) {
 540 
 541   out->cr();
 542   out->print_cr("Usage:");
 543 
 544   if (Metaspace::using_class_space()) {
 545     out->print("  Non-class:  ");
 546   }
 547 
 548   // In its most basic form, we do not require walking the CLDG. Instead, just print the running totals from
 549   // MetaspaceUtils.
 550   const size_t cap_nc = MetaspaceUtils::capacity_words(Metaspace::NonClassType);
 551   const size_t overhead_nc = MetaspaceUtils::overhead_words(Metaspace::NonClassType);
 552   const size_t used_nc = MetaspaceUtils::used_words(Metaspace::NonClassType);
 553   const size_t free_and_waste_nc = cap_nc - overhead_nc - used_nc;
 554 
 555   print_scaled_words(out, cap_nc, scale, 5);
 556   out->print(" capacity, ");
 557   print_scaled_words_and_percentage(out, used_nc, cap_nc, scale, 5);
 558   out->print(" used, ");
 559   print_scaled_words_and_percentage(out, free_and_waste_nc, cap_nc, scale, 5);
 560   out->print(" free+waste, ");
 561   print_scaled_words_and_percentage(out, overhead_nc, cap_nc, scale, 5);
 562   out->print(" overhead. ");
 563   out->cr();
 564 
 565   if (Metaspace::using_class_space()) {
 566     const size_t cap_c = MetaspaceUtils::capacity_words(Metaspace::ClassType);
 567     const size_t overhead_c = MetaspaceUtils::overhead_words(Metaspace::ClassType);
 568     const size_t used_c = MetaspaceUtils::used_words(Metaspace::ClassType);
 569     const size_t free_and_waste_c = cap_c - overhead_c - used_c;
 570     out->print("      Class:  ");
 571     print_scaled_words(out, cap_c, scale, 5);
 572     out->print(" capacity, ");
 573     print_scaled_words_and_percentage(out, used_c, cap_c, scale, 5);
 574     out->print(" used, ");
 575     print_scaled_words_and_percentage(out, free_and_waste_c, cap_c, scale, 5);
 576     out->print(" free+waste, ");
 577     print_scaled_words_and_percentage(out, overhead_c, cap_c, scale, 5);
 578     out->print(" overhead. ");
 579     out->cr();
 580 
 581     out->print("       Both:  ");
 582     const size_t cap = cap_nc + cap_c;
 583 
 584     print_scaled_words(out, cap, scale, 5);
 585     out->print(" capacity, ");
 586     print_scaled_words_and_percentage(out, used_nc + used_c, cap, scale, 5);
 587     out->print(" used, ");
 588     print_scaled_words_and_percentage(out, free_and_waste_nc + free_and_waste_c, cap, scale, 5);
 589     out->print(" free+waste, ");
 590     print_scaled_words_and_percentage(out, overhead_nc + overhead_c, cap, scale, 5);
 591     out->print(" overhead. ");
 592     out->cr();
 593   }
 594 
 595   out->cr();
 596   out->print_cr("Virtual space:");
 597 
 598   print_vs(out, scale);
 599 
 600   out->cr();
 601   out->print_cr("Chunk freelists:");
 602 
 603   if (Metaspace::using_class_space()) {
 604     out->print("   Non-Class:  ");
 605   }
 606   print_human_readable_size(out, Metaspace::chunk_manager_metadata()->free_chunks_total_bytes(), scale);
 607   out->cr();
 608   if (Metaspace::using_class_space()) {
 609     out->print("       Class:  ");
 610     print_human_readable_size(out, Metaspace::chunk_manager_class()->free_chunks_total_bytes(), scale);
 611     out->cr();
 612     out->print("        Both:  ");
 613     print_human_readable_size(out, Metaspace::chunk_manager_class()->free_chunks_total_bytes() +
 614                               Metaspace::chunk_manager_metadata()->free_chunks_total_bytes(), scale);
 615     out->cr();
 616   }
 617   out->cr();
 618 
 619 }
 620 
 621 void MetaspaceUtils::print_report(outputStream* out, size_t scale, int flags) {
 622 
 623   const bool print_loaders = (flags & rf_show_loaders) > 0;
 624   const bool print_classes = (flags & rf_show_classes) > 0;
 625   const bool print_by_chunktype = (flags & rf_break_down_by_chunktype) > 0;
 626   const bool print_by_spacetype = (flags & rf_break_down_by_spacetype) > 0;
 627 
 628   // Some report options require walking the class loader data graph.
 629   PrintCLDMetaspaceInfoClosure cl(out, scale, print_loaders, print_classes, print_by_chunktype);
 630   if (print_loaders) {
 631     out->cr();
 632     out->print_cr("Usage per loader:");
 633     out->cr();
 634   }
 635 
 636   ClassLoaderDataGraph::loaded_cld_do(&cl); // collect data and optionally print
 637 
 638   // Print totals, broken up by space type.
 639   if (print_by_spacetype) {
 640     out->cr();
 641     out->print_cr("Usage per space type:");
 642     out->cr();
 643     for (int space_type = (int)Metaspace::ZeroMetaspaceType;
 644          space_type < (int)Metaspace::MetaspaceTypeCount; space_type ++)
 645     {
 646       uintx num = cl._num_loaders_by_spacetype[space_type];
 647       out->print("%s (" UINTX_FORMAT " loader%s)%c",
 648         space_type_name((Metaspace::MetaspaceType)space_type),
 649         num, (num == 1 ? "" : "s"), (num > 0 ? ':' : '.'));
 650       if (num > 0) {
 651         cl._stats_by_spacetype[space_type].print_on(out, scale, print_by_chunktype);
 652       }
 653       out->cr();
 654     }
 655   }
 656 
 657   // Print totals for in-use data:
 658   out->cr();
 659   out->print_cr("Total Usage ( " UINTX_FORMAT " loader%s)%c",
 660       cl._num_loaders, (cl._num_loaders == 1 ? "" : "s"), (cl._num_loaders > 0 ? ':' : '.'));
 661 
 662   cl._stats_total.print_on(out, scale, print_by_chunktype);
 663 
 664   // -- Print Virtual space.
 665   out->cr();
 666   out->print_cr("Virtual space:");
 667 
 668   print_vs(out, scale);
 669 
 670   // -- Print VirtualSpaceList details.
 671   if ((flags & rf_show_vslist) > 0) {
 672     out->cr();
 673     out->print_cr("Virtual space list%s:", Metaspace::using_class_space() ? "s" : "");
 674 
 675     if (Metaspace::using_class_space()) {
 676       out->print_cr("   Non-Class:");
 677     }
 678     Metaspace::space_list()->print_on(out, scale);
 679     if (Metaspace::using_class_space()) {
 680       out->print_cr("       Class:");
 681       Metaspace::class_space_list()->print_on(out, scale);
 682     }
 683   }
 684   out->cr();
 685 
 686   // -- Print VirtualSpaceList map.
 687   if ((flags & rf_show_vsmap) > 0) {
 688     out->cr();
 689     out->print_cr("Virtual space map:");
 690 
 691     if (Metaspace::using_class_space()) {
 692       out->print_cr("   Non-Class:");
 693     }
 694     Metaspace::space_list()->print_map(out);
 695     if (Metaspace::using_class_space()) {
 696       out->print_cr("       Class:");
 697       Metaspace::class_space_list()->print_map(out);
 698     }
 699   }
 700   out->cr();
 701 
 702   // -- Print Freelists (ChunkManager) details
 703   out->cr();
 704   out->print_cr("Chunk freelist%s:", Metaspace::using_class_space() ? "s" : "");
 705 
 706   ChunkManagerStatistics non_class_cm_stat;
 707   Metaspace::chunk_manager_metadata()->collect_statistics(&non_class_cm_stat);
 708 
 709   if (Metaspace::using_class_space()) {
 710     out->print_cr("   Non-Class:");
 711   }
 712   non_class_cm_stat.print_on(out, scale);
 713 
 714   if (Metaspace::using_class_space()) {
 715     ChunkManagerStatistics class_cm_stat;
 716     Metaspace::chunk_manager_class()->collect_statistics(&class_cm_stat);
 717     out->print_cr("       Class:");
 718     class_cm_stat.print_on(out, scale);
 719   }
 720 
 721   // As a convenience, print a summary of common waste.
 722   out->cr();
 723   out->print("Waste ");
 724   // For all wastages, print percentages from total. As total use the total size of memory committed for metaspace.
 725   const size_t committed_words = committed_bytes() / BytesPerWord;
 726 
 727   out->print("(percentages refer to total committed size ");
 728   print_scaled_words(out, committed_words, scale);
 729   out->print_cr("):");
 730 
 731   // Print space committed but not yet used by any class loader
 732   const size_t unused_words_in_vs = MetaspaceUtils::free_in_vs_bytes() / BytesPerWord;
 733   out->print("              Committed unused: ");
 734   print_scaled_words_and_percentage(out, unused_words_in_vs, committed_words, scale, 6);
 735   out->cr();
 736 
 737   // Print waste for in-use chunks.
 738   UsedChunksStatistics ucs_nonclass = cl._stats_total.nonclass_sm_stats().totals();
 739   UsedChunksStatistics ucs_class = cl._stats_total.class_sm_stats().totals();
 740   UsedChunksStatistics ucs_all;
 741   ucs_all.add(ucs_nonclass);
 742   ucs_all.add(ucs_class);
 743 
 744   out->print("        Waste in chunks in use: ");
 745   print_scaled_words_and_percentage(out, ucs_all.waste(), committed_words, scale, 6);
 746   out->cr();
 747   out->print("         Free in chunks in use: ");
 748   print_scaled_words_and_percentage(out, ucs_all.free(), committed_words, scale, 6);
 749   out->cr();
 750   out->print("     Overhead in chunks in use: ");
 751   print_scaled_words_and_percentage(out, ucs_all.overhead(), committed_words, scale, 6);
 752   out->cr();
 753 
 754   // Print waste in free chunks.
 755   const size_t total_capacity_in_free_chunks =
 756       Metaspace::chunk_manager_metadata()->free_chunks_total_words() +
 757      (Metaspace::using_class_space() ? Metaspace::chunk_manager_class()->free_chunks_total_words() : 0);
 758   out->print("                In free chunks: ");
 759   print_scaled_words_and_percentage(out, total_capacity_in_free_chunks, committed_words, scale, 6);
 760   out->cr();
 761 
 762   // Print waste in deallocated blocks.
 763   const uintx free_blocks_num =
 764       cl._stats_total.nonclass_sm_stats().free_blocks_num() +
 765       cl._stats_total.class_sm_stats().free_blocks_num();
 766   const size_t free_blocks_cap_words =
 767       cl._stats_total.nonclass_sm_stats().free_blocks_cap_words() +
 768       cl._stats_total.class_sm_stats().free_blocks_cap_words();
 769   out->print("Deallocated from chunks in use: ");
 770   print_scaled_words_and_percentage(out, free_blocks_cap_words, committed_words, scale, 6);
 771   out->print(" (" UINTX_FORMAT " blocks)", free_blocks_num);
 772   out->cr();
 773 
 774   // Print total waste.
 775   const size_t total_waste = ucs_all.waste() + ucs_all.free() + ucs_all.overhead() + total_capacity_in_free_chunks
 776       + free_blocks_cap_words + unused_words_in_vs;
 777   out->print("                       -total-: ");
 778   print_scaled_words_and_percentage(out, total_waste, committed_words, scale, 6);
 779   out->cr();
 780 
 781   // Print internal statistics
 782 #ifdef ASSERT
 783   out->cr();
 784   out->cr();
 785   out->print_cr("Internal statistics:");
 786   out->cr();
 787   out->print_cr("Number of allocations: " UINTX_FORMAT ".", g_internal_statistics.num_allocs);
 788   out->print_cr("Number of space births: " UINTX_FORMAT ".", g_internal_statistics.num_metaspace_births);
 789   out->print_cr("Number of space deaths: " UINTX_FORMAT ".", g_internal_statistics.num_metaspace_deaths);
 790   out->print_cr("Number of virtual space node births: " UINTX_FORMAT ".", g_internal_statistics.num_vsnodes_created);
 791   out->print_cr("Number of virtual space node deaths: " UINTX_FORMAT ".", g_internal_statistics.num_vsnodes_purged);
 792   out->print_cr("Number of times virtual space nodes were expanded: " UINTX_FORMAT ".", g_internal_statistics.num_committed_space_expanded);
 793   out->print_cr("Number of deallocations: " UINTX_FORMAT " (" UINTX_FORMAT " external).", g_internal_statistics.num_deallocs, g_internal_statistics.num_external_deallocs);
 794   out->print_cr("Allocations from deallocated blocks: " UINTX_FORMAT ".", g_internal_statistics.num_allocs_from_deallocated_blocks);
 795   out->print_cr("Number of chunks added to freelist: " UINTX_FORMAT ".",
 796                 g_internal_statistics.num_chunks_added_to_freelist);
 797   out->print_cr("Number of chunks removed from freelist: " UINTX_FORMAT ".",
 798                 g_internal_statistics.num_chunks_removed_from_freelist);
 799   out->print_cr("Number of chunk merges: " UINTX_FORMAT ", split-ups: " UINTX_FORMAT ".",
 800                 g_internal_statistics.num_chunk_merges, g_internal_statistics.num_chunk_splits);
 801 
 802   out->cr();
 803 #endif
 804 
 805   // Print some interesting settings
 806   out->cr();
 807   out->cr();
 808   out->print("MaxMetaspaceSize: ");
 809   print_human_readable_size(out, MaxMetaspaceSize, scale);
 810   out->cr();
 811   out->print("InitialBootClassLoaderMetaspaceSize: ");
 812   print_human_readable_size(out, InitialBootClassLoaderMetaspaceSize, scale);
 813   out->cr();
 814 
 815   out->print("UseCompressedClassPointers: %s", UseCompressedClassPointers ? "true" : "false");
 816   out->cr();
 817   if (Metaspace::using_class_space()) {
 818     out->print("CompressedClassSpaceSize: ");
 819     print_human_readable_size(out, CompressedClassSpaceSize, scale);
 820   }
 821 
 822   out->cr();
 823   out->cr();
 824 
 825 } // MetaspaceUtils::print_report()
 826 
 827 // Prints an ASCII representation of the given space.
 828 void MetaspaceUtils::print_metaspace_map(outputStream* out, Metaspace::MetadataType mdtype) {
 829   MutexLockerEx cl(MetaspaceExpand_lock, Mutex::_no_safepoint_check_flag);
 830   const bool for_class = mdtype == Metaspace::ClassType ? true : false;
 831   VirtualSpaceList* const vsl = for_class ? Metaspace::class_space_list() : Metaspace::space_list();
 832   if (vsl != NULL) {
 833     if (for_class) {
 834       if (!Metaspace::using_class_space()) {
 835         out->print_cr("No Class Space.");
 836         return;
 837       }
 838       out->print_raw("---- Metaspace Map (Class Space) ----");
 839     } else {
 840       out->print_raw("---- Metaspace Map (Non-Class Space) ----");
 841     }
 842     // Print legend:
 843     out->cr();
 844     out->print_cr("Chunk Types (uppercase chunks are in use): x-specialized, s-small, m-medium, h-humongous.");
 845     out->cr();
 846     VirtualSpaceList* const vsl = for_class ? Metaspace::class_space_list() : Metaspace::space_list();
 847     vsl->print_map(out);
 848     out->cr();
 849   }
 850 }
 851 
 852 void MetaspaceUtils::verify_free_chunks() {
 853 #ifdef ASSERT
 854   Metaspace::chunk_manager_metadata()->verify(false);
 855   if (Metaspace::using_class_space()) {
 856     Metaspace::chunk_manager_class()->verify(false);
 857   }
 858 #endif
 859 }
 860 
 861 void MetaspaceUtils::verify_metrics() {
 862 #ifdef ASSERT
 863   // Please note: there are time windows where the internal counters are out of sync with
 864   // reality. For example, when a newly created ClassLoaderMetaspace creates its first chunk -
 865   // the ClassLoaderMetaspace is not yet attached to its ClassLoaderData object and hence will
 866   // not be counted when iterating the CLDG. So be careful when you call this method.
 867   ClassLoaderMetaspaceStatistics total_stat;
 868   collect_statistics(&total_stat);
 869   UsedChunksStatistics nonclass_chunk_stat = total_stat.nonclass_sm_stats().totals();
 870   UsedChunksStatistics class_chunk_stat = total_stat.class_sm_stats().totals();
 871 
 872   bool mismatch = false;
 873   for (int i = 0; i < Metaspace::MetadataTypeCount; i ++) {
 874     Metaspace::MetadataType mdtype = (Metaspace::MetadataType)i;
 875     UsedChunksStatistics chunk_stat = total_stat.sm_stats(mdtype).totals();
 876     if (capacity_words(mdtype) != chunk_stat.cap() ||
 877         used_words(mdtype) != chunk_stat.used() ||
 878         overhead_words(mdtype) != chunk_stat.overhead()) {
 879       mismatch = true;
 880       tty->print_cr("MetaspaceUtils::verify_metrics: counter mismatch for mdtype=%u:", mdtype);
 881       tty->print_cr("Expected cap " SIZE_FORMAT ", used " SIZE_FORMAT ", overhead " SIZE_FORMAT ".",
 882                     capacity_words(mdtype), used_words(mdtype), overhead_words(mdtype));
 883       tty->print_cr("Got cap " SIZE_FORMAT ", used " SIZE_FORMAT ", overhead " SIZE_FORMAT ".",
 884                     chunk_stat.cap(), chunk_stat.used(), chunk_stat.overhead());
 885       tty->flush();
 886     }
 887   }
 888   assert(mismatch == false, "MetaspaceUtils::verify_metrics: counter mismatch.");
 889 #endif
 890 }
 891 
 892 // Utils to check if a pointer or range is part of a committed metaspace region.
 893 metaspace::VirtualSpaceNode* MetaspaceUtils::find_enclosing_virtual_space(const void* p) {
 894   MutexLockerEx cl(MetaspaceExpand_lock, Mutex::_no_safepoint_check_flag);
 895   VirtualSpaceNode* vsn = Metaspace::space_list()->find_enclosing_space(p);
 896   if (Metaspace::using_class_space() && vsn == NULL) {
 897     vsn = Metaspace::class_space_list()->find_enclosing_space(p);
 898   }
 899   return vsn;
 900 }
 901 
 902 bool MetaspaceUtils::is_range_in_committed(const void* from, const void* to) {
 903 #if INCLUDE_CDS
 904   if (UseSharedSpaces) {
 905     for (int idx = MetaspaceShared::ro; idx <= MetaspaceShared::mc; idx++) {
 906       if (FileMapInfo::current_info()->is_in_shared_region(from, idx)) {
 907         return FileMapInfo::current_info()->is_in_shared_region(to, idx);
 908       }
 909     }
 910   }
 911 #endif
 912   VirtualSpaceNode* vsn = find_enclosing_virtual_space(from);
 913   return (vsn != NULL) && vsn->contains(to);
 914 }
 915 
 916 
 917 // Metaspace methods
 918 
 919 size_t Metaspace::_first_chunk_word_size = 0;
 920 size_t Metaspace::_first_class_chunk_word_size = 0;
 921 
 922 size_t Metaspace::_commit_alignment = 0;
 923 size_t Metaspace::_reserve_alignment = 0;
 924 
 925 VirtualSpaceList* Metaspace::_space_list = NULL;
 926 VirtualSpaceList* Metaspace::_class_space_list = NULL;
 927 
 928 ChunkManager* Metaspace::_chunk_manager_metadata = NULL;
 929 ChunkManager* Metaspace::_chunk_manager_class = NULL;
 930 
 931 #define VIRTUALSPACEMULTIPLIER 2
 932 
 933 #ifdef _LP64
 934 static const uint64_t UnscaledClassSpaceMax = (uint64_t(max_juint) + 1);
 935 
 936 void Metaspace::set_narrow_klass_base_and_shift(address metaspace_base, address cds_base) {
 937   assert(!DumpSharedSpaces, "narrow_klass is set by MetaspaceShared class.");
 938   // Figure out the narrow_klass_base and the narrow_klass_shift.  The
 939   // narrow_klass_base is the lower of the metaspace base and the cds base
 940   // (if cds is enabled).  The narrow_klass_shift depends on the distance
 941   // between the lower base and higher address.
 942   address lower_base;
 943   address higher_address;
 944 #if INCLUDE_CDS
 945   if (UseSharedSpaces) {
 946     higher_address = MAX2((address)(cds_base + MetaspaceShared::core_spaces_size()),
 947                           (address)(metaspace_base + compressed_class_space_size()));
 948     lower_base = MIN2(metaspace_base, cds_base);
 949   } else
 950 #endif
 951   {
 952     higher_address = metaspace_base + compressed_class_space_size();
 953     lower_base = metaspace_base;
 954 
 955     uint64_t klass_encoding_max = UnscaledClassSpaceMax << LogKlassAlignmentInBytes;
 956     // If compressed class space fits in lower 32G, we don't need a base.
 957     if (higher_address <= (address)klass_encoding_max) {
 958       lower_base = 0; // Effectively lower base is zero.
 959     }
 960   }
 961 
 962   Universe::set_narrow_klass_base(lower_base);
 963 
 964   // CDS uses LogKlassAlignmentInBytes for narrow_klass_shift. See
 965   // MetaspaceShared::initialize_dumptime_shared_and_meta_spaces() for
 966   // how dump time narrow_klass_shift is set. Although, CDS can work
 967   // with zero-shift mode also, to be consistent with AOT it uses
 968   // LogKlassAlignmentInBytes for klass shift so archived java heap objects
 969   // can be used at same time as AOT code.
 970   if (!UseSharedSpaces
 971       && (uint64_t)(higher_address - lower_base) <= UnscaledClassSpaceMax) {
 972     Universe::set_narrow_klass_shift(0);
 973   } else {
 974     Universe::set_narrow_klass_shift(LogKlassAlignmentInBytes);
 975   }
 976   AOTLoader::set_narrow_klass_shift();
 977 }
 978 
 979 #if INCLUDE_CDS
 980 // Return TRUE if the specified metaspace_base and cds_base are close enough
 981 // to work with compressed klass pointers.
 982 bool Metaspace::can_use_cds_with_metaspace_addr(char* metaspace_base, address cds_base) {
 983   assert(cds_base != 0 && UseSharedSpaces, "Only use with CDS");
 984   assert(UseCompressedClassPointers, "Only use with CompressedKlassPtrs");
 985   address lower_base = MIN2((address)metaspace_base, cds_base);
 986   address higher_address = MAX2((address)(cds_base + MetaspaceShared::core_spaces_size()),
 987                                 (address)(metaspace_base + compressed_class_space_size()));
 988   return ((uint64_t)(higher_address - lower_base) <= UnscaledClassSpaceMax);
 989 }
 990 #endif
 991 
 992 // Try to allocate the metaspace at the requested addr.
 993 void Metaspace::allocate_metaspace_compressed_klass_ptrs(char* requested_addr, address cds_base) {
 994   assert(!DumpSharedSpaces, "compress klass space is allocated by MetaspaceShared class.");
 995   assert(using_class_space(), "called improperly");
 996   assert(UseCompressedClassPointers, "Only use with CompressedKlassPtrs");
 997   assert(compressed_class_space_size() < KlassEncodingMetaspaceMax,
 998          "Metaspace size is too big");
 999   assert_is_aligned(requested_addr, _reserve_alignment);
1000   assert_is_aligned(cds_base, _reserve_alignment);
1001   assert_is_aligned(compressed_class_space_size(), _reserve_alignment);
1002 
1003   // Don't use large pages for the class space.
1004   bool large_pages = false;
1005 
1006 #if !(defined(AARCH64) || defined(AIX))
1007   ReservedSpace metaspace_rs = ReservedSpace(compressed_class_space_size(),
1008                                              _reserve_alignment,
1009                                              large_pages,
1010                                              requested_addr);
1011 #else // AARCH64
1012   ReservedSpace metaspace_rs;
1013 
1014   // Our compressed klass pointers may fit nicely into the lower 32
1015   // bits.
1016   if ((uint64_t)requested_addr + compressed_class_space_size() < 4*G) {
1017     metaspace_rs = ReservedSpace(compressed_class_space_size(),
1018                                  _reserve_alignment,
1019                                  large_pages,
1020                                  requested_addr);
1021   }
1022 
1023   if (! metaspace_rs.is_reserved()) {
1024     // Aarch64: Try to align metaspace so that we can decode a compressed
1025     // klass with a single MOVK instruction.  We can do this iff the
1026     // compressed class base is a multiple of 4G.
1027     // Aix: Search for a place where we can find memory. If we need to load
1028     // the base, 4G alignment is helpful, too.
1029     size_t increment = AARCH64_ONLY(4*)G;
1030     for (char *a = align_up(requested_addr, increment);
1031          a < (char*)(1024*G);
1032          a += increment) {
1033       if (a == (char *)(32*G)) {
1034         // Go faster from here on. Zero-based is no longer possible.
1035         increment = 4*G;
1036       }
1037 
1038 #if INCLUDE_CDS
1039       if (UseSharedSpaces
1040           && ! can_use_cds_with_metaspace_addr(a, cds_base)) {
1041         // We failed to find an aligned base that will reach.  Fall
1042         // back to using our requested addr.
1043         metaspace_rs = ReservedSpace(compressed_class_space_size(),
1044                                      _reserve_alignment,
1045                                      large_pages,
1046                                      requested_addr);
1047         break;
1048       }
1049 #endif
1050 
1051       metaspace_rs = ReservedSpace(compressed_class_space_size(),
1052                                    _reserve_alignment,
1053                                    large_pages,
1054                                    a);
1055       if (metaspace_rs.is_reserved())
1056         break;
1057     }
1058   }
1059 
1060 #endif // AARCH64
1061 
1062   if (!metaspace_rs.is_reserved()) {
1063 #if INCLUDE_CDS
1064     if (UseSharedSpaces) {
1065       size_t increment = align_up(1*G, _reserve_alignment);
1066 
1067       // Keep trying to allocate the metaspace, increasing the requested_addr
1068       // by 1GB each time, until we reach an address that will no longer allow
1069       // use of CDS with compressed klass pointers.
1070       char *addr = requested_addr;
1071       while (!metaspace_rs.is_reserved() && (addr + increment > addr) &&
1072              can_use_cds_with_metaspace_addr(addr + increment, cds_base)) {
1073         addr = addr + increment;
1074         metaspace_rs = ReservedSpace(compressed_class_space_size(),
1075                                      _reserve_alignment, large_pages, addr);
1076       }
1077     }
1078 #endif
1079     // If no successful allocation then try to allocate the space anywhere.  If
1080     // that fails then OOM doom.  At this point we cannot try allocating the
1081     // metaspace as if UseCompressedClassPointers is off because too much
1082     // initialization has happened that depends on UseCompressedClassPointers.
1083     // So, UseCompressedClassPointers cannot be turned off at this point.
1084     if (!metaspace_rs.is_reserved()) {
1085       metaspace_rs = ReservedSpace(compressed_class_space_size(),
1086                                    _reserve_alignment, large_pages);
1087       if (!metaspace_rs.is_reserved()) {
1088         vm_exit_during_initialization(err_msg("Could not allocate metaspace: " SIZE_FORMAT " bytes",
1089                                               compressed_class_space_size()));
1090       }
1091     }
1092   }
1093 
1094   // If we got here then the metaspace got allocated.
1095   MemTracker::record_virtual_memory_type((address)metaspace_rs.base(), mtClass);
1096 
1097 #if INCLUDE_CDS
1098   // Verify that we can use shared spaces.  Otherwise, turn off CDS.
1099   if (UseSharedSpaces && !can_use_cds_with_metaspace_addr(metaspace_rs.base(), cds_base)) {
1100     FileMapInfo::stop_sharing_and_unmap(
1101         "Could not allocate metaspace at a compatible address");
1102   }
1103 #endif
1104   set_narrow_klass_base_and_shift((address)metaspace_rs.base(),
1105                                   UseSharedSpaces ? (address)cds_base : 0);
1106 
1107   initialize_class_space(metaspace_rs);
1108 
1109   LogTarget(Trace, gc, metaspace) lt;
1110   if (lt.is_enabled()) {
1111     ResourceMark rm;
1112     LogStream ls(lt);
1113     print_compressed_class_space(&ls, requested_addr);
1114   }
1115 }
1116 
1117 void Metaspace::print_compressed_class_space(outputStream* st, const char* requested_addr) {
1118   st->print_cr("Narrow klass base: " PTR_FORMAT ", Narrow klass shift: %d",
1119                p2i(Universe::narrow_klass_base()), Universe::narrow_klass_shift());
1120   if (_class_space_list != NULL) {
1121     address base = (address)_class_space_list->current_virtual_space()->bottom();
1122     st->print("Compressed class space size: " SIZE_FORMAT " Address: " PTR_FORMAT,
1123                  compressed_class_space_size(), p2i(base));
1124     if (requested_addr != 0) {
1125       st->print(" Req Addr: " PTR_FORMAT, p2i(requested_addr));
1126     }
1127     st->cr();
1128   }
1129 }
1130 
1131 // For UseCompressedClassPointers the class space is reserved above the top of
1132 // the Java heap.  The argument passed in is at the base of the compressed space.
1133 void Metaspace::initialize_class_space(ReservedSpace rs) {
1134   // The reserved space size may be bigger because of alignment, esp with UseLargePages
1135   assert(rs.size() >= CompressedClassSpaceSize,
1136          SIZE_FORMAT " != " SIZE_FORMAT, rs.size(), CompressedClassSpaceSize);
1137   assert(using_class_space(), "Must be using class space");
1138   _class_space_list = new VirtualSpaceList(rs);
1139   _chunk_manager_class = new ChunkManager(true/*is_class*/);
1140 
1141   if (!_class_space_list->initialization_succeeded()) {
1142     vm_exit_during_initialization("Failed to setup compressed class space virtual space list.");
1143   }
1144 }
1145 
1146 #endif
1147 
1148 void Metaspace::ergo_initialize() {
1149   if (DumpSharedSpaces) {
1150     // Using large pages when dumping the shared archive is currently not implemented.
1151     FLAG_SET_ERGO(bool, UseLargePagesInMetaspace, false);
1152   }
1153 
1154   size_t page_size = os::vm_page_size();
1155   if (UseLargePages && UseLargePagesInMetaspace) {
1156     page_size = os::large_page_size();
1157   }
1158 
1159   _commit_alignment  = page_size;
1160   _reserve_alignment = MAX2(page_size, (size_t)os::vm_allocation_granularity());
1161 
1162   // Do not use FLAG_SET_ERGO to update MaxMetaspaceSize, since this will
1163   // override if MaxMetaspaceSize was set on the command line or not.
1164   // This information is needed later to conform to the specification of the
1165   // java.lang.management.MemoryUsage API.
1166   //
1167   // Ideally, we would be able to set the default value of MaxMetaspaceSize in
1168   // globals.hpp to the aligned value, but this is not possible, since the
1169   // alignment depends on other flags being parsed.
1170   MaxMetaspaceSize = align_down_bounded(MaxMetaspaceSize, _reserve_alignment);
1171 
1172   if (MetaspaceSize > MaxMetaspaceSize) {
1173     MetaspaceSize = MaxMetaspaceSize;
1174   }
1175 
1176   MetaspaceSize = align_down_bounded(MetaspaceSize, _commit_alignment);
1177 
1178   assert(MetaspaceSize <= MaxMetaspaceSize, "MetaspaceSize should be limited by MaxMetaspaceSize");
1179 
1180   MinMetaspaceExpansion = align_down_bounded(MinMetaspaceExpansion, _commit_alignment);
1181   MaxMetaspaceExpansion = align_down_bounded(MaxMetaspaceExpansion, _commit_alignment);
1182 
1183   CompressedClassSpaceSize = align_down_bounded(CompressedClassSpaceSize, _reserve_alignment);
1184 
1185   // Initial virtual space size will be calculated at global_initialize()
1186   size_t min_metaspace_sz =
1187       VIRTUALSPACEMULTIPLIER * InitialBootClassLoaderMetaspaceSize;
1188   if (UseCompressedClassPointers) {
1189     if ((min_metaspace_sz + CompressedClassSpaceSize) >  MaxMetaspaceSize) {
1190       if (min_metaspace_sz >= MaxMetaspaceSize) {
1191         vm_exit_during_initialization("MaxMetaspaceSize is too small.");
1192       } else {
1193         FLAG_SET_ERGO(size_t, CompressedClassSpaceSize,
1194                       MaxMetaspaceSize - min_metaspace_sz);
1195       }
1196     }
1197   } else if (min_metaspace_sz >= MaxMetaspaceSize) {
1198     FLAG_SET_ERGO(size_t, InitialBootClassLoaderMetaspaceSize,
1199                   min_metaspace_sz);
1200   }
1201 
1202   set_compressed_class_space_size(CompressedClassSpaceSize);
1203 }
1204 
1205 void Metaspace::global_initialize() {
1206   MetaspaceGC::initialize();
1207 
1208 #if INCLUDE_CDS
1209   if (DumpSharedSpaces) {
1210     MetaspaceShared::initialize_dumptime_shared_and_meta_spaces();
1211   } else if (UseSharedSpaces) {
1212     // If any of the archived space fails to map, UseSharedSpaces
1213     // is reset to false. Fall through to the
1214     // (!DumpSharedSpaces && !UseSharedSpaces) case to set up class
1215     // metaspace.
1216     MetaspaceShared::initialize_runtime_shared_and_meta_spaces();
1217   }
1218 
1219   if (!DumpSharedSpaces && !UseSharedSpaces)
1220 #endif // INCLUDE_CDS
1221   {
1222 #ifdef _LP64
1223     if (using_class_space()) {
1224       char* base = (char*)align_up(Universe::heap()->reserved_region().end(), _reserve_alignment);
1225       allocate_metaspace_compressed_klass_ptrs(base, 0);
1226     }
1227 #endif // _LP64
1228   }
1229 
1230   // Initialize these before initializing the VirtualSpaceList
1231   _first_chunk_word_size = InitialBootClassLoaderMetaspaceSize / BytesPerWord;
1232   _first_chunk_word_size = align_word_size_up(_first_chunk_word_size);
1233   // Make the first class chunk bigger than a medium chunk so it's not put
1234   // on the medium chunk list.   The next chunk will be small and progress
1235   // from there.  This size calculated by -version.
1236   _first_class_chunk_word_size = MIN2((size_t)MediumChunk*6,
1237                                      (CompressedClassSpaceSize/BytesPerWord)*2);
1238   _first_class_chunk_word_size = align_word_size_up(_first_class_chunk_word_size);
1239   // Arbitrarily set the initial virtual space to a multiple
1240   // of the boot class loader size.
1241   size_t word_size = VIRTUALSPACEMULTIPLIER * _first_chunk_word_size;
1242   word_size = align_up(word_size, Metaspace::reserve_alignment_words());
1243 
1244   // Initialize the list of virtual spaces.
1245   _space_list = new VirtualSpaceList(word_size);
1246   _chunk_manager_metadata = new ChunkManager(false/*metaspace*/);
1247 
1248   if (!_space_list->initialization_succeeded()) {
1249     vm_exit_during_initialization("Unable to setup metadata virtual space list.", NULL);
1250   }
1251 
1252   _tracer = new MetaspaceTracer();
1253 }
1254 
1255 void Metaspace::post_initialize() {
1256   MetaspaceGC::post_initialize();
1257 }
1258 
1259 void Metaspace::verify_global_initialization() {
1260   assert(space_list() != NULL, "Metadata VirtualSpaceList has not been initialized");
1261   assert(chunk_manager_metadata() != NULL, "Metadata ChunkManager has not been initialized");
1262 
1263   if (using_class_space()) {
1264     assert(class_space_list() != NULL, "Class VirtualSpaceList has not been initialized");
1265     assert(chunk_manager_class() != NULL, "Class ChunkManager has not been initialized");
1266   }
1267 }
1268 
1269 size_t Metaspace::align_word_size_up(size_t word_size) {
1270   size_t byte_size = word_size * wordSize;
1271   return ReservedSpace::allocation_align_size_up(byte_size) / wordSize;
1272 }
1273 
1274 MetaWord* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size,
1275                               MetaspaceObj::Type type, TRAPS) {
1276   assert(!_frozen, "sanity");
1277   assert(!(DumpSharedSpaces && THREAD->is_VM_thread()), "sanity");
1278 
1279   if (HAS_PENDING_EXCEPTION) {
1280     assert(false, "Should not allocate with exception pending");
1281     return NULL;  // caller does a CHECK_NULL too
1282   }
1283 
1284   assert(loader_data != NULL, "Should never pass around a NULL loader_data. "
1285         "ClassLoaderData::the_null_class_loader_data() should have been used.");
1286 
1287   MetadataType mdtype = (type == MetaspaceObj::ClassType) ? ClassType : NonClassType;
1288 
1289   // Try to allocate metadata.
1290   MetaWord* result = loader_data->metaspace_non_null()->allocate(word_size, mdtype);
1291 
1292   if (result == NULL) {
1293     tracer()->report_metaspace_allocation_failure(loader_data, word_size, type, mdtype);
1294 
1295     // Allocation failed.
1296     if (is_init_completed()) {
1297       // Only start a GC if the bootstrapping has completed.
1298       // Try to clean out some heap memory and retry. This can prevent premature
1299       // expansion of the metaspace.
1300       result = Universe::heap()->satisfy_failed_metadata_allocation(loader_data, word_size, mdtype);
1301     }
1302   }
1303 
1304   if (result == NULL) {
1305     if (DumpSharedSpaces) {
1306       // CDS dumping keeps loading classes, so if we hit an OOM we probably will keep hitting OOM.
1307       // We should abort to avoid generating a potentially bad archive.
1308       vm_exit_during_cds_dumping(err_msg("Failed allocating metaspace object type %s of size " SIZE_FORMAT ". CDS dump aborted.",
1309           MetaspaceObj::type_name(type), word_size * BytesPerWord),
1310         err_msg("Please increase MaxMetaspaceSize (currently " SIZE_FORMAT " bytes).", MaxMetaspaceSize));
1311     }
1312     report_metadata_oome(loader_data, word_size, type, mdtype, THREAD);
1313     assert(HAS_PENDING_EXCEPTION, "sanity");
1314     return NULL;
1315   }
1316 
1317   // Zero initialize.
1318   Copy::fill_to_words((HeapWord*)result, word_size, 0);
1319 
1320   return result;
1321 }
1322 
1323 void Metaspace::report_metadata_oome(ClassLoaderData* loader_data, size_t word_size, MetaspaceObj::Type type, MetadataType mdtype, TRAPS) {
1324   tracer()->report_metadata_oom(loader_data, word_size, type, mdtype);
1325 
1326   // If result is still null, we are out of memory.
1327   Log(gc, metaspace, freelist, oom) log;
1328   if (log.is_info()) {
1329     log.info("Metaspace (%s) allocation failed for size " SIZE_FORMAT,
1330              is_class_space_allocation(mdtype) ? "class" : "data", word_size);
1331     ResourceMark rm;
1332     if (log.is_debug()) {
1333       if (loader_data->metaspace_or_null() != NULL) {
1334         LogStream ls(log.debug());
1335         loader_data->print_value_on(&ls);
1336       }
1337     }
1338     LogStream ls(log.info());
1339     // In case of an OOM, log out a short but still useful report.
1340     MetaspaceUtils::print_basic_report(&ls, 0);
1341   }
1342 
1343   bool out_of_compressed_class_space = false;
1344   if (is_class_space_allocation(mdtype)) {
1345     ClassLoaderMetaspace* metaspace = loader_data->metaspace_non_null();
1346     out_of_compressed_class_space =
1347       MetaspaceUtils::committed_bytes(Metaspace::ClassType) +
1348       (metaspace->class_chunk_size(word_size) * BytesPerWord) >
1349       CompressedClassSpaceSize;
1350   }
1351 
1352   // -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support
1353   const char* space_string = out_of_compressed_class_space ?
1354     "Compressed class space" : "Metaspace";
1355 
1356   report_java_out_of_memory(space_string);
1357 
1358   if (JvmtiExport::should_post_resource_exhausted()) {
1359     JvmtiExport::post_resource_exhausted(
1360         JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR,
1361         space_string);
1362   }
1363 
1364   if (!is_init_completed()) {
1365     vm_exit_during_initialization("OutOfMemoryError", space_string);
1366   }
1367 
1368   if (out_of_compressed_class_space) {
1369     THROW_OOP(Universe::out_of_memory_error_class_metaspace());
1370   } else {
1371     THROW_OOP(Universe::out_of_memory_error_metaspace());
1372   }
1373 }
1374 
1375 const char* Metaspace::metadata_type_name(Metaspace::MetadataType mdtype) {
1376   switch (mdtype) {
1377     case Metaspace::ClassType: return "Class";
1378     case Metaspace::NonClassType: return "Metadata";
1379     default:
1380       assert(false, "Got bad mdtype: %d", (int) mdtype);
1381       return NULL;
1382   }
1383 }
1384 
1385 void Metaspace::purge(MetadataType mdtype) {
1386   get_space_list(mdtype)->purge(get_chunk_manager(mdtype));
1387 }
1388 
1389 void Metaspace::purge() {
1390   MutexLockerEx cl(MetaspaceExpand_lock,
1391                    Mutex::_no_safepoint_check_flag);
1392   purge(NonClassType);
1393   if (using_class_space()) {
1394     purge(ClassType);
1395   }
1396 }
1397 
1398 bool Metaspace::contains(const void* ptr) {
1399   if (MetaspaceShared::is_in_shared_metaspace(ptr)) {
1400     return true;
1401   }
1402   return contains_non_shared(ptr);
1403 }
1404 
1405 bool Metaspace::contains_non_shared(const void* ptr) {
1406   if (using_class_space() && get_space_list(ClassType)->contains(ptr)) {
1407      return true;
1408   }
1409 
1410   return get_space_list(NonClassType)->contains(ptr);
1411 }
1412 
1413 // ClassLoaderMetaspace
1414 
1415 ClassLoaderMetaspace::ClassLoaderMetaspace(Mutex* lock, Metaspace::MetaspaceType type)
1416   : _space_type(type)
1417   , _lock(lock)
1418   , _vsm(NULL)
1419   , _class_vsm(NULL)
1420 {
1421   initialize(lock, type);
1422 }
1423 
1424 ClassLoaderMetaspace::~ClassLoaderMetaspace() {
1425   Metaspace::assert_not_frozen();
1426   DEBUG_ONLY(Atomic::inc(&g_internal_statistics.num_metaspace_deaths));
1427   delete _vsm;
1428   if (Metaspace::using_class_space()) {
1429     delete _class_vsm;
1430   }
1431 }
1432 
1433 void ClassLoaderMetaspace::initialize_first_chunk(Metaspace::MetaspaceType type, Metaspace::MetadataType mdtype) {
1434   Metachunk* chunk = get_initialization_chunk(type, mdtype);
1435   if (chunk != NULL) {
1436     // Add to this manager's list of chunks in use and make it the current_chunk().
1437     get_space_manager(mdtype)->add_chunk(chunk, true);
1438   }
1439 }
1440 
1441 Metachunk* ClassLoaderMetaspace::get_initialization_chunk(Metaspace::MetaspaceType type, Metaspace::MetadataType mdtype) {
1442   size_t chunk_word_size = get_space_manager(mdtype)->get_initial_chunk_size(type);
1443 
1444   // Get a chunk from the chunk freelist
1445   Metachunk* chunk = Metaspace::get_chunk_manager(mdtype)->chunk_freelist_allocate(chunk_word_size);
1446 
1447   if (chunk == NULL) {
1448     chunk = Metaspace::get_space_list(mdtype)->get_new_chunk(chunk_word_size,
1449                                                   get_space_manager(mdtype)->medium_chunk_bunch());
1450   }
1451 
1452   return chunk;
1453 }
1454 
1455 void ClassLoaderMetaspace::initialize(Mutex* lock, Metaspace::MetaspaceType type) {
1456   Metaspace::verify_global_initialization();
1457 
1458   DEBUG_ONLY(Atomic::inc(&g_internal_statistics.num_metaspace_births));
1459 
1460   // Allocate SpaceManager for metadata objects.
1461   _vsm = new SpaceManager(Metaspace::NonClassType, type, lock);
1462 
1463   if (Metaspace::using_class_space()) {
1464     // Allocate SpaceManager for classes.
1465     _class_vsm = new SpaceManager(Metaspace::ClassType, type, lock);
1466   }
1467 
1468   MutexLockerEx cl(MetaspaceExpand_lock, Mutex::_no_safepoint_check_flag);
1469 
1470   // Allocate chunk for metadata objects
1471   initialize_first_chunk(type, Metaspace::NonClassType);
1472 
1473   // Allocate chunk for class metadata objects
1474   if (Metaspace::using_class_space()) {
1475     initialize_first_chunk(type, Metaspace::ClassType);
1476   }
1477 }
1478 
1479 MetaWord* ClassLoaderMetaspace::allocate(size_t word_size, Metaspace::MetadataType mdtype) {
1480   Metaspace::assert_not_frozen();
1481 
1482   DEBUG_ONLY(Atomic::inc(&g_internal_statistics.num_allocs));
1483 
1484   // Don't use class_vsm() unless UseCompressedClassPointers is true.
1485   if (Metaspace::is_class_space_allocation(mdtype)) {
1486     return  class_vsm()->allocate(word_size);
1487   } else {
1488     return  vsm()->allocate(word_size);
1489   }
1490 }
1491 
1492 MetaWord* ClassLoaderMetaspace::expand_and_allocate(size_t word_size, Metaspace::MetadataType mdtype) {
1493   Metaspace::assert_not_frozen();
1494   size_t delta_bytes = MetaspaceGC::delta_capacity_until_GC(word_size * BytesPerWord);
1495   assert(delta_bytes > 0, "Must be");
1496 
1497   size_t before = 0;
1498   size_t after = 0;
1499   bool can_retry = true;
1500   MetaWord* res;
1501   bool incremented;
1502 
1503   // Each thread increments the HWM at most once. Even if the thread fails to increment
1504   // the HWM, an allocation is still attempted. This is because another thread must then
1505   // have incremented the HWM and therefore the allocation might still succeed.
1506   do {
1507     incremented = MetaspaceGC::inc_capacity_until_GC(delta_bytes, &after, &before, &can_retry);
1508     res = allocate(word_size, mdtype);
1509   } while (!incremented && res == NULL && can_retry);
1510 
1511   if (incremented) {
1512     Metaspace::tracer()->report_gc_threshold(before, after,
1513                                   MetaspaceGCThresholdUpdater::ExpandAndAllocate);
1514     log_trace(gc, metaspace)("Increase capacity to GC from " SIZE_FORMAT " to " SIZE_FORMAT, before, after);
1515   }
1516 
1517   return res;
1518 }
1519 
1520 size_t ClassLoaderMetaspace::allocated_blocks_bytes() const {
1521   return (vsm()->used_words() +
1522       (Metaspace::using_class_space() ? class_vsm()->used_words() : 0)) * BytesPerWord;
1523 }
1524 
1525 size_t ClassLoaderMetaspace::allocated_chunks_bytes() const {
1526   return (vsm()->capacity_words() +
1527       (Metaspace::using_class_space() ? class_vsm()->capacity_words() : 0)) * BytesPerWord;
1528 }
1529 
1530 void ClassLoaderMetaspace::deallocate(MetaWord* ptr, size_t word_size, bool is_class) {
1531   Metaspace::assert_not_frozen();
1532   assert(!SafepointSynchronize::is_at_safepoint()
1533          || Thread::current()->is_VM_thread(), "should be the VM thread");
1534 
1535   DEBUG_ONLY(Atomic::inc(&g_internal_statistics.num_external_deallocs));
1536 
1537   MutexLockerEx ml(vsm()->lock(), Mutex::_no_safepoint_check_flag);
1538 
1539   if (is_class && Metaspace::using_class_space()) {
1540     class_vsm()->deallocate(ptr, word_size);
1541   } else {
1542     vsm()->deallocate(ptr, word_size);
1543   }
1544 }
1545 
1546 size_t ClassLoaderMetaspace::class_chunk_size(size_t word_size) {
1547   assert(Metaspace::using_class_space(), "Has to use class space");
1548   return class_vsm()->calc_chunk_size(word_size);
1549 }
1550 
1551 void ClassLoaderMetaspace::print_on(outputStream* out) const {
1552   // Print both class virtual space counts and metaspace.
1553   if (Verbose) {
1554     vsm()->print_on(out);
1555     if (Metaspace::using_class_space()) {
1556       class_vsm()->print_on(out);
1557     }
1558   }
1559 }
1560 
1561 void ClassLoaderMetaspace::verify() {
1562   vsm()->verify();
1563   if (Metaspace::using_class_space()) {
1564     class_vsm()->verify();
1565   }
1566 }
1567 
1568 void ClassLoaderMetaspace::add_to_statistics_locked(ClassLoaderMetaspaceStatistics* out) const {
1569   assert_lock_strong(lock());
1570   vsm()->add_to_statistics_locked(&out->nonclass_sm_stats());
1571   if (Metaspace::using_class_space()) {
1572     class_vsm()->add_to_statistics_locked(&out->class_sm_stats());
1573   }
1574 }
1575 
1576 void ClassLoaderMetaspace::add_to_statistics(ClassLoaderMetaspaceStatistics* out) const {
1577   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
1578   add_to_statistics_locked(out);
1579 }
1580 
1581 /////////////// Unit tests ///////////////
1582 
1583 #ifndef PRODUCT
1584 
1585 class TestMetaspaceUtilsTest : AllStatic {
1586  public:
1587   static void test_reserved() {
1588     size_t reserved = MetaspaceUtils::reserved_bytes();
1589 
1590     assert(reserved > 0, "assert");
1591 
1592     size_t committed  = MetaspaceUtils::committed_bytes();
1593     assert(committed <= reserved, "assert");
1594 
1595     size_t reserved_metadata = MetaspaceUtils::reserved_bytes(Metaspace::NonClassType);
1596     assert(reserved_metadata > 0, "assert");
1597     assert(reserved_metadata <= reserved, "assert");
1598 
1599     if (UseCompressedClassPointers) {
1600       size_t reserved_class    = MetaspaceUtils::reserved_bytes(Metaspace::ClassType);
1601       assert(reserved_class > 0, "assert");
1602       assert(reserved_class < reserved, "assert");
1603     }
1604   }
1605 
1606   static void test_committed() {
1607     size_t committed = MetaspaceUtils::committed_bytes();
1608 
1609     assert(committed > 0, "assert");
1610 
1611     size_t reserved  = MetaspaceUtils::reserved_bytes();
1612     assert(committed <= reserved, "assert");
1613 
1614     size_t committed_metadata = MetaspaceUtils::committed_bytes(Metaspace::NonClassType);
1615     assert(committed_metadata > 0, "assert");
1616     assert(committed_metadata <= committed, "assert");
1617 
1618     if (UseCompressedClassPointers) {
1619       size_t committed_class    = MetaspaceUtils::committed_bytes(Metaspace::ClassType);
1620       assert(committed_class > 0, "assert");
1621       assert(committed_class < committed, "assert");
1622     }
1623   }
1624 
1625   static void test_virtual_space_list_large_chunk() {
1626     VirtualSpaceList* vs_list = new VirtualSpaceList(os::vm_allocation_granularity());
1627     MutexLockerEx cl(MetaspaceExpand_lock, Mutex::_no_safepoint_check_flag);
1628     // A size larger than VirtualSpaceSize (256k) and add one page to make it _not_ be
1629     // vm_allocation_granularity aligned on Windows.
1630     size_t large_size = (size_t)(2*256*K + (os::vm_page_size()/BytesPerWord));
1631     large_size += (os::vm_page_size()/BytesPerWord);
1632     vs_list->get_new_chunk(large_size, 0);
1633   }
1634 
1635   static void test() {
1636     test_reserved();
1637     test_committed();
1638     test_virtual_space_list_large_chunk();
1639   }
1640 };
1641 
1642 void TestMetaspaceUtils_test() {
1643   TestMetaspaceUtilsTest::test();
1644 }
1645 
1646 #endif // !PRODUCT
1647 
1648 struct chunkmanager_statistics_t {
1649   int num_specialized_chunks;
1650   int num_small_chunks;
1651   int num_medium_chunks;
1652   int num_humongous_chunks;
1653 };
1654 
1655 extern void test_metaspace_retrieve_chunkmanager_statistics(Metaspace::MetadataType mdType, chunkmanager_statistics_t* out) {
1656   ChunkManager* const chunk_manager = Metaspace::get_chunk_manager(mdType);
1657   ChunkManagerStatistics stat;
1658   chunk_manager->collect_statistics(&stat);
1659   out->num_specialized_chunks = (int)stat.chunk_stats(SpecializedIndex).num();
1660   out->num_small_chunks = (int)stat.chunk_stats(SmallIndex).num();
1661   out->num_medium_chunks = (int)stat.chunk_stats(MediumIndex).num();
1662   out->num_humongous_chunks = (int)stat.chunk_stats(HumongousIndex).num();
1663 }
1664 
1665 struct chunk_geometry_t {
1666   size_t specialized_chunk_word_size;
1667   size_t small_chunk_word_size;
1668   size_t medium_chunk_word_size;
1669 };
1670 
1671 extern void test_metaspace_retrieve_chunk_geometry(Metaspace::MetadataType mdType, chunk_geometry_t* out) {
1672   if (mdType == Metaspace::NonClassType) {
1673     out->specialized_chunk_word_size = SpecializedChunk;
1674     out->small_chunk_word_size = SmallChunk;
1675     out->medium_chunk_word_size = MediumChunk;
1676   } else {
1677     out->specialized_chunk_word_size = ClassSpecializedChunk;
1678     out->small_chunk_word_size = ClassSmallChunk;
1679     out->medium_chunk_word_size = ClassMediumChunk;
1680   }
1681 }