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