1 /*
2 * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved.
3 * Copyright (c) 2013, 2021, Red Hat, Inc. All rights reserved.
4 * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
5 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
6 *
7 * This code is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License version 2 only, as
9 * published by the Free Software Foundation.
10 *
11 * This code is distributed in the hope that it will be useful, but WITHOUT
12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 * version 2 for more details (a copy is included in the LICENSE file that
15 * accompanied this code).
16 *
17 * You should have received a copy of the GNU General Public License version
18 * 2 along with this work; if not, write to the Free Software Foundation,
19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20 *
21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22 * or visit www.oracle.com if you need additional information or have any
23 * questions.
24 *
25 */
26
27 #ifndef SHARE_GC_SHENANDOAH_SHENANDOAHHEAP_HPP
28 #define SHARE_GC_SHENANDOAH_SHENANDOAHHEAP_HPP
29
30 #include "gc/shared/collectedHeap.hpp"
31 #include "gc/shared/markBitMap.hpp"
32 #include "gc/shenandoah/mode/shenandoahMode.hpp"
33 #include "gc/shenandoah/shenandoahAllocRate.hpp"
34 #include "gc/shenandoah/shenandoahAllocRequest.hpp"
35 #include "gc/shenandoah/shenandoahAsserts.hpp"
36 #include "gc/shenandoah/shenandoahController.hpp"
37 #include "gc/shenandoah/shenandoahEvacTracker.hpp"
38 #include "gc/shenandoah/shenandoahGenerationType.hpp"
39 #include "gc/shenandoah/shenandoahLock.hpp"
40 #include "gc/shenandoah/shenandoahMmuTracker.hpp"
41 #include "gc/shenandoah/shenandoahPadding.hpp"
42 #include "gc/shenandoah/shenandoahSharedVariables.hpp"
43 #include "gc/shenandoah/shenandoahUnload.hpp"
44 #include "memory/metaspace.hpp"
45 #include "services/memoryManager.hpp"
46 #include "utilities/globalDefinitions.hpp"
47 #include "utilities/stack.hpp"
48
49 class ConcurrentGCTimer;
50 class ObjectIterateScanRootClosure;
51 class ShenandoahAllocator;
52 class ShenandoahCollectorPolicy;
53 class ShenandoahGCSession;
54 class ShenandoahGCStateResetter;
55 class ShenandoahGeneration;
56 class ShenandoahYoungGeneration;
57 class ShenandoahOldGeneration;
58 class ShenandoahHeuristics;
59 class ShenandoahMarkingContext;
60 class ShenandoahMode;
61 class ShenandoahPhaseTimings;
62 class ShenandoahHeap;
63 class ShenandoahHeapRegion;
64 class ShenandoahHeapRegionClosure;
65 class ShenandoahCollectionSet;
66 class ShenandoahFreeSet;
67 class ShenandoahConcurrentMark;
68 class ShenandoahFullGC;
69 class ShenandoahMonitoringSupport;
70 class ShenandoahReferenceProcessor;
71 class ShenandoahUncommitThread;
72 class ShenandoahVerifier;
73 class ShenandoahWorkerThreads;
74 class VMStructs;
75
76 // Used for buffering per-region liveness data.
77 // Needed since ShenandoahHeapRegion uses atomics to update liveness.
78 // The ShenandoahHeap array has max-workers elements, each of which is an array of
79 // uint16_t * max_regions. The choice of uint16_t is not accidental:
80 // there is a tradeoff between static/dynamic footprint that translates
81 // into cache pressure (which is already high during marking), and
82 // too many atomic updates. uint32_t is too large, uint8_t is too small.
83 typedef uint16_t ShenandoahLiveData;
84 #define SHENANDOAH_LIVEDATA_MAX ((ShenandoahLiveData)-1)
85
86 class ShenandoahRegionIterator : public StackObj {
87 private:
88 ShenandoahHeap* _heap;
89
90 shenandoah_padding(0);
91 Atomic<size_t> _index;
92 shenandoah_padding(1);
93
94 // No implicit copying: iterators should be passed by reference to capture the state
95 NONCOPYABLE(ShenandoahRegionIterator);
96
97 public:
98 ShenandoahRegionIterator();
99 ShenandoahRegionIterator(ShenandoahHeap* heap);
100
101 // Reset iterator to default state
102 void reset();
103
104 // Returns next region, or null if there are no more regions.
105 // This is multi-thread-safe.
106 inline ShenandoahHeapRegion* next();
107
108 // This is *not* MT safe. However, in the absence of multithreaded access, it
109 // can be used to determine if there is more work to do.
110 bool has_next() const;
111 };
112
113 class ShenandoahHeapRegionClosure : public StackObj {
114 public:
115 virtual void heap_region_do(ShenandoahHeapRegion* r) = 0;
116 virtual size_t parallel_region_stride() { return ShenandoahParallelRegionStride; }
117 virtual bool is_thread_safe() { return false; }
118 };
119
120 typedef ShenandoahLock ShenandoahHeapLock;
121 // ShenandoahHeapLocker implements locker to assure mutually exclusive access to the global heap data structures.
122 // Asserts in the implementation detect potential deadlock usage with regards the rebuild lock that is present
123 // in ShenandoahFreeSet. Whenever both locks are acquired, this lock should be acquired before the
124 // ShenandoahFreeSet rebuild lock.
125 class ShenandoahHeapLocker : public StackObj {
126 private:
127 ShenandoahHeapLock* _lock;
128 public:
129 ShenandoahHeapLocker(ShenandoahHeapLock* lock, bool allow_block_for_safepoint = false);
130
131 ~ShenandoahHeapLocker() {
132 _lock->unlock();
133 }
134 };
135
136 typedef Stack<oop, mtGC> ShenandoahScanObjectStack;
137
138 // Shenandoah GC is low-pause concurrent GC that uses a load reference barrier
139 // for concurent evacuation and a snapshot-at-the-beginning write barrier for
140 // concurrent marking. See ShenandoahControlThread for GC cycle structure.
141 //
142 class ShenandoahHeap : public CollectedHeap {
143 friend class ShenandoahAsserts;
144 friend class VMStructs;
145 friend class ShenandoahGCSession;
146 friend class ShenandoahGCStateResetter;
147 friend class ShenandoahParallelObjectIterator;
148 friend class ShenandoahSafepoint;
149
150 // Supported GC
151 friend class ShenandoahConcurrentGC;
152 friend class ShenandoahOldGC;
153 friend class ShenandoahDegenGC;
154 friend class ShenandoahFullGC;
155 friend class ShenandoahUnload;
156
157 // ---------- Locks that guard important data structures in Heap
158 //
159 private:
160 ShenandoahHeapLock _lock;
161
162 // This is set and cleared by only the VMThread
163 // at each STW pause (safepoint) to the value given to the VM operation.
164 // This allows the value to be always consistently
165 // seen by all mutators as well as all GC worker threads.
166 ShenandoahGeneration* _active_generation;
167
168 protected:
169 void print_tracing_info() const override;
170 void stop() override;
171
172 public:
173 ShenandoahHeapLock* lock() {
174 return &_lock;
175 }
176
177 ShenandoahGeneration* active_generation() const {
178 // value of _active_generation field, see above
179 return _active_generation;
180 }
181
182 // Update the _active_generation field: can only be called at a safepoint by the VMThread.
183 void set_active_generation(ShenandoahGeneration* generation);
184
185 ShenandoahHeuristics* heuristics();
186
187 // ---------- Initialization, termination, identification, printing routines
188 //
189 public:
190 static ShenandoahHeap* heap();
191
192 const char* name() const override { return "Shenandoah"; }
193 ShenandoahHeap::Name kind() const override { return CollectedHeap::Shenandoah; }
194
195 ShenandoahHeap(ShenandoahCollectorPolicy* policy);
196 jint initialize() override;
197 void post_initialize() override;
198 virtual void initialize_generations();
199 void initialize_mode();
200 virtual void initialize_heuristics();
201 virtual void post_initialize_heuristics();
202 virtual void print_init_logger() const;
203 void initialize_serviceability() override;
204
205 void print_heap_on(outputStream* st) const override;
206 void print_gc_on(outputStream* st) const override;
207 void print_heap_regions_on(outputStream* st) const;
208
209 // Flushes cycle timings to global timings and prints the phase timings for the last completed cycle.
210 void process_gc_stats() const;
211
212 void prepare_for_verify() override;
213 void verify(VerifyOption vo) override;
214
215 // WhiteBox testing support.
216 bool supports_concurrent_gc_breakpoints() const override {
217 return true;
218 }
219
220 // ---------- Heap counters and metrics
221 //
222 private:
223 size_t _initial_size;
224 size_t _minimum_size;
225
226 Atomic<size_t> _soft_max_size;
227 shenandoah_padding(0);
228 Atomic<size_t> _committed;
229 shenandoah_padding(1);
230
231 ShenandoahAllocationRate _alloc_rate;
232 ShenandoahDecayAllocRate _alloc_rate_decay;
233
234 public:
235 void increase_committed(size_t bytes);
236 void decrease_committed(size_t bytes);
237
238 size_t min_capacity() const;
239 size_t max_capacity() const override;
240 size_t soft_max_capacity() const;
241 size_t initial_capacity() const;
242 size_t capacity() const override;
243 size_t used() const override;
244 size_t committed() const;
245
246 void set_soft_max_capacity(size_t v);
247
248 ShenandoahAllocationRate& alloc_rate() {
249 return _alloc_rate;
250 }
251
252 // ---------- Periodic Tasks
253 //
254 public:
255 // Notify heuristics and region state change logger that the state of the heap has changed
256 void notify_heap_changed();
257
258 // Force counters to update
259 void set_forced_counters_update(bool value);
260
261 // Update counters if forced flag is set
262 void handle_force_counters_update();
263
264 // ---------- Workers handling
265 //
266 private:
267 uint _max_workers;
268 ShenandoahWorkerThreads* _workers;
269 ShenandoahWorkerThreads* _safepoint_workers;
270
271 virtual void initialize_controller();
272
273 public:
274 uint max_workers();
275 void assert_gc_workers(uint nworker) NOT_DEBUG_RETURN;
276
277 WorkerThreads* workers() const;
278 WorkerThreads* safepoint_workers() override;
279
280 void gc_threads_do(ThreadClosure* tcl) const override;
281
282 // ---------- Heap regions handling machinery
283 //
284 private:
285 MemRegion _heap_region;
286 bool _heap_region_special;
287 size_t _num_regions;
288 ShenandoahHeapRegion** _regions;
289 uint8_t* _affiliations; // Holds array of enum ShenandoahAffiliation, including FREE status in non-generational mode
290 uint8_t* _biased_affiliations;
291
292 public:
293
294 inline HeapWord* base() const { return _heap_region.start(); }
295 inline HeapWord* end() const { return _heap_region.end(); }
296
297 inline size_t num_regions() const { return _num_regions; }
298 inline bool is_heap_region_special() { return _heap_region_special; }
299
300 inline ShenandoahHeapRegion* heap_region_containing(const void* addr) const;
301 inline size_t heap_region_index_containing(const void* addr) const;
302
303 inline ShenandoahHeapRegion* get_region(size_t region_idx) const;
304
305 void heap_region_iterate(ShenandoahHeapRegionClosure* blk) const;
306 void parallel_heap_region_iterate(ShenandoahHeapRegionClosure* blk) const;
307 void heap_region_iterator(ShenandoahHeapRegionClosure* blk) const;
308
309 inline ShenandoahMmuTracker* mmu_tracker() { return &_mmu_tracker; };
310
311 // ---------- GC state machinery
312 //
313 // GC state describes the important parts of collector state, that may be
314 // used to make barrier selection decisions in the native and generated code.
315 // Multiple bits can be set at once.
316 //
317 // Important invariant: when GC state is zero, the heap is stable, and no barriers
318 // are required.
319 //
320 public:
321 enum GCStateBitPos {
322 // Heap has forwarded objects: needs LRB barriers.
323 HAS_FORWARDED_BITPOS = 0,
324
325 // Heap is under marking: needs SATB barriers.
326 // For generational mode, it means either young or old marking, or both.
327 MARKING_BITPOS = 1,
328
329 // Heap is under evacuation: needs LRB barriers. (Set together with HAS_FORWARDED)
330 EVACUATION_BITPOS = 2,
331
332 // Heap is under updating: needs no additional barriers.
333 UPDATE_REFS_BITPOS = 3,
334
335 // Heap is under weak-reference/roots processing: needs weak-LRB barriers.
336 WEAK_ROOTS_BITPOS = 4,
337
338 // Young regions are under marking, need SATB barriers.
339 YOUNG_MARKING_BITPOS = 5,
340
341 // Old regions are under marking, need SATB barriers.
342 OLD_MARKING_BITPOS = 6
343 };
344
345 enum GCState {
346 STABLE = 0,
347 HAS_FORWARDED = 1 << HAS_FORWARDED_BITPOS,
348 MARKING = 1 << MARKING_BITPOS,
349 EVACUATION = 1 << EVACUATION_BITPOS,
350 UPDATE_REFS = 1 << UPDATE_REFS_BITPOS,
351 WEAK_ROOTS = 1 << WEAK_ROOTS_BITPOS,
352 YOUNG_MARKING = 1 << YOUNG_MARKING_BITPOS,
353 OLD_MARKING = 1 << OLD_MARKING_BITPOS
354 };
355
356 private:
357 bool _gc_state_changed;
358 ShenandoahSharedBitmap _gc_state;
359 ShenandoahSharedFlag _heap_changed;
360 ShenandoahSharedFlag _degenerated_gc_in_progress;
361 ShenandoahSharedFlag _full_gc_in_progress;
362 ShenandoahSharedFlag _full_gc_move_in_progress;
363 ShenandoahSharedFlag _concurrent_strong_root_in_progress;
364
365 Atomic<size_t> _gc_no_progress_count;
366
367 // This updates the singular, global gc state. This call must happen on a safepoint.
368 void set_gc_state_at_safepoint(uint mask, bool value);
369
370 // This also updates the global gc state, but does not need to be called on a safepoint.
371 // Critically, this method will _not_ flag that the global gc state has changed and threads
372 // will continue to use their thread local copy. This is expected to be used in conjunction
373 // with a handshake operation to propagate the new gc state.
374 void set_gc_state_concurrent(uint mask, bool value);
375
376 public:
377 // This returns the raw value of the singular, global gc state.
378 inline char gc_state() const;
379
380 // Compares the given state against either the global gc state, or the thread local state.
381 // The global gc state may change on a safepoint and is the correct value to use until
382 // the global gc state has been propagated to all threads (after which, this method will
383 // compare against the thread local state). The thread local gc state may also be changed
384 // by a handshake operation, in which case, this function continues using the updated thread
385 // local value.
386 inline bool is_gc_state(GCState state) const;
387
388 // This copies the global gc state into a thread local variable for all threads.
389 // The thread local gc state is primarily intended to support quick access at barriers.
390 // All threads are updated because in some cases the control thread or the vm thread may
391 // need to execute the load reference barrier.
392 void propagate_gc_state_to_all_threads();
393
394 // This is public to support assertions that the state hasn't been changed off of
395 // a safepoint and that any changes were propagated to threads after the safepoint.
396 bool has_gc_state_changed() const { return _gc_state_changed; }
397
398 // Returns true if allocations have occurred in new regions or if regions have been
399 // uncommitted since the previous calls. This call will reset the flag to false.
400 bool has_changed() {
401 return _heap_changed.try_unset();
402 }
403
404 virtual void start_idle_span();
405
406 void set_concurrent_young_mark_in_progress(bool in_progress);
407 void set_concurrent_old_mark_in_progress(bool in_progress);
408 void set_evacuation_in_progress(bool in_progress);
409 void set_update_refs_in_progress(bool in_progress);
410 void set_degenerated_gc_in_progress(bool in_progress);
411 void set_full_gc_in_progress(bool in_progress);
412 void set_full_gc_move_in_progress(bool in_progress);
413 void set_has_forwarded_objects(bool cond);
414 void set_concurrent_strong_root_in_progress(bool cond);
415 void set_concurrent_weak_root_in_progress(bool cond);
416
417 inline bool is_idle() const;
418 inline bool is_concurrent_mark_in_progress() const;
419 inline bool is_concurrent_young_mark_in_progress() const;
420 inline bool is_concurrent_old_mark_in_progress() const;
421 inline bool is_update_refs_in_progress() const;
422 inline bool is_evacuation_in_progress() const;
423 inline bool is_degenerated_gc_in_progress() const;
424 inline bool is_full_gc_in_progress() const;
425 inline bool is_full_gc_move_in_progress() const;
426 inline bool has_forwarded_objects() const;
427
428 inline bool is_stw_gc_in_progress() const;
429 inline bool is_concurrent_strong_root_in_progress() const;
430 inline bool is_concurrent_weak_root_in_progress() const;
431 bool is_prepare_for_old_mark_in_progress() const;
432
433 private:
434 void manage_satb_barrier(bool active);
435
436 // Records the time of the first successful cancellation request. This is used to measure
437 // the responsiveness of the heuristic when starting a cycle.
438 double _cancel_requested_time;
439
440 // Indicates the reason the current GC has been cancelled (GCCause::_no_gc means the gc is not cancelled).
441 ShenandoahSharedEnumFlag<GCCause::Cause> _cancelled_gc;
442
443 // Returns true if cancel request was successfully communicated.
444 // Returns false if some other thread already communicated cancel
445 // request. A true return value does not mean GC has been
446 // cancelled, only that the process of cancelling GC has begun.
447 bool try_cancel_gc(GCCause::Cause cause);
448
449 public:
450 // True if gc has been cancelled
451 inline bool cancelled_gc() const;
452
453 // Used by workers in the GC cycle to detect cancellation and honor STS requirements
454 inline bool check_cancelled_gc_and_yield(bool sts_active = true);
455
456 // This indicates the reason the last GC cycle was cancelled.
457 inline GCCause::Cause cancelled_cause() const;
458
459 // Clears the cancellation cause and resets the oom handler
460 inline void clear_cancelled_gc();
461
462 // Clears the cancellation cause iff the current cancellation reason equals the given
463 // expected cancellation cause. Does not reset the oom handler.
464 inline GCCause::Cause clear_cancellation(GCCause::Cause expected);
465
466 void cancel_concurrent_mark();
467
468 // Returns true if and only if this call caused a gc to be cancelled.
469 bool cancel_gc(GCCause::Cause cause);
470
471 // Returns true if the soft maximum heap has been changed using management APIs.
472 bool check_soft_max_changed();
473
474 protected:
475 // This is shared between shConcurrentGC and shDegenerateGC so that degenerated
476 // GC can resume update refs from where the concurrent GC was cancelled. It is
477 // also used in shGenerationalHeap, which uses a different closure for update refs.
478 ShenandoahRegionIterator _update_refs_iterator;
479
480 private:
481 inline void reset_cancellation_time();
482
483 // GC support
484 // Evacuation
485 virtual void evacuate_collection_set(ShenandoahGeneration* generation, bool concurrent);
486 // Concurrent root processing
487 void prepare_concurrent_roots();
488 void finish_concurrent_roots();
489 // Concurrent class unloading support
490 void do_class_unloading();
491 // Reference updating
492 void prepare_update_heap_references();
493
494 // Retires LABs used for evacuation
495 void concurrent_prepare_for_update_refs();
496
497 // Turn off weak roots flag
498 void concurrent_final_roots();
499
500 virtual void update_heap_references(ShenandoahGeneration* generation, bool concurrent);
501 // Final update region states
502 void update_heap_region_states(bool concurrent);
503 virtual void final_update_refs_update_region_states();
504
505 void rendezvous_threads(const char* name);
506 void recycle_trash();
507 public:
508 // The following two functions rebuild the free set at the end of GC, in preparation for an idle phase.
509 void rebuild_free_set(bool concurrent);
510 void rebuild_free_set_within_phase();
511 void notify_gc_progress();
512 void notify_gc_no_progress();
513 size_t get_gc_no_progress_count() const;
514
515 // The uncommit thread targets soft max heap, notify this thread when that value has changed.
516 void notify_soft_max_changed();
517
518 // An explicit GC request may have freed regions, notify the uncommit thread.
519 void notify_explicit_gc_requested();
520
521 private:
522 ShenandoahGeneration* _global_generation;
523
524 protected:
525 // The control thread presides over concurrent collection cycles
526 ShenandoahController* _control_thread;
527
528 // The uncommit thread periodically attempts to uncommit regions that have been empty for longer than ShenandoahUncommitDelay
529 ShenandoahUncommitThread* _uncommit_thread;
530
531 ShenandoahYoungGeneration* _young_generation;
532 ShenandoahOldGeneration* _old_generation;
533
534 private:
535 ShenandoahCollectorPolicy* _shenandoah_policy;
536 ShenandoahMode* _gc_mode;
537 ShenandoahFreeSet* _free_set;
538 ShenandoahAllocator* _allocator;
539 ShenandoahVerifier* _verifier;
540
541 ShenandoahPhaseTimings* _phase_timings;
542 ShenandoahMmuTracker _mmu_tracker;
543
544 public:
545 ShenandoahController* control_thread() const { return _control_thread; }
546
547 ShenandoahGeneration* global_generation() const { return _global_generation; }
548 ShenandoahYoungGeneration* young_generation() const {
549 assert(mode()->is_generational(), "Young generation requires generational mode");
550 return _young_generation;
551 }
552
553 ShenandoahOldGeneration* old_generation() const {
554 assert(ShenandoahCardBarrier, "Card mark barrier should be on");
555 return _old_generation;
556 }
557
558 ShenandoahGeneration* generation_for(ShenandoahAffiliation affiliation) const;
559
560 ShenandoahCollectorPolicy* shenandoah_policy() const { return _shenandoah_policy; }
561 ShenandoahMode* mode() const { return _gc_mode; }
562 ShenandoahFreeSet* free_set() const { return _free_set; }
563 ShenandoahAllocator* allocator() const { return _allocator; }
564
565 ShenandoahPhaseTimings* phase_timings() const { return _phase_timings; }
566
567 ShenandoahEvacuationTracker* evac_tracker() const {
568 return _evac_tracker;
569 }
570
571 void on_cycle_start(GCCause::Cause cause, ShenandoahGeneration* generation, bool is_degenerated, bool is_out_of_cycle);
572 void on_cycle_end(ShenandoahGeneration* generation);
573
574 ShenandoahVerifier* verifier();
575
576 // ---------- VM subsystem bindings
577 //
578 private:
579 ShenandoahMonitoringSupport* _monitoring_support;
580 MemoryPool* _memory_pool;
581 GCMemoryManager _stw_memory_manager;
582 GCMemoryManager _cycle_memory_manager;
583 ConcurrentGCTimer* _gc_timer;
584 // For exporting to SA
585 int _log_min_obj_alignment_in_bytes;
586 public:
587 ShenandoahMonitoringSupport* monitoring_support() const { return _monitoring_support; }
588 GCMemoryManager* cycle_memory_manager() { return &_cycle_memory_manager; }
589 GCMemoryManager* stw_memory_manager() { return &_stw_memory_manager; }
590
591 GrowableArray<GCMemoryManager*> memory_managers() override;
592 GrowableArray<MemoryPool*> memory_pools() override;
593 MemoryUsage memory_usage() override;
594 GCTracer* tracer();
595 ConcurrentGCTimer* gc_timer() const;
596
597 // ---------- Class Unloading
598 //
599 private:
600 ShenandoahSharedFlag _unload_classes;
601 ShenandoahUnload _unloader;
602
603 public:
604 void set_unload_classes(bool uc);
605 bool unload_classes() const;
606
607 // Perform STW class unloading and weak root cleaning
608 void parallel_cleaning(ShenandoahGeneration* generation, bool full_gc);
609
610 private:
611 void stw_unload_classes(bool full_gc);
612 void stw_process_weak_roots(bool full_gc);
613 void stw_weak_refs(ShenandoahGeneration* generation, bool full_gc);
614
615 inline void assert_lock_for_affiliation(ShenandoahAffiliation orig_affiliation,
616 ShenandoahAffiliation new_affiliation);
617
618 // Heap iteration support
619 void scan_roots_for_iteration(ShenandoahScanObjectStack* oop_stack, ObjectIterateScanRootClosure* oops);
620 bool prepare_aux_bitmap_for_iteration();
621 void reclaim_aux_bitmap_for_iteration();
622
623 // ---------- Generic interface hooks
624 // Minor things that super-interface expects us to implement to play nice with
625 // the rest of runtime. Some of the things here are not required to be implemented,
626 // and can be stubbed out.
627 //
628 public:
629 // Check the pointer is in active part of Java heap.
630 // Use is_in_reserved to check if object is within heap bounds.
631 bool is_in(const void* p) const override;
632
633 // Returns true if the given oop belongs to a generation that is actively being collected.
634 inline bool is_in_active_generation(oop obj) const;
635 inline bool is_in_young(const void* p) const;
636 inline bool is_in_old(const void* p) const;
637
638 // Returns true if `maybe_old` is in old and `maybe_young` is in young
639 inline bool is_old_to_young(const void* maybe_old, oop maybe_young) const;
640
641 // Returns false if `p` is not in the heap or does not have the given affiliation.
642 inline bool has_affiliation(const void* p, ShenandoahAffiliation affiliation) const;
643
644 // Does not check that `obj` is in the heap (debug builds assert that `obj` is in the heap).
645 inline bool has_affiliation(oop obj, ShenandoahAffiliation affiliation) const;
646
647 // Returns true iff the young generation is being collected and the given pointer
648 // is in the old generation. This is used to prevent the young collection from treating
649 // such an object as unreachable.
650 inline bool is_in_old_during_young_collection(oop obj) const;
651
652 inline ShenandoahAffiliation region_affiliation(const ShenandoahHeapRegion* r) const;
653 inline void set_affiliation(ShenandoahHeapRegion* r, ShenandoahAffiliation new_affiliation);
654
655 inline ShenandoahAffiliation region_affiliation(size_t index) const;
656
657 inline bool is_region_young(size_t index) const;
658 inline bool is_region_old(size_t index) const;
659 inline bool is_region_free(size_t index) const;
660
661 bool requires_barriers(stackChunkOop obj) const override;
662
663 MemRegion reserved_region() const { return _reserved; }
664 bool is_in_reserved(const void* addr) const { return _reserved.contains(addr); }
665
666 void collect_as_vm_thread(GCCause::Cause cause) override;
667 void collect(GCCause::Cause cause) override;
668 void do_full_collection(bool clear_all_soft_refs) override;
669
670 // Used for parsing heap during error printing
671 HeapWord* block_start(const void* addr) const;
672 bool block_is_obj(const HeapWord* addr) const;
673 bool print_location(outputStream* st, void* addr) const override;
674
675 // Used for native heap walkers: heap dumpers, mostly
676 void object_iterate(ObjectClosure* cl) override;
677 // Parallel heap iteration support
678 ParallelObjectIteratorImpl* parallel_object_iterator(uint workers) override;
679
680 // Keep alive an object that was loaded with AS_NO_KEEPALIVE.
681 void keep_alive(oop obj) override;
682
683 // ---------- Safepoint interface hooks
684 //
685 public:
686 void safepoint_synchronize_begin() override;
687 void safepoint_synchronize_end() override;
688
689 // ---------- Code roots handling hooks
690 //
691 public:
692 void register_nmethod(nmethod* nm) override;
693 void unregister_nmethod(nmethod* nm) override;
694 void verify_nmethod(nmethod* nm) override {}
695
696 // ---------- Pinning hooks
697 //
698 public:
699 // Shenandoah supports per-object (per-region) pinning
700 void pin_object(JavaThread* thread, oop obj) override;
701 void unpin_object(JavaThread* thread, oop obj) override;
702
703 // Flushes this thread's accumulated pin count to its cached region's
704 // shared counter and clears the thread's count.
705 void flush_region_pin_cache(JavaThread* thread);
706
707 // Flushes all Java threads' pin counts.
708 void flush_region_pin_cache();
709
710 void sync_pinned_region_status();
711 void assert_pinned_region_status() const NOT_DEBUG_RETURN;
712 void assert_pinned_region_status(ShenandoahGeneration* generation) const NOT_DEBUG_RETURN;
713
714 // ---------- CDS archive support
715
716 bool can_load_archived_objects() const override { return true; }
717 HeapWord* allocate_loaded_archive_space(size_t size) override;
718 void complete_loaded_archive_space(MemRegion archive_space) override;
719
720 // ---------- Allocation support
721 //
722 protected:
723 inline HeapWord* allocate_from_gclab(Thread* thread, size_t size);
724
725 private:
726 HeapWord* allocate_memory_work(ShenandoahAllocRequest& request, bool& in_new_region);
727 HeapWord* allocate_from_gclab_slow(Thread* thread, size_t size);
728 HeapWord* allocate_new_gclab(size_t min_size, size_t word_size, size_t* actual_size);
729
730 // We want to retry an unsuccessful attempt at allocation until at least a full gc.
731 bool should_retry_allocation(size_t original_full_gc_count) const;
732
733 public:
734 HeapWord* allocate_memory(ShenandoahAllocRequest& request);
735 HeapWord* mem_allocate(size_t size) override;
736 oop array_allocate(Klass* klass, size_t size, int length, bool do_zero, TRAPS) override;
737 MetaWord* satisfy_failed_metadata_allocation(ClassLoaderData* loader_data,
738 size_t size,
739 Metaspace::MetadataType mdtype) override;
740
741 HeapWord* allocate_new_tlab(size_t min_size, size_t requested_size, size_t* actual_size) override;
742 size_t tlab_capacity() const override;
743 size_t unsafe_max_tlab_alloc() const override;
744 size_t max_tlab_size() const override;
745 size_t tlab_used() const override;
746
747 void ensure_parsability(bool retire_labs) override;
748
749 void labs_make_parsable();
750 void tlabs_retire(bool resize);
751 void gclabs_retire(bool resize);
752
753 // ---------- Marking support
754 //
755 private:
756 ShenandoahMarkingContext* _marking_context;
757 MemRegion _bitmap_region;
758 MemRegion _aux_bitmap_region;
759 MarkBitMap _verification_bit_map;
760 MarkBitMap _aux_bit_map;
761
762 size_t _bitmap_size;
763 size_t _bitmap_regions_per_slice;
764 size_t _bitmap_bytes_per_slice;
765
766 size_t _pretouch_heap_page_size;
767 size_t _pretouch_bitmap_page_size;
768
769 bool _bitmap_region_special;
770 bool _aux_bitmap_region_special;
771
772 ShenandoahLiveData** _liveness_cache;
773
774 public:
775 // Return the marking context regardless of the completeness status.
776 inline ShenandoahMarkingContext* marking_context() const;
777
778 template<class T>
779 inline void marked_object_iterate(ShenandoahHeapRegion* region, T* cl);
780
781 template<class T>
782 inline void marked_object_iterate(ShenandoahHeapRegion* region, T* cl, HeapWord* limit);
783
784 template<class T>
785 inline void marked_object_oop_iterate(ShenandoahHeapRegion* region, T* cl, HeapWord* limit);
786
787 // SATB barriers hooks
788 inline bool requires_marking(const void* entry) const;
789
790 // Support for bitmap uncommits
791 void commit_bitmap_slice(ShenandoahHeapRegion *r);
792 void uncommit_bitmap_slice(ShenandoahHeapRegion *r);
793 bool is_bitmap_region_special() { return _bitmap_region_special; }
794 bool is_bitmap_slice_committed(ShenandoahHeapRegion* r, bool skip_self = false);
795
796 // During concurrent reset, the control thread will zero out the mark bitmaps for committed regions.
797 // This cannot happen when the uncommit thread is simultaneously trying to uncommit regions and their bitmaps.
798 // To prevent these threads from working at the same time, we provide these methods for the control thread to
799 // prevent the uncommit thread from working while a collection cycle is in progress.
800
801 // Forbid uncommits (will stop and wait if regions are being uncommitted)
802 void forbid_uncommit();
803
804 // Allow the uncommit thread to process regions
805 void allow_uncommit();
806 #ifdef ASSERT
807 bool is_uncommit_in_progress();
808 #endif
809
810 // Liveness caching support
811 ShenandoahLiveData* get_liveness_cache(uint worker_id);
812 void flush_liveness_cache(uint worker_id);
813
814 size_t pretouch_heap_page_size() { return _pretouch_heap_page_size; }
815
816 // ---------- Evacuation support
817 //
818 private:
819 ShenandoahCollectionSet* _collection_set;
820
821 oop try_evacuate_object(oop src, Thread* thread, ShenandoahHeapRegion* from_region, ShenandoahAffiliation target_gen);
822
823 protected:
824 // Used primarily to look for failed evacuation attempts.
825 ShenandoahEvacuationTracker* _evac_tracker;
826
827 public:
828 static address in_cset_fast_test_addr();
829
830 ShenandoahCollectionSet* collection_set() const { return _collection_set; }
831
832 // Checks if object is in the collection set.
833 inline bool in_collection_set(oop obj) const;
834
835 // Checks if location is in the collection set. Can be interior pointer, not the oop itself.
836 inline bool in_collection_set_loc(void* loc) const;
837
838 // Evacuates or promotes object src. Returns the evacuated object, either evacuated
839 // by this thread, or by some other thread. On allocation failure, installs the
840 // self-forwarded bit on src, flags src's region, and returns src.
841 virtual oop evacuate_object(oop src, Thread* thread);
842
843 // Parallel scan of flagged cset regions to clear self-forwarded bits on live
844 // objects. Must be called at a safepoint; intended for the degenerated and
845 // full GC entry paths.
846 void un_self_forward_cset_regions();
847
848 DEBUG_ONLY(void assert_no_self_forwards() const;)
849
850 // ---------- Helper functions
851 //
852 public:
853 template <class T>
854 inline void conc_update_with_forwarded(T* p);
855
856 template <class T>
857 inline void non_conc_update_with_forwarded(T* p);
858
859 static inline void atomic_update_oop(oop update, oop* addr, oop compare);
860 static inline void atomic_update_oop(oop update, narrowOop* addr, oop compare);
861 static inline void atomic_update_oop(oop update, narrowOop* addr, narrowOop compare);
862
863 static inline bool atomic_update_oop_check(oop update, oop* addr, oop compare);
864 static inline bool atomic_update_oop_check(oop update, narrowOop* addr, oop compare);
865 static inline bool atomic_update_oop_check(oop update, narrowOop* addr, narrowOop compare);
866
867 static inline void atomic_clear_oop( oop* addr, oop compare);
868 static inline void atomic_clear_oop(narrowOop* addr, oop compare);
869 static inline void atomic_clear_oop(narrowOop* addr, narrowOop compare);
870
871 size_t trash_humongous_region_at(ShenandoahHeapRegion *r) const;
872
873 static inline void increase_object_age(oop obj, uint additional_age);
874
875 // Return the object's age, or a sentinel value when the age can't
876 // necessarily be determined because of concurrent locking by the
877 // mutator
878 static inline uint get_object_age(oop obj);
879
880 void log_heap_status(const char *msg) const;
881
882 private:
883 void trash_cset_regions();
884
885 // ---------- Testing helpers functions
886 //
887 private:
888 ShenandoahSharedFlag _inject_alloc_failure;
889
890 void try_inject_alloc_failure();
891 bool should_inject_alloc_failure();
892
893 // Randomly pin a region when ShenandoahPinRegionRate > 0. Pin injection is only called after
894 // the cycle has populated _live_data and runs concurrently on the control thread. Releasing
895 // injected pins is done at the start of every cycle preventing stale pinned region states.
896 void try_inject_pin();
897 void release_injected_pins();
898
899 // Maximum number of regions that can be injected with pins.
900 static const uint MAX_INJECTED_PINS = 32;
901
902 // Tracker for injected pins added by try_inject_pin().
903 size_t _injected_pin_indices[MAX_INJECTED_PINS];
904 uint _injected_pin_count;
905 };
906
907 #endif // SHARE_GC_SHENANDOAH_SHENANDOAHHEAP_HPP