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