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