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