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