1 /*
2 * Copyright (c) 2001, 2026, 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_G1_G1COLLECTEDHEAP_HPP
26 #define SHARE_GC_G1_G1COLLECTEDHEAP_HPP
27
28 #include "gc/g1/g1BarrierSet.hpp"
29 #include "gc/g1/g1BiasedArray.hpp"
30 #include "gc/g1/g1CardSet.hpp"
31 #include "gc/g1/g1CardTable.hpp"
32 #include "gc/g1/g1CollectionSet.hpp"
33 #include "gc/g1/g1CollectorState.hpp"
34 #include "gc/g1/g1ConcurrentMark.hpp"
35 #include "gc/g1/g1EdenRegions.hpp"
36 #include "gc/g1/g1EvacStats.hpp"
37 #include "gc/g1/g1HeapRegionAttr.hpp"
38 #include "gc/g1/g1HeapRegionManager.hpp"
39 #include "gc/g1/g1HeapRegionSet.hpp"
40 #include "gc/g1/g1HeapTransition.hpp"
41 #include "gc/g1/g1HeapVerifier.hpp"
42 #include "gc/g1/g1MonitoringSupport.hpp"
43 #include "gc/g1/g1MonotonicArenaFreeMemoryTask.hpp"
44 #include "gc/g1/g1MonotonicArenaFreePool.hpp"
45 #include "gc/g1/g1NUMA.hpp"
46 #include "gc/g1/g1SurvivorRegions.hpp"
47 #include "gc/g1/g1YoungGCAllocationFailureInjector.hpp"
48 #include "gc/shared/barrierSet.hpp"
49 #include "gc/shared/collectedHeap.hpp"
50 #include "gc/shared/gcHeapSummary.hpp"
51 #include "gc/shared/plab.hpp"
52 #include "gc/shared/taskqueue.hpp"
53 #include "memory/allocation.hpp"
54 #include "memory/iterator.hpp"
55 #include "memory/memRegion.hpp"
56 #include "runtime/atomic.hpp"
57 #include "runtime/mutexLocker.hpp"
58 #include "runtime/threadSMR.hpp"
59 #include "utilities/bitMap.hpp"
60
61 // A "G1CollectedHeap" is an implementation of a java heap for HotSpot.
62 // It uses the "Garbage First" heap organization and algorithm, which
63 // may combine concurrent marking with parallel, incremental compaction of
64 // heap subsets that will yield large amounts of garbage.
65
66 // Forward declarations
67 class G1Allocator;
68 class G1BatchedTask;
69 class G1CardTableEntryClosure;
70 class G1ConcurrentMark;
71 class G1ConcurrentMarkThread;
72 class G1ConcurrentRefine;
73 class G1GCCounters;
74 class G1GCPhaseTimes;
75 class G1HeapSizingPolicy;
76 class G1NewTracer;
77 class G1RemSet;
78 class G1ReviseNumYoungRegionsTask;
79 class G1ServiceTask;
80 class G1ServiceThread;
81 class GCMemoryManager;
82 class G1HeapRegion;
83 class MemoryPool;
84 class nmethod;
85 class PartialArrayStateManager;
86 class ReferenceProcessor;
87 class STWGCTimer;
88 class WorkerThreads;
89
90 typedef OverflowTaskQueue<ScannerTask, mtGC> G1ScannerTasksQueue;
91 typedef GenericTaskQueueSet<G1ScannerTasksQueue, mtGC> G1ScannerTasksQueueSet;
92
93 typedef int RegionIdx_t; // needs to hold [ 0..max_num_regions() )
94 typedef int CardIdx_t; // needs to hold [ 0..CardsPerRegion )
95
96 // The G1 STW is alive closure.
97 // An instance is embedded into the G1CH and used as the
98 // (optional) _is_alive_non_header closure in the STW
99 // reference processor. It is also extensively used during
100 // reference processing during STW evacuation pauses.
101 class G1STWIsAliveClosure : public BoolObjectClosure {
102 G1CollectedHeap* _g1h;
103 public:
104 G1STWIsAliveClosure(G1CollectedHeap* g1h) : _g1h(g1h) {}
105 bool do_object_b(oop p) override;
106 };
107
108 class G1STWSubjectToDiscoveryClosure : public BoolObjectClosure {
109 G1CollectedHeap* _g1h;
110 public:
111 G1STWSubjectToDiscoveryClosure(G1CollectedHeap* g1h) : _g1h(g1h) {}
112 bool do_object_b(oop p) override;
113 };
114
115 class G1RegionMappingChangedListener : public G1MappingChangedListener {
116 private:
117 void reset_from_card_cache(uint start_idx, size_t num_regions);
118 public:
119 void on_commit(uint start_idx, size_t num_regions, bool zero_filled) override;
120 };
121
122 // Helper to claim contiguous sets of JavaThread for processing by multiple threads.
123 class G1JavaThreadsListClaimer : public StackObj {
124 ThreadsListHandle _list;
125 uint _claim_step;
126
127 Atomic<uint> _cur_claim;
128
129 // Attempts to claim _claim_step JavaThreads, returning an array of claimed
130 // JavaThread* with count elements. Returns null (and a zero count) if there
131 // are no more threads to claim.
132 JavaThread* const* claim(uint& count);
133
134 public:
135 G1JavaThreadsListClaimer(uint claim_step) : _list(), _claim_step(claim_step), _cur_claim(0) {
136 assert(claim_step > 0, "must be");
137 }
138
139 // Executes the given closure on the elements of the JavaThread list, chunking the
140 // JavaThread set in claim_step chunks for each caller to reduce parallelization
141 // overhead.
142 void apply(ThreadClosure* cl);
143
144 // Total number of JavaThreads that can be claimed.
145 uint length() const { return _list.length(); }
146 };
147
148 class G1CollectedHeap : public CollectedHeap {
149 friend class G1CheckRegionAttrTableClosure;
150 friend class G1EvacuateRegionsTask;
151 friend class G1FullCollector;
152 friend class G1GCAllocRegion;
153 friend class G1HeapPrinterMark;
154 friend class G1HeapRegionClaimer;
155 friend class G1HeapVerifier;
156 friend class G1PLABAllocator;
157 friend class G1YoungGCVerifierMark;
158 friend class MutatorAllocRegion;
159 friend class VM_G1CollectForAllocation;
160 friend class VM_G1CollectFull;
161 friend class VM_G1TryInitiateConcMark;
162 friend class VMStructs;
163
164 private:
165 // GC Overhead Limit functionality related members.
166 //
167 // The goal is to return null for allocations prematurely (before really going
168 // OOME) in case both GC CPU usage (>= GCTimeLimit) and not much available free
169 // memory (<= GCHeapFreeLimit) so that applications can exit gracefully or try
170 // to keep running by easing off memory.
171 uintx _gc_overhead_counter; // The number of consecutive garbage collections we were over the limits.
172
173 void update_gc_overhead_counter();
174 bool gc_overhead_limit_exceeded();
175
176 G1ServiceThread* _service_thread;
177 G1ServiceTask* _periodic_gc_task;
178 G1MonotonicArenaFreeMemoryTask* _free_arena_memory_task;
179 G1ReviseNumYoungRegionsTask* _revise_num_young_regions_task;
180
181 WorkerThreads* _workers;
182
183 // The current epoch for refinement, i.e. the number of times the card tables
184 // have been swapped by a garbage collection.
185 // Used for detecting whether concurrent refinement has been interrupted by a
186 // garbage collection.
187 size_t _refinement_epoch;
188
189 // The following members are for tracking safepoint durations between garbage
190 // collections.
191 jlong _last_synchronized_start;
192
193 jlong _last_refinement_epoch_start;
194 jlong _yield_duration_in_refinement_epoch; // Time spent in safepoints since beginning of last refinement epoch.
195 size_t _last_safepoint_refinement_epoch; // Refinement epoch before last safepoint.
196
197 Ticks _collection_pause_end;
198
199 static size_t _humongous_object_threshold_in_words;
200
201 // These sets keep track of old and humongous regions respectively.
202 G1HeapRegionSet _old_set;
203 G1HeapRegionSet _humongous_set;
204
205 // Young gen memory statistics before GC.
206 G1MonotonicArenaMemoryStats _young_gen_card_set_stats;
207 // Collection set candidates memory statistics after GC.
208 G1MonotonicArenaMemoryStats _collection_set_candidates_card_set_stats;
209
210 // The block offset table for the G1 heap.
211 G1BlockOffsetTable* _bot;
212
213 public:
214 void rebuild_free_region_list();
215 // Start a new incremental collection set for the next pause.
216 void start_new_collection_set();
217
218 void prepare_region_for_full_compaction(G1HeapRegion* hr);
219
220 private:
221 // Rebuilds the region sets / lists so that they are repopulated to
222 // reflect the contents of the heap. The only exception is the
223 // humongous set which was not torn down in the first place. If
224 // free_list_only is true, it will only rebuild the free list.
225 void rebuild_region_sets(bool free_list_only);
226
227 // Callback for region mapping changed events.
228 G1RegionMappingChangedListener _listener;
229
230 // Handle G1 NUMA support.
231 G1NUMA* _numa;
232
233 // The sequence of all heap regions in the heap.
234 G1HeapRegionManager _hrm;
235
236 // Manages all allocations with regions except humongous object allocations.
237 G1Allocator* _allocator;
238
239 G1YoungGCAllocationFailureInjector _allocation_failure_injector;
240
241 // Manages all heap verification.
242 G1HeapVerifier* _verifier;
243
244 // Outside of GC pauses, the number of bytes used in all regions other
245 // than the current allocation region(s).
246 volatile size_t _summary_bytes_used;
247
248 void increase_used(size_t bytes);
249 void decrease_used(size_t bytes);
250
251 void set_used(size_t bytes);
252
253 // Number of bytes used in all regions during GC. Typically changed when
254 // retiring a GC alloc region.
255 size_t _bytes_used_during_gc;
256
257 public:
258 size_t bytes_used_during_gc() const { return _bytes_used_during_gc; }
259
260 private:
261 // GC allocation statistics policy for survivors.
262 G1EvacStats _survivor_evac_stats;
263
264 // GC allocation statistics policy for tenured objects.
265 G1EvacStats _old_evac_stats;
266
267 // Helper for monitoring and management support.
268 G1MonitoringSupport* _monitoring_support;
269
270 uint _num_humongous_objects; // Current amount of (all) humongous objects found in the heap.
271 uint _num_humongous_reclaim_candidates; // Number of humongous object eager reclaim candidates.
272 public:
273 uint num_humongous_objects() const { return _num_humongous_objects; }
274 uint num_humongous_reclaim_candidates() const { return _num_humongous_reclaim_candidates; }
275 bool has_humongous_reclaim_candidates() const { return _num_humongous_reclaim_candidates > 0; }
276
277 void set_humongous_stats(uint num_humongous_total, uint num_humongous_candidates);
278
279 bool should_sample_collection_set_candidates() const;
280 void set_collection_set_candidates_stats(G1MonotonicArenaMemoryStats& stats);
281 void set_young_gen_card_set_stats(const G1MonotonicArenaMemoryStats& stats);
282
283 void update_perf_counter_cpu_time();
284 private:
285
286 // Return true if an explicit GC should start a concurrent cycle instead
287 // of doing a STW full GC. A concurrent cycle should be started if:
288 // (a) cause == _g1_humongous_allocation,
289 // (b) cause == _java_lang_system_gc and +ExplicitGCInvokesConcurrent,
290 // (c) cause == _dcmd_gc_run and +ExplicitGCInvokesConcurrent,
291 // (d) cause == _wb_breakpoint,
292 // (e) cause == _g1_periodic_collection and +G1PeriodicGCInvokesConcurrent.
293 bool should_do_concurrent_full_gc(GCCause::Cause cause);
294
295 // Wait until a full mark (either currently in progress or one that completed
296 // after the current request) has finished. Returns whether that full mark started
297 // after this request. If so, we typically do not need another one.
298 bool wait_full_mark_finished(GCCause::Cause cause,
299 uint old_marking_started_before,
300 uint old_marking_started_after,
301 uint old_marking_completed_after);
302
303 // Attempt to start a concurrent cycle with the indicated cause, for potentially
304 // allocating allocation_word_size words.
305 // precondition: should_do_concurrent_full_gc(cause)
306 bool try_collect_concurrently(size_t allocation_word_size,
307 GCCause::Cause cause,
308 uint gc_counter,
309 uint old_marking_started_before);
310
311 // indicates whether we are in young or mixed GC mode
312 G1CollectorState _collector_state;
313
314 // Keeps track of how many "old marking cycles" (i.e., Full GCs or
315 // concurrent cycles) we have started.
316 Atomic<uint> _old_marking_cycles_started;
317
318 // Keeps track of how many "old marking cycles" (i.e., Full GCs or
319 // concurrent cycles) we have completed.
320 Atomic<uint> _old_marking_cycles_completed;
321
322 // Create a memory mapper for auxiliary data structures of the given size and
323 // translation factor.
324 static G1RegionToSpaceMapper* create_aux_memory_mapper(const char* description,
325 size_t size,
326 size_t translation_factor);
327
328 void trace_heap(GCWhen::Type when, const GCTracer* tracer) override;
329
330 // These are macros so that, if the assert fires, we get the correct
331 // line number, file, etc.
332
333 #define heap_locking_asserts_params(_extra_message_) \
334 "%s : Heap_lock locked: %s, at safepoint: %s, is VM thread: %s", \
335 (_extra_message_), \
336 BOOL_TO_STR(Heap_lock->owned_by_self()), \
337 BOOL_TO_STR(SafepointSynchronize::is_at_safepoint()), \
338 BOOL_TO_STR(Thread::current()->is_VM_thread())
339
340 #define assert_heap_locked() \
341 do { \
342 assert(Heap_lock->owned_by_self(), \
343 heap_locking_asserts_params("should be holding the Heap_lock")); \
344 } while (0)
345
346 #define assert_heap_locked_or_at_safepoint(_should_be_vm_thread_) \
347 do { \
348 assert(Heap_lock->owned_by_self() || \
349 (SafepointSynchronize::is_at_safepoint() && \
350 ((_should_be_vm_thread_) == Thread::current()->is_VM_thread())), \
351 heap_locking_asserts_params("should be holding the Heap_lock or " \
352 "should be at a safepoint")); \
353 } while (0)
354
355 #define assert_heap_locked_and_not_at_safepoint() \
356 do { \
357 assert(Heap_lock->owned_by_self() && \
358 !SafepointSynchronize::is_at_safepoint(), \
359 heap_locking_asserts_params("should be holding the Heap_lock and " \
360 "should not be at a safepoint")); \
361 } while (0)
362
363 #define assert_heap_not_locked() \
364 do { \
365 assert(!Heap_lock->owned_by_self(), \
366 heap_locking_asserts_params("should not be holding the Heap_lock")); \
367 } while (0)
368
369 #define assert_heap_not_locked_and_not_at_safepoint() \
370 do { \
371 assert(!Heap_lock->owned_by_self() && \
372 !SafepointSynchronize::is_at_safepoint(), \
373 heap_locking_asserts_params("should not be holding the Heap_lock and " \
374 "should not be at a safepoint")); \
375 } while (0)
376
377 #define assert_at_safepoint_on_vm_thread() \
378 do { \
379 assert_at_safepoint(); \
380 assert(Thread::current_or_null() != nullptr, "no current thread"); \
381 assert(Thread::current()->is_VM_thread(), "current thread is not VM thread"); \
382 } while (0)
383
384 #ifdef ASSERT
385 #define assert_used_and_recalculate_used_equal(g1h) \
386 do { \
387 size_t cur_used_bytes = g1h->used(); \
388 size_t recal_used_bytes = g1h->recalculate_used(); \
389 assert(cur_used_bytes == recal_used_bytes, "Used(%zu) is not" \
390 " same as recalculated used(%zu).", \
391 cur_used_bytes, recal_used_bytes); \
392 } while (0)
393 #else
394 #define assert_used_and_recalculate_used_equal(g1h) do {} while(0)
395 #endif
396
397 G1EdenRegions _eden;
398 G1SurvivorRegions _survivor;
399
400 STWGCTimer* _gc_timer_stw;
401
402 G1NewTracer* _gc_tracer_stw;
403
404 // The current policy object for the collector.
405 G1Policy* _policy;
406 G1HeapSizingPolicy* _heap_sizing_policy;
407
408 G1CollectionSet _collection_set;
409
410 // Try to allocate a single non-humongous G1HeapRegion sufficient for
411 // an allocation of the given word_size. If do_expand is true,
412 // attempt to expand the heap if necessary to satisfy the allocation
413 // request. 'type' takes the type of region to be allocated. (Use constants
414 // Old, Eden, Humongous, Survivor defined in G1HeapRegionType.)
415 G1HeapRegion* new_region(size_t word_size,
416 G1HeapRegionType type,
417 bool do_expand,
418 uint node_index = G1NUMA::AnyNodeIndex);
419
420 // Initialize a contiguous set of free regions of length num_regions
421 // and starting at index first so that they appear as a single
422 // humongous region.
423 HeapWord* humongous_obj_allocate_initialize_regions(G1HeapRegion* first_hr,
424 uint num_regions,
425 size_t word_size);
426
427 // Attempt to allocate a humongous object of the given size. Return
428 // null if unsuccessful.
429 HeapWord* humongous_obj_allocate(size_t word_size);
430
431 // The following two methods, allocate_new_tlab() and
432 // mem_allocate(), are the two main entry points from the runtime
433 // into the G1's allocation routines. They have the following
434 // assumptions:
435 //
436 // * They should both be called outside safepoints.
437 //
438 // * They should both be called without holding the Heap_lock.
439 //
440 // * All allocation requests for new TLABs should go to
441 // allocate_new_tlab().
442 //
443 // * All non-TLAB allocation requests should go to mem_allocate().
444 //
445 // * If either call cannot satisfy the allocation request using the
446 // current allocating region, they will try to get a new one. If
447 // this fails, (only) mem_allocate() will attempt to do an evacuation
448 // pause and retry the allocation. Allocate_new_tlab() will return null,
449 // deferring to the following mem_allocate().
450 //
451 // * We do not allow humongous-sized TLABs. So, allocate_new_tlab
452 // should never be called with word_size being humongous. All
453 // humongous allocation requests should go to mem_allocate() which
454 // will satisfy them in a special path.
455
456 HeapWord* allocate_new_tlab(size_t min_size,
457 size_t requested_size,
458 size_t* actual_size) override;
459
460 HeapWord* mem_allocate(size_t word_size) override;
461
462 // First-level mutator allocation attempt: try to allocate out of
463 // the mutator alloc region without taking the Heap_lock. This
464 // should only be used for non-humongous allocations.
465 inline HeapWord* attempt_allocation(size_t min_word_size,
466 size_t desired_word_size,
467 size_t* actual_word_size,
468 bool allow_gc);
469 // Second-level mutator allocation attempt: take the Heap_lock and
470 // retry the allocation attempt, potentially scheduling a GC
471 // pause if allow_gc is set. This should only be used for non-humongous
472 // allocations.
473 HeapWord* attempt_allocation_slow(uint node_index, size_t word_size, bool allow_gc);
474
475 // Takes the Heap_lock and attempts a humongous allocation. It can
476 // potentially schedule a GC pause.
477 HeapWord* attempt_allocation_humongous(size_t word_size);
478
479 // Allocation attempt that should be called during safepoints (e.g.,
480 // at the end of a successful GC). expect_null_mutator_alloc_region
481 // specifies whether the mutator alloc region is expected to be null
482 // or not.
483 HeapWord* attempt_allocation_at_safepoint(size_t word_size,
484 bool expect_null_mutator_alloc_region);
485
486 // These methods are the "callbacks" from the G1AllocRegion class.
487
488 // For mutator alloc regions.
489 G1HeapRegion* new_mutator_alloc_region(size_t word_size, uint node_index);
490 void retire_mutator_alloc_region(G1HeapRegion* alloc_region,
491 size_t allocated_bytes);
492
493 // For GC alloc regions.
494 bool has_more_regions(G1HeapRegionAttr dest);
495 G1HeapRegion* new_gc_alloc_region(size_t word_size, G1HeapRegionAttr dest, uint node_index);
496 void retire_gc_alloc_region(G1HeapRegion* alloc_region,
497 size_t allocated_bytes, G1HeapRegionAttr dest);
498
499 void resize_heap(size_t resize_bytes, bool should_expand);
500
501 // - if clear_all_soft_refs is true, all soft references should be
502 // cleared during the GC.
503 // - if do_maximal_compaction is true, full gc will do a maximally
504 // compacting collection, leaving no dead wood.
505 // - if allocation_word_size is set, then this allocation size will
506 // be accounted for in case shrinking of the heap happens.
507 // - it returns false if it is unable to do the collection due to the
508 // GC locker being active, true otherwise.
509 void do_full_collection(size_t allocation_word_size,
510 bool clear_all_soft_refs,
511 bool do_maximal_compaction);
512
513 // Callback from VM_G1CollectFull operation, or collect_as_vm_thread.
514 void do_full_collection(bool clear_all_soft_refs) override;
515
516 // Helper to do a full collection that clears soft references.
517 void upgrade_to_full_collection();
518
519 // Callback from VM_G1CollectForAllocation operation.
520 // This function does everything necessary/possible to satisfy a
521 // failed allocation request (including collection, expansion, etc.)
522 HeapWord* satisfy_failed_allocation(size_t word_size);
523 // Internal helpers used during full GC to split it up to
524 // increase readability.
525 bool abort_concurrent_cycle();
526 void verify_before_full_collection(bool concurrent_cycle_aborted);
527 void prepare_heap_for_full_collection();
528 void prepare_for_mutator_after_full_collection(size_t allocation_word_size);
529 void abort_refinement();
530 void verify_after_full_collection();
531 void print_heap_after_full_collection();
532
533 // Helper method for satisfy_failed_allocation()
534 HeapWord* satisfy_failed_allocation_helper(size_t word_size,
535 bool do_gc,
536 bool maximal_compaction,
537 bool expect_null_mutator_alloc_region);
538
539 // Attempting to expand the heap sufficiently
540 // to support an allocation of the given "word_size". If
541 // successful, perform the allocation and return the address of the
542 // allocated block, or else null.
543 HeapWord* expand_and_allocate(size_t word_size);
544
545 void verify_numa_regions(const char* desc);
546
547 public:
548 // If during a concurrent start pause we may install a pending list head which is not
549 // otherwise reachable, ensure that it is marked in the bitmap for concurrent marking
550 // to discover.
551 void make_pending_list_reachable();
552
553 G1ServiceThread* service_thread() const { return _service_thread; }
554
555 WorkerThreads* workers() const { return _workers; }
556
557 // Run the given batch task using the workers.
558 void run_batch_task(G1BatchedTask* cl);
559
560 // Return "optimal" number of chunks per region we want to use for claiming areas
561 // within a region to claim during card table scanning.
562 // The returned value is a trade-off between granularity of work distribution and
563 // memory usage and maintenance costs of that table.
564 // Testing showed that 64 for 1M/2M region, 128 for 4M/8M regions, 256 for 16/32M regions,
565 // and so on seems to be such a good trade-off.
566 static uint get_chunks_per_region_for_scan();
567 // Return "optimal" number of chunks per region we want to use for claiming areas
568 // within a region to claim during card table merging.
569 // This is much smaller than for scanning as the merge work is much smaller.
570 // Currently 1 for 1M regions, 2 for 2/4M regions, 4 for 8/16M regions and so on.
571 static uint get_chunks_per_region_for_merge();
572
573 G1Allocator* allocator() {
574 return _allocator;
575 }
576
577 G1YoungGCAllocationFailureInjector* allocation_failure_injector() { return &_allocation_failure_injector; }
578
579 G1HeapVerifier* verifier() {
580 return _verifier;
581 }
582
583 G1MonitoringSupport* monitoring_support() {
584 assert(_monitoring_support != nullptr, "should have been initialized");
585 return _monitoring_support;
586 }
587
588 void pin_object(JavaThread* thread, oop obj) override;
589 void unpin_object(JavaThread* thread, oop obj) override;
590
591 void resize_heap_after_young_collection(size_t allocation_word_size);
592 void resize_heap_after_full_collection(size_t allocation_word_size);
593
594 // Check if there is memory to uncommit and if so schedule a task to do it.
595 void uncommit_regions_if_necessary();
596 // Immediately uncommit uncommittable regions.
597 uint uncommit_regions(uint region_limit);
598 bool has_uncommittable_regions();
599
600 G1NUMA* numa() const { return _numa; }
601
602 // Expand the garbage-first heap by at least the given size (in bytes!).
603 // Returns true if the heap was expanded by the requested amount;
604 // false otherwise.
605 // (Rounds up to a G1HeapRegion boundary.)
606 bool expand(size_t expand_bytes, WorkerThreads* pretouch_workers);
607 bool expand_single_region(uint node_index);
608
609 // Returns the PLAB statistics for a given destination.
610 inline G1EvacStats* alloc_buffer_stats(G1HeapRegionAttr dest);
611
612 // Determines PLAB size for a given destination.
613 inline size_t desired_plab_sz(G1HeapRegionAttr dest);
614 // Clamp the given PLAB word size to allowed values. Prevents humongous PLAB sizes
615 // for two reasons:
616 // * PLABs are allocated using a similar paths as oops, but should
617 // never be in a humongous region
618 // * Allowing humongous PLABs needlessly churns the region free lists
619 inline size_t clamp_plab_size(size_t value) const;
620
621 // Do anything common to GC's.
622 void gc_prologue(bool full);
623 void gc_epilogue(bool full);
624
625 // Does the given region fulfill remembered set based eager reclaim candidate requirements?
626 bool is_potential_eager_reclaim_candidate(G1HeapRegion* r) const;
627
628 inline bool is_humongous_reclaim_candidate(uint region);
629
630 // Remove from the reclaim candidate set. Also remove from the
631 // collection set so that later encounters avoid the slow path.
632 inline void set_humongous_is_live(oop obj);
633
634 // Register the given region to be part of the collection set.
635 inline void register_humongous_candidate_region_with_region_attr(uint index);
636
637 void set_humongous_metadata(G1HeapRegion* first_hr,
638 uint num_regions,
639 size_t word_size,
640 bool update_remsets);
641
642 // The following methods update the region attribute table, i.e. a compact
643 // representation of per-region information that is regularly accessed
644 // during GC.
645 inline void register_young_region_with_region_attr(G1HeapRegion* r);
646 inline void register_new_survivor_region_with_region_attr(G1HeapRegion* r);
647 inline void register_old_collection_set_region_with_region_attr(G1HeapRegion* r);
648 inline void register_optional_region_with_region_attr(G1HeapRegion* r);
649
650 // Updates region state without overwriting the type in the region attribute table.
651 inline void update_region_attr(G1HeapRegion* r);
652
653 void clear_region_attr(const G1HeapRegion* hr) {
654 _region_attr.clear(hr);
655 }
656
657 void clear_region_attr() {
658 _region_attr.clear();
659 }
660
661 // Verify that the G1RegionAttr remset tracking corresponds to actual remset tracking
662 // for all regions.
663 void verify_region_attr_is_remset_tracked() PRODUCT_RETURN;
664
665 void clear_bitmap_for_region(G1HeapRegion* hr);
666
667 bool is_user_requested_concurrent_full_gc(GCCause::Cause cause);
668
669 // This is called at the start of either a concurrent cycle or a Full
670 // GC to update the number of old marking cycles started.
671 void increment_old_marking_cycles_started();
672
673 // This is called at the end of either a concurrent cycle or a Full
674 // GC to update the number of old marking cycles completed. Those two
675 // can happen in a nested fashion, i.e., we start a concurrent
676 // cycle, a Full GC happens half-way through it which ends first,
677 // and then the cycle notices that a Full GC happened and ends
678 // too. The concurrent parameter is a boolean to help us do a bit
679 // tighter consistency checking in the method. If concurrent is
680 // false, the caller is the inner caller in the nesting (i.e., the
681 // Full GC). If concurrent is true, the caller is the outer caller
682 // in this nesting (i.e., the concurrent cycle). Further nesting is
683 // not currently supported. The end of this call also notifies
684 // the G1OldGCCount_lock in case a Java thread is waiting for a full
685 // GC to happen (e.g., it called System.gc() with
686 // +ExplicitGCInvokesConcurrent).
687 // whole_heap_examined should indicate that during that old marking
688 // cycle the whole heap has been examined for live objects (as opposed
689 // to only parts, or aborted before completion).
690 void increment_old_marking_cycles_completed(bool concurrent, bool whole_heap_examined);
691
692 uint old_marking_cycles_started() const {
693 return _old_marking_cycles_started.load_relaxed();
694 }
695
696 uint old_marking_cycles_completed() const {
697 return _old_marking_cycles_completed.load_relaxed();
698 }
699
700 // Allocates a new heap region instance.
701 G1HeapRegion* new_heap_region(uint hrs_index, MemRegion mr);
702
703 // Frees a region by resetting its metadata and adding it to the free list
704 // passed as a parameter (this is usually a local list which will be appended
705 // to the master free list later or null if free list management is handled
706 // in another way).
707 // Callers must ensure they are the only one calling free on the given region
708 // at the same time.
709 void free_region(G1HeapRegion* hr, G1FreeRegionList* free_list);
710
711 // Add the given region to the retained regions collection set candidates.
712 void retain_region(G1HeapRegion* hr);
713
714 // Frees a humongous region by collapsing it into individual regions
715 // and calling free_region() for each of them. The freed regions
716 // will be added to the free list that's passed as a parameter (this
717 // is usually a local list which will be appended to the master free
718 // list later).
719 // The method assumes that only a single thread is ever calling
720 // this for a particular region at once.
721 void free_humongous_region(G1HeapRegion* hr,
722 G1FreeRegionList* free_list);
723
724 // Execute func(G1HeapRegion* r, bool is_last) on every region covered by the
725 // given range.
726 template <typename Func>
727 void iterate_regions_in_range(MemRegion range, const Func& func);
728
729 // Commit the required number of G1 region(s) according to the size requested
730 // and mark them as 'old' region(s).
731 // This API is only used for allocating heap space for the archived heap objects
732 // in the CDS archive.
733 HeapWord* alloc_archive_region(size_t word_size);
734
735 // Populate the G1BlockOffsetTable for archived regions with the given
736 // memory range.
737 void populate_archive_regions_bot(MemRegion range);
738
739 // For the specified range, uncommit the containing G1 regions
740 // which had been allocated by alloc_archive_regions. This should be called
741 // at JVM init time if the archive heap's contents cannot be used (e.g., if
742 // CRC check fails).
743 void dealloc_archive_regions(MemRegion range);
744
745 private:
746
747 // Shrink the garbage-first heap by at most the given size (in bytes!).
748 // (Rounds down to a G1HeapRegion boundary.)
749 void shrink(size_t shrink_bytes);
750 void shrink_helper(size_t expand_bytes);
751
752 // Schedule the VM operation that will do an evacuation pause to
753 // satisfy an allocation request of word_size. *succeeded will
754 // return whether the VM operation was successful (it did do an
755 // evacuation pause) or not (another thread beat us to it or the GC
756 // locker was active). Given that we should not be holding the
757 // Heap_lock when we enter this method, we will pass the
758 // gc_count_before (i.e., total_collections()) as a parameter since
759 // it has to be read while holding the Heap_lock. Currently, both
760 // methods that call do_collection_pause() release the Heap_lock
761 // before the call, so it's easy to read gc_count_before just before.
762 HeapWord* do_collection_pause(size_t word_size,
763 uint gc_count_before,
764 bool* succeeded,
765 GCCause::Cause gc_cause);
766
767 // Perform an incremental collection at a safepoint, possibly followed by a
768 // by-policy upgrade to a full collection.
769 // The collection should expect to be followed by an allocation of allocation_word_size.
770 // precondition: at safepoint on VM thread
771 // precondition: !is_stw_gc_active()
772 void do_collection_pause_at_safepoint(size_t allocation_word_size);
773
774 void verify_before_young_collection(G1HeapVerifier::G1VerifyType type);
775 void verify_after_young_collection(G1HeapVerifier::G1VerifyType type);
776
777 public:
778 // Start a concurrent cycle.
779 void start_concurrent_cycle(bool concurrent_operation_is_full_mark);
780
781 void prepare_for_mutator_after_young_collection();
782
783 void retire_tlabs();
784
785 // Update all region's pin counts from the per-thread caches and resets them.
786 // Must be called before any decision based on pin counts.
787 void flush_region_pin_cache();
788
789 void record_obj_copy_mem_stats();
790
791 private:
792 // The g1 remembered set of the heap.
793 G1RemSet* _rem_set;
794 // Global card set configuration
795 G1CardSetConfiguration _card_set_config;
796
797 G1MonotonicArenaFreePool _card_set_freelist_pool;
798
799 // Group cardsets
800 G1CSetCandidateGroup _young_regions_cset_group;
801
802 public:
803 G1CardSetConfiguration* card_set_config() { return &_card_set_config; }
804
805 G1CSetCandidateGroup* young_regions_cset_group() { return &_young_regions_cset_group; }
806
807 // After a collection pause, reset eden and the collection set.
808 void clear_eden();
809 void clear_collection_set();
810
811 // Abandon the current collection set without recording policy
812 // statistics or updating free lists.
813 void abandon_collection_set();
814
815 // The concurrent marker (and the thread it runs in.)
816 G1ConcurrentMark* _cm;
817
818 // The concurrent refiner.
819 G1ConcurrentRefine* _cr;
820
821 // Reusable parallel task queues and partial array manager.
822 G1ScannerTasksQueueSet* _task_queues;
823 PartialArrayStateManager* _partial_array_state_manager;
824
825 // ("Weak") Reference processing support.
826 //
827 // G1 has 2 instances of the reference processor class.
828 //
829 // One (_ref_processor_cm) handles reference object discovery and subsequent
830 // processing during concurrent marking cycles. Discovery is enabled/disabled
831 // at the start/end of a concurrent marking cycle.
832 //
833 // The other (_ref_processor_stw) handles reference object discovery and
834 // processing during incremental evacuation pauses and full GC pauses.
835 //
836 // ## Incremental evacuation pauses
837 //
838 // STW ref processor discovery is enabled/disabled at the start/end of an
839 // incremental evacuation pause. No particular handling of the CM ref
840 // processor is needed, apart from treating the discovered references as
841 // roots; CM discovery does not need to be temporarily disabled as all
842 // marking threads are paused during incremental evacuation pauses.
843 //
844 // ## Full GC pauses
845 //
846 // We abort any ongoing concurrent marking cycle, disable CM discovery, and
847 // temporarily substitute a new closure for the STW ref processor's
848 // _is_alive_non_header field (old value is restored after the full GC). Then
849 // STW ref processor discovery is enabled, and marking & compaction
850 // commences.
851
852 // The (stw) reference processor...
853 ReferenceProcessor* _ref_processor_stw;
854
855 // During reference object discovery, the _is_alive_non_header
856 // closure (if non-null) is applied to the referent object to
857 // determine whether the referent is live. If so then the
858 // reference object does not need to be 'discovered' and can
859 // be treated as a regular oop. This has the benefit of reducing
860 // the number of 'discovered' reference objects that need to
861 // be processed.
862 //
863 // Instance of the is_alive closure for embedding into the
864 // STW reference processor as the _is_alive_non_header field.
865 // Supplying a value for the _is_alive_non_header field is
866 // optional but doing so prevents unnecessary additions to
867 // the discovered lists during reference discovery.
868 G1STWIsAliveClosure _is_alive_closure_stw;
869
870 G1STWSubjectToDiscoveryClosure _is_subject_to_discovery_stw;
871
872 // The (concurrent marking) reference processor...
873 ReferenceProcessor* _ref_processor_cm;
874
875 // Instance of the concurrent mark is_alive closure for embedding
876 // into the Concurrent Marking reference processor as the
877 // _is_alive_non_header field. Supplying a value for the
878 // _is_alive_non_header field is optional but doing so prevents
879 // unnecessary additions to the discovered lists during reference
880 // discovery.
881 G1CMIsAliveClosure _is_alive_closure_cm;
882
883 G1CMSubjectToDiscoveryClosure _is_subject_to_discovery_cm;
884 public:
885
886 G1ScannerTasksQueueSet* task_queues() const;
887 G1ScannerTasksQueue* task_queue(uint i) const;
888
889 PartialArrayStateManager* partial_array_state_manager() const;
890
891 // Create a G1CollectedHeap.
892 // Must call the initialize method afterwards.
893 // May not return if something goes wrong.
894 G1CollectedHeap();
895
896 private:
897 jint initialize_concurrent_refinement();
898 jint initialize_service_thread();
899
900 void print_tracing_info() const override;
901 void stop() override;
902
903 public:
904 // Initialize the G1CollectedHeap to have the initial and
905 // maximum sizes and remembered and barrier sets
906 // specified by the policy object.
907 jint initialize() override;
908
909 void safepoint_synchronize_begin() override;
910 void safepoint_synchronize_end() override;
911
912 jlong last_refinement_epoch_start() const { return _last_refinement_epoch_start; }
913 void set_last_refinement_epoch_start(jlong epoch_start, jlong last_yield_duration);
914 jlong yield_duration_in_refinement_epoch();
915
916 // Does operations required after initialization has been done.
917 void post_initialize() override;
918
919 // Initialize weak reference processing.
920 void ref_processing_init();
921
922 Name kind() const override {
923 return CollectedHeap::G1;
924 }
925
926 const char* name() const override {
927 return "G1";
928 }
929
930 const G1CollectorState* collector_state() const { return &_collector_state; }
931 G1CollectorState* collector_state() { return &_collector_state; }
932
933 // The current policy object for the collector.
934 G1Policy* policy() const { return _policy; }
935 // The remembered set.
936 G1RemSet* rem_set() const { return _rem_set; }
937
938 const G1MonotonicArenaFreePool* card_set_freelist_pool() const { return &_card_set_freelist_pool; }
939 G1MonotonicArenaFreePool* card_set_freelist_pool() { return &_card_set_freelist_pool; }
940
941 inline G1GCPhaseTimes* phase_times() const;
942
943 const G1CollectionSet* collection_set() const { return &_collection_set; }
944 G1CollectionSet* collection_set() { return &_collection_set; }
945
946 inline bool is_collection_set_candidate(const G1HeapRegion* r) const;
947
948 void initialize_serviceability() override;
949 MemoryUsage memory_usage() override;
950 GrowableArray<GCMemoryManager*> memory_managers() override;
951 GrowableArray<MemoryPool*> memory_pools() override;
952
953 void fill_with_dummy_object(HeapWord* start, HeapWord* end, bool zap) override;
954
955 static void start_codecache_marking_cycle_if_inactive(bool concurrent_mark_start);
956 static void finish_codecache_marking_cycle();
957
958 // The shared block offset table array.
959 G1BlockOffsetTable* bot() const { return _bot; }
960
961 // Reference Processing accessors
962
963 // The STW reference processor....
964 ReferenceProcessor* ref_processor_stw() const { return _ref_processor_stw; }
965
966 G1NewTracer* gc_tracer_stw() const { return _gc_tracer_stw; }
967 STWGCTimer* gc_timer_stw() const { return _gc_timer_stw; }
968
969 // The Concurrent Marking reference processor...
970 ReferenceProcessor* ref_processor_cm() const { return _ref_processor_cm; }
971
972 size_t unused_committed_regions_in_bytes() const;
973
974 size_t capacity() const override;
975 size_t used() const override;
976 // This should be called when we're not holding the heap lock. The
977 // result might be a bit inaccurate.
978 size_t used_unlocked() const;
979 size_t recalculate_used() const;
980
981 // These virtual functions do the actual allocation.
982 // Some heaps may offer a contiguous region for shared non-blocking
983 // allocation, via inlined code (by exporting the address of the top and
984 // end fields defining the extent of the contiguous allocation region.)
985 // But G1CollectedHeap doesn't yet support this.
986
987 // Returns true if an incremental GC should be upgrade to a full gc. This
988 // is done when there are no free regions and the heap can't be expanded.
989 bool should_upgrade_to_full_gc() const {
990 return num_available_regions() == 0;
991 }
992
993 // The number of inactive regions.
994 uint num_inactive_regions() const { return _hrm.num_inactive_regions(); }
995
996 // The current number of regions in the heap.
997 uint num_committed_regions() const { return _hrm.num_committed_regions(); }
998
999 // The max number of regions reserved for the heap.
1000 uint max_num_regions() const { return _hrm.max_num_regions(); }
1001
1002 // The number of regions that are completely free.
1003 uint num_free_regions() const { return _hrm.num_free_regions(); }
1004
1005 // The number of regions that are not completely free.
1006 uint num_used_regions() const { return _hrm.num_used_regions(); }
1007
1008 // The number of regions that can be allocated into.
1009 uint num_available_regions() const { return num_free_regions() + num_inactive_regions(); }
1010
1011 MemoryUsage get_auxiliary_data_memory_usage() const {
1012 return _hrm.get_auxiliary_data_memory_usage();
1013 }
1014
1015 #ifdef ASSERT
1016 bool is_on_master_free_list(G1HeapRegion* hr) {
1017 return _hrm.is_free(hr);
1018 }
1019 #endif // ASSERT
1020
1021 inline void old_set_add(G1HeapRegion* hr);
1022 inline void old_set_remove(G1HeapRegion* hr);
1023
1024 // Returns how much memory there is assigned to non-young heap that can not be
1025 // allocated into any more without garbage collection after a hypothetical
1026 // allocation of allocation_word_size.
1027 size_t non_young_occupancy_after_allocation(size_t allocation_word_size) const;
1028
1029 // Determine whether the given region is one that we are using as an
1030 // old GC alloc region.
1031 bool is_old_gc_alloc_region(G1HeapRegion* hr);
1032
1033 void collect(GCCause::Cause cause) override;
1034
1035 // Try to perform a collection of the heap with the given cause to allocate allocation_word_size
1036 // words.
1037 // Returns whether this collection actually executed.
1038 bool try_collect(size_t allocation_word_size, GCCause::Cause cause, const G1GCCounters& counters_before);
1039
1040 void start_concurrent_gc_for_metadata_allocation(GCCause::Cause gc_cause);
1041
1042 bool last_gc_was_periodic() { return _gc_lastcause == GCCause::_g1_periodic_collection; }
1043
1044 void remove_from_old_gen_sets(const uint old_regions_removed,
1045 const uint humongous_regions_removed);
1046 void prepend_to_freelist(G1FreeRegionList* list);
1047 void decrement_summary_bytes(size_t bytes);
1048
1049 bool is_in(const void* p) const override;
1050
1051 // Return "TRUE" iff the given object address is within the collection
1052 // set. Assumes that the reference points into the heap.
1053 inline bool is_in_cset(const G1HeapRegion* hr) const;
1054 inline bool is_in_cset(oop obj) const;
1055 inline bool is_in_cset(HeapWord* addr) const;
1056
1057 inline bool is_in_cset_or_humongous_candidate(const oop obj);
1058
1059 private:
1060 // This array is used for a quick test on whether a reference points into
1061 // the collection set or not. Each of the array's elements denotes whether the
1062 // corresponding region is in the collection set or not.
1063 G1HeapRegionAttrBiasedMappedArray _region_attr;
1064
1065 public:
1066
1067 inline G1HeapRegionAttr region_attr(const void* obj) const;
1068 inline G1HeapRegionAttr region_attr(uint idx) const;
1069
1070 MemRegion reserved() const {
1071 return _hrm.reserved();
1072 }
1073
1074 bool is_in_reserved(const void* addr) const {
1075 return reserved().contains(addr);
1076 }
1077
1078 G1CardTable* card_table() const {
1079 return static_cast<G1CardTable*>(G1BarrierSet::g1_barrier_set()->card_table());
1080 }
1081
1082 G1CardTable* refinement_table() const {
1083 return G1BarrierSet::g1_barrier_set()->refinement_table();
1084 }
1085
1086 G1CardTable::CardValue* card_table_base() const {
1087 assert(card_table() != nullptr, "must be");
1088 return card_table()->byte_map_base();
1089 }
1090
1091 // Iteration functions.
1092
1093 void object_iterate_parallel(ObjectClosure* cl, uint worker_id, G1HeapRegionClaimer* claimer);
1094
1095 // Iterate over all objects, calling "cl.do_object" on each.
1096 void object_iterate(ObjectClosure* cl) override;
1097
1098 ParallelObjectIteratorImpl* parallel_object_iterator(uint thread_num) override;
1099
1100 // Keep alive an object that was loaded with AS_NO_KEEPALIVE.
1101 void keep_alive(oop obj) override;
1102
1103 // Iterate over heap regions, in address order, terminating the
1104 // iteration early if the "do_heap_region" method returns "true".
1105 void heap_region_iterate(G1HeapRegionClosure* blk) const;
1106 void heap_region_iterate(G1HeapRegionIndexClosure* blk) const;
1107
1108 // Return the region with the given index. It assumes the index is valid.
1109 inline G1HeapRegion* region_at(uint index) const;
1110 inline G1HeapRegion* region_at_or_null(uint index) const;
1111
1112 // Iterate over the regions that the humongous object starting at the given
1113 // region and apply the given method with the signature f(G1HeapRegion*) on them.
1114 template <typename Func>
1115 void humongous_obj_regions_iterate(G1HeapRegion* start, const Func& f);
1116
1117 // Calculate the region index of the given address. Given address must be
1118 // within the heap.
1119 inline uint addr_to_region(const void* addr) const;
1120
1121 inline HeapWord* bottom_addr_for_region(uint index) const;
1122
1123 // Two functions to iterate over the heap regions in parallel. Threads
1124 // compete using the G1HeapRegionClaimer to claim the regions before
1125 // applying the closure on them.
1126 // The _from_worker_offset version uses the G1HeapRegionClaimer and
1127 // the worker id to calculate a start offset to prevent all workers to
1128 // start from the point.
1129 void heap_region_par_iterate_from_worker_offset(G1HeapRegionClosure* cl,
1130 G1HeapRegionClaimer* hrclaimer,
1131 uint worker_id) const;
1132
1133 void heap_region_par_iterate_from_start(G1HeapRegionClosure* cl,
1134 G1HeapRegionClaimer* hrclaimer) const;
1135
1136 // Iterate over all regions in the collection set in parallel.
1137 void collection_set_par_iterate_all(G1HeapRegionClosure* cl,
1138 G1HeapRegionClaimer* hr_claimer,
1139 uint worker_id);
1140
1141 // Iterate over all regions currently in the current collection set.
1142 void collection_set_iterate_all(G1HeapRegionClosure* blk);
1143
1144 // Iterate over the regions in the current increment of the collection set.
1145 // Starts the iteration so that the start regions of a given worker id over the
1146 // set active_workers are evenly spread across the set of collection set regions
1147 // to be iterated.
1148 // The variant with the G1HeapRegionClaimer guarantees that the closure will be
1149 // applied to a particular region exactly once.
1150 void collection_set_iterate_increment_from(G1HeapRegionClosure *blk, uint worker_id) {
1151 collection_set_iterate_increment_from(blk, nullptr, worker_id);
1152 }
1153 void collection_set_iterate_increment_from(G1HeapRegionClosure *blk, G1HeapRegionClaimer* hr_claimer, uint worker_id);
1154 // Iterate over the array of region indexes, uint regions[length], applying
1155 // the given G1HeapRegionClosure on each region. The worker_id will determine where
1156 // to start the iteration to allow for more efficient parallel iteration.
1157 void par_iterate_regions_array(G1HeapRegionClosure* cl,
1158 G1HeapRegionClaimer* hr_claimer,
1159 const uint regions[],
1160 size_t length,
1161 uint worker_id) const;
1162
1163 // Returns the G1HeapRegion that contains addr. addr must not be null.
1164 inline G1HeapRegion* heap_region_containing(const void* addr) const;
1165
1166 // Returns the G1HeapRegion that contains addr, or null if that is an uncommitted
1167 // region. addr must not be null.
1168 inline G1HeapRegion* heap_region_containing_or_null(const void* addr) const;
1169
1170 // A CollectedHeap is divided into a dense sequence of "blocks"; that is,
1171 // each address in the (reserved) heap is a member of exactly
1172 // one block. The defining characteristic of a block is that it is
1173 // possible to find its size, and thus to progress forward to the next
1174 // block. (Blocks may be of different sizes.) Thus, blocks may
1175 // represent Java objects, or they might be free blocks in a
1176 // free-list-based heap (or subheap), as long as the two kinds are
1177 // distinguishable and the size of each is determinable.
1178
1179 // Returns the address of the start of the "block" that contains the
1180 // address "addr". We say "blocks" instead of "object" since some heaps
1181 // may not pack objects densely; a chunk may either be an object or a
1182 // non-object.
1183 HeapWord* block_start(const void* addr) const;
1184
1185 // Requires "addr" to be the start of a block, and returns "TRUE" iff
1186 // the block is an object.
1187 bool block_is_obj(const HeapWord* addr) const;
1188
1189 // Section on thread-local allocation buffers (TLABs)
1190 // See CollectedHeap for semantics.
1191
1192 size_t tlab_capacity() const override;
1193 size_t tlab_used() const override;
1194 size_t max_tlab_size() const override;
1195 size_t unsafe_max_tlab_alloc() const override;
1196
1197 inline bool is_in_young(const oop obj) const;
1198 inline bool requires_barriers(stackChunkOop obj) const override;
1199
1200 // Returns "true" iff the given word_size is "very large".
1201 static bool is_humongous(size_t word_size) {
1202 // Note this has to be strictly greater-than as the TLABs
1203 // are capped at the humongous threshold and we want to
1204 // ensure that we don't try to allocate a TLAB as
1205 // humongous and that we don't allocate a humongous
1206 // object in a TLAB.
1207 return word_size > _humongous_object_threshold_in_words;
1208 }
1209
1210 // Returns the humongous threshold for a specific region size
1211 static size_t humongous_threshold_for(size_t region_size) {
1212 return (region_size / 2);
1213 }
1214
1215 // Returns the number of regions the humongous object of the given word size
1216 // requires.
1217 static size_t humongous_obj_size_in_regions(size_t word_size);
1218
1219 // Returns how much space in bytes an allocation of word_size will use up in the
1220 // heap.
1221 static size_t allocation_used_bytes(size_t word_size);
1222
1223 // Print the maximum heap capacity.
1224 size_t max_capacity() const override;
1225 size_t min_capacity() const;
1226
1227 Tickspan time_since_last_collection() const { return Ticks::now() - _collection_pause_end; }
1228
1229 // Convenience function to be used in situations where the heap type can be
1230 // asserted to be this type.
1231 static G1CollectedHeap* heap() {
1232 return named_heap<G1CollectedHeap>(CollectedHeap::G1);
1233 }
1234
1235 // add appropriate methods for any other surv rate groups
1236
1237 G1SurvivorRegions* survivor() { return &_survivor; }
1238
1239 inline uint target_num_eden_regions() const;
1240 uint eden_regions_count() const { return _eden.length(); }
1241 uint eden_regions_count(uint node_index) const { return _eden.regions_on_node(node_index); }
1242 uint survivor_regions_count() const { return _survivor.length(); }
1243 uint survivor_regions_count(uint node_index) const { return _survivor.regions_on_node(node_index); }
1244 size_t eden_regions_used_bytes() const { return _eden.used_bytes(); }
1245 size_t survivor_regions_used_bytes() const { return _survivor.used_bytes(); }
1246 uint young_regions_count() const { return _eden.length() + _survivor.length(); }
1247 uint old_regions_count() const { return _old_set.length(); }
1248 uint humongous_regions_count() const { return _humongous_set.length(); }
1249
1250 #ifdef ASSERT
1251 bool check_no_young_regions();
1252 #endif
1253
1254 bool is_marked(oop obj) const;
1255
1256 // Determine if an object is dead, given the object and also
1257 // the region to which the object belongs.
1258 inline bool is_obj_dead(const oop obj, const G1HeapRegion* hr) const;
1259
1260 // Determine if an object is dead, given only the object itself.
1261 // This will find the region to which the object belongs and
1262 // then call the region version of the same function.
1263 // If obj is null it is not dead.
1264 inline bool is_obj_dead(const oop obj) const;
1265
1266 inline bool is_obj_dead_full(const oop obj, const G1HeapRegion* hr) const;
1267 inline bool is_obj_dead_full(const oop obj) const;
1268
1269 // Mark the live object that failed evacuation in the bitmap.
1270 void mark_evac_failure_object(oop obj) const;
1271
1272 G1ConcurrentMark* concurrent_mark() const { return _cm; }
1273
1274 // Refinement
1275
1276 G1ConcurrentRefine* concurrent_refine() const { return _cr; }
1277
1278 // Optimized nmethod scanning support routines
1279
1280 // Register the given nmethod with the G1 heap.
1281 void register_nmethod(nmethod* nm) override;
1282
1283 // Unregister the given nmethod from the G1 heap.
1284 void unregister_nmethod(nmethod* nm) override;
1285
1286 // No nmethod verification implemented.
1287 void verify_nmethod(nmethod* nm) override {}
1288
1289 // Recalculate amount of used memory after GC. Must be called after all allocation
1290 // has finished.
1291 void update_used_after_gc(bool evacuation_failed);
1292
1293 // Rebuild the code root lists for each region
1294 // after a full GC.
1295 void rebuild_code_roots();
1296
1297 // Performs cleaning of data structures after class unloading.
1298 void complete_cleaning(bool class_unloading_occurred);
1299
1300 void unload_classes_and_code(const char* description, BoolObjectClosure* cl, GCTimer* timer);
1301
1302 void bulk_unregister_nmethods();
1303
1304 // Verification
1305
1306 // Perform any cleanup actions necessary before allowing a verification.
1307 void prepare_for_verify() override;
1308
1309 // Perform verification.
1310 void verify(VerifyOption vo) override;
1311
1312 // WhiteBox testing support.
1313 bool supports_concurrent_gc_breakpoints() const override;
1314
1315 WorkerThreads* safepoint_workers() override { return _workers; }
1316
1317 // The methods below are here for convenience and dispatch the
1318 // appropriate method depending on value of the given VerifyOption
1319 // parameter. The values for that parameter, and their meanings,
1320 // are the same as those above.
1321
1322 bool is_obj_dead_cond(const oop obj,
1323 const G1HeapRegion* hr,
1324 const VerifyOption vo) const;
1325
1326 bool is_obj_dead_cond(const oop obj,
1327 const VerifyOption vo) const;
1328
1329 G1HeapSummary create_g1_heap_summary();
1330 G1EvacSummary create_g1_evac_summary(G1EvacStats* stats);
1331
1332 // Printing
1333 private:
1334 void print_heap_regions() const;
1335 void print_regions_on(outputStream* st) const;
1336
1337 public:
1338 void print_heap_on(outputStream* st) const override;
1339 void print_extended_on(outputStream* st) const;
1340 void print_gc_on(outputStream* st) const override;
1341
1342 void gc_threads_do(ThreadClosure* tc) const override;
1343
1344 // Used to print information about locations in the hs_err file.
1345 bool print_location(outputStream* st, void* addr) const override;
1346 };
1347
1348 // Scoped object that performs common pre- and post-gc heap printing operations.
1349 class G1HeapPrinterMark : public StackObj {
1350 G1CollectedHeap* _g1h;
1351 G1HeapTransition _heap_transition;
1352
1353 public:
1354 G1HeapPrinterMark(G1CollectedHeap* g1h);
1355 ~G1HeapPrinterMark();
1356 };
1357
1358 // Scoped object that performs common pre- and post-gc operations related to
1359 // JFR events.
1360 class G1JFRTracerMark : public StackObj {
1361 protected:
1362 STWGCTimer* _timer;
1363 GCTracer* _tracer;
1364
1365 public:
1366 G1JFRTracerMark(STWGCTimer* timer, GCTracer* tracer);
1367 ~G1JFRTracerMark();
1368 };
1369
1370 #endif // SHARE_GC_G1_G1COLLECTEDHEAP_HPP