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 // Can concurrent mark process this object immediately, i.e. mark as live without the need
626 // of pushing it on the mark stack (to process references)?
627 // Used to keep objects that are potentially eagerly reclaimed out of the mark stack.
628 // Its klass may still need to be handled.
629 inline bool can_be_marked_through_immediately(oop obj) const;
630 // Does the given region fulfill remembered set based eager reclaim candidate requirements?
631 bool is_potential_eager_reclaim_candidate(G1HeapRegion* r) const;
632
633 inline bool is_humongous_reclaim_candidate(uint region);
634
635 // Remove from the reclaim candidate set. Also remove from the
636 // collection set so that later encounters avoid the slow path.
637 inline void set_humongous_is_live(oop obj);
638
639 // Register the given region to be part of the collection set.
640 inline void register_humongous_candidate_region_with_region_attr(uint index);
641
642 void set_humongous_metadata(G1HeapRegion* first_hr,
643 uint num_regions,
644 size_t word_size,
645 bool update_remsets);
646
647 // The following methods update the region attribute table, i.e. a compact
648 // representation of per-region information that is regularly accessed
649 // during GC.
650 inline void register_young_region_with_region_attr(G1HeapRegion* r);
651 inline void register_new_survivor_region_with_region_attr(G1HeapRegion* r);
652 inline void register_old_collection_set_region_with_region_attr(G1HeapRegion* r);
653 inline void register_optional_region_with_region_attr(G1HeapRegion* r);
654
655 // Updates region state without overwriting the type in the region attribute table.
656 inline void update_region_attr(G1HeapRegion* r);
657
658 void clear_region_attr(const G1HeapRegion* hr) {
659 _region_attr.clear(hr);
660 }
661
662 void clear_region_attr() {
663 _region_attr.clear();
664 }
665
666 // Verify that the G1RegionAttr remset tracking corresponds to actual remset tracking
667 // for all regions.
668 void verify_region_attr_is_remset_tracked() PRODUCT_RETURN;
669
670 void clear_bitmap_for_region(G1HeapRegion* hr);
671
672 bool is_user_requested_concurrent_full_gc(GCCause::Cause cause);
673
674 // This is called at the start of either a concurrent cycle or a Full
675 // GC to update the number of old marking cycles started.
676 void increment_old_marking_cycles_started();
677
678 // This is called at the end of either a concurrent cycle or a Full
679 // GC to update the number of old marking cycles completed. Those two
680 // can happen in a nested fashion, i.e., we start a concurrent
681 // cycle, a Full GC happens half-way through it which ends first,
682 // and then the cycle notices that a Full GC happened and ends
683 // too. The concurrent parameter is a boolean to help us do a bit
684 // tighter consistency checking in the method. If concurrent is
685 // false, the caller is the inner caller in the nesting (i.e., the
686 // Full GC). If concurrent is true, the caller is the outer caller
687 // in this nesting (i.e., the concurrent cycle). Further nesting is
688 // not currently supported. The end of this call also notifies
689 // the G1OldGCCount_lock in case a Java thread is waiting for a full
690 // GC to happen (e.g., it called System.gc() with
691 // +ExplicitGCInvokesConcurrent).
692 // whole_heap_examined should indicate that during that old marking
693 // cycle the whole heap has been examined for live objects (as opposed
694 // to only parts, or aborted before completion).
695 void increment_old_marking_cycles_completed(bool concurrent, bool whole_heap_examined);
696
697 uint old_marking_cycles_started() const {
698 return _old_marking_cycles_started.load_relaxed();
699 }
700
701 uint old_marking_cycles_completed() const {
702 return _old_marking_cycles_completed.load_relaxed();
703 }
704
705 // Allocates a new heap region instance.
706 G1HeapRegion* new_heap_region(uint hrs_index, MemRegion mr);
707
708 // Frees a region by resetting its metadata and adding it to the free list
709 // passed as a parameter (this is usually a local list which will be appended
710 // to the master free list later or null if free list management is handled
711 // in another way).
712 // Callers must ensure they are the only one calling free on the given region
713 // at the same time.
714 void free_region(G1HeapRegion* hr, G1FreeRegionList* free_list);
715
716 // Add the given region to the retained regions collection set candidates.
717 void retain_region(G1HeapRegion* hr);
718
719 // Frees a humongous region by collapsing it into individual regions
720 // and calling free_region() for each of them. The freed regions
721 // will be added to the free list that's passed as a parameter (this
722 // is usually a local list which will be appended to the master free
723 // list later).
724 // The method assumes that only a single thread is ever calling
725 // this for a particular region at once.
726 void free_humongous_region(G1HeapRegion* hr,
727 G1FreeRegionList* free_list);
728
729 // Execute func(G1HeapRegion* r, bool is_last) on every region covered by the
730 // given range.
731 template <typename Func>
732 void iterate_regions_in_range(MemRegion range, const Func& func);
733
734 // Commit the required number of G1 region(s) according to the size requested
735 // and mark them as 'old' region(s).
736 // This API is only used for allocating heap space for the archived heap objects
737 // in the CDS archive.
738 HeapWord* alloc_archive_region(size_t word_size);
739
740 // Populate the G1BlockOffsetTable for archived regions with the given
741 // memory range.
742 void populate_archive_regions_bot(MemRegion range);
743
744 // For the specified range, uncommit the containing G1 regions
745 // which had been allocated by alloc_archive_regions. This should be called
746 // at JVM init time if the archive heap's contents cannot be used (e.g., if
747 // CRC check fails).
748 void dealloc_archive_regions(MemRegion range);
749
750 private:
751
752 // Shrink the garbage-first heap by at most the given size (in bytes!).
753 // (Rounds down to a G1HeapRegion boundary.)
754 void shrink(size_t shrink_bytes);
755 void shrink_helper(size_t expand_bytes);
756
757 // Schedule the VM operation that will do an evacuation pause to
758 // satisfy an allocation request of word_size. *succeeded will
759 // return whether the VM operation was successful (it did do an
760 // evacuation pause) or not (another thread beat us to it or the GC
761 // locker was active). Given that we should not be holding the
762 // Heap_lock when we enter this method, we will pass the
763 // gc_count_before (i.e., total_collections()) as a parameter since
764 // it has to be read while holding the Heap_lock. Currently, both
765 // methods that call do_collection_pause() release the Heap_lock
766 // before the call, so it's easy to read gc_count_before just before.
767 HeapWord* do_collection_pause(size_t word_size,
768 uint gc_count_before,
769 bool* succeeded,
770 GCCause::Cause gc_cause);
771
772 // Perform an incremental collection at a safepoint, possibly followed by a
773 // by-policy upgrade to a full collection.
774 // The collection should expect to be followed by an allocation of allocation_word_size.
775 // precondition: at safepoint on VM thread
776 // precondition: !is_stw_gc_active()
777 void do_collection_pause_at_safepoint(size_t allocation_word_size);
778
779 void verify_before_young_collection(G1HeapVerifier::G1VerifyType type);
780 void verify_after_young_collection(G1HeapVerifier::G1VerifyType type);
781
782 public:
783 // Start a concurrent cycle.
784 void start_concurrent_cycle(bool concurrent_operation_is_full_mark);
785
786 void prepare_for_mutator_after_young_collection();
787
788 void retire_tlabs();
789
790 // Update all region's pin counts from the per-thread caches and resets them.
791 // Must be called before any decision based on pin counts.
792 void flush_region_pin_cache();
793
794 void record_obj_copy_mem_stats();
795
796 private:
797 // The g1 remembered set of the heap.
798 G1RemSet* _rem_set;
799 // Global card set configuration
800 G1CardSetConfiguration _card_set_config;
801
802 G1MonotonicArenaFreePool _card_set_freelist_pool;
803
804 // Group cardsets
805 G1CSetCandidateGroup _young_regions_cset_group;
806
807 public:
808 G1CardSetConfiguration* card_set_config() { return &_card_set_config; }
809
810 G1CSetCandidateGroup* young_regions_cset_group() { return &_young_regions_cset_group; }
811
812 // After a collection pause, reset eden and the collection set.
813 void clear_eden();
814 void clear_collection_set();
815
816 // Abandon the current collection set without recording policy
817 // statistics or updating free lists.
818 void abandon_collection_set();
819
820 // The concurrent marker (and the thread it runs in.)
821 G1ConcurrentMark* _cm;
822
823 // The concurrent refiner.
824 G1ConcurrentRefine* _cr;
825
826 // Reusable parallel task queues and partial array manager.
827 G1ScannerTasksQueueSet* _task_queues;
828 PartialArrayStateManager* _partial_array_state_manager;
829
830 // ("Weak") Reference processing support.
831 //
832 // G1 has 2 instances of the reference processor class.
833 //
834 // One (_ref_processor_cm) handles reference object discovery and subsequent
835 // processing during concurrent marking cycles. Discovery is enabled/disabled
836 // at the start/end of a concurrent marking cycle.
837 //
838 // The other (_ref_processor_stw) handles reference object discovery and
839 // processing during incremental evacuation pauses and full GC pauses.
840 //
841 // ## Incremental evacuation pauses
842 //
843 // STW ref processor discovery is enabled/disabled at the start/end of an
844 // incremental evacuation pause. No particular handling of the CM ref
845 // processor is needed, apart from treating the discovered references as
846 // roots; CM discovery does not need to be temporarily disabled as all
847 // marking threads are paused during incremental evacuation pauses.
848 //
849 // ## Full GC pauses
850 //
851 // We abort any ongoing concurrent marking cycle, disable CM discovery, and
852 // temporarily substitute a new closure for the STW ref processor's
853 // _is_alive_non_header field (old value is restored after the full GC). Then
854 // STW ref processor discovery is enabled, and marking & compaction
855 // commences.
856
857 // The (stw) reference processor...
858 ReferenceProcessor* _ref_processor_stw;
859
860 // During reference object discovery, the _is_alive_non_header
861 // closure (if non-null) is applied to the referent object to
862 // determine whether the referent is live. If so then the
863 // reference object does not need to be 'discovered' and can
864 // be treated as a regular oop. This has the benefit of reducing
865 // the number of 'discovered' reference objects that need to
866 // be processed.
867 //
868 // Instance of the is_alive closure for embedding into the
869 // STW reference processor as the _is_alive_non_header field.
870 // Supplying a value for the _is_alive_non_header field is
871 // optional but doing so prevents unnecessary additions to
872 // the discovered lists during reference discovery.
873 G1STWIsAliveClosure _is_alive_closure_stw;
874
875 G1STWSubjectToDiscoveryClosure _is_subject_to_discovery_stw;
876
877 // The (concurrent marking) reference processor...
878 ReferenceProcessor* _ref_processor_cm;
879
880 // Instance of the concurrent mark is_alive closure for embedding
881 // into the Concurrent Marking reference processor as the
882 // _is_alive_non_header field. Supplying a value for the
883 // _is_alive_non_header field is optional but doing so prevents
884 // unnecessary additions to the discovered lists during reference
885 // discovery.
886 G1CMIsAliveClosure _is_alive_closure_cm;
887
888 G1CMSubjectToDiscoveryClosure _is_subject_to_discovery_cm;
889 public:
890
891 G1ScannerTasksQueueSet* task_queues() const;
892 G1ScannerTasksQueue* task_queue(uint i) const;
893
894 PartialArrayStateManager* partial_array_state_manager() const;
895
896 // Create a G1CollectedHeap.
897 // Must call the initialize method afterwards.
898 // May not return if something goes wrong.
899 G1CollectedHeap();
900
901 private:
902 jint initialize_concurrent_refinement();
903 jint initialize_service_thread();
904
905 void print_tracing_info() const override;
906 void stop() override;
907
908 public:
909 // Initialize the G1CollectedHeap to have the initial and
910 // maximum sizes and remembered and barrier sets
911 // specified by the policy object.
912 jint initialize() override;
913
914 void safepoint_synchronize_begin() override;
915 void safepoint_synchronize_end() override;
916
917 jlong last_refinement_epoch_start() const { return _last_refinement_epoch_start; }
918 void set_last_refinement_epoch_start(jlong epoch_start, jlong last_yield_duration);
919 jlong yield_duration_in_refinement_epoch();
920
921 // Does operations required after initialization has been done.
922 void post_initialize() override;
923
924 // Initialize weak reference processing.
925 void ref_processing_init();
926
927 Name kind() const override {
928 return CollectedHeap::G1;
929 }
930
931 const char* name() const override {
932 return "G1";
933 }
934
935 const G1CollectorState* collector_state() const { return &_collector_state; }
936 G1CollectorState* collector_state() { return &_collector_state; }
937
938 // The current policy object for the collector.
939 G1Policy* policy() const { return _policy; }
940 // The remembered set.
941 G1RemSet* rem_set() const { return _rem_set; }
942
943 const G1MonotonicArenaFreePool* card_set_freelist_pool() const { return &_card_set_freelist_pool; }
944 G1MonotonicArenaFreePool* card_set_freelist_pool() { return &_card_set_freelist_pool; }
945
946 inline G1GCPhaseTimes* phase_times() const;
947
948 const G1CollectionSet* collection_set() const { return &_collection_set; }
949 G1CollectionSet* collection_set() { return &_collection_set; }
950
951 inline bool is_collection_set_candidate(const G1HeapRegion* r) const;
952
953 void initialize_serviceability() override;
954 MemoryUsage memory_usage() override;
955 GrowableArray<GCMemoryManager*> memory_managers() override;
956 GrowableArray<MemoryPool*> memory_pools() override;
957
958 void fill_with_dummy_object(HeapWord* start, HeapWord* end, bool zap) override;
959
960 static void start_codecache_marking_cycle_if_inactive(bool concurrent_mark_start);
961 static void finish_codecache_marking_cycle();
962
963 // The shared block offset table array.
964 G1BlockOffsetTable* bot() const { return _bot; }
965
966 // Reference Processing accessors
967
968 // The STW reference processor....
969 ReferenceProcessor* ref_processor_stw() const { return _ref_processor_stw; }
970
971 G1NewTracer* gc_tracer_stw() const { return _gc_tracer_stw; }
972 STWGCTimer* gc_timer_stw() const { return _gc_timer_stw; }
973
974 // The Concurrent Marking reference processor...
975 ReferenceProcessor* ref_processor_cm() const { return _ref_processor_cm; }
976
977 size_t unused_committed_regions_in_bytes() const;
978
979 size_t capacity() const override;
980 size_t used() const override;
981 // This should be called when we're not holding the heap lock. The
982 // result might be a bit inaccurate.
983 size_t used_unlocked() const;
984 size_t recalculate_used() const;
985
986 // These virtual functions do the actual allocation.
987 // Some heaps may offer a contiguous region for shared non-blocking
988 // allocation, via inlined code (by exporting the address of the top and
989 // end fields defining the extent of the contiguous allocation region.)
990 // But G1CollectedHeap doesn't yet support this.
991
992 // Returns true if an incremental GC should be upgrade to a full gc. This
993 // is done when there are no free regions and the heap can't be expanded.
994 bool should_upgrade_to_full_gc() const {
995 return num_available_regions() == 0;
996 }
997
998 // The number of inactive regions.
999 uint num_inactive_regions() const { return _hrm.num_inactive_regions(); }
1000
1001 // The current number of regions in the heap.
1002 uint num_committed_regions() const { return _hrm.num_committed_regions(); }
1003
1004 // The max number of regions reserved for the heap.
1005 uint max_num_regions() const { return _hrm.max_num_regions(); }
1006
1007 // The number of regions that are completely free.
1008 uint num_free_regions() const { return _hrm.num_free_regions(); }
1009
1010 // The number of regions that are not completely free.
1011 uint num_used_regions() const { return _hrm.num_used_regions(); }
1012
1013 // The number of regions that can be allocated into.
1014 uint num_available_regions() const { return num_free_regions() + num_inactive_regions(); }
1015
1016 MemoryUsage get_auxiliary_data_memory_usage() const {
1017 return _hrm.get_auxiliary_data_memory_usage();
1018 }
1019
1020 #ifdef ASSERT
1021 bool is_on_master_free_list(G1HeapRegion* hr) {
1022 return _hrm.is_free(hr);
1023 }
1024 #endif // ASSERT
1025
1026 inline void old_set_add(G1HeapRegion* hr);
1027 inline void old_set_remove(G1HeapRegion* hr);
1028
1029 // Returns how much memory there is assigned to non-young heap that can not be
1030 // allocated into any more without garbage collection after a hypothetical
1031 // allocation of allocation_word_size.
1032 size_t non_young_occupancy_after_allocation(size_t allocation_word_size) const;
1033
1034 // Determine whether the given region is one that we are using as an
1035 // old GC alloc region.
1036 bool is_old_gc_alloc_region(G1HeapRegion* hr);
1037
1038 void collect(GCCause::Cause cause) override;
1039
1040 // Try to perform a collection of the heap with the given cause to allocate allocation_word_size
1041 // words.
1042 // Returns whether this collection actually executed.
1043 bool try_collect(size_t allocation_word_size, GCCause::Cause cause, const G1GCCounters& counters_before);
1044
1045 void start_concurrent_gc_for_metadata_allocation(GCCause::Cause gc_cause);
1046
1047 bool last_gc_was_periodic() { return _gc_lastcause == GCCause::_g1_periodic_collection; }
1048
1049 void remove_from_old_gen_sets(const uint old_regions_removed,
1050 const uint humongous_regions_removed);
1051 void prepend_to_freelist(G1FreeRegionList* list);
1052 void decrement_summary_bytes(size_t bytes);
1053
1054 bool is_in(const void* p) const override;
1055
1056 // Return "TRUE" iff the given object address is within the collection
1057 // set. Assumes that the reference points into the heap.
1058 inline bool is_in_cset(const G1HeapRegion* hr) const;
1059 inline bool is_in_cset(oop obj) const;
1060 inline bool is_in_cset(HeapWord* addr) const;
1061
1062 inline bool is_in_cset_or_humongous_candidate(const oop obj);
1063
1064 private:
1065 // This array is used for a quick test on whether a reference points into
1066 // the collection set or not. Each of the array's elements denotes whether the
1067 // corresponding region is in the collection set or not.
1068 G1HeapRegionAttrBiasedMappedArray _region_attr;
1069
1070 public:
1071
1072 inline G1HeapRegionAttr region_attr(const void* obj) const;
1073 inline G1HeapRegionAttr region_attr(uint idx) const;
1074
1075 MemRegion reserved() const {
1076 return _hrm.reserved();
1077 }
1078
1079 bool is_in_reserved(const void* addr) const {
1080 return reserved().contains(addr);
1081 }
1082
1083 G1CardTable* card_table() const {
1084 return static_cast<G1CardTable*>(G1BarrierSet::g1_barrier_set()->card_table());
1085 }
1086
1087 G1CardTable* refinement_table() const {
1088 return G1BarrierSet::g1_barrier_set()->refinement_table();
1089 }
1090
1091 G1CardTable::CardValue* card_table_base() const {
1092 assert(card_table() != nullptr, "must be");
1093 return card_table()->byte_map_base();
1094 }
1095
1096 // Iteration functions.
1097
1098 void object_iterate_parallel(ObjectClosure* cl, uint worker_id, G1HeapRegionClaimer* claimer);
1099
1100 // Iterate over all objects, calling "cl.do_object" on each.
1101 void object_iterate(ObjectClosure* cl) override;
1102
1103 ParallelObjectIteratorImpl* parallel_object_iterator(uint thread_num) override;
1104
1105 // Keep alive an object that was loaded with AS_NO_KEEPALIVE.
1106 void keep_alive(oop obj) override;
1107
1108 // Iterate over heap regions, in address order, terminating the
1109 // iteration early if the "do_heap_region" method returns "true".
1110 void heap_region_iterate(G1HeapRegionClosure* blk) const;
1111 void heap_region_iterate(G1HeapRegionIndexClosure* blk) const;
1112
1113 // Return the region with the given index. It assumes the index is valid.
1114 inline G1HeapRegion* region_at(uint index) const;
1115 inline G1HeapRegion* region_at_or_null(uint index) const;
1116
1117 // Iterate over the regions that the humongous object starting at the given
1118 // region and apply the given method with the signature f(G1HeapRegion*) on them.
1119 template <typename Func>
1120 void humongous_obj_regions_iterate(G1HeapRegion* start, const Func& f);
1121
1122 // Calculate the region index of the given address. Given address must be
1123 // within the heap.
1124 inline uint addr_to_region(const void* addr) const;
1125
1126 inline HeapWord* bottom_addr_for_region(uint index) const;
1127
1128 // Two functions to iterate over the heap regions in parallel. Threads
1129 // compete using the G1HeapRegionClaimer to claim the regions before
1130 // applying the closure on them.
1131 // The _from_worker_offset version uses the G1HeapRegionClaimer and
1132 // the worker id to calculate a start offset to prevent all workers to
1133 // start from the point.
1134 void heap_region_par_iterate_from_worker_offset(G1HeapRegionClosure* cl,
1135 G1HeapRegionClaimer* hrclaimer,
1136 uint worker_id) const;
1137
1138 void heap_region_par_iterate_from_start(G1HeapRegionClosure* cl,
1139 G1HeapRegionClaimer* hrclaimer) const;
1140
1141 // Iterate over all regions in the collection set in parallel.
1142 void collection_set_par_iterate_all(G1HeapRegionClosure* cl,
1143 G1HeapRegionClaimer* hr_claimer,
1144 uint worker_id);
1145
1146 // Iterate over all regions currently in the current collection set.
1147 void collection_set_iterate_all(G1HeapRegionClosure* blk);
1148
1149 // Iterate over the regions in the current increment of the collection set.
1150 // Starts the iteration so that the start regions of a given worker id over the
1151 // set active_workers are evenly spread across the set of collection set regions
1152 // to be iterated.
1153 // The variant with the G1HeapRegionClaimer guarantees that the closure will be
1154 // applied to a particular region exactly once.
1155 void collection_set_iterate_increment_from(G1HeapRegionClosure *blk, uint worker_id) {
1156 collection_set_iterate_increment_from(blk, nullptr, worker_id);
1157 }
1158 void collection_set_iterate_increment_from(G1HeapRegionClosure *blk, G1HeapRegionClaimer* hr_claimer, uint worker_id);
1159 // Iterate over the array of region indexes, uint regions[length], applying
1160 // the given G1HeapRegionClosure on each region. The worker_id will determine where
1161 // to start the iteration to allow for more efficient parallel iteration.
1162 void par_iterate_regions_array(G1HeapRegionClosure* cl,
1163 G1HeapRegionClaimer* hr_claimer,
1164 const uint regions[],
1165 size_t length,
1166 uint worker_id) const;
1167
1168 // Returns the G1HeapRegion that contains addr. addr must not be null.
1169 inline G1HeapRegion* heap_region_containing(const void* addr) const;
1170
1171 // Returns the G1HeapRegion that contains addr, or null if that is an uncommitted
1172 // region. addr must not be null.
1173 inline G1HeapRegion* heap_region_containing_or_null(const void* addr) const;
1174
1175 // A CollectedHeap is divided into a dense sequence of "blocks"; that is,
1176 // each address in the (reserved) heap is a member of exactly
1177 // one block. The defining characteristic of a block is that it is
1178 // possible to find its size, and thus to progress forward to the next
1179 // block. (Blocks may be of different sizes.) Thus, blocks may
1180 // represent Java objects, or they might be free blocks in a
1181 // free-list-based heap (or subheap), as long as the two kinds are
1182 // distinguishable and the size of each is determinable.
1183
1184 // Returns the address of the start of the "block" that contains the
1185 // address "addr". We say "blocks" instead of "object" since some heaps
1186 // may not pack objects densely; a chunk may either be an object or a
1187 // non-object.
1188 HeapWord* block_start(const void* addr) const;
1189
1190 // Requires "addr" to be the start of a block, and returns "TRUE" iff
1191 // the block is an object.
1192 bool block_is_obj(const HeapWord* addr) const;
1193
1194 // Section on thread-local allocation buffers (TLABs)
1195 // See CollectedHeap for semantics.
1196
1197 size_t tlab_capacity() const override;
1198 size_t tlab_used() const override;
1199 size_t max_tlab_size() const override;
1200 size_t unsafe_max_tlab_alloc() const override;
1201
1202 inline bool is_in_young(const oop obj) const;
1203 inline bool requires_barriers(stackChunkOop obj) const override;
1204
1205 // Returns "true" iff the given word_size is "very large".
1206 static bool is_humongous(size_t word_size) {
1207 // Note this has to be strictly greater-than as the TLABs
1208 // are capped at the humongous threshold and we want to
1209 // ensure that we don't try to allocate a TLAB as
1210 // humongous and that we don't allocate a humongous
1211 // object in a TLAB.
1212 return word_size > _humongous_object_threshold_in_words;
1213 }
1214
1215 // Returns the humongous threshold for a specific region size
1216 static size_t humongous_threshold_for(size_t region_size) {
1217 return (region_size / 2);
1218 }
1219
1220 // Returns the number of regions the humongous object of the given word size
1221 // requires.
1222 static size_t humongous_obj_size_in_regions(size_t word_size);
1223
1224 // Returns how much space in bytes an allocation of word_size will use up in the
1225 // heap.
1226 static size_t allocation_used_bytes(size_t word_size);
1227
1228 // Print the maximum heap capacity.
1229 size_t max_capacity() const override;
1230 size_t min_capacity() const;
1231
1232 Tickspan time_since_last_collection() const { return Ticks::now() - _collection_pause_end; }
1233
1234 // Convenience function to be used in situations where the heap type can be
1235 // asserted to be this type.
1236 static G1CollectedHeap* heap() {
1237 return named_heap<G1CollectedHeap>(CollectedHeap::G1);
1238 }
1239
1240 // add appropriate methods for any other surv rate groups
1241
1242 G1SurvivorRegions* survivor() { return &_survivor; }
1243
1244 inline uint target_num_eden_regions() const;
1245 uint eden_regions_count() const { return _eden.length(); }
1246 uint eden_regions_count(uint node_index) const { return _eden.regions_on_node(node_index); }
1247 uint survivor_regions_count() const { return _survivor.length(); }
1248 uint survivor_regions_count(uint node_index) const { return _survivor.regions_on_node(node_index); }
1249 size_t eden_regions_used_bytes() const { return _eden.used_bytes(); }
1250 size_t survivor_regions_used_bytes() const { return _survivor.used_bytes(); }
1251 uint young_regions_count() const { return _eden.length() + _survivor.length(); }
1252 uint old_regions_count() const { return _old_set.length(); }
1253 uint humongous_regions_count() const { return _humongous_set.length(); }
1254
1255 #ifdef ASSERT
1256 bool check_no_young_regions();
1257 #endif
1258
1259 bool is_marked(oop obj) const;
1260
1261 // Determine if an object is dead, given the object and also
1262 // the region to which the object belongs.
1263 inline bool is_obj_dead(const oop obj, const G1HeapRegion* hr) const;
1264
1265 // Determine if an object is dead, given only the object itself.
1266 // This will find the region to which the object belongs and
1267 // then call the region version of the same function.
1268 // If obj is null it is not dead.
1269 inline bool is_obj_dead(const oop obj) const;
1270
1271 inline bool is_obj_dead_full(const oop obj, const G1HeapRegion* hr) const;
1272 inline bool is_obj_dead_full(const oop obj) const;
1273
1274 // Mark the live object that failed evacuation in the bitmap.
1275 void mark_evac_failure_object(oop obj) const;
1276
1277 G1ConcurrentMark* concurrent_mark() const { return _cm; }
1278
1279 // Refinement
1280
1281 G1ConcurrentRefine* concurrent_refine() const { return _cr; }
1282
1283 // Optimized nmethod scanning support routines
1284
1285 // Register the given nmethod with the G1 heap.
1286 void register_nmethod(nmethod* nm) override;
1287
1288 // Unregister the given nmethod from the G1 heap.
1289 void unregister_nmethod(nmethod* nm) override;
1290
1291 // No nmethod verification implemented.
1292 void verify_nmethod(nmethod* nm) override {}
1293
1294 // Recalculate amount of used memory after GC. Must be called after all allocation
1295 // has finished.
1296 void update_used_after_gc(bool evacuation_failed);
1297
1298 // Rebuild the code root lists for each region
1299 // after a full GC.
1300 void rebuild_code_roots();
1301
1302 // Performs cleaning of data structures after class unloading.
1303 void complete_cleaning(bool class_unloading_occurred);
1304
1305 void unload_classes_and_code(const char* description, BoolObjectClosure* cl, GCTimer* timer);
1306
1307 void bulk_unregister_nmethods();
1308
1309 // Verification
1310
1311 // Perform any cleanup actions necessary before allowing a verification.
1312 void prepare_for_verify() override;
1313
1314 // Perform verification.
1315 void verify(VerifyOption vo) override;
1316
1317 // WhiteBox testing support.
1318 bool supports_concurrent_gc_breakpoints() const override;
1319
1320 WorkerThreads* safepoint_workers() override { return _workers; }
1321
1322 // The methods below are here for convenience and dispatch the
1323 // appropriate method depending on value of the given VerifyOption
1324 // parameter. The values for that parameter, and their meanings,
1325 // are the same as those above.
1326
1327 bool is_obj_dead_cond(const oop obj,
1328 const G1HeapRegion* hr,
1329 const VerifyOption vo) const;
1330
1331 bool is_obj_dead_cond(const oop obj,
1332 const VerifyOption vo) const;
1333
1334 G1HeapSummary create_g1_heap_summary();
1335 G1EvacSummary create_g1_evac_summary(G1EvacStats* stats);
1336
1337 // Printing
1338 private:
1339 void print_heap_regions() const;
1340 void print_regions_on(outputStream* st) const;
1341
1342 public:
1343 void print_heap_on(outputStream* st) const override;
1344 void print_extended_on(outputStream* st) const;
1345 void print_gc_on(outputStream* st) const override;
1346
1347 void gc_threads_do(ThreadClosure* tc) const override;
1348
1349 // Used to print information about locations in the hs_err file.
1350 bool print_location(outputStream* st, void* addr) const override;
1351 };
1352
1353 // Scoped object that performs common pre- and post-gc heap printing operations.
1354 class G1HeapPrinterMark : public StackObj {
1355 G1CollectedHeap* _g1h;
1356 G1HeapTransition _heap_transition;
1357
1358 public:
1359 G1HeapPrinterMark(G1CollectedHeap* g1h);
1360 ~G1HeapPrinterMark();
1361 };
1362
1363 // Scoped object that performs common pre- and post-gc operations related to
1364 // JFR events.
1365 class G1JFRTracerMark : public StackObj {
1366 protected:
1367 STWGCTimer* _timer;
1368 GCTracer* _tracer;
1369
1370 public:
1371 G1JFRTracerMark(STWGCTimer* timer, GCTracer* tracer);
1372 ~G1JFRTracerMark();
1373 };
1374
1375 #endif // SHARE_GC_G1_G1COLLECTEDHEAP_HPP