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 #ifndef SHARE_MEMORY_METASPACE_HPP
  25 #define SHARE_MEMORY_METASPACE_HPP
  26 
  27 #include "memory/allocation.hpp"
  28 #include "memory/memRegion.hpp"
  29 #include "memory/metaspaceChunkFreeListSummary.hpp"
  30 #include "memory/virtualspace.hpp"
  31 #include "memory/metaspace/metaspaceSizesSnapshot.hpp"
  32 #include "runtime/globals.hpp"
  33 #include "utilities/exceptions.hpp"
  34 
  35 // Metaspace
  36 //
  37 // Metaspaces are Arenas for the VM's metadata.
  38 // They are allocated one per class loader object, and one for the null
  39 // bootstrap class loader
  40 //
  41 //    block X ---+       +-------------------+
  42 //               |       |  Virtualspace     |
  43 //               |       |                   |
  44 //               |       |                   |
  45 //               |       |-------------------|
  46 //               |       || Chunk            |
  47 //               |       ||                  |
  48 //               |       ||----------        |
  49 //               +------>||| block 0 |       |
  50 //                       ||----------        |
  51 //                       ||| block 1 |       |
  52 //                       ||----------        |
  53 //                       ||                  |
  54 //                       |-------------------|
  55 //                       |                   |
  56 //                       |                   |
  57 //                       +-------------------+
  58 //
  59 
  60 class ClassLoaderData;
  61 class MetaspaceTracer;
  62 class Mutex;
  63 class outputStream;
  64 
  65 class CollectedHeap;
  66 
  67 namespace metaspace {
  68   class ChunkManager;
  69   class ClassLoaderMetaspaceStatistics;
  70   class Metablock;
  71   class Metachunk;
  72   class PrintCLDMetaspaceInfoClosure;
  73   class SpaceManager;
  74   class VirtualSpaceList;
  75   class VirtualSpaceNode;
  76 }
  77 
  78 // Metaspaces each have a  SpaceManager and allocations
  79 // are done by the SpaceManager.  Allocations are done
  80 // out of the current Metachunk.  When the current Metachunk
  81 // is exhausted, the SpaceManager gets a new one from
  82 // the current VirtualSpace.  When the VirtualSpace is exhausted
  83 // the SpaceManager gets a new one.  The SpaceManager
  84 // also manages freelists of available Chunks.
  85 //
  86 // Currently the space manager maintains the list of
  87 // virtual spaces and the list of chunks in use.  Its
  88 // allocate() method returns a block for use as a
  89 // quantum of metadata.
  90 
  91 // Namespace for important central static functions
  92 // (auxiliary stuff goes into MetaspaceUtils)
  93 class Metaspace : public AllStatic {
  94 
  95   friend class MetaspaceShared;
  96 
  97  public:
  98   enum MetadataType {
  99     ClassType,
 100     NonClassType,
 101     MetadataTypeCount
 102   };
 103   enum MetaspaceType {
 104     ZeroMetaspaceType = 0,
 105     StandardMetaspaceType = ZeroMetaspaceType,
 106     BootMetaspaceType = StandardMetaspaceType + 1,
 107     ShortLivedMetaspaceType = BootMetaspaceType + 1,
 108     ReflectionMetaspaceType = ShortLivedMetaspaceType + 1,
 109     MetaspaceTypeCount
 110   };
 111 
 112  private:
 113 
 114   // Align up the word size to the allocation word size
 115   static size_t align_word_size_up(size_t);
 116 
 117   // Aligned size of the metaspace.
 118   static size_t _compressed_class_space_size;
 119 
 120   static size_t compressed_class_space_size() {
 121     return _compressed_class_space_size;
 122   }
 123 
 124   static void set_compressed_class_space_size(size_t size) {
 125     _compressed_class_space_size = size;
 126   }
 127 
 128   static size_t _first_chunk_word_size;
 129   static size_t _first_class_chunk_word_size;
 130 
 131   static size_t _commit_alignment;
 132   static size_t _reserve_alignment;
 133   DEBUG_ONLY(static bool   _frozen;)
 134 
 135   // Virtual Space lists for both classes and other metadata
 136   static metaspace::VirtualSpaceList* _space_list;
 137   static metaspace::VirtualSpaceList* _class_space_list;
 138 
 139   static metaspace::ChunkManager* _chunk_manager_metadata;
 140   static metaspace::ChunkManager* _chunk_manager_class;
 141 
 142   static const MetaspaceTracer* _tracer;
 143 
 144   static bool _initialized;
 145 
 146  public:
 147   static metaspace::VirtualSpaceList* space_list()       { return _space_list; }
 148   static metaspace::VirtualSpaceList* class_space_list() { return _class_space_list; }
 149   static metaspace::VirtualSpaceList* get_space_list(MetadataType mdtype) {
 150     assert(mdtype != MetadataTypeCount, "MetadaTypeCount can't be used as mdtype");
 151     return mdtype == ClassType ? class_space_list() : space_list();
 152   }
 153 
 154   static metaspace::ChunkManager* chunk_manager_metadata() { return _chunk_manager_metadata; }
 155   static metaspace::ChunkManager* chunk_manager_class()    { return _chunk_manager_class; }
 156   static metaspace::ChunkManager* get_chunk_manager(MetadataType mdtype) {
 157     assert(mdtype != MetadataTypeCount, "MetadaTypeCount can't be used as mdtype");
 158     return mdtype == ClassType ? chunk_manager_class() : chunk_manager_metadata();
 159   }
 160 
 161   // convenience function
 162   static metaspace::ChunkManager* get_chunk_manager(bool is_class) {
 163     return is_class ? chunk_manager_class() : chunk_manager_metadata();
 164   }
 165 
 166   static const MetaspaceTracer* tracer() { return _tracer; }
 167   static void freeze() {
 168     assert(DumpSharedSpaces, "sanity");
 169     DEBUG_ONLY(_frozen = true;)
 170   }
 171   static void assert_not_frozen() {
 172     assert(!_frozen, "sanity");
 173   }
 174 #ifdef _LP64
 175   static void allocate_metaspace_compressed_klass_ptrs(ReservedSpace metaspace_rs, char* requested_addr, address cds_base);
 176 #endif
 177 
 178  private:
 179 
 180 #ifdef _LP64
 181   static void set_narrow_klass_base_and_shift(ReservedSpace metaspace_rs, address cds_base);
 182 
 183   static void initialize_class_space(ReservedSpace rs);
 184 #endif
 185 
 186  public:
 187 
 188   static void ergo_initialize();
 189   static void global_initialize();
 190   static void post_initialize();
 191 
 192   static void verify_global_initialization();
 193 
 194   static size_t first_chunk_word_size() { return _first_chunk_word_size; }
 195   static size_t first_class_chunk_word_size() { return _first_class_chunk_word_size; }
 196 
 197   static size_t reserve_alignment()       { return _reserve_alignment; }
 198   static size_t reserve_alignment_words() { return _reserve_alignment / BytesPerWord; }
 199   static size_t commit_alignment()        { return _commit_alignment; }
 200   static size_t commit_alignment_words()  { return _commit_alignment / BytesPerWord; }
 201 
 202   static MetaWord* allocate(ClassLoaderData* loader_data, size_t word_size,
 203                             MetaspaceObj::Type type, TRAPS);
 204 
 205   static bool contains(const void* ptr);
 206   static bool contains_non_shared(const void* ptr);
 207 
 208   // Free empty virtualspaces
 209   static void purge(MetadataType mdtype);
 210   static void purge();
 211 
 212   static void report_metadata_oome(ClassLoaderData* loader_data, size_t word_size,
 213                                    MetaspaceObj::Type type, MetadataType mdtype, TRAPS);
 214 
 215   static const char* metadata_type_name(Metaspace::MetadataType mdtype);
 216 
 217   static void print_compressed_class_space(outputStream* st, const char* requested_addr = 0) NOT_LP64({});
 218 
 219   // Return TRUE only if UseCompressedClassPointers is True.
 220   static bool using_class_space() {
 221     return NOT_LP64(false) LP64_ONLY(UseCompressedClassPointers);
 222   }
 223 
 224   static bool is_class_space_allocation(MetadataType mdType) {
 225     return mdType == ClassType && using_class_space();
 226   }
 227 
 228   static bool initialized() { return _initialized; }
 229 
 230 };
 231 
 232 // Manages the metaspace portion belonging to a class loader
 233 class ClassLoaderMetaspace : public CHeapObj<mtClass> {
 234   friend class CollectedHeap; // For expand_and_allocate()
 235   friend class ZCollectedHeap; // For expand_and_allocate()
 236   friend class ShenandoahHeap; // For expand_and_allocate()
 237   friend class Metaspace;
 238   friend class MetaspaceUtils;
 239   friend class metaspace::PrintCLDMetaspaceInfoClosure;
 240   friend class VM_CollectForMetadataAllocation; // For expand_and_allocate()
 241 
 242  private:
 243 
 244   void initialize(Mutex* lock, Metaspace::MetaspaceType type);
 245 
 246   // Initialize the first chunk for a Metaspace.  Used for
 247   // special cases such as the boot class loader, reflection
 248   // class loader and hidden class loader.
 249   void initialize_first_chunk(Metaspace::MetaspaceType type, Metaspace::MetadataType mdtype);
 250   metaspace::Metachunk* get_initialization_chunk(Metaspace::MetaspaceType type, Metaspace::MetadataType mdtype);
 251 
 252   const Metaspace::MetaspaceType _space_type;
 253   Mutex* const  _lock;
 254   metaspace::SpaceManager* _vsm;
 255   metaspace::SpaceManager* _class_vsm;
 256 
 257   metaspace::SpaceManager* vsm() const { return _vsm; }
 258   metaspace::SpaceManager* class_vsm() const { return _class_vsm; }
 259   metaspace::SpaceManager* get_space_manager(Metaspace::MetadataType mdtype) {
 260     assert(mdtype != Metaspace::MetadataTypeCount, "MetadaTypeCount can't be used as mdtype");
 261     return mdtype == Metaspace::ClassType ? class_vsm() : vsm();
 262   }
 263 
 264   Mutex* lock() const { return _lock; }
 265 
 266   MetaWord* expand_and_allocate(size_t size, Metaspace::MetadataType mdtype);
 267 
 268   size_t class_chunk_size(size_t word_size);
 269 
 270   // Adds to the given statistic object. Must be locked with CLD metaspace lock.
 271   void add_to_statistics_locked(metaspace::ClassLoaderMetaspaceStatistics* out) const;
 272 
 273   Metaspace::MetaspaceType space_type() const { return _space_type; }
 274 
 275  public:
 276 
 277   ClassLoaderMetaspace(Mutex* lock, Metaspace::MetaspaceType type);
 278   ~ClassLoaderMetaspace();
 279 
 280   // Allocate space for metadata of type mdtype. This is space
 281   // within a Metachunk and is used by
 282   //   allocate(ClassLoaderData*, size_t, bool, MetadataType, TRAPS)
 283   MetaWord* allocate(size_t word_size, Metaspace::MetadataType mdtype);
 284 
 285   size_t allocated_blocks_bytes() const;
 286   size_t allocated_chunks_bytes() const;
 287 
 288   void deallocate(MetaWord* ptr, size_t byte_size, bool is_class);
 289 
 290   void print_on(outputStream* st) const;
 291   // Debugging support
 292   void verify();
 293 
 294   // Adds to the given statistic object. Will lock with CLD metaspace lock.
 295   void add_to_statistics(metaspace::ClassLoaderMetaspaceStatistics* out) const;
 296 
 297 }; // ClassLoaderMetaspace
 298 
 299 class MetaspaceUtils : AllStatic {
 300 
 301   // Spacemanager updates running counters.
 302   friend class metaspace::SpaceManager;
 303 
 304   // Special access for error reporting (checks without locks).
 305   friend class oopDesc;
 306   friend class Klass;
 307 
 308   // Running counters for statistics concerning in-use chunks.
 309   // Note: capacity = used + free + waste + overhead. Note that we do not
 310   // count free and waste. Their sum can be deduces from the three other values.
 311   // For more details, one should call print_report() from within a safe point.
 312   static size_t _capacity_words [Metaspace:: MetadataTypeCount];
 313   static size_t _overhead_words [Metaspace:: MetadataTypeCount];
 314   static volatile size_t _used_words [Metaspace:: MetadataTypeCount];
 315 
 316   // Atomically decrement or increment in-use statistic counters
 317   static void dec_capacity(Metaspace::MetadataType mdtype, size_t words);
 318   static void inc_capacity(Metaspace::MetadataType mdtype, size_t words);
 319   static void dec_used(Metaspace::MetadataType mdtype, size_t words);
 320   static void inc_used(Metaspace::MetadataType mdtype, size_t words);
 321   static void dec_overhead(Metaspace::MetadataType mdtype, size_t words);
 322   static void inc_overhead(Metaspace::MetadataType mdtype, size_t words);
 323 
 324 
 325   // Getters for the in-use counters.
 326   static size_t capacity_words(Metaspace::MetadataType mdtype)        { return _capacity_words[mdtype]; }
 327   static size_t used_words(Metaspace::MetadataType mdtype)            { return _used_words[mdtype]; }
 328   static size_t overhead_words(Metaspace::MetadataType mdtype)        { return _overhead_words[mdtype]; }
 329 
 330   static size_t free_chunks_total_words(Metaspace::MetadataType mdtype);
 331 
 332   // Helper for print_xx_report.
 333   static void print_vs(outputStream* out, size_t scale);
 334 
 335 public:
 336 
 337   // Collect used metaspace statistics. This involves walking the CLDG. The resulting
 338   // output will be the accumulated values for all live metaspaces.
 339   // Note: method does not do any locking.
 340   static void collect_statistics(metaspace::ClassLoaderMetaspaceStatistics* out);
 341 
 342   // Used by MetaspaceCounters
 343   static size_t free_chunks_total_words();
 344   static size_t free_chunks_total_bytes();
 345   static size_t free_chunks_total_bytes(Metaspace::MetadataType mdtype);
 346 
 347   static size_t capacity_words() {
 348     return capacity_words(Metaspace::NonClassType) +
 349            capacity_words(Metaspace::ClassType);
 350   }
 351   static size_t capacity_bytes(Metaspace::MetadataType mdtype) {
 352     return capacity_words(mdtype) * BytesPerWord;
 353   }
 354   static size_t capacity_bytes() {
 355     return capacity_words() * BytesPerWord;
 356   }
 357 
 358   static size_t used_words() {
 359     return used_words(Metaspace::NonClassType) +
 360            used_words(Metaspace::ClassType);
 361   }
 362   static size_t used_bytes(Metaspace::MetadataType mdtype) {
 363     return used_words(mdtype) * BytesPerWord;
 364   }
 365   static size_t used_bytes() {
 366     return used_words() * BytesPerWord;
 367   }
 368 
 369   // Space committed but yet unclaimed by any class loader.
 370   static size_t free_in_vs_bytes();
 371   static size_t free_in_vs_bytes(Metaspace::MetadataType mdtype);
 372 
 373   static size_t reserved_bytes(Metaspace::MetadataType mdtype);
 374   static size_t reserved_bytes() {
 375     return reserved_bytes(Metaspace::ClassType) +
 376            reserved_bytes(Metaspace::NonClassType);
 377   }
 378 
 379   static size_t committed_bytes(Metaspace::MetadataType mdtype);
 380   static size_t committed_bytes() {
 381     return committed_bytes(Metaspace::ClassType) +
 382            committed_bytes(Metaspace::NonClassType);
 383   }
 384 
 385   static size_t min_chunk_size_words();
 386 
 387   // Flags for print_report().
 388   enum ReportFlag {
 389     // Show usage by class loader.
 390     rf_show_loaders                 = (1 << 0),
 391     // Breaks report down by chunk type (small, medium, ...).
 392     rf_break_down_by_chunktype      = (1 << 1),
 393     // Breaks report down by space type (hidden, reflection, ...).
 394     rf_break_down_by_spacetype      = (1 << 2),
 395     // Print details about the underlying virtual spaces.
 396     rf_show_vslist                  = (1 << 3),
 397     // Print metaspace map.
 398     rf_show_vsmap                   = (1 << 4),
 399     // If show_loaders: show loaded classes for each loader.
 400     rf_show_classes                 = (1 << 5)
 401   };
 402 
 403   // This will print out a basic metaspace usage report but
 404   // unlike print_report() is guaranteed not to lock or to walk the CLDG.
 405   static void print_basic_report(outputStream* st, size_t scale);
 406 
 407   // Prints a report about the current metaspace state.
 408   // Optional parts can be enabled via flags.
 409   // Function will walk the CLDG and will lock the expand lock; if that is not
 410   // convenient, use print_basic_report() instead.
 411   static void print_report(outputStream* out, size_t scale = 0, int flags = 0);
 412 
 413   static bool has_chunk_free_list(Metaspace::MetadataType mdtype);
 414   static MetaspaceChunkFreeListSummary chunk_free_list_summary(Metaspace::MetadataType mdtype);
 415 
 416   // Log change in used metadata.
 417   static void print_metaspace_change(const metaspace::MetaspaceSizesSnapshot& pre_meta_values);
 418   static void print_on(outputStream * out);
 419 
 420   // Prints an ASCII representation of the given space.
 421   static void print_metaspace_map(outputStream* out, Metaspace::MetadataType mdtype);
 422 
 423   static void dump(outputStream* out);
 424   static void verify_free_chunks();
 425   // Check internal counters (capacity, used).
 426   static void verify_metrics();
 427 };
 428 
 429 // Metaspace are deallocated when their class loader are GC'ed.
 430 // This class implements a policy for inducing GC's to recover
 431 // Metaspaces.
 432 
 433 class MetaspaceGC : AllStatic {
 434 
 435   // The current high-water-mark for inducing a GC.
 436   // When committed memory of all metaspaces reaches this value,
 437   // a GC is induced and the value is increased. Size is in bytes.
 438   static volatile size_t _capacity_until_GC;
 439   static uint _shrink_factor;
 440 
 441   static size_t shrink_factor() { return _shrink_factor; }
 442   void set_shrink_factor(uint v) { _shrink_factor = v; }
 443 
 444  public:
 445 
 446   static void initialize();
 447   static void post_initialize();
 448 
 449   static size_t capacity_until_GC();
 450   static bool inc_capacity_until_GC(size_t v,
 451                                     size_t* new_cap_until_GC = NULL,
 452                                     size_t* old_cap_until_GC = NULL,
 453                                     bool* can_retry = NULL);
 454   static size_t dec_capacity_until_GC(size_t v);
 455 
 456   // The amount to increase the high-water-mark (_capacity_until_GC)
 457   static size_t delta_capacity_until_GC(size_t bytes);
 458 
 459   // Tells if we have can expand metaspace without hitting set limits.
 460   static bool can_expand(size_t words, bool is_class);
 461 
 462   // Returns amount that we can expand without hitting a GC,
 463   // measured in words.
 464   static size_t allowed_expansion();
 465 
 466   // Calculate the new high-water mark at which to induce
 467   // a GC.
 468   static void compute_new_size();
 469 };
 470 
 471 #endif // SHARE_MEMORY_METASPACE_HPP