1 /*
2 * Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
3 * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
4 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 *
6 * This code is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 only, as
8 * published by the Free Software Foundation.
9 *
10 * This code is distributed in the hope that it will be useful, but WITHOUT
11 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
13 * version 2 for more details (a copy is included in the LICENSE file that
14 * accompanied this code).
15 *
16 * You should have received a copy of the GNU General Public License version
17 * 2 along with this work; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19 *
20 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21 * or visit www.oracle.com if you need additional information or have any
22 * questions.
23 *
24 */
25
26 #include "gc/shenandoah/shenandoahAgeCensus.hpp"
27 #include "gc/shenandoah/shenandoahClosures.inline.hpp"
28 #include "gc/shenandoah/shenandoahCollectorPolicy.hpp"
29 #include "gc/shenandoah/shenandoahFreeSet.hpp"
30 #include "gc/shenandoah/shenandoahGeneration.hpp"
31 #include "gc/shenandoah/shenandoahGenerationalControlThread.hpp"
32 #include "gc/shenandoah/shenandoahGenerationalEvacuationTask.hpp"
33 #include "gc/shenandoah/shenandoahGenerationalHeap.hpp"
34 #include "gc/shenandoah/shenandoahHeap.inline.hpp"
35 #include "gc/shenandoah/shenandoahHeapRegion.hpp"
36 #include "gc/shenandoah/shenandoahHeapRegionClosures.hpp"
37 #include "gc/shenandoah/shenandoahInitLogger.hpp"
38 #include "gc/shenandoah/shenandoahMemoryPool.hpp"
39 #include "gc/shenandoah/shenandoahMonitoringSupport.hpp"
40 #include "gc/shenandoah/shenandoahOldGeneration.hpp"
41 #include "gc/shenandoah/shenandoahPhaseTimings.hpp"
42 #include "gc/shenandoah/shenandoahRegulatorThread.hpp"
43 #include "gc/shenandoah/shenandoahScanRemembered.inline.hpp"
44 #include "gc/shenandoah/shenandoahUtils.hpp"
45 #include "gc/shenandoah/shenandoahWorkerPolicy.hpp"
46 #include "gc/shenandoah/shenandoahYoungGeneration.hpp"
47 #include "logging/log.hpp"
48 #include "utilities/events.hpp"
49
50
51 class ShenandoahGenerationalInitLogger : public ShenandoahInitLogger {
52 public:
53 static void print() {
54 ShenandoahGenerationalInitLogger logger;
55 logger.print_all();
56 }
57 protected:
58 void print_gc_specific() override {
59 ShenandoahInitLogger::print_gc_specific();
60
61 ShenandoahGenerationalHeap* heap = ShenandoahGenerationalHeap::heap();
62 log_info(gc, init)("Young Heuristics: %s", heap->young_generation()->heuristics()->name());
63 log_info(gc, init)("Old Heuristics: %s", heap->old_generation()->heuristics()->name());
64 }
65 };
66
67 size_t ShenandoahGenerationalHeap::calculate_min_plab() {
68 return align_up(PLAB::min_size(), CardTable::card_size_in_words());
69 }
70
71 size_t ShenandoahGenerationalHeap::calculate_max_plab() {
72 size_t MaxTLABSizeWords = ShenandoahHeapRegion::max_tlab_size_words();
73 return align_down(MaxTLABSizeWords, CardTable::card_size_in_words());
74 }
75
76 // Returns size in bytes
77 size_t ShenandoahGenerationalHeap::unsafe_max_tlab_alloc() const {
78 return MIN2(ShenandoahHeapRegion::max_tlab_size_bytes(), young_generation()->available());
79 }
80
81 ShenandoahGenerationalHeap::ShenandoahGenerationalHeap(ShenandoahCollectorPolicy* policy) :
82 ShenandoahHeap(policy),
83 _age_census(nullptr),
84 _min_plab_size(calculate_min_plab()),
85 _max_plab_size(calculate_max_plab()),
86 _regulator_thread(nullptr),
87 _young_gen_memory_pool(nullptr),
88 _old_gen_memory_pool(nullptr) {
89 assert(is_aligned(_min_plab_size, CardTable::card_size_in_words()), "min_plab_size must be aligned");
90 assert(is_aligned(_max_plab_size, CardTable::card_size_in_words()), "max_plab_size must be aligned");
91 }
92
93 void ShenandoahGenerationalHeap::post_initialize() {
94 ShenandoahHeap::post_initialize();
95 _age_census = new ShenandoahAgeCensus();
96 }
97
98 void ShenandoahGenerationalHeap::print_init_logger() const {
99 ShenandoahGenerationalInitLogger logger;
100 logger.print_all();
101 }
102
103 void ShenandoahGenerationalHeap::initialize_heuristics() {
104 // Initialize global generation and heuristics even in generational mode.
105 ShenandoahHeap::initialize_heuristics();
106
107 // Max capacity is the maximum _allowed_ capacity. That is, the maximum allowed capacity
108 // for old would be total heap - minimum capacity of young. This means the sum of the maximum
109 // allowed for old and young could exceed the total heap size. It remains the case that the
110 // _actual_ capacity of young + old = total.
111 size_t region_count = num_regions();
112 size_t max_young_regions = MAX2((region_count * ShenandoahMaxYoungPercentage) / 100, (size_t) 1U);
113 size_t initial_capacity_young = max_young_regions * ShenandoahHeapRegion::region_size_bytes();
114 size_t max_capacity_young = initial_capacity_young;
115 size_t initial_capacity_old = max_capacity() - max_capacity_young;
116 size_t max_capacity_old = max_capacity() - initial_capacity_young;
117
118 _young_generation = new ShenandoahYoungGeneration(max_workers());
119 _old_generation = new ShenandoahOldGeneration(max_workers());
120 _young_generation->initialize_heuristics(mode());
121 _old_generation->initialize_heuristics(mode());
122 }
123
124 void ShenandoahGenerationalHeap::post_initialize_heuristics() {
125 ShenandoahHeap::post_initialize_heuristics();
126 _young_generation->post_initialize(this);
127 _old_generation->post_initialize(this);
128 }
129
130 void ShenandoahGenerationalHeap::initialize_serviceability() {
131 assert(mode()->is_generational(), "Only for the generational mode");
132 _young_gen_memory_pool = new ShenandoahYoungGenMemoryPool(this);
133 _old_gen_memory_pool = new ShenandoahOldGenMemoryPool(this);
134 cycle_memory_manager()->add_pool(_young_gen_memory_pool);
135 cycle_memory_manager()->add_pool(_old_gen_memory_pool);
136 stw_memory_manager()->add_pool(_young_gen_memory_pool);
137 stw_memory_manager()->add_pool(_old_gen_memory_pool);
138 }
139
140 GrowableArray<MemoryPool*> ShenandoahGenerationalHeap::memory_pools() {
141 assert(mode()->is_generational(), "Only for the generational mode");
142 GrowableArray<MemoryPool*> memory_pools(2);
143 memory_pools.append(_young_gen_memory_pool);
144 memory_pools.append(_old_gen_memory_pool);
145 return memory_pools;
146 }
147
148 void ShenandoahGenerationalHeap::initialize_controller() {
149 auto control_thread = new ShenandoahGenerationalControlThread();
150 _control_thread = control_thread;
151 _regulator_thread = new ShenandoahRegulatorThread(control_thread);
152 }
153
154 void ShenandoahGenerationalHeap::gc_threads_do(ThreadClosure* tcl) const {
155 if (!shenandoah_policy()->is_at_shutdown()) {
156 ShenandoahHeap::gc_threads_do(tcl);
157 tcl->do_thread(regulator_thread());
158 }
159 }
160
161 void ShenandoahGenerationalHeap::stop() {
162 ShenandoahHeap::stop();
163 regulator_thread()->stop();
164 }
165
166 bool ShenandoahGenerationalHeap::requires_barriers(stackChunkOop obj) const {
167 if (is_idle()) {
168 return false;
169 }
170
171 if (is_concurrent_young_mark_in_progress() && is_in_young(obj) && !marking_context()->allocated_after_mark_start(obj)) {
172 // We are marking young, this object is in young, and it is below the TAMS
173 return true;
174 }
175
176 if (is_in_old(obj)) {
177 // Card marking barriers are required for objects in the old generation
178 return true;
179 }
180
181 if (has_forwarded_objects()) {
182 // Object may have pointers that need to be updated
183 return true;
184 }
185
186 return false;
187 }
188
189 void ShenandoahGenerationalHeap::evacuate_collection_set(ShenandoahGeneration* generation, bool concurrent) {
190 ShenandoahRegionIterator regions;
191 ShenandoahGenerationalEvacuationTask task(this, generation, ®ions, concurrent, false /* only promote regions */);
192 workers()->run_task(&task);
193 }
194
195 void ShenandoahGenerationalHeap::promote_regions_in_place(ShenandoahGeneration* generation, bool concurrent) {
196 ShenandoahRegionIterator regions;
197 ShenandoahGenerationalEvacuationTask task(this, generation, ®ions, concurrent, true /* only promote regions */);
198 workers()->run_task(&task);
199 }
200
201 oop ShenandoahGenerationalHeap::evacuate_object(oop p, Thread* thread) {
202 assert(thread == Thread::current(), "Expected thread parameter to be current thread.");
203 if (ShenandoahThreadLocalData::is_oom_during_evac(thread)) {
204 // This thread went through the OOM during evac protocol and it is safe to return
205 // the forward pointer. It must not attempt to evacuate anymore.
206 return ShenandoahBarrierSet::resolve_forwarded(p);
207 }
208
209 assert(ShenandoahThreadLocalData::is_evac_allowed(thread), "must be enclosed in oom-evac scope");
210
211 ShenandoahHeapRegion* r = heap_region_containing(p);
212 assert(!r->is_humongous(), "never evacuate humongous objects");
213
214 ShenandoahAffiliation target_gen = r->affiliation();
215 // gc_generation() can change asynchronously and should not be used here.
216 assert(active_generation() != nullptr, "Error");
217 if (active_generation()->is_young() && target_gen == YOUNG_GENERATION) {
218 markWord mark = p->mark();
219 if (mark.is_marked()) {
220 // Already forwarded.
221 return ShenandoahBarrierSet::resolve_forwarded(p);
222 }
223
224 if (mark.has_displaced_mark_helper()) {
225 // We don't want to deal with MT here just to ensure we read the right mark word.
226 // Skip the potential promotion attempt for this one.
227 } else if (age_census()->is_tenurable(r->age() + mark.age())) {
228 oop result = try_evacuate_object(p, thread, r, OLD_GENERATION);
229 if (result != nullptr) {
230 return result;
231 }
232 // If we failed to promote this aged object, we'll fall through to code below and evacuate to young-gen.
233 }
234 }
235 return try_evacuate_object(p, thread, r, target_gen);
236 }
237
238 // try_evacuate_object registers the object and dirties the associated remembered set information when evacuating
239 // to OLD_GENERATION.
240 oop ShenandoahGenerationalHeap::try_evacuate_object(oop p, Thread* thread, ShenandoahHeapRegion* from_region,
241 ShenandoahAffiliation target_gen) {
242 bool alloc_from_lab = true;
243 bool has_plab = false;
244 HeapWord* copy = nullptr;
245 size_t size = ShenandoahForwarding::size(p);
246 bool is_promotion = (target_gen == OLD_GENERATION) && from_region->is_young();
247
248 #ifdef ASSERT
249 if (ShenandoahOOMDuringEvacALot &&
250 (os::random() & 1) == 0) { // Simulate OOM every ~2nd slow-path call
251 copy = nullptr;
252 } else {
253 #endif
254 if (UseTLAB) {
255 switch (target_gen) {
256 case YOUNG_GENERATION: {
257 copy = allocate_from_gclab(thread, size);
258 if ((copy == nullptr) && (size < ShenandoahThreadLocalData::gclab_size(thread))) {
259 // GCLAB allocation failed because we are bumping up against the limit on young evacuation reserve. Try resetting
260 // the desired GCLAB size and retry GCLAB allocation to avoid cascading of shared memory allocations.
261 ShenandoahThreadLocalData::set_gclab_size(thread, PLAB::min_size());
262 copy = allocate_from_gclab(thread, size);
263 // If we still get nullptr, we'll try a shared allocation below.
264 }
265 break;
266 }
267 case OLD_GENERATION: {
268 PLAB* plab = ShenandoahThreadLocalData::plab(thread);
269 if (plab != nullptr) {
270 has_plab = true;
271 copy = allocate_from_plab(thread, size, is_promotion);
272 if ((copy == nullptr) && (size < ShenandoahThreadLocalData::plab_size(thread)) &&
273 ShenandoahThreadLocalData::plab_retries_enabled(thread)) {
274 // PLAB allocation failed because we are bumping up against the limit on old evacuation reserve or because
275 // the requested object does not fit within the current plab but the plab still has an "abundance" of memory,
276 // where abundance is defined as >= ShenGenHeap::plab_min_size(). In the former case, we try shrinking the
277 // desired PLAB size to the minimum and retry PLAB allocation to avoid cascading of shared memory allocations.
278 // Shrinking the desired PLAB size may allow us to eke out a small PLAB while staying beneath evacuation reserve.
279 if (plab->words_remaining() < plab_min_size()) {
280 ShenandoahThreadLocalData::set_plab_size(thread, plab_min_size());
281 copy = allocate_from_plab(thread, size, is_promotion);
282 // If we still get nullptr, we'll try a shared allocation below.
283 if (copy == nullptr) {
284 // If retry fails, don't continue to retry until we have success (probably in next GC pass)
285 ShenandoahThreadLocalData::disable_plab_retries(thread);
286 }
287 }
288 // else, copy still equals nullptr. this causes shared allocation below, preserving this plab for future needs.
289 }
290 }
291 break;
292 }
293 default: {
294 ShouldNotReachHere();
295 break;
296 }
297 }
298 }
299
300 if (copy == nullptr) {
301 // If we failed to allocate in LAB, we'll try a shared allocation.
302 if (!is_promotion || !has_plab || (size > PLAB::min_size())) {
303 ShenandoahAllocRequest req = ShenandoahAllocRequest::for_shared_gc(size, target_gen, is_promotion);
304 copy = allocate_memory(req);
305 alloc_from_lab = false;
306 }
307 // else, we leave copy equal to nullptr, signaling a promotion failure below if appropriate.
308 // We choose not to promote objects smaller than PLAB::min_size() by way of shared allocations, as this is too
309 // costly. Instead, we'll simply "evacuate" to young-gen memory (using a GCLAB) and will promote in a future
310 // evacuation pass. This condition is denoted by: is_promotion && has_plab && (size <= PLAB::min_size())
311 }
312 #ifdef ASSERT
313 }
314 #endif
315
316 if (copy == nullptr) {
317 if (target_gen == OLD_GENERATION) {
318 if (from_region->is_young()) {
319 // Signal that promotion failed. Will evacuate this old object somewhere in young gen.
320 old_generation()->handle_failed_promotion(thread, size);
321 return nullptr;
322 } else {
323 // Remember that evacuation to old gen failed. We'll want to trigger a full gc to recover from this
324 // after the evacuation threads have finished.
325 old_generation()->handle_failed_evacuation();
326 }
327 }
328
329 control_thread()->handle_alloc_failure_evac(size);
330
331 oom_evac_handler()->handle_out_of_memory_during_evacuation();
332
333 return ShenandoahBarrierSet::resolve_forwarded(p);
334 }
335
336 if (ShenandoahEvacTracking) {
337 evac_tracker()->begin_evacuation(thread, size * HeapWordSize, from_region->affiliation(), target_gen);
338 }
339
340 // Copy the object:
341 Copy::aligned_disjoint_words(cast_from_oop<HeapWord*>(p), copy, size);
342 oop copy_val = cast_to_oop(copy);
343
344 // Update the age of the evacuated object
345 if (target_gen == YOUNG_GENERATION && is_aging_cycle()) {
346 ShenandoahHeap::increase_object_age(copy_val, from_region->age() + 1);
347 }
348
349 // Try to install the new forwarding pointer.
350 oop result = ShenandoahForwarding::try_update_forwardee(p, copy_val);
351 if (result == copy_val) {
352 // Successfully evacuated. Our copy is now the public one!
353
354 // This is necessary for virtual thread support. This uses the mark word without
355 // considering that it may now be a forwarding pointer (and could therefore crash).
356 // Secondarily, we do not want to spend cycles relativizing stack chunks for oops
357 // that lost the evacuation race (and will therefore not become visible). It is
358 // safe to do this on the public copy (this is also done during concurrent mark).
359 ContinuationGCSupport::relativize_stack_chunk(copy_val);
360
361 if (ShenandoahEvacTracking) {
362 // Record that the evacuation succeeded
363 evac_tracker()->end_evacuation(thread, size * HeapWordSize, from_region->affiliation(), target_gen);
364 }
365
366 if (target_gen == OLD_GENERATION) {
367 old_generation()->handle_evacuation(copy, size, from_region->is_young());
368 } else {
369 // When copying to the old generation above, we don't care
370 // about recording object age in the census stats.
371 assert(target_gen == YOUNG_GENERATION, "Error");
372 }
373 shenandoah_assert_correct(nullptr, copy_val);
374 return copy_val;
375 } else {
376 // Failed to evacuate. We need to deal with the object that is left behind. Since this
377 // new allocation is certainly after TAMS, it will be considered live in the next cycle.
378 // But if it happens to contain references to evacuated regions, those references would
379 // not get updated for this stale copy during this cycle, and we will crash while scanning
380 // it the next cycle.
381 if (alloc_from_lab) {
382 // For LAB allocations, it is enough to rollback the allocation ptr. Either the next
383 // object will overwrite this stale copy, or the filler object on LAB retirement will
384 // do this.
385 switch (target_gen) {
386 case YOUNG_GENERATION: {
387 ShenandoahThreadLocalData::gclab(thread)->undo_allocation(copy, size);
388 break;
389 }
390 case OLD_GENERATION: {
391 ShenandoahThreadLocalData::plab(thread)->undo_allocation(copy, size);
392 if (is_promotion) {
393 ShenandoahThreadLocalData::subtract_from_plab_promoted(thread, size * HeapWordSize);
394 }
395 break;
396 }
397 default: {
398 ShouldNotReachHere();
399 break;
400 }
401 }
402 } else {
403 // For non-LAB allocations, we have no way to retract the allocation, and
404 // have to explicitly overwrite the copy with the filler object. With that overwrite,
405 // we have to keep the fwdptr initialized and pointing to our (stale) copy.
406 assert(size >= ShenandoahHeap::min_fill_size(), "previously allocated object known to be larger than min_size");
407 fill_with_object(copy, size);
408 shenandoah_assert_correct(nullptr, copy_val);
409 // For non-LAB allocations, the object has already been registered
410 }
411 shenandoah_assert_correct(nullptr, result);
412 return result;
413 }
414 }
415
416 inline HeapWord* ShenandoahGenerationalHeap::allocate_from_plab(Thread* thread, size_t size, bool is_promotion) {
417 assert(UseTLAB, "TLABs should be enabled");
418
419 PLAB* plab = ShenandoahThreadLocalData::plab(thread);
420 HeapWord* obj;
421
422 if (plab == nullptr) {
423 assert(!thread->is_Java_thread() && !thread->is_Worker_thread(), "Performance: thread should have PLAB: %s", thread->name());
424 // No PLABs in this thread, fallback to shared allocation
425 return nullptr;
426 } else if (is_promotion && !ShenandoahThreadLocalData::allow_plab_promotions(thread)) {
427 return nullptr;
428 }
429 // if plab->word_size() <= 0, thread's plab not yet initialized for this pass, so allow_plab_promotions() is not trustworthy
430 obj = plab->allocate(size);
431 if ((obj == nullptr) && (plab->words_remaining() < plab_min_size())) {
432 // allocate_from_plab_slow will establish allow_plab_promotions(thread) for future invocations
433 obj = allocate_from_plab_slow(thread, size, is_promotion);
434 }
435 // if plab->words_remaining() >= ShenGenHeap::heap()->plab_min_size(), just return nullptr so we can use a shared allocation
436 if (obj == nullptr) {
437 return nullptr;
438 }
439
440 if (is_promotion) {
441 ShenandoahThreadLocalData::add_to_plab_promoted(thread, size * HeapWordSize);
442 }
443 return obj;
444 }
445
446 // Establish a new PLAB and allocate size HeapWords within it.
447 HeapWord* ShenandoahGenerationalHeap::allocate_from_plab_slow(Thread* thread, size_t size, bool is_promotion) {
448 assert(mode()->is_generational(), "PLABs only relevant to generational GC");
449
450 const size_t plab_min_size = this->plab_min_size();
451 // PLABs are aligned to card boundaries to avoid synchronization with concurrent
452 // allocations in other PLABs.
453 const size_t min_size = (size > plab_min_size)? align_up(size, CardTable::card_size_in_words()): plab_min_size;
454
455 // Figure out size of new PLAB, using value determined at last refill.
456 size_t cur_size = ShenandoahThreadLocalData::plab_size(thread);
457 if (cur_size == 0) {
458 cur_size = plab_min_size;
459 }
460
461 // Expand aggressively, doubling at each refill in this epoch, ceiling at plab_max_size()
462 const size_t future_size = MIN2(cur_size * 2, plab_max_size());
463 // Doubling, starting at a card-multiple, should give us a card-multiple. (Ceiling and floor
464 // are card multiples.)
465 assert(is_aligned(future_size, CardTable::card_size_in_words()), "Card multiple by construction, future_size: %zu"
466 ", card_size: %u, cur_size: %zu, max: %zu",
467 future_size, CardTable::card_size_in_words(), cur_size, plab_max_size());
468
469 // Record new heuristic value even if we take any shortcut. This captures
470 // the case when moderately-sized objects always take a shortcut. At some point,
471 // heuristics should catch up with them. Note that the requested cur_size may
472 // not be honored, but we remember that this is the preferred size.
473 log_debug(gc, plab)("Set next PLAB refill size: %zu bytes", future_size * HeapWordSize);
474 ShenandoahThreadLocalData::set_plab_size(thread, future_size);
475
476 if (cur_size < size) {
477 // The PLAB to be allocated is still not large enough to hold the object. Fall back to shared allocation.
478 // This avoids retiring perfectly good PLABs in order to represent a single large object allocation.
479 log_debug(gc, plab)("Current PLAB size (%zu) is too small for %zu", cur_size * HeapWordSize, size * HeapWordSize);
480 return nullptr;
481 }
482
483 // Retire current PLAB, and allocate a new one.
484 PLAB* plab = ShenandoahThreadLocalData::plab(thread);
485 if (plab->words_remaining() < plab_min_size) {
486 // Retire current PLAB. This takes care of any PLAB book-keeping.
487 // retire_plab() registers the remnant filler object with the remembered set scanner without a lock.
488 // Since PLABs are card-aligned, concurrent registrations in other PLABs don't interfere.
489 retire_plab(plab, thread);
490
491 size_t actual_size = 0;
492 HeapWord* plab_buf = allocate_new_plab(min_size, cur_size, &actual_size);
493 if (plab_buf == nullptr) {
494 if (min_size == plab_min_size) {
495 // Disable PLAB promotions for this thread because we cannot even allocate a minimal PLAB. This allows us
496 // to fail faster on subsequent promotion attempts.
497 ShenandoahThreadLocalData::disable_plab_promotions(thread);
498 }
499 return nullptr;
500 } else {
501 ShenandoahThreadLocalData::enable_plab_retries(thread);
502 }
503 // Since the allocated PLAB may have been down-sized for alignment, plab->allocate(size) below may still fail.
504 if (ZeroTLAB) {
505 // ... and clear it.
506 Copy::zero_to_words(plab_buf, actual_size);
507 } else {
508 // ...and zap just allocated object.
509 #ifdef ASSERT
510 // Skip mangling the space corresponding to the object header to
511 // ensure that the returned space is not considered parsable by
512 // any concurrent GC thread.
513 size_t hdr_size = oopDesc::header_size();
514 Copy::fill_to_words(plab_buf + hdr_size, actual_size - hdr_size, badHeapWordVal);
515 #endif // ASSERT
516 }
517 assert(is_aligned(actual_size, CardTable::card_size_in_words()), "Align by design");
518 plab->set_buf(plab_buf, actual_size);
519 if (is_promotion && !ShenandoahThreadLocalData::allow_plab_promotions(thread)) {
520 return nullptr;
521 }
522 return plab->allocate(size);
523 } else {
524 // If there's still at least min_size() words available within the current plab, don't retire it. Let's nibble
525 // away on this plab as long as we can. Meanwhile, return nullptr to force this particular allocation request
526 // to be satisfied with a shared allocation. By packing more promotions into the previously allocated PLAB, we
527 // reduce the likelihood of evacuation failures, and we reduce the need for downsizing our PLABs.
528 return nullptr;
529 }
530 }
531
532 HeapWord* ShenandoahGenerationalHeap::allocate_new_plab(size_t min_size, size_t word_size, size_t* actual_size) {
533 // Align requested sizes to card-sized multiples. Align down so that we don't violate max size of TLAB.
534 assert(is_aligned(min_size, CardTable::card_size_in_words()), "Align by design");
535 assert(word_size >= min_size, "Requested PLAB is too small");
536
537 ShenandoahAllocRequest req = ShenandoahAllocRequest::for_plab(min_size, word_size);
538 // Note that allocate_memory() sets a thread-local flag to prohibit further promotions by this thread
539 // if we are at risk of infringing on the old-gen evacuation budget.
540 HeapWord* res = allocate_memory(req);
541 if (res != nullptr) {
542 *actual_size = req.actual_size();
543 } else {
544 *actual_size = 0;
545 }
546 assert(is_aligned(res, CardTable::card_size_in_words()), "Align by design");
547 return res;
548 }
549
550 void ShenandoahGenerationalHeap::retire_plab(PLAB* plab, Thread* thread) {
551 // We don't enforce limits on plab evacuations. We let it consume all available old-gen memory in order to reduce
552 // probability of an evacuation failure. We do enforce limits on promotion, to make sure that excessive promotion
553 // does not result in an old-gen evacuation failure. Note that a failed promotion is relatively harmless. Any
554 // object that fails to promote in the current cycle will be eligible for promotion in a subsequent cycle.
555
556 // When the plab was instantiated, its entirety was treated as if the entire buffer was going to be dedicated to
557 // promotions. Now that we are retiring the buffer, we adjust for the reality that the plab is not entirely promotions.
558 // 1. Some of the plab may have been dedicated to evacuations.
559 // 2. Some of the plab may have been abandoned due to waste (at the end of the plab).
560 size_t not_promoted =
561 ShenandoahThreadLocalData::get_plab_actual_size(thread) - ShenandoahThreadLocalData::get_plab_promoted(thread);
562 ShenandoahThreadLocalData::reset_plab_promoted(thread);
563 ShenandoahThreadLocalData::set_plab_actual_size(thread, 0);
564 if (not_promoted > 0) {
565 log_debug(gc, plab)("Retire PLAB, unexpend unpromoted: %zu", not_promoted * HeapWordSize);
566 old_generation()->unexpend_promoted(not_promoted);
567 }
568 const size_t original_waste = plab->waste();
569 HeapWord* const top = plab->top();
570
571 // plab->retire() overwrites unused memory between plab->top() and plab->hard_end() with a dummy object to make memory parsable.
572 // It adds the size of this unused memory, in words, to plab->waste().
573 plab->retire();
574 if (top != nullptr && plab->waste() > original_waste && is_in_old(top)) {
575 // If retiring the plab created a filler object, then we need to register it with our card scanner so it can
576 // safely walk the region backing the plab.
577 log_debug(gc, plab)("retire_plab() is registering remnant of size %zu at " PTR_FORMAT,
578 (plab->waste() - original_waste) * HeapWordSize, p2i(top));
579 // No lock is necessary because the PLAB memory is aligned on card boundaries.
580 old_generation()->card_scan()->register_object_without_lock(top);
581 }
582 }
583
584 void ShenandoahGenerationalHeap::retire_plab(PLAB* plab) {
585 Thread* thread = Thread::current();
586 retire_plab(plab, thread);
587 }
588
589 // Make sure old-generation is large enough, but no larger than is necessary, to hold mixed evacuations
590 // and promotions, if we anticipate either. Any deficit is provided by the young generation, subject to
591 // xfer_limit, and any surplus is transferred to the young generation.
592 //
593 // xfer_limit is the maximum we're able to transfer from young to old based on either:
594 // 1. an assumption that we will be able to replenish memory "borrowed" from young at the end of collection, or
595 // 2. there is sufficient excess in the allocation runway during GC idle cycles
596 void ShenandoahGenerationalHeap::compute_old_generation_balance(size_t old_xfer_limit, size_t old_cset_regions) {
597
598 // We can limit the old reserve to the size of anticipated promotions:
599 // max_old_reserve is an upper bound on memory evacuated from old and promoted to old,
600 // clamped by the old generation space available.
601 //
602 // Here's the algebra.
603 // Let SOEP = ShenandoahOldEvacRatioPercent,
604 // OE = old evac,
605 // YE = young evac, and
606 // TE = total evac = OE + YE
607 // By definition:
608 // SOEP/100 = OE/TE
609 // = OE/(OE+YE)
610 // => SOEP/(100-SOEP) = OE/((OE+YE)-OE) // componendo-dividendo: If a/b = c/d, then a/(b-a) = c/(d-c)
611 // = OE/YE
612 // => OE = YE*SOEP/(100-SOEP)
613
614 // We have to be careful in the event that SOEP is set to 100 by the user.
615 assert(ShenandoahOldEvacRatioPercent <= 100, "Error");
616 const size_t old_available = old_generation()->available();
617 // The free set will reserve this amount of memory to hold young evacuations
618 const size_t young_reserve = (young_generation()->max_capacity() * ShenandoahEvacReserve) / 100;
619
620 // In the case that ShenandoahOldEvacRatioPercent equals 100, max_old_reserve is limited only by xfer_limit.
621
622 const double bound_on_old_reserve = old_available + old_xfer_limit + young_reserve;
623 const double max_old_reserve = ((ShenandoahOldEvacRatioPercent == 100)? bound_on_old_reserve:
624 MIN2(double(young_reserve * ShenandoahOldEvacRatioPercent)
625 / double(100 - ShenandoahOldEvacRatioPercent), bound_on_old_reserve));
626
627 const size_t region_size_bytes = ShenandoahHeapRegion::region_size_bytes();
628
629 // Decide how much old space we should reserve for a mixed collection
630 double reserve_for_mixed = 0;
631 if (old_generation()->has_unprocessed_collection_candidates()) {
632 // We want this much memory to be unfragmented in order to reliably evacuate old. This is conservative because we
633 // may not evacuate the entirety of unprocessed candidates in a single mixed evacuation.
634 const double max_evac_need =
635 (double(old_generation()->unprocessed_collection_candidates_live_memory()) * ShenandoahOldEvacWaste);
636 assert(old_available >= old_generation()->free_unaffiliated_regions() * region_size_bytes,
637 "Unaffiliated available must be less than total available");
638 const double old_fragmented_available =
639 double(old_available - old_generation()->free_unaffiliated_regions() * region_size_bytes);
640 reserve_for_mixed = max_evac_need + old_fragmented_available;
641 if (reserve_for_mixed > max_old_reserve) {
642 reserve_for_mixed = max_old_reserve;
643 }
644 }
645
646 // Decide how much space we should reserve for promotions from young
647 size_t reserve_for_promo = 0;
648 const size_t promo_load = old_generation()->get_promotion_potential();
649 const bool doing_promotions = promo_load > 0;
650 if (doing_promotions) {
651 // We're promoting and have a bound on the maximum amount that can be promoted
652 assert(max_old_reserve >= reserve_for_mixed, "Sanity");
653 const size_t available_for_promotions = max_old_reserve - reserve_for_mixed;
654 reserve_for_promo = MIN2((size_t)(promo_load * ShenandoahPromoEvacWaste), available_for_promotions);
655 }
656
657 // This is the total old we want to ideally reserve
658 const size_t old_reserve = reserve_for_mixed + reserve_for_promo;
659 assert(old_reserve <= max_old_reserve, "cannot reserve more than max for old evacuations");
660
661 // We now check if the old generation is running a surplus or a deficit.
662 const size_t max_old_available = old_generation()->available() + old_cset_regions * region_size_bytes;
663 if (max_old_available >= old_reserve) {
664 // We are running a surplus, so the old region surplus can go to young
665 const size_t old_surplus = (max_old_available - old_reserve) / region_size_bytes;
666 const size_t unaffiliated_old_regions = old_generation()->free_unaffiliated_regions() + old_cset_regions;
667 const size_t old_region_surplus = MIN2(old_surplus, unaffiliated_old_regions);
668 old_generation()->set_region_balance(checked_cast<ssize_t>(old_region_surplus));
669 } else {
670 // We are running a deficit which we'd like to fill from young.
671 // Ignore that this will directly impact young_generation()->max_capacity(),
672 // indirectly impacting young_reserve and old_reserve. These computations are conservative.
673 // Note that deficit is rounded up by one region.
674 const size_t old_need = (old_reserve - max_old_available + region_size_bytes - 1) / region_size_bytes;
675 const size_t max_old_region_xfer = old_xfer_limit / region_size_bytes;
676
677 // Round down the regions we can transfer from young to old. If we're running short
678 // on young-gen memory, we restrict the xfer. Old-gen collection activities will be
679 // curtailed if the budget is restricted.
680 const size_t old_region_deficit = MIN2(old_need, max_old_region_xfer);
681 old_generation()->set_region_balance(0 - checked_cast<ssize_t>(old_region_deficit));
682 }
683 }
684
685 void ShenandoahGenerationalHeap::reset_generation_reserves() {
686 ShenandoahHeapLocker locker(lock());
687 young_generation()->set_evacuation_reserve(0);
688 old_generation()->set_evacuation_reserve(0);
689 old_generation()->set_promoted_reserve(0);
690 }
691
692 void ShenandoahGenerationalHeap::TransferResult::print_on(const char* when, outputStream* ss) const {
693 auto heap = ShenandoahGenerationalHeap::heap();
694 ShenandoahYoungGeneration* const young_gen = heap->young_generation();
695 ShenandoahOldGeneration* const old_gen = heap->old_generation();
696 const size_t young_available = young_gen->available();
697 const size_t old_available = old_gen->available();
698 ss->print_cr("After %s, %s %zu regions to %s to prepare for next gc, old available: "
699 PROPERFMT ", young_available: " PROPERFMT,
700 when,
701 success? "successfully transferred": "failed to transfer", region_count, region_destination,
702 PROPERFMTARGS(old_available), PROPERFMTARGS(young_available));
703 }
704
705 void ShenandoahGenerationalHeap::coalesce_and_fill_old_regions(bool concurrent) {
706 class ShenandoahGlobalCoalesceAndFill : public WorkerTask {
707 private:
708 ShenandoahPhaseTimings::Phase _phase;
709 ShenandoahRegionIterator _regions;
710 public:
711 explicit ShenandoahGlobalCoalesceAndFill(ShenandoahPhaseTimings::Phase phase) :
712 WorkerTask("Shenandoah Global Coalesce"),
713 _phase(phase) {}
714
715 void work(uint worker_id) override {
716 ShenandoahWorkerTimingsTracker timer(_phase,
717 ShenandoahPhaseTimings::ScanClusters,
718 worker_id, true);
719 ShenandoahHeapRegion* region;
720 while ((region = _regions.next()) != nullptr) {
721 // old region is not in the collection set and was not immediately trashed
722 if (region->is_old() && region->is_active() && !region->is_humongous()) {
723 // Reset the coalesce and fill boundary because this is a global collect
724 // and cannot be preempted by young collects. We want to be sure the entire
725 // region is coalesced here and does not resume from a previously interrupted
726 // or completed coalescing.
727 region->begin_preemptible_coalesce_and_fill();
728 region->oop_coalesce_and_fill(false);
729 }
730 }
731 }
732 };
733
734 ShenandoahPhaseTimings::Phase phase = concurrent ?
735 ShenandoahPhaseTimings::conc_coalesce_and_fill :
736 ShenandoahPhaseTimings::degen_gc_coalesce_and_fill;
737
738 // This is not cancellable
739 ShenandoahGlobalCoalesceAndFill coalesce(phase);
740 workers()->run_task(&coalesce);
741 old_generation()->set_parsable(true);
742 }
743
744 template<bool CONCURRENT>
745 class ShenandoahGenerationalUpdateHeapRefsTask : public WorkerTask {
746 private:
747 // For update refs, _generation will be young or global. Mixed collections use the young generation.
748 ShenandoahGeneration* _generation;
749 ShenandoahGenerationalHeap* _heap;
750 ShenandoahRegionIterator* _regions;
751 ShenandoahRegionChunkIterator* _work_chunks;
752
753 public:
754 ShenandoahGenerationalUpdateHeapRefsTask(ShenandoahGeneration* generation,
755 ShenandoahRegionIterator* regions,
756 ShenandoahRegionChunkIterator* work_chunks) :
757 WorkerTask("Shenandoah Update References"),
758 _generation(generation),
759 _heap(ShenandoahGenerationalHeap::heap()),
760 _regions(regions),
761 _work_chunks(work_chunks)
762 {
763 const bool old_bitmap_stable = _heap->old_generation()->is_mark_complete();
764 log_debug(gc, remset)("Update refs, scan remembered set using bitmap: %s", BOOL_TO_STR(old_bitmap_stable));
765 }
766
767 void work(uint worker_id) override {
768 if (CONCURRENT) {
769 ShenandoahConcurrentWorkerSession worker_session(worker_id);
770 ShenandoahSuspendibleThreadSetJoiner stsj;
771 do_work<ShenandoahConcUpdateRefsClosure>(worker_id);
772 } else {
773 ShenandoahParallelWorkerSession worker_session(worker_id);
774 do_work<ShenandoahNonConcUpdateRefsClosure>(worker_id);
775 }
776 }
777
778 private:
779 template<class T>
780 void do_work(uint worker_id) {
781 T cl;
782
783 if (CONCURRENT && (worker_id == 0)) {
784 // We ask the first worker to replenish the Mutator free set by moving regions previously reserved to hold the
785 // results of evacuation. These reserves are no longer necessary because evacuation has completed.
786 size_t cset_regions = _heap->collection_set()->count();
787
788 // Now that evacuation is done, we can reassign any regions that had been reserved to hold the results of evacuation
789 // to the mutator free set. At the end of GC, we will have cset_regions newly evacuated fully empty regions from
790 // which we will be able to replenish the Collector free set and the OldCollector free set in preparation for the
791 // next GC cycle.
792 _heap->free_set()->move_regions_from_collector_to_mutator(cset_regions);
793 }
794 // If !CONCURRENT, there's no value in expanding Mutator free set
795
796 ShenandoahHeapRegion* r = _regions->next();
797 // We update references for global, mixed, and young collections.
798 assert(_generation->is_mark_complete(), "Expected complete marking");
799 ShenandoahMarkingContext* const ctx = _heap->marking_context();
800 bool is_mixed = _heap->collection_set()->has_old_regions();
801 while (r != nullptr) {
802 HeapWord* update_watermark = r->get_update_watermark();
803 assert(update_watermark >= r->bottom(), "sanity");
804
805 log_debug(gc)("Update refs worker " UINT32_FORMAT ", looking at region %zu", worker_id, r->index());
806 if (r->is_active() && !r->is_cset()) {
807 if (r->is_young()) {
808 _heap->marked_object_oop_iterate(r, &cl, update_watermark);
809 } else if (r->is_old()) {
810 if (_generation->is_global()) {
811
812 _heap->marked_object_oop_iterate(r, &cl, update_watermark);
813 }
814 // Otherwise, this is an old region in a young or mixed cycle. Process it during a second phase, below.
815 } else {
816 // Because updating of references runs concurrently, it is possible that a FREE inactive region transitions
817 // to a non-free active region while this loop is executing. Whenever this happens, the changing of a region's
818 // active status may propagate at a different speed than the changing of the region's affiliation.
819
820 // When we reach this control point, it is because a race has allowed a region's is_active() status to be seen
821 // by this thread before the region's affiliation() is seen by this thread.
822
823 // It's ok for this race to occur because the newly transformed region does not have any references to be
824 // updated.
825
826 assert(r->get_update_watermark() == r->bottom(),
827 "%s Region %zu is_active but not recognized as YOUNG or OLD so must be newly transitioned from FREE",
828 r->affiliation_name(), r->index());
829 }
830 }
831
832 if (_heap->check_cancelled_gc_and_yield(CONCURRENT)) {
833 return;
834 }
835
836 r = _regions->next();
837 }
838
839 if (_generation->is_young()) {
840 // Since this is generational and not GLOBAL, we have to process the remembered set. There's no remembered
841 // set processing if not in generational mode or if GLOBAL mode.
842
843 // After this thread has exhausted its traditional update-refs work, it continues with updating refs within
844 // remembered set. The remembered set workload is better balanced between threads, so threads that are "behind"
845 // can catch up with other threads during this phase, allowing all threads to work more effectively in parallel.
846 update_references_in_remembered_set(worker_id, cl, ctx, is_mixed);
847 }
848 }
849
850 template<class T>
851 void update_references_in_remembered_set(uint worker_id, T &cl, const ShenandoahMarkingContext* ctx, bool is_mixed) {
852
853 struct ShenandoahRegionChunk assignment;
854 ShenandoahScanRemembered* scanner = _heap->old_generation()->card_scan();
855
856 while (!_heap->check_cancelled_gc_and_yield(CONCURRENT) && _work_chunks->next(&assignment)) {
857 // Keep grabbing next work chunk to process until finished, or asked to yield
858 ShenandoahHeapRegion* r = assignment._r;
859 if (r->is_active() && !r->is_cset() && r->is_old()) {
860 HeapWord* start_of_range = r->bottom() + assignment._chunk_offset;
861 HeapWord* end_of_range = r->get_update_watermark();
862 if (end_of_range > start_of_range + assignment._chunk_size) {
863 end_of_range = start_of_range + assignment._chunk_size;
864 }
865
866 if (start_of_range >= end_of_range) {
867 continue;
868 }
869
870 // Old region in a young cycle or mixed cycle.
871 if (is_mixed) {
872 if (r->is_humongous()) {
873 // Need to examine both dirty and clean cards during mixed evac.
874 r->oop_iterate_humongous_slice_all(&cl,start_of_range, assignment._chunk_size);
875 } else {
876 // Since this is mixed evacuation, old regions that are candidates for collection have not been coalesced
877 // and filled. This will use mark bits to find objects that need to be updated.
878 update_references_in_old_region(cl, ctx, scanner, r, start_of_range, end_of_range);
879 }
880 } else {
881 // This is a young evacuation
882 size_t cluster_size = CardTable::card_size_in_words() * ShenandoahCardCluster::CardsPerCluster;
883 size_t clusters = assignment._chunk_size / cluster_size;
884 assert(clusters * cluster_size == assignment._chunk_size, "Chunk assignment must align on cluster boundaries");
885 scanner->process_region_slice(r, assignment._chunk_offset, clusters, end_of_range, &cl, true, worker_id);
886 }
887 }
888 }
889 }
890
891 template<class T>
892 void update_references_in_old_region(T &cl, const ShenandoahMarkingContext* ctx, ShenandoahScanRemembered* scanner,
893 const ShenandoahHeapRegion* r, HeapWord* start_of_range,
894 HeapWord* end_of_range) const {
895 // In case last object in my range spans boundary of my chunk, I may need to scan all the way to top()
896 ShenandoahObjectToOopBoundedClosure<T> objs(&cl, start_of_range, r->top());
897
898 // Any object that begins in a previous range is part of a different scanning assignment. Any object that
899 // starts after end_of_range is also not my responsibility. (Either allocated during evacuation, so does
900 // not hold pointers to from-space, or is beyond the range of my assigned work chunk.)
901
902 // Find the first object that begins in my range, if there is one. Note that `p` will be set to `end_of_range`
903 // when no live object is found in the range.
904 HeapWord* tams = ctx->top_at_mark_start(r);
905 HeapWord* p = get_first_object_start_word(ctx, scanner, tams, start_of_range, end_of_range);
906
907 while (p < end_of_range) {
908 // p is known to point to the beginning of marked object obj
909 oop obj = cast_to_oop(p);
910 objs.do_object(obj);
911 HeapWord* prev_p = p;
912 p += obj->size();
913 if (p < tams) {
914 p = ctx->get_next_marked_addr(p, tams);
915 // If there are no more marked objects before tams, this returns tams. Note that tams is
916 // either >= end_of_range, or tams is the start of an object that is marked.
917 }
918 assert(p != prev_p, "Lack of forward progress");
919 }
920 }
921
922 HeapWord* get_first_object_start_word(const ShenandoahMarkingContext* ctx, ShenandoahScanRemembered* scanner, HeapWord* tams,
923 HeapWord* start_of_range, HeapWord* end_of_range) const {
924 HeapWord* p = start_of_range;
925
926 if (p >= tams) {
927 // We cannot use ctx->is_marked(obj) to test whether an object begins at this address. Instead,
928 // we need to use the remembered set crossing map to advance p to the first object that starts
929 // within the enclosing card.
930 size_t card_index = scanner->card_index_for_addr(start_of_range);
931 while (true) {
932 HeapWord* first_object = scanner->first_object_in_card(card_index);
933 if (first_object != nullptr) {
934 p = first_object;
935 break;
936 } else if (scanner->addr_for_card_index(card_index + 1) < end_of_range) {
937 card_index++;
938 } else {
939 // Signal that no object was found in range
940 p = end_of_range;
941 break;
942 }
943 }
944 } else if (!ctx->is_marked(cast_to_oop(p))) {
945 p = ctx->get_next_marked_addr(p, tams);
946 // If there are no more marked objects before tams, this returns tams.
947 // Note that tams is either >= end_of_range, or tams is the start of an object that is marked.
948 }
949 return p;
950 }
951 };
952
953 void ShenandoahGenerationalHeap::update_heap_references(ShenandoahGeneration* generation, bool concurrent) {
954 assert(!is_full_gc_in_progress(), "Only for concurrent and degenerated GC");
955 const uint nworkers = workers()->active_workers();
956 ShenandoahRegionChunkIterator work_list(nworkers);
957 if (concurrent) {
958 ShenandoahGenerationalUpdateHeapRefsTask<true> task(generation, &_update_refs_iterator, &work_list);
959 workers()->run_task(&task);
960 } else {
961 ShenandoahGenerationalUpdateHeapRefsTask<false> task(generation, &_update_refs_iterator, &work_list);
962 workers()->run_task(&task);
963 }
964
965 if (ShenandoahEnableCardStats) {
966 // Only do this if we are collecting card stats
967 ShenandoahScanRemembered* card_scan = old_generation()->card_scan();
968 assert(card_scan != nullptr, "Card table must exist when card stats are enabled");
969 card_scan->log_card_stats(nworkers, CARD_STAT_UPDATE_REFS);
970 }
971 }
972
973 struct ShenandoahCompositeRegionClosure {
974 template<typename C1, typename C2>
975 class Closure : public ShenandoahHeapRegionClosure {
976 private:
977 C1 &_c1;
978 C2 &_c2;
979
980 public:
981 Closure(C1 &c1, C2 &c2) : ShenandoahHeapRegionClosure(), _c1(c1), _c2(c2) {}
982
983 void heap_region_do(ShenandoahHeapRegion* r) override {
984 _c1.heap_region_do(r);
985 _c2.heap_region_do(r);
986 }
987
988 bool is_thread_safe() override {
989 return _c1.is_thread_safe() && _c2.is_thread_safe();
990 }
991 };
992
993 template<typename C1, typename C2>
994 static Closure<C1, C2> of(C1 &c1, C2 &c2) {
995 return Closure<C1, C2>(c1, c2);
996 }
997 };
998
999 class ShenandoahUpdateRegionAges : public ShenandoahHeapRegionClosure {
1000 private:
1001 ShenandoahMarkingContext* _ctx;
1002
1003 public:
1004 explicit ShenandoahUpdateRegionAges(ShenandoahMarkingContext* ctx) : _ctx(ctx) { }
1005
1006 void heap_region_do(ShenandoahHeapRegion* r) override {
1007 // Maintenance of region age must follow evacuation in order to account for
1008 // evacuation allocations within survivor regions. We consult region age during
1009 // the subsequent evacuation to determine whether certain objects need to
1010 // be promoted.
1011 if (r->is_young() && r->is_active()) {
1012 HeapWord *tams = _ctx->top_at_mark_start(r);
1013 HeapWord *top = r->top();
1014
1015 // Allocations move the watermark when top moves. However, compacting
1016 // objects will sometimes lower top beneath the watermark, after which,
1017 // attempts to read the watermark will assert out (watermark should not be
1018 // higher than top).
1019 if (top > tams) {
1020 // There have been allocations in this region since the start of the cycle.
1021 // Any objects new to this region must not assimilate elevated age.
1022 r->reset_age();
1023 } else if (ShenandoahGenerationalHeap::heap()->is_aging_cycle()) {
1024 r->increment_age();
1025 }
1026 }
1027 }
1028
1029 bool is_thread_safe() override {
1030 return true;
1031 }
1032 };
1033
1034 void ShenandoahGenerationalHeap::final_update_refs_update_region_states() {
1035 ShenandoahSynchronizePinnedRegionStates pins;
1036 ShenandoahUpdateRegionAges ages(marking_context());
1037 auto cl = ShenandoahCompositeRegionClosure::of(pins, ages);
1038 parallel_heap_region_iterate(&cl);
1039 }
1040
1041 void ShenandoahGenerationalHeap::complete_degenerated_cycle() {
1042 shenandoah_assert_heaplocked_or_safepoint();
1043 // In case degeneration interrupted concurrent evacuation or update references, we need to clean up
1044 // transient state. Otherwise, these actions have no effect.
1045 reset_generation_reserves();
1046
1047 if (!old_generation()->is_parsable()) {
1048 ShenandoahGCPhase phase(ShenandoahPhaseTimings::degen_gc_coalesce_and_fill);
1049 coalesce_and_fill_old_regions(false);
1050 }
1051 }
1052
1053 void ShenandoahGenerationalHeap::complete_concurrent_cycle() {
1054 if (!old_generation()->is_parsable()) {
1055 // Class unloading may render the card offsets unusable, so we must rebuild them before
1056 // the next remembered set scan. We _could_ let the control thread do this sometime after
1057 // the global cycle has completed and before the next young collection, but under memory
1058 // pressure the control thread may not have the time (that is, because it's running back
1059 // to back GCs). In that scenario, we would have to make the old regions parsable before
1060 // we could start a young collection. This could delay the start of the young cycle and
1061 // throw off the heuristics.
1062 entry_global_coalesce_and_fill();
1063 }
1064 reset_generation_reserves();
1065 }
1066
1067 void ShenandoahGenerationalHeap::entry_global_coalesce_and_fill() {
1068 const char* msg = "Coalescing and filling old regions";
1069 ShenandoahConcurrentPhase gc_phase(msg, ShenandoahPhaseTimings::conc_coalesce_and_fill);
1070
1071 TraceCollectorStats tcs(monitoring_support()->concurrent_collection_counters());
1072 EventMark em("%s", msg);
1073 ShenandoahWorkerScope scope(workers(),
1074 ShenandoahWorkerPolicy::calc_workers_for_conc_marking(),
1075 "concurrent coalesce and fill");
1076
1077 coalesce_and_fill_old_regions(true);
1078 }
1079
1080 void ShenandoahGenerationalHeap::update_region_ages(ShenandoahMarkingContext* ctx) {
1081 ShenandoahUpdateRegionAges cl(ctx);
1082 parallel_heap_region_iterate(&cl);
1083 }