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