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