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