1 /* 2 * Copyright (c) 2001, 2019, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #ifndef SHARE_GC_SHARED_COLLECTEDHEAP_HPP 26 #define SHARE_GC_SHARED_COLLECTEDHEAP_HPP 27 28 #include "gc/shared/gcCause.hpp" 29 #include "gc/shared/gcWhen.hpp" 30 #include "gc/shared/verifyOption.hpp" 31 #include "memory/allocation.hpp" 32 #include "memory/metaspace/metaspaceEnums.hpp" 33 #include "runtime/handles.hpp" 34 #include "runtime/perfData.hpp" 35 #include "runtime/safepoint.hpp" 36 #include "services/memoryUsage.hpp" 37 #include "utilities/debug.hpp" 38 #include "utilities/events.hpp" 39 #include "utilities/formatBuffer.hpp" 40 #include "utilities/growableArray.hpp" 41 42 // A "CollectedHeap" is an implementation of a java heap for HotSpot. This 43 // is an abstract class: there may be many different kinds of heaps. This 44 // class defines the functions that a heap must implement, and contains 45 // infrastructure common to all heaps. 46 47 class AdaptiveSizePolicy; 48 class BarrierSet; 49 class GCHeapSummary; 50 class GCTimer; 51 class GCTracer; 52 class GCMemoryManager; 53 class MemoryPool; 54 class MetaspaceSummary; 55 class SoftRefPolicy; 56 class Thread; 57 class ThreadClosure; 58 class VirtualSpaceSummary; 59 class WorkGang; 60 class nmethod; 61 62 class GCMessage : public FormatBuffer<1024> { 63 public: 64 bool is_before; 65 66 public: 67 GCMessage() {} 68 }; 69 70 class CollectedHeap; 71 72 class GCHeapLog : public EventLogBase<GCMessage> { 73 private: 74 void log_heap(CollectedHeap* heap, bool before); 75 76 public: 77 GCHeapLog() : EventLogBase<GCMessage>("GC Heap History", "gc") {} 78 79 void log_heap_before(CollectedHeap* heap) { 80 log_heap(heap, true); 81 } 82 void log_heap_after(CollectedHeap* heap) { 83 log_heap(heap, false); 84 } 85 }; 86 87 // 88 // CollectedHeap 89 // GenCollectedHeap 90 // SerialHeap 91 // CMSHeap 92 // G1CollectedHeap 93 // ParallelScavengeHeap 94 // ShenandoahHeap 95 // ZCollectedHeap 96 // 97 class CollectedHeap : public CHeapObj<mtInternal> { 98 friend class VMStructs; 99 friend class JVMCIVMStructs; 100 friend class IsGCActiveMark; // Block structured external access to _is_gc_active 101 friend class MemAllocator; 102 103 private: 104 GCHeapLog* _gc_heap_log; 105 106 MemRegion _reserved; 107 108 protected: 109 bool _is_gc_active; 110 111 // Used for filler objects (static, but initialized in ctor). 112 static size_t _filler_array_max_size; 113 114 unsigned int _total_collections; // ... started 115 unsigned int _total_full_collections; // ... started 116 NOT_PRODUCT(volatile size_t _promotion_failure_alot_count;) 117 NOT_PRODUCT(volatile size_t _promotion_failure_alot_gc_number;) 118 119 // Reason for current garbage collection. Should be set to 120 // a value reflecting no collection between collections. 121 GCCause::Cause _gc_cause; 122 GCCause::Cause _gc_lastcause; 123 PerfStringVariable* _perf_gc_cause; 124 PerfStringVariable* _perf_gc_lastcause; 125 126 // Constructor 127 CollectedHeap(); 128 129 // Create a new tlab. All TLAB allocations must go through this. 130 // To allow more flexible TLAB allocations min_size specifies 131 // the minimum size needed, while requested_size is the requested 132 // size based on ergonomics. The actually allocated size will be 133 // returned in actual_size. 134 virtual HeapWord* allocate_new_tlab(size_t min_size, 135 size_t requested_size, 136 size_t* actual_size); 137 138 // Reinitialize tlabs before resuming mutators. 139 virtual void resize_all_tlabs(); 140 141 // Raw memory allocation facilities 142 // The obj and array allocate methods are covers for these methods. 143 // mem_allocate() should never be 144 // called to allocate TLABs, only individual objects. 145 virtual HeapWord* mem_allocate(size_t size, 146 bool* gc_overhead_limit_was_exceeded) = 0; 147 148 // Filler object utilities. 149 static inline size_t filler_array_hdr_size(); 150 static inline size_t filler_array_min_size(); 151 152 DEBUG_ONLY(static void fill_args_check(HeapWord* start, size_t words);) 153 DEBUG_ONLY(static void zap_filler_array(HeapWord* start, size_t words, bool zap = true);) 154 155 // Fill with a single array; caller must ensure filler_array_min_size() <= 156 // words <= filler_array_max_size(). 157 static inline void fill_with_array(HeapWord* start, size_t words, bool zap = true); 158 159 // Fill with a single object (either an int array or a java.lang.Object). 160 static inline void fill_with_object_impl(HeapWord* start, size_t words, bool zap = true); 161 162 virtual void trace_heap(GCWhen::Type when, const GCTracer* tracer); 163 164 // Verification functions 165 virtual void check_for_non_bad_heap_word_value(HeapWord* addr, size_t size) 166 PRODUCT_RETURN; 167 debug_only(static void check_for_valid_allocation_state();) 168 169 public: 170 enum Name { 171 None, 172 Serial, 173 Parallel, 174 CMS, 175 G1, 176 Epsilon, 177 Z, 178 Shenandoah 179 }; 180 181 static inline size_t filler_array_max_size() { 182 return _filler_array_max_size; 183 } 184 185 virtual Name kind() const = 0; 186 187 virtual const char* name() const = 0; 188 189 /** 190 * Returns JNI error code JNI_ENOMEM if memory could not be allocated, 191 * and JNI_OK on success. 192 */ 193 virtual jint initialize() = 0; 194 195 // In many heaps, there will be a need to perform some initialization activities 196 // after the Universe is fully formed, but before general heap allocation is allowed. 197 // This is the correct place to place such initialization methods. 198 virtual void post_initialize(); 199 200 // Stop any onging concurrent work and prepare for exit. 201 virtual void stop() {} 202 203 // Stop and resume concurrent GC threads interfering with safepoint operations 204 virtual void safepoint_synchronize_begin() {} 205 virtual void safepoint_synchronize_end() {} 206 207 void initialize_reserved_region(HeapWord *start, HeapWord *end); 208 MemRegion reserved_region() const { return _reserved; } 209 address base() const { return (address)reserved_region().start(); } 210 211 virtual size_t capacity() const = 0; 212 virtual size_t used() const = 0; 213 214 // Returns unused capacity. 215 virtual size_t unused() const; 216 217 // Return "true" if the part of the heap that allocates Java 218 // objects has reached the maximal committed limit that it can 219 // reach, without a garbage collection. 220 virtual bool is_maximal_no_gc() const = 0; 221 222 // Support for java.lang.Runtime.maxMemory(): return the maximum amount of 223 // memory that the vm could make available for storing 'normal' java objects. 224 // This is based on the reserved address space, but should not include space 225 // that the vm uses internally for bookkeeping or temporary storage 226 // (e.g., in the case of the young gen, one of the survivor 227 // spaces). 228 virtual size_t max_capacity() const = 0; 229 230 // Returns "TRUE" if "p" points into the reserved area of the heap. 231 bool is_in_reserved(const void* p) const { 232 return _reserved.contains(p); 233 } 234 235 bool is_in_reserved_or_null(const void* p) const { 236 return p == NULL || is_in_reserved(p); 237 } 238 239 // Returns "TRUE" iff "p" points into the committed areas of the heap. 240 // This method can be expensive so avoid using it in performance critical 241 // code. 242 virtual bool is_in(const void* p) const = 0; 243 244 DEBUG_ONLY(bool is_in_or_null(const void* p) const { return p == NULL || is_in(p); }) 245 246 virtual uint32_t hash_oop(oop obj) const; 247 248 void set_gc_cause(GCCause::Cause v) { 249 if (UsePerfData) { 250 _gc_lastcause = _gc_cause; 251 _perf_gc_lastcause->set_value(GCCause::to_string(_gc_lastcause)); 252 _perf_gc_cause->set_value(GCCause::to_string(v)); 253 } 254 _gc_cause = v; 255 } 256 GCCause::Cause gc_cause() { return _gc_cause; } 257 258 virtual oop obj_allocate(Klass* klass, int size, TRAPS); 259 virtual oop array_allocate(Klass* klass, int size, int length, bool do_zero, TRAPS); 260 virtual oop class_allocate(Klass* klass, int size, TRAPS); 261 262 // Utilities for turning raw memory into filler objects. 263 // 264 // min_fill_size() is the smallest region that can be filled. 265 // fill_with_objects() can fill arbitrary-sized regions of the heap using 266 // multiple objects. fill_with_object() is for regions known to be smaller 267 // than the largest array of integers; it uses a single object to fill the 268 // region and has slightly less overhead. 269 static size_t min_fill_size() { 270 return size_t(align_object_size(oopDesc::header_size())); 271 } 272 273 static void fill_with_objects(HeapWord* start, size_t words, bool zap = true); 274 275 static void fill_with_object(HeapWord* start, size_t words, bool zap = true); 276 static void fill_with_object(MemRegion region, bool zap = true) { 277 fill_with_object(region.start(), region.word_size(), zap); 278 } 279 static void fill_with_object(HeapWord* start, HeapWord* end, bool zap = true) { 280 fill_with_object(start, pointer_delta(end, start), zap); 281 } 282 283 virtual void fill_with_dummy_object(HeapWord* start, HeapWord* end, bool zap); 284 virtual size_t min_dummy_object_size() const; 285 size_t tlab_alloc_reserve() const; 286 287 // Return the address "addr" aligned by "alignment_in_bytes" if such 288 // an address is below "end". Return NULL otherwise. 289 inline static HeapWord* align_allocation_or_fail(HeapWord* addr, 290 HeapWord* end, 291 unsigned short alignment_in_bytes); 292 293 // Some heaps may offer a contiguous region for shared non-blocking 294 // allocation, via inlined code (by exporting the address of the top and 295 // end fields defining the extent of the contiguous allocation region.) 296 297 // This function returns "true" iff the heap supports this kind of 298 // allocation. (Default is "no".) 299 virtual bool supports_inline_contig_alloc() const { 300 return false; 301 } 302 // These functions return the addresses of the fields that define the 303 // boundaries of the contiguous allocation area. (These fields should be 304 // physically near to one another.) 305 virtual HeapWord* volatile* top_addr() const { 306 guarantee(false, "inline contiguous allocation not supported"); 307 return NULL; 308 } 309 virtual HeapWord** end_addr() const { 310 guarantee(false, "inline contiguous allocation not supported"); 311 return NULL; 312 } 313 314 // Some heaps may be in an unparseable state at certain times between 315 // collections. This may be necessary for efficient implementation of 316 // certain allocation-related activities. Calling this function before 317 // attempting to parse a heap ensures that the heap is in a parsable 318 // state (provided other concurrent activity does not introduce 319 // unparsability). It is normally expected, therefore, that this 320 // method is invoked with the world stopped. 321 // NOTE: if you override this method, make sure you call 322 // super::ensure_parsability so that the non-generational 323 // part of the work gets done. See implementation of 324 // CollectedHeap::ensure_parsability and, for instance, 325 // that of GenCollectedHeap::ensure_parsability(). 326 // The argument "retire_tlabs" controls whether existing TLABs 327 // are merely filled or also retired, thus preventing further 328 // allocation from them and necessitating allocation of new TLABs. 329 virtual void ensure_parsability(bool retire_tlabs); 330 331 // Section on thread-local allocation buffers (TLABs) 332 // If the heap supports thread-local allocation buffers, it should override 333 // the following methods: 334 // Returns "true" iff the heap supports thread-local allocation buffers. 335 // The default is "no". 336 virtual bool supports_tlab_allocation() const = 0; 337 338 // The amount of space available for thread-local allocation buffers. 339 virtual size_t tlab_capacity(Thread *thr) const = 0; 340 341 // The amount of used space for thread-local allocation buffers for the given thread. 342 virtual size_t tlab_used(Thread *thr) const = 0; 343 344 virtual size_t max_tlab_size() const; 345 346 // An estimate of the maximum allocation that could be performed 347 // for thread-local allocation buffers without triggering any 348 // collection or expansion activity. 349 virtual size_t unsafe_max_tlab_alloc(Thread *thr) const { 350 guarantee(false, "thread-local allocation buffers not supported"); 351 return 0; 352 } 353 354 // Perform a collection of the heap; intended for use in implementing 355 // "System.gc". This probably implies as full a collection as the 356 // "CollectedHeap" supports. 357 virtual void collect(GCCause::Cause cause) = 0; 358 359 // Perform a full collection 360 virtual void do_full_collection(bool clear_all_soft_refs) = 0; 361 362 // This interface assumes that it's being called by the 363 // vm thread. It collects the heap assuming that the 364 // heap lock is already held and that we are executing in 365 // the context of the vm thread. 366 virtual void collect_as_vm_thread(GCCause::Cause cause); 367 368 virtual MetaWord* satisfy_failed_metadata_allocation(ClassLoaderData* loader_data, 369 size_t size, 370 metaspace::MetadataType mdtype); 371 372 // Returns "true" iff there is a stop-world GC in progress. (I assume 373 // that it should answer "false" for the concurrent part of a concurrent 374 // collector -- dld). 375 bool is_gc_active() const { return _is_gc_active; } 376 377 // Total number of GC collections (started) 378 unsigned int total_collections() const { return _total_collections; } 379 unsigned int total_full_collections() const { return _total_full_collections;} 380 381 // Increment total number of GC collections (started) 382 // Should be protected but used by PSMarkSweep - cleanup for 1.4.2 383 void increment_total_collections(bool full = false) { 384 _total_collections++; 385 if (full) { 386 increment_total_full_collections(); 387 } 388 } 389 390 void increment_total_full_collections() { _total_full_collections++; } 391 392 // Return the SoftRefPolicy for the heap; 393 virtual SoftRefPolicy* soft_ref_policy() = 0; 394 395 virtual MemoryUsage memory_usage(); 396 virtual GrowableArray<GCMemoryManager*> memory_managers() = 0; 397 virtual GrowableArray<MemoryPool*> memory_pools() = 0; 398 399 // Iterate over all objects, calling "cl.do_object" on each. 400 virtual void object_iterate(ObjectClosure* cl) = 0; 401 402 // Similar to object_iterate() except iterates only 403 // over live objects. 404 virtual void safe_object_iterate(ObjectClosure* cl) = 0; 405 406 // NOTE! There is no requirement that a collector implement these 407 // functions. 408 // 409 // A CollectedHeap is divided into a dense sequence of "blocks"; that is, 410 // each address in the (reserved) heap is a member of exactly 411 // one block. The defining characteristic of a block is that it is 412 // possible to find its size, and thus to progress forward to the next 413 // block. (Blocks may be of different sizes.) Thus, blocks may 414 // represent Java objects, or they might be free blocks in a 415 // free-list-based heap (or subheap), as long as the two kinds are 416 // distinguishable and the size of each is determinable. 417 418 // Returns the address of the start of the "block" that contains the 419 // address "addr". We say "blocks" instead of "object" since some heaps 420 // may not pack objects densely; a chunk may either be an object or a 421 // non-object. 422 virtual HeapWord* block_start(const void* addr) const = 0; 423 424 // Requires "addr" to be the start of a block, and returns "TRUE" iff 425 // the block is an object. 426 virtual bool block_is_obj(const HeapWord* addr) const = 0; 427 428 // Returns the longest time (in ms) that has elapsed since the last 429 // time that any part of the heap was examined by a garbage collection. 430 virtual jlong millis_since_last_gc() = 0; 431 432 // Perform any cleanup actions necessary before allowing a verification. 433 virtual void prepare_for_verify() = 0; 434 435 // Generate any dumps preceding or following a full gc 436 private: 437 void full_gc_dump(GCTimer* timer, bool before); 438 439 virtual void initialize_serviceability() = 0; 440 441 public: 442 void pre_full_gc_dump(GCTimer* timer); 443 void post_full_gc_dump(GCTimer* timer); 444 445 virtual VirtualSpaceSummary create_heap_space_summary(); 446 GCHeapSummary create_heap_summary(); 447 448 MetaspaceSummary create_metaspace_summary(); 449 450 // Print heap information on the given outputStream. 451 virtual void print_on(outputStream* st) const = 0; 452 // The default behavior is to call print_on() on tty. 453 virtual void print() const; 454 455 // Print more detailed heap information on the given 456 // outputStream. The default behavior is to call print_on(). It is 457 // up to each subclass to override it and add any additional output 458 // it needs. 459 virtual void print_extended_on(outputStream* st) const { 460 print_on(st); 461 } 462 463 virtual void print_on_error(outputStream* st) const; 464 465 // Print all GC threads (other than the VM thread) 466 // used by this heap. 467 virtual void print_gc_threads_on(outputStream* st) const = 0; 468 // The default behavior is to call print_gc_threads_on() on tty. 469 void print_gc_threads() { 470 print_gc_threads_on(tty); 471 } 472 // Iterator for all GC threads (other than VM thread) 473 virtual void gc_threads_do(ThreadClosure* tc) const = 0; 474 475 // Print any relevant tracing info that flags imply. 476 // Default implementation does nothing. 477 virtual void print_tracing_info() const = 0; 478 479 void print_heap_before_gc(); 480 void print_heap_after_gc(); 481 482 // Registering and unregistering an nmethod (compiled code) with the heap. 483 virtual void register_nmethod(nmethod* nm) = 0; 484 virtual void unregister_nmethod(nmethod* nm) = 0; 485 // Callback for when nmethod is about to be deleted. 486 virtual void flush_nmethod(nmethod* nm) = 0; 487 virtual void verify_nmethod(nmethod* nm) = 0; 488 489 void trace_heap_before_gc(const GCTracer* gc_tracer); 490 void trace_heap_after_gc(const GCTracer* gc_tracer); 491 492 // Heap verification 493 virtual void verify(VerifyOption option) = 0; 494 495 // Return true if concurrent phase control (via 496 // request_concurrent_phase_control) is supported by this collector. 497 // The default implementation returns false. 498 virtual bool supports_concurrent_phase_control() const; 499 500 // Request the collector enter the indicated concurrent phase, and 501 // wait until it does so. Supports WhiteBox testing. Only one 502 // request may be active at a time. Phases are designated by name; 503 // the set of names and their meaning is GC-specific. Once the 504 // requested phase has been reached, the collector will attempt to 505 // avoid transitioning to a new phase until a new request is made. 506 // [Note: A collector might not be able to remain in a given phase. 507 // For example, a full collection might cancel an in-progress 508 // concurrent collection.] 509 // 510 // Returns true when the phase is reached. Returns false for an 511 // unknown phase. The default implementation returns false. 512 virtual bool request_concurrent_phase(const char* phase); 513 514 // Provides a thread pool to SafepointSynchronize to use 515 // for parallel safepoint cleanup. 516 // GCs that use a GC worker thread pool may want to share 517 // it for use during safepoint cleanup. This is only possible 518 // if the GC can pause and resume concurrent work (e.g. G1 519 // concurrent marking) for an intermittent non-GC safepoint. 520 // If this method returns NULL, SafepointSynchronize will 521 // perform cleanup tasks serially in the VMThread. 522 virtual WorkGang* get_safepoint_workers() { return NULL; } 523 524 // Support for object pinning. This is used by JNI Get*Critical() 525 // and Release*Critical() family of functions. If supported, the GC 526 // must guarantee that pinned objects never move. 527 virtual bool supports_object_pinning() const; 528 virtual oop pin_object(JavaThread* thread, oop obj); 529 virtual void unpin_object(JavaThread* thread, oop obj); 530 531 // Deduplicate the string, iff the GC supports string deduplication. 532 virtual void deduplicate_string(oop str); 533 534 virtual bool is_oop(oop object) const; 535 536 virtual size_t obj_size(oop obj) const; 537 538 // Non product verification and debugging. 539 #ifndef PRODUCT 540 // Support for PromotionFailureALot. Return true if it's time to cause a 541 // promotion failure. The no-argument version uses 542 // this->_promotion_failure_alot_count as the counter. 543 bool promotion_should_fail(volatile size_t* count); 544 bool promotion_should_fail(); 545 546 // Reset the PromotionFailureALot counters. Should be called at the end of a 547 // GC in which promotion failure occurred. 548 void reset_promotion_should_fail(volatile size_t* count); 549 void reset_promotion_should_fail(); 550 #endif // #ifndef PRODUCT 551 }; 552 553 // Class to set and reset the GC cause for a CollectedHeap. 554 555 class GCCauseSetter : StackObj { 556 CollectedHeap* _heap; 557 GCCause::Cause _previous_cause; 558 public: 559 GCCauseSetter(CollectedHeap* heap, GCCause::Cause cause) { 560 _heap = heap; 561 _previous_cause = _heap->gc_cause(); 562 _heap->set_gc_cause(cause); 563 } 564 565 ~GCCauseSetter() { 566 _heap->set_gc_cause(_previous_cause); 567 } 568 }; 569 570 #endif // SHARE_GC_SHARED_COLLECTEDHEAP_HPP